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,354
11.01.2022 10:43:26
18,000
d3ed24f910eb5496875bea296c7ee916ce1c94eb
fix id_tap jit example
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -139,8 +139,8 @@ If your Python callbacks have side-effects you may need to wait until the\ncomputation has finished to ensure that the side-effects have been observed.\nYou can use the :func:`barrier_wait` function for that purpose::\n- accumulator = p[]\n- def host_log(arg):\n+ accumulator = []\n+ def host_log(arg, transforms):\n# We just record the arguments in a list\naccumulator.append(arg)\n" } ]
Python
Apache License 2.0
google/jax
fix id_tap jit example
260,335
11.12.2021 14:07:30
28,800
08aec823fda6d8b43eaa666cc8b51dbb219c7d20
fix a custom_vjp post_process bug, related cleanups related to doesn't completely fix it
[ { "change_type": "MODIFY", "old_path": "jax/_src/custom_derivatives.py", "new_path": "jax/_src/custom_derivatives.py", "diff": "@@ -274,10 +274,10 @@ class CustomJVPCallPrimitive(core.CallPrimitive):\ndef bind(self, fun, jvp, *args):\nargs = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\n- fun, env_trace_todo1 = core.process_env_traces(\n- fun, self, top_trace and top_trace.level, (), None)\n- jvp, env_trace_todo2 = core.process_env_traces(\n- jvp, self, top_trace and top_trace.level, (), None)\n+ fun, env_trace_todo1 = process_env_traces(\n+ fun, self, top_trace and top_trace.level, False)\n+ jvp, env_trace_todo2 = process_env_traces(\n+ jvp, self, top_trace and top_trace.level, True)\ntracers = map(top_trace.full_raise, args) # type: ignore\nouts = top_trace.process_custom_jvp_call(self, fun, jvp, tracers) # type: ignore\n_, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n@@ -287,8 +287,25 @@ class CustomJVPCallPrimitive(core.CallPrimitive):\nwith core.new_sublevel():\nreturn fun.call_wrapped(*args)\n- def post_process(self, trace, out_tracers, params):\n- return trace.post_process_custom_jvp_call(out_tracers, params)\n+ def post_process(self, trace, out_tracers, jvp_was_run: bool):\n+ return trace.post_process_custom_jvp_call(out_tracers, jvp_was_run)\n+\n+@lu.transformation_with_aux\n+def process_env_traces(primitive, level: int, jvp_was_run: bool, *args):\n+ outs = yield args, {}\n+ todo = []\n+ while True:\n+ tracers = [x for x in outs if isinstance(x, core.Tracer)\n+ and (level is None or x._trace.level > level)]\n+ if tracers:\n+ ans = max(tracers, key=lambda x: x._trace.level)\n+ else:\n+ break\n+ trace = ans._trace.main.with_cur_sublevel()\n+ outs = map(trace.full_raise, outs)\n+ outs, cur_todo = primitive.post_process(trace, outs, jvp_was_run)\n+ todo.append(cur_todo)\n+ yield outs, tuple(todo) # Ensure the aux output is immutable\ndef _apply_todos(todos, outs):\ntodos_list = list(todos)\n@@ -567,6 +584,7 @@ def _flatten_fwd(in_tree, *args):\n@lu.transformation\ndef _flatten_bwd(in_tree, in_avals, out_trees, *args):\nout_tree, res_tree = out_trees()\n+ assert len(args) == res_tree.num_leaves + out_tree.num_leaves\nres, cts_out = split_list(args, [res_tree.num_leaves])\npy_res = tree_unflatten(res_tree, res)\npy_cts_out = tree_unflatten(out_tree, cts_out)\n@@ -605,14 +623,20 @@ class CustomVJPCallPrimitive(core.CallPrimitive):\ndef bind(self, fun, fwd, bwd, *args, out_trees):\nargs = map(core.full_lower, args)\ntop_trace = core.find_top_trace(args)\n- fun, env_trace_todo1 = core.process_env_traces(\n- fun, self, top_trace and top_trace.level, (), None)\n- fwd, env_trace_todo2 = core.process_env_traces(\n- fwd, self, top_trace and top_trace.level, (), None)\n+ fun, env_trace_todo1 = process_env_traces(\n+ fun, self, top_trace and top_trace.level, False)\n+ fwd, env_trace_todo2 = process_env_traces_fwd(\n+ fwd, top_trace and top_trace.level, out_trees)\ntracers = map(top_trace.full_raise, args) # type: ignore\n- outs = top_trace.process_custom_vjp_call(self, fun, fwd, bwd, tracers,\n+ bwd_ = lu.wrap_init(lambda *args: bwd.call_wrapped(*args))\n+ outs = top_trace.process_custom_vjp_call(self, fun, fwd, bwd_, tracers,\nout_trees=out_trees)\n- _, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n+ fst, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n+ if fst:\n+ return _apply_todos(env_trace_todo, map(core.full_lower, outs))\n+ else:\n+ env_trace_todo, bwd_transform = env_trace_todo\n+ bwd = _apply_bwd_transform(bwd_transform, bwd)\nreturn _apply_todos(env_trace_todo, map(core.full_lower, outs))\ndef impl(self, fun, fwd, bwd, *args, out_trees):\n@@ -624,6 +648,32 @@ class CustomVJPCallPrimitive(core.CallPrimitive):\nreturn trace.post_process_custom_vjp_call(out_tracers, params)\ncustom_vjp_call_p = CustomVJPCallPrimitive('custom_vjp_call')\n+@lu.transformation_with_aux\n+def process_env_traces_fwd(level: int, out_trees, *args):\n+ outs = yield args, {}\n+ todo = []\n+ bwd_transforms = []\n+ while True:\n+ tracers = [x for x in outs if isinstance(x, core.Tracer)\n+ and (level is None or x._trace.level > level)]\n+ if tracers:\n+ ans = max(tracers, key=lambda x: x._trace.level)\n+ else:\n+ break\n+ trace = ans._trace.main.with_cur_sublevel()\n+ outs = map(trace.full_raise, outs)\n+ outs, cur_todo, bwd_xform = trace.post_process_custom_vjp_call_fwd(outs, out_trees)\n+ todo.append(cur_todo)\n+ bwd_transforms.append(bwd_xform)\n+ yield outs, (tuple(todo), tuple(bwd_transforms))\n+\n+\n+def _apply_bwd_transform(todos, bwd):\n+ todos_list = list(todos)\n+ while todos_list:\n+ bwd = todos_list.pop()(bwd)\n+ return bwd\n+\ndef _custom_vjp_call_jaxpr_impl(*args, fun_jaxpr, **_):\nreturn core.jaxpr_as_fun(fun_jaxpr)(*args)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1662,25 +1662,32 @@ def as_named_shape(shape) -> NamedShape:\n# ------------------- Call -------------------\n-def apply_todos(todos, outs):\n- todos_list = list(todos)\n- while todos_list:\n- outs = map(full_lower, todos_list.pop()(outs))\n- return outs\n+class CallPrimitive(Primitive):\n+ multiple_results = True\n+ call_primitive = True\n-class _IgnoreElemList(list):\n- \"\"\"Compares equal to all other _ignore_elem_lists.\"\"\"\n- def __hash__(self): return 0\n- def __eq__(self, other):\n- return type(other) is _IgnoreElemList\n+ def bind(self, fun, *args, **params):\n+ return call_bind(self, fun, *args, **params)\n+\n+ def get_bind_params(self, params):\n+ new_params = dict(params)\n+ subfun = lu.wrap_init(partial(eval_jaxpr, new_params.pop('call_jaxpr'), ()))\n+ return [subfun], new_params\n+\n+def call_bind(primitive: CallPrimitive, fun, *args, **params):\n+ top_trace = find_top_trace(args)\n+ fun, env_trace_todo = process_env_traces_call(\n+ fun, primitive, top_trace and top_trace.level, tuple(params.items()))\n+ tracers = map(top_trace.full_raise, args)\n+ outs = top_trace.process_call(primitive, fun, tracers, params)\n+ return map(full_lower, apply_todos(env_trace_todo(), outs))\n@lu.transformation_with_aux\n-def process_env_traces(primitive: Union['CallPrimitive', 'MapPrimitive'],\n- level: int, params_tuple: tuple, out_axes_transforms, *args):\n+def process_env_traces_call(primitive: CallPrimitive, level: int,\n+ params_tuple: tuple, *args):\nouts = yield args, {}\nparams = dict(params_tuple)\ntodo = []\n- assert not out_axes_transforms\nwhile True:\ntracers = [x for x in outs if isinstance(x, Tracer)\nand (level is None or x._trace.level > level)]\n@@ -1690,55 +1697,16 @@ def process_env_traces(primitive: Union['CallPrimitive', 'MapPrimitive'],\nbreak\ntrace = ans._trace.main.with_cur_sublevel()\nouts = map(trace.full_raise, outs)\n- outs, cur_todo = primitive.post_process(trace, outs, params)\n- if isinstance(primitive, MapPrimitive):\n- cur_todo, out_axes_transform = cur_todo\n- out_axes_transforms.append(out_axes_transform)\n+ outs, cur_todo = trace.post_process_call(primitive, outs, params)\ntodo.append(cur_todo)\nyield outs, tuple(todo) # Ensure the aux output is immutable\n-def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\n- fun, *args, **params):\n- out_axes_transforms = _IgnoreElemList()\n- if primitive.map_primitive:\n- out_axes_thunk = params['out_axes_thunk']\n- # The new thunk depends deterministically on the old thunk and the wrapped\n- # function. Any caching already has to include the wrapped function as part\n- # of the key, so we only use the previous thunk for equality checks.\n- @as_hashable_function(closure=out_axes_thunk)\n- def new_out_axes_thunk():\n- out_axes = out_axes_thunk()\n- for t in out_axes_transforms:\n- out_axes = t(out_axes)\n- return out_axes\n- params = dict(params, out_axes_thunk=new_out_axes_thunk)\n- params_tuple = tuple(params.items())\n- top_trace = find_top_trace(args)\n- fun, env_trace_todo = process_env_traces(\n- fun, primitive, top_trace and top_trace.level,\n- params_tuple, out_axes_transforms)\n- tracers = map(top_trace.full_raise, args)\n- outs = primitive.process(top_trace, fun, tracers, params)\n- return map(full_lower, apply_todos(env_trace_todo(), outs))\n-\n-\n-class CallPrimitive(Primitive):\n- multiple_results = True\n- call_primitive = True\n-\n- def bind(self, fun, *args, **params):\n- return call_bind(self, fun, *args, **params)\n-\n- def process(self, trace, fun, tracers, params):\n- return trace.process_call(self, fun, tracers, params)\n-\n- def post_process(self, trace, out_tracers, params):\n- return trace.post_process_call(self, out_tracers, params)\n+def apply_todos(todos, outs):\n+ todos_list = list(todos)\n+ while todos_list:\n+ outs = map(full_lower, todos_list.pop()(outs))\n+ return outs\n- def get_bind_params(self, params):\n- new_params = dict(params)\n- subfun = lu.wrap_init(partial(eval_jaxpr, new_params.pop('call_jaxpr'), ()))\n- return [subfun], new_params\ndef call_impl(f: lu.WrappedFun, *args, **params):\ndel params # params parameterize the call primitive, not the function\n@@ -1781,6 +1749,70 @@ def primitive_uses_outfeed(prim: Primitive, params: Dict) -> bool:\n# ------------------- Map -------------------\n+class MapPrimitive(Primitive):\n+ multiple_results = True\n+ map_primitive = True\n+\n+ def bind(self, fun, *args, **params):\n+ assert len(params['in_axes']) == len(args)\n+ return map_bind(self, fun, *args, **params)\n+\n+ def process(self, trace, fun, tracers, params):\n+ return trace.process_map(self, fun, tracers, params)\n+\n+ def post_process(self, trace, out_tracers, params):\n+ return trace.post_process_map(self, out_tracers, params)\n+\n+ def get_bind_params(self, params):\n+ new_params = dict(params)\n+ subfun = lu.wrap_init(partial(eval_jaxpr, new_params.pop('call_jaxpr'), ()))\n+ axes = new_params.pop('out_axes')\n+ new_params['out_axes_thunk'] = HashableFunction(lambda: axes, closure=axes)\n+ return [subfun], new_params\n+\n+def map_bind(primitive: 'MapPrimitive', fun, *args, out_axes_thunk, **params):\n+ # The new thunk depends deterministically on the old thunk and the wrapped\n+ # function. Any caching already has to include the wrapped function as part\n+ # of the key, so we only use the previous thunk for equality checks.\n+ @as_hashable_function(closure=out_axes_thunk)\n+ def new_out_axes_thunk():\n+ out_axes = out_axes_thunk()\n+ _, out_axes_transforms = todo_and_xforms()\n+ for t in out_axes_transforms:\n+ out_axes = t(out_axes)\n+ return out_axes\n+ params = dict(params, out_axes_thunk=new_out_axes_thunk)\n+ params_tuple = tuple(params.items())\n+ top_trace = find_top_trace(args)\n+ fun, todo_and_xforms = process_env_traces_map(\n+ fun, primitive, top_trace and top_trace.level, params_tuple)\n+ tracers = map(top_trace.full_raise, args)\n+ outs = primitive.process(top_trace, fun, tracers, params)\n+ env_trace_todo, _ = todo_and_xforms()\n+ return map(full_lower, apply_todos(env_trace_todo, outs))\n+\n+@lu.transformation_with_aux\n+def process_env_traces_map(primitive: MapPrimitive, level: int,\n+ params_tuple: tuple, *args):\n+ outs = yield args, {}\n+ params = dict(params_tuple)\n+ todo = []\n+ out_axes_transforms = []\n+ while True:\n+ tracers = [x for x in outs if isinstance(x, Tracer)\n+ and (level is None or x._trace.level > level)]\n+ if tracers:\n+ ans = max(tracers, key=lambda x: x._trace.level)\n+ else:\n+ break\n+ trace = ans._trace.main.with_cur_sublevel()\n+ outs = map(trace.full_raise, outs)\n+ outs, (cur_todo, cur_xform) = primitive.post_process(trace, outs, params)\n+ todo.append(cur_todo)\n+ out_axes_transforms.append(cur_xform)\n+ yield outs, (tuple(todo), tuple(out_axes_transforms))\n+\n+\ndef mapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\nhandler, _ = aval_mapping_handlers.get(type(aval), (None, None))\nif handler is not None:\n@@ -1818,28 +1850,6 @@ aval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\nConcreteArray: (_map_shaped_array, _unmap_shaped_array),\n}\n-\n-class MapPrimitive(Primitive):\n- multiple_results = True\n- map_primitive = True\n-\n- def bind(self, fun, *args, **params):\n- assert len(params['in_axes']) == len(args)\n- return call_bind(self, fun, *args, **params)\n-\n- def process(self, trace, fun, tracers, params):\n- return trace.process_map(self, fun, tracers, params)\n-\n- def post_process(self, trace, out_tracers, params):\n- return trace.post_process_map(self, out_tracers, params)\n-\n- def get_bind_params(self, params):\n- new_params = dict(params)\n- subfun = lu.wrap_init(partial(eval_jaxpr, new_params.pop('call_jaxpr'), ()))\n- axes = new_params.pop('out_axes')\n- new_params['out_axes_thunk'] = HashableFunction(lambda: axes, closure=axes)\n- return [subfun], new_params\n-\n@contextmanager\ndef extend_axis_env(axis_name: AxisName, size: int, tag: Any):\nframe = AxisEnvFrame(axis_name, size, tag)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -928,7 +928,7 @@ class TensorFlowTrace(core.Trace):\ndel jvp # Unused.\nreturn self.process_call(core.call_p, fun, tracers, {})\n- def post_process_custom_jvp_call(self, out_tracers, params):\n+ def post_process_custom_jvp_call(self, out_tracers, _):\nassert False # unreachable assuming jax2tf runs with clean trace state\ndef process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, out_trees):\n@@ -938,7 +938,10 @@ class TensorFlowTrace(core.Trace):\ndel fwd, bwd, out_trees # Unused.\nreturn self.process_call(core.call_p, fun, tracers, {})\n- def post_process_custom_vjp_call(self, out_tracers, params):\n+ def post_process_custom_vjp_call(self, out_tracers, _):\n+ assert False # unreachable assuming jax2tf runs with clean trace state\n+\n+ def post_process_custom_vjp_call_fwd(self, *_, **__):\nassert False # unreachable assuming jax2tf runs with clean trace state\ndef get_primitive_impl(self, p: core.Primitive) -> Tuple[Callable, bool]:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -850,15 +850,15 @@ class EvaluationPlan(NamedTuple):\n# -------- xmap primitive and its transforms --------\n# xmap has a different set of parameters than pmap, so we make it its own primitive type\n-class XMapPrimitive(core.MapPrimitive): # Not really a map, but it gives us a few good defaults\n+class XMapPrimitive(core.MapPrimitive):\ndef __init__(self):\nsuper().__init__('xmap')\nself.def_impl(xmap_impl)\nself.def_custom_bind(self.bind)\n- def bind(self, fun, *args, **params):\n- assert len(params['in_axes']) == len(args), (params['in_axes'], args)\n- return core.call_bind(self, fun, *args, **params) # type: ignore\n+ def bind(self, fun, *args, in_axes, **params):\n+ assert len(in_axes) == len(args), (in_axes, args)\n+ return core.map_bind(self, fun, *args, in_axes=in_axes, **params)\ndef process(self, trace, fun, tracers, params):\nreturn trace.process_xmap(self, fun, tracers, params)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -359,7 +359,7 @@ class JVPTrace(Trace):\ntangents_out = map(recast_to_float0, primals_out, tangents_out)\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\n- def post_process_custom_jvp_call(self, out_tracers, params):\n+ def post_process_custom_jvp_call(self, out_tracers, _):\nraise CustomJVPException()\ndef process_custom_vjp_call(self, _, __, fwd, bwd, tracers, *, out_trees):\n@@ -375,7 +375,7 @@ class JVPTrace(Trace):\ntangents_out = map(recast_to_float0, primals_out, tangents_out)\nreturn map(partial(JVPTracer, self), primals_out, tangents_out)\n- def post_process_custom_vjp_call(self, out_tracers, params):\n+ def post_process_custom_vjp_call(self, out_tracers, _):\nraise CustomVJPException()\ndef join(self, xt, yt):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -274,11 +274,16 @@ class BatchTrace(Trace):\nout_dims = out_dims[:len(out_dims) // 2]\nreturn [BatchTracer(self, v, d) for v, d in zip(out_vals, out_dims)]\n- def post_process_custom_jvp_call(self, out_tracers, params):\n+ def post_process_custom_jvp_call(self, out_tracers, jvp_was_run):\nvals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\nmain = self.main\ndef todo(vals):\ntrace = main.with_cur_sublevel()\n+ if jvp_was_run:\n+ primal_dims, tangent_dims = dims[:len(vals)], dims[len(vals):]\n+ assert primal_dims == tangent_dims\n+ return map(partial(BatchTracer, trace), vals, primal_dims)\n+ else:\nreturn map(partial(BatchTracer, trace), vals, dims)\nreturn vals, todo\n@@ -296,7 +301,29 @@ class BatchTrace(Trace):\nout_dims = out_dims[-len(out_vals) % len(out_dims):]\nreturn [BatchTracer(self, v, d) for v, d in zip(out_vals, out_dims)]\n- post_process_custom_vjp_call = post_process_custom_jvp_call\n+ def post_process_custom_vjp_call(self, out_tracers, _):\n+ vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ main = self.main\n+ def todo(vals):\n+ trace = main.with_cur_sublevel()\n+ return map(partial(BatchTracer, trace), vals, dims)\n+ return vals, todo\n+\n+ def post_process_custom_vjp_call_fwd(self, out_tracers, out_trees):\n+ vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ axis_size, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\n+ main, trace_type = self.main, self.main.trace_type\n+ axis_name = self.axis_name\n+ _, res_tree = out_trees()\n+ num_res = res_tree.num_leaves\n+ res_dims, primal_dims = split_list(dims, [num_res])\n+ def todo(vals):\n+ trace = main.with_cur_sublevel()\n+ return map(partial(BatchTracer, trace), vals, primal_dims)\n+ def bwd_transform(bwd):\n+ return batch_custom_vjp_bwd(bwd, axis_name, axis_size, dims, (None, ),\n+ trace_type)\n+ return vals, todo, bwd_transform\ndef _main_trace_for_axis_names(main_trace: core.MainTrace,\naxis_name: Iterable[core.AxisName],\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -174,6 +174,7 @@ class JaxprTrace(Trace):\nreturn out_tracer\n# We use process_call to handle both call and map primitives.\n+ # TODO(mattjj): split out process_call and process_map\ndef process_call(self, primitive, f: lu.WrappedFun, tracers, params):\nif primitive in call_partial_eval_rules:\nreturn call_partial_eval_rules[primitive](self, primitive, f, tracers, params)\n@@ -253,8 +254,8 @@ class JaxprTrace(Trace):\nprocess_map = process_call\n# We use post_process_call to handle both call and map primitives.\n+ # TODO(mattjj): split out post_process_call and post_process_map\ndef post_process_call(self, primitive, out_tracers, params):\n-\njaxpr, consts, env = tracers_to_jaxpr([], out_tracers)\nout_pvs, out_pv_consts = unzip2(t.pval for t in out_tracers)\nout = out_pv_consts + consts\n@@ -262,19 +263,23 @@ class JaxprTrace(Trace):\ndel consts, out_pv_consts\nmain = self.main\n+ def todo(x):\nif primitive.map_primitive:\n- out_axes = params['out_axes_thunk']()\n+ out_axes_ = params['out_axes_thunk']()\n+ assert len(out_axes_) == len(out_pvs) + nconsts # transformed below\n+ out_axes = out_axes_[:len(out_pvs)]\nsz = params['axis_size']\n- out_pvs = [None if pv is None else core.unmapped_aval(sz, params['axis_name'], ax, pv)\n- for pv, ax in zip(out_pvs, out_axes)]\n+ out_pvs_ = [core.unmapped_aval(sz, params['axis_name'], ax, pv)\n+ if pv is not None else None for pv, ax in zip(out_pvs, out_axes)]\n+ else:\n+ out_pvs_ = out_pvs\n- def todo(x):\nn = len(jaxpr.outvars)\nout_pv_consts, consts = x[:n], x[n:]\ntrace = JaxprTrace(main, core.cur_sublevel())\nconst_tracers = map(trace.new_instantiated_const, consts)\nout_tracers = [JaxprTracer(trace, PartialVal((out_pv, out_pv_const)), None)\n- for out_pv, out_pv_const in zip(out_pvs, out_pv_consts)]\n+ for out_pv, out_pv_const in zip(out_pvs_, out_pv_consts)]\nin_tracers = (*const_tracers, *map(trace.full_raise, env))\nnew_params = dict(params, call_jaxpr=convert_constvars_jaxpr(jaxpr))\n@@ -349,7 +354,7 @@ class JaxprTrace(Trace):\nfor t in out_tracers: t.recipe = eqn\nreturn out_tracers\n- def post_process_custom_jvp_call(self, out_tracers, params):\n+ def post_process_custom_jvp_call(self, out_tracers, _):\n# This path should only be reachable if we expose a partial eval API\n# unrelated to autodiff, since we raise an error when differentiation with\n# respect to values over which a custom_jvp function closes is detected.\n@@ -390,7 +395,7 @@ class JaxprTrace(Trace):\nfor t in out_tracers: t.recipe = eqn\nreturn out_tracers\n- def post_process_custom_vjp_call(self, out_tracers, params):\n+ def post_process_custom_vjp_call(self, out_tracers, _):\n# This path should only be reachable if we expose a partial eval API\n# unrelated to autodiff, since we raise an error when differentiation with\n# respect to values over which a custom_vjp function closes is detected.\n@@ -1435,7 +1440,7 @@ class DynamicJaxprTrace(core.Trace):\nself.frame.eqns.append(eqn)\nreturn out_tracers\n- def post_process_custom_jvp_call(self, out_tracers, params):\n+ def post_process_custom_jvp_call(self, out_tracers, _):\nassert False # unreachable\ndef process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, out_trees):\n@@ -1459,7 +1464,7 @@ class DynamicJaxprTrace(core.Trace):\nself.frame.eqns.append(eqn)\nreturn out_tracers\n- def post_process_custom_vjp_call(self, out_tracers, params):\n+ def post_process_custom_vjp_call(self, out_tracers, _):\nassert False # unreachable\ndef _memoize(thunk):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4955,6 +4955,28 @@ class CustomJVPTest(jtu.JaxTestCase):\napi.vmap(sample)(jax.random.split(jax.random.PRNGKey(1), 3)) # don't crash\n+ def test_closure_with_vmap2(self):\n+ # https://github.com/google/jax/issues/8783\n+ def h(z):\n+ def f(x):\n+ @jax.custom_jvp\n+ def g(y):\n+ return x * y\n+\n+ # NOTE: rule closes over vmap tracer\n+ @g.defjvp\n+ def g_jvp(primals, tangents):\n+ (y,), (ydot,) = primals, tangents\n+ return x * y, x * ydot\n+\n+ return g(z) # NOTE: no vmapped arg\n+\n+ return jax.vmap(f)(jnp.arange(3., dtype='float32'))\n+\n+ primals, tangents = jax.jvp(h, (jnp.float32(1.),), (jnp.float32(2.),))\n+ self.assertAllClose(primals , jnp.arange(3., dtype='float32'))\n+ self.assertAllClose(tangents, 2 * jnp.arange(3., dtype='float32'))\n+\n@unittest.skipIf(numpy_version == (1, 21, 0),\n\"https://github.com/numpy/numpy/issues/19305\")\ndef test_float0(self):\n@@ -6199,6 +6221,27 @@ class CustomVJPTest(jtu.JaxTestCase):\njtu.check_grads(batched_scan_over_mul, (x_batch, coeff), order=2,\nmodes=['rev'])\n+ def test_closure_with_vmap2(self):\n+ # https://github.com/google/jax/issues/8783\n+ def h(z):\n+ def f(x):\n+ @jax.custom_vjp\n+ def g(y):\n+ return x * y\n+\n+ def g_fwd(y):\n+ return x * y, (x, x * y, y)\n+ def g_rev(res, w_bar):\n+ x, *_ = res\n+ return (x * w_bar,)\n+ g.defvjp(g_fwd, g_rev)\n+\n+ return g(z)\n+\n+ return jax.vmap(f)(jnp.arange(3., dtype='float32')).sum()\n+\n+ jtu.check_grads(h, (jnp.float32(3.14),), order=1, modes=['rev'])\n+\ndef transpose_unary(f, x_example):\ndef transposed(y):\n" } ]
Python
Apache License 2.0
google/jax
fix a custom_vjp post_process bug, related cleanups related to #8783, doesn't completely fix it
260,515
07.12.2021 01:26:23
0
2e5ab11652be377e0381eb6a2448d07e8c8652f0
Resolves issue 8744
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.ipynb", "diff": "\"id\": \"HowvqayEuy-H\"\n},\n\"source\": [\n- \"A limitation to this approach is that the argument `f` can't close over any values involved in differentiation. That is, you might notice that we kept the parameter `a` explicit in the argument list of `fixed_point`. While other JAX mechanisms can handle closed-over transformation-traced values in the arguments to higher-order functions (as is done for the control flow primitives like `lax.cond`, `lax.scan`, and `lax.while_loop` itself), `jax.custom_vjp` used as above cannot. A `fixed_point` routine that used a bit more of JAX's internals could have a more convenient and robust API.\"\n+ \"A limitation to this approach is that the argument `f` can't close over any values involved in differentiation. That is, you might notice that we kept the parameter `a` explicit in the argument list of `fixed_point`. For this use case, consider using the low-level primitive `lax.custom_root`, which allows for deriviatives in closed-over variables with custom root-finding functions.\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.md", "new_path": "docs/notebooks/Custom_derivative_rules_for_Python_code.md", "diff": "@@ -560,7 +560,7 @@ print(grad(grad(jnp.sqrt))(2.))\n+++ {\"id\": \"HowvqayEuy-H\"}\n-A limitation to this approach is that the argument `f` can't close over any values involved in differentiation. That is, you might notice that we kept the parameter `a` explicit in the argument list of `fixed_point`. While other JAX mechanisms can handle closed-over transformation-traced values in the arguments to higher-order functions (as is done for the control flow primitives like `lax.cond`, `lax.scan`, and `lax.while_loop` itself), `jax.custom_vjp` used as above cannot. A `fixed_point` routine that used a bit more of JAX's internals could have a more convenient and robust API.\n+A limitation to this approach is that the argument `f` can't close over any values involved in differentiation. That is, you might notice that we kept the parameter `a` explicit in the argument list of `fixed_point`. For this use case, consider using the low-level primitive `lax.custom_root`, which allows for deriviatives in closed-over variables with custom root-finding functions.\n+++ {\"id\": \"Dr0aNkBslfQf\"}\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -2357,18 +2357,6 @@ def _promote_weak_typed_inputs(in_vals, in_avals, out_avals):\nin_vals[i] = lax.convert_element_type(in_vals[i], new_dtype)\nreturn in_vals, True\n-def _stop_gradient_fun(f):\n- \"\"\"Create a version of f() that stops all gradients.\"\"\"\n- def wrapper(*args, **kwargs):\n- args_flat, in_args_tree = tree_flatten((args, kwargs))\n- args_avals = tuple(_map(_abstractify, args_flat))\n- g = lambda a, b: f(*a, **b)\n- jaxpr, consts, out_tree = _initial_style_jaxpr(g, in_args_tree, args_avals)\n- all_args = _map(lax.stop_gradient, (*consts, *args_flat))\n- out = core.jaxpr_as_fun(jaxpr)(*all_args)\n- return tree_unflatten(out_tree, out)\n- return wrapper\n-\n_RootTuple = collections.namedtuple('_RootTuple', 'f, solve, l_and_s')\n@@ -2426,7 +2414,7 @@ def custom_root(f, initial_guess, solve, tangent_solve, has_aux=False):\n_check_tree(\"f\", \"initial_guess\", out_tree, in_tree, False)\nsolve_jaxpr, solve_consts, solution_tree = _initial_style_jaxpr(\n- partial(solve, _stop_gradient_fun(f)), in_args_tree, guess_avals)\n+ partial(solve, f), in_args_tree, guess_avals)\n_check_tree(\"solve\", \"initial_guess\", solution_tree, in_tree, has_aux)\ndef linearize_and_solve(x, b):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -95,6 +95,52 @@ ignore_jit_of_pmap_warning = partial(\njtu.ignore_warning, message=\".*jit-of-pmap.*\")\n+# Simple optimization routine for testing custom_root\n+def binary_search(func, x0, low=0.0, high=100.0):\n+ del x0 # unused\n+\n+ def cond(state):\n+ low, high = state\n+ midpoint = 0.5 * (low + high)\n+ return (low < midpoint) & (midpoint < high)\n+\n+ def body(state):\n+ low, high = state\n+ midpoint = 0.5 * (low + high)\n+ update_upper = func(midpoint) > 0\n+ low = jnp.where(update_upper, low, midpoint)\n+ high = jnp.where(update_upper, midpoint, high)\n+ return (low, high)\n+\n+ solution, _ = lax.while_loop(cond, body, (low, high))\n+ return solution\n+\n+# Optimization routine for testing custom_root.\n+def newton_raphson(func, x0):\n+ tol = 1e-16\n+ max_it = 20\n+\n+ fx0, dfx0 = func(x0), jax.jacobian(func)(x0)\n+ initial_state = (0, x0, fx0, dfx0) # (iteration, x, f(x), grad(f)(x))\n+\n+ def cond(state):\n+ it, _, fx, _ = state\n+ return (jnp.max(jnp.abs(fx)) > tol) & (it < max_it)\n+\n+ def body(state):\n+ it, x, fx, dfx = state\n+ step = jnp.linalg.solve(\n+ dfx.reshape((-1, fx.size)), fx.ravel()\n+ ).reshape(fx.shape)\n+ x_next = x - step\n+ fx, dfx = func(x_next), jax.jacobian(func)(x_next)\n+ return (it + 1, x_next, fx, dfx)\n+\n+ _, x, _, _ = lax.while_loop(cond, body, initial_state)\n+\n+ return x\n+\n+\nclass LaxControlFlowTest(jtu.JaxTestCase):\ndef setUp(self):\n@@ -2007,33 +2053,19 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njax.grad(lambda x: jit_run_scan(x))(0.) # doesn't crash\n- def test_custom_root_scalar(self):\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"binary_search\", \"solve_method\": binary_search},\n+ {\"testcase_name\": \"newton_raphson\", \"solve_method\": newton_raphson},\n+ )\n+ def test_custom_root_scalar(self, solve_method):\ndef scalar_solve(f, y):\nreturn y / f(1.0)\n- def binary_search(func, x0, low=0.0, high=100.0):\n- del x0 # unused\n-\n- def cond(state):\n- low, high = state\n- midpoint = 0.5 * (low + high)\n- return (low < midpoint) & (midpoint < high)\n-\n- def body(state):\n- low, high = state\n- midpoint = 0.5 * (low + high)\n- update_upper = func(midpoint) > 0\n- low = jnp.where(update_upper, low, midpoint)\n- high = jnp.where(update_upper, midpoint, high)\n- return (low, high)\n-\n- solution, _ = lax.while_loop(cond, body, (low, high))\n- return solution\n-\ndef sqrt_cubed(x, tangent_solve=scalar_solve):\nf = lambda y: y ** 2 - x ** 3\n- return lax.custom_root(f, 0.0, binary_search, tangent_solve)\n+ # Note: Nonzero derivative at x0 required for newton_raphson\n+ return lax.custom_root(f, 1.0, solve_method, tangent_solve)\nvalue, grad = jax.value_and_grad(sqrt_cubed)(5.0)\nself.assertAllClose(value, 5 ** 1.5, check_dtypes=False, rtol=1e-6)\n@@ -2044,7 +2076,11 @@ class LaxControlFlowTest(jtu.JaxTestCase):\ninputs = jnp.array([4.0, 5.0])\nresults = jax.vmap(sqrt_cubed)(inputs)\n- self.assertAllClose(results, inputs ** 1.5, check_dtypes=False)\n+ self.assertAllClose(\n+ results, inputs ** 1.5, check_dtypes=False,\n+ atol={jnp.float32: 1e-3, jnp.float64: 1e-6},\n+ rtol={jnp.float32: 1e-3, jnp.float64: 1e-6},\n+ )\nresults = jax.jit(sqrt_cubed)(5.0)\nself.assertAllClose(\n@@ -2073,6 +2109,30 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = jnp.linalg.solve(a, b)\nself.assertAllClose(expected, actual)\n+ def test_custom_root_vector_nonlinear(self):\n+\n+ def nonlinear_func(x, y):\n+ # func(x, y) == 0 if and only if x == y.\n+ return (x - y) * (x**2 + y**2 + 1)\n+\n+ def tangent_solve(g, y):\n+ return jnp.linalg.solve(\n+ jax.jacobian(g)(y).reshape(-1, y.size),\n+ y.ravel()\n+ ).reshape(y.shape)\n+\n+ def nonlinear_solve(y):\n+ f = lambda x: nonlinear_func(x, y)\n+ x0 = -jnp.ones_like(y)\n+ return lax.custom_root(f, x0, newton_raphson, tangent_solve)\n+\n+ y = self.rng().randn(3, 1)\n+ jtu.check_grads(nonlinear_solve, (y,), order=2,\n+ rtol={jnp.float32: 1e-2, jnp.float64: 1e-3})\n+\n+ actual = jax.jit(nonlinear_solve)(y)\n+ self.assertAllClose(y, actual, rtol=1e-5, atol=1e-5)\n+\ndef test_custom_root_with_custom_linear_solve(self):\ndef linear_solve(a, b):\n" } ]
Python
Apache License 2.0
google/jax
Resolves issue 8744
260,411
13.01.2022 12:28:25
-7,200
5bfe1852a4626680f3612beee7d1a8b7a66fc79c
[jax2tf] Add jax2tf_associative_scan_reductions flag This flag allows users to match the JAX performance for associative reductions in CPU. See README.md for details.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -33,6 +33,10 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nIf set, JAX dumps the MHLO/HLO IR it generates for each computation to a\nfile under the given path.\n* Added `jax.ensure_compile_time_eval` to the public api ({jax-issue}`#7987`).\n+ * jax2tf now supports a flag jax2tf_associative_scan_reductions to change\n+ the lowering for associative reductions, e.g., jnp.cumsum, to behave\n+ like JAX on CPU and GPU (to use an associative scan). See the jax2tf README\n+ for more details ({jax-issue}`#9189`).\n## jaxlib 0.1.76 (Unreleased)\n* New features\n" }, { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -49,6 +49,7 @@ from jax._src.config import (\ndefault_matmul_precision as default_matmul_precision,\ndefault_prng_impl as default_prng_impl,\nnumpy_rank_promotion as numpy_rank_promotion,\n+ jax2tf_associative_scan_reductions as jax2tf_associative_scan_reductions\n)\nfrom .core import eval_context as ensure_compile_time_eval\nfrom jax._src.api import (\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -473,6 +473,22 @@ flags.DEFINE_bool(\n)\n)\n+# TODO(b/214340779): remove flag when XLA:CPU is improved.\n+jax2tf_associative_scan_reductions = config.define_bool_state(\n+ name='jax2tf_associative_scan_reductions',\n+ default=False,\n+ help=(\n+ 'JAX has two separate lowering rules for the cumulative reduction '\n+ 'primitives (cumsum, cumprod, cummax, cummin). On CPUs and GPUs it uses '\n+ 'a lax.associative_scan, while for TPUs it uses the HLO ReduceWindow. '\n+ 'The latter has a slow implementation on CPUs and GPUs. '\n+ 'By default, jax2tf uses the TPU lowering. Set this flag to True to '\n+ 'use the associative scan lowering usage, and only if it makes a difference '\n+ 'for your application. '\n+ 'See the jax2tf README.md for more details.'\n+ )\n+)\n+\nenable_checks = config.define_bool_state(\nname='jax_enable_checks',\ndefault=False,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -759,6 +759,27 @@ jax2tf.convert(jax_fun)(3.14)\njax2tf.convert(jax_fun)(tf.Variable(3.14, dtype=jax2tf.dtype_of_val(3.14))\n```\n+### Slow implementation of associative reductions for CPU\n+\n+Operations like ``jax.numpy.cumsum`` are compiled by JAX differently based\n+on the platform. For TPU, the compilation uses the [HLO ReduceWindow](https://www.tensorflow.org/xla/operation_semantics#reducewindow)\n+operation, which has an efficient implementation for the cases when the\n+reduction function is associative. For CPU and GPU, JAX uses an alternative\n+implementation using [associative scans](https://github.com/google/jax/blob/f08bb50bfa9f6cf2de1f3f78f76e1aee4a78735d/jax/_src/lax/control_flow.py#L2801).\n+jax2tf uses the TPU lowering (because it does not support backend-specific lowering)\n+and hence it can be slow in some cases on CPU and GPU.\n+\n+We have filed a bug with the XLA:CPU compiler to improve ReduceWindow.\n+Meanwhile, if you run into this problem you can use the\n+``--jax2tf_associative_scan_reductions`` flag to get the special\n+associative scan lowering.\n+You can alternatively use the ``with jax.jax2tf_associative_scan_reductions(True)``\n+around the code that invokes the function returned by ``jax2tf.convert``.\n+Use this only if it improves the performance for your application.\n+\n+Note that this lowering may not work as well as the default one in presence\n+of shape polymorphism.\n+\n### Unchecked assumption that the dimension variables take strictly positive values\nThe shape polymorphic conversion is sound with the assumption that the dimension\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1950,30 +1950,32 @@ tf_impl_with_avals[lax.reduce_p] = _reduce\n# cummin, cumsum and cumprod. This is efficient on TPU, but the complexity is\n# O(n^2) on other backends. This may be implemented using associative_scan\n# instead to favor different backends.\n-tf_impl_with_avals[lax.cummin_p] = _convert_jax_impl(\n- partial(lax_control_flow._cumred_tpu_translation_rule,\n- lax._reduce_window_min),\n+def _cumred(lax_reduce_fn: Callable,\n+ lax_reduce_window_fn: Callable,\n+ extra_name_stack: str):\n+ if config.jax2tf_associative_scan_reductions:\n+ return _convert_jax_impl(partial(lax_control_flow.associative_scan,\n+ lax_reduce_fn),\nmultiple_results=False,\n- extra_name_stack=\"cummin\")\n-tf_impl_with_avals[lax.cummax_p] = _convert_jax_impl(\n- partial(lax_control_flow._cumred_tpu_translation_rule,\n- lax._reduce_window_max),\n+ extra_name_stack=extra_name_stack)\n+ else:\n+ return _convert_jax_impl(partial(lax_control_flow._cumred_tpu_translation_rule,\n+ lax_reduce_window_fn),\nmultiple_results=False,\n+ extra_name_stack=extra_name_stack)\n+\n+\n+tf_impl_with_avals[lax.cummax_p] = _cumred(lax_reduce_window_fn=lax._reduce_window_max,\n+ lax_reduce_fn=lax.max,\n+ extra_name_stack=\"cummax\")\n+tf_impl_with_avals[lax.cummin_p] = _cumred(lax_reduce_window_fn=lax._reduce_window_min,\n+ lax_reduce_fn=lax.min,\nextra_name_stack=\"cummin\")\n-# TODO(bchetioui): cumsum and cumprod can be converted using pure TF ops for\n-# certain dtypes: bfloat16, float16, float32, float64, and int32. Other dtypes\n-# will fail when running in compiled mode, but are otherwise compatible with\n-# the operation. A non-XLA path can thus be defined for all dtypes, though the\n-# tests will crash.\n-tf_impl_with_avals[lax.cumsum_p] = _convert_jax_impl(\n- partial(lax_control_flow._cumred_tpu_translation_rule,\n- lax._reduce_window_sum),\n- multiple_results=False,\n+tf_impl_with_avals[lax.cumsum_p] = _cumred(lax_reduce_window_fn=lax._reduce_window_sum,\n+ lax_reduce_fn=lax.add,\nextra_name_stack=\"cumsum\")\n-tf_impl_with_avals[lax.cumprod_p] = _convert_jax_impl(\n- partial(lax_control_flow._cumred_tpu_translation_rule,\n- lax._reduce_window_prod),\n- multiple_results=False,\n+tf_impl_with_avals[lax.cumprod_p] = _cumred(lax_reduce_window_fn=lax._reduce_window_prod,\n+ lax_reduce_fn=lax.mul,\nextra_name_stack=\"cumprod\")\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -300,28 +300,23 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef cumprod(cls, harness):\nreturn [\n- # TODO: very high tolerance\n+ # JAX uses a different lowering for CPU and GPU.\ncustom_numeric(\n- dtypes=np.float16,\n+ dtypes=(np.float16, jnp.bfloat16),\ndevices=(\"cpu\", \"gpu\"),\nmodes=(\"eager\", \"graph\", \"compiled\"),\n- tol=1e-1)\n+ tol=5e-1)\n]\n@classmethod\ndef cumsum(cls, harness):\nreturn [\n- # TODO: very high tolerance\n- custom_numeric(\n- dtypes=np.float16,\n- tol=0.1,\n- devices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\", \"compiled\")),\n+ # JAX uses a different lowering for CPU and GPU.\ncustom_numeric(\n- dtypes=dtypes.bfloat16,\n- tol=0.5,\n+ dtypes=(np.float16, jnp.bfloat16),\ndevices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\", \"compiled\")),\n+ modes=(\"eager\", \"graph\", \"compiled\"),\n+ tol=5e-1)\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": "@@ -1411,8 +1411,23 @@ def _make_cumreduce_harness(name,\nshape=shape,\ndtype=dtype,\naxis=axis,\n- reverse=reverse)\n-\n+ reverse=reverse,\n+ associative_scan_reductions=False\n+ )\n+ define(\n+ f_jax.__name__,\n+ f\"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_associative_scan_reductions_axis={axis}_reverse={reverse}\",\n+ f_jax, [RandArg(shape, dtype),\n+ StaticArg(axis),\n+ StaticArg(reverse)],\n+ jax_unimplemented=limitations,\n+ f_jax=f_jax,\n+ shape=shape,\n+ dtype=dtype,\n+ axis=axis,\n+ reverse=reverse,\n+ associative_scan_reductions=True\n+ )\n# Validate dtypes for each function\nfor f_jax in [\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -100,7 +100,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n@primitive_harness.parameterized(\nprimitive_harness.all_harnesses,\ninclude_jax_unimpl=False,\n- #one_containing=\"mode=GatherScatterMode.CLIP\"\n+ #one_containing=\"cumprod_dtype_by_fun_shape=float16[8,9]_axis=0_reverse=False\"\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\n@@ -112,6 +112,8 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nfunc_jax = harness.dyn_fun\nargs = harness.dyn_args_maker(self.rng())\nenable_xla = harness.params.get(\"enable_xla\", True)\n+ associative_scan_reductions = harness.params.get(\"associative_scan_reductions\", False)\n+ with jax.jax2tf_associative_scan_reductions(associative_scan_reductions):\nself.ConvertAndCompare(func_jax, *args, limitations=limitations,\nenable_xla=enable_xla)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add jax2tf_associative_scan_reductions flag This flag allows users to match the JAX performance for associative reductions in CPU. See README.md for details.
260,424
14.01.2022 11:18:40
0
f591d0b2e946826fea57b4ced8d9928e4114748c
Add ensure_compile_time_eval docstring to docs
[ { "change_type": "MODIFY", "old_path": "docs/jax.rst", "new_path": "docs/jax.rst", "diff": "@@ -95,6 +95,7 @@ Parallelization (:code:`pmap`)\n.. autofunction:: jit\n.. autofunction:: disable_jit\n+.. autofunction:: ensure_compile_time_eval\n.. autofunction:: xla_computation\n.. autofunction:: make_jaxpr\n.. autofunction:: eval_shape\n" } ]
Python
Apache License 2.0
google/jax
Add ensure_compile_time_eval docstring to docs
260,424
10.01.2022 18:21:41
0
8ea85769eaf35f591a0b3a9710ba4a49c31a7bc9
Checkify: add way to disable categories of errors. By default only user_asserts are lifted into the checked function.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import enum\nfrom dataclasses import dataclass\nfrom functools import partial\nimport itertools as it\n-from typing import Union, Optional, Callable, Dict, Tuple, TypeVar\n+from typing import Union, Optional, Callable, Dict, Tuple, TypeVar, Set, FrozenSet\nimport numpy as np\n@@ -97,6 +98,13 @@ class CheckifyTracer(core.Tracer):\nclass CheckifyTrace(core.Trace):\npure = lift = lambda self, val: CheckifyTracer(self, val)\n+ def __init__(self, main: core.MainTrace, sublevel: core.Sublevel,\n+ enabled_errors: FrozenSet['ErrorCategory']) -> None:\n+ self.main = main\n+ self.level = main.level\n+ self.sublevel = sublevel\n+ self.main.enabled_errors = enabled_errors\n+\ndef sublift(self, tracer):\nreturn CheckifyTracer(self, tracer.val)\n@@ -104,7 +112,7 @@ class CheckifyTrace(core.Trace):\nin_vals = [t.val for t in tracers]\nrule = error_checks.get(primitive)\nif rule:\n- out, self.main.error = rule(self.main.error, *in_vals, **params) # type: ignore\n+ out, self.main.error = rule(self.main.error, self.main.enabled_errors, *in_vals, **params) # type: ignore\nelse:\nout = primitive.bind(*in_vals, **params)\nif primitive.multiple_results:\n@@ -166,18 +174,18 @@ def _reduce_any_error(errs, codes):\nerrs_, codes_ = lax.sort_key_val(errs, codes, dimension=0)\nreturn errs_[-1], codes_[-1]\n-ErrorCheckRule = Callable\n+ErrorCheckRule = Callable # (Error, FrozenSet[ErrorCategory], *in_vals, **params) -> (Any, Error)\nerror_checks: Dict[core.Primitive, ErrorCheckRule] = {}\n-def checkify_flat(fun: lu.WrappedFun, *args):\n+def checkify_flat(fun: lu.WrappedFun, enabled_errors: FrozenSet['ErrorCategory'], *args):\nfun, msgs = checkify_subtrace(fun)\n- fun = checkify_traceable(fun, tuple(init_error.msgs.items()))\n+ fun = checkify_traceable(fun, tuple(init_error.msgs.items()), enabled_errors)\nerr, code, *outvals = fun.call_wrapped(init_error.err, init_error.code, *args)\nreturn (err, code, outvals), msgs()\n@lu.transformation\n-def checkify_traceable(msgs, err, code, *args):\n- with core.new_main(CheckifyTrace) as main:\n+def checkify_traceable(msgs, enabled_errors, err, code, *args):\n+ with core.new_main(CheckifyTrace, enabled_errors=enabled_errors) as main:\nouts = yield (main, msgs, err, code, *args), {}\ndel main\nyield outs\n@@ -196,13 +204,13 @@ def checkify_subtrace(main, msgs, err, code, *args):\n# TODO take (error_aval, code_aval) instead of error here?\n-def checkify_jaxpr(jaxpr, error):\n+def checkify_jaxpr(jaxpr, error, enabled_errors):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n- return checkify_fun_to_jaxpr(f, error, jaxpr.in_avals)\n+ return checkify_fun_to_jaxpr(f, error, enabled_errors, jaxpr.in_avals)\n-def checkify_fun_to_jaxpr(f, error, in_avals):\n+def checkify_fun_to_jaxpr(f, error, enabled_errors, in_avals):\nf, msgs = checkify_subtrace(f)\n- f = checkify_traceable(f, tuple(error.msgs.items()))\n+ f = checkify_traceable(f, tuple(error.msgs.items()), enabled_errors)\nerr_aval = core.raise_to_shaped(core.get_aval(error.err))\ncode_aval = core.raise_to_shaped(core.get_aval(error.code))\navals_in = [err_aval, code_aval, *in_avals]\n@@ -244,13 +252,15 @@ def assert_abstract_eval(pred, code, *, msgs):\ndef summary() -> str:\nreturn str(source_info_util.summarize(source_info_util.current()))\n-def nan_error_check(prim, error, *in_vals, **params):\n+def nan_error_check(prim, error, enabled_errors, *in_vals, **params):\nout = prim.bind(*in_vals, **params)\n+ if ErrorCategory.NAN not in enabled_errors:\n+ return out, error\nno_nans = jnp.logical_not(jnp.any(jnp.isnan(out)))\nmsg = f\"nan generated by primitive {prim.name} at {summary()}\"\nreturn out, assert_func(error, no_nans, msg)\n-def gather_error_check(error, operand, start_indices, *,\n+def gather_error_check(error, enabled_errors, operand, start_indices, *,\ndimension_numbers, slice_sizes, unique_indices,\nindices_are_sorted, mode, fill_value):\nout = lax.gather_p.bind(\n@@ -258,6 +268,9 @@ def gather_error_check(error, operand, start_indices, *,\nslice_sizes=slice_sizes, unique_indices=unique_indices,\nindices_are_sorted=indices_are_sorted, mode=mode, fill_value=fill_value)\n+ if ErrorCategory.OOB not in enabled_errors:\n+ return out, error\n+\n# compare to OOB masking logic in lax._gather_translation_rule\ndnums = dimension_numbers\noperand_dims = np.array(operand.shape)\n@@ -270,12 +283,13 @@ def gather_error_check(error, operand, start_indices, *,\nreturn out, assert_func(error, all_inbounds, msg)\nerror_checks[lax.gather_p] = gather_error_check\n-def div_error_check(error, x, y):\n+def div_error_check(error, enabled_errors, x, y):\n\"\"\"Checks for division by zero and NaN.\"\"\"\n+ if ErrorCategory.DIV in enabled_errors:\nall_nonzero = jnp.logical_not(jnp.any(jnp.equal(y, 0)))\nmsg = f'divided by zero at {summary()}'\n- div_by_zero_err = assert_func(error, all_nonzero, msg)\n- return nan_error_check(lax.div_p, div_by_zero_err, x, y)\n+ error = assert_func(error, all_nonzero, msg)\n+ return nan_error_check(lax.div_p, error, enabled_errors, x, y)\nerror_checks[lax.div_p] = div_error_check\ndef scatter_in_bounds(operand, indices, updates, dnums):\n@@ -300,10 +314,9 @@ def scatter_in_bounds(operand, indices, updates, dnums):\nupper_in_bounds = jnp.all(jnp.less_equal(indices, upper_bound))\nreturn jnp.logical_and(lower_in_bounds, upper_in_bounds)\n-def scatter_error_check(prim, error, operand, indices, updates, *,\n- update_jaxpr, update_consts,\n- dimension_numbers, indices_are_sorted,\n- unique_indices, mode):\n+def scatter_error_check(prim, error, enabled_errors, operand, indices, updates,\n+ *, update_jaxpr, update_consts, dimension_numbers,\n+ indices_are_sorted, unique_indices, mode):\n\"\"\"Checks if indices are within bounds and update does not generate NaN.\"\"\"\nout = prim.bind(\noperand, indices, updates, update_jaxpr=update_jaxpr,\n@@ -311,6 +324,9 @@ def scatter_error_check(prim, error, operand, indices, updates, *,\nindices_are_sorted=indices_are_sorted, unique_indices=unique_indices,\nmode=mode)\n+ if ErrorCategory.OOB not in enabled_errors:\n+ return out, error\n+\nin_bounds = scatter_in_bounds(operand, indices, updates, dimension_numbers)\noob_msg = f'out-of-bounds indexing while updating at {summary()}'\noob_error = assert_func(error, in_bounds, oob_msg)\n@@ -324,8 +340,8 @@ error_checks[lax.scatter_mul_p] = partial(scatter_error_check, lax.scatter_mul_p\nerror_checks[lax.scatter_min_p] = partial(scatter_error_check, lax.scatter_min_p)\nerror_checks[lax.scatter_max_p] = partial(scatter_error_check, lax.scatter_max_p)\n-def cond_error_check(error, index, *ops, branches, linear):\n- new_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error) for jxpr in branches)\n+def cond_error_check(error, enabled_errors, index, *ops, branches, linear):\n+ new_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error, enabled_errors) for jxpr in branches)\nnew_linear = (False, False, *linear)\nerr, code, *outs = lax.cond_p.bind(\nindex, error.err, error.code, *ops,\n@@ -334,9 +350,9 @@ def cond_error_check(error, index, *ops, branches, linear):\nreturn outs, Error(err, code, new_msgs)\nerror_checks[lax.cond_p] = cond_error_check\n-def scan_error_check(error, *in_flat, reverse, length, jaxpr, num_consts, num_carry, linear, unroll):\n+def scan_error_check(error, enabled_errors, *in_flat, reverse, length, jaxpr, num_consts, num_carry, linear, unroll):\nconsts, carry, xs = split_list(in_flat, [num_consts, num_carry])\n- checked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error)\n+ checked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error, enabled_errors)\nnew_linear = (False, False, *linear)\nnew_in_flat = [*consts, error.err, error.code, *carry, *xs]\nerr, code, *outs = lax.scan_p.bind(\n@@ -348,14 +364,14 @@ def scan_error_check(error, *in_flat, reverse, length, jaxpr, num_consts, num_ca\nreturn outs, Error(err, code, new_msgs)\nerror_checks[lax.scan_p] = scan_error_check\n-def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error):\n+def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors):\ncond_f = core.jaxpr_as_fun(cond_jaxpr)\nbody_f = core.jaxpr_as_fun(body_jaxpr)\ndef new_body_f(*vals):\nout = body_f(*vals)\n_ = cond_f(*out) # this checks if the next cond application will error\nreturn out\n- return checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, body_jaxpr.in_avals)\n+ return checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, enabled_errors, body_jaxpr.in_avals)\ndef ignore_errors_jaxpr(jaxpr, error):\n\"\"\"Constructs a jaxpr which takes two extra args but ignores them.\"\"\"\n@@ -369,13 +385,13 @@ def ignore_errors_jaxpr(jaxpr, error):\njaxpr.outvars, jaxpr.eqns)\nreturn core.ClosedJaxpr(new_jaxpr, consts)\n-def while_loop_error_check(error, *in_flat, cond_nconsts, cond_jaxpr, body_nconsts, body_jaxpr):\n- checked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error)\n+def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts, cond_jaxpr, body_nconsts, body_jaxpr):\n+ checked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\nchecked_cond_fun = core.jaxpr_as_fun(checked_cond_jaxpr)\n# Check if the first cond application will error.\ncond_err, cond_code, _ = checked_cond_fun(error.err, error.code, *in_flat)\n- checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error)\n+ checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors)\ncompat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\nnew_in_flat = [*c_consts, *b_consts, cond_err, cond_code, *carry]\n@@ -453,7 +469,10 @@ add_nan_check(lax.select_p)\nadd_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n-def assert_discharge_rule(error, pred, code, *, msgs):\n+def assert_discharge_rule(error, enabled_errors, pred, code, *, msgs):\n+ if ErrorCategory.ASSERT not in enabled_errors:\n+ return [], error\n+\nout_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})\n@@ -462,13 +481,24 @@ error_checks[assert_p] = assert_discharge_rule\n## checkify api\n+ErrorCategory = enum.Enum('ErrorCategory', ['NAN', 'OOB', 'DIV', 'ASSERT'])\n+\n+float_errors = {ErrorCategory.NAN, ErrorCategory.DIV}\n+index_errors = {ErrorCategory.OOB}\n+automatic_errors = float_errors | index_errors\n+user_asserts = {ErrorCategory.ASSERT}\n+\nOut = TypeVar('Out')\n-def checkify(fun: Callable[..., Out]) -> Callable[..., Tuple[Error, Out]]:\n+def checkify(fun: Callable[..., Out], errors: Set[ErrorCategory] = user_asserts) -> Callable[..., Tuple[Error, Out]]:\n+ if not errors:\n+ raise ValueError('Checkify needs to be called with at least one enabled'\n+ ' ErrorCategory, was called with an empty errors set.')\n+\n@traceback_util.api_boundary\ndef checked_fun(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\nf, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- (err, code, out_flat), msgs = checkify_flat(f, *args_flat)\n+ (err, code, out_flat), msgs = checkify_flat(f, frozenset(errors), *args_flat)\nout = tree_unflatten(out_tree(), out_flat)\nreturn Error(err, code, msgs), out\nreturn checked_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -39,11 +39,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn y1 + y2\nf = jax.jit(f) if jit else f\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n- err, _ = checkify.checkify(f)(3., 4.)\n+ err, _ = checked_f(3., 4.)\nself.assertIs(err.get(), None)\n- err, _ = checkify.checkify(f)(3., jnp.inf)\n+ err, _ = checked_f(3., jnp.inf)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive sin')\n@@ -58,16 +59,17 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn w\nf = jax.jit(f) if jit else f\n+ checked_f = checkify.checkify(f, errors=checkify.index_errors)\n- err, _ = checkify.checkify(f)(jnp.arange(3), 2)\n+ err, _ = checked_f(jnp.arange(3), 2)\nself.assertIs(err.get(), None)\n- err, _ = checkify.checkify(f)(jnp.arange(3), 5)\n+ err, _ = checked_f(jnp.arange(3), 5)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n@parameterized.named_parameters(\n- {\"testcase_name\": f\"_update={update_fn}\", \"update_fn\": update_fn}\n+ {\"testcase_name\": f\"_updatefn={update_fn}\", \"update_fn\": update_fn}\nfor update_fn in [\"set\", \"add\", \"multiply\", \"divide\", \"power\", \"min\",\n\"max\", \"get\"])\ndef test_jit_oob_update(self, update_fn):\n@@ -75,11 +77,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn getattr(x.at[i], update_fn)(1.)\nf = jax.jit(f)\n+ checked_f = checkify.checkify(f, errors=checkify.index_errors)\n- err, _ = checkify.checkify(f)(jnp.arange(3), 2)\n+ err, _ = checked_f(jnp.arange(3), 2)\nself.assertIs(err.get(), None)\n- err, _ = checkify.checkify(f)(jnp.arange(3), 3)\n+ err, _ = checked_f(jnp.arange(3), 3)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n@@ -91,15 +94,16 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn x/y\nf = jax.jit(f) if jit else f\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n- err, _ = checkify.checkify(f)(jnp.ones((3,)), jnp.ones((3,)))\n+ err, _ = checked_f(jnp.ones((3,)), jnp.ones((3,)))\nself.assertIs(err.get(), None)\n- err, _ = checkify.checkify(f)(jnp.ones((3,)), jnp.array([1, 0, 1]))\n+ err, _ = checked_f(jnp.ones((3,)), jnp.array([1, 0, 1]))\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n- err, _ = checkify.checkify(f)(jnp.array([1, jnp.inf, 1]), jnp.array([1, jnp.inf, 1]))\n+ err, _ = checked_f(jnp.array([1, jnp.inf, 1]), jnp.array([1, jnp.inf, 1]))\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive div')\n@@ -114,18 +118,19 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn z\nf = jax.jit(f) if jit else f\n+ checked_f = checkify.checkify(f, errors=checkify.automatic_errors)\n# no error\n- err, _ = checkify.checkify(f)(jnp.array([0., jnp.inf, 2.]), 2)\n+ err, _ = checked_f(jnp.array([0., jnp.inf, 2.]), 2)\nself.assertIs(err.get(), None)\n# oob error\n- err, _ = checkify.checkify(f)(jnp.array([0., 1., 2.]), 5)\n+ err, _ = checked_f(jnp.array([0., 1., 2.]), 5)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n# nan error\n- err, _ = checkify.checkify(f)(jnp.array([0., 1., jnp.inf]), 2)\n+ err, _ = checked_f(jnp.array([0., 1., jnp.inf]), 2)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive cos')\n@@ -139,9 +144,10 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn y * z\nf = jax.jit(f) if jit else f\n+ checked_f = checkify.checkify(f, errors=checkify.automatic_errors)\n# both oob and nan error, but oob happens first\n- err, _ = checkify.checkify(f)(jnp.array([0., 1., jnp.inf]), 5)\n+ err, _ = checked_f(jnp.array([0., 1., jnp.inf]), 5)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'out-of-bounds indexing')\n@@ -155,13 +161,14 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ny1 = jnp.sin(x1)\ny2 = jnp.sin(x2)\nreturn y1 + y2\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\nxs = jnp.array([0., 2.])\n- err, _ = checkify.checkify(f)(xs, xs)\n+ err, _ = checked_f(xs, xs)\nself.assertIs(err.get(), None)\nys = jnp.array([3., jnp.inf])\n- err, _ = checkify.checkify(f)(xs, ys)\n+ err, _ = checked_f(xs, ys)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive sin')\n@@ -173,14 +180,16 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nlambda: jnp.sin(x),\nlambda: x)\n- err, y = checkify.checkify(f)(3.)\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\n+ err, y = checked_f(3.)\nself.assertIs(err.get(), None)\n- err, y = checkify.checkify(f)(jnp.inf)\n+ err, y = checked_f(jnp.inf)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive sin')\n- err, y = checkify.checkify(f)(-jnp.inf)\n+ err, y = checked_f(-jnp.inf)\nself.assertIs(err.get(), None)\n@@ -193,14 +202,16 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(xs):\nreturn lax.scan(scan_body, None, xs)\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\nxs = jnp.array([0., 2.])\n- err, (_, ch_outs) = checkify.checkify(f)(xs)\n+ err, (_, ch_outs) = checked_f(xs)\n_, outs = f(xs)\nself.assertIs(err.get(), None)\nself.assertArraysEqual(ch_outs, outs)\nxs = jnp.array([3., jnp.inf])\n- err, (_, ch_outs) = checkify.checkify(f)(xs)\n+ err, (_, ch_outs) = checked_f(xs)\n_, outs = f(xs)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n@@ -217,8 +228,10 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(carry, xs):\nreturn lax.scan(scan_body, carry, xs)\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\ncarry, xs = 3., jnp.ones((2,))\n- err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ err, (ch_out_carry, ch_outs) = checked_f(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIs(err.get(), None)\nself.assertArraysEqual(ch_outs, outs)\n@@ -226,7 +239,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# error happens on first iteration\ncarry, xs = 1., jnp.ones((2,))\n- err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ err, (ch_out_carry, ch_outs) = checked_f(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n@@ -235,7 +248,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# error happens on second iteration\ncarry, xs = 2., jnp.ones((4,))\n- err, (ch_out_carry, ch_outs) = checkify.checkify(f)(carry, xs)\n+ err, (ch_out_carry, ch_outs) = checked_f(carry, xs)\nout_carry, outs = f(carry, xs)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n@@ -257,14 +270,16 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, while_body, (init_val, 0.))\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\ninit_val = 1.\n- err, ch_out = checkify.checkify(f)(init_val)\n+ err, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIs(err.get(), None)\nself.assertArraysEqual(ch_out, out)\ninit_val = 0.\n- err, ch_out = checkify.checkify(f)(init_val)\n+ err, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n@@ -283,14 +298,16 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, while_body, init_val)\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\ninit_val = 1.\n- err, ch_out = checkify.checkify(f)(init_val)\n+ err, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIs(err.get(), None)\nself.assertArraysEqual(ch_out, out)\ninit_val = 0.\n- err, ch_out = checkify.checkify(f)(init_val)\n+ err, ch_out = checked_f(init_val)\nout = f(init_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n@@ -307,15 +324,17 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, lambda val: val-1, init_val)\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\n# error on first cond\ninit_val = 0.\n- err, _ = checkify.checkify(f)(init_val)\n+ err, _ = checked_f(init_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n# error on second cond\ninit_val = 1.\n- err, _ = checkify.checkify(f)(init_val)\n+ err, _ = checked_f(init_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"divided by zero\")\n@@ -335,25 +354,53 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(cond_val, body_val):\nreturn lax.while_loop(while_cond, while_body, (0., cond_val, body_val))\n+ checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+\ncond_val = jnp.inf\nbody_val = 1.\n- err, _ = checkify.checkify(f)(cond_val, body_val)\n+ err, _ = checked_f(cond_val, body_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\ncond_val = 1.\nbody_val = jnp.inf\n- err, _ = checkify.checkify(f)(cond_val, body_val)\n+ err, _ = checked_f(cond_val, body_val)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"nan generated by primitive cos\")\ncond_val = jnp.inf\nbody_val = jnp.inf\n- err, _ = checkify.checkify(f)(cond_val, body_val)\n+ err, _ = checked_f(cond_val, body_val)\nself.assertIsNotNone(err.get())\n# first error which occurs is in cond\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ def test_empty_enabled_errors(self):\n+ with self.assertRaisesRegex(ValueError, 'called with an empty errors set'):\n+ checkify.checkify(lambda x: x, errors={})\n+\n+ @parameterized.named_parameters(\n+ (\"assert\", checkify.user_asserts, \"must be negative!\"),\n+ (\"div\", {checkify.ErrorCategory.DIV}, \"divided by zero\"),\n+ (\"nan\", {checkify.ErrorCategory.NAN}, \"nan generated\"),\n+ (\"oob\", checkify.index_errors, \"out-of-bounds indexing\"),\n+ (\"automatic_errors\", checkify.automatic_errors, \"divided by zero\"),\n+ )\n+ @jtu.skip_on_devices('tpu')\n+ def test_enabled_errors(self, error_set, expected_error):\n+ def multi_errors(x):\n+ x = x/0 # DIV\n+ x = jnp.sin(x) # NAN\n+ x = x[500] # OOB\n+ checkify.assert_(x < 0, \"must be negative!\") # ASSERT\n+ return x\n+\n+ x = jnp.ones((2,))\n+ err, _ = checkify.checkify(multi_errors, errors=error_set)(x)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), expected_error)\n+\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_assert_primitive_impl(self):\ndef f():\n" } ]
Python
Apache License 2.0
google/jax
Checkify: add way to disable categories of errors. By default only user_asserts are lifted into the checked function.
260,335
18.01.2022 11:17:48
28,800
5884c1f20eb63e0f07ca7ce41c3a9cc67950bdf6
add caching to partial_eval_jaxpr follow-up to
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -723,6 +723,11 @@ def partial_eval_jaxpr(jaxpr: ClosedJaxpr, unknowns: Sequence[bool],\nto obtain the full outputs once `jaxpr_unknown` is ran. Outputs known ahead of time will\nsimply get passed as residual constants and returned immediately.\n\"\"\"\n+ instantiate = tuple(instantiate) if isinstance(instantiate, list) else instantiate\n+ return _partial_eval_jaxpr(jaxpr, tuple(unknowns), instantiate)\n+\n+@cache()\n+def _partial_eval_jaxpr(jaxpr, unknowns, instantiate):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\ncell = []\n" } ]
Python
Apache License 2.0
google/jax
add caching to partial_eval_jaxpr follow-up to #9196
260,390
18.01.2022 14:17:17
28,800
9d43ccafa3598827063cabe49c697c6747335e0d
converting to use switch
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -289,28 +289,20 @@ def _calc_P_Q(A):\nA_L1 = np_linalg.norm(A,1)\nn_squarings = 0\nif A.dtype == 'float64' or A.dtype == 'complex128':\n- U3, V3 = _pade3(A)\n- U5, V5 = _pade5(A)\n- U7, V7 = _pade7(A)\n- U9, V9 = _pade9(A)\nmaxnorm = 5.371920351148152\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\n- U13, V13 = _pade13(A)\nconds = jnp.array([1.495585217958292e-002, 2.539398330063230e-001,\n- 9.504178996162932e-001, 2.097847961257068e+000])\n- U = jnp.select((A_L1 < conds), (U3, U5, U7, U9), U13)\n- V = jnp.select((A_L1 < conds), (V3, V5, V7, V9), V13)\n+ 9.504178996162932e-001, 2.097847961257068e+000, jnp.inf])\n+ idx = jnp.argmax(A_L1 < conds)\n+ U, V = lax.switch(idx, [_pade3, _pade5, _pade7, _pade9, _pade13])\nelif A.dtype == 'float32' or A.dtype == 'complex64':\n- U3,V3 = _pade3(A)\n- U5,V5 = _pade5(A)\nmaxnorm = 3.925724783138660\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\n- U7,V7 = _pade7(A)\n- conds = jnp.array([4.258730016922831e-001, 1.880152677804762e+000])\n- U = jnp.select((A_L1 < conds), (U3, U5), U7)\n- V = jnp.select((A_L1 < conds), (V3, V5), V7)\n+ conds = jnp.array([4.258730016922831e-001, 1.880152677804762e+000, jnp.inf])\n+ idx = jnp.argmax(A_L1 < conds)\n+ U, V = lax.switch(idx, [_pade3, _pade5, _pade7])\nelse:\nraise TypeError(\"A.dtype={} is not supported.\".format(A.dtype))\nP = U + V # p_m(A) : numerator\n" } ]
Python
Apache License 2.0
google/jax
converting to use switch
260,390
18.01.2022 16:28:36
28,800
cbb2f7baabaab1084b4ed5b6617ebd7ec1181d74
changed to use argwhere
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -294,15 +294,15 @@ def _calc_P_Q(A):\nA = A / 2**n_squarings\nconds = jnp.array([1.495585217958292e-002, 2.539398330063230e-001,\n9.504178996162932e-001, 2.097847961257068e+000, jnp.inf])\n- idx = jnp.argmax(A_L1 < conds)\n- U, V = lax.switch(idx, [_pade3, _pade5, _pade7, _pade9, _pade13])\n+ idx = jnp.argwhere(A_L1 < conds, size=1).squeeze()\n+ U, V = lax.switch(idx, [_pade3, _pade5, _pade7, _pade9, _pade13], A)\nelif A.dtype == 'float32' or A.dtype == 'complex64':\nmaxnorm = 3.925724783138660\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\nconds = jnp.array([4.258730016922831e-001, 1.880152677804762e+000, jnp.inf])\n- idx = jnp.argmax(A_L1 < conds)\n- U, V = lax.switch(idx, [_pade3, _pade5, _pade7])\n+ idx = jnp.argwhere(A_L1 < conds, size=1).squeeze()\n+ U, V = lax.switch(idx, [_pade3, _pade5, _pade7], A)\nelse:\nraise TypeError(\"A.dtype={} is not supported.\".format(A.dtype))\nP = U + V # p_m(A) : numerator\n" } ]
Python
Apache License 2.0
google/jax
changed to use argwhere
260,390
19.01.2022 10:02:06
28,800
2d2ac12aa074a137cdf9d3d427b36f14b1fb3f1f
switching to use jnp.digitize for index identification
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -293,15 +293,15 @@ def _calc_P_Q(A):\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\nconds = jnp.array([1.495585217958292e-002, 2.539398330063230e-001,\n- 9.504178996162932e-001, 2.097847961257068e+000, jnp.inf])\n- idx = jnp.argwhere(A_L1 < conds, size=1).squeeze()\n+ 9.504178996162932e-001, 2.097847961257068e+000])\n+ idx = jnp.digitize(A_L1, conds)\nU, V = lax.switch(idx, [_pade3, _pade5, _pade7, _pade9, _pade13], A)\nelif A.dtype == 'float32' or A.dtype == 'complex64':\nmaxnorm = 3.925724783138660\nn_squarings = jnp.maximum(0, jnp.floor(jnp.log2(A_L1 / maxnorm)))\nA = A / 2**n_squarings\n- conds = jnp.array([4.258730016922831e-001, 1.880152677804762e+000, jnp.inf])\n- idx = jnp.argwhere(A_L1 < conds, size=1).squeeze()\n+ conds = jnp.array([4.258730016922831e-001, 1.880152677804762e+000])\n+ idx = jnp.digitize(A_L1, conds)\nU, V = lax.switch(idx, [_pade3, _pade5, _pade7], A)\nelse:\nraise TypeError(\"A.dtype={} is not supported.\".format(A.dtype))\n" } ]
Python
Apache License 2.0
google/jax
switching to use jnp.digitize for index identification
260,335
19.01.2022 10:24:09
28,800
726f60f6bc2ba99128d815f9f8e2f22ce028b0ba
remove cpu platform setting in quickstart fixes
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/quickstart.ipynb", "new_path": "docs/notebooks/quickstart.ipynb", "diff": "\"from jax import random\"\n]\n},\n- {\n- \"cell_type\": \"code\",\n- \"execution_count\": null,\n- \"metadata\": {\n- \"tags\": [\n- \"remove-cell\"\n- ]\n- },\n- \"outputs\": [],\n- \"source\": [\n- \"# Prevent GPU/TPU warning.\\n\",\n- \"import jax; jax.config.update('jax_platform_name', 'cpu')\"\n- ]\n- },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/quickstart.md", "new_path": "docs/notebooks/quickstart.md", "diff": "@@ -45,13 +45,6 @@ from jax import grad, jit, vmap\nfrom jax import random\n```\n-```{code-cell} ipython3\n-:tags: [remove-cell]\n-\n-# Prevent GPU/TPU warning.\n-import jax; jax.config.update('jax_platform_name', 'cpu')\n-```\n-\n+++ {\"id\": \"FQ89jHCYfhpg\"}\n## Multiplying Matrices\n" } ]
Python
Apache License 2.0
google/jax
remove cpu platform setting in quickstart fixes #9244
260,335
19.01.2022 11:43:02
28,800
13ede5b2eb8b1ca7e07642791c19bbf5df1c6284
add origin info to leaked tracer error add origin info to vmap tracers (BatchTracer)
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -747,7 +747,8 @@ the following:\nthreading.current_thread().pydev_do_not_trace = True\n\"\"\"\n-def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]):\n+def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]\n+ ) -> List[Tracer]:\n\"\"\"Find the leaked tracers holding a reference to the MainTrace or SubLevel.\nIt's possible there's none! eg. there's some cases where JAX itself holds a\n@@ -762,6 +763,11 @@ def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]):\ntracers = list(filter(lambda x: isinstance(x, Tracer), gc.get_referrers(*traces)))\nreturn tracers\n+def leaked_tracer_error(name: str, t, tracers: List[Tracer]) -> Exception:\n+ assert tracers\n+ msgs = '\\n\\n'.join(f'{tracer}{tracer._origin_msg()}' for tracer in tracers)\n+ return Exception(f'Leaked {name} {t}. Leaked tracer(s):\\n\\n{msgs}\\n')\n+\n@contextmanager\ndef new_main(trace_type: Type[Trace],\ndynamic: bool = False,\n@@ -788,8 +794,7 @@ def new_main(trace_type: Type[Trace],\ndel main\nif t() is not None:\nleaked_tracers = maybe_find_leaked_tracers(t())\n- if leaked_tracers:\n- raise Exception(f'Leaked level {t()}. Leaked tracer(s): {leaked_tracers}.')\n+ if leaked_tracers: raise leaked_tracer_error(\"trace\", t(), leaked_tracers)\n@contextmanager\ndef new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\n@@ -811,8 +816,7 @@ def new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\ndel main\nif t() is not None:\nleaked_tracers = maybe_find_leaked_tracers(t())\n- if leaked_tracers:\n- raise Exception(f'Leaked level {t()}. Leaked tracer(s): {leaked_tracers}.')\n+ if leaked_tracers: raise leaked_tracer_error(\"trace\", t(), leaked_tracers)\n@contextmanager\ndef ensure_compile_time_eval():\n@@ -892,7 +896,7 @@ def new_sublevel() -> Generator[None, None, None]:\nif t() is not None:\nleaked_tracers = maybe_find_leaked_tracers(t())\nif leaked_tracers:\n- raise Exception(f'Leaked sublevel {t()}. Leaked tracer(s): {leaked_tracers}.')\n+ raise leaked_tracer_error(\"sublevel\", t(), leaked_tracers)\ndef full_lower(val):\nif isinstance(val, Tracer):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -26,9 +26,10 @@ from jax._src.tree_util import tree_unflatten, tree_flatten\nfrom jax._src.ad_util import (add_jaxvals, add_jaxvals_p, zeros_like_jaxval,\nzeros_like_p, Zero)\nfrom jax import linear_util as lu\n-from jax._src.util import (unzip2, safe_map, safe_zip, wrap_name, split_list,\n- canonicalize_axis, moveaxis, as_hashable_function,\n- curry, memoize, cache)\n+from jax._src.util import (unzip2, unzip3, safe_map, safe_zip, wrap_name,\n+ split_list, canonicalize_axis, moveaxis,\n+ as_hashable_function, curry, memoize, cache)\n+from jax._src import source_info_util\nfrom jax.interpreters import partial_eval as pe\nmap = safe_map\n@@ -51,7 +52,8 @@ def to_elt(trace: Trace, get_idx: GetIdx, x: Vmappable, spec: MapSpec) -> Elt:\nreturn handler(partial(to_elt, trace, get_idx), get_idx, x, spec)\nelse:\nspec = spec and canonicalize_axis(spec, len(np.shape(x)))\n- return BatchTracer(trace, x, spec) if spec is not None else x\n+ return (BatchTracer(trace, x, spec, source_info_util.current())\n+ if spec is not None else x)\nto_elt_handlers: Dict[Type, ToEltHandler] = {}\ndef from_elt(trace: 'BatchTrace', axis_size: AxisSize, x: Elt, spec: MapSpec\n@@ -107,9 +109,10 @@ NotMapped = type(None)\nnot_mapped = None\nclass BatchTracer(Tracer):\n- __slots__ = ['val', 'batch_dim']\n+ __slots__ = ['val', 'batch_dim', 'source_info']\n- def __init__(self, trace, val, batch_dim: Optional[int]):\n+ def __init__(self, trace, val, batch_dim: Optional[int],\n+ source_info: Optional[source_info_util.SourceInfo] = None):\nif config.jax_enable_checks:\nassert type(batch_dim) in (int, NotMapped)\nif type(batch_dim) is int:\n@@ -118,6 +121,7 @@ class BatchTracer(Tracer):\nself._trace = trace\nself.val = val\nself.batch_dim = batch_dim\n+ self.source_info = source_info\n@property\ndef aval(self):\n@@ -133,19 +137,28 @@ class BatchTracer(Tracer):\nelse:\nreturn self\n+ def _origin_msg(self):\n+ if self.source_info is None:\n+ return \"\"\n+ return (\"\\nThis Tracer was created on line \"\n+ f\"{source_info_util.summarize(self.source_info)}\")\n+\n+ def _contents(self):\n+ return [('val', self.val), ('batch_dim', self.batch_dim)]\n+\nclass BatchTrace(Trace):\ndef __init__(self, *args, axis_name):\nsuper().__init__(*args)\nself.axis_name = axis_name\ndef pure(self, val):\n- return BatchTracer(self, val, not_mapped)\n+ return BatchTracer(self, val, not_mapped, source_info_util.current())\ndef lift(self, val):\n- return BatchTracer(self, val, not_mapped)\n+ return BatchTracer(self, val, not_mapped, source_info_util.current())\ndef sublift(self, val):\n- return BatchTracer(self, val.val, val.batch_dim)\n+ return BatchTracer(self, val.val, val.batch_dim, source_info_util.current())\ndef get_primitive_batcher(self, primitive, frame):\nif primitive in primitive_batchers:\n@@ -183,10 +196,12 @@ class BatchTrace(Trace):\nframe = self.get_frame(vals_in, dims_in)\nbatched_primitive = self.get_primitive_batcher(primitive, frame)\nval_out, dim_out = batched_primitive(vals_in, dims_in, **params)\n+ src = source_info_util.current()\nif primitive.multiple_results:\n+ return [BatchTracer(self, x, d, src) for x, d in zip(val_out, dim_out)]\nreturn map(partial(BatchTracer, self), val_out, dim_out)\nelse:\n- return BatchTracer(self, val_out, dim_out)\n+ return BatchTracer(self, val_out, dim_out, src)\ndef process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):\nassert call_primitive.multiple_results\n@@ -197,14 +212,16 @@ class BatchTrace(Trace):\nelse:\nf, dims_out = batch_subtrace(f, self.main, dims)\nvals_out = call_primitive.bind(f, *vals, **params)\n- return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out())]\n+ src = source_info_util.current()\n+ return [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out())]\ndef post_process_call(self, call_primitive, out_tracers, params):\n- vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n+ for t in out_tracers)\nmain = self.main\ndef todo(vals):\ntrace = main.with_cur_sublevel()\n- return map(partial(BatchTracer, trace), vals, dims)\n+ return map(partial(BatchTracer, trace), vals, dims, srcs)\nreturn vals, todo\ndef process_map(self, map_primitive, f: lu.WrappedFun, tracers, params):\n@@ -245,17 +262,19 @@ class BatchTrace(Trace):\nvals_out = map_primitive.bind(f, *vals, **new_params)\ndims_out = (d + 1 if both_mapped(out_axis, d) and out_axis <= d else d\nfor d, out_axis in zip(dims_out(), out_axes_thunk()))\n- return [BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out)]\n+ src = source_info_util.current()\n+ return [BatchTracer(self, v, d, src) for v, d in zip(vals_out, dims_out)]\ndef post_process_map(self, call_primitive, out_tracers, params):\n- vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n+ for t in out_tracers)\nmain = self.main\ndef both_mapped(in_out_axis, d):\nreturn in_out_axis is not None and d is not not_mapped\ndef todo(vals):\ntrace = main.with_cur_sublevel()\n- return [BatchTracer(trace, v, d + 1 if both_mapped(out_axis, d) and out_axis <= d else d)\n- for v, d, out_axis in zip(vals, dims, params['out_axes_thunk']())]\n+ return [BatchTracer(trace, v, d + 1 if both_mapped(oa, d) and oa <= d else d, s)\n+ for v, d, oa, s in zip(vals, dims, params['out_axes_thunk'](), srcs)]\nif call_primitive.map_primitive:\ndef out_axes_transform(out_axes):\nreturn tuple(out_axis + 1 if both_mapped(out_axis, d) and d < out_axis else out_axis\n@@ -272,19 +291,22 @@ class BatchTrace(Trace):\nif not fst:\nassert out_dims == out_dims[:len(out_dims) // 2] * 2\nout_dims = out_dims[:len(out_dims) // 2]\n- return [BatchTracer(self, v, d) for v, d in zip(out_vals, out_dims)]\n+ src = source_info_util.current()\n+ return [BatchTracer(self, v, d, src) for v, d in zip(out_vals, out_dims)]\ndef post_process_custom_jvp_call(self, out_tracers, jvp_was_run):\n- vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n+ for t in out_tracers)\nmain = self.main\ndef todo(vals):\ntrace = main.with_cur_sublevel()\nif jvp_was_run:\nprimal_dims, tangent_dims = dims[:len(vals)], dims[len(vals):]\nassert primal_dims == tangent_dims\n- return map(partial(BatchTracer, trace), vals, primal_dims)\n+ primal_srcs = srcs[:len(vals)]\n+ return map(partial(BatchTracer, trace), vals, primal_dims, primal_srcs)\nelse:\n- return map(partial(BatchTracer, trace), vals, dims)\n+ return map(partial(BatchTracer, trace), vals, dims, srcs)\nreturn vals, todo\ndef process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, *, out_trees):\n@@ -299,27 +321,31 @@ class BatchTrace(Trace):\nfst, out_dims = lu.merge_linear_aux(out_dims1, out_dims2)\nif not fst:\nout_dims = out_dims[-len(out_vals) % len(out_dims):]\n- return [BatchTracer(self, v, d) for v, d in zip(out_vals, out_dims)]\n+ src = source_info_util.current()\n+ return [BatchTracer(self, v, d, src) for v, d in zip(out_vals, out_dims)]\ndef post_process_custom_vjp_call(self, out_tracers, _):\n- vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n+ for t in out_tracers)\nmain = self.main\ndef todo(vals):\ntrace = main.with_cur_sublevel()\n- return map(partial(BatchTracer, trace), vals, dims)\n+ return map(partial(BatchTracer, trace), vals, dims, srcs)\nreturn vals, todo\ndef post_process_custom_vjp_call_fwd(self, out_tracers, out_trees):\n- vals, dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n+ vals, dims, srcs = unzip3((t.val, t.batch_dim, t.source_info)\n+ for t in out_tracers)\naxis_size, = {x.shape[d] for x, d in zip(vals, dims) if d is not not_mapped}\nmain, trace_type = self.main, self.main.trace_type\naxis_name = self.axis_name\n_, res_tree = out_trees()\nnum_res = res_tree.num_leaves\nres_dims, primal_dims = split_list(dims, [num_res])\n+ _, primal_srcs = split_list(srcs, [num_res])\ndef todo(vals):\ntrace = main.with_cur_sublevel()\n- return map(partial(BatchTracer, trace), vals, primal_dims)\n+ return map(partial(BatchTracer, trace), vals, primal_dims, primal_srcs)\ndef bwd_transform(bwd):\nreturn batch_custom_vjp_bwd(bwd, axis_name, axis_size, dims, (None,),\ntrace_type)\n@@ -354,7 +380,8 @@ def _batch_outer(axis_name, axis_size, in_dims, main_type, *in_vals):\ndef _batch_inner(axis_size, out_dim_dests, main, in_dims, *in_vals):\nin_dims = in_dims() if callable(in_dims) else in_dims\ntrace = main.with_cur_sublevel()\n- idx = memoize(lambda: BatchTracer(trace, make_iota(axis_size), 0))\n+ idx = memoize(lambda: BatchTracer(trace, make_iota(axis_size), 0,\n+ source_info_util.current()))\nin_tracers = map(partial(to_elt, trace, idx), in_vals, in_dims)\nouts = yield in_tracers, {}\nout_dim_dests = out_dim_dests() if callable(out_dim_dests) else out_dim_dests\n@@ -401,8 +428,8 @@ def batch_subtrace(main, in_dims, *in_vals):\n# used in e.g. process_call\ntrace = main.with_cur_sublevel()\nin_dims = in_dims() if callable(in_dims) else in_dims\n- in_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\n- for val, dim in zip(in_vals, in_dims)]\n+ in_tracers = [BatchTracer(trace, x, dim, source_info_util.current())\n+ if dim is not None else x for x, dim in zip(in_vals, in_dims)]\nouts = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1155,6 +1155,12 @@ class DynamicJaxprTracer(core.Tracer):\nreturn ()\ndef _origin_msg(self):\n+ if not self._trace.main.jaxpr_stack: # type: ignore\n+ # If this Tracer has been leaked the jaxpr stack may no longer be\n+ # available. So we can't print as much origin information.\n+ return (\"\\nThis Tracer was created on line \"\n+ f\"{source_info_util.summarize(self._line_info)}\")\n+ else:\ninvar_pos, progenitor_eqns = self._trace.frame.find_progenitors(self)\ndbg = self._trace.main.debug_info\nif dbg is None:\n" } ]
Python
Apache License 2.0
google/jax
add origin info to leaked tracer error add origin info to vmap tracers (BatchTracer)
260,335
18.01.2022 22:22:57
28,800
9488c5ae72432d82c1422dec91239c3aff5cf2c0
checkify: fix and test post_process_call/map
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -29,11 +29,15 @@ from jax.interpreters import partial_eval as pe\nfrom jax.tree_util import tree_flatten, tree_unflatten, register_pytree_node\nfrom jax._src import source_info_util, traceback_util\nfrom jax import lax\n-from jax._src.util import as_hashable_function, unzip2, split_list\n+from jax._src.util import (as_hashable_function, unzip2, split_list, safe_map,\n+ safe_zip)\nsource_info_util.register_exclusion(__file__)\ntraceback_util.register_exclusion(__file__)\n+map, unsafe_map = safe_map, map\n+zip, unsafe_zip = safe_zip, zip\n+\n## Utils\n@@ -112,7 +116,8 @@ class CheckifyTrace(core.Trace):\nin_vals = [t.val for t in tracers]\nrule = error_checks.get(primitive)\nif rule:\n- out, self.main.error = rule(self.main.error, self.main.enabled_errors, *in_vals, **params) # type: ignore\n+ out, self.main.error = rule(self.main.error, self.main.enabled_errors, # type: ignore\n+ *in_vals, **params)\nelse:\nout = primitive.bind(*in_vals, **params)\nif primitive.multiple_results:\n@@ -149,22 +154,25 @@ class CheckifyTrace(core.Trace):\ndef post_process_call(self, primitive, tracers, params):\nvals = [t.val for t in tracers]\nmain = self.main\n- e = popattr(self.main, 'error')\n+ e = popattr(main, 'error')\nerr, code, main.msgs = e.err, e.code, e.msgs\ndef todo(vals):\n- trace = main.with_cur_sublevel()\nerr, code, *vals = vals\n+ setnewattr(main, 'error', Error(err, code, popattr(main, 'msgs')))\n+ trace = main.with_cur_sublevel()\nreturn [CheckifyTracer(trace, x) for x in vals]\nreturn (err, code, *vals), todo\ndef post_process_map(self, primitive, tracers, params):\nvals = [t.val for t in tracers]\nmain = self.main\n- e = popattr(self.main, 'error')\n+ e = popattr(main, 'error')\nerr, code, main.msgs = e.err, e.code, e.msgs\ndef todo(vals):\n+ errs, codes, *vals = vals\n+ err, code = _reduce_any_error(errs, codes)\n+ setnewattr(main, 'error', Error(err, code, popattr(main, 'msgs')))\ntrace = main.with_cur_sublevel()\n- err, code, *vals = vals\nreturn [CheckifyTracer(trace, x) for x in vals]\ndef out_axes_transform(out_axes):\nreturn (0, 0, *out_axes)\n@@ -177,7 +185,8 @@ def _reduce_any_error(errs, codes):\nErrorCheckRule = Callable # (Error, FrozenSet[ErrorCategory], *in_vals, **params) -> (Any, Error)\nerror_checks: Dict[core.Primitive, ErrorCheckRule] = {}\n-def checkify_flat(fun: lu.WrappedFun, enabled_errors: FrozenSet['ErrorCategory'], *args):\n+def checkify_flat(fun: lu.WrappedFun, enabled_errors: FrozenSet['ErrorCategory'],\n+ *args):\nfun, msgs = checkify_subtrace(fun)\nfun = checkify_traceable(fun, tuple(init_error.msgs.items()), enabled_errors)\nerr, code, *outvals = fun.call_wrapped(init_error.err, init_error.code, *args)\n@@ -341,7 +350,8 @@ error_checks[lax.scatter_min_p] = partial(scatter_error_check, lax.scatter_min_p\nerror_checks[lax.scatter_max_p] = partial(scatter_error_check, lax.scatter_max_p)\ndef cond_error_check(error, enabled_errors, index, *ops, branches, linear):\n- new_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error, enabled_errors) for jxpr in branches)\n+ new_branches, msgs_ = unzip2(checkify_jaxpr(jxpr, error, enabled_errors)\n+ for jxpr in branches)\nnew_linear = (False, False, *linear)\nerr, code, *outs = lax.cond_p.bind(\nindex, error.err, error.code, *ops,\n@@ -350,7 +360,8 @@ def cond_error_check(error, enabled_errors, index, *ops, branches, linear):\nreturn outs, Error(err, code, new_msgs)\nerror_checks[lax.cond_p] = cond_error_check\n-def scan_error_check(error, enabled_errors, *in_flat, reverse, length, jaxpr, num_consts, num_carry, linear, unroll):\n+def scan_error_check(error, enabled_errors, *in_flat, reverse, length, jaxpr,\n+ num_consts, num_carry, linear, unroll):\nconsts, carry, xs = split_list(in_flat, [num_consts, num_carry])\nchecked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error, enabled_errors)\nnew_linear = (False, False, *linear)\n@@ -371,7 +382,8 @@ def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors):\nout = body_f(*vals)\n_ = cond_f(*out) # this checks if the next cond application will error\nreturn out\n- return checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, enabled_errors, body_jaxpr.in_avals)\n+ return checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, enabled_errors,\n+ body_jaxpr.in_avals)\ndef ignore_errors_jaxpr(jaxpr, error):\n\"\"\"Constructs a jaxpr which takes two extra args but ignores them.\"\"\"\n@@ -385,13 +397,15 @@ def ignore_errors_jaxpr(jaxpr, error):\njaxpr.outvars, jaxpr.eqns)\nreturn core.ClosedJaxpr(new_jaxpr, consts)\n-def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts, cond_jaxpr, body_nconsts, body_jaxpr):\n- checked_cond_jaxpr, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\n- checked_cond_fun = core.jaxpr_as_fun(checked_cond_jaxpr)\n+def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\n+ cond_jaxpr, body_nconsts, body_jaxpr):\n+ cond_jaxpr_, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\n+ checked_cond_fun = core.jaxpr_as_fun(cond_jaxpr_)\n# Check if the first cond application will error.\ncond_err, cond_code, _ = checked_cond_fun(error.err, error.code, *in_flat)\n- checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors)\n+ checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(\n+ cond_jaxpr, body_jaxpr, error, enabled_errors)\ncompat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\nc_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\nnew_in_flat = [*c_consts, *b_consts, cond_err, cond_code, *carry]\n@@ -489,7 +503,8 @@ automatic_errors = float_errors | index_errors\nuser_asserts = {ErrorCategory.ASSERT}\nOut = TypeVar('Out')\n-def checkify(fun: Callable[..., Out], errors: Set[ErrorCategory] = user_asserts) -> Callable[..., Tuple[Error, Out]]:\n+def checkify(fun: Callable[..., Out], errors: Set[ErrorCategory] = user_asserts\n+ ) -> Callable[..., Tuple[Error, Out]]:\nif not errors:\nraise ValueError('Checkify needs to be called with at least one enabled'\n' ErrorCategory, was called with an empty errors set.')\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+from functools import partial\nimport unittest\nfrom absl.testing import absltest\n@@ -192,7 +193,6 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, y = checked_f(-jnp.inf)\nself.assertIs(err.get(), None)\n-\n@jtu.skip_on_devices('tpu')\ndef test_scan_map(self):\ndef scan_body(_, x):\n@@ -400,6 +400,30 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), expected_error)\n+ @jtu.skip_on_devices('tpu')\n+ def test_post_process_call(self):\n+ @partial(checkify.checkify, errors=checkify.float_errors)\n+ def g(x):\n+ @jax.jit\n+ def f(y):\n+ return jnp.sin(x * y)\n+ return f(jnp.inf)\n+ err, _ = g(2.)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ @jtu.skip_on_devices('tpu')\n+ def test_post_process_map(self):\n+ @partial(checkify.checkify, errors=checkify.float_errors)\n+ def g(x):\n+ @jax.pmap\n+ def f(y):\n+ return jnp.sin(x * y)\n+ return f(jnp.array([jnp.inf]))[0]\n+ err, _ = g(2.)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_assert_primitive_impl(self):\n" } ]
Python
Apache License 2.0
google/jax
checkify: fix and test post_process_call/map
260,335
19.01.2022 18:44:31
28,800
bbaee9c54eeb0303f1b2ae45fc852993007ae5aa
pjit: add test for basic static_argnums
[ { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -40,7 +40,7 @@ from jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters.sharded_jit import PartitionSpec\nfrom jax._src.lib import xla_client as xc\n-from jax.tree_util import tree_map, tree_flatten, tree_unflatten, tree_leaves\n+from jax.tree_util import tree_map, tree_flatten, tree_unflatten\nfrom jax._src.util import (extend_name_stack, HashableFunction, safe_zip,\nwrap_name, wraps, distributed_debug_log,\nsplit_list, cache, tuple_insert)\n@@ -220,8 +220,9 @@ def pjit(fun: Callable,\nf, static_argnums, args, allow_invalid=False)\nelse:\ndyn_args = args\n+ del args\n- args_flat, in_tree = tree_flatten(args)\n+ args_flat, in_tree = tree_flatten(dyn_args)\nflat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\nif donate_argnums:\ndonated_invars = donation_vector(donate_argnums, dyn_args, ())\n@@ -259,9 +260,9 @@ def pjit(fun: Callable,\n@wraps(fun)\ndef wrapped(*args, **kwargs):\n- for arg in tree_leaves(args):\n- _check_arg(arg)\nargs_flat, params, _, out_tree, _ = infer_params(*args, **kwargs)\n+ for arg in args_flat:\n+ _check_arg(arg)\nout = pjit_p.bind(*args_flat, **params)\nreturn tree_unflatten(out_tree, out)\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -622,6 +622,15 @@ class PJitTest(jtu.BufferDonationTestCase):\n\"called with:\\n.*int32.*\",\nlambda: exe(x_i32, x_i32))\n+ @jtu.with_mesh([('x', 2)])\n+ def test_static_argnums(self):\n+ @partial(pjit, in_axis_resources=None, out_axis_resources=None,\n+ static_argnums=(1,))\n+ def f(x, y):\n+ return x + (3 if y == 'hi' else 4)\n+\n+ self.assertEqual(f(1, 'hi' ), 4)\n+ self.assertEqual(f(1, 'bye'), 5)\nclass GDAPjitTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
pjit: add test for basic static_argnums
260,335
19.01.2022 20:40:38
28,800
ced2ae0104057295169fdc3b1ee9ec64d8c41da3
NotImplementedError for new_checkpoint-of-xmap Previously this was getting a default behavior which caused surprising errors downstream.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -617,7 +617,8 @@ xla.register_translation(while_p, _while_loop_translation_rule,\ninitial_style=True)\nad.primitive_transposes[while_p] = _while_transpose_error\nbatching.axis_primitive_batchers[while_p] = _while_loop_batching_rule\n-pe.partial_eval_jaxpr_custom_rules[while_p] = pe.partial_eval_jaxpr_custom_rule_not_implemented\n+pe.partial_eval_jaxpr_custom_rules[while_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'while_loop')\ndef _pred_bcast_select_mhlo(\n@@ -1403,7 +1404,8 @@ pe.custom_partial_eval_rules[cond_p] = _cond_partial_eval\nbatching.axis_primitive_batchers[cond_p] = _cond_batching_rule\nxla.register_translation(cond_p, _cond_translation_rule, initial_style=True)\ncore.custom_typechecks[cond_p] = _cond_typecheck\n-pe.partial_eval_jaxpr_custom_rules[cond_p] = pe.partial_eval_jaxpr_custom_rule_not_implemented\n+pe.partial_eval_jaxpr_custom_rules[cond_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'cond')\nif jax._src.lib._xla_extension_version < 51:\n@@ -2225,7 +2227,8 @@ xla.register_translation(scan_p, xla.lower_fun(_scan_impl, new_style=True,\nbatching.axis_primitive_batchers[scan_p] = _scan_batching_rule\nmasking.masking_rules[scan_p] = _scan_masking_rule\ncore.custom_typechecks[scan_p] = partial(_scan_typecheck, False)\n-pe.partial_eval_jaxpr_custom_rules[scan_p] = pe.partial_eval_jaxpr_custom_rule_not_implemented\n+pe.partial_eval_jaxpr_custom_rules[scan_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'scan')\nmlir.register_lowering(scan_p,\nmlir.lower_fun(_scan_impl, multiple_results=True))\n@@ -2783,7 +2786,8 @@ xla.register_translation(\ninitial_style=True)\nad.primitive_transposes[linear_solve_p] = _linear_solve_transpose_rule\nbatching.axis_primitive_batchers[linear_solve_p] = _linear_solve_batching_rule\n-pe.partial_eval_jaxpr_custom_rules[linear_solve_p] = pe.partial_eval_jaxpr_custom_rule_not_implemented\n+pe.partial_eval_jaxpr_custom_rules[linear_solve_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'linear_solve')\ndef _interleave(a, b, axis):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1067,6 +1067,8 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nself.frame.eqns.append(eqn)\nreturn out_tracers\npe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_process_xmap # type: ignore\n+pe.partial_eval_jaxpr_custom_rules[xmap_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'xmap')\n@lu.transformation_with_aux\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -975,9 +975,11 @@ PartialEvalCustomRule = Callable[\npartial_eval_jaxpr_custom_rules: Dict[Primitive, PartialEvalCustomRule] = {}\ndef partial_eval_jaxpr_custom_rule_not_implemented(\n- saveable: Callable[..., bool], unks_in: Sequence[bool], inst_in: Sequence[bool],\n- eqn: JaxprEqn) -> PartialEvalCustomResult:\n- raise NotImplementedError\n+ name: str, saveable: Callable[..., bool], unks_in: Sequence[bool],\n+ inst_in: Sequence[bool], eqn: JaxprEqn) -> PartialEvalCustomResult:\n+ msg = (f'custom-policy remat rule not implemented for {name}, '\n+ 'open a feature request at https://github.com/google/jax/issues!')\n+ raise NotImplementedError(msg)\nParamsUpdater = Callable[[List[bool], int, dict, dict], Tuple[dict, dict]]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1535,6 +1535,8 @@ xla_pmap_p.def_impl(xla_pmap_impl)\n# Set param update handlers to update `donated_invars` just like xla_call_p\npe.call_param_updaters[xla_pmap_p] = pe.call_param_updaters[xla.xla_call_p]\n+pe.partial_eval_jaxpr_custom_rules[xla_pmap_p] = \\\n+ partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'pmap')\nad.call_param_updaters[xla_pmap_p] = ad.call_param_updaters[xla.xla_call_p]\nad.call_transpose_param_updaters[xla_pmap_p] = \\\nad.call_transpose_param_updaters[xla.xla_call_p]\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -46,6 +46,7 @@ from jax._src.util import curry, unzip2, split_list, prod\nfrom jax._src.lax.lax import DotDimensionNumbers\nfrom jax._src.lax.parallel import pgather\nfrom jax.interpreters import batching, pxla\n+from jax.ad_checkpoint import checkpoint\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -617,6 +618,11 @@ class XMapTest(XMapTestCase):\n\"called with:\\n.*int32.*\",\nlambda: f_exe(x_i32))\n+ def testNewCheckpointError(self):\n+ f = checkpoint(xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...]))\n+ with self.assertRaisesRegex(NotImplementedError, 'xmap'):\n+ jax.grad(f)(jnp.arange(3.))\n+\nclass XMapTestSPMD(SPMDTestMixin, XMapTest):\n\"\"\"Re-executes all basic tests with the SPMD partitioner enabled\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
NotImplementedError for new_checkpoint-of-xmap Previously this was getting a default behavior which caused surprising errors downstream.
260,536
01.11.2021 13:58:37
-3,600
d05431a1ffd27abc3951d723c82fa63db88bdd69
has_aux for jvp and forward-mode AD value_and_grad Changes: revert value_and_grad_fwd add has_aux to jacfwd and jacrev tests fix mypy error
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -964,7 +964,8 @@ def value_and_grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\ntuple). If ``argnums`` is an integer then the gradient has the same shape\nand type as the positional argument indicated by that integer. If argnums is\na sequence of integers, the gradient is a tuple of values with the same\n- shapes and types as the corresponding arguments.\n+ shapes and types as the corresponding arguments. If ``has_aux`` is True\n+ then a tuple of ((value, auxiliary_data), gradient) is returned.\n\"\"\"\ndocstr = (\"Value and gradient of {fun} with respect to positional \"\n@@ -1061,19 +1062,23 @@ _check_output_dtype_grad = partial(_check_output_dtype_revderiv, \"grad\")\ndef jacfwd(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n- holomorphic: bool = False) -> Callable:\n+ has_aux: bool = False, holomorphic: bool = False) -> Callable:\n\"\"\"Jacobian of ``fun`` evaluated column-by-column using forward-mode AD.\nArgs:\nfun: Function whose Jacobian is to be computed.\nargnums: Optional, integer or sequence of integers. Specifies which\npositional argument(s) to differentiate with respect to (default ``0``).\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n+ first element is considered the output of the mathematical function to be\n+ differentiated and the second element is auxiliary data. Default False.\nholomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nReturns:\nA function with the same arguments as ``fun``, that evaluates the Jacobian of\n- ``fun`` using forward-mode automatic differentiation.\n+ ``fun`` using forward-mode automatic differentiation. If ``has_aux`` is True\n+ then a pair of (jacobian, auxiliary_data) is returned.\n>>> import jax\n>>> import jax.numpy as jnp\n@@ -1096,11 +1101,19 @@ def jacfwd(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nf_partial, dyn_args = argnums_partial(f, argnums, args,\nrequire_static_args_hashable=False)\ntree_map(partial(_check_input_dtype_jacfwd, holomorphic), dyn_args)\n+ if not has_aux:\npushfwd = partial(_jvp, f_partial, dyn_args)\ny, jac = vmap(pushfwd, out_axes=(None, -1))(_std_basis(dyn_args))\n+ else:\n+ pushfwd = partial(_jvp, f_partial, dyn_args, has_aux=True)\n+ y, jac, aux = vmap(pushfwd, out_axes=(None, -1, None))(_std_basis(dyn_args))\ntree_map(partial(_check_output_dtype_jacfwd, holomorphic), y)\nexample_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\n- return tree_map(partial(_jacfwd_unravel, example_args), y, jac)\n+ jac_tree = tree_map(partial(_jacfwd_unravel, example_args), y, jac)\n+ if not has_aux:\n+ return jac_tree\n+ else:\n+ return jac_tree, aux\nreturn jacfun\n@@ -1126,13 +1139,16 @@ def _check_output_dtype_jacfwd(holomorphic, x):\nf\"but got {aval.dtype.name}.\")\ndef jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n- holomorphic: bool = False, allow_int: bool = False) -> Callable:\n+ has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False) -> Callable:\n\"\"\"Jacobian of ``fun`` evaluated row-by-row using reverse-mode AD.\nArgs:\nfun: Function whose Jacobian is to be computed.\nargnums: Optional, integer or sequence of integers. Specifies which\npositional argument(s) to differentiate with respect to (default ``0``).\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n+ first element is considered the output of the mathematical function to be\n+ differentiated and the second element is auxiliary data. Default False.\nholomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\nholomorphic. Default False.\nallow_int: Optional, bool. Whether to allow differentiating with\n@@ -1141,7 +1157,8 @@ def jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nReturns:\nA function with the same arguments as ``fun``, that evaluates the Jacobian of\n- ``fun`` using reverse-mode automatic differentiation.\n+ ``fun`` using reverse-mode automatic differentiation. If ``has_aux`` is True\n+ then a pair of (jacobian, auxiliary_data) is returned.\n>>> import jax\n>>> import jax.numpy as jnp\n@@ -1163,13 +1180,20 @@ def jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\nf_partial, dyn_args = argnums_partial(f, argnums, args,\nrequire_static_args_hashable=False)\ntree_map(partial(_check_input_dtype_jacrev, holomorphic, allow_int), dyn_args)\n+ if not has_aux:\ny, pullback = _vjp(f_partial, *dyn_args)\n+ else:\n+ y, pullback, aux = _vjp(f_partial, *dyn_args, has_aux=True)\ntree_map(partial(_check_output_dtype_jacrev, holomorphic), y)\njac = vmap(pullback)(_std_basis(y))\njac = jac[0] if isinstance(argnums, int) else jac\nexample_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\njac_tree = tree_map(partial(_jacrev_unravel, y), example_args, jac)\n- return tree_transpose(tree_structure(example_args), tree_structure(y), jac_tree)\n+ jac_tree = tree_transpose(tree_structure(example_args), tree_structure(y), jac_tree)\n+ if not has_aux:\n+ return jac_tree\n+ else:\n+ return jac_tree, aux\nreturn jacfun\njacobian = jacrev\n@@ -2046,7 +2070,9 @@ def shapecheck(in_shapes, out_shape, fun: Callable):\nmap(tuple, out_shapes), out_tree_thunk())\nreturn fun\n-def jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\n+def jvp(\n+ fun: Callable, primals, tangents, has_aux: bool = False\n+) -> Tuple[Any, ...]:\n\"\"\"Computes a (forward-mode) Jacobian-vector product of ``fun``.\nArgs:\n@@ -2060,13 +2086,19 @@ def jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\ntangents: The tangent vector for which the Jacobian-vector product should be\nevaluated. Should be either a tuple or a list of tangents, with the same\ntree structure and array shapes as ``primals``.\n+ has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n+ first element is considered the output of the mathematical function to be\n+ differentiated and the second element is auxiliary data. Default False.\nReturns:\n- A ``(primals_out, tangents_out)`` pair, where ``primals_out`` is\n- ``fun(*primals)``, and ``tangents_out`` is the Jacobian-vector product of\n+ If ``has_aux`` is ``False``, returns a ``(primals_out, tangents_out)`` pair,\n+ where ``primals_out`` is ``fun(*primals)``,\n+ and ``tangents_out`` is the Jacobian-vector product of\n``function`` evaluated at ``primals`` with ``tangents``. The\n``tangents_out`` value has the same Python tree structure and shapes as\n- ``primals_out``.\n+ ``primals_out``. If ``has_aux`` is ``True``, returns a\n+ ``(primals_out, tangents_out, aux)`` tuple where ``aux``\n+ is the auxiliary data returned by ``fun``.\nFor example:\n@@ -2079,9 +2111,9 @@ def jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\n0.19900084\n\"\"\"\n_check_callable(fun)\n- return _jvp(lu.wrap_init(fun), primals, tangents)\n+ return _jvp(lu.wrap_init(fun), primals, tangents, has_aux=has_aux)\n-def _jvp(fun: lu.WrappedFun, primals, tangents):\n+def _jvp(fun: lu.WrappedFun, primals, tangents, has_aux=False):\n\"\"\"Variant of jvp() that takes an lu.WrappedFun.\"\"\"\nif (not isinstance(primals, (tuple, list)) or\nnot isinstance(tangents, (tuple, list))):\n@@ -2106,10 +2138,20 @@ def _jvp(fun: lu.WrappedFun, primals, tangents):\nraise ValueError(\"jvp called with different primal and tangent shapes;\"\nf\"Got primal shape {np.shape(p)} and tangent shape as {np.shape(t)}\")\n+ if not has_aux:\nflat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)\nout_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)\n- return (tree_unflatten(out_tree(), out_primals),\n- tree_unflatten(out_tree(), out_tangents))\n+ out_tree = out_tree()\n+ return (tree_unflatten(out_tree, out_primals),\n+ tree_unflatten(out_tree, out_tangents))\n+ else:\n+ flat_fun, out_aux_trees = flatten_fun_nokwargs2(fun, tree_def)\n+ jvp_fun, aux = ad.jvp(flat_fun, has_aux=True)\n+ out_primals, out_tangents = jvp_fun.call_wrapped(ps_flat, ts_flat)\n+ out_tree, aux_tree = out_aux_trees()\n+ return (tree_unflatten(out_tree, out_primals),\n+ tree_unflatten(out_tree, out_tangents),\n+ tree_unflatten(aux_tree, aux()))\ndef linearize(fun: Callable, *primals) -> Tuple[Any, Callable]:\n\"\"\"Produces a linear approximation to ``fun`` using :py:func:`jvp` and partial eval.\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1230,6 +1230,66 @@ class APITest(jtu.JaxTestCase):\nfor val in aux.values():\nself.assertNotIsInstance(val, core.Tracer)\n+ def test_jacfwd_and_aux_basic(self):\n+ jac, aux = jacfwd(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n+ self.assertAllClose(jac, jacfwd(lambda x: x**3)(3.))\n+ self.assertAllClose(aux, [9.], check_dtypes=False)\n+\n+ def test_jacrev_and_aux_basic(self):\n+ jac, aux = jacrev(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n+ self.assertAllClose(jac, jacrev(lambda x: x**3)(3.))\n+ self.assertAllClose(aux, [9.], check_dtypes=False)\n+\n+ def test_jacfwd_and_aux_nested(self):\n+ def f(x):\n+ jac, aux = jacfwd(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0]\n+\n+ f2 = lambda x: x**3\n+\n+ self.assertEqual(jacfwd(f)(4.), jacfwd(f2)(4.))\n+ self.assertEqual(jit(jacfwd(f))(4.), jacfwd(f2)(4.))\n+ self.assertEqual(jit(jacfwd(jit(f)))(4.), jacfwd(f2)(4.))\n+\n+ def f(x):\n+ jac, aux = jacfwd(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0] * jnp.sin(x)\n+\n+ f2 = lambda x: x**3 * jnp.sin(x)\n+\n+ self.assertEqual(jacfwd(f)(4.), jacfwd(f2)(4.))\n+ self.assertEqual(jit(jacfwd(f))(4.), jacfwd(f2)(4.))\n+ self.assertEqual(jit(jacfwd(jit(f)))(4.), jacfwd(f2)(4.))\n+\n+ def test_jacrev_and_aux_nested(self):\n+ def f(x):\n+ jac, aux = jacrev(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0]\n+\n+ f2 = lambda x: x**3\n+\n+ self.assertEqual(jacrev(f)(4.), jacrev(f2)(4.))\n+ self.assertEqual(jit(jacrev(f))(4.), jacrev(f2)(4.))\n+ self.assertEqual(jit(jacrev(jit(f)))(4.), jacrev(f2)(4.))\n+\n+ def f(x):\n+ jac, aux = jacrev(lambda x: (x**3, [x**3]), has_aux=True)(x)\n+ return aux[0] * jnp.sin(x)\n+\n+ f2 = lambda x: x**3 * jnp.sin(x)\n+\n+ self.assertEqual(jacrev(f)(4.), jacrev(f2)(4.))\n+ self.assertEqual(jit(jacrev(f))(4.), jacrev(f2)(4.))\n+ self.assertEqual(jit(jacrev(jit(f)))(4.), jacrev(f2)(4.))\n+\n+ def test_jvp_and_aux_basic(self):\n+ fun = lambda x: (x**3, [x**2])\n+ primals, tangents, aux = api.jvp(fun, (3.,), (4.,), has_aux=True)\n+ expected_primals, expected_tangents = api.jvp(lambda x: x**3, (3.,), (4.,))\n+ self.assertAllClose(primals, expected_primals, check_dtypes=True)\n+ self.assertAllClose(tangents, expected_tangents, check_dtypes=True)\n+ self.assertEqual(aux, [3.**2])\n+\ndef test_jvp_mismatched_arguments(self):\nself.assertRaisesRegex(\nTypeError,\n" } ]
Python
Apache License 2.0
google/jax
has_aux for jvp and forward-mode AD value_and_grad Changes: - revert value_and_grad_fwd - add has_aux to jacfwd and jacrev - tests fix mypy error
260,578
21.01.2022 14:37:41
28,800
c0212d4079b39468f57a0c06c412e310df9c3b14
Add GDA to the API pages
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/jax.experimental.global_device_array.rst", "diff": "+jax.experimental.global_device_array module\n+============================\n+\n+.. automodule:: jax.experimental.global_device_array\n+\n+API\n+---\n+\n+.. autoclass:: GlobalDeviceArray\n+ :members:\n+.. autoclass:: Shard\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.experimental.rst", "new_path": "docs/jax.experimental.rst", "diff": "@@ -8,6 +8,7 @@ jax.experimental package\n:maxdepth: 1\njax.experimental.ann\n+ jax.experimental.global_device_array\njax.experimental.host_callback\njax.experimental.loops\njax.experimental.maps\n" } ]
Python
Apache License 2.0
google/jax
Add GDA to the API pages
260,411
20.01.2022 14:56:27
-7,200
83b818d45c474515d833b1d2084a7b39f4f00d72
Add more documentation for buffer donation Fixes:
[ { "change_type": "MODIFY", "old_path": "docs/faq.rst", "new_path": "docs/faq.rst", "diff": "@@ -366,6 +366,73 @@ Interestingly, ``jax.grad(divide)(3., 2.)``, works because :func:`jax.grad`\nuses concrete tracers, and resolves the conditional using the concrete\nvalue of ``y``.\n+.. _faq-donation:\n+\n+Buffer donation\n+---------------\n+\n+(This feature is implemented only for TPU and GPU.)\n+\n+When JAX executes a computation it reserves buffers on the device for all inputs and outputs.\n+If you know than one of the inputs is not needed after the computation, and if it\n+matches the shape and element type of one of the outputs, you can specify that you\n+want the corresponding input buffer to be donated to hold an output. This will reduce\n+the memory required for the execution by the size of the donated buffer.\n+\n+You achieve this by using the `donate_argnums` parameter to the functions :func:`jax.jit`,\n+:func:`jax.pjit`, and :func:`jax.pmap`. This parameter is a sequence of indices (0 based) into\n+the positional argument list::\n+\n+ def add(x, y):\n+ return x + y\n+\n+ x = jax.device_put(np.ones((2, 3)))\n+ y = jax.device_put(np.ones((2, 3)))\n+ # Execute `add` with donation of the buffer for `y`. The result has\n+ # the same shape and type as `y`, so it will share its buffer.\n+ z = jax.jit(add, donate_argnums=(1,))(x, y)\n+\n+If an argument whose buffer is donated is a pytree, then all the buffers\n+for its components are donated::\n+\n+ def add_ones(xs: List[Array]):\n+ return [x + 1 for x in xs]\n+\n+ xs = [jax.device_put(np.ones((2, 3)), jax.device_put(np.ones((3, 4))]\n+ # Execute `add_ones` with donation of all the buffers for `xs`.\n+ # The outputs have the same shape and type as the elements of `xs`,\n+ # so they will share those buffers.\n+ z = jax.jit(add_ones, donate_argnums=0)(xs)\n+\n+It is not allowed to donate a buffer that is used subsequently in the computation,\n+and JAX will give an error because the buffer for `y` has become invalid\n+after it was donated::\n+\n+ # Donate the buffer for `y`\n+ z = jax.jit(add, donate_argnums=(1,))(x, y)\n+ w = y + 1 # Reuses `y` whose buffer was donated above\n+ # >> RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer\n+\n+You will get a warning if the donated buffer is not used, e.g., because\n+there are more donated buffers than can be used for the outputs::\n+\n+ # Execute `add` with donation of the buffers for both `x` and `y`.\n+ # One of those buffers will be used for the result, but the other will\n+ # not be used.\n+ z = jax.jit(add, donate_argnums=(0, 1))(x, y)\n+ # >> UserWarning: Some donated buffers were not usable: f32[2,3]{1,0}\n+\n+The donation may also be unused if there is no output whose shape matches\n+the donation::\n+\n+ y = jax.device_put(np.ones((1, 3))) # `y` has different shape than the output\n+ # Execute `add` with donation of the buffer for `y`.\n+ z = jax.jit(add, donate_argnums=(1,))(x, y)\n+ # >> UserWarning: Some donated buffers were not usable: f32[1,3]{1,0}\n+\n+Buffer donation is implemented for GPU and TPU. You will get the above warning\n+anytime you try to use donation on CPU.\n+\nGradients contain `NaN` where using ``where``\n------------------------------------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -277,13 +277,16 @@ def jit(\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or\n``'tpu'``.\n- donate_argnums: Specify which arguments are \"donated\" to the computation.\n- It is safe to donate arguments if you no longer need them once the\n+ donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n+ It is safe to donate argument buffers if you no longer need them once the\ncomputation has finished. In some cases XLA can make use of donated\nbuffers to reduce the amount of memory needed to perform a computation,\nfor example recycling one of your input buffers to store a result. You\nshould not reuse buffers that you donate to a computation, JAX will raise\n- an error if you try to. By default, no arguments are donated.\n+ an error if you try to. By default, no argument buffers are donated.\n+\n+ For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+\ninline: Specify whether this function should be inlined into enclosing\njaxprs (rather than being represented as an application of the xla_call\nprimitive with its own subjaxpr). Default False.\n@@ -1701,13 +1704,16 @@ def pmap(\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend. 'cpu', 'gpu', or 'tpu'.\naxis_size: Optional; the size of the mapped axis.\n- donate_argnums: Specify which arguments are \"donated\" to the computation.\n- It is safe to donate arguments if you no longer need them once the\n+ donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n+ It is safe to donate argument buffers if you no longer need them once the\ncomputation has finished. In some cases XLA can make use of donated\nbuffers to reduce the amount of memory needed to perform a computation,\nfor example recycling one of your input buffers to store a result. You\nshould not reuse buffers that you donate to a computation, JAX will raise\nan error if you try to.\n+\n+ For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+\nglobal_arg_shapes: Optional, must be set when using pmap(sharded_jit) and\nthe partitioned values span multiple processes. The global cross-process\nper-replica shape of each argument, i.e. does not include the leading\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -454,6 +454,16 @@ def xmap(fun: Callable,\n:py:func:`xmap` to one or more resource axes. Any array that has in its\nshape an axis with some resources assigned will be partitioned over the\nresources associated with the respective resource axes.\n+ donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n+ It is safe to donate argument buffers if you no longer need them once the\n+ computation has finished. In some cases XLA can make use of donated\n+ buffers to reduce the amount of memory needed to perform a computation,\n+ for example recycling one of your input buffers to store a result. You\n+ should not reuse buffers that you donate to a computation, JAX will raise\n+ an error if you try to.\n+\n+ For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\n+\nbackend: This is an experimental feature and the API is likely to change.\nOptional, a string representing the XLA backend. 'cpu', 'gpu', or 'tpu'.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -150,14 +150,15 @@ def pjit(fun: Callable,\nstatic.\nIf ``static_argnums`` is not provided, no arguments are treated as static.\n- donate_argnums: Specify which arguments are \"donated\" to the computation.\n- It is safe to donate arguments if you no longer need them once the\n+ donate_argnums: Specify which argument buffers are \"donated\" to the computation.\n+ It is safe to donate argument buffers if you no longer need them once the\ncomputation has finished. In some cases XLA can make use of donated\nbuffers to reduce the amount of memory needed to perform a computation,\nfor example recycling one of your input buffers to store a result. You\nshould not reuse buffers that you donate to a computation, JAX will raise\nan error if you try to.\n+ For more details on buffer donation see the [FAQ](https://jax.readthedocs.io/en/latest/faq.html#buffer-donation).\nReturns:\nA wrapped version of ``fun``, set up for just-in-time compilation and\nautomaticly partitioned by the mesh available at each call site.\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -382,15 +382,18 @@ def lower_jaxpr_to_module(\nHandles the quirks of the argument/return value passing conventions of the\nruntime.\"\"\"\ninput_output_aliases = None\n- if platform in (\"gpu\", \"tpu\"):\n+ platforms_with_donation = (\"gpu\", \"tpu\")\n+ if platform in platforms_with_donation:\ninput_output_aliases, donated_args = _set_up_aliases(\njaxpr.in_avals, jaxpr.out_avals, donated_args)\nif any(donated_args):\n# TODO(tomhennigan): At call time we should mark these buffers as deleted.\nunused_donations = [str(a) for a, d in zip(jaxpr.in_avals, donated_args)\nif d]\n- warnings.warn(\"Some donated buffers were not usable: {}\".format(\n- \", \".join(unused_donations)))\n+ msg = \"See an explanation at https://jax.readthedocs.io/en/latest/notebooks/faq.html#buffer-donation.\"\n+ if platform not in platforms_with_donation:\n+ msg = f\"Donation is not implemented for {platform}.\\n{msg}\"\n+ warnings.warn(f\"Some donated buffers were not usable: {', '.join(unused_donations)}.\\n{msg}\")\nctx = ModuleContext(platform, axis_env, name_stack)\nwith ctx.context, ir.Location.unknown(ctx.context):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -789,15 +789,18 @@ def lower_jaxpr_to_xla_module(\nelse:\noutput = with_sharding(c, out_partitions, build_out_tuple)\n- if platform in (\"gpu\", \"tpu\"):\n+ platforms_with_donation = (\"gpu\", \"tpu\")\n+ if platform in platforms_with_donation:\ndonated_invars = set_up_aliases(\nc, xla_args, c.GetShape(output), donated_invars, tuple_args)\nif any(donated_invars):\n# TODO(tomhennigan): At call time we should mark these buffers as deleted.\nunused_donations = [str(c.GetShape(a))\nfor a, d in zip(xla_args, donated_invars) if d]\n- warnings.warn(\"Some donated buffers were not usable: {}\".format(\n- \", \".join(unused_donations)))\n+ msg = \"See an explanation at https://jax.readthedocs.io/en/latest/notebooks/faq.html#buffer-donation.\"\n+ if platform not in platforms_with_donation:\n+ msg = f\"Donation is not implemented for {platform}.\\n{msg}\"\n+ warnings.warn(f\"Some donated buffers were not usable: {', '.join(unused_donations)}.\\n{msg}\")\nreturn c.build(output)\n" } ]
Python
Apache License 2.0
google/jax
Add more documentation for buffer donation Fixes: #9237
260,411
20.01.2022 13:25:35
-7,200
34ba42b5daaf4e1ed5c2d4793ea5d866a342b957
[jax2tf] Improve shape polymorphism for scatter with CLIP mode Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -701,7 +701,7 @@ def broadcast_in_dim(operand: Array, shape: Shape,\nArgs:\noperand: an array\nshape: the shape of the target array\n- broadcast_dimensions: which dimension in the target shape each dimension\n+ broadcast_dimensions: to which dimension in the target shape each dimension\nof the operand shape corresponds to\nReturns:\n@@ -2934,7 +2934,7 @@ mlir.register_lowering(squeeze_p, _squeeze_lower)\n-def _shape_as_value(shape):\n+def _shape_as_value(shape: core.Shape):\n\"\"\"Converts a shape that may contain Poly values into a JAX value.\"\"\"\nif len(shape) == 0:\nreturn full((0,), np.array(0, np.int64))\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/slicing.py", "new_path": "jax/_src/lax/slicing.py", "diff": "@@ -1415,7 +1415,7 @@ def _scatter_shape_rule(operand, indices, updates, *, update_jaxpr,\nfor i in update_scatter_dims:\nif scatter_dims_seen == index_vector_dim:\nscatter_dims_seen += 1\n- if updates.shape[i] != expanded_indices_shape[scatter_dims_seen]:\n+ if not core.symbolic_equal_dim(updates.shape[i], expanded_indices_shape[scatter_dims_seen]):\nraise TypeError(f\"Bounds of the scatter dimensions of updates must be \"\nf\"the same as the bounds of the corresponding dimensions \"\nf\"of scatter indices. For scatter dimension {i}, updates \"\n@@ -1437,10 +1437,11 @@ def _clamp_scatter_indices(operand, indices, updates, *, dnums):\nslice_sizes.append(updates.shape[dnums.update_window_dims[pos]])\npos += 1\n- upper_bound = np.array([operand.shape[i] - slice_sizes[i]\n- for i in dnums.scatter_dims_to_operand_dims],\n- np.int64)\n- upper_bound = np.minimum(upper_bound, np.iinfo(indices.dtype).max)\n+ upper_bounds: core.Shape = tuple(operand.shape[i] - slice_sizes[i]\n+ for i in dnums.scatter_dims_to_operand_dims)\n+ # Stack upper_bounds into a DeviceArray[n]\n+ upper_bound = lax._shape_as_value(upper_bounds)\n+ upper_bound = lax.min(upper_bound, np.iinfo(indices.dtype).max)\nupper_bound = lax.broadcast_in_dim(upper_bound, indices.shape,\n(len(indices.shape) - 1,))\nreturn lax.clamp(np.int64(0), lax.convert_element_type(indices, np.int64),\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": "@@ -1554,17 +1554,24 @@ _POLY_SHAPE_TEST_HARNESSES = [\n_make_harness(\"scatter_add\", \"\",\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True),\n[RandArg((7, 4), _f32),\n- np.array([[1], [2]], np.int32), # indices\n- RandArg((7, 2), _f32), # updates\n+ np.array([[1], [2]], np.int32), # indices: [2, 1]\n+ RandArg((7, 2), _f32), # updates: [7, 2]\nStaticArg(lax.ScatterDimensionNumbers((0,), (1,), (1,)))],\npoly_axes=[0, None, 0]),\n- _make_harness(\"scatter_add\", \"clip\",\n+ _make_harness(\"scatter_add\", \"clip0\",\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True, mode=lax.GatherScatterMode.CLIP),\n- [RandArg((7, 4), _f32),\n- np.array([[1], [2]], np.int32), # indices\n- RandArg((7, 2), _f32), # updates\n+ [RandArg((7, 4), _f32), # [b, 4]\n+ np.array([[1], [2]], np.int32), # indices: [2, 1]\n+ RandArg((7, 2), _f32), # updates: [b, 2]\nStaticArg(lax.ScatterDimensionNumbers((0,), (1,), (1,)))],\npoly_axes=[0, None, 0]),\n+ _make_harness(\"scatter_add\", \"clip1\",\n+ partial(lax.scatter_add, indices_are_sorted=False, unique_indices=True, mode=lax.GatherScatterMode.CLIP),\n+ [RandArg((7, 4), _f32), # [b, 4]\n+ np.array([[1, 2], [-2, 0], [6, 4], [7, -1], [1, 0], [3, 0], [0, 5]], np.int32), # indices: [b, 2]\n+ RandArg((7, 1), _f32), # updates: [b, 1]\n+ StaticArg(lax.ScatterDimensionNumbers((1,), (0,), (0, 1,)))],\n+ poly_axes=[0, 0, 0]),\n_make_harness(\"select\", \"0\",\n# x.shape = (b, 3)\nlambda x: lax.select(x > 5., x, x),\n@@ -1701,9 +1708,6 @@ def _add_vmap_primitive_harnesses():\n\"lu\",\n\"custom_linear_solve\",\n- # Broken by https://github.com/google/jax/pull/9094\n- \"dynamic_update_slice\",\n-\n# We do *= shapes in the batching rule for conv_general_dilated\n\"conv_general_dilated\",\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Improve shape polymorphism for scatter with CLIP mode Fixes: #9231
260,411
24.01.2022 10:06:22
-3,600
cb3fadce29fa7d3075547f1b5ab8b2249f7d8cd4
[jax2tf] Move the no_xla_limitations documentation Put it in the g3doc directory, along with the other pieces of jax2tf documentation. This enables special documentation features in the Google repo.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -851,29 +851,12 @@ There are several drawbacks of using XLA TF ops:\n* These ops will only be executable by a consumer that has XLA linked in.\nThis should not be a problem for TPU execution, since that requires XLA anyway.\n- But for other platforms (CPU, GPU, embedded) this can be a drawback in certain settings.\n* These ops are not yet recognized by tools that process\n- tf.Graph, e.g., TensorFlow.js converter.\n-\n-We use the following XLA TF ops:\n-\n- * `XlaPad` (wraps XLA Pad operator). We use this instead of `tf.pad` in order to\n- support `lax.pad` interior padding (dilation) or negative edge padding.\n- * `XlaConv2` (wraps XLA ConvGeneralDilated operator).\n- * `XlaDotV2` (wraps XLA DotGeneral operator).\n- * `XlaGather` (wraps XLA Gather operator). We could use `tf.gather` in some\n- cases but not always. Also, `tf.gather` has a different semantics than `lax.gather`\n- for index out of bounds.\n- * `XlaScatter` (wraps XLA Scatter operator).\n- * `XlaSelectAndScatter` (wraps XLA SelectAndScatter operator).\n- * `XlaDynamicSlice` (wraps XLA DynamicSlice operator).\n- We use this instead of `tf.slice` for reasons explained above for `XlaGather`.\n- * `XlaDynamicUpdateSlice` (wraps XLA DynamicUpdateSlice operator).\n- * `XlaReduceWindow` (wraps XLA ReduceWindow operator). These are used\n- for `lax.reduce_window_sum_p`, `lax.reduce_window_min_p`,\n- `lax.reduce_window_max_p`, and `lax.reduce_window_p`.\n- * `XlaVariadicReduceV2` (for `lax.reduce`, `lax.argmin`, `lax.argmax`).\n- * `XlaVariadicSort` (wraps XLA Sort operator).\n+ tf.Graph, e.g., TensorFlow.js converter or the TensorFlow Lite converter.\n+\n+As an experimental feature we implemented alternative conversions to avoid the XLA TF ops.\n+You can enable this with the `enable_xla=False` parameter to `jax2tf.convert`.\n+For more details see [no_xla_limitations.md](g3doc/no_xla_limitations.md).\n### Different performance characteristics\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/converters_eval/README.md", "new_path": "jax/experimental/jax2tf/converters_eval/README.md", "diff": "@@ -32,7 +32,7 @@ cannot use a number of JAX ops directly, because they don't have a corresponding\nop in TF. For this, we provide support on a case-by-case basis.\nTo track this, we use a list of known limitations of the `jax2tf` emitter when\n-XLA support is not available in [no_xla_limitations.md](no_xla_limitations.md).\n+XLA support is not available in [no_xla_limitations.md](../g3doc/no_xla_limitations.md).\n## Description of Converters\n@@ -50,7 +50,7 @@ for a list of known problems.\n### `jax2tf_to_tflite`\nThis converter first converts a JAX model to TF SavedModel format without XLA\n-support. Please see [no_xla_limitations.md](no_xla_limitations.md) for a list\n+support. Please see [no_xla_limitations.md](../g3doc/no_xla_limitations.md) for a list\nof known limitations for this conversion step.\nAfter that, it converts the SavedModel to TFLite using the\n@@ -59,7 +59,7 @@ After that, it converts the SavedModel to TFLite using the\n### `jax2tf_to_tfjs`\nThis converter first converts a JAX model to TF SavedModel format without XLA\n-support. Please see [no_xla_limitations.md](no_xla_limitations.md) for a list\n+support. Please see [no_xla_limitations.md](../g3doc/no_xla_limitations.md) for a list\nof known limitations for this conversion step.\nAfter that, it converts the SavedModel to TF.js using the\n" }, { "change_type": "RENAME", "old_path": "jax/experimental/jax2tf/converters_eval/no_xla_limitations.md", "new_path": "jax/experimental/jax2tf/g3doc/no_xla_limitations.md", "diff": "@@ -36,7 +36,7 @@ For a detailed description of these XLA ops, please see the\n| XlaScatter | `lax.scatter_p`, `lax.scatter_min_p`, `lax.scatter_max_p`, `lax.scatter_mul_p`, `lax.scatter_add_p` | Unsupported |\n| XlaSelectAndScatter | `lax.select_and_scatter_add_p` | Unsupported |\n| XlaReduce | `lax.reduce`, `lax.argmin`, `lax.argmax` | Unsupported |\n-| XlaSort | `lax.sort` | Unsupported |\n+| XlaVariadicSort | `lax.sort` | Unsupported |\n## Partially Supported JAX Primitives\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Move the no_xla_limitations documentation Put it in the g3doc directory, along with the other pieces of jax2tf documentation. This enables special documentation features in the Google repo.
260,586
25.01.2022 09:54:23
0
70bf2812505505e68f528e7e4f446935673c22eb
Fix `max_squarings` in `expm`
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -275,7 +275,7 @@ def expm(A, *, upper_triangular=False, max_squarings=16):\ndef _compute(args):\nA, P, Q = args\nR = _solve_P_Q(P, Q, upper_triangular)\n- R = _squaring(R, n_squarings)\n+ R = _squaring(R, n_squarings, max_squarings)\nreturn R\nR = lax.cond(n_squarings > max_squarings, _nan, _compute, (A, P, Q))\n@@ -318,8 +318,8 @@ def _solve_P_Q(P, Q, upper_triangular=False):\ndef _precise_dot(A, B):\nreturn jnp.dot(A, B, precision=lax.Precision.HIGHEST)\n-@jit\n-def _squaring(R, n_squarings):\n+@partial(jit, static_argnums=2)\n+def _squaring(R, n_squarings, max_squarings):\n# squaring step to undo scaling\ndef _squaring_precise(x):\nreturn _precise_dot(x, x)\n@@ -329,7 +329,7 @@ def _squaring(R, n_squarings):\ndef _scan_f(c, i):\nreturn lax.cond(i < n_squarings, _squaring_precise, _identity, c), None\n- res, _ = lax.scan(_scan_f, R, jnp.arange(16))\n+ res, _ = lax.scan(_scan_f, R, jnp.arange(max_squarings))\nreturn res\n" } ]
Python
Apache License 2.0
google/jax
Fix `max_squarings` in `expm`
260,314
25.01.2022 12:20:55
18,000
3afe67367df36b73053371c0429923eb549bc793
NamedShape matches tuple behavior
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1639,13 +1639,11 @@ class NamedShape:\nf\"{', '.join(f'{k}={v}' for k, v in self.__named.items())})\")\ndef __eq__(self, other):\n- if other is None:\n- return False\nif isinstance(other, NamedShape):\nreturn (self.__positional, self.__named) == (other.__positional, other.__named)\nif isinstance(other, tuple):\nreturn not self.__named and self.__positional == other\n- raise TypeError(f\"NamedShape doesn't support comparisons with {type(other)}\")\n+ return False\ndef __hash__(self):\nnamed = frozenset(self.__named.items())\n" }, { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -515,6 +515,13 @@ class JaxprTypeChecks(jtu.JaxTestCase):\naval3 = core.ShapedArray((2, 3), np.float32, False, {'i': 5})\nself.assertFalse(core.typecompat(aval1, aval3))\n+ def test_named_shape_comparision(self):\n+ self.assertTrue(core.NamedShape(2, 3) == (2, 3))\n+ self.assertFalse(core.NamedShape(2, i=3) == (2,))\n+ self.assertFalse(core.NamedShape(2, i=3) == (2, 3))\n+ self.assertFalse(core.NamedShape(2, i=3) == None)\n+ self.assertFalse(core.NamedShape() == [])\n+\nclass DynamicShapesTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
NamedShape matches tuple behavior
260,335
25.01.2022 15:27:29
28,800
98816f3ffa70d85655636f417ad1df2f4b3aedae
jaxpr staging: only one tracer per jaxpr variable
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1193,20 +1193,29 @@ class DynamicJaxprTracer(core.Tracer):\nif not self._trace.main.jaxpr_stack: # type: ignore\nraise core.escaped_tracer_error(self, None)\n+TracerId = int\n+ConstId = int\nclass JaxprStackFrame:\n- __slots__ = ['gensym', 'tracer_to_var', 'constid_to_var', 'constvar_to_val',\n- 'tracers', 'eqns', 'invars']\n+ gensym: Callable[[AbstractValue], Var]\n+ tracer_to_var: Dict[TracerId, Var]\n+ constid_to_tracer: Dict[ConstId, Tracer]\n+ constvar_to_val: Dict[Var, Any]\n+ tracers: List[DynamicJaxprTracer] # hold onto strong refs for all tracers\n+ eqns: List[JaxprEqn]\n+ invars: List[Var]\ndef __init__(self):\nself.gensym = core.gensym()\nself.tracer_to_var = {}\n- self.constid_to_var = {}\n+ self.constid_to_tracer = {}\nself.constvar_to_val = {}\nself.tracers = [] # circ refs, frame->tracer->trace->main->frame,\nself.eqns = [] # cleared when we pop frame from main\nself.invars = []\ndef to_jaxpr(self, out_tracers):\n+ # It's not necessary, but we keep the tracer-to-var mapping injective:\n+ assert len(self.tracer_to_var) == len(set(self.tracer_to_var.values()))\noutvars = [self.tracer_to_var[id(t)] for t in out_tracers]\nconstvars, constvals = unzip2(self.constvar_to_val.items())\njaxpr = Jaxpr(constvars, self.invars, outvars, self.eqns)\n@@ -1322,12 +1331,15 @@ class DynamicJaxprTrace(core.Trace):\nself.frame.invars.append(var)\nreturn tracer\n- def new_const(self, val):\n- aval = raise_to_shaped(get_aval(val), weak_type=dtypes.is_weakly_typed(val))\n+ def new_const(self, c):\n+ tracer = self.frame.constid_to_tracer.get(id(c))\n+ if tracer is None:\n+ aval = raise_to_shaped(get_aval(c), weak_type=dtypes.is_weakly_typed(c))\ntracer = DynamicJaxprTracer(self, aval, source_info_util.current())\nself.frame.tracers.append(tracer)\n- var = self.frame.tracer_to_var[id(tracer)] = self.getconstvar(aval, val)\n- self.frame.constvar_to_val[var] = val\n+ self.frame.tracer_to_var[id(tracer)] = var = self.frame.newvar(aval)\n+ self.frame.constid_to_tracer[id(c)] = tracer\n+ self.frame.constvar_to_val[var] = c\nreturn tracer\npure = lift = sublift = new_const\n@@ -1345,12 +1357,6 @@ class DynamicJaxprTrace(core.Trace):\nvar = self.frame.tracer_to_var[id(tracer)] = self.frame.newvar(tracer.aval)\nreturn var\n- def getconstvar(self, aval, c):\n- var = self.frame.constid_to_var.get(id(c))\n- if var is None:\n- var = self.frame.constid_to_var[id(c)] = self.frame.newvar(aval)\n- return var\n-\ndef instantiate_const(self, val):\nif (isinstance(val, Tracer) and val._trace.main is self.main\nand val._trace.sublevel == self.sublevel):\n@@ -1648,7 +1654,6 @@ def partial_eval_to_jaxpr_dynamic(fun: lu.WrappedFun, in_pvals: Sequence[Partial\nAvalId = int\n-TracerId = int\ndef _avals_to_tracers(\ntrace: DynamicJaxprTrace, in_avals: Sequence[AbstractValue]\n) -> Sequence[Tracer]:\n" } ]
Python
Apache License 2.0
google/jax
jaxpr staging: only one tracer per jaxpr variable
260,447
31.01.2022 11:01:58
28,800
97d55eb13c1c03ba6e2714d52e37b8c45bee9162
[JAX] Re-enables lowering bcoo dot general to cuSparse.
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -663,3 +663,10 @@ enable_mlir = config.define_bool_state(\ndefault=lib.mlir_api_version >= 1,\nhelp=('Enables an experimental code path that compiles JAX programs via '\n'emitting the MLIR MHLO dialect.'))\n+\n+# This flag is temporary and for internal use.\n+# TODO(tianjianlu): Removes after providing the information in BCOO meta data.\n+bcoo_cusparse_lowering = config.define_bool_state(\n+ name='jax_bcoo_cusparse_lowering',\n+ default=False,\n+ help=('Enables lowering BCOO ops to cuSparse.'))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -24,8 +24,9 @@ from jax import core\nfrom jax import lax\nfrom jax import tree_util\nfrom jax import vmap\n+from jax.config import config\nfrom jax.experimental.sparse._base import JAXSparse\n-from jax.experimental.sparse.util import _safe_asarray\n+from jax.experimental.sparse.util import _safe_asarray, CuSparseEfficiencyWarning\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\n@@ -37,8 +38,12 @@ from jax._src.api_util import flatten_axes\nfrom jax._src.lax.lax import (\nranges_like, remaining, _dot_general_batch_dim_nums, _dot_general_shape_rule,\nDotDimensionNumbers)\n+from jax._src.lib import cusparse\n+from jax._src.lib import xla_client as xc\nfrom jax._src.numpy.lax_numpy import _unique\n+xops = xc._xla.ops\n+\nDtype = Any\nShape = Tuple[int, ...]\n@@ -646,6 +651,116 @@ def _bcoo_dot_general_abstract_eval(lhs_data, lhs_indices, rhs, *, dimension_num\nreturn core.ShapedArray(out_shape, lhs_data.dtype)\n+_bcoo_dot_general_default_translation_rule = xla.lower_fun(\n+ _bcoo_dot_general_impl, multiple_results=False, new_style=True)\n+\n+def _bcoo_dot_general_cuda_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n+ lhs_spinfo: BCOOInfo):\n+\n+ c = ctx.builder\n+\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n+ props = _validate_bcoo_indices(lhs_indices_aval, lhs_spinfo.shape)\n+ rhs_ndim = len(c.get_shape(rhs).dimensions())\n+\n+ # Checks the shapes of lhs and rhs.\n+ assert 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+\n+ # Checks the operation dimensions.\n+ assert len(lhs_batch) == 0\n+ assert len(rhs_batch) == 0\n+ assert len(lhs_contract) == 1\n+\n+ # Checks the dtype.\n+ assert lhs_data_aval.dtype in [np.float32, np.float64, np.complex64, np.complex128]\n+ assert lhs_data_aval.dtype == rhs_aval.dtype\n+ assert lhs_indices_aval.dtype == np.int32\n+\n+ if rhs_ndim == 1:\n+ bcoo_dot_general_fn = cusparse.coo_matvec\n+ elif rhs_ndim == 2:\n+ bcoo_dot_general_fn = cusparse.coo_matmat\n+ if rhs_contract[0] == 1:\n+ rhs = xops.Transpose(rhs, permutation=[1, 0])\n+ else:\n+ raise ValueError(f\"rhs has to be 1d or 2d; get {rhs_ndim}d.\")\n+\n+ lhs_transpose = False\n+ if props.n_sparse == 1:\n+ # Converts lhs to a row vector.\n+ col = xops.Collapse(lhs_indices, dimensions=[0, 1])\n+ row = xops.Broadcast(xops.Constant(c, jnp.array(0, dtype=jnp.int32)),\n+ c.get_shape(col).dimensions())\n+ lhs_shape = (1, lhs_spinfo.shape[0])\n+ dot_product = bcoo_dot_general_fn(\n+ c, lhs_data, row, col, rhs, shape=lhs_shape, transpose=lhs_transpose)\n+\n+ if rhs_ndim == 1:\n+ # Transforms a single-element array to a scalar.\n+ return [xops.Reshape(dot_product, dimensions=[0], new_sizes=[])]\n+ else:\n+ return [xops.Collapse(dot_product, dimensions=[0, 1])]\n+ elif props.n_sparse == 2:\n+ row = xops.Collapse(\n+ xops.Slice(lhs_indices,\n+ start_indices=[0, 0],\n+ limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 1],\n+ strides=[1, 1]),\n+ dimensions=[0, 1])\n+ col = xops.Collapse(\n+ xops.Slice(lhs_indices,\n+ start_indices=[0, 1],\n+ limit_indices=[c.get_shape(lhs_indices).dimensions()[0], 2],\n+ strides=[1, 1]),\n+ dimensions=[0, 1])\n+\n+ if lhs_contract[0] == 0:\n+ lhs_transpose = True\n+\n+ return [bcoo_dot_general_fn(\n+ c, lhs_data, row, col, rhs, shape=lhs_spinfo.shape,\n+ transpose=lhs_transpose)]\n+ else:\n+ raise ValueError(f\"lhs has to be 1d or 2d; get {props.n_sparse}d.\")\n+\n+def _bcoo_dot_general_gpu_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\n+ lhs_spinfo: BCOOInfo):\n+\n+ (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n+ lhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\n+ n_batch, n_sparse, n_dense, nse = _validate_bcoo(\n+ lhs_data_aval, lhs_indices_aval, lhs_spinfo.shape)\n+\n+ dtype = lhs_data_aval.dtype\n+ if dtype not in [np.float32, np.float64, np.complex64, np.complex128]:\n+ warnings.warn(f'bcoo_dot_general cusparse lowering not available for '\n+ f'dtype={dtype}. Falling back to default implementation.',\n+ CuSparseEfficiencyWarning)\n+ return _bcoo_dot_general_default_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+\n+ if (n_batch or n_dense or\n+ n_sparse not in [1, 2] or rhs_aval.ndim not in [1, 2] or\n+ lhs_batch or rhs_batch or len(lhs_contract) != 1):\n+ return _bcoo_dot_general_default_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+ else:\n+ # The lhs indices are row-wise sorted.\n+ lhs_indices_row, lhs_indices_col, lhs_data = lax.sort(\n+ [lhs_indices[:, 0], lhs_indices[:, 1], lhs_data])\n+ lhs_indices = jnp.hstack((lhs_indices_row, lhs_indices_col))\n+ return _bcoo_dot_general_cuda_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+\ndef _bcoo_dot_general_jvp_lhs(lhs_data_dot, lhs_data, lhs_indices, rhs, *, dimension_numbers, lhs_spinfo: BCOOInfo):\nreturn bcoo_dot_general(lhs_data_dot, lhs_indices, rhs, dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n@@ -711,8 +826,13 @@ def _bcoo_dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\nad.defjvp(bcoo_dot_general_p, _bcoo_dot_general_jvp_lhs, None, _bcoo_dot_general_jvp_rhs)\nad.primitive_transposes[bcoo_dot_general_p] = _bcoo_dot_general_transpose\nbatching.primitive_batchers[bcoo_dot_general_p] = _bcoo_dot_general_batch_rule\n-xla.register_translation(bcoo_dot_general_p, xla.lower_fun(\n- _bcoo_dot_general_impl, multiple_results=False, new_style=True))\n+\n+xla.register_translation(\n+ bcoo_dot_general_p, _bcoo_dot_general_default_translation_rule)\n+if config.jax_bcoo_cusparse_lowering and cusparse and cusparse.is_supported:\n+ xla.register_translation(bcoo_dot_general_p,\n+ _bcoo_dot_general_gpu_translation_rule,\n+ platform='gpu')\n#----------------------------------------------------------------------\n# bcoo_dot_general_sampled\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -831,6 +831,103 @@ class BCOOTest(jtu.JaxTestCase):\n# TODO(jakevdp): In rare cases, this fails python_should_be_executing check. Why?\n# self._CompileAndCheck(f_sparse, args_maker)\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ \"_lhs_shape={}_rhs_shape={}_lhs_contracting={}_rhs_contracting={}\"\n+ .format(jtu.format_shape_dtype_string(lhs_shape, dtype),\n+ jtu.format_shape_dtype_string(rhs_shape, dtype),\n+ lhs_contracting, rhs_contracting),\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"dtype\": dtype,\n+ \"lhs_contracting\": lhs_contracting, \"rhs_contracting\": rhs_contracting}\n+ for lhs_shape, rhs_shape, lhs_contracting, rhs_contracting in [\n+ [(5,), (5,), [0], [0]],\n+ [(5,), (5, 7), [0], [0]],\n+ [(5,), (7, 5), [0], [1]],\n+ [(5, 7), (5,), [0], [0]],\n+ [(7, 5), (5,), [1], [0]],\n+ [(3, 5), (2, 5), [1], [1]],\n+ [(3, 5), (5, 2), [1], [0]],\n+ [(5, 3), (2, 5), [0], [1]],\n+ [(5, 3), (5, 2), [0], [0]],\n+ ]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.complex))\n+ def test_bcoo_dot_general_cusparse(\n+ self, lhs_shape, rhs_shape, dtype, lhs_contracting, 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+ data, indices = sparse.bcoo_fromdense(lhs, index_dtype=jnp.int32)\n+ return data, indices, lhs, rhs\n+ dimension_numbers = ((lhs_contracting, rhs_contracting), ([], []))\n+\n+ def f_dense(data, indices, lhs, rhs):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n+\n+ def f_sparse(data, indices, lhs, rhs):\n+ return sparse.bcoo_dot_general(data, indices, rhs,\n+ dimension_numbers=dimension_numbers,\n+ lhs_spinfo=BCOOInfo(lhs.shape))\n+\n+ self._CompileAndCheck(f_sparse, args_maker)\n+ self._CheckAgainstNumpy(f_dense, f_sparse, args_maker)\n+\n+ @unittest.skipIf(jtu.device_under_test() != \"gpu\", \"test requires GPU\")\n+ def test_bcoo_dot_general_oob_and_unsorted_indices_cusparse(self):\n+ \"\"\"Tests bcoo dot general with out-of-bound and unsorted indices.\"\"\"\n+\n+ rhs = jnp.ones((5, 3), dtype=jnp.float32)\n+\n+ # It creates out-of-bound indices when nse > nnz.\n+ lhs_2d_dense = jnp.array([[1, 0, 2, 3, 0], [0, 0, 0, 4, 0]],\n+ dtype=jnp.float32)\n+ lhs_2d_sparse, lhs_sparse_2d_indicdes = sparse.bcoo_fromdense(\n+ lhs_2d_dense, nse=7)\n+\n+ def create_unsorted_indices(data, indices):\n+ data_to_shuffle = jnp.hstack((jnp.expand_dims(data, axis=1), indices))\n+ key = jax.random.PRNGKey(1701)\n+ data_after_shuffle = jax.random.permutation(key, data_to_shuffle)\n+ return (data_after_shuffle[:, 0],\n+ data_after_shuffle[:, 1:].astype(dtype=jnp.int32))\n+\n+ # Random permutate the indices to make them unsorted.\n+ lhs_2d_sparse, lhs_sparse_2d_indicdes = create_unsorted_indices(\n+ lhs_2d_sparse, lhs_sparse_2d_indicdes)\n+\n+ dimension_numbers = (([1], [0]), ([], []))\n+ expected_2d = lax.dot_general(\n+ lhs_2d_dense, rhs, dimension_numbers=dimension_numbers)\n+ actual_2d = sparse.bcoo_dot_general(\n+ lhs_2d_sparse, lhs_sparse_2d_indicdes, rhs,\n+ dimension_numbers=dimension_numbers,\n+ lhs_spinfo=BCOOInfo(lhs_2d_dense.shape))\n+\n+ with self.subTest(msg=\"2D\"):\n+ self.assertAllClose(expected_2d, actual_2d)\n+\n+ # It creates out-of-bound indices when nse > nnz.\n+ lhs_1d_dense = jnp.array([0, 1, 0, 2, 0], dtype=jnp.float32)\n+ lhs_1d_sparse, lhs_sparse_1d_indicdes = sparse.bcoo_fromdense(\n+ lhs_1d_dense, nse=7)\n+\n+ # Random permutate the indices to make them unsorted.\n+ lhs_1d_sparse, lhs_sparse_1d_indicdes = create_unsorted_indices(\n+ lhs_1d_sparse, lhs_sparse_1d_indicdes)\n+\n+ dimension_numbers = (([0], [0]), ([], []))\n+ expected_1d = lax.dot_general(\n+ lhs_1d_dense, rhs, dimension_numbers=dimension_numbers)\n+ actual_1d = sparse.bcoo_dot_general(\n+ lhs_1d_sparse, lhs_sparse_1d_indicdes, rhs,\n+ dimension_numbers=dimension_numbers,\n+ lhs_spinfo=BCOOInfo(lhs_1d_dense.shape))\n+\n+ with self.subTest(msg=\"1D\"):\n+ self.assertAllClose(expected_1d, actual_1d)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": props.testcase_name(), \"props\": props}\nfor props in _generate_bcoo_dot_general_properties(\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Re-enables lowering bcoo dot general to cuSparse. PiperOrigin-RevId: 425410511
260,631
31.01.2022 13:45:26
28,800
c12ca7f64cb4a0338939d84b7dc5c25ccc5b47be
[XLA:TPU] Add 'aggregate_to_topk' option to ann in jax Also adds a pmap test for demonstrating multi-tpu ann.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ann.py", "new_path": "jax/experimental/ann.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"ANN (Approximate Nearest Neighbor) is an **experimental** module for fast top-k with a configurable recall rate on TPU.\n+\"\"\"ANN (Approximate Nearest Neighbor) computes top-k with a configurable recall rate on TPU.\nTPUs are highly efficient on matrix multiplication, which scales up by TPU\ngeneration. Nevertheless, TPUs are surprisingly inefficient in the other\n@@ -44,16 +44,36 @@ Usage::\nfrom jax.experimental import ann\n# Maximum inner product search\n+ # qy shape: [qy_size, feature_dim]\n+ # db shape: [feature_dim, db_size]\nscores, docids = ann.approx_max_k(lax.dot(qy, db), k=10, recall_target=0.95)\n-The current JAX implementation sorts and slice the approximate results M into\n-the final top-k on TPU. We'll also provide a on-host final top-k aggregation\n-for JAX in the future.\n+ # Pmap Maximum inner product search\n+ # qy shape: [qy_size, feature_dim]\n+ # db shape: [num_devices, per_device_db_size, feature_dim]\n+ db_offsets = np.arange(num_devices, dtype=np.int32) * per_device_db_size\n+ def parallel_topk(qy, db, db_offset):\n+ scores = lax.dot_general(qy, db, (([1],[1]),([],[])))\n+ ann_vals, ann_args = ann.approx_max_k(scores, k, recall_target=0.95,\n+ reduction_input_size_override=db_size,\n+ aggregate_to_topk=False)\n+ return (ann_vals, ann_docids + db_offset)\n+ # shape = [qy_size, num_devices, approx_dp]\n+ ann_vals, ann_docids = jax.pmap(\n+ parallel_topk,\n+ in_axes(None, 0, 0), # broadcast qy, shard db and db_offsets\n+ out_axes(1, 1))(qy, db, db_offsets)\n+ # collapse num_devices and approx_dp\n+ ann_vals = lax.collapse(ann_vals, 1, 3)\n+ ann_docids = lax.collapse(ann_docids, 1, 3)\n+ ann_vals, ann_docids = lax.sort_key_val(-ann_vals, ann_docids, dimension=1)\n+ # slice to k\n+ ann_vals = lax.slice_in_dim(ann_vals, start_index=0, limit_index=k, axis=1)\n+ ann_docids = lax.slice_in_dim(ann_docids, start_index=0, limit_index=k, axis=1)\nTodos::\n* On host top-k aggregation\n- * Accurate but slow differentiation\n* Inaccurate but fast differentiation\n\"\"\"\n@@ -71,12 +91,12 @@ from jax.interpreters import ad, xla, batching\nArray = Any\n-def approx_max_k(\n- operand: Array,\n+def approx_max_k(operand: Array,\nk: int,\nreduction_dimension: int = -1,\nrecall_target: float = 0.95,\n- reduction_input_size_override: int = -1) -> Tuple[Array, Array]:\n+ reduction_input_size_override: int = -1,\n+ aggregate_to_topk: bool = True) -> Tuple[Array, Array]:\n\"\"\"Returns max ``k`` values and their indices of the ``operand``.\nArgs:\n@@ -89,25 +109,30 @@ def approx_max_k(\nThis option is useful when the given operand is only a subset of the\noverall computation in SPMD or distributed pipelines, where the true input\nsize cannot be deferred by the operand shape.\n+ aggregate_to_topk: When true, aggregates approximate results to top-k. When\n+ false, returns the approximate results.\nReturns:\nTuple[Array, Array] : Max k values and their indices of the inputs.\n\"\"\"\n+ if xc._version < 45:\n+ aggregate_to_topk = True\nreturn approx_top_k_p.bind(\noperand,\nk=k,\nreduction_dimension=reduction_dimension,\nrecall_target=recall_target,\nis_max_k=True,\n- reduction_input_size_override=reduction_input_size_override)\n+ reduction_input_size_override=reduction_input_size_override,\n+ aggregate_to_topk=aggregate_to_topk)\n-def approx_min_k(\n- operand: Array,\n+def approx_min_k(operand: Array,\nk: int,\nreduction_dimension: int = -1,\nrecall_target: float = 0.95,\n- reduction_input_size_override: int = -1) -> Tuple[Array, Array]:\n+ reduction_input_size_override: int = -1,\n+ aggregate_to_topk: bool = True) -> Tuple[Array, Array]:\n\"\"\"Returns min ``k`` values and their indices of the ``operand``.\nArgs:\n@@ -117,25 +142,31 @@ def approx_min_k(\nrecall_target: Recall target for the approximation.\nreduction_input_size_override : When set to a positive value, it overrides\nthe size determined by operands[reduction_dim] for evaluating the recall.\n- This option is useful when the given operand is only a subset of the overall\n- computation in SPMD or distributed pipelines, where the true input size\n- cannot be deferred by the operand shape.\n+ This option is useful when the given operand is only a subset of the\n+ overall computation in SPMD or distributed pipelines, where the true input\n+ size cannot be deferred by the operand shape.\n+ aggregate_to_topk: When true, aggregates approximate results to top-k. When\n+ false, returns the approximate results.\nReturns:\nTuple[Array, Array] : Least k values and their indices of the inputs.\n\"\"\"\n+ if xc._version < 45:\n+ aggregate_to_topk = True\nreturn approx_top_k_p.bind(\noperand,\nk=k,\nreduction_dimension=reduction_dimension,\nrecall_target=recall_target,\nis_max_k=False,\n- reduction_input_size_override=reduction_input_size_override)\n+ reduction_input_size_override=reduction_input_size_override,\n+ aggregate_to_topk=aggregate_to_topk)\ndef _approx_top_k_abstract_eval(operand, *, k, reduction_dimension,\nrecall_target, is_max_k,\n- reduction_input_size_override):\n+ reduction_input_size_override,\n+ aggregate_to_topk):\nif k <= 0:\nraise ValueError('k must be positive, got {}'.format(k))\nif len(operand.shape) == 0:\n@@ -146,16 +177,11 @@ def _approx_top_k_abstract_eval(operand, *, k, reduction_dimension,\nraise ValueError(\n'k must be smaller than the size of reduction_dim {}, got {}'.format(\ndims[reduction_dimension], k))\n- if xc._version > 42:\n+ if xc._version >= 45:\nreduction_input_size = dims[reduction_dimension]\n- if reduction_input_size_override >= 0:\n- if reduction_input_size < reduction_input_size_override:\n- raise ValueError(\n- 'reduction_input_size_override must be greater equals to operand.shape[reduction_dimension], which is {}'\n- .format(reduction_input_size))\n- reduction_input_size = reduction_input_size_override\ndims[reduction_dimension] = xc.ops.ApproxTopKReductionOutputSize(\n- reduction_input_size, len(dims), k, recall_target, True)[0]\n+ reduction_input_size, len(dims), k, recall_target, aggregate_to_topk,\n+ reduction_input_size_override)[0]\nelse:\ndims[reduction_dimension] = k\nreturn (operand.update(\n@@ -179,7 +205,8 @@ def _comparator_builder(operand, op_type, is_max_k):\ndef _approx_top_k_tpu_translation(ctx, avals_in, avals_out, operand, *, k,\nreduction_dimension, recall_target, is_max_k,\n- reduction_input_size_override):\n+ reduction_input_size_override,\n+ aggregate_to_topk):\nc = ctx.builder\nop_shape = c.get_shape(operand)\nif not op_shape.is_array():\n@@ -204,15 +231,15 @@ def _approx_top_k_tpu_translation(ctx, avals_in, avals_out, operand, *, k,\ninit_val = xc.ops.Constant(c, init_literal)\ninit_arg = xc.ops.Constant(c, np.int32(-1))\nout = xc.ops.ApproxTopK(c, [operand, iota], [init_val, init_arg], k,\n- reduction_dimension, comparator, recall_target, True,\n- reduction_input_size_override)\n+ reduction_dimension, comparator, recall_target,\n+ aggregate_to_topk, reduction_input_size_override)\nreturn xla.xla_destructure(c, out)\ndef _approx_top_k_fallback_translation(ctx, avals_in, avals_out, operand, *, k,\n- reduction_dimension,\n- recall_target, is_max_k,\n- reduction_input_size_override):\n+ reduction_dimension, recall_target,\n+ is_max_k, reduction_input_size_override,\n+ aggregate_to_topk):\nc = ctx.builder\nop_shape = c.get_shape(operand)\nif not op_shape.is_array():\n@@ -227,14 +254,18 @@ def _approx_top_k_fallback_translation(ctx, avals_in, avals_out, operand, *, k,\nval_arg = xc.ops.Sort(c, [operand, iota], comparator, reduction_dimension)\nvals = xc.ops.GetTupleElement(val_arg, 0)\nargs = xc.ops.GetTupleElement(val_arg, 1)\n- sliced_vals = xc.ops.SliceInDim(vals, 0, k, 1, reduction_dimension)\n- sliced_args = xc.ops.SliceInDim(args, 0, k, 1, reduction_dimension)\n+ sliced_vals = xc.ops.SliceInDim(vals, 0,\n+ avals_out[0].shape[reduction_dimension], 1,\n+ reduction_dimension)\n+ sliced_args = xc.ops.SliceInDim(args, 0,\n+ avals_out[0].shape[reduction_dimension], 1,\n+ reduction_dimension)\nreturn sliced_vals, sliced_args\ndef _approx_top_k_batch_rule(batched_args, batch_dims, *, k,\nreduction_dimension, recall_target, is_max_k,\n- reduction_input_size_override):\n+ reduction_input_size_override, aggregate_to_topk):\nprototype_arg, new_bdim = next(\n(a, b) for a, b in zip(batched_args, batch_dims) if b is not None)\nnew_args = []\n@@ -252,7 +283,8 @@ def _approx_top_k_batch_rule(batched_args, batch_dims, *, k,\nreduction_dimension=new_reduction_dim,\nrecall_target=recall_target,\nis_max_k=False,\n- reduction_input_size_override=reduction_input_size_override), bdims)\n+ reduction_input_size_override=reduction_input_size_override,\n+ aggregate_to_topk=aggregate_to_topk), bdims)\n# Slow jvp implementation using gather.\n@@ -264,17 +296,20 @@ def _approx_top_k_batch_rule(batched_args, batch_dims, *, k,\n# distribute the output cotangent to input cotangent. A reasonable way to do\n# this is to run it on CPU.\ndef _approx_top_k_jvp(primals, tangents, *, k, reduction_dimension,\n- recall_target, is_max_k, reduction_input_size_override):\n+ recall_target, is_max_k, reduction_input_size_override,\n+ aggregate_to_topk):\noperand, = primals\ntangent, = tangents\nif is_max_k:\nval_out, arg_out = approx_max_k(operand, k, reduction_dimension,\nrecall_target,\n- reduction_input_size_override)\n+ reduction_input_size_override,\n+ aggregate_to_topk)\nelse:\nval_out, arg_out = approx_min_k(operand, k, reduction_dimension,\nrecall_target,\n- reduction_input_size_override)\n+ reduction_input_size_override,\n+ aggregate_to_topk)\nif type(tangent) is ad_util.Zero:\ntangent_out = ad_util.Zero.from_value(val_out)\nelse:\n" }, { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+from functools import partial\n+\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\n+import jax\nfrom jax import lax\nfrom jax.experimental import ann\nfrom jax._src import test_util as jtu\n@@ -26,6 +29,8 @@ from jax.config import config\nconfig.parse_flags_with_absl()\n+ignore_jit_of_pmap_warning = partial(\n+ jtu.ignore_warning,message=\".*jit-of-pmap.*\")\nclass AnnTest(jtu.JaxTestCase):\n@@ -105,5 +110,54 @@ class AnnTest(jtu.JaxTestCase):\njtu.check_grads(fn, (vals,), 2, [\"fwd\", \"rev\"], eps=1e-2)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_qy={}_db={}_k={}_recall={}\".format(\n+ jtu.format_shape_dtype_string(qy_shape, dtype),\n+ jtu.format_shape_dtype_string(db_shape, dtype), k, recall),\n+ \"qy_shape\": qy_shape, \"db_shape\": db_shape, \"dtype\": dtype,\n+ \"k\": k, \"recall\": recall }\n+ for qy_shape in [(200, 128), (128, 128)]\n+ for db_shape in [(2048, 128)]\n+ for dtype in jtu.dtypes.all_floating\n+ for k in [1, 10] for recall in [0.9, 0.95]))\n+ def test_pmap(self, qy_shape, db_shape, dtype, k, recall):\n+ num_devices = jax.device_count()\n+ rng = jtu.rand_default(self.rng())\n+ qy = rng(qy_shape, dtype)\n+ db = rng(db_shape, dtype)\n+ db_size = db.shape[0]\n+ gt_scores = lax.dot_general(qy, db, (([1], [1]), ([], [])))\n+ _, gt_args = lax.top_k(-gt_scores, k) # negate the score to get min-k\n+ gt_args_sets = [set(np.asarray(x)) for x in gt_args]\n+ db_per_device = db_size//num_devices\n+ sharded_db = db.reshape(num_devices, db_per_device, 128)\n+ db_offsets = np.arange(num_devices, dtype=np.int32) * db_per_device\n+ def parallel_topk(qy, db, db_offset):\n+ scores = lax.dot_general(qy, db, (([1],[1]),([],[])))\n+ ann_vals, ann_args = ann.approx_min_k(scores, k=k, reduction_dimension=1,\n+ recall_target=recall,\n+ reduction_input_size_override=db_size,\n+ aggregate_to_topk=False)\n+ return (ann_vals, ann_args + db_offset)\n+ # shape = qy_size, num_devices, approx_dp\n+ ann_vals, ann_args = jax.pmap(\n+ parallel_topk,\n+ in_axes=(None, 0, 0),\n+ out_axes=(1, 1))(qy, sharded_db, db_offsets)\n+ # collapse num_devices and approx_dp\n+ ann_vals = lax.collapse(ann_vals, 1, 3)\n+ ann_args = lax.collapse(ann_args, 1, 3)\n+ ann_vals, ann_args = lax.sort_key_val(ann_vals, ann_args, dimension=1)\n+ ann_args = lax.slice_in_dim(ann_args, start_index=0, limit_index=k, axis=1)\n+ hits = sum(\n+ len(list(x\n+ for x in ann_args_per_q\n+ if x.item() in gt_args_sets[q]))\n+ for q, ann_args_per_q in enumerate(ann_args))\n+ self.assertGreater(hits / (qy_shape[0] * k), recall)\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[XLA:TPU] Add 'aggregate_to_topk' option to ann in jax Also adds a pmap test for demonstrating multi-tpu ann. PiperOrigin-RevId: 425451716
260,411
01.02.2022 16:06:31
-7,200
0d4fdccbe6354f600532c2dfa25c9723c66f7fac
[jax2tf] minor changes to the documentation for TF Lite
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tflite/mnist/README.md", "new_path": "jax/experimental/jax2tf/examples/tflite/mnist/README.md", "diff": "@@ -59,6 +59,15 @@ tf_predict = tf.function(\nautograph=False)\n```\n+Note the `enable_xla=False` parameter to `jax2tf.convert`.\n+This is used to instruct the converter to avoid using a few special\n+TensorFlow ops that are only available with the XLA compiler, and which\n+are not understood (yet) by the TFLite converter to be used below.\n+\n+\n+Check out [more details about this limitation](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/g3doc/no_xla_limitations.md),\n+including to which JAX primitives it applies.\n+\n### Convert the trained model to the TF Lite format\nThe [TF Lite converter](https://www.tensorflow.org/lite/convert#python_api_)\n@@ -126,9 +135,4 @@ android {\n}\n```\n-## Limitations\n-* The TF Lite runtime currently doesn't support XLA ops.\n-Therefore, you need to specify `enable_xla=False` to use the jax2tf\n-conversion purely based on TensorFlow (not XLA).\n-The support is limited to a subset of JAX ops.\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] minor changes to the documentation for TF Lite
260,442
02.02.2022 14:01:54
28,800
08fd83b68c1dea0b35b13f661a9e1a50db9c2e61
[mhlo] jax infeed/outfeed lowering changes in response to detupling of the ops.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -4058,24 +4058,45 @@ infeed_p.def_abstract_eval(_infeed_abstract_eval)\nxla.register_translation(infeed_p, _infeed_translation_rule)\n+if jax._src.lib.mlir_api_version >= 2:\n+\n+ def _infeed_lowering(ctx, token, *, shapes, partitions):\n+ output_types = safe_map(mlir.aval_to_ir_types, ctx.avals_out[:-1])\n+ flat_output_types = util.flatten(output_types)\n+ # TODO(phawkins): verify `shapes` have a major-to-minor layout.\n+ layouts = ir.ArrayAttr.get([\n+ ir.ArrayAttr.get(\n+ [mlir.i64_attr(i)\n+ for i in range(len(aval.shape) - 1, -1, -1)])\n+ for aval in shapes\n+ ])\n+ infeed = mhlo.InfeedOp(flat_output_types + [mhlo.TokenType.get()], token,\n+ ir.StringAttr.get(''), layouts)\n+ if partitions is not None:\n+ mlir.set_sharding(infeed, xla.sharding_to_proto(partitions))\n+ token = infeed.results[-1]\n+ outs = infeed.results[:-1]\n+ return util.unflatten(outs, safe_map(len, output_types)) + [[\n+ token,\n+ ]]\n+else:\n+\ndef _infeed_lowering(ctx, token, *, shapes, partitions):\noutput_types = safe_map(mlir.aval_to_ir_types, ctx.avals_out[:-1])\nflat_output_types = util.flatten(output_types)\noutput_tuple_type = ir.TupleType.get_tuple(flat_output_types)\n# TODO(phawkins): verify `shapes` have a major-to-minor layout.\nlayouts = ir.ArrayAttr.get([\n+ ir.ArrayAttr.get([\nir.ArrayAttr.get(\n- [ir.ArrayAttr.get(\n- [mlir.i64_attr(i) for i in range(len(aval.shape) - 1, -1, -1)])\n- for aval in shapes]),\n+ [mlir.i64_attr(i)\n+ for i in range(len(aval.shape) - 1, -1, -1)])\n+ for aval in shapes\n+ ]),\nir.UnitAttr.get(),\n])\noutput_and_token_tuple_type = ir.TupleType.get_tuple(\n[output_tuple_type, mhlo.TokenType.get()])\n- if jax._src.lib.mlir_api_version >= 2:\n- infeed = mhlo.InfeedOp([output_and_token_tuple_type], token,\n- ir.StringAttr.get(''), layouts)\n- else:\ninfeed = mhlo.InfeedOp(output_and_token_tuple_type, token,\nir.StringAttr.get(''), layouts)\nif partitions is not None:\n@@ -4084,9 +4105,13 @@ def _infeed_lowering(ctx, token, *, shapes, partitions):\nmlir.i32_attr(0)).result\ntoken = mhlo.GetTupleElementOp(mhlo.TokenType.get(), infeed.result,\nmlir.i32_attr(1)).result\n- outs = [mhlo.GetTupleElementOp(typ, outs_tuple, mlir.i32_attr(i)).result\n- for i, typ in enumerate(flat_output_types)]\n- return util.unflatten(outs, safe_map(len, output_types)) + [[token,]]\n+ outs = [\n+ mhlo.GetTupleElementOp(typ, outs_tuple, mlir.i32_attr(i)).result\n+ for i, typ in enumerate(flat_output_types)\n+ ]\n+ return util.unflatten(outs, safe_map(len, output_types)) + [[\n+ token,\n+ ]]\nmlir.register_lowering(infeed_p, _infeed_lowering)\n@@ -4125,17 +4150,26 @@ outfeed_p.def_abstract_eval(_outfeed_abstract_eval)\nxla.register_translation(outfeed_p, _outfeed_translation_rule)\n+if jax._src.lib.mlir_api_version >= 2:\n+\n+ def _outfeed_lowering(ctx, token, *xs, partitions):\n+ token_aval = ctx.avals_in[0]\n+ outfeed = mhlo.OutfeedOp(\n+ mlir.aval_to_ir_type(token_aval), mlir.flatten_lowering_ir_args(xs),\n+ token, ir.StringAttr.get(''))\n+ if partitions is not None:\n+ mlir.set_sharding(outfeed, xla.sharding_to_proto(partitions))\n+ return outfeed.results\n+else:\n+\ndef _outfeed_lowering(ctx, token, *xs, partitions):\ntoken_aval = ctx.avals_in[0]\nxs_avals = ctx.avals_in[1:]\ninput_types = map(mlir.aval_to_ir_types, xs_avals)\nflat_input_types = util.flatten(input_types)\ninput_tuple_type = ir.TupleType.get_tuple(flat_input_types)\n- tup = mhlo.TupleOp(input_tuple_type, mlir.flatten_lowering_ir_args(xs)).result\n- if jax._src.lib.mlir_api_version >= 2:\n- outfeed = mhlo.OutfeedOp(\n- mlir.aval_to_ir_type(token_aval), [tup], token, ir.StringAttr.get(''))\n- else:\n+ tup = mhlo.TupleOp(input_tuple_type,\n+ mlir.flatten_lowering_ir_args(xs)).result\noutfeed = mhlo.OutfeedOp(\nmlir.aval_to_ir_type(token_aval), tup, token, ir.StringAttr.get(''))\nif partitions is not None:\n" } ]
Python
Apache License 2.0
google/jax
[mhlo] jax infeed/outfeed lowering changes in response to detupling of the ops. PiperOrigin-RevId: 425972002
260,631
02.02.2022 15:49:28
28,800
a0abe8e4aca186b4746887ad69f571802bb83563
[JAX] Move the ann recall computation to ann.py. This function is very useful for our users to evaluate the ann results against the standard ann datasets that provides the ground truth.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ann.py", "new_path": "jax/experimental/ann.py", "diff": "@@ -163,6 +163,45 @@ def approx_min_k(operand: Array,\naggregate_to_topk=aggregate_to_topk)\n+def ann_recall(result_neighbors: Array, ground_truth_neighbors: Array) -> float:\n+ \"\"\"Computes the recall of an approximate nearest neighbor search.\n+\n+ Note, this is NOT a JAX-compatible op. This is a host function that only takes\n+ numpy arrays as the inputs.\n+\n+ Args:\n+ result_neighbors: int32 numpy array of the shape\n+ [num_queries, neighbors_per_query] where the values are the indices of the\n+ dataset.\n+ ground_truth_neighbors: int32 numpy array of with shape\n+ [num_queries, ground_truth_neighbors_per_query] where the values are the\n+ indices of the dataset.\n+\n+ Example:\n+ # shape [num_queries, 100]\n+ ground_truth_neighbors = ... # pre-computed top 100 sorted neighbors\n+ # shape [num_queries, 200]\n+ result_neighbors = ... # Retrieves 200 neighbors from some ann algorithms.\n+\n+ # Computes the recall with k = 100\n+ ann_recall(result_neighbors, ground_truth_neighbors)\n+\n+ # Computes the recall with k = 10\n+ ann_recall(result_neighbors, ground_truth_neighbors[:,0:10])\n+\n+ Returns:\n+ The recall.\n+ \"\"\"\n+ assert len(result_neighbors.shape) == 2, 'shape = [num_queries, neighbors_per_query]'\n+ assert len(ground_truth_neighbors.shape) == 2, 'shape = [num_queries, ground_truth_neighbors_per_query]'\n+ assert result_neighbors.shape[0] == ground_truth_neighbors.shape[0]\n+ gt_sets = [set(np.asarray(x)) for x in ground_truth_neighbors]\n+ hits = sum(\n+ len(list(x for x in nn_per_q if x.item() in gt_sets[q]))\n+ for q, nn_per_q in enumerate(result_neighbors))\n+ return hits / ground_truth_neighbors.size\n+\n+\ndef _approx_top_k_abstract_eval(operand, *, k, reduction_dimension,\nrecall_target, is_max_k,\nreduction_input_size_override,\n" }, { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "@@ -54,13 +54,8 @@ class AnnTest(jtu.JaxTestCase):\n_, gt_args = lax.top_k(scores, k)\n_, ann_args = ann.approx_max_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\n- gt_args_sets = [set(np.asarray(x)) for x in gt_args]\n- hits = sum(\n- len(list(x\n- for x in ann_args_per_q\n- if x.item() in gt_args_sets[q]))\n- for q, ann_args_per_q in enumerate(ann_args))\n- self.assertGreater(hits / (qy_shape[0] * k), recall)\n+ ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ self.assertGreater(ann_recall, recall)\n@parameterized.named_parameters(\njtu.cases_from_list({\n@@ -82,13 +77,8 @@ class AnnTest(jtu.JaxTestCase):\n_, gt_args = lax.top_k(-scores, k)\n_, ann_args = ann.approx_min_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\n- gt_args_sets = [set(np.asarray(x)) for x in gt_args]\n- hits = sum(\n- len(list(x\n- for x in ann_args_per_q\n- if x.item() in gt_args_sets[q]))\n- for q, ann_args_per_q in enumerate(ann_args))\n- self.assertGreater(hits / (qy_shape[0] * k), recall)\n+ ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ self.assertGreater(ann_recall, recall)\n@parameterized.named_parameters(\njtu.cases_from_list({\n@@ -130,7 +120,6 @@ class AnnTest(jtu.JaxTestCase):\ndb_size = db.shape[0]\ngt_scores = lax.dot_general(qy, db, (([1], [1]), ([], [])))\n_, gt_args = lax.top_k(-gt_scores, k) # negate the score to get min-k\n- gt_args_sets = [set(np.asarray(x)) for x in gt_args]\ndb_per_device = db_size//num_devices\nsharded_db = db.reshape(num_devices, db_per_device, 128)\ndb_offsets = np.arange(num_devices, dtype=np.int32) * db_per_device\n@@ -151,12 +140,8 @@ class AnnTest(jtu.JaxTestCase):\nann_args = lax.collapse(ann_args, 1, 3)\nann_vals, ann_args = lax.sort_key_val(ann_vals, ann_args, dimension=1)\nann_args = lax.slice_in_dim(ann_args, start_index=0, limit_index=k, axis=1)\n- hits = sum(\n- len(list(x\n- for x in ann_args_per_q\n- if x.item() in gt_args_sets[q]))\n- for q, ann_args_per_q in enumerate(ann_args))\n- self.assertGreater(hits / (qy_shape[0] * k), recall)\n+ ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ self.assertGreater(ann_recall, recall)\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Move the ann recall computation to ann.py. This function is very useful for our users to evaluate the ann results against the standard ann datasets that provides the ground truth. PiperOrigin-RevId: 425997236
260,411
03.02.2022 11:09:12
-7,200
53be1b9c2c6752a8700ed3b07d316bf92108f8f5
[jax2tf] Add a TF version check for support of conv:batch_group_count The batch_group_count != 1 is only supported with TF version 2.8.0 and above. Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -1086,8 +1086,8 @@ cannot be sure that the shape-polymorphic conversion is safe.\n## TensorFlow versions supported\n-The ``jax2tf.convert`` and `call_tf` require very recent versions of TensorFlow.\n-As of today, the tests are run using `tf_nightly==2.7.0.dev20210715`.\n+The ``jax2tf.convert`` and `call_tf` require fairly recent versions of TensorFlow.\n+As of today, the tests are run using `tf_nightly==2.9.0.dev20220202`.\n## Running on GPU\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1499,19 +1499,29 @@ def _conv_general_dilated(lhs, rhs, *,\nprecision_config_proto = _precision_config_proto(precision)\ndef gen_conv(lhs, rhs, preferred_element_type: Optional[DType]):\n+ if tf.__version__ >= \"2.8.0\":\n+ # TODO(necula): remove when 2.8.0 is the stable TF version (and supports\n+ # batch_group_count.\nout = tfxla.conv(\n- lhs,\n- rhs,\n- window_strides,\n- padding,\n- lhs_dilation,\n- rhs_dilation,\n+ lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\ndnums_proto,\nfeature_group_count=feature_group_count,\nbatch_group_count=batch_group_count,\nprecision_config=precision_config_proto,\npreferred_element_type=preferred_element_type,\nuse_v2=True)\n+ else:\n+ if batch_group_count != 1:\n+ raise ValueError(\n+ \"The batch_group_count parameter for conv requires TF version \"\n+ \"at least 2.8.0. You may want to use tf-nightly.\")\n+ out = tfxla.conv(\n+ lhs, rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n+ dnums_proto,\n+ feature_group_count=feature_group_count,\n+ precision_config=precision_config_proto,\n+ preferred_element_type=preferred_element_type,\n+ use_v2=True)\n# TODO: implement shape inference for XlaConv\nout.set_shape(out_tf_shape)\nif _WRAP_JAX_JIT_WITH_TF_FUNCTION:\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add a TF version check for support of conv:batch_group_count The batch_group_count != 1 is only supported with TF version 2.8.0 and above. Fixes: #9384
260,447
03.02.2022 11:16:18
28,800
5a012d5e7b056047208aa4c21ca226faa68fd8bb
[JAX] Added jit-able singular value decomposition.
[ { "change_type": "ADD", "old_path": null, "new_path": "tests/svd_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+\n+\"\"\"Tests for the library of QDWH-based SVD decomposition.\"\"\"\n+import functools\n+\n+import jax\n+from jax import test_util as jtu\n+from jax.config import config\n+import jax.numpy as jnp\n+import numpy as np\n+import scipy.linalg as osp_linalg\n+from jax._src.lax import svd\n+\n+from absl.testing import absltest\n+from absl.testing import parameterized\n+\n+\n+config.parse_flags_with_absl()\n+_JAX_ENABLE_X64 = config.x64_enabled\n+\n+# Input matrix data type for SvdTest.\n+_SVD_TEST_DTYPE = np.float64 if _JAX_ENABLE_X64 else np.float32\n+\n+# Machine epsilon used by SvdTest.\n+_SVD_TEST_EPS = jnp.finfo(_SVD_TEST_DTYPE).eps\n+\n+# SvdTest relative tolerance.\n+_SVD_RTOL = 1E-6 if _JAX_ENABLE_X64 else 1E-2\n+\n+_MAX_LOG_CONDITION_NUM = 9 if _JAX_ENABLE_X64 else 4\n+\n+\n+@jtu.with_config(jax_numpy_rank_promotion='allow')\n+class SvdTest(jtu.JaxTestCase):\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_by_n={}_log_cond={}'.format(m, n, log_cond),\n+ 'm': m, 'n': n, 'log_cond': log_cond}\n+ for m, n in zip([2, 8, 10, 20], [4, 6, 10, 18])\n+ for log_cond in np.linspace(1, _MAX_LOG_CONDITION_NUM, 4)))\n+ def testSvdWithRectangularInput(self, m, n, log_cond):\n+ \"\"\"Tests SVD with rectangular input.\"\"\"\n+ with jax.default_matmul_precision('float32'):\n+ a = np.random.uniform(\n+ low=0.3, high=0.9, size=(m, n)).astype(_SVD_TEST_DTYPE)\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, min(m, n))\n+ a = (u * s) @ v\n+ a = a + 1j * a\n+\n+ osp_linalg_fn = functools.partial(osp_linalg.svd, full_matrices=False)\n+ actual_u, actual_s, actual_v = svd.svd(a)\n+\n+ k = min(m, n)\n+ if m > n:\n+ unitary_u = jnp.abs(actual_u.T.conj() @ actual_u)\n+ unitary_v = jnp.abs(actual_v.T.conj() @ actual_v)\n+ else:\n+ unitary_u = jnp.abs(actual_u @ actual_u.T.conj())\n+ unitary_v = jnp.abs(actual_v @ actual_v.T.conj())\n+\n+ _, expected_s, _ = osp_linalg_fn(a)\n+\n+ args_maker = lambda: [a]\n+\n+ with self.subTest('Test JIT compatibility'):\n+ self._CompileAndCheck(svd.svd, args_maker)\n+\n+ with self.subTest('Test unitary u.'):\n+ self.assertAllClose(np.eye(k), unitary_u, rtol=_SVD_RTOL, atol=2E-3)\n+\n+ with self.subTest('Test unitary v.'):\n+ self.assertAllClose(np.eye(k), unitary_v, rtol=_SVD_RTOL, atol=2E-3)\n+\n+ with self.subTest('Test s.'):\n+ self.assertAllClose(\n+ expected_s, jnp.real(actual_s), rtol=_SVD_RTOL, atol=1E-6)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {'testcase_name': '_m={}_by_n={}'.format(m, n), 'm': m, 'n': n}\n+ for m, n in zip([50, 6], [3, 60])))\n+ def testSvdWithSkinnyTallInput(self, m, n):\n+ \"\"\"Tests SVD with skinny and tall input.\"\"\"\n+ # Generates a skinny and tall input\n+ with jax.default_matmul_precision('float32'):\n+ np.random.seed(1235)\n+ a = np.random.randn(m, n).astype(_SVD_TEST_DTYPE)\n+ u, s, v = svd.svd(a, is_hermitian=False)\n+\n+ relative_diff = np.linalg.norm(a - (u * s) @ v) / np.linalg.norm(a)\n+\n+ np.testing.assert_almost_equal(relative_diff, 1E-6, decimal=6)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ { # pylint:disable=g-complex-comprehension\n+ 'testcase_name': '_m={}_r={}_log_cond={}'.format(m, r, log_cond),\n+ 'm': m, 'r': r, 'log_cond': log_cond}\n+ for m, r in zip([8, 8, 8, 10], [3, 5, 7, 9])\n+ for log_cond in np.linspace(1, 3, 3)))\n+ def testSvdWithOnRankDeficientInput(self, m, r, log_cond):\n+ \"\"\"Tests SVD with rank-deficient input.\"\"\"\n+ with jax.default_matmul_precision('float32'):\n+ a = jnp.triu(jnp.ones((m, m))).astype(_SVD_TEST_DTYPE)\n+\n+ # Generates a rank-deficient input.\n+ u, s, v = jnp.linalg.svd(a, full_matrices=False)\n+ cond = 10**log_cond\n+ s = jnp.linspace(cond, 1, m)\n+ s = s.at[r:m].set(jnp.zeros((m-r,)))\n+ a = (u * s) @ v\n+\n+ with jax.default_matmul_precision('float32'):\n+ u, s, v = svd.svd(a, is_hermitian=False)\n+ diff = np.linalg.norm(a - (u * s) @ v)\n+\n+ np.testing.assert_almost_equal(diff, 1E-4, decimal=2)\n+\n+\n+if __name__ == '__main__':\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Added jit-able singular value decomposition. PiperOrigin-RevId: 426193395
260,335
28.01.2022 15:54:19
28,800
e186aa3f1e428a2716f6dff7b37119e88aadf0e5
add and test pytree utils for better errors
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1404,11 +1404,12 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None, axis_size=None) -> F:\nrange ``[-ndim, ndim)`` for each array, where ``ndim`` is the number of\ndimensions (axes) of the corresponding input array.\n- If the positional arguments to ``fun`` are container types, the\n+ If the positional arguments to ``fun`` are container (pytree) types, the\ncorresponding element of ``in_axes`` can itself be a matching container,\nso that distinct array axes can be mapped for different container\nelements. ``in_axes`` must be a container tree prefix of the positional\n- argument tuple passed to ``fun``.\n+ argument tuple passed to ``fun``. See this link for more detail:\n+ https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees\nEither ``axis_size`` must be provided explicitly, or at least one\npositional argument must have ``in_axes`` not None. The sizes of the\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/tree_util.py", "new_path": "jax/_src/tree_util.py", "diff": "@@ -17,7 +17,7 @@ import functools\nfrom functools import partial\nimport operator as op\nfrom typing import (Any, Callable, Hashable, Iterable, Optional, Tuple, List,\n- Type, TypeVar, overload, TYPE_CHECKING)\n+ Dict, Type, TypeVar, overload, TYPE_CHECKING, NamedTuple)\nfrom jax._src.lib import pytree\n@@ -361,8 +361,121 @@ register_pytree_node(\ndef broadcast_prefix(prefix_tree: Any, full_tree: Any,\nis_leaf: Optional[Callable[[Any], bool]] = None\n) -> List[Any]:\n+ # If prefix_tree is not a tree prefix of full_tree, this code can raise a\n+ # ValueError; use prefix_errors to find disagreements and raise more precise\n+ # error messages.\nresult = []\nnum_leaves = lambda t: tree_structure(t).num_leaves\nadd_leaves = lambda x, subtree: result.extend([x] * num_leaves(subtree))\ntree_map(add_leaves, prefix_tree, full_tree, is_leaf=is_leaf)\nreturn result\n+\n+def flatten_one_level(pytree: Any) -> Tuple[List[Any], Hashable]:\n+ handler = _registry.get(type(pytree))\n+ if handler:\n+ children, meta = handler.to_iter(pytree)\n+ return list(children), meta\n+ elif isinstance(pytree, tuple) and hasattr(pytree, '_fields'):\n+ return list(pytree), None\n+ else:\n+ raise ValueError(f\"can't tree-flatten type: {type(pytree)}\")\n+\n+def prefix_errors(prefix_tree: Any, full_tree: Any\n+ ) -> List[Callable[[str], ValueError]]:\n+ return list(_prefix_error(KeyPath(()), prefix_tree, full_tree))\n+\n+class KeyPathEntry(NamedTuple):\n+ key: Any\n+ def pprint(self) -> str:\n+ assert False # must override\n+\n+class KeyPath(NamedTuple):\n+ keys: Tuple[KeyPathEntry, ...]\n+ def __add__(self, other):\n+ if isinstance(other, KeyPathEntry):\n+ return KeyPath(self.keys + (other,))\n+ raise TypeError(type(other))\n+ def pprint(self) -> str:\n+ if not self.keys:\n+ return ' tree root'\n+ return ''.join(k.pprint() for k in self.keys)\n+\n+class GetitemKeyPathEntry(KeyPathEntry):\n+ def pprint(self) -> str:\n+ return f'[{repr(self.key)}]'\n+\n+class AttributeKeyPathEntry(KeyPathEntry):\n+ def pprint(self) -> str:\n+ return f'.{self.key}'\n+\n+class FlattenedKeyPathEntry(KeyPathEntry): # fallback\n+ def pprint(self) -> str:\n+ return f'[<flat index {self.key}>]'\n+\n+def _child_keys(pytree: Any) -> List[KeyPathEntry]:\n+ assert not treedef_is_leaf(tree_structure(pytree))\n+ handler = _keypath_registry.get(type(pytree))\n+ if handler:\n+ return handler(pytree)\n+ elif isinstance(pytree, tuple) and hasattr(pytree, '_fields'):\n+ # handle namedtuple as a special case, based on heuristic\n+ return [AttributeKeyPathEntry(s) for s in pytree._fields]\n+ else:\n+ num_children = len(treedef_children(tree_structure(pytree)))\n+ return [FlattenedKeyPathEntry(i) for i in range(num_children)]\n+\n+_keypath_registry: Dict[Type, Callable[[Any], List[KeyPathEntry]]] = {}\n+\n+def register_keypaths(ty: Type, handler: Callable[[Any], List[KeyPathEntry]]\n+ ) -> None:\n+ _keypath_registry[ty] = handler\n+\n+register_keypaths(tuple,\n+ lambda tup: [GetitemKeyPathEntry(i) for i in range(len(tup))])\n+register_keypaths(list,\n+ lambda lst: [GetitemKeyPathEntry(i) for i in range(len(lst))])\n+register_keypaths(dict,\n+ lambda dct: [GetitemKeyPathEntry(k) for k in sorted(dct)])\n+\n+def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any\n+ ) -> Iterable[Callable[[str], ValueError]]:\n+ # A leaf is a valid prefix of any tree:\n+ if treedef_is_leaf(tree_structure(prefix_tree)): return\n+\n+ # The subtrees may disagree because their roots are of different types:\n+ if type(prefix_tree) != type(full_tree):\n+ yield lambda name: ValueError(\n+ \"pytree structure error: different types \"\n+ f\"at {{name}}{key_path.pprint()}: \"\n+ f\"prefix pytree {{name}} has type {type(prefix_tree)} \"\n+ f\"where full pytree has type {type(full_tree)}.\".format(name=name))\n+ return # don't look for more errors in this subtree\n+\n+ # Or they may disagree if their roots have different numbers of children:\n+ prefix_tree_children, prefix_tree_meta = flatten_one_level(prefix_tree)\n+ full_tree_children, full_tree_meta = flatten_one_level(full_tree)\n+ if len(prefix_tree_children) != len(full_tree_children):\n+ yield lambda name: ValueError(\n+ \"pytree structure error: different numbers of pytree children \"\n+ f\"at {{name}}{key_path.pprint()}: \"\n+ f\"prefix pytree {{name}} has {len(prefix_tree_children)} children where \"\n+ f\"full pytree has {len(full_tree_children)} children.\".format(name=name))\n+ return # don't look for more errors in this subtree\n+\n+ # Or they may disagree if their roots have different pytree metadata:\n+ if prefix_tree_meta != full_tree_meta:\n+ yield lambda name: ValueError(\n+ \"pytree structure error: different pytree metadata \"\n+ f\"at {{name}}{key_path.pprint()}: \"\n+ f\"prefix pytree {{name}} has metadata {prefix_tree_meta} where \"\n+ f\"full pytree has metadata {full_tree_meta}.\".format(name=name))\n+ return # don't look for more errors in this subtree\n+\n+ # If the root types and numbers of children agree, there must be an error\n+ # in a subtree, so recurse:\n+ keys = _child_keys(prefix_tree)\n+ keys_ = _child_keys(full_tree)\n+ assert keys == keys_, \\\n+ f\"equal pytree nodes gave differing keys: {keys} and {keys_}\"\n+ for k, t1, t2 in zip(keys, prefix_tree_children, full_tree_children):\n+ yield from _prefix_error(key_path + k, t1, t2)\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_test.py", "new_path": "tests/tree_util_test.py", "diff": "@@ -24,7 +24,7 @@ from jax import tree_util\nfrom jax import flatten_util\nfrom jax._src import test_util as jtu\nfrom jax._src.lib import pytree as pytree\n-from jax._src.tree_util import _process_pytree\n+from jax._src.tree_util import _process_pytree, prefix_errors\nimport jax.numpy as jnp\n@@ -435,5 +435,89 @@ class RavelUtilTest(jtu.JaxTestCase):\n_ = unravel(y)\n+class TreePrefixErrorsTest(jtu.JaxTestCase):\n+\n+ def test_different_types(self):\n+ e, = prefix_errors((1, 2), [1, 2])\n+ expected = \"pytree structure error: different types at in_axes tree root\"\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_types_nested(self):\n+ e, = prefix_errors(((1,), (2,)), ([3], (4,)))\n+ expected = r\"pytree structure error: different types at in_axes\\[0\\]\"\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_types_multiple(self):\n+ e1, e2 = prefix_errors(((1,), (2,)), ([3], [4]))\n+ expected = r\"pytree structure error: different types at in_axes\\[0\\]\"\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e1('in_axes')\n+ expected = r\"pytree structure error: different types at in_axes\\[1\\]\"\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e2('in_axes')\n+\n+ def test_different_num_children(self):\n+ e, = prefix_errors((1,), (2, 3))\n+ expected = (\"pytree structure error: different numbers of pytree children \"\n+ \"at in_axes tree root\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_num_children_nested(self):\n+ e, = prefix_errors([[1]], [[2, 3]])\n+ expected = (\"pytree structure error: different numbers of pytree children \"\n+ r\"at in_axes\\[0\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_num_children_multiple(self):\n+ e1, e2 = prefix_errors([[1], [2]], [[3, 4], [5, 6]])\n+ expected = (\"pytree structure error: different numbers of pytree children \"\n+ r\"at in_axes\\[0\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e1('in_axes')\n+ expected = (\"pytree structure error: different numbers of pytree children \"\n+ r\"at in_axes\\[1\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e2('in_axes')\n+\n+ def test_different_metadata(self):\n+ e, = prefix_errors({1: 2}, {3: 4})\n+ expected = (\"pytree structure error: different pytree metadata \"\n+ \"at in_axes tree root\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_metadata_nested(self):\n+ e, = prefix_errors([{1: 2}], [{3: 4}])\n+ expected = (\"pytree structure error: different pytree metadata \"\n+ r\"at in_axes\\[0\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_different_metadata_multiple(self):\n+ e1, e2 = prefix_errors([{1: 2}, {3: 4}], [{3: 4}, {5: 6}])\n+ expected = (\"pytree structure error: different pytree metadata \"\n+ r\"at in_axes\\[0\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e1('in_axes')\n+ expected = (\"pytree structure error: different pytree metadata \"\n+ r\"at in_axes\\[1\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e2('in_axes')\n+\n+ def test_fallback_keypath(self):\n+ e, = prefix_errors(Special(1, [2]), Special(3, 4))\n+ expected = (\"pytree structure error: different types at \"\n+ r\"in_axes\\[<flat index 1>\\]\")\n+ with self.assertRaisesRegex(ValueError, expected):\n+ raise e('in_axes')\n+\n+ def test_no_errors(self):\n+ () = prefix_errors((1, 2), ((11, 12, 13), 2))\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
add and test pytree utils for better errors
260,631
04.02.2022 20:02:45
28,800
7a6986c4c8fd8469bae36306efb0417b0a2f6d8c
[JAX] Update the ANN document. Deletes the documentation that explains the algorithm. I don't think it is the necessary detail for users. We'll write a paper to explain it in detail very soon.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ann.py", "new_path": "jax/experimental/ann.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"ANN (Approximate Nearest Neighbor) computes top-k with a configurable recall rate on TPU.\n-\n-TPUs are highly efficient on matrix multiplication, which scales up by TPU\n-generation. Nevertheless, TPUs are surprisingly inefficient in the other\n-generalized instructions used in standard algorithm designs.\n-\n-We can illustrate the inefficiency of writing general algorithms on TPU by\n-comparing general instructions and matrix multiplication instruction throughput.\n-We could only use no more than ten vector instructions per matrix\n-multiplication; otherwise, we would see a significant performance regression.\n-This constraint prevents us from almost all standard exact top-k algorithms,\n-including parallel binary-heap, median-of-medians, and bitonic sort.\n-\n-Our approach to this problem is to reshape the inputs into equally sized\n-windows,\n-and return the top-1s in each window containing the true top-k. Suppose we have\n-the actual top-k elements randomly spreaded in the windows, and we select the\n-top-1 from each window. The collision rate of the top-k affects the accuracy,\n-which we can model by the number of people with shared birthdays in the Birthday\n-problem.\n-\n-The recall of this approximation depends on the output size :math:`M` and\n-desired :math`K` elements in top-k. The recall is approximately\n-:math:`\\\\exp\\\\left(\\\\frac{1-K}{M}\\\\right)`. A quick estimate is the output\n-would roughly be :math:`M=10\\\\cdot K` for 90% target recall, and\n-:math:`M=100\\\\cdot K` for 99% target recall. The smaller the output, the smaller\n-memory bandwidth it consumes.\n+\"\"\"ANN (Approximate Nearest Neighbor) computes top-k with a configurable recall rate.\n+\n+This package only optimizes the TPU backend. For other device types it fallbacks\n+to sort and slice.\nUsage::\n+ import functools\n+ import jax\nfrom jax.experimental import ann\n- # Maximum inner product search\n- # qy shape: [qy_size, feature_dim]\n- # db shape: [feature_dim, db_size]\n- scores, docids = ann.approx_max_k(lax.dot(qy, db), k=10, recall_target=0.95)\n-\n- # Pmap Maximum inner product search\n- # qy shape: [qy_size, feature_dim]\n- # db shape: [num_devices, per_device_db_size, feature_dim]\n- db_offsets = np.arange(num_devices, dtype=np.int32) * per_device_db_size\n- def parallel_topk(qy, db, db_offset):\n- scores = lax.dot_general(qy, db, (([1],[1]),([],[])))\n- ann_vals, ann_args = ann.approx_max_k(scores, k, recall_target=0.95,\n- reduction_input_size_override=db_size,\n- aggregate_to_topk=False)\n- return (ann_vals, ann_docids + db_offset)\n- # shape = [qy_size, num_devices, approx_dp]\n- ann_vals, ann_docids = jax.pmap(\n- parallel_topk,\n- in_axes(None, 0, 0), # broadcast qy, shard db and db_offsets\n- out_axes(1, 1))(qy, db, db_offsets)\n- # collapse num_devices and approx_dp\n- ann_vals = lax.collapse(ann_vals, 1, 3)\n- ann_docids = lax.collapse(ann_docids, 1, 3)\n- ann_vals, ann_docids = lax.sort_key_val(-ann_vals, ann_docids, dimension=1)\n- # slice to k\n- ann_vals = lax.slice_in_dim(ann_vals, start_index=0, limit_index=k, axis=1)\n- ann_docids = lax.slice_in_dim(ann_docids, start_index=0, limit_index=k, axis=1)\n+\n+ # MIPS := maximal inner product search\n+ # Inputs:\n+ # qy: f32[qy_size, feature_dim]\n+ # db: f32[db_size, feature_dim]\n+ #\n+ # Returns:\n+ # (f32[qy_size, k], i32[qy_size, k])\n+ @functools.partial(jax.jit, static_argnames=[\"k\", \"recall_target\"])\n+ def mips(qy, db, k=10, recall_target=0.95):\n+ dists = jax.lax.dot(qy, db.transpose())\n+ # Computes max_k along the last dimension\n+ # returns (f32[qy_size, k], i32[qy_size, k])\n+ return ann.approx_max_k(dists, k=k, recall_target=recall_target)\n+\n+ # Obtains the top-10 dot products and its offsets in db.\n+ dot_products, neighbors = mips(qy, db, k=10)\n+ # Computes the recall against the true neighbors.\n+ recall = ann.ann_recall(neighbors, true_neighbors)\n+\n+ # Multi-core example\n+ # Inputs:\n+ # qy: f32[num_devices, qy_size, feature_dim]\n+ # db: f32[num_devices, per_device_db_size, feature_dim]\n+ # db_offset: i32[num_devices]\n+ #\n+ # Returns:\n+ # (f32[qy_size, num_devices, k], i32[qy_size, num_devices, k])\n+ @functools.partial(\n+ jax.pmap,\n+ # static args: db_size, k, recall_target\n+ static_broadcasted_argnums=[3, 4, 5],\n+ out_axes=(1, 1))\n+ def pmap_mips(qy, db, db_offset, db_size, k, recall_target):\n+ dists = jax.lax.dot(qy, db.transpose())\n+ dists, neighbors = ann.approx_max_k(\n+ dists, k=k, recall_target=recall_target,\n+ reduction_input_size_override=db_size)\n+ return (dists, neighbors + db_offset)\n+\n+ # i32[qy_size, num_devices, k]\n+ pmap_neighbors = pmap_mips(qy, db, db_offset, db_size, 10, 0.95)[1]\n+ # i32[qy_size, num_devices * k]\n+ neighbors = jax.lax.collapse(pmap_neighbors, start_dimension=1, stop_dimension=3)\nTodos::\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Update the ANN document. Deletes the documentation that explains the algorithm. I don't think it is the necessary detail for users. We'll write a paper to explain it in detail very soon. PiperOrigin-RevId: 426546480
260,287
07.02.2022 10:34:36
28,800
42cd7ed1d0653c5a9d1b25c3f701ff3ec2b6c74b
Allow nesting MANUAL-style xmaps in pjits
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1312,7 +1312,7 @@ pxla.SPMDBatchTrace.process_xmap = partialmethod(_batch_trace_process_xmap, True\ndef _xmap_lowering_rule(*args, **kwargs):\nif config.experimental_xmap_spmd_lowering_manual:\n- raise NotImplementedError\n+ return _xmap_lowering_rule_spmd_manual(*args, **kwargs)\nelif config.experimental_xmap_spmd_lowering:\nreturn _xmap_lowering_rule_spmd(*args, **kwargs)\nelse:\n@@ -1428,9 +1428,6 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\naxes[dim_extra_axis] = dim\nadd_spmd_axes(mesh_in_axes, spmd_in_axes)\nadd_spmd_axes(mesh_out_axes, spmd_out_axes)\n- # NOTE: We don't extend the resource env with the mesh shape, because those\n- # resources are already in scope! It's the outermost xmap that introduces\n- # them!\nglobal_in_avals = ctx.avals_in\nvectorized_jaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(f, global_in_avals)\nassert not consts\n@@ -1459,6 +1456,44 @@ def _xmap_lowering_rule_spmd(ctx, *global_in_nodes,\nreturn sharded_global_out_nodes\n+def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\n+ call_jaxpr, name, in_axes, out_axes,\n+ donated_invars, global_axis_sizes, spmd_in_axes,\n+ spmd_out_axes, positional_semantics,\n+ axis_resources, resource_env, backend):\n+ assert spmd_in_axes is None and spmd_out_axes is None\n+ # This first part (up to vtile_manual) is shared with non-MANUAL SPMD rule.\n+ xla.check_backend_matches(backend, ctx.module_context.platform)\n+ plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, global_axis_sizes)\n+\n+ resource_call_jaxpr = plan.subst_axes_with_resources(call_jaxpr)\n+ f = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(resource_call_jaxpr, ())))\n+ f = hide_mapped_axes(f, in_axes, out_axes)\n+ f = plan.vectorize_and_loop(f, in_axes, out_axes)\n+\n+ # NOTE: Sharding constraints are handled entirely by vtile_manual!\n+ mesh_in_axes, mesh_out_axes = plan.to_mesh_axes(in_axes, out_axes)\n+ mesh = resource_env.physical_mesh\n+ f = pxla.vtile_manual(f, mesh, mesh_in_axes, mesh_out_axes)\n+\n+ # NOTE: We don't extend the resource env with the mesh shape, because those\n+ # resources are already in scope! It's the outermost xmap that introduces\n+ # them!\n+ global_in_avals = ctx.avals_in\n+ vectorized_jaxpr, global_out_avals, consts = pe.trace_to_jaxpr_dynamic(f, global_in_avals)\n+ assert not consts\n+\n+ # We in-line here rather than generating a Call HLO as in the xla_call\n+ # translation rule just because the extra tuple stuff is a pain.\n+ sub_ctx = ctx.module_context.replace(\n+ name_stack=xla.extend_name_stack(ctx.module_context.name_stack,\n+ xla.wrap_name(name, 'xmap')))\n+ global_out_nodes = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr, (),\n+ *([n] for n in global_in_nodes))\n+\n+ return global_out_nodes\n+\n+\ndef _xmap_translation_rule(*args, **kwargs):\nif config.experimental_xmap_spmd_lowering_manual:\nraise NotImplementedError(\"Manual lowering only supported in MLIR lowering\")\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -39,6 +39,8 @@ from jax import lax\nfrom jax import core\nfrom jax.core import NamedShape, JaxprTypeError\nfrom jax.experimental import maps\n+from jax.experimental.pjit import pjit\n+from jax.experimental.pjit import PartitionSpec as P\nfrom jax.experimental.maps import Mesh, mesh, xmap, serial_loop, SerialLoop\nfrom jax.errors import JAXTypeError\nfrom jax._src.lib import xla_bridge\n@@ -693,6 +695,13 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(20, dtype=jnp.float32)\nself.assertAllClose(fx(x), f(x))\n+ @jtu.with_mesh([('x', 2), ('y', 1)])\n+ def testInPJit(self):\n+ f = xmap(lambda x: jnp.sin(x) + x, in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})\n+ h = pjit(lambda x: f(x * x) + x, in_axis_resources=P('y'), out_axis_resources=None)\n+ x = jnp.arange(20, dtype=jnp.float32)\n+ self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+\nclass NamedNumPyTest(XMapTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Allow nesting MANUAL-style xmaps in pjits PiperOrigin-RevId: 426955137
260,287
07.02.2022 10:37:01
28,800
296832e891def967b64ad0d24e3df1ad0cb5cf8f
Use aval_out to construct a sharding spec in shard to full The shard's dimensions might be too small and might trigger asserts, even though the shape has no influence on sharding specs.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1977,7 +1977,7 @@ def _shard_to_full_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\nmanual_proto = _manual_proto(aval_in, axes, mesh)\nresult_type, = mlir.aval_to_ir_types(aval_out)\nsx = mlir.wrap_with_sharding_op(x, manual_proto, unspecified_dims=set(range(aval_in.ndim)))\n- sharding_proto = mesh_sharding_specs(mesh.shape, mesh.axis_names)(aval_in, axes).sharding_proto()\n+ sharding_proto = mesh_sharding_specs(mesh.shape, mesh.axis_names)(aval_out, axes).sharding_proto()\nunspecified_dims = set(range(aval_in.ndim)) - set(axes.values())\nreturn [mlir.wrap_with_shard_to_full_op(result_type, sx, sharding_proto, unspecified_dims)]\n" } ]
Python
Apache License 2.0
google/jax
Use aval_out to construct a sharding spec in shard to full The shard's dimensions might be too small and might trigger asserts, even though the shape has no influence on sharding specs. PiperOrigin-RevId: 426955706
260,303
07.02.2022 17:11:10
28,800
085e65863a5137cb1e25bfca8f494f22410bffb4
Update compilation cache logging to log individual hashes as well as cumulative hash
[ { "change_type": "MODIFY", "old_path": "jax/experimental/compilation_cache/compilation_cache.py", "new_path": "jax/experimental/compilation_cache/compilation_cache.py", "diff": "@@ -58,8 +58,14 @@ def put_executable(module_name, xla_computation, compile_options,\nserialized_executable = backend.serialize_executable(executable)\n_cache.put(cache_key, serialized_executable)\n-def _log_cache_key_hash(hash_obj, last_serialized: str):\n+def _log_cache_key_hash(hash_obj, last_serialized: str, hashfn):\nif logging.vlog_is_on(1):\n+ # Log the hash of just this entry\n+ fresh_hash_obj = hashlib.sha256()\n+ hashfn(fresh_hash_obj)\n+ logging.vlog(1, \"get_cache_key hash of serialized %s: %s\", last_serialized,\n+ fresh_hash_obj.digest().hex())\n+ # Log the cumulative hash\nlogging.vlog(1, \"get_cache_key hash after serializing %s: %s\",\nlast_serialized, hash_obj.digest().hex())\n@@ -73,7 +79,24 @@ def get_cache_key(xla_computation, compile_options, backend) -> str:\nTypical return value example:\n'14ac577cdb2ef6d986078b4054cc9893a9a14a16dbb0d8f37b89167c1f1aacdf'\n\"\"\"\n+ entries = [\n+ (\"computation\",\n+ lambda hash_obj: _hash_computation(hash_obj, xla_computation)),\n+ (\"compile_options\",\n+ lambda hash_obj: _hash_compile_options(hash_obj, compile_options)),\n+ (\"jax_lib version\",\n+ lambda hash_obj: hash_obj.update(bytes(jax._src.lib.version))),\n+ (\"the backend\", lambda hash_obj: _hash_platform(hash_obj, backend)),\n+ (\"XLA flags\", _hash_xla_flags),\n+ ]\n+\nhash_obj = hashlib.sha256()\n+ for name, hashfn in entries:\n+ hashfn(hash_obj)\n+ _log_cache_key_hash(hash_obj, name, hashfn)\n+ return hash_obj.digest().hex()\n+\n+def _hash_computation(hash_obj, xla_computation):\n# The HLO op_name metadata sometimes includes Python function pointers,\n# which cause spurious cache misses. Scrub anything that looks like a\n# function pointer. Example op_name metadata:\n@@ -88,21 +111,6 @@ def get_cache_key(xla_computation, compile_options, backend) -> str:\nserialized_hlo = xla_computation.as_serialized_hlo_module_proto()\nscrubbed_hlo = re.sub(b\" at 0x[a-f0-9]+>\", b\" at 0x...>\", serialized_hlo)\nhash_obj.update(scrubbed_hlo)\n- _log_cache_key_hash(hash_obj, \"computation\")\n-\n- _hash_compile_options(hash_obj, compile_options)\n- _log_cache_key_hash(hash_obj, \"compile_options\")\n-\n- hash_obj.update(bytes(jax._src.lib.version))\n- _log_cache_key_hash(hash_obj, \"jax_lib version\")\n-\n- _hash_platform(hash_obj, backend)\n- _log_cache_key_hash(hash_obj, \"the backend\")\n-\n- _hash_xla_flags(hash_obj)\n- _log_cache_key_hash(hash_obj, \"XLA flags\")\n-\n- return hash_obj.digest().hex()\ndef _hash_compile_options(hash_obj, compile_options_obj):\nassert len(dir(compile_options_obj)) == 31,(f\"Unexpected number of CompileOption fields: \"\n" } ]
Python
Apache License 2.0
google/jax
Update compilation cache logging to log individual hashes as well as cumulative hash
260,330
08.02.2022 13:28:41
-3,600
c07a0f11395b07caa3660d0186e58f8a1752eab7
Add test and jet-primitive for dynamic_slice
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -238,6 +238,7 @@ deflinear(lax.reshape_p)\ndeflinear(lax.rev_p)\ndeflinear(lax.transpose_p)\ndeflinear(lax.slice_p)\n+deflinear(lax.dynamic_slice_p)\ndeflinear(lax.reduce_sum_p)\ndeflinear(lax.reduce_window_sum_p)\ndeflinear(lax.fft_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/jet_test.py", "new_path": "tests/jet_test.py", "diff": "@@ -303,6 +303,8 @@ class JetTest(jtu.JaxTestCase):\ndef test_cummax(self): self.unary_check(partial(lax.cummax, axis=0))\n@jtu.skip_on_devices(\"tpu\")\ndef test_cummin(self): self.unary_check(partial(lax.cummin, axis=0))\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_dynamic_slice(self): self.unary_check(partial(lax.dynamic_slice, start_indices=(0,0), slice_sizes=(1,1)))\n@jtu.skip_on_devices(\"tpu\")\n" } ]
Python
Apache License 2.0
google/jax
Add test and jet-primitive for dynamic_slice
260,424
10.01.2022 12:25:47
0
0042edb5f444462cdf4d00d3c83c956087fa710a
Checkify: rename some symbols and add some docstrings.
[ { "change_type": "MODIFY", "old_path": "docs/jax.experimental.rst", "new_path": "docs/jax.experimental.rst", "diff": "@@ -28,3 +28,7 @@ Experimental APIs\nenable_x64\ndisable_x64\n+\n+ jax.experimental.checkify.checkify\n+ jax.experimental.checkify.check\n+ jax.experimental.checkify.check_error\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -16,7 +16,7 @@ import enum\nfrom dataclasses import dataclass\nfrom functools import partial\nimport itertools as it\n-from typing import Union, Optional, Callable, Dict, Tuple, TypeVar, Set, FrozenSet\n+from typing import Union, Optional, Callable, Dict, Tuple, TypeVar, FrozenSet\nimport numpy as np\n@@ -54,13 +54,18 @@ def setnewattr(obj, name, val):\n## Error value data type and functional assert.\n+Bool = Union[bool, core.Tracer]\n+Int = Union[int, core.Tracer]\n+\n+\n@dataclass(frozen=True)\nclass Error:\n- err: Union[bool, core.Tracer]\n- code: Union[int, core.Tracer]\n+ err: Bool\n+ code: Int\nmsgs: Dict[int, str]\ndef get(self) -> Optional[str]:\n+ \"\"\"Returns error message is error happened, None if no error happened.\"\"\"\nassert np.shape(self.err) == np.shape(self.code)\nif np.size(self.err) == 1:\nif self.err:\n@@ -71,6 +76,12 @@ class Error:\nfor idx, e in np.ndenumerate(self.err) if e) or None\nreturn None\n+ def throw(self):\n+ \"\"\"Throw ValueError with error message if error happened.\"\"\"\n+ err = self.get()\n+ if err:\n+ raise ValueError(err)\n+\nregister_pytree_node(Error,\nlambda e: ((e.err, e.code), tuple(sorted(e.msgs.items()))),\nlambda msgs, data: Error(*data, dict(msgs))) # type: ignore\n@@ -79,9 +90,6 @@ init_error = Error(False, 0, {})\nnext_code = it.count(1).__next__ # globally unique ids, could be uuid4\n-Bool = Union[bool, core.Tracer]\n-Int = Union[int, core.Tracer]\n-\ndef assert_func(error: Error, pred: Bool, msg: str) -> Error:\ncode = next_code()\nout_err = error.err | jnp.logical_not(pred)\n@@ -229,26 +237,86 @@ def checkify_fun_to_jaxpr(f, error, enabled_errors, in_avals):\n## assert primitive\n-def assert_(pred: Bool, msg: str) -> None:\n+def check(pred: Bool, msg: str) -> None:\n+ \"\"\"Check a condition, add an error with msg if condition is False.\n+\n+ This is an effectful operation, and can't be staged (jitted/scanned/...).\n+ Before staging a function with checks, ``checkify`` it!\n+\n+ Args:\n+ pred: if False, an error is added.\n+ msg: error message if error is added.\n+\n+ For example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+ >>> from jax.experimental import checkify\n+ >>> def f(x):\n+ ... checkify.check(x!=0, \"cannot be zero!\")\n+ ... return 1/x\n+ >>> checked_f = checkify.checkify(f)\n+ >>> err, out = jax.jit(checked_f)(0)\n+ >>> err.throw() # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ ValueError: cannot be zero! (check failed at ...)\n+\n+ \"\"\"\nif not is_scalar_pred(pred):\n- raise TypeError(f\"assert_ takes a scalar pred as argument, got {pred}\")\n+ raise TypeError(f'check takes a scalar pred as argument, got {pred}')\ncode = next_code()\n- return assert2_(pred, code, {code: msg})\n+ msg += f' (check failed at {summary()})'\n+ return check_error(Error(jnp.logical_not(pred), code, {code: msg}))\ndef is_scalar_pred(pred) -> bool:\nreturn (isinstance(pred, bool) or\nisinstance(pred, jnp.ndarray) and pred.shape == () and\npred.dtype == jnp.dtype('bool'))\n-def assert2_(pred: Bool, code: Int, msgs: Dict[int, str]) -> None:\n- return assert_p.bind(pred, code, msgs=msgs)\n-\n-assert_p = core.Primitive('assert')\n+def check_error(error: Error) -> None:\n+ \"\"\"Check if an error has occurred.\n+\n+ When running in an un-staged function, this will throw the error\n+ if an error has occured.\n+ When running in a staged function, the error will be threaded back\n+ into the function, so it can be functionalized later.\n+\n+ This is useful when you want to re-check an error after you've\n+ functionalized a function.\n+\n+ Args:\n+ error: Error to check\n+\n+ For example:\n+\n+ >>> import jax\n+ >>> from jax.experimental import checkify\n+ >>> def f(x):\n+ ... checkify.check(x>0, \"must be positive!\")\n+ ... return x\n+ >>> def with_inner_jit(x):\n+ ... checked_f = checkify.checkify(f)\n+ ... # a checkified function can be jitted\n+ ... error, out = jax.jit(checked_f)(x)\n+ ... checkify.check_error(error)\n+ ... return out\n+ >>> _ = with_inner_jit(1) # no failed check\n+ >>> with_inner_jit(-1) # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ ValueError: must be positive!\n+ >>> # can re-checkify\n+ >>> error, _ = checkify.checkify(with_inner_jit)(-1)\n+ \"\"\"\n+ return assert_p.bind(~error.err, error.code, msgs=error.msgs)\n+\n+assert_p = core.Primitive('assert') # TODO: rename to check?\nassert_p.multiple_results = True # zero results\n@assert_p.def_impl\ndef assert_impl(pred, code, *, msgs):\n- assert pred, msgs[int(code)]\n+ Error(~pred, code, msgs).throw()\nreturn []\n@assert_p.def_abstract_eval\n@@ -483,8 +551,9 @@ add_nan_check(lax.select_p)\nadd_nan_check(lax.max_p)\nadd_nan_check(lax.min_p)\n+\ndef assert_discharge_rule(error, enabled_errors, pred, code, *, msgs):\n- if ErrorCategory.ASSERT not in enabled_errors:\n+ if ErrorCategory.USER_CHECK not in enabled_errors:\nreturn [], error\nout_err = error.err | jnp.logical_not(pred)\n@@ -495,16 +564,65 @@ error_checks[assert_p] = assert_discharge_rule\n## checkify api\n-ErrorCategory = enum.Enum('ErrorCategory', ['NAN', 'OOB', 'DIV', 'ASSERT'])\n+ErrorCategory = enum.Enum('ErrorCategory', ['NAN', 'OOB', 'DIV', 'USER_CHECK'])\n-float_errors = {ErrorCategory.NAN, ErrorCategory.DIV}\n-index_errors = {ErrorCategory.OOB}\n+float_errors = frozenset({ErrorCategory.NAN, ErrorCategory.DIV})\n+index_errors = frozenset({ErrorCategory.OOB})\nautomatic_errors = float_errors | index_errors\n-user_asserts = {ErrorCategory.ASSERT}\n+user_checks = frozenset({ErrorCategory.USER_CHECK})\nOut = TypeVar('Out')\n-def checkify(fun: Callable[..., Out], errors: Set[ErrorCategory] = user_asserts\n+\n+\n+def checkify(fun: Callable[..., Out],\n+ errors: FrozenSet[ErrorCategory] = user_checks\n) -> Callable[..., Tuple[Error, Out]]:\n+ \"\"\"Check for run-time errors in ``fun``.\n+\n+ Run-time errors are either user-added ``checkify.check`` assertions, or\n+ automatically added checks like NaN checks, depending on the ``errors``\n+ argument.\n+\n+ The returned function will return an Error object along with the output of\n+ the function. ``err.get()`` will either return ``None`` (if no error occurred)\n+ or a string containing an error message. This error message will correspond to\n+ the first error which occurred.\n+\n+ The kinds of errors are:\n+ - ErrorCategory.USER_CHECK: a ``checkify.check`` predicate evaluated\n+ to False.\n+ - ErrorCategory.NAN: a floating-point operation generated a NaN value\n+ as output.\n+ - ErrorCategory.DIV: division by zero\n+ - ErrorCategory.OOB: an indexing operation was out-of-bounds\n+\n+ Multiple categories can be enabled together (eg. ``errors={ErrorCategory.NAN,\n+ ErrorCategory.OOB}``).\n+\n+ Args:\n+ fun: Callable which can contain user checks (see ``check``).\n+ errors: Enabled errors. Options are NAN, OOB, DIV. By default USER_CHECK is\n+ enabled.\n+ Returns:\n+ A function with output signature (Error, out)\n+\n+ For example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as jnp\n+ >>> from jax.experimental import checkify\n+ >>>\n+ >>> @jax.jit\n+ ... def f(x):\n+ ... y = jnp.sin(x)\n+ ... return x+y\n+ >>> err, out = checkify.checkify(f, errors=checkify.float_errors)(jnp.inf)\n+ >>> err.throw() # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ ValueError: nan generated by primitive sin\n+\n+ \"\"\"\nif not errors:\nraise ValueError('Checkify needs to be called with at least one enabled'\n' ErrorCategory, was called with an empty errors set.')\n@@ -513,7 +631,7 @@ def checkify(fun: Callable[..., Out], errors: Set[ErrorCategory] = user_asserts\ndef checked_fun(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\nf, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n- (err, code, out_flat), msgs = checkify_flat(f, frozenset(errors), *args_flat)\n+ (err, code, out_flat), msgs = checkify_flat(f, errors, *args_flat)\nout = tree_unflatten(out_tree(), out_flat)\nreturn Error(err, code, msgs), out\nreturn checked_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -19,20 +19,21 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n-import jax.numpy as jnp\nfrom jax import lax\n+import jax._src.test_util as jtu\nfrom jax.config import config\nfrom jax.experimental import checkify\n-import jax._src.test_util as jtu\n+import jax.numpy as jnp\nconfig.parse_flags_with_absl()\nclass CheckifyTransformTests(jtu.JaxTestCase):\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\nfor jit in [False, True]))\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_jit_nan(self, jit):\ndef f(x1, x2):\ny1 = jnp.sin(x1)\n@@ -47,7 +48,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(3., jnp.inf)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n@@ -67,7 +68,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.arange(3), 5)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_updatefn={update_fn}\", \"update_fn\": update_fn}\n@@ -85,7 +86,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.arange(3), 3)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n@@ -106,12 +107,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, _ = checked_f(jnp.array([1, jnp.inf, 1]), jnp.array([1, jnp.inf, 1]))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive div')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive div\")\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\nfor jit in [False, True]))\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_jit_multi(self, jit):\ndef f(x, i):\ny = x[i]\n@@ -128,12 +129,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# oob error\nerr, _ = checked_f(jnp.array([0., 1., 2.]), 5)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n# nan error\nerr, _ = checked_f(jnp.array([0., 1., jnp.inf]), 2)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive cos')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive cos\")\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_jit={}\".format(jit), \"jit\": jit}\n@@ -150,9 +151,9 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# both oob and nan error, but oob happens first\nerr, _ = checked_f(jnp.array([0., 1., jnp.inf]), 5)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'out-of-bounds indexing')\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_pmap_basic(self):\nif len(jax.devices()) < 2:\nraise unittest.SkipTest(\"requires at least 2 devices\")\n@@ -171,9 +172,9 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nys = jnp.array([3., jnp.inf])\nerr, _ = checked_f(xs, ys)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_cond_basic(self):\n@jax.jit\ndef f(x):\n@@ -183,17 +184,17 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nchecked_f = checkify.checkify(f, errors=checkify.float_errors)\n- err, y = checked_f(3.)\n+ err, _ = checked_f(3.)\nself.assertIs(err.get(), None)\n- err, y = checked_f(jnp.inf)\n+ err, _ = checked_f(jnp.inf)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n- err, y = checked_f(-jnp.inf)\n+ err, _ = checked_f(-jnp.inf)\nself.assertIs(err.get(), None)\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_scan_map(self):\ndef scan_body(_, x):\nreturn None, jnp.sin(x)\n@@ -217,7 +218,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\nself.assertArraysEqual(ch_outs, outs)\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_scan_carry(self):\ndef scan_body(carry, x):\ncarry = carry-1.\n@@ -376,23 +377,23 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\ndef test_empty_enabled_errors(self):\n- with self.assertRaisesRegex(ValueError, 'called with an empty errors set'):\n+ with self.assertRaisesRegex(ValueError, \"called with an empty errors set\"):\ncheckify.checkify(lambda x: x, errors={})\n@parameterized.named_parameters(\n- (\"assert\", checkify.user_asserts, \"must be negative!\"),\n+ (\"assert\", checkify.user_checks, \"must be negative!\"),\n(\"div\", {checkify.ErrorCategory.DIV}, \"divided by zero\"),\n(\"nan\", {checkify.ErrorCategory.NAN}, \"nan generated\"),\n(\"oob\", checkify.index_errors, \"out-of-bounds indexing\"),\n(\"automatic_errors\", checkify.automatic_errors, \"divided by zero\"),\n)\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_enabled_errors(self, error_set, expected_error):\ndef multi_errors(x):\nx = x/0 # DIV\nx = jnp.sin(x) # NAN\nx = x[500] # OOB\n- checkify.assert_(x < 0, \"must be negative!\") # ASSERT\n+ checkify.check(x < 0, \"must be negative!\") # ASSERT\nreturn x\nx = jnp.ones((2,))\n@@ -400,7 +401,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), expected_error)\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_post_process_call(self):\n@partial(checkify.checkify, errors=checkify.float_errors)\ndef g(x):\n@@ -410,9 +411,9 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn f(jnp.inf)\nerr, _ = g(2.)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n- @jtu.skip_on_devices('tpu')\n+ @jtu.skip_on_devices(\"tpu\")\ndef test_post_process_map(self):\n@partial(checkify.checkify, errors=checkify.float_errors)\ndef g(x):\n@@ -422,21 +423,22 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn f(jnp.array([jnp.inf]))[0]\nerr, _ = g(2.)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n+\ndef test_assert_primitive_impl(self):\ndef f():\n- checkify.assert_(False, \"hi\")\n+ checkify.check(False, \"hi\")\n- with self.assertRaisesRegex(AssertionError, \"hi\"):\n+ with self.assertRaisesRegex(ValueError, \"hi\"):\nf()\ndef test_assert_primitive_(self):\n@jax.jit\ndef f():\n- checkify.assert_(False, \"hi\")\n+ checkify.check(False, \"hi\")\nwith self.assertRaisesRegex(Exception, \"can't be staged\"):\nf()\n@@ -444,30 +446,30 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_assert_discharging(self):\n@checkify.checkify\ndef f(x):\n- checkify.assert_(x > 0, \"must be positive!\")\n+ checkify.check(x > 0, \"must be positive!\")\nreturn jnp.log(x)\n- err, y = f(1.)\n+ err, _ = f(1.)\nself.assertIsNone(err.get())\n- err, y = f(0.)\n+ err, _ = f(0.)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"must be positive\")\nf = jax.jit(f)\n- err, y = f(1.)\n+ err, _ = f(1.)\nself.assertIsNone(err.get())\n- err, y = f(0.)\n+ err, _ = f(0.)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"must be positive\")\n- def test_assert2(self):\n+ def test_check_error(self):\ndef f(pred): # note: data dependence needed!\n- checkify.assert2_(pred, 0, {0: \"hi\"})\n+ checkify.check_error(checkify.Error(~pred, 0, {0: \"hi\"}))\n- with self.assertRaisesRegex(AssertionError, \"hi\"):\n+ with self.assertRaisesRegex(ValueError, \"hi\"):\nf(False)\nf = checkify.checkify(f)\n@@ -483,21 +485,21 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nf = jax.jit(f)\ndef jitted_f(*args):\nerr, out = f(*args)\n- checkify.assert2_(~err.err, err.code, err.msgs)\n+ checkify.check_error(err)\nreturn out\nreturn jitted_f\n@ejit\ndef f(pred):\nassert python_should_be_running\n- checkify.assert_(pred, \"foo\")\n+ checkify.check(pred, \"foo\")\npython_should_be_running = True\nf(True)\npython_should_be_running = False\nf(True)\n- with self.assertRaisesRegex(AssertionError, \"foo\"):\n+ with self.assertRaisesRegex(ValueError, \"foo\"):\nf(False)\n" } ]
Python
Apache License 2.0
google/jax
Checkify: rename some symbols and add some docstrings.
260,424
08.02.2022 19:33:55
0
010eb82ad01a08f8b9a17e6b2f39676bc7066eb6
Rename wrapper functions to always refer to the JAX api function. eg. batched_fun -> vmap_fun
[ { "change_type": "MODIFY", "old_path": "jax/_src/api.py", "new_path": "jax/_src/api.py", "diff": "@@ -1544,7 +1544,7 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None, axis_size=None) -> F:\n@wraps(fun, docstr=docstr)\n@api_boundary\n- def batched_fun(*args, **kwargs):\n+ def vmap_f(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs), is_leaf=batching.is_vmappable)\nf = lu.wrap_init(fun)\nflat_fun, out_tree = batching.flatten_fun_for_vmap(f, in_tree)\n@@ -1558,7 +1558,7 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None, axis_size=None) -> F:\n).call_wrapped(*args_flat)\nreturn tree_unflatten(out_tree(), out_flat)\n- return batched_fun\n+ return vmap_f\ndef _mapped_axis_size(tree, vals, dims, name, *, kws=False):\nif not vals:\n@@ -1965,7 +1965,7 @@ def _get_f_mapped(\ndonate_tuple: Tuple[int],\nglobal_arg_shapes: Optional[Tuple[Tuple[int, ...], ...]],\n):\n- def f_pmapped(*args, **kwargs):\n+ def pmap_f(*args, **kwargs):\np = _prepare_pmap(\nfun, in_axes, out_axes, static_broadcasted_tuple, donate_tuple,\nglobal_arg_shapes, args, kwargs)\n@@ -1978,7 +1978,7 @@ def _get_f_mapped(\nglobal_arg_shapes=p.global_arg_shapes_flat)\nreturn p.out_tree, out\n- return f_pmapped\n+ return pmap_f\ndef _shared_code_pmap(fun, axis_name, static_broadcasted_argnums,\n@@ -2022,7 +2022,7 @@ def _python_pmap(\n@wraps(fun)\n@api_boundary\n- def f_pmapped(*args, **kwargs):\n+ def pmap_f(*args, **kwargs):\nf_pmapped_ = _get_f_mapped(\nfun=fun,\naxis_name=axis_name,\n@@ -2038,11 +2038,11 @@ def _python_pmap(\nout_tree, out_flat = f_pmapped_(*args, **kwargs)\nreturn tree_unflatten(out_tree(), out_flat)\n- f_pmapped.lower = _pmap_lower(\n+ pmap_f.lower = _pmap_lower(\nfun, axis_name, in_axes, out_axes, static_broadcasted_tuple, devices,\nbackend, axis_size, global_arg_shapes, donate_tuple)\n- return f_pmapped\n+ return pmap_f\nclass _PmapFastpathData(NamedTuple):\n@@ -2133,13 +2133,13 @@ def _cpp_pmap(\ncpp_mapped_f = pmap_lib.pmap(fun, cache_miss,\nstatic_broadcasted_tuple, pxla._shard_arg)\n- f_pmapped = wraps(fun)(cpp_mapped_f)\n+ pmap_f = wraps(fun)(cpp_mapped_f)\n- f_pmapped.lower = _pmap_lower(\n+ pmap_f.lower = _pmap_lower(\nfun, axis_name, in_axes, out_axes, static_broadcasted_tuple, devices,\nbackend, axis_size, global_arg_shapes, donate_tuple)\n- return f_pmapped\n+ return pmap_f\ndef _pmap_lower(fun, axis_name, in_axes, out_axes, static_broadcasted_tuple,\n@@ -2714,7 +2714,7 @@ def make_jaxpr(fun: Callable,\n@wraps(fun)\n@api_boundary\n- def jaxpr_maker(*args, **kwargs):\n+ def make_jaxpr_f(*args, **kwargs):\nf = lu.wrap_init(fun)\nif static_argnums:\ndyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\n@@ -2733,8 +2733,8 @@ def make_jaxpr(fun: Callable,\nreturn closed_jaxpr, tree_unflatten(out_tree(), out_shapes_flat)\nreturn closed_jaxpr\n- jaxpr_maker.__name__ = f\"make_jaxpr({jaxpr_maker.__name__})\"\n- return jaxpr_maker\n+ make_jaxpr_f.__name__ = f\"make_jaxpr({make_jaxpr.__name__})\"\n+ return make_jaxpr_f\ndef device_put(x, device: Optional[xc.Device] = None):\n@@ -3149,7 +3149,7 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n\"\"\"\n@wraps(fun)\n@api_boundary\n- def fun_remat(*args, **kwargs):\n+ def remat_f(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\nflat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\nout_flat = pe.remat_call(flat_fun, *args_flat, name=flat_fun.__name__,\n@@ -3157,7 +3157,7 @@ def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\ndifferentiated=False,\npolicy=policy)\nreturn tree_unflatten(out_tree(), out_flat)\n- return fun_remat\n+ return remat_f\nremat = checkpoint # type: ignore\ndef named_call(\n@@ -3194,13 +3194,13 @@ def named_call(\n_, in_tree = tree_flatten(())\n@functools.wraps(fun)\n- def named_f(*args, **kwargs):\n+ def named_call_f(*args, **kwargs):\nlu_f = lu.wrap_init(lambda: fun(*args, **kwargs))\nflat_f, out_tree = flatten_fun_nokwargs(lu_f, in_tree)\nout_flat = core.named_call_p.bind(flat_f, name=name)\nreturn tree_unflatten(out_tree(), out_flat)\n- return named_f\n+ return named_call_f\ndef invertible(fun: Callable) -> Callable:\n\"\"\"Asserts that the decorated function is invertible.\n" } ]
Python
Apache License 2.0
google/jax
Rename wrapper functions to always refer to the JAX api function. eg. batched_fun -> vmap_fun
260,424
08.02.2022 20:41:19
0
4d0db5d9759b855a5751bf66ade04a73e5c71f66
Fix build and address suggestion
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -292,16 +292,18 @@ def check_error(error: Error) -> None:\ncannot be staged out by `jit`, `pmap`, `scan`, etc. Both also can be\nfunctionalized by using `checkify`.\n- But unlike `check`, this function is like a direct inverse of `checkify`: whereas\n- `checkify` takes as input a function which can raise a Python Exception and\n- produces a new function without that effect but which produces an `Error`\n- value as output, this `check_error` function can accept an `Error` value as\n- input and can produce the side-effect of raising an Exception. That is, while\n- `checkify` goes from functionalizable Exception effect to error value, this\n- `check_error` goes from error value to functionalizable Exception effect.\n-\n- `check_error` is useful when you want to turn checks represented by an `Error` value\n- (produced by functionalizing `check`s via `checkify`) back into Python Exceptions.\n+ But unlike `check`, this function is like a direct inverse of `checkify`:\n+ whereas `checkify` takes as input a function which can raise a Python\n+ Exception and produces a new function without that effect but which\n+ produces an `Error` value as output, this `check_error` function can accept\n+ an `Error` value as input and can produce the side-effect of raising an\n+ Exception. That is, while `checkify` goes from functionalizable Exception\n+ effect to error value, this `check_error` goes from error value to\n+ functionalizable Exception effect.\n+\n+ `check_error` is useful when you want to turn checks represented by an\n+ `Error` value (produced by functionalizing `check`s via `checkify`) back\n+ into Python Exceptions.\nArgs:\nerror: Error to check\n@@ -593,7 +595,7 @@ Out = TypeVar('Out')\ndef checkify(fun: Callable[..., Out],\n- errors: Set[ErrorCategory] = user_checks\n+ errors: FrozenSet[ErrorCategory] = user_checks\n) -> Callable[..., Tuple[Error, Out]]:\n\"\"\"Functionalize `check` calls in `fun`, and optionally add run-time error checks.\n@@ -601,10 +603,10 @@ def checkify(fun: Callable[..., Out],\nautomatically added checks like NaN checks, depending on the ``errors``\nargument.\n- The returned function will return an Error object `err` along with the output of\n- the original function. ``err.get()`` will either return ``None`` (if no error occurred)\n- or a string containing an error message. This error message will correspond to\n- the first error which occurred.\n+ The returned function will return an Error object `err` along with the output\n+ of the original function. ``err.get()`` will either return ``None`` (if no\n+ error occurred) or a string containing an error message. This error message\n+ will correspond to the first error which occurred.\nThe kinds of errors are:\n- ErrorCategory.USER_CHECK: a ``checkify.check`` predicate evaluated\n@@ -614,17 +616,21 @@ def checkify(fun: Callable[..., Out],\n- ErrorCategory.DIV: division by zero\n- ErrorCategory.OOB: an indexing operation was out-of-bounds\n- Multiple categories can be enabled together by creating a `Set` (eg. ``errors={ErrorCategory.NAN,\n- ErrorCategory.OOB}``).\n+ Multiple categories can be enabled together by creating a `Set` (eg.\n+ ``errors={ErrorCategory.NAN, ErrorCategory.OOB}``).\nArgs:\nfun: Callable which can contain user checks (see ``check``).\n- errors: Enabled errors. Options are NAN, OOB, DIV. By default USER_CHECK is\n- enabled.\n+ errors: A set of ErrorCategory values which defines the set of enabled\n+ checks. By default only explicit ``check``s are enabled\n+ (``{ErrorCategory.USER_CHECK}``). You can also for example enable NAN and\n+ DIV errors through passing the ``checkify.float_errors`` set, or for\n+ example combine multiple sets through set operations\n+ (``checkify.float_errors|checkify.user_checks``)\nReturns:\nA function which accepts the same arguments as ``fun`` and returns as output\n- a pair where the first element is an ``Error`` value, representing any failed\n- ``check``s, and the second element is the original output of ``fun``.\n+ a pair where the first element is an ``Error`` value, representing any\n+ failed ``check``s, and the second element is the original output of ``fun``.\nFor example:\n" } ]
Python
Apache License 2.0
google/jax
Fix build and address suggestion
260,335
08.02.2022 12:45:38
28,800
d57990ecf9dcc6b37c3c240d5abe021d20d2fef9
improve pjit in/out_axis_resources pytree errors This is an application of the utilities in
[ { "change_type": "MODIFY", "old_path": "jax/_src/tree_util.py", "new_path": "jax/_src/tree_util.py", "diff": "# limitations under the License.\nimport collections\n+import difflib\nimport functools\nfrom functools import partial\nimport operator as op\nfrom typing import (Any, Callable, Hashable, Iterable, Optional, Tuple, List,\nDict, Type, TypeVar, overload, TYPE_CHECKING, NamedTuple)\n+import textwrap\nfrom jax._src.lib import pytree\n@@ -380,9 +382,10 @@ def flatten_one_level(pytree: Any) -> Tuple[List[Any], Hashable]:\nelse:\nraise ValueError(f\"can't tree-flatten type: {type(pytree)}\")\n-def prefix_errors(prefix_tree: Any, full_tree: Any\n+def prefix_errors(prefix_tree: Any, full_tree: Any,\n+ is_leaf: Optional[Callable[[Any], bool]] = None,\n) -> List[Callable[[str], ValueError]]:\n- return list(_prefix_error(KeyPath(()), prefix_tree, full_tree))\n+ return list(_prefix_error(KeyPath(()), prefix_tree, full_tree, is_leaf))\nclass KeyPathEntry(NamedTuple):\nkey: Any\n@@ -437,38 +440,59 @@ register_keypaths(list,\nregister_keypaths(dict,\nlambda dct: [GetitemKeyPathEntry(k) for k in sorted(dct)])\n-def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any\n+def _prefix_error(key_path: KeyPath, prefix_tree: Any, full_tree: Any,\n+ is_leaf: Optional[Callable[[Any], bool]] = None,\n) -> Iterable[Callable[[str], ValueError]]:\n# A leaf is a valid prefix of any tree:\n- if treedef_is_leaf(tree_structure(prefix_tree)): return\n+ if treedef_is_leaf(tree_structure(prefix_tree, is_leaf=is_leaf)): return\n# The subtrees may disagree because their roots are of different types:\nif type(prefix_tree) != type(full_tree):\nyield lambda name: ValueError(\n- \"pytree structure error: different types \"\n- f\"at {{name}}{key_path.pprint()}: \"\n- f\"prefix pytree {{name}} has type {type(prefix_tree)} \"\n- f\"where full pytree has type {type(full_tree)}.\".format(name=name))\n+ \"pytree structure error: different types at key path\\n\"\n+ f\" {{name}}{key_path.pprint()}\\n\"\n+ f\"At that key path, the prefix pytree {{name}} has a subtree of type\\n\"\n+ f\" {type(prefix_tree)}\\n\"\n+ f\"but at the same key path the full pytree has a subtree of different type\\n\"\n+ f\" {type(full_tree)}.\".format(name=name))\nreturn # don't look for more errors in this subtree\n- # Or they may disagree if their roots have different numbers of children:\n+ # Or they may disagree if their roots have different numbers of children (note\n+ # that because both prefix_tree and full_tree have the same type at this\n+ # point, and because prefix_tree is not a leaf, each can be flattened once):\nprefix_tree_children, prefix_tree_meta = flatten_one_level(prefix_tree)\nfull_tree_children, full_tree_meta = flatten_one_level(full_tree)\nif len(prefix_tree_children) != len(full_tree_children):\nyield lambda name: ValueError(\n- \"pytree structure error: different numbers of pytree children \"\n- f\"at {{name}}{key_path.pprint()}: \"\n- f\"prefix pytree {{name}} has {len(prefix_tree_children)} children where \"\n- f\"full pytree has {len(full_tree_children)} children.\".format(name=name))\n+ \"pytree structure error: different numbers of pytree children at key path\\n\"\n+ f\" {{name}}{key_path.pprint()}\\n\"\n+ f\"At that key path, the prefix pytree {{name}} has a subtree of type\\n\"\n+ f\" {type(prefix_tree)}\\n\"\n+ f\"with {len(prefix_tree_children)} children, \"\n+ f\"but at the same key path the full pytree has a subtree of the same \"\n+ f\"type but with {len(full_tree_children)} children.\".format(name=name))\nreturn # don't look for more errors in this subtree\n# Or they may disagree if their roots have different pytree metadata:\nif prefix_tree_meta != full_tree_meta:\n+ prefix_tree_meta_str = str(prefix_tree_meta)\n+ full_tree_meta_str = str(full_tree_meta)\n+ metadata_diff = textwrap.indent(\n+ '\\n'.join(difflib.ndiff(prefix_tree_meta_str.splitlines(),\n+ full_tree_meta_str.splitlines())),\n+ prefix=\" \")\nyield lambda name: ValueError(\n- \"pytree structure error: different pytree metadata \"\n- f\"at {{name}}{key_path.pprint()}: \"\n- f\"prefix pytree {{name}} has metadata {prefix_tree_meta} where \"\n- f\"full pytree has metadata {full_tree_meta}.\".format(name=name))\n+ \"pytree structure error: different pytree metadata at key path\\n\"\n+ f\" {{name}}{key_path.pprint()}\\n\"\n+ f\"At that key path, the prefix pytree {{name}} has a subtree of type\\n\"\n+ f\" {type(prefix_tree)}\\n\"\n+ f\"with metadata\\n\"\n+ f\" {prefix_tree_meta_str}\\n\"\n+ f\"but at the same key path the full pytree has a subtree of the same \"\n+ f\"type but with metadata\\n\"\n+ f\" {full_tree_meta_str}\\n\"\n+ f\"so the diff in the metadata at these pytree nodes is\\n\"\n+ f\"{metadata_diff}\".format(name=name))\nreturn # don't look for more errors in this subtree\n# If the root types and numbers of children agree, there must be an error\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "@@ -40,7 +40,9 @@ from jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters.sharded_jit import PartitionSpec\nfrom jax._src.lib import xla_client as xc\n-from jax.tree_util import tree_map, tree_flatten, tree_unflatten\n+from jax.tree_util import (tree_map, tree_flatten, tree_unflatten,\n+ treedef_is_leaf, tree_structure)\n+from jax._src.tree_util import prefix_errors\nfrom jax._src.util import (extend_name_stack, HashableFunction, safe_zip,\nwrap_name, wraps, distributed_debug_log,\nsplit_list, cache, tuple_insert)\n@@ -293,11 +295,60 @@ def flatten_axis_resources(what, tree, axis_resources, tupled_args):\ntry:\nreturn tuple(flatten_axes(what, tree, axis_resources, tupled_args=tupled_args))\nexcept ValueError:\n- pass\n+ pass # Raise a tree prefix error below\n+\n+ # Tree leaves are always valid prefixes, so if there was a prefix error as\n+ # assumed here, axis_resources must not be a leaf.\n+ assert not treedef_is_leaf(tree_structure(axis_resources))\n+\n+ # Check the type directly rather than using isinstance because of namedtuples.\n+ if tupled_args and (type(axis_resources) is not tuple or\n+ len(axis_resources) != len(tree.children())):\n+ # We know axis_resources is meant to be a tuple corresponding to the args\n+ # tuple, but while it is a non-leaf pytree, either it wasn't a tuple or it\n+ # wasn't the right length.\n+ msg = (f\"{what} specification must be a tree prefix of the positional \"\n+ f\"arguments tuple passed to the `pjit`-decorated function. In \"\n+ f\"particular, {what} must either be a None, a PartitionSpec, or \"\n+ f\"a tuple of length equal to the number of positional arguments.\")\n+ # If `tree` represents an args tuple, then `axis_resources` must be a tuple.\n+ # TODO(mattjj,apaszke): disable implicit list casts, remove 'or list' below\n+ if type(axis_resources) is not tuple:\n+ msg += f\" But {what} is not a tuple: got {type(axis_resources)} instead.\"\n+ elif len(axis_resources) != len(tree.children()):\n+ msg += (f\" But {what} is the wrong length: got a tuple or list of length \"\n+ f\"{len(axis_resources)} for an args tuple of length \"\n+ f\"{len(tree.children())}.\")\n+\n+ # As an extra hint, let's check if the user just forgot to wrap\n+ # in_axis_resources in a singleton tuple.\n+ if len(tree.children()) == 1:\n+ try: flatten_axes(what, tree, (axis_resources,))\n+ except ValueError: pass # That's not the issue.\n+ else:\n+ msg += (f\" Given the corresponding argument being \"\n+ f\"passed, it looks like {what} might need to be wrapped in \"\n+ f\"a singleton tuple.\")\n+\n+ raise ValueError(msg)\n+\n# Replace axis_resources with unparsed versions to avoid revealing internal details\n- flatten_axes(what, tree, tree_map(lambda parsed: parsed.user_spec, axis_resources),\n- tupled_args=tupled_args)\n- raise AssertionError(\"Please open a bug request!\") # This should be unreachable\n+ axis_tree = tree_map(lambda parsed: parsed.user_spec, axis_resources)\n+\n+ # Because ecause we only have the `tree` treedef and not the full pytree here,\n+ # we construct a dummy tree to compare against. Revise this in callers?\n+ dummy_tree = tree_unflatten(tree, [PytreeLeaf()] * tree.num_leaves)\n+ errors = prefix_errors(axis_tree, dummy_tree)\n+ if errors:\n+ e = errors[0] # Only show information about the first disagreement found.\n+ raise e(what)\n+\n+ # At this point we've failed to find a tree prefix error.\n+ assert False, \"Please open a bug report!\" # This should be unreachable.\n+\n+class PytreeLeaf:\n+ def __repr__(self): return \"pytree leaf\"\n+\n@lu.cache\ndef _pjit_jaxpr(fun, mesh, local_in_avals,\n@@ -472,8 +523,7 @@ class CanonicalizedParsedPartitionSpec(ParsedPartitionSpec):\ndef _prepare_axis_resources(axis_resources,\narg_name,\nallow_unconstrained_dims=False):\n- # PyTrees don't treat None values as leaves, so we explicitly need\n- # to explicitly declare them as such\n+ # PyTrees don't treat None values as leaves, so we use an is_leaf function.\nentries, treedef = tree_flatten(axis_resources, is_leaf=lambda x: x is None)\nwhat = f\"{arg_name} leaf specifications\"\nentries = [\n" }, { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -55,4 +55,7 @@ from jax._src.tree_util import (\ntreedef_children as treedef_children,\ntreedef_is_leaf as treedef_is_leaf,\ntreedef_tuple as treedef_tuple,\n+ register_keypaths as register_keypaths,\n+ AttributeKeyPathEntry as AttributeKeyPathEntry,\n+ GetitemKeyPathEntry as GetitemKeyPathEntry,\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/pjit_test.py", "new_path": "tests/pjit_test.py", "diff": "@@ -1138,15 +1138,32 @@ class PJitErrorTest(jtu.JaxTestCase):\ndef testAxisResourcesMismatch(self):\nx = jnp.ones([])\np = [None, None, None]\n+\npjit(lambda x: x, (p,), p)([x, x, x]) # OK\n+\nerror = re.escape(\n- r\"pjit in_axis_resources specification must be a tree prefix of the \"\n- r\"corresponding value, got specification (None, None, None) for value \"\n- r\"tree PyTreeDef((*, *)). Note that pjit in_axis_resources that are \"\n- r\"non-trivial pytrees should always be wrapped in a tuple representing \"\n- r\"the argument list.\")\n+ \"pjit in_axis_resources specification must be a tree prefix of the \"\n+ \"positional arguments tuple passed to the `pjit`-decorated function. \"\n+ \"In particular, pjit in_axis_resources must either be a None, a \"\n+ \"PartitionSpec, or a tuple of length equal to the number of positional \"\n+ \"arguments. But pjit in_axis_resources is the wrong length: got a \"\n+ \"tuple or list of length 3 for an args tuple of length 2.\")\nwith self.assertRaisesRegex(ValueError, error):\n- pjit(lambda x, y: x, p, p)(x, x) # Error, but make sure we hint at tupling\n+ pjit(lambda x, y: x, p, p)(x, x)\n+\n+ Foo = namedtuple('Foo', ['x'])\n+ error = \"in_axis_resources is not a tuple.*might need to be wrapped\"\n+ with self.assertRaisesRegex(ValueError, error):\n+ pjit(lambda x: x, Foo(None), Foo(None))(Foo(x))\n+\n+ pjit(lambda x: x, (Foo(None),), Foo(None))(Foo(x)) # OK w/ singleton tuple\n+\n+ # TODO(apaszke,mattjj): Disable implicit list casts and enable this\n+ # error = (\"it looks like pjit in_axis_resources might need to be wrapped in \"\n+ # \"a singleton tuple.\")\n+ # with self.assertRaisesRegex(ValueError, error):\n+ # pjit(lambda x, y: x, p, p)([x, x, x])\n+\n# TODO(apaszke): Disable implicit list casts and enable this\n# error = re.escape(\n# r\"pjit in_axis_resources specification must be a tree prefix of the \"\n@@ -1158,10 +1175,16 @@ class PJitErrorTest(jtu.JaxTestCase):\n# r\"singleton tuple.\")\n# with self.assertRaisesRegex(ValueError, error):\n# pjit(lambda x: x, p, p)([x, x, x]) # Error, but make sure we hint at singleton tuple\n+\nerror = re.escape(\n- r\"pjit out_axis_resources specification must be a tree prefix of the \"\n- r\"corresponding value, got specification [[None, None, None], None] for \"\n- r\"value tree PyTreeDef([*, *, *]).\")\n+ \"pytree structure error: different numbers of pytree children at \"\n+ \"key path\\n\"\n+ \" pjit out_axis_resources tree root\\n\"\n+ \"At that key path, the prefix pytree pjit out_axis_resources has a \"\n+ \"subtree of type\\n\"\n+ \" <class 'list'>\\n\"\n+ \"with 2 children, but at the same key path the full pytree has a \"\n+ \"subtree of the same type but with 3 children.\")\nwith self.assertRaisesRegex(ValueError, error):\npjit(lambda x: x, (p,), [p, None])([x, x, x]) # Error, we raise a generic tree mismatch message\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_test.py", "new_path": "tests/tree_util_test.py", "diff": "@@ -439,78 +439,90 @@ class TreePrefixErrorsTest(jtu.JaxTestCase):\ndef test_different_types(self):\ne, = prefix_errors((1, 2), [1, 2])\n- expected = \"pytree structure error: different types at in_axes tree root\"\n+ expected = (\"pytree structure error: different types at key path\\n\"\n+ \" in_axes tree root\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_types_nested(self):\ne, = prefix_errors(((1,), (2,)), ([3], (4,)))\n- expected = r\"pytree structure error: different types at in_axes\\[0\\]\"\n+ expected = (\"pytree structure error: different types at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_types_multiple(self):\ne1, e2 = prefix_errors(((1,), (2,)), ([3], [4]))\n- expected = r\"pytree structure error: different types at in_axes\\[0\\]\"\n+ expected = (\"pytree structure error: different types at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e1('in_axes')\n- expected = r\"pytree structure error: different types at in_axes\\[1\\]\"\n+ expected = (\"pytree structure error: different types at key path\\n\"\n+ r\" in_axes\\[1\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e2('in_axes')\ndef test_different_num_children(self):\ne, = prefix_errors((1,), (2, 3))\nexpected = (\"pytree structure error: different numbers of pytree children \"\n- \"at in_axes tree root\")\n+ \"at key path\\n\"\n+ \" in_axes tree root\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_num_children_nested(self):\ne, = prefix_errors([[1]], [[2, 3]])\nexpected = (\"pytree structure error: different numbers of pytree children \"\n- r\"at in_axes\\[0\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_num_children_multiple(self):\ne1, e2 = prefix_errors([[1], [2]], [[3, 4], [5, 6]])\nexpected = (\"pytree structure error: different numbers of pytree children \"\n- r\"at in_axes\\[0\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e1('in_axes')\nexpected = (\"pytree structure error: different numbers of pytree children \"\n- r\"at in_axes\\[1\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[1\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e2('in_axes')\ndef test_different_metadata(self):\ne, = prefix_errors({1: 2}, {3: 4})\nexpected = (\"pytree structure error: different pytree metadata \"\n- \"at in_axes tree root\")\n+ \"at key path\\n\"\n+ \" in_axes tree root\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_metadata_nested(self):\ne, = prefix_errors([{1: 2}], [{3: 4}])\nexpected = (\"pytree structure error: different pytree metadata \"\n- r\"at in_axes\\[0\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\ndef test_different_metadata_multiple(self):\ne1, e2 = prefix_errors([{1: 2}, {3: 4}], [{3: 4}, {5: 6}])\nexpected = (\"pytree structure error: different pytree metadata \"\n- r\"at in_axes\\[0\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[0\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e1('in_axes')\nexpected = (\"pytree structure error: different pytree metadata \"\n- r\"at in_axes\\[1\\]\")\n+ \"at key path\\n\"\n+ r\" in_axes\\[1\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e2('in_axes')\ndef test_fallback_keypath(self):\ne, = prefix_errors(Special(1, [2]), Special(3, 4))\n- expected = (\"pytree structure error: different types at \"\n+ expected = (\"pytree structure error: different types at key path\\n\"\nr\" in_axes\\[<flat index 1>\\]\")\nwith self.assertRaisesRegex(ValueError, expected):\nraise e('in_axes')\n" } ]
Python
Apache License 2.0
google/jax
improve pjit in/out_axis_resources pytree errors This is an application of the utilities in #9372.
260,335
09.02.2022 11:18:40
28,800
4ce749e681d5cd9a9e302e7e6a6f27bdc9384daa
[checkify] handle custom_jvp
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -186,6 +186,34 @@ class CheckifyTrace(core.Trace):\nreturn (0, 0, *out_axes)\nreturn (err, code, *vals), (todo, out_axes_transform)\n+ def process_custom_jvp_call(self, prim, fun, jvp, tracers):\n+ in_vals = [t.val for t in tracers]\n+ e = popattr(self.main, 'error')\n+ msgs = tuple(e.msgs.items())\n+ fun, msgs1 = checkify_subtrace(fun, self.main, msgs)\n+ jvp, msgs2 = checkify_custom_jvp_subtrace(jvp, self.main, msgs)\n+ err, code, *out_vals = prim.bind(fun, jvp, e.err, e.code, *in_vals)\n+ fst, out_msgs = lu.merge_linear_aux(msgs1, msgs2)\n+ setattr(self.main, 'error', Error(err, code, out_msgs))\n+ return [CheckifyTracer(self, x) for x in out_vals]\n+\n+ def post_process_custom_jvp_call(self, out_tracers, jvp_was_run):\n+ if jvp_was_run:\n+ msg = (\"support for custom_jvp rules which close over checkify values is \"\n+ \"not implemented. If you see this, open an issue at \"\n+ \"https://github.com/google/jax/issues!\")\n+ raise NotImplementedError(msg)\n+ vals = [t.val for t in out_tracers]\n+ main = self.main\n+ e = popattr(main, 'error')\n+ err, code, main.msgs = e.err, e.code, e.msgs\n+ def todo(vals):\n+ err, code, *vals = vals\n+ setnewattr(main, 'error', Error(err, code, popattr(main, 'msgs')))\n+ trace = main.with_cur_sublevel()\n+ return [CheckifyTracer(trace, x) for x in vals]\n+ return (err, code, *vals), todo\n+\ndef _reduce_any_error(errs, codes):\nerrs_, codes_ = lax.sort_key_val(errs, codes, dimension=0)\nreturn errs_[-1], codes_[-1]\n@@ -219,6 +247,32 @@ def checkify_subtrace(main, msgs, err, code, *args):\ndel main.error\nyield (err, code, *out_vals), msgs\n+@lu.transformation_with_aux\n+def checkify_custom_jvp_subtrace(main, msgs, *args):\n+ # Like checkify_subtrace, but used specifically on the custom JVP rules\n+ # associated with a custom_jvp. This code is called in the context of a\n+ # jvp-of-checkify-of-custom_jvp. It takes both primal and tangent inputs,\n+ # flattened into a single args tuple, and similarly must produce flattened\n+ # primal and tangent outputs. Both primals and tangents include error values,\n+ # but the tangent error values are trivially zero.\n+ # The types to have in mind are:\n+ # jvp : (a -> b) -> (a, T a) -> (b, T b)\n+ # checkify : (a -> b) -> a -> Err b\n+ # jvp-of-checkify : (a -> b) -> (a, T a) -> (Err b, T (Err b))\n+ # where because Err is a pytree, we necessarily have T (Err b) = Err' (T b)\n+ # where the other Err' components are trivial (of float0 dtype).\n+ # Semantically, we don't add checks to the JVP rule. To check the result of a\n+ # JVP rule, one must instead use checkify-of-jvp. Thus this implementation\n+ # just forwards the input error and code (and trivial tangents) to the output.\n+ n, ragged = divmod(len(args), 2)\n+ assert not ragged\n+ (err,), (code,), primals = split_list(args[:n], [1, 1])\n+ (err_dot,), (code_dot,), tangents = split_list(args[n:], [1, 1])\n+ outs = yield (*primals, *tangents), {}\n+ m, ragged = divmod(len(outs), 2)\n+ assert not ragged\n+ out_primals, out_tangents = outs[:m], outs[m:]\n+ yield (err, code, *out_primals, err_dot, code_dot, *out_tangents), dict(msgs)\n# TODO take (error_aval, code_aval) instead of error here?\ndef checkify_jaxpr(jaxpr, error, enabled_errors):\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -423,7 +423,39 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn f(jnp.array([jnp.inf]))[0]\nerr, _ = g(2.)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_custom_jvp(self):\n+ @jax.custom_jvp\n+ def sin(x):\n+ return jnp.sin(x)\n+\n+ @sin.defjvp\n+ def sin_jvp(primals, tangents):\n+ (x,), (xdot,) = primals, tangents\n+ return sin(x), jnp.cos(x) * xdot\n+\n+ f = checkify.checkify(sin, errors=checkify.float_errors)\n+\n+ err, y = f(3.)\n+ self.assertIsNone(err.get())\n+ err, y = f(jnp.inf)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ # When we hit the custom jvp rule with jvp-of-checkify, no checks are added.\n+ (err, y), (errdot, ydot) = jax.jvp(f, (3.,), (1.,)) # doesn't crash\n+ self.assertIsNone(err.get()) # no error\n+ self.assertEmpty(err.msgs) # and no checks were added!\n+ self.assertEmpty(errdot.msgs)\n+ y_expected, ydot_expected = jax.jvp(jnp.sin, (3.,), (1.,))\n+ self.assertAllClose(y, y_expected)\n+ self.assertAllClose(ydot, ydot_expected)\n+\n+ # Grad doesn't crash either.\n+ x_bar = jax.grad(lambda x: f(x)[1])(3.)\n+ self.assertAllClose(x_bar, jnp.cos(3.))\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
[checkify] handle custom_jvp
260,335
09.02.2022 12:04:34
28,800
d9270b242d157ee7c578661636be2a0ed946560e
[checkify] add custom_vjp support
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -214,6 +214,21 @@ class CheckifyTrace(core.Trace):\nreturn [CheckifyTracer(trace, x) for x in vals]\nreturn (err, code, *vals), todo\n+ def process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, out_trees):\n+ in_vals = [t.val for t in tracers]\n+ e = popattr(self.main, 'error')\n+ msgs = tuple(e.msgs.items())\n+ fun, msgs1 = checkify_subtrace(fun, self.main, msgs)\n+ fwd, msgs2 = checkify_custom_vjp_subtrace(fwd, self.main, msgs)\n+ out = prim.bind(fun, fwd, bwd, e.err, e.code, *in_vals, out_trees=out_trees)\n+ fst, out_msgs = lu.merge_linear_aux(msgs1, msgs2)\n+ if fst:\n+ err, code, *out = out\n+ else:\n+ err, code = e.err, e.code # forward input error values to output\n+ setattr(self.main, 'error', Error(err, code, out_msgs))\n+ return [CheckifyTracer(self, x) for x in out]\n+\ndef _reduce_any_error(errs, codes):\nerrs_, codes_ = lax.sort_key_val(errs, codes, dimension=0)\nreturn errs_[-1], codes_[-1]\n@@ -264,6 +279,7 @@ def checkify_custom_jvp_subtrace(main, msgs, *args):\n# Semantically, we don't add checks to the JVP rule. To check the result of a\n# JVP rule, one must instead use checkify-of-jvp. Thus this implementation\n# just forwards the input error and code (and trivial tangents) to the output.\n+ del main\nn, ragged = divmod(len(args), 2)\nassert not ragged\n(err,), (code,), primals = split_list(args[:n], [1, 1])\n@@ -274,6 +290,13 @@ def checkify_custom_jvp_subtrace(main, msgs, *args):\nout_primals, out_tangents = outs[:m], outs[m:]\nyield (err, code, *out_primals, err_dot, code_dot, *out_tangents), dict(msgs)\n+@lu.transformation_with_aux\n+def checkify_custom_vjp_subtrace(main, msgs, err, code, *args):\n+ # We don't add any checks; just drop input error values.\n+ del main, err, code\n+ outs = yield args, {}\n+ yield outs, dict(msgs)\n+\n# TODO take (error_aval, code_aval) instead of error here?\ndef checkify_jaxpr(jaxpr, error, enabled_errors):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -453,10 +453,59 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertAllClose(y, y_expected)\nself.assertAllClose(ydot, ydot_expected)\n- # Grad doesn't crash either.\n+ # Grad-of-checkify doesn't crash either.\nx_bar = jax.grad(lambda x: f(x)[1])(3.)\nself.assertAllClose(x_bar, jnp.cos(3.))\n+ # Checkify-of-jvp adds checks (unlike jvp-of-checkify above).\n+ g = checkify.checkify(lambda x, xdot: jax.jvp(sin, (x,), (xdot,)),\n+ errors=checkify.float_errors)\n+ err, (y, ydot) = g(3., 1.) # doesn't crash\n+ self.assertIsNone(err.get()) # no error\n+ self.assertNotEmpty(err.msgs) # but checks were added!\n+ self.assertAllClose(y, jnp.sin(3.))\n+ self.assertAllClose(ydot, jnp.cos(3.))\n+ err, _ = g(jnp.inf, 1.)\n+ self.assertIsNotNone(err.get()) # yes error\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ @jtu.skip_on_devices(\"tpu\")\n+ def test_custom_vjp(self):\n+ @jax.custom_vjp\n+ def sin(x):\n+ return jnp.sin(x)\n+\n+ def sin_fwd(x):\n+ return jnp.sin(x), 2. * x\n+ def sin_bwd(x2, g):\n+ return jnp.cos(x2 / 2.) * g,\n+ sin.defvjp(sin_fwd, sin_bwd)\n+\n+ f = checkify.checkify(sin, errors=checkify.float_errors)\n+\n+ # no differentiation, no error\n+ err, y = f(3.)\n+ self.assertIsNone(err.get())\n+\n+ # no differentiation, yes error\n+ err, y = f(jnp.inf)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\n+ # When we hit the custom vjp rule with vjp-of-checkify, no checks are added.\n+ (err, y), f_vjp = jax.vjp(f, 3.)\n+ self.assertIsNone(err.get()) # no error\n+ self.assertEmpty(err.msgs) # and no checks were added!\n+\n+ # Checkify-of-vjp adds checks (unlike vjp-of-checkify above).\n+ err, y = checkify.checkify(jax.grad(sin), errors=checkify.float_errors)(3.)\n+ self.assertIsNone(err.get()) # no error\n+ self.assertNotEmpty(err.msgs) # but checks were added!\n+ err, y = checkify.checkify(jax.grad(sin),\n+ errors=checkify.float_errors)(jnp.inf)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
[checkify] add custom_vjp support
260,424
10.02.2022 14:28:46
0
2ba8aec2746a01c211ae7a1a49220cc103161f37
Checkify: Fix docstring formatting and polish enabled_errors sets.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -315,7 +315,7 @@ def checkify_fun_to_jaxpr(f, error, enabled_errors, in_avals):\n## assert primitive\ndef check(pred: Bool, msg: str) -> None:\n- \"\"\"Check a condition, add an error with msg if condition is False.\n+ \"\"\"Check a predicate, add an error with msg if predicate is False.\nThis is an effectful operation, and can't be staged (jitted/scanned/...).\nBefore staging a function with checks, ``checkify`` it!\n@@ -352,40 +352,42 @@ def is_scalar_pred(pred) -> bool:\npred.dtype == jnp.dtype('bool'))\ndef check_error(error: Error) -> None:\n- \"\"\"Raise an Exception if `error` represents a failure. Functionalized by `checkify`.\n+ \"\"\"Raise an Exception if ``error`` represents a failure. Functionalized by ``checkify``.\nThe semantics of this function are equivalent to:\n- def check_error(err: Error) -> None:\n- err.throw() # can raise ValueError Exception\n-\n- But unlike that implementation, `check_error` can be functionalized using\n- the `checkify` transformation.\n-\n- This function is similar to `check` but with a different signature: whereas\n- `check` takes as arguments a boolean predicate and a new error message\n- string, this function takes an `Error` value as argument. Both `check` and\n- this function raise a Python Exception on failure (a side-effect), and thus\n- cannot be staged out by `jit`, `pmap`, `scan`, etc. Both also can be\n- functionalized by using `checkify`.\n-\n- But unlike `check`, this function is like a direct inverse of `checkify`:\n- whereas `checkify` takes as input a function which can raise a Python\n- Exception and produces a new function without that effect but which\n- produces an `Error` value as output, this `check_error` function can accept\n- an `Error` value as input and can produce the side-effect of raising an\n- Exception. That is, while `checkify` goes from functionalizable Exception\n- effect to error value, this `check_error` goes from error value to\n+ >>> def check_error(err: Error) -> None:\n+ ... err.throw() # can raise ValueError\n+\n+ But unlike that implementation, ``check_error`` can be functionalized using\n+ the ``checkify`` transformation.\n+\n+ This function is similar to ``check`` but with a different signature: whereas\n+ ``check`` takes as arguments a boolean predicate and a new error message\n+ string, this function takes an ``Error`` value as argument. Both ``check``\n+ and this function raise a Python Exception on failure (a side-effect), and\n+ thus cannot be staged out by ``jit``, ``pmap``, ``scan``, etc. Both also can\n+ be functionalized by using ``checkify``.\n+\n+ But unlike ``check``, this function is like a direct inverse of ``checkify``:\n+ whereas ``checkify`` takes as input a function which can raise a Python\n+ Exception and produces a new function without that effect but which produces\n+ an ``Error`` value as output, this ``check_error`` function can accept an\n+ ``Error`` value as input and can produce the side-effect of raising an\n+ Exception. That is, while ``checkify`` goes from functionalizable Exception\n+ effect to error value, this ``check_error`` goes from error value to\nfunctionalizable Exception effect.\n- `check_error` is useful when you want to turn checks represented by an\n- `Error` value (produced by functionalizing `check`s via `checkify`) back\n- into Python Exceptions.\n+ ``check_error`` is useful when you want to turn checks represented by an\n+ ``Error`` value (produced by functionalizing ``checks`` via ``checkify``)\n+ back into Python Exceptions.\nArgs:\n- error: Error to check\n+ error: Error to check.\n- For example:\n+ For example, you might want to functionalize part of your program through\n+ checkify, stage out your functionalized code through ``jit``, then re-inject\n+ your error value outside of the ``jit``:\n>>> import jax\n>>> from jax.experimental import checkify\n@@ -663,10 +665,13 @@ error_checks[assert_p] = assert_discharge_rule\nErrorCategory = enum.Enum('ErrorCategory', ['NAN', 'OOB', 'DIV', 'USER_CHECK'])\n-float_errors = frozenset({ErrorCategory.NAN, ErrorCategory.DIV})\n-index_errors = frozenset({ErrorCategory.OOB})\n-automatic_errors = float_errors | index_errors\nuser_checks = frozenset({ErrorCategory.USER_CHECK})\n+nan_checks = frozenset({ErrorCategory.NAN})\n+index_checks = frozenset({ErrorCategory.OOB})\n+div_checks = frozenset({ErrorCategory.DIV})\n+float_checks = nan_checks | div_checks\n+automatic_checks = float_checks | index_checks\n+all_checks = automatic_checks | user_checks\nOut = TypeVar('Out')\n@@ -683,31 +688,35 @@ def checkify(fun: Callable[..., Out],\nThe returned function will return an Error object `err` along with the output\nof the original function. ``err.get()`` will either return ``None`` (if no\nerror occurred) or a string containing an error message. This error message\n- will correspond to the first error which occurred.\n+ will correspond to the first error which occurred. ``err.throw()`` will raise\n+ a ValueError with the error message if an error occurred.\n+\n+ By default only user-added ``checkify.check`` assertions are enabled. You can\n+ enable automatic checks through the ``errors`` argument.\n- The kinds of errors are:\n- - ErrorCategory.USER_CHECK: a ``checkify.check`` predicate evaluated\n- to False.\n- - ErrorCategory.NAN: a floating-point operation generated a NaN value\n+ The automatic check sets which can be enabled, and when an error is generated:\n+ - ``user_checks``: a ``checkify.check`` evaluated to False.\n+ - ``nan_checks``: a floating-point operation generated a NaN value\nas output.\n- - ErrorCategory.DIV: division by zero\n- - ErrorCategory.OOB: an indexing operation was out-of-bounds\n+ - ``div_checks``: a division by zero.\n+ - ``index_checks``: an index was out-of-bounds.\nMultiple categories can be enabled together by creating a `Set` (eg.\n- ``errors={ErrorCategory.NAN, ErrorCategory.OOB}``).\n+ ``errors={ErrorCategory.NAN, ErrorCategory.OOB}``). Multiple sets can be\n+ re-combined (eg. ``errors=float_checks|user_checks``)\nArgs:\nfun: Callable which can contain user checks (see ``check``).\nerrors: A set of ErrorCategory values which defines the set of enabled\n- checks. By default only explicit ``check``s are enabled\n- (``{ErrorCategory.USER_CHECK}``). You can also for example enable NAN and\n- DIV errors through passing the ``checkify.float_errors`` set, or for\n+ checks. By default only explicit ``checks`` are enabled\n+ (``user_checks``). You can also for example enable NAN and\n+ DIV errors by passing the ``float_checks`` set, or for\nexample combine multiple sets through set operations\n- (``checkify.float_errors|checkify.user_checks``)\n+ (``float_checks | user_checks``)\nReturns:\nA function which accepts the same arguments as ``fun`` and returns as output\n- a pair where the first element is an ``Error`` value, representing any\n- failed ``check``s, and the second element is the original output of ``fun``.\n+ a pair where the first element is an ``Error`` value, representing the first\n+ failed ``check``, and the second element is the original output of ``fun``.\nFor example:\n@@ -719,7 +728,7 @@ def checkify(fun: Callable[..., Out],\n... def f(x):\n... y = jnp.sin(x)\n... return x+y\n- >>> err, out = checkify.checkify(f, errors=checkify.float_errors)(jnp.inf)\n+ >>> err, out = checkify.checkify(f, errors=checkify.float_checks)(jnp.inf)\n>>> err.throw() # doctest: +IGNORE_EXCEPTION_DETAIL\nTraceback (most recent call last):\n...\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -41,7 +41,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn y1 + y2\nf = jax.jit(f) if jit else f\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\nerr, _ = checked_f(3., 4.)\nself.assertIs(err.get(), None)\n@@ -61,7 +61,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn w\nf = jax.jit(f) if jit else f\n- checked_f = checkify.checkify(f, errors=checkify.index_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.index_checks)\nerr, _ = checked_f(jnp.arange(3), 2)\nself.assertIs(err.get(), None)\n@@ -79,7 +79,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn getattr(x.at[i], update_fn)(1.)\nf = jax.jit(f)\n- checked_f = checkify.checkify(f, errors=checkify.index_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.index_checks)\nerr, _ = checked_f(jnp.arange(3), 2)\nself.assertIs(err.get(), None)\n@@ -96,7 +96,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn x/y\nf = jax.jit(f) if jit else f\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\nerr, _ = checked_f(jnp.ones((3,)), jnp.ones((3,)))\nself.assertIs(err.get(), None)\n@@ -120,7 +120,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn z\nf = jax.jit(f) if jit else f\n- checked_f = checkify.checkify(f, errors=checkify.automatic_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.automatic_checks)\n# no error\nerr, _ = checked_f(jnp.array([0., jnp.inf, 2.]), 2)\n@@ -146,7 +146,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn y * z\nf = jax.jit(f) if jit else f\n- checked_f = checkify.checkify(f, errors=checkify.automatic_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.automatic_checks)\n# both oob and nan error, but oob happens first\nerr, _ = checked_f(jnp.array([0., 1., jnp.inf]), 5)\n@@ -163,7 +163,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ny1 = jnp.sin(x1)\ny2 = jnp.sin(x2)\nreturn y1 + y2\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\nxs = jnp.array([0., 2.])\nerr, _ = checked_f(xs, xs)\n@@ -182,7 +182,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nlambda: jnp.sin(x),\nlambda: x)\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\nerr, _ = checked_f(3.)\nself.assertIs(err.get(), None)\n@@ -203,7 +203,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(xs):\nreturn lax.scan(scan_body, None, xs)\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\nxs = jnp.array([0., 2.])\nerr, (_, ch_outs) = checked_f(xs)\n@@ -229,7 +229,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(carry, xs):\nreturn lax.scan(scan_body, carry, xs)\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\ncarry, xs = 3., jnp.ones((2,))\nerr, (ch_out_carry, ch_outs) = checked_f(carry, xs)\n@@ -271,7 +271,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, while_body, (init_val, 0.))\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\ninit_val = 1.\nerr, ch_out = checked_f(init_val)\n@@ -299,7 +299,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, while_body, init_val)\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\ninit_val = 1.\nerr, ch_out = checked_f(init_val)\n@@ -325,7 +325,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(init_val):\nreturn lax.while_loop(while_cond, lambda val: val-1, init_val)\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\n# error on first cond\ninit_val = 0.\n@@ -355,7 +355,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef f(cond_val, body_val):\nreturn lax.while_loop(while_cond, while_body, (0., cond_val, body_val))\n- checked_f = checkify.checkify(f, errors=checkify.float_errors)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\ncond_val = jnp.inf\nbody_val = 1.\n@@ -384,8 +384,8 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n(\"assert\", checkify.user_checks, \"must be negative!\"),\n(\"div\", {checkify.ErrorCategory.DIV}, \"divided by zero\"),\n(\"nan\", {checkify.ErrorCategory.NAN}, \"nan generated\"),\n- (\"oob\", checkify.index_errors, \"out-of-bounds indexing\"),\n- (\"automatic_errors\", checkify.automatic_errors, \"divided by zero\"),\n+ (\"oob\", checkify.index_checks, \"out-of-bounds indexing\"),\n+ (\"automatic_checks\", checkify.automatic_checks, \"divided by zero\"),\n)\n@jtu.skip_on_devices(\"tpu\")\ndef test_enabled_errors(self, error_set, expected_error):\n@@ -403,7 +403,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_post_process_call(self):\n- @partial(checkify.checkify, errors=checkify.float_errors)\n+ @partial(checkify.checkify, errors=checkify.float_checks)\ndef g(x):\n@jax.jit\ndef f(y):\n@@ -415,7 +415,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_post_process_map(self):\n- @partial(checkify.checkify, errors=checkify.float_errors)\n+ @partial(checkify.checkify, errors=checkify.float_checks)\ndef g(x):\n@jax.pmap\ndef f(y):\n@@ -436,7 +436,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n(x,), (xdot,) = primals, tangents\nreturn sin(x), jnp.cos(x) * xdot\n- f = checkify.checkify(sin, errors=checkify.float_errors)\n+ f = checkify.checkify(sin, errors=checkify.float_checks)\nerr, y = f(3.)\nself.assertIsNone(err.get())\n@@ -459,7 +459,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n# Checkify-of-jvp adds checks (unlike jvp-of-checkify above).\ng = checkify.checkify(lambda x, xdot: jax.jvp(sin, (x,), (xdot,)),\n- errors=checkify.float_errors)\n+ errors=checkify.float_checks)\nerr, (y, ydot) = g(3., 1.) # doesn't crash\nself.assertIsNone(err.get()) # no error\nself.assertNotEmpty(err.msgs) # but checks were added!\n@@ -481,7 +481,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn jnp.cos(x2 / 2.) * g,\nsin.defvjp(sin_fwd, sin_bwd)\n- f = checkify.checkify(sin, errors=checkify.float_errors)\n+ f = checkify.checkify(sin, errors=checkify.float_checks)\n# no differentiation, no error\nerr, y = f(3.)\n@@ -498,11 +498,11 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertEmpty(err.msgs) # and no checks were added!\n# Checkify-of-vjp adds checks (unlike vjp-of-checkify above).\n- err, y = checkify.checkify(jax.grad(sin), errors=checkify.float_errors)(3.)\n+ err, y = checkify.checkify(jax.grad(sin), errors=checkify.float_checks)(3.)\nself.assertIsNone(err.get()) # no error\nself.assertNotEmpty(err.msgs) # but checks were added!\nerr, y = checkify.checkify(jax.grad(sin),\n- errors=checkify.float_errors)(jnp.inf)\n+ errors=checkify.float_checks)(jnp.inf)\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), 'nan generated by primitive sin')\n" } ]
Python
Apache License 2.0
google/jax
Checkify: Fix docstring formatting and polish enabled_errors sets.
260,330
12.02.2022 08:14:57
-3,600
faf57d813b74f4741823fca137dfac081986bb80
Wrote docstring for jet
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/jax.experimental.jet.rst", "diff": "+jax.experimental.jet module\n+===========================\n+\n+.. automodule:: jax.experimental.jet\n+\n+API\n+---\n+\n+.. autofunction:: jet\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.experimental.rst", "new_path": "docs/jax.experimental.rst", "diff": "@@ -19,6 +19,7 @@ Experimental Modules\njax.experimental.maps\njax.experimental.pjit\njax.experimental.sparse\n+ jax.experimental.jet\nExperimental APIs\n-----------------\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+r\"\"\"Jet is an experimental module for higher-order automatic differentiation\n+ that does not rely on repeated first-order automatic differentiation.\n+\n+ How? Through the propagation of truncated Taylor polynomials.\n+ Let :math:`x: \\mathbb{R} \\rightarrow \\mathbb{R}^n` be the Taylor polynomial\n+\n+ .. math:: x(t) := x_0 + x_1 t + \\frac{x_2}{2!} t^2 + ... + \\frac{1}{d!} x_d t^d.\n+\n+ For some function :math:`f: \\mathbb{R}^n \\rightarrow \\mathbb{R}^m`,\n+ you can use :func:`jet` to compute the\n+ Taylor polynomial\n+\n+ .. math:: y(t) := y_0 + y_1 t + \\frac{y_2}{2!} t^2 + ... + \\frac{1}{d!} y_d t^d.\n+\n+ which approximates :math:`f(x(\\cdot)):\\mathbb{R} \\rightarrow \\mathbb{R}^m`,\n+ and relates to :math:`x(t)` and :math:`f(z)` through\n+\n+ .. math::\n+ y_k = \\frac{d^k}{dt^k}f(x(t_0)), \\quad k=0,...,d.\n+\n+ More specifically, :func:`jet` computes\n+\n+ .. math::\n+ y_0, (y_1, . . . , y_d) = \\texttt{jet} (f, x_0, (x_1, . . . , x_d))\n+\n+ and can thus be used for high-order\n+ automatic differentiation of :math:`f`.\n+ Details are explained in\n+ `this paper <https://openreview.net/forum?id=SkxEF3FNPH>`__.\n+\n+ Note:\n+ Help improve :func:`jet` by contributing\n+ `outstanding primitive rules <https://github.com/google/jax/issues/2431>`__.\n+\"\"\"\n+\nfrom typing import Callable\nfrom functools import partial\n@@ -32,6 +67,51 @@ from jax.custom_derivatives import custom_jvp_call_jaxpr_p\nfrom jax import lax\ndef jet(fun, primals, series):\n+ r\"\"\"Taylor-mode higher-order automatic differentiation.\n+\n+ Args:\n+ fun: Function to be differentiated. Its arguments should be arrays, scalars,\n+ or standard Python containers of arrays or scalars. It should return an\n+ array, scalar, or standard Python container of arrays or scalars.\n+ primals: The primal values at which the Taylor approximation of ``fun`` should be\n+ evaluated. Should be either a tuple or a list of arguments,\n+ and its length should be equal to the number of positional parameters of\n+ ``fun``.\n+ series: Higher order Taylor-series-coefficients.\n+ Together, `primals` and `series` make up a truncated Taylor polynomial.\n+ Should be either a tuple or a list of tuples or lists,\n+ and its length dictates the degree of the truncated Taylor polynomial.\n+\n+ Returns:\n+ A ``(primals_out, series_out)`` pair, where ``primals_out`` is ``fun(*primals)``,\n+ and together, ``primals_out`` and ``series_out`` are a\n+ truncated Taylor polynomial of :math:`f(x(\\cdot))`.\n+ The ``primals_out`` value has the same Python tree structure as ``primals``,\n+ and the ``series_out`` value the same Python tree structure as ``series``.\n+\n+ For example:\n+\n+ >>> import jax\n+ >>> import jax.numpy as np\n+\n+ Consider the function :math:`x(t) = t^3`, :math:`t_0 = 0.5`,\n+ and the first few Taylor coefficients\n+ :math:`x_0=t_0^3`, :math:`x_1=3t_0^2`, and :math:`x_2=6t_0`.\n+\n+ >>> x0, x1, x2 = 0.5**3., 3.*0.5**2., 6.*0.5\n+ >>> y0, (y1, y2) = jet(np.sin, (x0,), ((x1, x2),))\n+\n+ :func:`jet` returns the Taylor coefficients of :math:`f(x(t)) = \\sin(t^3)`:\n+\n+ >>> print(y0, np.sin(x0))\n+ 0.12 0.12\n+\n+ >>> print(y1, np.cos(x0) * x1)\n+ 0.74 0.74\n+\n+ >>> print(y2, -np.sin(x0) * x1 + x2)\n+ 2.9099998 2.9099998\n+ \"\"\"\ntry:\norder, = set(map(len, series))\nexcept ValueError:\n" } ]
Python
Apache License 2.0
google/jax
Wrote docstring for jet
260,330
12.02.2022 08:19:54
-3,600
4f744e9033e309d6f6973b8ca49f0715c4009829
'approximates' -> 'corresponding to' in jet-docstring.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -26,7 +26,7 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\n.. math:: y(t) := y_0 + y_1 t + \\frac{y_2}{2!} t^2 + ... + \\frac{1}{d!} y_d t^d.\n- which approximates :math:`f(x(\\cdot)):\\mathbb{R} \\rightarrow \\mathbb{R}^m`,\n+ corresponding to :math:`f(x(\\cdot)):\\mathbb{R} \\rightarrow \\mathbb{R}^m`,\nand relates to :math:`x(t)` and :math:`f(z)` through\n.. math::\n" } ]
Python
Apache License 2.0
google/jax
'approximates' -> 'corresponding to' in jet-docstring.
260,330
12.02.2022 08:31:39
-3,600
0210b563e832488a7796b7959c227d8abc45150b
Changed example output values to exact numbers
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -104,13 +104,13 @@ def jet(fun, primals, series):\n:func:`jet` returns the Taylor coefficients of :math:`f(x(t)) = \\sin(t^3)`:\n>>> print(y0, np.sin(x0))\n- 0.12 0.12\n+ 0.12467473 0.12467473\n>>> print(y1, np.cos(x0) * x1)\n- 0.74 0.74\n+ 0.7441479 0.74414825\n>>> print(y2, -np.sin(x0) * x1 + x2)\n- 2.9099998 2.9099998\n+ 2.9064622 2.906494\n\"\"\"\ntry:\norder, = set(map(len, series))\n" } ]
Python
Apache License 2.0
google/jax
Changed example output values to exact numbers
260,335
04.02.2022 19:12:57
28,800
004bb684ea630633782dc5071dd73813350b8975
add flag for jaxpr colorful syntax highlighting set it on by default
[ { "change_type": "MODIFY", "old_path": "jax/_src/config.py", "new_path": "jax/_src/config.py", "diff": "@@ -440,6 +440,12 @@ flags.DEFINE_integer(\nhelp='Set the number of stack frames in JAX tracer error messages.'\n)\n+flags.DEFINE_bool(\n+ 'jax_pprint_use_color',\n+ bool_env('JAX_PPRINT_USE_COLOR', False),\n+ help='Enable jaxpr pretty-printing with colorful syntax highlighting.'\n+)\n+\nflags.DEFINE_bool(\n'jax_host_callback_inline',\nbool_env('JAX_HOST_CALLBACK_INLINE', False),\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -47,6 +47,7 @@ from jax.interpreters import ad\nfrom jax.interpreters import invertible_ad as iad\nfrom jax.interpreters import batching\nfrom jax.interpreters import masking\n+import jax._src.pretty_printer as pp\nfrom jax._src import util\nfrom jax._src.util import (cache, safe_zip, prod, safe_map, canonicalize_axis,\nsplit_list)\n@@ -2250,6 +2251,16 @@ def _convert_elt_type_fwd_rule(eqn):\nelse:\nreturn [None], eqn\n+def _convert_elt_type_pp_rule(eqn, context):\n+ # don't print new_dtype because the output binder shows it\n+ printed_params = {}\n+ if eqn.params['weak_type']:\n+ printed_params['weak_type'] = True\n+ return [pp.text(eqn.primitive.name),\n+ core.pp_kv_pairs(sorted(printed_params.items()), context),\n+ pp.text(\" \") + core.pp_vars(eqn.invars, context)]\n+\n+\nconvert_element_type_p = Primitive('convert_element_type')\nconvert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\nconvert_element_type_p.def_abstract_eval(\n@@ -2264,6 +2275,8 @@ batching.defvectorized(convert_element_type_p)\nmasking.defvectorized(convert_element_type_p)\npe.const_fold_rules[convert_element_type_p] = _convert_elt_type_folding_rule\npe.forwarding_rules[convert_element_type_p] = _convert_elt_type_fwd_rule\n+# TODO(mattjj): un-comment the next line (see #9456)\n+# core.pp_eqn_rules[convert_element_type_p] = _convert_elt_type_pp_rule\ndef _real_dtype(dtype): return np.finfo(dtype).dtype\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/pretty_printer.py", "new_path": "jax/_src/pretty_printer.py", "diff": "@@ -29,6 +29,7 @@ import abc\nimport enum\nfrom functools import partial\nfrom typing import List, NamedTuple, Optional, Sequence, Tuple, Union\n+from jax.config import config\ntry:\nimport colorama # pytype: disable=import-error\n@@ -41,6 +42,7 @@ class Doc(abc.ABC):\ndef format(self, width: int = 80, use_color: bool = False,\nannotation_prefix=\" # \") -> str:\n+ use_color = use_color or config.FLAGS.jax_pprint_use_color\nreturn _format(self, width, use_color=use_color,\nannotation_prefix=annotation_prefix)\n@@ -374,8 +376,9 @@ def color(doc: Doc, *, foreground: Optional[Color] = None,\nintensity=intensity)\n-dim = partial(color, intensity=Intensity.DIM)\n-bright = partial(color, intensity=Intensity.BRIGHT)\n+type_annotation = partial(color, intensity=Intensity.NORMAL,\n+ foreground=Color.MAGENTA)\n+keyword = partial(color, intensity=Intensity.BRIGHT, foreground=Color.BLUE)\ndef join(sep: Doc, docs: Sequence[Doc]) -> Doc:\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -87,6 +87,9 @@ class Jaxpr:\ncustom_pp_eqn_rules=custom_pp_eqn_rules)\nreturn doc.format(**kw)\n+ def _repr_pretty_(self, p, cycle):\n+ return p.text(self.pretty_print(use_color=True))\n+\ndef jaxprs_in_params(params) -> Iterator[Jaxpr]:\nfor val in params.values():\n@@ -142,6 +145,10 @@ class ClosedJaxpr:\nreturn pp_jaxpr(self.jaxpr, JaxprPpContext(), source_info=source_info,\nprint_shapes=print_shapes).format(**kw)\n+\n+ def _repr_pretty_(self, p, cycle):\n+ return p.text(self.pretty_print(use_color=True))\n+\n@curry\ndef jaxpr_as_fun(closed_jaxpr: ClosedJaxpr, *args):\nreturn eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.consts, *args)\n@@ -2248,7 +2255,7 @@ def pp_vars(vs: Sequence[Any], context: JaxprPpContext,\nreturn pp.nest(2, pp.group(\npp.join(pp.text(separator) + pp.group(pp.brk()), [\npp.text(pp_var(v, context)) +\n- pp.dim(pp.text(\":\" + pp_aval(v.aval, context)))\n+ pp.type_annotation(pp.text(\":\" + pp_aval(v.aval, context)))\nfor v in vs\n])\n))\n@@ -2321,11 +2328,11 @@ def pp_jaxpr_skeleton(jaxpr, eqns_fn, context: JaxprPpContext, *,\npp.text(\"(\"), pp_vars(jaxpr.outvars, context, separator=\",\"),\npp.text(\")\" if len(jaxpr.outvars) != 1 else \",)\")])\nreturn pp.group(pp.nest(2, pp.concat([\n- pp.text(\"{ \"), pp.bright(pp.text(\"lambda \")),\n+ pp.text(\"{ \"), pp.keyword(pp.text(\"lambda \")),\nconstvars, pp.text(\"; \"), invars,\n- pp.text(\". \"), pp.bright(pp.text(\"let\")),\n+ pp.text(\". \"), pp.keyword(pp.text(\"let\")),\npp.nest(2, pp.brk() + eqns), pp.brk(),\n- pp.bright(pp.text(\"in \")), outvars\n+ pp.keyword(pp.text(\"in \")), outvars\n])) + pp.text(\" }\"))\n" } ]
Python
Apache License 2.0
google/jax
add flag for jaxpr colorful syntax highlighting set it on by default
260,330
13.02.2022 08:19:24
-3,600
cbc9024b9db492ff2b865dfb97aa5f57f85104a6
Replaced fraction-notation for derivatives, and link different notes
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -18,19 +18,19 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\nHow? Through the propagation of truncated Taylor polynomials.\nLet :math:`x: \\mathbb{R} \\rightarrow \\mathbb{R}^n` be the Taylor polynomial\n- .. math:: x(t) := x_0 + x_1 t + \\frac{x_2}{2!} t^2 + ... + \\frac{1}{d!} x_d t^d.\n+ .. math:: x(t) := x_0 + x_1 t + \\frac{1}{2!} x_2 t^2 + ... + \\frac{1}{d!} x_d t^d.\nFor some function :math:`f: \\mathbb{R}^n \\rightarrow \\mathbb{R}^m`,\nyou can use :func:`jet` to compute the\nTaylor polynomial\n- .. math:: y(t) := y_0 + y_1 t + \\frac{y_2}{2!} t^2 + ... + \\frac{1}{d!} y_d t^d.\n+ .. math:: y(t) := y_0 + y_1 t + \\frac{1}{2!} y_2 t^2 + ... + \\frac{1}{d!} y_d t^d.\ncorresponding to :math:`f(x(\\cdot)):\\mathbb{R} \\rightarrow \\mathbb{R}^m`,\nand relates to :math:`x(t)` and :math:`f(z)` through\n.. math::\n- y_k = \\frac{d^k}{dt^k}f(x(t_0)), \\quad k=0,...,d.\n+ y_k = \\partial^k f(x(t_0)), \\quad k=0,...,d.\nMore specifically, :func:`jet` computes\n@@ -40,7 +40,7 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\nand can thus be used for high-order\nautomatic differentiation of :math:`f`.\nDetails are explained in\n- `this paper <https://openreview.net/forum?id=SkxEF3FNPH>`__.\n+ `these notes <https://github.com/google/jax/files/6717197/jet.pdf>`__.\nNote:\nHelp improve :func:`jet` by contributing\n" } ]
Python
Apache License 2.0
google/jax
Replaced fraction-notation for derivatives, and link different notes
260,330
13.02.2022 08:52:34
-3,600
c2a20db9b68b22ddf853a744e7dbd37578caab01
Changed Taylor-series notation in module docstring
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -16,26 +16,31 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\nthat does not rely on repeated first-order automatic differentiation.\nHow? Through the propagation of truncated Taylor polynomials.\n- Let :math:`x: \\mathbb{R} \\rightarrow \\mathbb{R}^n` be the Taylor polynomial\n+ Consider a function :math:`f = g \\circ h`, some point :math:`x`\n+ and some offset :math:`v`.\n+ First-order automatic differentiation (such as :func:`jax.jvp`)\n+ computes the pair :math:`(f(x), \\partial f(x)[v])` from the the pair\n+ :math:`(h(x), \\partial h(x)[v])`.\n- .. math:: x(t) := x_0 + x_1 t + \\frac{1}{2!} x_2 t^2 + ... + \\frac{1}{d!} x_d t^d.\n+ :func:`jet` implements the higher-order analogue:\n+ Given the tuple\n- For some function :math:`f: \\mathbb{R}^n \\rightarrow \\mathbb{R}^m`,\n- you can use :func:`jet` to compute the\n- Taylor polynomial\n-\n- .. math:: y(t) := y_0 + y_1 t + \\frac{1}{2!} y_2 t^2 + ... + \\frac{1}{d!} y_d t^d.\n+ .. math::\n+ (h_0, ... h_K) :=\n+ (h(x), \\partial h(x)[v], \\partial^2 h(x)[v], ..., \\partial^K h(x)[v,...,v]),\n- corresponding to :math:`f(x(\\cdot)):\\mathbb{R} \\rightarrow \\mathbb{R}^m`,\n- and relates to :math:`x(t)` and :math:`f(z)` through\n+ which represents a :math:`K`-th order Taylor approximation\n+ of :math:`h` at :math:`x`, :func:`jet` returns a :math:`K`-th order\n+ Taylor approximation of :math:`f` at :math:`x`,\n.. math::\n- y_k = \\partial^k f(x(t_0)), \\quad k=0,...,d.\n+ (f_0, ..., f_K) :=\n+ (f(x), \\partial f(x)[v], \\partial^2 f(x)[v], ..., \\partial^K f(x)[v,...,v]).\nMore specifically, :func:`jet` computes\n.. math::\n- y_0, (y_1, . . . , y_d) = \\texttt{jet} (f, x_0, (x_1, . . . , x_d))\n+ f_0, (f_1, . . . , f_K) = \\texttt{jet} (f, h_0, (h_1, . . . , h_K))\nand can thus be used for high-order\nautomatic differentiation of :math:`f`.\n@@ -85,7 +90,7 @@ def jet(fun, primals, series):\nReturns:\nA ``(primals_out, series_out)`` pair, where ``primals_out`` is ``fun(*primals)``,\nand together, ``primals_out`` and ``series_out`` are a\n- truncated Taylor polynomial of :math:`f(x(\\cdot))`.\n+ truncated Taylor polynomial of :math:`f(h(\\cdot))`.\nThe ``primals_out`` value has the same Python tree structure as ``primals``,\nand the ``series_out`` value the same Python tree structure as ``series``.\n@@ -94,22 +99,24 @@ def jet(fun, primals, series):\n>>> import jax\n>>> import jax.numpy as np\n- Consider the function :math:`x(t) = t^3`, :math:`t_0 = 0.5`,\n+ Consider the function :math:`h(z) = z^3`, :math:`x = 0.5`,\nand the first few Taylor coefficients\n- :math:`x_0=t_0^3`, :math:`x_1=3t_0^2`, and :math:`x_2=6t_0`.\n+ :math:`h_0=x^3`, :math:`h_1=3x^2`, and :math:`h_2=6x`.\n+ Let :math:`f(y) = \\sin(y)`.\n- >>> x0, x1, x2 = 0.5**3., 3.*0.5**2., 6.*0.5\n- >>> y0, (y1, y2) = jet(np.sin, (x0,), ((x1, x2),))\n+ >>> h0, h1, h2 = 0.5**3., 3.*0.5**2., 6.*0.5\n+ >>> f, df, ddf = np.sin, np.cos, lambda *args: -np.sin(*args)\n- :func:`jet` returns the Taylor coefficients of :math:`f(x(t)) = \\sin(t^3)`:\n+ :func:`jet` returns the Taylor coefficients of :math:`f(h(z)) = \\sin(z^3)`:\n- >>> print(y0, np.sin(x0))\n+ >>> f0, (f1, f2) = jet(f, (h0,), ((h1, h2),))\n+ >>> print(f0, f(h0))\n0.12467473 0.12467473\n- >>> print(y1, np.cos(x0) * x1)\n+ >>> print(f1, df(h0) * h1)\n0.7441479 0.74414825\n- >>> print(y2, -np.sin(x0) * x1 + x2)\n+ >>> print(f2, ddf(h0) * h1 + h2)\n2.9064622 2.906494\n\"\"\"\ntry:\n" } ]
Python
Apache License 2.0
google/jax
Changed Taylor-series notation in module docstring
260,330
13.02.2022 08:59:29
-3,600
5446cee0e926fc3556f59e07061a63774668851b
fixed a typo in maths-part of jet-module-docstring
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -27,7 +27,7 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\n.. math::\n(h_0, ... h_K) :=\n- (h(x), \\partial h(x)[v], \\partial^2 h(x)[v], ..., \\partial^K h(x)[v,...,v]),\n+ (h(x), \\partial h(x)[v], \\partial^2 h(x)[v, v], ..., \\partial^K h(x)[v,...,v]),\nwhich represents a :math:`K`-th order Taylor approximation\nof :math:`h` at :math:`x`, :func:`jet` returns a :math:`K`-th order\n@@ -35,7 +35,7 @@ r\"\"\"Jet is an experimental module for higher-order automatic differentiation\n.. math::\n(f_0, ..., f_K) :=\n- (f(x), \\partial f(x)[v], \\partial^2 f(x)[v], ..., \\partial^K f(x)[v,...,v]).\n+ (f(x), \\partial f(x)[v], \\partial^2 f(x)[v, v], ..., \\partial^K f(x)[v,...,v]).\nMore specifically, :func:`jet` computes\n" } ]
Python
Apache License 2.0
google/jax
fixed a typo in maths-part of jet-module-docstring
260,580
13.02.2022 23:47:52
-32,400
fc4f47cdaec9160d054053e58924d59705224c39
shape_poly_test.py : remove duplicate word
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -1681,7 +1681,7 @@ def _add_vmap_primitive_harnesses():\ndevice = jtu.device_under_test()\nfor h in all_h:\n- # Drop the the JAX limitations\n+ # Drop the JAX limitations\nif not h.filter(device_under_test=device, include_jax_unimpl=False):\ncontinue\n# And the jax2tf limitations that are known to result in TF error.\n" } ]
Python
Apache License 2.0
google/jax
shape_poly_test.py : remove duplicate word
260,424
14.02.2022 15:02:05
0
a4cacf5729466afb7efbec23b0f9dffeeb79faff
Checkify: handle named_call in process_call. named_call does not specify donated_invars, this change handles this missing param case. For future reference: we might want to add a call_param_updater registry to define how call params need to get updated wrt checkify, like eg. partial_eval/ad does.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -137,8 +137,10 @@ class CheckifyTrace(core.Trace):\nin_vals = [t.val for t in tracers]\ne = popattr(self.main, 'error')\nf, msgs = checkify_subtrace(f, self.main, tuple(e.msgs.items()))\n- params_ = dict(params, donated_invars=(False, False, *params['donated_invars']))\n- err, code, *out_vals = primitive.bind(f, e.err, e.code, *in_vals, **params_)\n+ if 'donated_invars' in params:\n+ params = dict(params, donated_invars=(False, False,\n+ *params['donated_invars']))\n+ err, code, *out_vals = primitive.bind(f, e.err, e.code, *in_vals, **params)\nsetnewattr(self.main, 'error', Error(err, code, msgs()))\nreturn [CheckifyTracer(self, x) for x in out_vals]\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -583,6 +583,13 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"foo\"):\nf(False)\n+ def test_cond_of_named_call(self):\n+ def g(x):\n+ branch = jax.named_call(lambda x: x)\n+ out = jax.lax.cond(True, branch, branch, x)\n+ return out\n+\n+ checkify.checkify(g)(0.) # does not crash\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Checkify: handle named_call in process_call. named_call does not specify donated_invars, this change handles this missing param case. For future reference: we might want to add a call_param_updater registry to define how call params need to get updated wrt checkify, like eg. partial_eval/ad does.
260,447
14.02.2022 15:23:47
28,800
273ea6262404eaade9d50ec01c2c9bf3be133140
[sparse] Updates `bcoo_dot_general` cuSparse lowering rule by adding sorted indices.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/sparse/bcoo.py", "new_path": "jax/experimental/sparse/bcoo.py", "diff": "@@ -142,6 +142,9 @@ def _bcoo_sort_indices(data, indices, shape):\nf = broadcasting_vmap(f)\nreturn f(data, indices)\n+_bcoo_sort_indices_rule = xla.lower_fun(\n+ _bcoo_sort_indices, multiple_results=True, new_style=True)\n+\ndef _unbatch_bcoo(data, indices, shape):\nn_batch = _validate_bcoo(data, indices, shape).n_batch\nif n_batch == 0:\n@@ -736,6 +739,11 @@ def _bcoo_dot_general_gpu_translation_rule(\nctx, avals_in, avals_out, lhs_data, lhs_indices, rhs, *, dimension_numbers,\nlhs_spinfo: BCOOInfo):\n+ if not config.jax_bcoo_cusparse_lowering:\n+ return _bcoo_dot_general_default_translation_rule(\n+ ctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\n+ dimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n+\n(lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\nlhs_data_aval, lhs_indices_aval, rhs_aval, = avals_in\nn_batch, n_sparse, n_dense, nse = _validate_bcoo(\n@@ -757,10 +765,11 @@ def _bcoo_dot_general_gpu_translation_rule(\nctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\nelse:\n- # The lhs indices are row-wise sorted.\n- lhs_indices_row, lhs_indices_col, lhs_data = lax.sort(\n- [lhs_indices[:, 0], lhs_indices[:, 1], lhs_data])\n- lhs_indices = jnp.hstack((lhs_indices_row, lhs_indices_col))\n+ # Sorts lhs by row indices.\n+ lhs_data, lhs_indices = _bcoo_sort_indices_rule(\n+ ctx, avals_in[:2], avals_in[:2], lhs_data, lhs_indices,\n+ shape=lhs_spinfo.shape)\n+\nreturn _bcoo_dot_general_cuda_translation_rule(\nctx, avals_in, avals_out, lhs_data, lhs_indices, rhs,\ndimension_numbers=dimension_numbers, lhs_spinfo=lhs_spinfo)\n@@ -833,7 +842,7 @@ batching.primitive_batchers[bcoo_dot_general_p] = _bcoo_dot_general_batch_rule\nxla.register_translation(\nbcoo_dot_general_p, _bcoo_dot_general_default_translation_rule)\n-if config.jax_bcoo_cusparse_lowering and cusparse and cusparse.is_supported:\n+if cusparse and cusparse.is_supported:\nxla.register_translation(bcoo_dot_general_p,\n_bcoo_dot_general_gpu_translation_rule,\nplatform='gpu')\n" }, { "change_type": "MODIFY", "old_path": "tests/sparse_test.py", "new_path": "tests/sparse_test.py", "diff": "@@ -42,6 +42,7 @@ import jax.numpy as jnp\nfrom jax.util import split_list\nimport numpy as np\nimport scipy.sparse\n+\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n@@ -915,36 +916,46 @@ class BCOOTest(jtu.JaxTestCase):\nlhs_2d_sparse, lhs_sparse_2d_indicdes = create_unsorted_indices(\nlhs_2d_sparse, lhs_sparse_2d_indicdes)\n- dimension_numbers = (([1], [0]), ([], []))\n- expected_2d = lax.dot_general(\n- lhs_2d_dense, rhs, dimension_numbers=dimension_numbers)\n- actual_2d = sparse.bcoo_dot_general(\n- lhs_2d_sparse, lhs_sparse_2d_indicdes, rhs,\n- dimension_numbers=dimension_numbers,\n- lhs_spinfo=BCOOInfo(lhs_2d_dense.shape))\n+ dimension_numbers_2d = (([1], [0]), ([], []))\n+\n+ def args_maker_2d():\n+ return lhs_2d_sparse, lhs_sparse_2d_indicdes, lhs_2d_dense, rhs\n+\n+ def f_dense_2d(data, indices, lhs, rhs):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers_2d)\n+ def f_sparse_2d(data, indices, lhs, rhs):\n+ return sparse.bcoo_dot_general(data, indices, rhs,\n+ dimension_numbers=dimension_numbers_2d,\n+ lhs_spinfo=BCOOInfo(lhs.shape))\nwith self.subTest(msg=\"2D\"):\n- self.assertAllClose(expected_2d, actual_2d)\n+ self._CompileAndCheck(f_sparse_2d, args_maker_2d)\n+ self._CheckAgainstNumpy(f_dense_2d, f_sparse_2d, args_maker_2d)\n- # It creates out-of-bound indices when nse > nnz.\nlhs_1d_dense = jnp.array([0, 1, 0, 2, 0], dtype=jnp.float32)\nlhs_1d_sparse, lhs_sparse_1d_indicdes = sparse.bcoo_fromdense(\n- lhs_1d_dense, nse=7)\n+ lhs_1d_dense, nse=5)\n# Random permutate the indices to make them unsorted.\nlhs_1d_sparse, lhs_sparse_1d_indicdes = create_unsorted_indices(\nlhs_1d_sparse, lhs_sparse_1d_indicdes)\n- dimension_numbers = (([0], [0]), ([], []))\n- expected_1d = lax.dot_general(\n- lhs_1d_dense, rhs, dimension_numbers=dimension_numbers)\n- actual_1d = sparse.bcoo_dot_general(\n- lhs_1d_sparse, lhs_sparse_1d_indicdes, rhs,\n- dimension_numbers=dimension_numbers,\n- lhs_spinfo=BCOOInfo(lhs_1d_dense.shape))\n+ dimension_numbers_1d = (([0], [0]), ([], []))\n+\n+ def args_maker_1d():\n+ return lhs_1d_sparse, lhs_sparse_1d_indicdes, lhs_1d_dense, rhs\n+\n+ def f_dense_1d(data, indices, lhs, rhs):\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers_1d)\n+\n+ def f_sparse_1d(data, indices, lhs, rhs):\n+ return sparse.bcoo_dot_general(data, indices, rhs,\n+ dimension_numbers=dimension_numbers_1d,\n+ lhs_spinfo=BCOOInfo(lhs.shape))\nwith self.subTest(msg=\"1D\"):\n- self.assertAllClose(expected_1d, actual_1d)\n+ self._CompileAndCheck(f_sparse_1d, args_maker_1d)\n+ self._CheckAgainstNumpy(f_dense_1d, f_sparse_1d, args_maker_1d)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": props.testcase_name(), \"props\": props}\n" } ]
Python
Apache License 2.0
google/jax
[sparse] Updates `bcoo_dot_general` cuSparse lowering rule by adding sorted indices. PiperOrigin-RevId: 428621454
260,424
15.02.2022 02:42:30
28,800
0d9990e4f3305aa9b1180fcabc5b96234b6e40f1
Run all tests with jax_traceback_filtering=off. Context: If an AssertionError is thrown inside a test and traceback filtering is enabled, most of the stack-trace is swallowed (due to https://bugs.python.org/issue24959).
[ { "change_type": "MODIFY", "old_path": "jax/_src/test_util.py", "new_path": "jax/_src/test_util.py", "diff": "@@ -917,7 +917,8 @@ class JaxTestCase(parameterized.TestCase):\n\"\"\"Base class for JAX tests including numerical checks and boilerplate.\"\"\"\n_default_config = {\n'jax_enable_checks': True,\n- 'jax_numpy_rank_promotion': 'raise'\n+ 'jax_numpy_rank_promotion': 'raise',\n+ 'jax_traceback_filtering': 'off',\n}\n# TODO(mattjj): this obscures the error messages from failures, figure out how\n" }, { "change_type": "MODIFY", "old_path": "tests/errors_test.py", "new_path": "tests/errors_test.py", "diff": "@@ -70,6 +70,7 @@ def check_filtered_stack_trace(test, etype, f, frame_patterns=(),\ntest.assertRegex(frame_fmt, full_pat)\n+@jtu.with_config(jax_traceback_filtering='auto') # JaxTestCase defaults to off.\n@parameterized.named_parameters(\n{\"testcase_name\": f\"_{f}\", \"filter_mode\": f}\nfor f in (\"tracebackhide\", \"remove_frames\"))\n@@ -363,6 +364,7 @@ class FilteredTracebackTest(jtu.JaxTestCase):\n('err', 'return jit(f)(a)')], filter_mode=filter_mode)\n+@jtu.with_config(jax_traceback_filtering='auto') # JaxTestCase defaults to off.\nclass UserContextTracebackTest(jtu.JaxTestCase):\ndef test_grad_norm(self):\n" } ]
Python
Apache License 2.0
google/jax
Run all tests with jax_traceback_filtering=off. Context: If an AssertionError is thrown inside a test and traceback filtering is enabled, most of the stack-trace is swallowed (due to https://bugs.python.org/issue24959). PiperOrigin-RevId: 428729211
260,287
15.02.2022 03:43:40
28,800
c551beda7af61fe0ba4d3a590d41333c913f5923
Add a partial_eval_jaxpr_custom_rule for xmap Additionaly fix a bug in partial_eval rule for xmap.
[ { "change_type": "MODIFY", "old_path": "jax/_src/ad_checkpoint.py", "new_path": "jax/_src/ad_checkpoint.py", "diff": "@@ -335,11 +335,8 @@ def remat_partial_eval(trace, *tracers, jaxpr, **params):\nreturn pe._zip_knowns(out_known_tracers, out_jaxpr_tracers, out_unknowns)\npe.custom_partial_eval_rules[remat_p] = remat_partial_eval\n-def remat_partial_eval_custom_params_updater(_, __, params_known, params_staged):\n- jaxpr_known = params_known.pop('call_jaxpr')\n- jaxpr_staged = params_staged.pop('call_jaxpr')\n- return (dict(params_known, jaxpr=jaxpr_known),\n- dict(params_staged, jaxpr=jaxpr_staged, differentiated=True))\n+def remat_partial_eval_custom_params_updater(_, __, ___, ____, params_known, params_staged):\n+ return params_known, dict(params_staged, differentiated=True)\npe.partial_eval_jaxpr_custom_rules[remat_p] = \\\npartial(pe.call_partial_eval_custom_rule, 'jaxpr',\nremat_partial_eval_custom_params_updater)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1098,8 +1098,49 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nself.frame.eqns.append(eqn)\nreturn out_tracers\npe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_process_xmap # type: ignore\n+\n+def _xmap_partial_eval_custom_params_updater(\n+ unks_in: Sequence[bool],\n+ kept_outs_known: Sequence[bool], kept_outs_staged: Sequence[bool],\n+ num_res: int, params_known: dict, params_staged: dict\n+ ) -> Tuple[dict, dict]:\n+ assert params_known['spmd_in_axes'] is None and params_known['spmd_out_axes'] is None\n+ assert params_staged['spmd_in_axes'] is None and params_staged['spmd_out_axes'] is None\n+\n+ # pruned inputs to jaxpr_known according to unks_in\n+ donated_invars_known, _ = pe.partition_list(unks_in, params_known['donated_invars'])\n+ in_axes_known, _ = pe.partition_list(unks_in, params_known['in_axes'])\n+ if num_res == 0:\n+ residual_axes = []\n+ else:\n+ residual_axes = [\n+ AxisNamePos(zip(sort_named_shape, range(len(sort_named_shape))),\n+ user_repr=f'<internal: {sort_named_shape}>')\n+ for named_shape in (v.aval.named_shape for v in params_known['call_jaxpr'].outvars[:-num_res])\n+ # We sort here to make the iteration order deterministic\n+ for sort_named_shape in [sorted(named_shape, key=str)]\n+ ]\n+ _, out_axes_known = pe.partition_list(kept_outs_known, params_known['out_axes'])\n+ new_params_known = dict(params_known,\n+ in_axes=tuple(in_axes_known),\n+ out_axes=(*out_axes_known, *residual_axes),\n+ donated_invars=tuple(donated_invars_known))\n+ assert len(new_params_known['in_axes']) == len(params_known['call_jaxpr'].invars)\n+ assert len(new_params_known['out_axes']) == len(params_known['call_jaxpr'].outvars)\n+\n+ # added num_res new inputs to jaxpr_staged\n+ donated_invars_staged = (*(False for _ in range(num_res)), *params_staged['donated_invars'])\n+ _, out_axes_staged = pe.partition_list(kept_outs_staged, params_staged['out_axes'])\n+ new_params_staged = dict(params_staged,\n+ in_axes=(*residual_axes, *params_staged['in_axes']),\n+ out_axes=tuple(out_axes_staged),\n+ donated_invars=donated_invars_staged)\n+ assert len(new_params_staged['in_axes']) == len(params_staged['call_jaxpr'].invars)\n+ assert len(new_params_staged['out_axes']) == len(params_staged['call_jaxpr'].outvars)\n+ return new_params_known, new_params_staged\npe.partial_eval_jaxpr_custom_rules[xmap_p] = \\\n- partial(pe.partial_eval_jaxpr_custom_rule_not_implemented, 'xmap')\n+ partial(pe.call_partial_eval_custom_rule, 'call_jaxpr',\n+ _xmap_partial_eval_custom_params_updater)\n@lu.transformation_with_aux\n@@ -1155,6 +1196,10 @@ def _jaxpr_trace_process_xmap(self, primitive, f: lu.WrappedFun, tracers, params\nassert not any(const_units)\nnum_consts = len(const_units)\nout_axes_no_units = [a for a, u in zip(out_axes, axes_units) if not u]\n+ const_axes: Sequence[AxisNamePos]\n+ if num_consts == 0:\n+ const_axes = ()\n+ else:\nconst_axes = [\nAxisNamePos(zip(sort_named_shape, range(len(sort_named_shape))),\nuser_repr=f'<internal: {sort_named_shape}>')\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1026,7 +1026,8 @@ def partial_eval_jaxpr_custom_rule_not_implemented(\nraise NotImplementedError(msg)\n-ParamsUpdater = Callable[[List[bool], int, dict, dict], Tuple[dict, dict]]\n+ParamsUpdater = Callable[[Sequence[bool], Sequence[bool], Sequence[bool],\n+ int, dict, dict], Tuple[dict, dict]]\ndef call_partial_eval_custom_rule(\njaxpr_param_name: str, params_updater: ParamsUpdater,\n@@ -1040,13 +1041,16 @@ def call_partial_eval_custom_rule(\n# by convention, _partial_eval_jaxpr_custom drops units on known outputs\nknown_units_out = [v.aval is core.abstract_unit for v in jaxpr.outvars]\ndropped_outs_known = map(op.or_, unks_out, known_units_out)\n+ kept_outs_known = [not d for d in dropped_outs_known]\nout_binders_known, _ = partition_list(dropped_outs_known, eqn.outvars)\n_, out_binders_staged = partition_list(inst_out, eqn.outvars)\n+ kept_outs_staged = inst_out\nnewvar = core.gensym([jaxpr_known, jaxpr_staged])\nresiduals = [newvar(v.aval) for v in jaxpr_staged.invars[:num_res]]\n- params_known = dict(eqn.params, call_jaxpr=jaxpr_known)\n- params_staged = dict(eqn.params, call_jaxpr=jaxpr_staged)\n- params_known, params_staged = params_updater(unks_in, num_res, params_known, params_staged)\n+ params_known = {**eqn.params, jaxpr_param_name: jaxpr_known}\n+ params_staged = {**eqn.params, jaxpr_param_name: jaxpr_staged}\n+ params_known, params_staged = params_updater(\n+ unks_in, kept_outs_known, kept_outs_staged, num_res, params_known, params_staged)\neqn_known = new_jaxpr_eqn(ins_known, [*out_binders_known, *residuals],\neqn.primitive, params_known, eqn.source_info)\neqn_staged = new_jaxpr_eqn([*residuals, *eqn.invars], out_binders_staged,\n@@ -1057,13 +1061,13 @@ def call_partial_eval_custom_rule(\nreturn eqn_known, eqn_staged, unks_out, inst_out, new_inst + residuals\npartial_eval_jaxpr_custom_rules[core.call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\n- lambda _, __, x, y: (x, y))\n+ lambda _, __, ___, ____, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[core.named_call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\n- lambda _, __, x, y: (x, y))\n+ lambda _, __, ___, ____, x, y: (x, y))\npartial_eval_jaxpr_custom_rules[remat_call_p] = \\\npartial(call_partial_eval_custom_rule, 'call_jaxpr',\n- lambda _, __, p1, p2: (p1, dict(p2, differentiated=True)))\n+ lambda _, __, ___, ____, p1, p2: (p1, dict(p2, differentiated=True)))\n# TODO(mattjj): unify with dce code below\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -859,7 +859,9 @@ ad.primitive_transposes[xla_call_p] = partial(ad.call_transpose, xla_call_p)\ndef _xla_call_partial_eval_custom_params_updater(\n- unks_in: List[bool], num_res: int, params_known: dict, params_staged: dict\n+ unks_in: Sequence[bool],\n+ kept_outs_known: Sequence[bool], kept_outs_staged: Sequence[bool],\n+ num_res: int, params_known: dict, params_staged: dict\n) -> Tuple[dict, dict]:\n# pruned inputs to jaxpr_known according to unks_in, so prune donated_invars\ndonated_invars_known, _ = partition_list(unks_in, params_known['donated_invars'])\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -659,10 +659,9 @@ class XMapTest(XMapTestCase):\n\"called with:\\n.*int32.*\",\nlambda: f_exe(x_i32))\n- def testNewCheckpointError(self):\n+ def testNewCheckpoint(self):\nf = checkpoint(xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...]))\n- with self.assertRaisesRegex(NotImplementedError, 'xmap'):\n- jax.grad(f)(jnp.arange(3.))\n+ self.assertAllClose(jax.grad(lambda x: f(x).sum())(jnp.arange(3.)), jnp.ones(3))\nclass XMapTestSPMD(SPMDTestMixin, XMapTest):\n" } ]
Python
Apache License 2.0
google/jax
Add a partial_eval_jaxpr_custom_rule for xmap Additionaly fix a bug in partial_eval rule for xmap. PiperOrigin-RevId: 428738277
260,287
15.02.2022 04:00:19
28,800
b75b0c04dee4a384864d4e9af1dad3783acf5336
Limit the set of unspecified dims to those that are not explicitly converted to MANUAL.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1967,7 +1967,7 @@ def _full_to_shard_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\nsx = mlir.wrap_with_sharding_op(x, sharding_proto, unspecified_dims=unspecified_dims)\nmanual_proto = _manual_proto(aval_in, axes, mesh)\nresult_type, = mlir.aval_to_ir_types(aval_out)\n- return [mlir.wrap_with_full_to_shard_op(result_type, sx, manual_proto, unspecified_dims=set(range(aval_in.ndim)))]\n+ return mlir.wrap_with_full_to_shard_op(result_type, sx, manual_proto, unspecified_dims=unspecified_dims),\nshard_to_full_p = core.Primitive('shard_to_full')\n@@ -1982,10 +1982,10 @@ def _shard_to_full_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\naval_out, = ctx.avals_out\nmanual_proto = _manual_proto(aval_in, axes, mesh)\nresult_type, = mlir.aval_to_ir_types(aval_out)\n- sx = mlir.wrap_with_sharding_op(x, manual_proto, unspecified_dims=set(range(aval_in.ndim)))\n- sharding_proto = mesh_sharding_specs(mesh.shape, mesh.axis_names)(aval_out, axes).sharding_proto()\nunspecified_dims = set(range(aval_in.ndim)) - set(axes.values())\n- return [mlir.wrap_with_shard_to_full_op(result_type, sx, sharding_proto, unspecified_dims)]\n+ sx = mlir.wrap_with_sharding_op(x, manual_proto, unspecified_dims=unspecified_dims)\n+ sharding_proto = mesh_sharding_specs(mesh.shape, mesh.axis_names)(aval_out, axes).sharding_proto()\n+ return mlir.wrap_with_shard_to_full_op(result_type, sx, sharding_proto, unspecified_dims),\n@lu.transformation\ndef vtile_manual(mesh: Mesh,\n" } ]
Python
Apache License 2.0
google/jax
Limit the set of unspecified dims to those that are not explicitly converted to MANUAL. PiperOrigin-RevId: 428740792
260,287
15.02.2022 10:12:31
28,800
a14ccb99d984ceb079267dd44d38901a2a9b057d
Try adding support for nesting with_sharding_constraint in MANUAL xmaps
[ { "change_type": "MODIFY", "old_path": "jax/_src/dispatch.py", "new_path": "jax/_src/dispatch.py", "diff": "@@ -256,8 +256,8 @@ def lower_xla_callable(fun: lu.WrappedFun, device, backend, name,\nmodule_name = f\"jit_{fun.__name__}\"\nif config.jax_enable_mlir:\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform, axis_env, name_stack,\n- donated_invars)\n+ module_name, closed_jaxpr, backend.platform,\n+ mlir.ReplicaAxisContext(axis_env), name_stack, donated_invars)\nelse:\nmodule = xla.lower_jaxpr_to_xla_module(\nmodule_name, closed_jaxpr, backend.platform, axis_env,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -2607,7 +2607,8 @@ def _shard_value(mesh: maps.Mesh,\ntype=int(sharding_proto.type),\ntile_assignment_dimensions=sharding_proto.tile_assignment_dimensions,\ntile_assignment_devices=sharding_proto.tile_assignment_devices,\n- replicate_on_last_tile_dim=sharding_proto.replicate_on_last_tile_dim))\n+ replicate_on_last_tile_dim=sharding_proto.replicate_on_last_tile_dim,\n+ last_tile_dims=sharding_proto.last_tile_dims))\nreturn xla_sharding.Sharding(proto=xla_sharding_proto).apply_to_tensor(\nval, use_sharding_op=True)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -1372,13 +1372,16 @@ pxla.SPMDBatchTrace.process_xmap = partialmethod(_batch_trace_process_xmap, True\n# -------- nested xmap handling --------\n-def _xmap_lowering_rule(*args, **kwargs):\n+def _xmap_lowering_rule(ctx, *args, **kwargs):\n+ if isinstance(ctx.module_context.axis_context, mlir.SPMDAxisContext):\nif config.experimental_xmap_spmd_lowering_manual:\n- return _xmap_lowering_rule_spmd_manual(*args, **kwargs)\n- elif config.experimental_xmap_spmd_lowering:\n- return _xmap_lowering_rule_spmd(*args, **kwargs)\n+ return _xmap_lowering_rule_spmd_manual(ctx, *args, **kwargs)\n+ else:\n+ return _xmap_lowering_rule_spmd(ctx, *args, **kwargs)\n+ elif isinstance(ctx.module_context.axis_context, mlir.ReplicaAxisContext):\n+ return _xmap_lowering_rule_replica(ctx, *args, **kwargs)\nelse:\n- return _xmap_lowering_rule_replica(*args, **kwargs)\n+ raise AssertionError(\"Unrecognized axis context type!\")\nmlir.register_lowering(xmap_p, _xmap_lowering_rule)\ndef _xmap_lowering_rule_replica(ctx, *in_nodes,\n@@ -1547,9 +1550,12 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\n# We in-line here rather than generating a Call HLO as in the xla_call\n# translation rule just because the extra tuple stuff is a pain.\n+ manual_mesh_axes = frozenset(it.chain.from_iterable(plan.physical_axis_resources.values()))\n+ assert isinstance(ctx.module_context.axis_context, mlir.SPMDAxisContext)\nsub_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\n- xla.wrap_name(name, 'xmap')))\n+ xla.wrap_name(name, 'xmap')),\n+ axis_context=ctx.module_context.axis_context.extend_manual(manual_mesh_axes))\nglobal_out_nodes = mlir.jaxpr_subcomp(sub_ctx, vectorized_jaxpr, (),\n*([n] for n in global_in_nodes))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/pjit.py", "new_path": "jax/experimental/pjit.py", "diff": "from enum import IntEnum\nimport numpy as np\nfrom collections import OrderedDict, Counter\n-from typing import Callable, Sequence, Tuple, Union\n+from typing import Callable, Sequence, Tuple, Union, Optional\nfrom warnings import warn\nimport itertools as it\nfrom functools import partial\n@@ -587,6 +587,7 @@ def _pjit_translation_rule(ctx, avals_in, avals_out, *in_nodes, name,\njaxpr, in_axis_resources, out_axis_resources,\nresource_env, donated_invars, in_positional_semantics,\nout_positional_semantics):\n+ # TODO: Make this into an MLIR rule and use manual_axes!\nmesh = resource_env.physical_mesh\nsubc = xc.XlaBuilder(f\"pjit_{name}\")\n@@ -918,7 +919,7 @@ def _sharding_constraint_mhlo_lowering(ctx, x_node, *, axis_resources,\nreturn [\nmlir.wrap_with_sharding_op(\nx_node,\n- get_aval_sharding_proto(aval, axis_resources, mesh),\n+ get_aval_sharding_proto(aval, axis_resources, mesh, ctx.module_context.axis_context),\nunspecified_dims=get_unconstrained_dims(axis_resources))\n]\nmlir.register_lowering(sharding_constraint_p,\n@@ -957,11 +958,17 @@ def get_array_mapping(axis_resources: ParsedPartitionSpec) -> pxla.ArrayMapping:\ndef get_aval_sharding_proto(aval: core.AbstractValue,\naxis_resources: ParsedPartitionSpec,\n- mesh: maps.Mesh) -> xc.OpSharding:\n+ mesh: maps.Mesh,\n+ axis_ctx: Optional[mlir.SPMDAxisContext] = None) -> xc.OpSharding:\narray_mapping = get_array_mapping(axis_resources)\nsharding_spec = pxla.mesh_sharding_specs(mesh.shape, mesh.axis_names)(\naval, array_mapping)\n- return sharding_spec.sharding_proto()\n+ special_axes = {}\n+ if axis_ctx is not None:\n+ axis_names = mesh.axis_names\n+ for manual_axis in axis_ctx.manual_axes:\n+ special_axes[axis_names.index(manual_axis)] = xc.OpSharding.Type.MANUAL\n+ return sharding_spec.sharding_proto(special_axes=special_axes)\ndef get_unconstrained_dims(axis_resources: ParsedPartitionSpec):\n@@ -1135,7 +1142,13 @@ def parse_op_sharding(op_sharding, mesh):\ndim_size //= axis_size\ndim_partitions.append(axis)\npartitions.append(tuple(dim_partitions))\n- if op_sharding.replicate_on_last_tile_dim:\n+ if op_sharding.last_tile_dims == [xc.OpSharding.Type.REPLICATED]:\n+ replicate_on_last_tile_dim = True\n+ else:\n+ replicate_on_last_tile_dim = op_sharding.replicate_on_last_tile_dim\n+ if op_sharding.last_tile_dims:\n+ raise NotImplementedError(\"Unhandled OpSharding type. Please open a bug report!\")\n+ if replicate_on_last_tile_dim:\npartitions = partitions[:-1]\nreturn ParsedPartitionSpec('<internally generated spec>', partitions)\nelse:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/mlir.py", "new_path": "jax/interpreters/mlir.py", "diff": "@@ -24,7 +24,7 @@ import itertools\nimport re\nimport typing\nfrom typing import (Any, Callable, Dict, List, Optional, Sequence, Set, Tuple,\n- Type, Union)\n+ Type, Union, FrozenSet)\nfrom typing_extensions import Protocol\nimport warnings\n@@ -289,6 +289,42 @@ def make_ir_context() -> ir.Context:\nreturn context\n+Mesh = Any\n+MeshAxisName = Any\n+\n+@dataclasses.dataclass(frozen=True)\n+class SPMDAxisContext:\n+ \"\"\"A hardware axis context for parallel computations that use the GSPMD partitioner.\n+\n+ This includes the mesh that will later by used to execute this computation,\n+ as well as a set of mesh axes that are currently (e.g. because the current lowering\n+ is invoked inside an xmap) lowered in the MANUAL sharding mode.\n+ \"\"\"\n+ mesh: Mesh\n+ manual_axes: FrozenSet[MeshAxisName] = frozenset()\n+\n+ @property\n+ def 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+\n+ def extend_manual(self, axes: FrozenSet[MeshAxisName]) -> 'SPMDAxisContext':\n+ return SPMDAxisContext(self.mesh, self.manual_axes | axes)\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class ReplicaAxisContext:\n+ \"\"\"A hardware axis context for parallel computations that are partitioned by JAX.\n+\n+ Unlike in the SPMDAxisContext, this means that JAX might need to emit calls to\n+ explicit collectives.\n+ \"\"\"\n+ axis_env: xla.AxisEnv\n+\n+AxisContext = Union[SPMDAxisContext, ReplicaAxisContext]\n+\n@dataclasses.dataclass\nclass ModuleContext:\n\"\"\"Module-wide context information for MLIR lowering.\"\"\"\n@@ -297,14 +333,18 @@ class ModuleContext:\nip: ir.InsertionPoint\nsymbol_table: ir.SymbolTable\nplatform: str\n- axis_env: xla.AxisEnv\n+ axis_context: AxisContext\nname_stack: str\n# Cached primitive lowerings.\ncached_primitive_lowerings: Dict[Any, builtin.FuncOp]\n+ @property\n+ def axis_env(self) -> xla.AxisEnv:\n+ return self.axis_context.axis_env\n+\ndef __init__(\n- self, platform: str, axis_env: xla.AxisEnv, name_stack: str,\n+ self, platform: str, axis_context: AxisContext, name_stack: str,\ncontext: Optional[ir.Context] = None,\nmodule: Optional[ir.Module] = None,\nip: Optional[ir.InsertionPoint] = None,\n@@ -316,7 +356,7 @@ class ModuleContext:\nself.ip = ip or ir.InsertionPoint(self.module.operation.opview.body)\nself.symbol_table = symbol_table or ir.SymbolTable(self.module.operation)\nself.platform = platform\n- self.axis_env = axis_env\n+ self.axis_context = axis_context\nself.name_stack = name_stack\nself.cached_primitive_lowerings = ({} if cached_primitive_lowerings is None\nelse cached_primitive_lowerings)\n@@ -371,7 +411,7 @@ _module_name_regex = re.compile(r\"[^\\w.-]\")\ndef lower_jaxpr_to_module(\nmodule_name: str, jaxpr: core.ClosedJaxpr, platform: str,\n- axis_env: xla.AxisEnv,\n+ axis_context: AxisContext,\nname_stack: str, donated_args: Sequence[bool],\nreplicated_args: Optional[Sequence[bool]] = None,\narg_shardings: Optional[Sequence[Optional[xc.OpSharding]]] = None,\n@@ -395,7 +435,7 @@ def lower_jaxpr_to_module(\nmsg = f\"Donation is not implemented for {platform}.\\n{msg}\"\nwarnings.warn(f\"Some donated buffers were not usable: {', '.join(unused_donations)}.\\n{msg}\")\n- ctx = ModuleContext(platform, axis_env, name_stack)\n+ ctx = ModuleContext(platform, axis_context, name_stack)\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" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -36,7 +36,7 @@ import itertools as it\nimport operator as op\nimport threading\nfrom typing import (Any, Callable, Dict, List, NamedTuple, Optional,\n- Sequence, Set, Tuple, Type, Union, Iterable, cast)\n+ Sequence, Set, Tuple, Type, Union, Iterable, Mapping, cast)\nimport enum\nimport sys\n@@ -104,6 +104,9 @@ AvalDimSharding = Union[Unstacked, Chunked, NoSharding]\nMeshDimAssignment = Union[ShardedAxis, Replicated]\nShardingSpec = pmap_lib.ShardingSpec\n+MeshAxisName = Any\n+OpShardingType = Any\n+\ndef sharding_spec_mesh_shape(self):\nsharded_axis_sizes = []\n@@ -119,7 +122,7 @@ def sharding_spec_mesh_shape(self):\nreturn tuple(sharded_axis_sizes[a.axis] if isinstance(a, ShardedAxis) else a.replicas\nfor a in self.mesh_mapping)\n-def sharding_spec_sharding_proto(self):\n+def sharding_spec_sharding_proto(self, special_axes: Mapping[int, OpShardingType] = {}):\n\"\"\"Converts a ShardingSpec to an OpSharding proto.\nSee\n@@ -135,14 +138,14 @@ def sharding_spec_sharding_proto(self):\nreplicated_maxes = [] # lists mesh axis identifiers to replicate over\nfor maxis, assignment in enumerate(self.mesh_mapping):\nif isinstance(assignment, Replicated):\n- replicated_maxes.append(maxis)\n+ replicated_maxes.append((maxis, assignment.replicas))\nelif isinstance(assignment, ShardedAxis):\nsharded_axes[assignment.axis] = maxis\nelse:\nassert_unreachable(assignment)\nproto = xc.OpSharding()\n- if len(replicated_maxes) == len(self.mesh_mapping):\n+ if len(replicated_maxes) == len(self.mesh_mapping) and not special_axes:\nproto.type = xc.OpSharding.Type.REPLICATED\nreturn proto\nelse:\n@@ -166,11 +169,22 @@ def sharding_spec_sharding_proto(self):\nelse:\nassert_unreachable(sharding)\n- # Create the partial sharding proto if tensor is replicated over some mesh axes\n+ # Create a partial sharding proto if tensor is replicated or partitioned\n+ # specially over some mesh axes.\nif replicated_maxes:\n- new_mesh_shape.append(-1)\n- mesh_permutation.extend(replicated_maxes)\n- proto.replicate_on_last_tile_dim = True\n+ last_tile_dims = []\n+ axes_by_type: Dict[OpShardingType, List[MeshAxisName]] = {}\n+ size_by_type: Dict[OpShardingType, int] = defaultdict(lambda: 1)\n+ assert set(x[0] for x in replicated_maxes).issuperset(set(special_axes.keys()))\n+ for axis, size in replicated_maxes:\n+ ty = special_axes.get(axis, xc.OpSharding.Type.REPLICATED)\n+ axes_by_type.setdefault(ty, []).append(axis)\n+ size_by_type[ty] *= size\n+ for ty, axes in sorted(axes_by_type.items(), key=lambda x: x[0].value):\n+ last_tile_dims.append(ty)\n+ new_mesh_shape.append(size_by_type[ty])\n+ mesh_permutation.extend(axes)\n+ proto.last_tile_dims = last_tile_dims\nproto_mesh = mesh.transpose(mesh_permutation).reshape(new_mesh_shape)\nproto.tile_assignment_dimensions = list(proto_mesh.shape)\n@@ -383,7 +397,6 @@ def _shard_abstract_array(size, axis: int, x):\nreturn x.update(shape=tuple_delete(x.shape, axis))\nshard_aval_handlers[ShapedArray] = _shard_abstract_array\n-MeshAxisName = Any\n\"\"\"\nArrayMapping specifies how an ndarray should map to mesh axes.\n@@ -1033,7 +1046,7 @@ def lower_parallel_callable(\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nif config.jax_enable_mlir:\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform, axis_env,\n+ module_name, closed_jaxpr, backend.platform, mlir.ReplicaAxisContext(axis_env),\nname_stack, donated_invars, replicated_args=replicated_args,\narg_shardings=_shardings_to_mlir_shardings(parts.arg_parts),\nresult_shardings=_shardings_to_mlir_shardings(parts.out_parts))\n@@ -1757,7 +1770,7 @@ def _pmap_lowering(ctx, *in_nodes, axis_name,\nwith maybe_extend_axis_env(axis_name, global_axis_size, None): # type: ignore\nsub_ctx = ctx.module_context.replace(\n- axis_env=new_env,\n+ axis_context=mlir.ReplicaAxisContext(new_env),\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\nutil.wrap_name(name, 'pmap')))\nsharded_outs = mlir.jaxpr_subcomp(sub_ctx, call_jaxpr, (),\n@@ -2066,6 +2079,7 @@ def lower_mesh_computation(\ntuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU\nin_partitions: Optional[List[Optional[xc.OpSharding]]]\nout_partitions: Optional[List[Optional[xc.OpSharding]]]\n+ axis_ctx: mlir.AxisContext\nif spmd_lowering:\nreplicated_args = [False] * len(in_jaxpr_avals)\nglobal_sharding_spec = mesh_sharding_specs(global_axis_sizes, mesh.axis_names)\n@@ -2076,7 +2090,7 @@ def lower_mesh_computation(\nfor aval, aval_out_axes in safe_zip(global_out_avals, out_axes)]\nout_partitions_t = xla.tuple_sharding_proto(out_partitions)\npartitions_proto = True\n- axis_env = xla.AxisEnv(nreps=1, names=(), sizes=()) # All named axes have been vmapped\n+ axis_ctx = mlir.SPMDAxisContext(mesh)\nelse:\nreplicated_args = [not axis for axis in in_axes]\nin_partitions = None\n@@ -2086,13 +2100,14 @@ def lower_mesh_computation(\naxis_env = xla.AxisEnv(nreps=mesh.size,\nnames=tuple(global_axis_sizes.keys()),\nsizes=tuple(global_axis_sizes.values()))\n+ axis_ctx = mlir.ReplicaAxisContext(axis_env)\nclosed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\nmodule: Union[str, xc.XlaComputation]\nmodule_name = f\"xmap_{fun.__name__}\"\nwith core.extend_axis_env_nd(mesh.shape.items()):\nif config.jax_enable_mlir:\nmodule = mlir.lower_jaxpr_to_module(\n- module_name, closed_jaxpr, backend.platform, axis_env, name_stack,\n+ module_name, closed_jaxpr, backend.platform, axis_ctx, name_stack,\ndonated_invars, replicated_args=replicated_args,\narg_shardings=in_partitions, result_shardings=out_partitions)\nelse:\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -39,7 +39,7 @@ from jax import lax\nfrom jax import core\nfrom jax.core import NamedShape, JaxprTypeError\nfrom jax.experimental import maps\n-from jax.experimental.pjit import pjit\n+from jax.experimental.pjit import pjit, with_sharding_constraint\nfrom jax.experimental.pjit import PartitionSpec as P\nfrom jax.experimental.maps import Mesh, mesh, xmap, serial_loop, SerialLoop\nfrom jax.errors import JAXTypeError\n@@ -723,6 +723,15 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(20, dtype=jnp.float32)\nself.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+ @jtu.with_mesh([('x', 2), ('y', 1)])\n+ def testNestedConstraint(self):\n+ # TODO(b/219691408): Using P('y') instead of P() causes an XLA crash!\n+ fimpl = lambda x: with_sharding_constraint(jnp.sin(x), P()) + x\n+ f = xmap(fimpl, in_axes=['i', ...], out_axes=['i', ...], axis_resources={'i': 'x'})\n+ h = pjit(lambda x: f(x * x) + x, in_axis_resources=P('y'), out_axis_resources=None)\n+ x = jnp.arange(20, dtype=jnp.float32).reshape(4, 5)\n+ self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+\nclass NamedNumPyTest(XMapTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Try adding support for nesting with_sharding_constraint in MANUAL xmaps PiperOrigin-RevId: 428812729
260,424
15.02.2022 13:12:19
28,800
b15c7f609a01cc0a420141ef4ea30b37d0297666
Checkify: fix check_error of nd-error.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3202,7 +3202,7 @@ def _select_shape_rule(which, *cases):\nraise TypeError(\"select must have at least one case\")\nif any(case.shape != cases[0].shape for case in cases[1:]):\nmsg = \"select cases must have the same shapes, got [{}].\"\n- raise TypeError(msg.format(\",\".join(map(str(c.shape) for c in cases))))\n+ raise TypeError(msg.format(\", \".join([str(c.shape) for c in cases])))\nif which.shape and which.shape != cases[0].shape:\nmsg = (\"select `which` must be scalar or have the same shape as cases, \"\n\"got `which` shape {} but case shape {}.\")\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -410,7 +410,11 @@ def check_error(error: Error) -> None:\n>>> # can re-checkify\n>>> error, _ = checkify.checkify(with_inner_jit)(-1)\n\"\"\"\n- return assert_p.bind(~error.err, error.code, msgs=error.msgs)\n+ if np.size(error.err) > 1:\n+ err, code = _reduce_any_error(error.err, error.code)\n+ else:\n+ err, code = error.err, error.code\n+ return assert_p.bind(~err, code, msgs=error.msgs)\nassert_p = core.Primitive('assert') # TODO: rename to check?\nassert_p.multiple_results = True # zero results\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -560,6 +560,24 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"hi\")\n+ def test_check_error_scanned(self):\n+ def body(carry, x):\n+ checkify.check(jnp.all(x > 0), \"should be negative\")\n+ return carry, x\n+\n+ def checked_body(carry, x):\n+ err, (carry, x) = checkify.checkify(body)(carry, x)\n+ return carry, (x, err)\n+\n+ def f(x):\n+ _, (xs, errs) = jax.lax.scan(checked_body, (None,), x)\n+ checkify.check_error(errs)\n+ return xs\n+\n+ err, _ = checkify.checkify(f)(jnp.array([-1, 0, -1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"should be negative\")\n+\ndef test_discharge_recharge(self):\ndef ejit(f):\nf = checkify.checkify(f)\n" } ]
Python
Apache License 2.0
google/jax
Checkify: fix check_error of nd-error. PiperOrigin-RevId: 428857813
260,573
16.02.2022 09:02:55
0
c1cbf786117654e51f8f465aaf036d0f2e213ada
fix: use boolean tf functions where possible instead of casting to int8 for jax2tf
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1348,7 +1348,7 @@ def _not(x):\ntf_impl[lax.not_p] = _not\n-def bool_to_int8(f, argnums: Sequence[int]):\n+def handle_boolean_args(f, argnums: Sequence[int], boolean_f=None):\n\"\"\"Computes functions with some bool args and bool results using int8.\nThis is needed because some TF ops do not work for bool args, e.g.,\n@@ -1357,12 +1357,14 @@ def bool_to_int8(f, argnums: Sequence[int]):\nArgs:\nf: a TF callable to wrap. It will be called with non-boolean arguments.\nargnums: the positional arguments that may be booleans.\n+ boolean_f: [Optional] a TF callable compatible with boolean\n+ arguments.\nReturns: a TF callable that can take a mix of boolean positional arguments\n(in the positions specified by `argnums`) and some non-boolean positional\narguments. If there are no boolean arguments, just calls `f`. Otherwise,\n- casts the boolean arguments to `int8`, calls `f`, then casts the result to\n- `bool`.\n+ it calls `boolean_f` if defined. Otherwise, casts the boolean\n+ arguments to `int8`, calls `f`, then casts the result to `bool`.\n\"\"\"\nargnums = tf.nest.flatten(argnums)\n@@ -1373,6 +1375,9 @@ def bool_to_int8(f, argnums: Sequence[int]):\nelse:\n# All argnums should be boolean\nassert len(argnum_types) == 1, argnum_types\n+ if boolean_f != None:\n+ return boolean_f(*args **kwargs)\n+ else:\nargs_cast = [(tf.cast(a, tf.int8) if i in argnums else a)\nfor i, a in enumerate(args)]\nif \"_in_avals\" in kwargs:\n@@ -1394,17 +1399,22 @@ def bool_to_int8(f, argnums: Sequence[int]):\nreturn wrapper\n-tf_impl[lax.or_p] = bool_to_int8(tf.bitwise.bitwise_or, argnums=(0, 1))\n-tf_impl[lax.and_p] = bool_to_int8(tf.bitwise.bitwise_and, argnums=(0, 1))\n-tf_impl[lax.xor_p] = bool_to_int8(tf.bitwise.bitwise_xor, argnums=(0, 1))\n+tf_impl[lax.or_p] = handle_boolean_args(tf.bitwise.bitwise_or, argnums=(0, 1), boolean_f=tf.logical_or)\n+tf_impl[lax.and_p] = handle_boolean_args(tf.bitwise.bitwise_and, argnums=(0, 1), boolean_f=tf.logical_and)\n+tf_impl[lax.xor_p] = handle_boolean_args(tf.bitwise.bitwise_xor, argnums=(0, 1), boolean_f=tf.math.logical_xor)\ntf_impl[lax.eq_p] = tf.math.equal\ntf_impl[lax.ne_p] = tf.math.not_equal\n-tf_impl[lax.ge_p] = bool_to_int8(tf.math.greater_equal, argnums=(0, 1))\n-tf_impl[lax.gt_p] = bool_to_int8(tf.math.greater, argnums=(0, 1))\n-tf_impl[lax.le_p] = bool_to_int8(tf.math.less_equal, argnums=(0, 1))\n-tf_impl[lax.lt_p] = bool_to_int8(tf.math.less, argnums=(0, 1))\n+bool_greater = lambda x,y: tf.logical_and(x, tf.logical_not(y)) # Only one combo: T,F -> T\n+bool_less = lambda x,y: tf.logical_and(tf.logical_not(x), y) # Only one combo: F,T -> T\n+def accept_equal(fn):\n+ return lambda x,y: tf.logical_or(tf.math.equal(x,y), fn(x,y)) # adds cases X,X -> T, X{T,F} to a boolean function of two arguments\n+\n+tf_impl[lax.ge_p] = handle_boolean_args(tf.math.greater_equal, argnums=(0, 1), boolean_f=accept_equal(bool_greater))\n+tf_impl[lax.gt_p] = handle_boolean_args(tf.math.greater, argnums=(0, 1), boolean_f=bool_greater)\n+tf_impl[lax.le_p] = handle_boolean_args(tf.math.less_equal, argnums=(0, 1), boolean_f=accept_equal(bool_less))\n+tf_impl[lax.lt_p] = handle_boolean_args(tf.math.less, argnums=(0, 1), boolean_f=bool_less)\ntf_impl[lax.linalg.cholesky_p] = tf.linalg.cholesky\n@@ -1671,10 +1681,20 @@ axes_to_axis = lambda func: lambda operand, axes: func(operand, axis=axes)\n# reduce_sum and reduce_prod are not supported for bool\ntf_impl[lax.reduce_sum_p] = axes_to_axis(tf.reduce_sum)\ntf_impl[lax.reduce_prod_p] = axes_to_axis(tf.reduce_prod)\n-tf_impl[lax.reduce_max_p] = (\n- bool_to_int8(axes_to_axis(tf.reduce_max), argnums=[0]))\n-tf_impl[lax.reduce_min_p] = (\n- bool_to_int8(axes_to_axis(tf.reduce_min), argnums=[0]))\n+tf_impl[lax.reduce_max_p] = handle_boolean_args(\n+ axes_to_axis(tf.reduce_max), argnums=[0],\n+ boolean_f=axes_to_axis(tf.reduce_any))\n+\n+def bool_reduce_min(x, axes):\n+ return tf.logical_not(\n+ axes_to_axis(tf.reduce_any)(\n+ tf.logical_not(x),\n+ axes\n+ )\n+ )\n+tf_impl[lax.reduce_min_p] = handle_boolean_args(\n+ axes_to_axis(tf.reduce_min), argnums=[0],\n+ boolean_f=bool_reduce_min)\ntf_impl[lax.reduce_or_p] = axes_to_axis(tf.reduce_any)\ntf_impl[lax.reduce_and_p] = axes_to_axis(tf.reduce_all)\n@@ -2018,7 +2038,7 @@ def _select_and_scatter(operand, source, init_value, select_jaxpr,\ntf_impl[lax.select_and_scatter_p] = _select_and_scatter\n-@partial(bool_to_int8, argnums=(0, 1))\n+@partial(handle_boolean_args, argnums=(0, 1))\ndef _select_and_scatter_add(source, operand, *, select_prim, window_dimensions,\nwindow_strides, padding, _in_avals, _out_aval):\ninit_value = tf.zeros((), operand.dtype)\n@@ -2093,7 +2113,7 @@ def _gather_dimensions_proto(indices_shape, dimension_numbers):\nreturn proto\n-@partial(bool_to_int8, argnums=[0])\n+@partial(handle_boolean_args, argnums=[0])\ndef _gather(operand, start_indices, *, dimension_numbers, slice_sizes: core.Shape,\nindices_are_sorted, unique_indices, mode, fill_value,\n_in_avals: Sequence[core.ShapedArray],\n" } ]
Python
Apache License 2.0
google/jax
fix: use boolean tf functions where possible instead of casting to int8 for jax2tf
260,411
16.02.2022 15:41:37
-3,600
461b37b2a80a6a3f46a35941c5b0f7401fae6253
[jax2tf] Fixed stale documentation about XLA metadata. jax2tf does not yet support passing source location information through to TF. The mechanism is partially implemented but disabled. Here we remove misleading documentation that suggests the mechanism is enabled.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -606,13 +606,6 @@ operations. There is support for `sharded_jit` and `pjit`.\nIf you suspect that the SavedModel is larger than it should be, check first\nthat you are not including the parameters as constants in the graph (see [above](#usage-saved-model)).\n-Additionally, the SavedModel obtained from a `jax2tf.convert`-ed function may include source\n-location information. This ensures that the debugging experience is similar\n-for JAX with XLA vs. `jax2tf.convert` with XLA. However, this debugging information\n-increases the size of the SavedModel, even possibly doubling it. You can\n-disable the generation of this metadata with the parameter\n-`include_xla_op_metadata`.\n-\n### SavedModel supports only first-order gradients\nThe `jax2tf`-converted function supports higher-order gradients, but when the\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -163,7 +163,8 @@ class _ThreadLocalState(threading.local):\nself.shape_env: Sequence[Tuple[str, TfVal]] = ()\n# Whether to actually include XLA op metadata in the generated TF ops\n- self.include_xla_op_metadata = True\n+ # TODO(b/189306134): implement support for XLA metadata\n+ self.include_xla_op_metadata = False\n# A cache for the tf.convert_to_tensor for constants. We try to preserve\n# sharing for constants, to enable tf.Graph to take advantage of it.\n@@ -415,6 +416,7 @@ def convert(fun: Callable,\n_thread_local_state.enable_xla = enable_xla\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_thread_local_state.shape_env = shape_env\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fixed stale documentation about XLA metadata. jax2tf does not yet support passing source location information through to TF. The mechanism is partially implemented but disabled. Here we remove misleading documentation that suggests the mechanism is enabled.
260,411
16.02.2022 16:16:08
-3,600
1928f6e6b10ed59d09d6af65b7d162773fe5d577
[jax2tf] Fixes shape polymorphism for jnp.take_along_axes Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -5624,7 +5624,7 @@ def take_along_axis(arr, indices, axis: Optional[int]):\nidx_shape = indices.shape\nout_shape = lax.broadcast_shapes(idx_shape, arr_shape)\n- index_dims = [i for i, idx in enumerate(idx_shape) if i == axis or idx != 1]\n+ index_dims = [i for i, idx in enumerate(idx_shape) if i == axis or not core.symbolic_equal_dim(idx, 1)]\ngather_index_shape = tuple(np.array(out_shape)[index_dims]) + (1,)\ngather_indices = []\n@@ -5641,7 +5641,7 @@ def take_along_axis(arr, indices, axis: Optional[int]):\nstart_index_map.append(i)\ncollapsed_slice_dims.append(i)\nj += 1\n- elif idx_shape[i] != 1:\n+ elif not core.symbolic_equal_dim(idx_shape[i], 1):\n# TODO(mattjj): next line needs updating for dynamic shapes\niota = lax.iota(_dtype(indices), out_shape[i]) # type: ignore\niota = lax.broadcast_in_dim(iota, gather_index_shape, (j,))\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": "@@ -1623,6 +1623,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda a, i: jnp.take(a, i, axis=1),\n[RandArg((3, 4, 5), _f32), np.array([1, 2], np.int32)],\npoly_axes=[0, None], enable_and_diable_xla=True),\n+ _make_harness(\"take_along_axis\", \"0\",\n+ lambda x, y: jnp.take_along_axis(x, y, axis=0),\n+ [RandArg((5, 2), _f32), RandArg((5, 1), _f32)],\n+ poly_axes=[0, 0]),\n+ _make_harness(\"take_along_axis\", \"1\",\n+ lambda x, y: jnp.take_along_axis(x, y, axis=1),\n+ [RandArg((5, 2), _f32), RandArg((5, 1), _f32)],\n+ poly_axes=[0, 0]),\n_make_harness(\"tile\", \"0\",\nlambda x: jnp.tile(x, (1, 2)),\n[RandArg((4, 3), _f32)],\n@@ -1788,7 +1796,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=\"reshape_1_poly_axes=[(0, 1)]\"\n+ #one_containing=\"take_along_axis_1_poly_axes=[0, 0]\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fixes shape polymorphism for jnp.take_along_axes Fixes: #9552
260,424
16.02.2022 19:12:54
0
758c721605220ecc7de4fc208fc62dbaa8a26f30
Checkify: fix nd-error case when array only has 1 element.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify.py", "diff": "@@ -410,7 +410,7 @@ def check_error(error: Error) -> None:\n>>> # can re-checkify\n>>> error, _ = checkify.checkify(with_inner_jit)(-1)\n\"\"\"\n- if np.size(error.err) > 1:\n+ if np.shape(error.err):\nerr, code = _reduce_any_error(error.err, error.code)\nelse:\nerr, code = error.err, error.code\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -562,7 +562,7 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ndef test_check_error_scanned(self):\ndef body(carry, x):\n- checkify.check(jnp.all(x > 0), \"should be negative\")\n+ checkify.check(jnp.all(x > 0), \"should be positive\")\nreturn carry, x\ndef checked_body(carry, x):\n@@ -574,9 +574,13 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ncheckify.check_error(errs)\nreturn xs\n- err, _ = checkify.checkify(f)(jnp.array([-1, 0, -1]))\n+ err, _ = checkify.checkify(f)(jnp.array([-1]))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"should be negative\")\n+ self.assertStartsWith(err.get(), \"should be positive\")\n+\n+ err, _ = checkify.checkify(f)(jnp.array([1, 0, -1]))\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"should be positive\")\ndef test_discharge_recharge(self):\ndef ejit(f):\n" } ]
Python
Apache License 2.0
google/jax
Checkify: fix nd-error case when array only has 1 element.
260,397
12.02.2022 02:55:53
-3,600
514d8883ce958a6e07f8fc106f4c27799d2ee9a4
adds jax.scipy.schur
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/linalg.py", "new_path": "jax/_src/scipy/linalg.py", "diff": "@@ -103,7 +103,18 @@ def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,\ndel overwrite_a, overwrite_b, turbo, check_finite\nreturn _eigh(a, b, lower, eigvals_only, eigvals, type)\n-\n+@partial(jit, static_argnames=('output',))\n+def _schur(a, output):\n+ if output == \"complex\":\n+ a = a.astype(jnp.result_type(a.dtype, 0j))\n+ return lax_linalg.schur(a)\n+\n+@_wraps(scipy.linalg.schur)\n+def schur(a, output='real'):\n+ if output not in ('real', 'complex'):\n+ raise ValueError(\n+ \"Expected 'output' to be either 'real' or 'complex', got output={}.\".format(output))\n+ return _schur(a, output)\n@_wraps(scipy.linalg.inv)\ndef inv(a, overwrite_a=False, check_finite=True):\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -21,6 +21,7 @@ from jax._src.scipy.linalg import (\ncho_solve as cho_solve,\ndet as det,\neigh as eigh,\n+ schur as schur,\neigh_tridiagonal as eigh_tridiagonal,\nexpm as expm,\nexpm_frechet as expm_frechet,\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -1373,6 +1373,20 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nreturn jsp.linalg.expm(x, upper_triangular=False, max_squarings=16)\njtu.check_grads(expm, (a,), modes=[\"fwd\", \"rev\"], order=1, atol=tol,\nrtol=tol)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\": shape, \"dtype\": dtype\n+ } for shape in [(4, 4), (15, 15), (50, 50), (100, 100)]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSchur(self, shape, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp.linalg.schur, jsp.linalg.schur, args_maker)\n+ self._CompileAndCheck(jsp.linalg.schur, args_maker)\n@jtu.with_config(jax_numpy_rank_promotion='raise')\nclass LaxLinalgTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
adds jax.scipy.schur
260,397
12.02.2022 03:11:57
-3,600
cb732323f376a26cf88e177a96ebd955074acbfc
adds jax.scipy.linalg.sqrtm
[ { "change_type": "MODIFY", "old_path": "jax/scipy/linalg.py", "new_path": "jax/scipy/linalg.py", "diff": "@@ -21,7 +21,6 @@ from jax._src.scipy.linalg import (\ncho_solve as cho_solve,\ndet as det,\neigh as eigh,\n- schur as schur,\neigh_tridiagonal as eigh_tridiagonal,\nexpm as expm,\nexpm_frechet as expm_frechet,\n@@ -31,6 +30,8 @@ from jax._src.scipy.linalg import (\nlu_solve as lu_solve,\npolar as polar,\nqr as qr,\n+ schur as schur,\n+ sqrtm as sqrtm,\nsolve as solve,\nsolve_triangular as solve_triangular,\nsvd as svd,\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -1388,6 +1388,70 @@ class ScipyLinalgTest(jtu.JaxTestCase):\nself._CheckAgainstNumpy(osp.linalg.schur, jsp.linalg.schur, args_maker)\nself._CompileAndCheck(jsp.linalg.schur, args_maker)\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\" : shape, \"dtype\" : dtype\n+ } for shape in [(4, 4), (15, 15), (50, 50), (100, 100)]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSqrtmPSDMatrix(self, shape, dtype):\n+ # Checks against scipy.linalg.sqrtm when the principal square root\n+ # is guaranteed to be unique (i.e no negative real eigenvalue)\n+ rng = jtu.rand_default(self.rng())\n+ arg = rng(shape, dtype)\n+ mat = arg @ arg.T\n+ args_maker = lambda : [mat]\n+ if dtype == np.float32 or dtype == np.complex64:\n+ tol = 1e-4\n+ else:\n+ tol = 1e-8\n+ self._CheckAgainstNumpy(osp.linalg.sqrtm,\n+ jsp.linalg.sqrtm,\n+ args_maker,\n+ tol=tol,\n+ check_dtypes=False)\n+ self._CompileAndCheck(jsp.linalg.sqrtm, args_maker)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_shape={}\".format(jtu.format_shape_dtype_string(shape, dtype)),\n+ \"shape\" : shape, \"dtype\" : dtype\n+ } for shape in [(4, 4), (15, 15), (50, 50), (100, 100)]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSqrtmGenMatrix(self, shape, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ arg = rng(shape, dtype)\n+ if dtype == np.float32 or dtype == np.complex64:\n+ tol = 1e-3\n+ else:\n+ tol = 1e-8\n+ R = jsp.linalg.sqrtm(arg)\n+ self.assertAllClose(R @ R, arg, atol=tol, check_dtypes=False)\n+\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list({\n+ \"testcase_name\":\n+ \"_diag={}\".format((diag, dtype)),\n+ \"diag\" : diag, \"expected\": expected, \"dtype\" : dtype\n+ } for diag, expected in [([1, 0, 0], [1, 0, 0]), ([0, 4, 0], [0, 2, 0]),\n+ ([0, 0, 0, 9],[0, 0, 0, 3]),\n+ ([0, 0, 9, 0, 0, 4], [0, 0, 3, 0, 0, 2])]\n+ for dtype in float_types + complex_types))\n+ @jtu.skip_on_devices(\"gpu\", \"tpu\")\n+ def testSqrtmEdgeCase(self, diag, expected, dtype):\n+ \"\"\"\n+ Tests the zero numerator condition\n+ \"\"\"\n+ mat = jnp.diag(jnp.array(diag)).astype(dtype)\n+ expected = jnp.diag(jnp.array(expected))\n+ root = jsp.linalg.sqrtm(mat)\n+\n+ self.assertAllClose(root, expected, check_dtypes=False)\n+\n@jtu.with_config(jax_numpy_rank_promotion='raise')\nclass LaxLinalgTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
adds jax.scipy.linalg.sqrtm
260,710
03.02.2022 14:18:44
-32,400
e085370ec4137cf0f73c5163cb664bc4e1c46082
Add some functions for spectral analysis. This commit adds "stft", "csd", and "welch" functions in scipy.signal.
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/signal.py", "new_path": "jax/_src/scipy/signal.py", "diff": "# limitations under the License.\nimport scipy.signal as osp_signal\n+import operator\nimport warnings\nimport numpy as np\n+import jax\n+import jax.numpy.fft\nfrom jax import lax\n+from jax._src.numpy.lax_numpy import _check_arraylike\nfrom jax._src.numpy import lax_numpy as jnp\nfrom jax._src.numpy import linalg\nfrom jax._src.numpy.lax_numpy import _promote_dtypes_inexact\nfrom jax._src.numpy.util import _wraps\n+from jax._src.third_party.scipy import signal_helper\n+from jax._src.util import canonicalize_axis, tuple_delete, tuple_insert\n# Note: we do not re-use the code from jax.numpy.convolve here, because the handling\n@@ -146,3 +152,343 @@ def detrend(data, axis=-1, type='linear', bp=0, overwrite_data=None):\ncoef, *_ = linalg.lstsq(A, data[sl])\ndata = data.at[sl].add(-jnp.matmul(A, coef, precision=lax.Precision.HIGHEST))\nreturn jnp.moveaxis(data.reshape(shape), 0, axis)\n+\n+\n+def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides):\n+ \"\"\"Calculate windowed FFT in the same way the original SciPy does.\n+ \"\"\"\n+ if x.dtype.kind == 'i':\n+ x = x.astype(win.dtype)\n+\n+ # Created strided array of data segments\n+ if nperseg == 1 and noverlap == 0:\n+ result = x[..., np.newaxis]\n+ else:\n+ step = nperseg - noverlap\n+ *batch_shape, signal_length = x.shape\n+ batch_shape = tuple(batch_shape)\n+ x = x.reshape((int(np.prod(batch_shape)), signal_length))[..., np.newaxis]\n+ result = jax.lax.conv_general_dilated_patches(\n+ x, (nperseg,), (step,),\n+ 'VALID',\n+ dimension_numbers=('NTC', 'OIT', 'NTC'))\n+ result = result.reshape(batch_shape + result.shape[-2:])\n+\n+ # Detrend each data segment individually\n+ result = detrend_func(result)\n+\n+ # Apply window by multiplication\n+ result = win.reshape((1,) * len(batch_shape) + (1, nperseg)) * result\n+\n+ # Perform the fft on last axis. Zero-pads automatically\n+ if sides == 'twosided':\n+ return jax.numpy.fft.fft(result, n=nfft)\n+ else:\n+ return jax.numpy.fft.rfft(result.real, n=nfft)\n+\n+\n+def odd_ext(x, n, axis=-1):\n+ \"\"\"Extends `x` along with `axis` by odd-extension.\n+\n+ This function was previously a part of \"scipy.signal.signaltools\" but is no\n+ longer exposed.\n+\n+ Args:\n+ x : input array\n+ n : the number of points to be added to the both end\n+ axis: the axis to be extended\n+ \"\"\"\n+ if n < 1:\n+ return x\n+ if n > x.shape[axis] - 1:\n+ raise ValueError(\n+ f\"The extension length n ({n}) is too big. \"\n+ f\"It must not exceed x.shape[axis]-1, which is {x.shape[axis] - 1}.\")\n+ left_end = lax.slice_in_dim(x, 0, 1, axis=axis)\n+ left_ext = jnp.flip(lax.slice_in_dim(x, 1, n + 1, axis=axis), axis=axis)\n+ right_end = lax.slice_in_dim(x, -1, None, axis=axis)\n+ right_ext = jnp.flip(lax.slice_in_dim(x, -(n + 1), -1, axis=axis), axis=axis)\n+ ext = jnp.concatenate((2 * left_end - left_ext,\n+ x,\n+ 2 * right_end - right_ext),\n+ axis=axis)\n+ return ext\n+\n+\n+def _spectral_helper(x, y,\n+ fs=1.0, window='hann', nperseg=None, noverlap=None,\n+ nfft=None, detrend_type='constant', return_onesided=True,\n+ scaling='density', axis=-1, mode='psd', boundary=None,\n+ padded=False):\n+ \"\"\"LAX-backend implementation of `scipy.signal._spectral_helper`.\n+\n+ Unlike the original helper function, `y` can be None for explicitly\n+ indicating auto-spectral (non cross-spectral) computation. In addition to\n+ this, `detrend` argument is renamed to `detrend_type` for avoiding internal\n+ name overlap.\n+ \"\"\"\n+ if mode not in ('psd', 'stft'):\n+ raise ValueError(f\"Unknown value for mode {mode}, \"\n+ \"must be one of: ('psd', 'stft')\")\n+\n+ def make_pad(mode, **kwargs):\n+ def pad(x, n, axis=-1):\n+ pad_width = [(0, 0) for unused_n in range(x.ndim)]\n+ pad_width[axis] = (n, n)\n+ return jnp.pad(x, pad_width, mode, **kwargs)\n+ return pad\n+\n+ boundary_funcs = {\n+ 'even': make_pad('reflect'),\n+ 'odd': odd_ext,\n+ 'constant': make_pad('edge'),\n+ 'zeros': make_pad('constant', constant_values=0.0),\n+ None: lambda x, *args, **kwargs: x\n+ }\n+\n+ # Check/ normalize inputs\n+ if boundary not in boundary_funcs:\n+ raise ValueError(\n+ f\"Unknown boundary option '{boundary}', \"\n+ f\"must be one of: {list(boundary_funcs.keys())}\")\n+\n+ axis = jax.core.concrete_or_error(operator.index, axis,\n+ \"axis of windowed-FFT\")\n+ axis = canonicalize_axis(axis, x.ndim)\n+\n+ if nperseg is not None: # if specified by user\n+ nperseg = jax.core.concrete_or_error(int, nperseg,\n+ \"nperseg of windowed-FFT\")\n+ if nperseg < 1:\n+ raise ValueError('nperseg must be a positive integer')\n+ # parse window; if array like, then set nperseg = win.shape\n+ win, nperseg = signal_helper._triage_segments(\n+ window, nperseg, input_length=x.shape[axis])\n+\n+ if noverlap is None:\n+ noverlap = nperseg // 2\n+ else:\n+ noverlap = jax.core.concrete_or_error(int, noverlap,\n+ \"noverlap of windowed-FFT\")\n+ if nfft is None:\n+ nfft = nperseg\n+ else:\n+ nfft = jax.core.concrete_or_error(int, nfft,\n+ \"nfft of windowed-FFT\")\n+\n+ _check_arraylike(\"_spectral_helper\", x)\n+ x = jnp.asarray(x)\n+\n+ if y is None:\n+ outdtype = jax.dtypes.canonicalize_dtype(np.result_type(x, np.complex64))\n+ else:\n+ _check_arraylike(\"_spectral_helper\", y)\n+ y = jnp.asarray(y)\n+ outdtype = jax.dtypes.canonicalize_dtype(\n+ np.result_type(x, y, np.complex64))\n+ if mode != 'psd':\n+ raise ValueError(\"two-argument mode is available only when mode=='psd'\")\n+ if x.ndim != y.ndim:\n+ raise ValueError(\n+ \"two-arguments must have the same rank ({x.ndim} vs {y.ndim}).\")\n+\n+ # Check if we can broadcast the outer axes together\n+ try:\n+ outershape = jnp.broadcast_shapes(tuple_delete(x.shape, axis),\n+ tuple_delete(y.shape, axis))\n+ except ValueError as e:\n+ raise ValueError('x and y cannot be broadcast together.') from e\n+\n+ # Special cases for size == 0\n+ if y is None:\n+ if x.size == 0:\n+ return jnp.zeros(x.shape), jnp.zeros(x.shape), jnp.zeros(x.shape)\n+ else:\n+ if x.size == 0 or y.size == 0:\n+ outshape = tuple_insert(\n+ outershape, min([x.shape[axis], y.shape[axis]]), axis)\n+ emptyout = jnp.zeros(outshape)\n+ return emptyout, emptyout, emptyout\n+\n+ # Move time-axis to the end\n+ if x.ndim > 1:\n+ if axis != -1:\n+ x = jnp.moveaxis(x, axis, -1)\n+ if y is not None and y.ndim > 1:\n+ y = jnp.moveaxis(y, axis, -1)\n+\n+ # Check if x and y are the same length, zero-pad if necessary\n+ if y is not None:\n+ if x.shape[-1] != y.shape[-1]:\n+ if x.shape[-1] < y.shape[-1]:\n+ pad_shape = list(x.shape)\n+ pad_shape[-1] = y.shape[-1] - x.shape[-1]\n+ x = jnp.concatenate((x, jnp.zeros(pad_shape)), -1)\n+ else:\n+ pad_shape = list(y.shape)\n+ pad_shape[-1] = x.shape[-1] - y.shape[-1]\n+ y = jnp.concatenate((y, jnp.zeros(pad_shape)), -1)\n+\n+ if nfft < nperseg:\n+ raise ValueError('nfft must be greater than or equal to nperseg.')\n+ if noverlap >= nperseg:\n+ raise ValueError('noverlap must be less than nperseg.')\n+ nstep = nperseg - noverlap\n+\n+ # Apply paddings\n+ if boundary is not None:\n+ ext_func = boundary_funcs[boundary]\n+ x = ext_func(x, nperseg // 2, axis=-1)\n+ if y is not None:\n+ y = ext_func(y, nperseg // 2, axis=-1)\n+\n+ if padded:\n+ # Pad to integer number of windowed segments\n+ # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg\n+ nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg\n+ zeros_shape = list(x.shape[:-1]) + [nadd]\n+ x = jnp.concatenate((x, jnp.zeros(zeros_shape)), axis=-1)\n+ if y is not None:\n+ zeros_shape = list(y.shape[:-1]) + [nadd]\n+ y = jnp.concatenate((y, jnp.zeros(zeros_shape)), axis=-1)\n+\n+ # Handle detrending and window functions\n+ if not detrend_type:\n+ def detrend_func(d):\n+ return d\n+ elif not hasattr(detrend_type, '__call__'):\n+ def detrend_func(d):\n+ return detrend(d, type=detrend_type, axis=-1)\n+ elif axis != -1:\n+ # Wrap this function so that it receives a shape that it could\n+ # reasonably expect to receive.\n+ def detrend_func(d):\n+ d = jnp.moveaxis(d, axis, -1)\n+ d = detrend_type(d)\n+ return jnp.moveaxis(d, -1, axis)\n+ else:\n+ detrend_func = detrend_type\n+\n+ if np.result_type(win, np.complex64) != outdtype:\n+ win = win.astype(outdtype)\n+\n+ # Determine scale\n+ if scaling == 'density':\n+ scale = 1.0 / (fs * (win * win).sum())\n+ elif scaling == 'spectrum':\n+ scale = 1.0 / win.sum()**2\n+ else:\n+ raise ValueError(f'Unknown scaling: {scaling}')\n+ if mode == 'stft':\n+ scale = jnp.sqrt(scale)\n+\n+ # Determine onesided/ two-sided\n+ if return_onesided:\n+ sides = 'onesided'\n+ if jnp.iscomplexobj(x) or jnp.iscomplexobj(y):\n+ sides = 'twosided'\n+ warnings.warn('Input data is complex, switching to '\n+ 'return_onesided=False')\n+ else:\n+ sides = 'twosided'\n+\n+ if sides == 'twosided':\n+ freqs = jax.numpy.fft.fftfreq(nfft, 1/fs)\n+ elif sides == 'onesided':\n+ freqs = jax.numpy.fft.rfftfreq(nfft, 1/fs)\n+\n+ # Perform the windowed FFTs\n+ result = _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides)\n+\n+ if y is not None:\n+ # All the same operations on the y data\n+ result_y = _fft_helper(y, win, detrend_func, nperseg, noverlap, nfft,\n+ sides)\n+ result = jnp.conjugate(result) * result_y\n+ elif mode == 'psd':\n+ result = jnp.conjugate(result) * result\n+\n+ result *= scale\n+\n+ if sides == 'onesided' and mode == 'psd':\n+ end = None if nfft % 2 else -1\n+ result = result.at[..., 1:end].mul(2)\n+\n+ time = jnp.arange(nperseg / 2, x.shape[-1] - nperseg / 2 + 1,\n+ nperseg - noverlap) / fs\n+ if boundary is not None:\n+ time -= (nperseg / 2) / fs\n+\n+ result = result.astype(outdtype)\n+\n+ # All imaginary parts are zero anyways\n+ if y is None and mode != 'stft':\n+ result = result.real\n+\n+ # Move frequency axis back to axis where the data came from\n+ result = jnp.moveaxis(result, -1, axis)\n+\n+ return freqs, time, result\n+\n+\n+@_wraps(osp_signal.stft)\n+def stft(x, fs=1.0, window='hann', nperseg=256, noverlap=None, nfft=None,\n+ detrend=False, return_onesided=True, boundary='zeros', padded=True,\n+ axis=-1):\n+ freqs, time, Zxx = _spectral_helper(x, None, fs, window, nperseg, noverlap,\n+ nfft, detrend, return_onesided,\n+ scaling='spectrum', axis=axis,\n+ mode='stft', boundary=boundary,\n+ padded=padded)\n+\n+ return freqs, time, Zxx\n+\n+\n+_csd_description = \"\"\"\n+The original SciPy function exhibits slightly different behavior between\n+``csd(x, x)``` and ```csd(x, x.copy())```. The LAX-backend version is designed\n+to follow the latter behavior. For using the former behavior, call this\n+function as `csd(x, None)`.\"\"\"\n+\n+\n+@_wraps(osp_signal.csd, lax_description=_csd_description)\n+def csd(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,\n+ detrend='constant', return_onesided=True, scaling='density',\n+ axis=-1, average='mean'):\n+ freqs, _, Pxy = _spectral_helper(x, y, fs, window, nperseg, noverlap, nfft,\n+ detrend, return_onesided, scaling, axis,\n+ mode='psd')\n+ if y is not None:\n+ Pxy = Pxy + 0j # Ensure complex output when x is not y\n+\n+ # Average over windows.\n+ if Pxy.ndim >= 2 and Pxy.size > 0:\n+ if Pxy.shape[-1] > 1:\n+ if average == 'median':\n+ bias = signal_helper._median_bias(Pxy.shape[-1]).astype(Pxy.dtype)\n+ if jnp.iscomplexobj(Pxy):\n+ Pxy = (jnp.median(jnp.real(Pxy), axis=-1)\n+ + 1j * jnp.median(jnp.imag(Pxy), axis=-1))\n+ else:\n+ Pxy = jnp.median(Pxy, axis=-1)\n+ Pxy /= bias\n+ elif average == 'mean':\n+ Pxy = Pxy.mean(axis=-1)\n+ else:\n+ raise ValueError(f'average must be \"median\" or \"mean\", got {average}')\n+ else:\n+ Pxy = jnp.reshape(Pxy, Pxy.shape[:-1])\n+\n+ return freqs, Pxy\n+\n+\n+@_wraps(osp_signal.welch)\n+def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,\n+ detrend='constant', return_onesided=True, scaling='density',\n+ axis=-1, average='mean'):\n+ freqs, Pxx = csd(x, None, fs=fs, window=window, nperseg=nperseg,\n+ noverlap=noverlap, nfft=nfft, detrend=detrend,\n+ return_onesided=return_onesided, scaling=scaling,\n+ axis=axis, average=average)\n+\n+ return freqs, Pxx.real\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/third_party/scipy/signal_helper.py", "diff": "+\"\"\"Utility functions adopted from scipy.signal.\"\"\"\n+\n+import scipy.signal as osp_signal\n+import warnings\n+\n+from jax._src.numpy import lax_numpy as jnp\n+\n+\n+def _triage_segments(window, nperseg, input_length):\n+ \"\"\"\n+ Parses window and nperseg arguments for spectrogram and _spectral_helper.\n+ This is a helper function, not meant to be called externally.\n+ Parameters\n+ ----------\n+ window : string, tuple, or ndarray\n+ If window is specified by a string or tuple and nperseg is not\n+ specified, nperseg is set to the default of 256 and returns a window of\n+ that length.\n+ If instead the window is array_like and nperseg is not specified, then\n+ nperseg is set to the length of the window. A ValueError is raised if\n+ the user supplies both an array_like window and a value for nperseg but\n+ nperseg does not equal the length of the window.\n+ nperseg : int\n+ Length of each segment\n+ input_length: int\n+ Length of input signal, i.e. x.shape[-1]. Used to test for errors.\n+ Returns\n+ -------\n+ win : ndarray\n+ window. If function was called with string or tuple than this will hold\n+ the actual array used as a window.\n+ nperseg : int\n+ Length of each segment. If window is str or tuple, nperseg is set to\n+ 256. If window is array_like, nperseg is set to the length of the\n+ 6\n+ window.\n+ \"\"\"\n+ # parse window; if array like, then set nperseg = win.shape\n+ if isinstance(window, (str, tuple)):\n+ # if nperseg not specified\n+ if nperseg is None:\n+ nperseg = 256 # then change to default\n+ if nperseg > input_length:\n+ warnings.warn(f'nperseg = {nperseg} is greater than input length '\n+ f' = {input_length}, using nperseg = {nperseg}')\n+ nperseg = input_length\n+ win = jnp.array(osp_signal.get_window(window, nperseg))\n+ else:\n+ win = jnp.asarray(window)\n+ if len(win.shape) != 1:\n+ raise ValueError('window must be 1-D')\n+ if input_length < win.shape[-1]:\n+ raise ValueError('window is longer than input signal')\n+ if nperseg is None:\n+ nperseg = win.shape[0]\n+ elif nperseg is not None:\n+ if nperseg != win.shape[0]:\n+ raise ValueError(\"value specified for nperseg is different\"\n+ \" from length of window\")\n+ return win, nperseg\n+\n+\n+def _median_bias(n):\n+ \"\"\"\n+ Returns the bias of the median of a set of periodograms relative to\n+ the mean.\n+ See Appendix B from [1]_ for details.\n+ Parameters\n+ ----------\n+ n : int\n+ Numbers of periodograms being averaged.\n+ Returns\n+ -------\n+ bias : float\n+ Calculated bias.\n+ References\n+ ----------\n+ .. [1] B. Allen, W.G. Anderson, P.R. Brady, D.A. Brown, J.D.E. Creighton.\n+ \"FINDCHIRP: an algorithm for detection of gravitational waves from\n+ inspiraling compact binaries\", Physical Review D 85, 2012,\n+ :arxiv:`gr-qc/0509116`\n+ \"\"\"\n+ ii_2 = jnp.arange(2., n, 2)\n+ return 1 + jnp.sum(1. / (ii_2 + 1) - 1. / ii_2)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/signal.py", "new_path": "jax/scipy/signal.py", "diff": "@@ -20,4 +20,7 @@ from jax._src.scipy.signal import (\ncorrelate as correlate,\ncorrelate2d as correlate2d,\ndetrend as detrend,\n+ csd as csd,\n+ stft as stft,\n+ welch as welch,\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_signal_test.py", "new_path": "tests/scipy_signal_test.py", "diff": "from functools import partial\n+import unittest\nfrom absl.testing import absltest, parameterized\n@@ -30,9 +31,25 @@ config.parse_flags_with_absl()\nonedim_shapes = [(1,), (2,), (5,), (10,)]\ntwodim_shapes = [(1, 1), (2, 2), (2, 3), (3, 4), (4, 4)]\nthreedim_shapes = [(2, 2, 2), (3, 3, 2), (4, 4, 2), (5, 5, 2)]\n+stft_test_shapes = [\n+ # (input_shape, nperseg, noverlap, axis)\n+ ((50,), 17, 5, -1),\n+ ((2, 13), 7, 0, -1),\n+ ((3, 17, 2), 9, 3, 1),\n+ ((2, 3, 389, 5), 17, 13, 2),\n+ ((2, 1, 133, 3), 17, 13, -2),\n+]\n+csd_test_shapes = [\n+ # (x_input_shape, y_input_shape, nperseg, noverlap, axis)\n+ ((50,), (13,), 17, 5, -1),\n+ ((2, 13), (2, 13), 7, 0, -1),\n+ ((3, 17, 2), (3, 12, 2), 9, 3, 1),\n+]\n+welch_test_shapes = stft_test_shapes\ndefault_dtypes = jtu.dtypes.floating + jtu.dtypes.integer + jtu.dtypes.complex\n+_TPU_FFT_TOL = 0.15\nclass LaxBackedScipySignalTests(jtu.JaxTestCase):\n@@ -104,6 +121,255 @@ class LaxBackedScipySignalTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, tol=tol)\nself._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}\"\n+ f\"_fs={fs}_window={window}_boundary={boundary}_detrend={detrend}\"\n+ f\"_padded={padded}_nperseg={nperseg}_noverlap={noverlap}\"\n+ f\"_axis={timeaxis}_nfft={nfft}\",\n+ \"shape\": shape, \"dtype\": dtype, \"fs\": fs, \"window\": window,\n+ \"nperseg\": nperseg, \"noverlap\": noverlap, \"nfft\": nfft,\n+ \"detrend\": detrend, \"boundary\": boundary, \"padded\": padded,\n+ \"timeaxis\": timeaxis}\n+ for shape, nperseg, noverlap, timeaxis in stft_test_shapes\n+ for dtype in default_dtypes\n+ for fs in [1.0, 16000.0]\n+ for window in ['boxcar', 'triang', 'blackman', 'hamming', 'hann']\n+ for nfft in [None, nperseg, int(nperseg * 1.5), nperseg * 2]\n+ for detrend in ['constant', 'linear', False]\n+ for boundary in [None, 'even', 'odd', 'zeros']\n+ for padded in [True, False]))\n+ def testStftAgainstNumpy(self, *, shape, dtype, fs, window, nperseg,\n+ noverlap, nfft, detrend, boundary, padded,\n+ timeaxis):\n+ is_complex = np.dtype(dtype).kind == 'c'\n+ if is_complex and detrend is not None:\n+ return\n+\n+ osp_fun = partial(osp_signal.stft,\n+ fs=fs, window=window, nfft=nfft, boundary=boundary, padded=padded,\n+ detrend=detrend, nperseg=nperseg, noverlap=noverlap, axis=timeaxis,\n+ return_onesided=not is_complex)\n+ jsp_fun = partial(jsp_signal.stft,\n+ fs=fs, window=window, nfft=nfft, boundary=boundary, padded=padded,\n+ detrend=detrend, nperseg=nperseg, noverlap=noverlap, axis=timeaxis,\n+ return_onesided=not is_complex)\n+ tol = {\n+ np.float32: 1e-5, np.float64: 1e-12,\n+ np.complex64: 1e-5, np.complex128: 1e-12\n+ }\n+ if jtu.device_under_test() == 'tpu':\n+ tol = _TPU_FFT_TOL\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, rtol=tol, atol=tol)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+\n+ # Tests with `average == 'median'`` is excluded from `testCsd*`\n+ # due to the issue:\n+ # https://github.com/scipy/scipy/issues/15601\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ f\"_xshape={jtu.format_shape_dtype_string(xshape, dtype)}\"\n+ f\"_yshape={jtu.format_shape_dtype_string(yshape, dtype)}\"\n+ f\"_average={average}_scaling={scaling}_nfft={nfft}\"\n+ f\"_fs={fs}_window={window}_detrend={detrend}\"\n+ f\"_nperseg={nperseg}_noverlap={noverlap}\"\n+ f\"_axis={timeaxis}\",\n+ \"xshape\": xshape, \"yshape\": yshape, \"dtype\": dtype, \"fs\": fs,\n+ \"window\": window, \"nperseg\": nperseg, \"noverlap\": noverlap,\n+ \"nfft\": nfft, \"detrend\": detrend, \"scaling\": scaling,\n+ \"timeaxis\": timeaxis, \"average\": average}\n+ for xshape, yshape, nperseg, noverlap, timeaxis in csd_test_shapes\n+ for dtype in default_dtypes\n+ for fs in [1.0, 16000.0]\n+ for window in ['boxcar', 'triang', 'blackman', 'hamming', 'hann']\n+ for nfft in [None, nperseg, int(nperseg * 1.5), nperseg * 2]\n+ for detrend in ['constant', 'linear', False]\n+ for scaling in ['density', 'spectrum']\n+ for average in ['mean']))\n+ def testCsdAgainstNumpy(\n+ self, *, xshape, yshape, dtype, fs, window, nperseg, noverlap, nfft,\n+ detrend, scaling, timeaxis, average):\n+ is_complex = np.dtype(dtype).kind == 'c'\n+ if is_complex and detrend is not None:\n+ raise unittest.SkipTest(\n+ \"Complex signal is not supported in lax-backed `signal.detrend`.\")\n+\n+ osp_fun = partial(osp_signal.csd,\n+ fs=fs, window=window,\n+ nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=not is_complex,\n+ scaling=scaling, axis=timeaxis, average=average)\n+ jsp_fun = partial(jsp_signal.csd,\n+ fs=fs, window=window,\n+ nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=not is_complex,\n+ scaling=scaling, axis=timeaxis, average=average)\n+ tol = {\n+ np.float32: 1e-5, np.float64: 1e-12,\n+ np.complex64: 1e-5, np.complex128: 1e-12\n+ }\n+ if jtu.device_under_test() == 'tpu':\n+ tol = _TPU_FFT_TOL\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, rtol=tol, atol=tol)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}\"\n+ f\"_average={average}_scaling={scaling}_nfft={nfft}\"\n+ f\"_fs={fs}_window={window}_detrend={detrend}\"\n+ f\"_nperseg={nperseg}_noverlap={noverlap}\"\n+ f\"_axis={timeaxis}\",\n+ \"shape\": shape, \"dtype\": dtype, \"fs\": fs,\n+ \"window\": window, \"nperseg\": nperseg, \"noverlap\": noverlap,\n+ \"nfft\": nfft, \"detrend\": detrend, \"scaling\": scaling,\n+ \"timeaxis\": timeaxis, \"average\": average}\n+ for shape, unused_yshape, nperseg, noverlap, timeaxis in csd_test_shapes\n+ for dtype in default_dtypes\n+ for fs in [1.0, 16000.0]\n+ for window in ['boxcar', 'triang', 'blackman', 'hamming', 'hann']\n+ for nfft in [None, nperseg, int(nperseg * 1.5), nperseg * 2]\n+ for detrend in ['constant', 'linear', False]\n+ for scaling in ['density', 'spectrum']\n+ for average in ['mean']))\n+ def testCsdWithSameParamAgainstNumpy(\n+ self, *, shape, dtype, fs, window, nperseg, noverlap, nfft,\n+ detrend, scaling, timeaxis, average):\n+ is_complex = np.dtype(dtype).kind == 'c'\n+ if is_complex and detrend is not None:\n+ raise unittest.SkipTest(\n+ \"Complex signal is not supported in lax-backed `signal.detrend`.\")\n+\n+ def osp_fun(x, y):\n+ # When the identical parameters are given, jsp-version follows\n+ # the behavior with copied parameters.\n+ freqs, Pxy = osp_signal.csd(\n+ x, y.copy(),\n+ fs=fs, window=window,\n+ nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=not is_complex,\n+ scaling=scaling, axis=timeaxis, average=average)\n+ return freqs, Pxy\n+ jsp_fun = partial(jsp_signal.csd,\n+ fs=fs, window=window,\n+ nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=not is_complex,\n+ scaling=scaling, axis=timeaxis, average=average)\n+\n+ tol = {\n+ np.float32: 1e-5, np.float64: 1e-12,\n+ np.complex64: 1e-5, np.complex128: 1e-12\n+ }\n+ if jtu.device_under_test() == 'tpu':\n+ tol = _TPU_FFT_TOL\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)] * 2\n+\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, rtol=tol, atol=tol)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}\"\n+ f\"_fs={fs}_window={window}\"\n+ f\"_nperseg={nperseg}_noverlap={noverlap}_nfft={nfft}\"\n+ f\"_detrend={detrend}_return_onesided={return_onesided}\"\n+ f\"_scaling={scaling}_axis={timeaxis}_average={average}\",\n+ \"shape\": shape, \"dtype\": dtype, \"fs\": fs, \"window\": window,\n+ \"nperseg\": nperseg, \"noverlap\": noverlap, \"nfft\": nfft,\n+ \"detrend\": detrend, \"return_onesided\": return_onesided,\n+ \"scaling\": scaling, \"timeaxis\": timeaxis, \"average\": average}\n+ for shape, nperseg, noverlap, timeaxis in welch_test_shapes\n+ for dtype in default_dtypes\n+ for fs in [1.0, 16000.0]\n+ for window in ['boxcar', 'triang', 'blackman', 'hamming', 'hann']\n+ for nfft in [None, nperseg, int(nperseg * 1.5), nperseg * 2]\n+ for detrend in ['constant', 'linear', False]\n+ for return_onesided in [True, False]\n+ for scaling in ['density', 'spectrum']\n+ for average in ['mean', 'median']))\n+ def testWelchAgainstNumpy(self, *, shape, dtype, fs, window, nperseg,\n+ noverlap, nfft, detrend, return_onesided,\n+ scaling, timeaxis, average):\n+ if np.dtype(dtype).kind == 'c':\n+ return_onesided = False\n+ if detrend is not None:\n+ raise unittest.SkipTest(\n+ \"Complex signal is not supported in lax-backed `signal.detrend`.\")\n+\n+ osp_fun = partial(osp_signal.welch,\n+ fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=return_onesided, scaling=scaling,\n+ axis=timeaxis, average=average)\n+ jsp_fun = partial(jsp_signal.welch,\n+ fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, nfft=nfft,\n+ detrend=detrend, return_onesided=return_onesided, scaling=scaling,\n+ axis=timeaxis, average=average)\n+ tol = {\n+ np.float32: 1e-5, np.float64: 1e-12,\n+ np.complex64: 1e-5, np.complex128: 1e-12\n+ }\n+ if jtu.device_under_test() == 'tpu':\n+ tol = _TPU_FFT_TOL\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, rtol=tol, atol=tol)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\":\n+ f\"_shape={jtu.format_shape_dtype_string(shape, dtype)}\"\n+ f\"_nperseg={nperseg}_noverlap={noverlap}\"\n+ f\"_use_nperseg={use_nperseg}_use_overlap={use_noverlap}\"\n+ f\"_axis={timeaxis}\",\n+ \"shape\": shape, \"dtype\": dtype,\n+ \"nperseg\": nperseg, \"noverlap\": noverlap,\n+ \"use_nperseg\": use_nperseg, \"use_noverlap\": use_noverlap,\n+ \"timeaxis\": timeaxis}\n+ for shape, nperseg, noverlap, timeaxis in welch_test_shapes\n+ for use_nperseg in [False, True]\n+ for use_noverlap in [False, True]\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.integer))\n+ def testWelchWithDefaultStepArgsAgainstNumpy(\n+ self, *, shape, dtype, nperseg, noverlap, use_nperseg, use_noverlap,\n+ timeaxis):\n+ kwargs = {\n+ 'axis': timeaxis\n+ }\n+\n+ if use_nperseg:\n+ kwargs['nperseg'] = nperseg\n+ else:\n+ kwargs['window'] = osp_signal.get_window('hann', nperseg)\n+ if use_noverlap:\n+ kwargs['noverlap'] = noverlap\n+\n+ osp_fun = partial(osp_signal.welch, **kwargs)\n+ jsp_fun = partial(jsp_signal.welch, **kwargs)\n+ tol = {\n+ np.float32: 1e-5, np.float64: 1e-12,\n+ np.complex64: 1e-5, np.complex128: 1e-12\n+ }\n+ if jtu.device_under_test() == 'tpu':\n+ tol = _TPU_FFT_TOL\n+\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape, dtype)]\n+\n+ self._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, rtol=tol, atol=tol)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add some functions for spectral analysis. This commit adds "stft", "csd", and "welch" functions in scipy.signal.
260,335
16.02.2022 23:11:22
28,800
e0fb424d81d0898971a85587e8f60c0a1fc000d7
use singleton dims in broadcasting binop batchers
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -597,8 +597,10 @@ def broadcast_batcher(prim, args, dims, **params):\nout = prim.bind(*args, **params)\nreturn (out, (d,) * len(out)) if prim.multiple_results else (out, d)\nelse:\n- size, = {shape[d] for shape, d in shapes if d is not not_mapped}\n- args = [bdim_at_front(x, d, size) if np.ndim(x) else x\n+ # We pass size of 1 here because (1) at least one argument has a real batch\n+ # dimension and (2) all unmapped axes can have a singleton axis inserted and\n+ # then rely on the primitive's built-in broadcasting.\n+ args = [bdim_at_front(x, d, 1) if np.ndim(x) else x\nfor x, d in zip(args, dims)]\nndim = max(np.ndim(x) for x in args) # special-case scalar broadcasting\nargs = [_handle_scalar_broadcasting(ndim, x, d) for x, d in zip(args, dims)]\n" } ]
Python
Apache License 2.0
google/jax
use singleton dims in broadcasting binop batchers
260,287
17.02.2022 03:27:38
28,800
57f423203d6313d2beba7fefbd700c25aa400372
Fix uninitialized axis_env error when MLIR lowering is disabled
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -2173,6 +2173,7 @@ def lower_mesh_computation(\nout_partitions_t = xla.tuple_sharding_proto(out_partitions)\npartitions_proto = True\naxis_ctx = mlir.SPMDAxisContext(mesh)\n+ axis_env = axis_ctx.axis_env\nelse:\nreplicated_args = [not axis for axis in in_axes]\nin_partitions = None\n" } ]
Python
Apache License 2.0
google/jax
Fix uninitialized axis_env error when MLIR lowering is disabled PiperOrigin-RevId: 429267926
260,424
17.02.2022 04:30:27
28,800
73f23705d01b88d4b4aad13a279f6a71d9116d0b
Checkify: explicitly export public API, hide private symbols.
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/checkify/__init__.py", "diff": "+# Copyright 2022 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# flake8: noqa: F401\n+from jax.experimental.checkify.checkify_impl import (\n+ Error as Error,\n+ ErrorCategory as ErrorCategory,\n+ all_checks as all_checks,\n+ automatic_checks as automatic_checks,\n+ check as check,\n+ check_error as check_error,\n+ checkify as checkify,\n+ div_checks as div_checks,\n+ float_checks as float_checks,\n+ index_checks as index_checks,\n+ nan_checks as nan_checks,\n+ user_checks as user_checks,\n+)\n" }, { "change_type": "RENAME", "old_path": "jax/experimental/checkify.py", "new_path": "jax/experimental/checkify/checkify_impl.py", "diff": "" } ]
Python
Apache License 2.0
google/jax
Checkify: explicitly export public API, hide private symbols. PiperOrigin-RevId: 429277551
260,486
17.02.2022 14:31:23
28,800
50f4b5806e2891dd82e564da2a7d8fc34f6d9e25
Fix Iree backend to for copy_to_device and executable results Executable results can be a tuple, if so iterate over the entires. Copy to device should just return the the IREE buffer as device buffer management is still in progress.
[ { "change_type": "MODIFY", "old_path": "jax/_src/iree.py", "new_path": "jax/_src/iree.py", "diff": "@@ -59,6 +59,9 @@ class IreeBuffer(xla_client.DeviceArrayBase):\nself._device = device\nself._npy_value = np.asarray(npy_value)\n+ def copy_to_device(self, device):\n+ return self\n+\ndef to_py(self) -> np.ndarray:\nreturn self._npy_value\n@@ -89,7 +92,7 @@ class IreeExecutable:\noutputs = self.module_object[self.function_name](*inputs)\n# TODO(phawkins): Have a way to just have it always return the list,\n# regardless of arity.\n- if not isinstance(outputs, list):\n+ if not isinstance(outputs, list) and not isinstance(outputs, tuple):\noutputs = [outputs]\nreturn [\nIreeBuffer(self.client, self._devices[0], output) for output in outputs\n" } ]
Python
Apache License 2.0
google/jax
Fix Iree backend to for copy_to_device and executable results Executable results can be a tuple, if so iterate over the entires. Copy to device should just return the the IREE buffer as device buffer management is still in progress.
260,573
18.02.2022 08:20:48
0
20635e4ac51565a939411265856a6c44b9bc6d85
fix: simplify reduce_min with reduce_all
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1683,18 +1683,10 @@ tf_impl[lax.reduce_sum_p] = axes_to_axis(tf.reduce_sum)\ntf_impl[lax.reduce_prod_p] = axes_to_axis(tf.reduce_prod)\ntf_impl[lax.reduce_max_p] = handle_boolean_args(\naxes_to_axis(tf.reduce_max), argnums=[0],\n- boolean_f=axes_to_axis(tf.reduce_any))\n-\n-def bool_reduce_min(x, axes):\n- return tf.logical_not(\n- axes_to_axis(tf.reduce_any)(\n- tf.logical_not(x),\n- axes\n- )\n- )\n+ boolean_f=axes_to_axis(tf.reduce_any)) # Max is T if any one is T\ntf_impl[lax.reduce_min_p] = handle_boolean_args(\naxes_to_axis(tf.reduce_min), argnums=[0],\n- boolean_f=bool_reduce_min)\n+ boolean_f=axes_to_axis(tf.reduce_all)) # Min is only F is all are T\ntf_impl[lax.reduce_or_p] = axes_to_axis(tf.reduce_any)\ntf_impl[lax.reduce_and_p] = axes_to_axis(tf.reduce_all)\n" } ]
Python
Apache License 2.0
google/jax
fix: simplify reduce_min with reduce_all
260,411
18.02.2022 09:38:10
-3,600
3576388982571737290d4a428103a8e76c405e82
[jax2tf] Added more links to the documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -13,8 +13,12 @@ written in JAX, possibly including JAX transformations, and turn it into\na function that uses only TensorFlow operations. The converted function\ncan be called or traced from TensorFlow and will behave as if it was written in TensorFlow.\nIn practice this means that you can take some code written in JAX and execute it using\n-TensorFlow eager mode, or stage it out as a TensorFlow graph, even save it\n-as a SavedModel for archival, or for use with TensorFlow tools such as serving stack,\n+TensorFlow eager mode, or stage it out as a TensorFlow graph, even use it\n+with TensorFlow tooling such as: SavedModel for archival ([examples below](#usage-saved-model)),\n+TensorFlow Serving ([examples](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/serving/README.md)),\n+TFX ([examples](https://github.com/tensorflow/tfx/blob/master/tfx/examples/penguin/README.md#instructions-for-using-flax)),\n+TensorFlow Lite ([examples](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/tflite/mnist/README.md)),\n+TensorFlow.js ([examples](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md)),\nor TensorFlow Hub.\nThis package also contains the `jax2tf.call_tf` mechanism to call TensorFlow functions\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/converters_eval/README.md", "new_path": "jax/experimental/jax2tf/converters_eval/README.md", "diff": "-# Evaluating JAX Converters\n+# Evaluating JAX Converters for TFLite and TensorFlow.js\nThis directory evaluates various JAX converters by attempting to convert a range\nof examples and reporting the errors. It also contains documentation for the\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added more links to the documentation
260,643
18.02.2022 09:07:29
0
f926d089f803b2bc6440030eec7d8488412a80b5
docs: spelling mistake fixed
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1686,7 +1686,7 @@ tf_impl[lax.reduce_max_p] = handle_boolean_args(\nboolean_f=axes_to_axis(tf.reduce_any)) # Max is T if any one is T\ntf_impl[lax.reduce_min_p] = handle_boolean_args(\naxes_to_axis(tf.reduce_min), argnums=[0],\n- boolean_f=axes_to_axis(tf.reduce_all)) # Min is only F is all are T\n+ boolean_f=axes_to_axis(tf.reduce_all)) # Min is only F if all are T\ntf_impl[lax.reduce_or_p] = axes_to_axis(tf.reduce_any)\ntf_impl[lax.reduce_and_p] = axes_to_axis(tf.reduce_all)\n" } ]
Python
Apache License 2.0
google/jax
docs: spelling mistake fixed
260,424
17.02.2022 12:31:59
0
2eeb683df0f264aba5c21f03b9d347e79c48fca8
Checkify: address initial feedback. - add a way to run checkify with no errors enabled - clarify "can't be staged" error message - export init_error: a way for users to set a default Error value
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify/__init__.py", "new_path": "jax/experimental/checkify/__init__.py", "diff": "@@ -24,6 +24,7 @@ from jax.experimental.checkify.checkify_impl import (\ndiv_checks as div_checks,\nfloat_checks as float_checks,\nindex_checks as index_checks,\n+ init_error as init_error,\nnan_checks as nan_checks,\nuser_checks as user_checks,\n)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/checkify/checkify_impl.py", "new_path": "jax/experimental/checkify/checkify_impl.py", "diff": "@@ -426,8 +426,12 @@ def assert_impl(pred, code, *, msgs):\n@assert_p.def_abstract_eval\ndef assert_abstract_eval(pred, code, *, msgs):\n- raise Exception(\"can't be staged!\")\n-\n+ # TODO(lenamartens) add in-depth explanation to link to in module docs.\n+ raise ValueError('Cannot abstractly evaluate a checkify.check which was not'\n+ ' functionalized. This probably means you tried to stage'\n+ ' (jit/scan/pmap/...) a `check` without functionalizing it'\n+ ' through `checkify.checkify`.'\n+ )\n## checkify rules\n@@ -742,8 +746,9 @@ def checkify(fun: Callable[..., Out],\n\"\"\"\nif not errors:\n- raise ValueError('Checkify needs to be called with at least one enabled'\n- ' ErrorCategory, was called with an empty errors set.')\n+ def checked_fun_trivial(*args, **kwargs):\n+ return init_error, fun(*args, **kwargs)\n+ return checked_fun_trivial\n@traceback_util.api_boundary\ndef checked_fun(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -377,8 +377,17 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\ndef test_empty_enabled_errors(self):\n- with self.assertRaisesRegex(ValueError, \"called with an empty errors set\"):\n- checkify.checkify(lambda x: x, errors={})\n+ def multi_errors(x):\n+ x = x/0 # DIV\n+ x = jnp.sin(x) # NAN\n+ x = x[500] # OOB\n+ # TODO(lenamartens): this error should also be disabled.\n+ # checkify.check(x < 0, \"must be negative!\") # ASSERT\n+ return x\n+\n+ x = jnp.ones((2,))\n+ err, _ = checkify.checkify(multi_errors, errors={})(x)\n+ self.assertIsNone(err.get())\n@parameterized.named_parameters(\n(\"assert\", checkify.user_checks, \"must be negative!\"),\n@@ -504,7 +513,7 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nerr, y = checkify.checkify(jax.grad(sin),\nerrors=checkify.float_checks)(jnp.inf)\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), 'nan generated by primitive sin')\n+ self.assertStartsWith(err.get(), \"nan generated by primitive sin\")\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n@@ -521,7 +530,7 @@ class AssertPrimitiveTests(jtu.JaxTestCase):\ndef f():\ncheckify.check(False, \"hi\")\n- with self.assertRaisesRegex(Exception, \"can't be staged\"):\n+ with self.assertRaisesRegex(ValueError, \"Cannot abstractly evaluate\"):\nf()\ndef test_assert_discharging(self):\n" } ]
Python
Apache License 2.0
google/jax
Checkify: address initial feedback. - add a way to run checkify with no errors enabled - clarify "can't be staged" error message - export init_error: a way for users to set a default Error value
260,486
18.02.2022 22:58:51
28,800
23d5eb0896a92c227b3e72df1a368fc86cef933e
IREE's get_default_device_assignment should return List[Device] Previously return List[List[Device]] which is not how the function is used. Updated to use the alternative overload.
[ { "change_type": "MODIFY", "old_path": "jax/_src/iree.py", "new_path": "jax/_src/iree.py", "diff": "@@ -125,11 +125,11 @@ class IreeClient:\ndef get_default_device_assignment(\nself,\n- num_replicas: int,\n- num_partitions: int = 1) -> List[List[IreeDevice]]:\n- if num_replicas != 1 or num_partitions != 1:\n+ num_replicas: int) -> List[IreeDevice]:\n+ if num_replicas != 1:\nraise NotImplementedError(\"Only single-device computations implemented\")\n- return [[self._devices[0]]]\n+ return [self._devices[0]]\n+\ndef compile(self, computation: str,\ncompile_options: xla_client.CompileOptions) -> IreeExecutable:\n" } ]
Python
Apache License 2.0
google/jax
IREE's get_default_device_assignment should return List[Device] Previously return List[List[Device]] which is not how the function is used. Updated to use the alternative overload.
260,339
20.02.2022 09:46:49
21,600
4a8de96e88e7772a4a64ef96be0dd027e40376ee
Update README.md to fix link to prng.md
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -357,7 +357,7 @@ Some standouts:\n1. [In-place mutating updates of\narrays](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#in-place-updates), like `x[i] += y`, aren't supported, but [there are functional alternatives](https://jax.readthedocs.io/en/latest/jax.ops.html). Under a `jit`, those functional alternatives will reuse buffers in-place automatically.\n1. [Random numbers are\n- different](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#random-numbers), but for [good reasons](https://github.com/google/jax/blob/main/design_notes/prng.md).\n+ different](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#random-numbers), but for [good reasons](https://github.com/google/jax/blob/main/docs/design_notes/prng.md).\n1. If you're looking for [convolution\noperators](https://jax.readthedocs.io/en/latest/notebooks/convolutions.html),\nthey're in the `jax.lax` package.\n" } ]
Python
Apache License 2.0
google/jax
Update README.md to fix link to prng.md
260,527
21.02.2022 07:50:49
0
add6c8254e03402d20c2e114616ea68cf789900a
Clarify tree_flatten docstring.
[ { "change_type": "MODIFY", "old_path": "jax/_src/tree_util.py", "new_path": "jax/_src/tree_util.py", "diff": "@@ -43,10 +43,9 @@ def tree_flatten(tree, is_leaf: Optional[Callable[[Any], bool]] = None):\nArgs:\ntree: a pytree to flatten.\nis_leaf: an optionally specified function that will be called at each\n- flattening step. It should return a boolean, which indicates whether\n- the flattening should traverse the current object, or if it should be\n- stopped immediately, with the whole subtree being treated as a leaf.\n-\n+ flattening step. It should return a boolean, with true stopping the\n+ traversal and the whole subtree being treated as a leaf, and false\n+ indicating the flattening should traverse the current object.\nReturns:\nA pair where the first element is a list of leaf values and the second\nelement is a treedef representing the structure of the flattened tree.\n" } ]
Python
Apache License 2.0
google/jax
Clarify tree_flatten docstring.
260,626
22.02.2022 13:49:48
-14,400
6423741db02139d17d9c46e58350eb662b2ebd13
Add copy button to code snippets in documentation
[ { "change_type": "MODIFY", "old_path": "docs/conf.py", "new_path": "docs/conf.py", "diff": "@@ -70,6 +70,7 @@ extensions = [\n'sphinx_autodoc_typehints',\n'myst_nb',\n\"sphinx_remove_toctrees\",\n+ 'sphinx_copybutton',\n'jax_extensions',\n]\n" }, { "change_type": "MODIFY", "old_path": "docs/requirements.txt", "new_path": "docs/requirements.txt", "diff": "@@ -5,6 +5,7 @@ sphinx-book-theme\nsphinx-remove-toctrees\n# Newer versions cause issues; see https://github.com/google/jax/pull/6449\nsphinx-autodoc-typehints==1.11.1\n+sphinx-copybutton>=0.5.0\njupyter-sphinx>=0.3.2\nmyst-nb\n" } ]
Python
Apache License 2.0
google/jax
Add copy button to code snippets in documentation
260,287
22.02.2022 06:01:36
28,800
2641f06152f3d730a1d09851a2d3b3f87e0c1408
Always treat all mesh axes controlled by xmap as MANUAL
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -731,10 +731,12 @@ def make_xmap_callable(fun: lu.WrappedFun,\nfor ax, av, ips in safe_zip(mesh_in_axes, in_avals, in_positional_semantics)\n]\nin_is_gda = [ips == _PositionalSemantics.GLOBAL for ips in in_positional_semantics]\n+ tiling_method: pxla.TilingMethod\nif config.experimental_xmap_spmd_lowering_manual:\n- tiling_method = pxla.TilingMethod.MANUAL\n+ manual_mesh_axes = frozenset(it.chain.from_iterable(plan.physical_axis_resources.values()))\n+ tiling_method = pxla.TileManual(manual_mesh_axes)\nelse:\n- tiling_method = pxla.TilingMethod.VECTORIZE\n+ tiling_method = pxla.TileVectorize()\nreturn pxla.lower_mesh_computation(\nf, name, mesh,\nmesh_in_axes, mesh_out_axes, donated_invars,\n@@ -1519,6 +1521,7 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\nxla.check_backend_matches(backend, ctx.module_context.platform)\nplan = EvaluationPlan.from_axis_resources(\naxis_resources, resource_env, global_axis_sizes, in_positional_semantics)\n+ manual_mesh_axes = frozenset(it.chain.from_iterable(plan.physical_axis_resources.values()))\nresource_call_jaxpr = plan.subst_axes_with_resources(call_jaxpr)\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(resource_call_jaxpr, ())))\n@@ -1528,7 +1531,7 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\n# NOTE: Sharding constraints are handled entirely by vtile_manual!\nmesh_in_axes, mesh_out_axes = plan.to_mesh_axes(in_axes, out_axes)\nmesh = resource_env.physical_mesh\n- f = pxla.vtile_manual(f, mesh, mesh_in_axes, mesh_out_axes)\n+ f = pxla.vtile_manual(f, tuple(manual_mesh_axes), mesh, mesh_in_axes, mesh_out_axes)\n# NOTE: We don't extend the resource env with the mesh shape, because those\n# resources are already in scope! It's the outermost xmap that introduces\n@@ -1539,7 +1542,6 @@ def _xmap_lowering_rule_spmd_manual(ctx, *global_in_nodes,\n# We in-line here rather than generating a Call HLO as in the xla_call\n# translation rule just because the extra tuple stuff is a pain.\n- manual_mesh_axes = frozenset(it.chain.from_iterable(plan.physical_axis_resources.values()))\nassert isinstance(ctx.module_context.axis_context, mlir.SPMDAxisContext)\nsub_ctx = ctx.module_context.replace(\nname_stack=xla.extend_name_stack(ctx.module_context.name_stack,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -37,9 +37,8 @@ from functools import partial\nimport itertools as it\nimport operator as op\nimport threading\n-from typing import (Any, Callable, Dict, List, NamedTuple, Optional,\n+from typing import (Any, Callable, Dict, List, NamedTuple, Optional, FrozenSet,\nSequence, Set, Tuple, Type, Union, Iterable, Mapping, cast)\n-import enum\nimport sys\nfrom absl import logging\n@@ -2047,11 +2046,11 @@ def vtile_by_mesh(fun: lu.WrappedFun,\nfull_to_shard_p = core.Primitive('full_to_shard')\n@full_to_shard_p.def_abstract_eval\n-def _full_to_shard_abstract_eval(x, axes, mesh):\n+def _full_to_shard_abstract_eval(x, axes, mesh, **_):\n# TODO: Assert x is a global aval! Or ideally check that it's global in dims from axes!\nreturn tile_aval_nd(mesh.shape, axes, x)\n-def _manual_proto(aval, axes, mesh):\n+def _manual_proto(aval: core.ShapedArray, manual_axes_set: FrozenSet[MeshAxisName], mesh: Mesh):\n\"\"\"Create an OpSharding proto that declares all mesh axes from `axes` as manual\nand all others as replicated.\n\"\"\"\n@@ -2059,8 +2058,8 @@ def _manual_proto(aval, axes, mesh):\nmesh_shape = list(named_mesh_shape.values())\naxis_order = {axis: i for i, axis in enumerate(mesh.axis_names)}\n- manual_axes = list(axes)\n- replicated_axes = list(axis for axis in mesh.axis_names if axis not in axes)\n+ manual_axes = list(sorted(manual_axes_set, key=str))\n+ replicated_axes = list(axis for axis in mesh.axis_names if axis not in manual_axes_set)\ntad_perm = ([axis_order[a] for a in replicated_axes] +\n[axis_order[a] for a in manual_axes])\n@@ -2077,29 +2076,29 @@ def _manual_proto(aval, axes, mesh):\nreturn proto\n@partial(mlir.register_lowering, full_to_shard_p)\n-def _full_to_shard_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\n+def _full_to_shard_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh, manual_axes: FrozenSet[MeshAxisName]):\n# TODO: Can we short-circuit for replicated values? Probably not.\naval_in, = ctx.avals_in\naval_out, = ctx.avals_out\nsharding_proto = mesh_sharding_specs(mesh.shape, mesh.axis_names)(aval_in, axes).sharding_proto()\nunspecified_dims = set(range(aval_in.ndim)) - set(axes.values())\nsx = mlir.wrap_with_sharding_op(x, sharding_proto, unspecified_dims=unspecified_dims)\n- manual_proto = _manual_proto(aval_in, axes, mesh)\n+ manual_proto = _manual_proto(aval_in, manual_axes, mesh)\nresult_type, = mlir.aval_to_ir_types(aval_out)\nreturn mlir.wrap_with_full_to_shard_op(result_type, sx, manual_proto, unspecified_dims=unspecified_dims),\nshard_to_full_p = core.Primitive('shard_to_full')\n@shard_to_full_p.def_abstract_eval\n-def _shard_to_full_abstract_eval(x, axes, mesh):\n+def _shard_to_full_abstract_eval(x, axes, mesh, **_):\n# TODO: Assert x is a global aval! Or ideally check that it's global in dims from axes!\nreturn untile_aval_nd(mesh.shape, axes, x)\n@partial(mlir.register_lowering, shard_to_full_p)\n-def _shard_to_full_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\n+def _shard_to_full_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh, manual_axes: FrozenSet[MeshAxisName]):\naval_in, = ctx.avals_in\naval_out, = ctx.avals_out\n- manual_proto = _manual_proto(aval_in, axes, mesh)\n+ manual_proto = _manual_proto(aval_in, manual_axes, mesh)\nresult_type, = mlir.aval_to_ir_types(aval_out)\nunspecified_dims = set(range(aval_in.ndim)) - set(axes.values())\nsx = mlir.wrap_with_sharding_op(x, manual_proto, unspecified_dims=unspecified_dims)\n@@ -2107,18 +2106,29 @@ def _shard_to_full_lowering(ctx, x, *, axes: ArrayMapping, mesh: Mesh):\nreturn mlir.wrap_with_shard_to_full_op(result_type, sx, sharding_proto, unspecified_dims),\n@lu.transformation\n-def vtile_manual(mesh: Mesh,\n+def vtile_manual(manual_axes: FrozenSet[MeshAxisName],\n+ mesh: Mesh,\nin_axes: Sequence[ArrayMapping],\nout_axes: Sequence[ArrayMapping],\n*args):\n- tiled_args = [full_to_shard_p.bind(arg, axes=axes, mesh=mesh)\n+ tiled_args = [full_to_shard_p.bind(arg, axes=axes, mesh=mesh, manual_axes=manual_axes)\nfor arg, axes in zip(args, in_axes)]\ntiled_outs = yield tiled_args, {}\n- outs = [shard_to_full_p.bind(out, axes=axes, mesh=mesh)\n+ outs = [shard_to_full_p.bind(out, axes=axes, mesh=mesh, manual_axes=manual_axes)\nfor out, axes in zip(tiled_outs, out_axes)]\nyield outs\n-TilingMethod = enum.Enum(\"TilingMethod\", [\"VECTORIZE\", \"MANUAL\"])\n+\n+@dataclasses.dataclass(frozen=True)\n+class TileVectorize:\n+ pass\n+\n+@dataclasses.dataclass(frozen=True)\n+class TileManual:\n+ manual_axes: FrozenSet[MeshAxisName]\n+\n+TilingMethod = Union[TileVectorize, TileManual]\n+\n@profiler.annotate_function\ndef lower_mesh_computation(\n@@ -2152,17 +2162,17 @@ def lower_mesh_computation(\nif spmd_lowering:\n# TODO: Consider handling xmap's 'vectorize' in here. We can vmap once instead of vtile twice!\nif tiling_method is not None:\n- if tiling_method is TilingMethod.VECTORIZE:\n+ if isinstance(tiling_method, TileVectorize):\ntiling_transform = vtile_by_mesh\n- elif tiling_method is TilingMethod.MANUAL:\n- tiling_transform = vtile_manual\n+ elif isinstance(tiling_method, TileManual):\n+ tiling_transform = lambda f, *args: vtile_manual(f, tiling_method.manual_axes, *args) # type: ignore\nelse:\nraise NotImplementedError(f\"Unrecognized tiling method: {tiling_method}\")\nassert not callable(out_axes)\nfun = tiling_transform(fun, mesh, in_axes, out_axes)\nin_jaxpr_avals = global_in_avals\nelse:\n- assert tiling_method is TilingMethod.VECTORIZE\n+ assert isinstance(tiling_method, TileVectorize)\nin_jaxpr_avals = in_tiled_avals\nwith core.extend_axis_env_nd(mesh.shape.items()):\nwith dispatch.log_elapsed_time(f\"Finished tracing + transforming {name_stack} \"\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -717,6 +717,14 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(20, dtype=jnp.float32)\nself.assertAllClose(fx(x), f(x))\n+ @jtu.with_mesh([('x', 2)])\n+ def testReplicated(self):\n+ # TODO(apaszke): This seems to be failing if I try to have a replicated and a mapped argument?\n+ f = lambda x: jnp.sin(jnp.cos(x) + x) * x\n+ fx = xmap(f, in_axes=[...], out_axes=[...], axis_sizes={'i': 4}, axis_resources={'i': 'x'})\n+ x = jnp.arange(20, dtype=jnp.float32)\n+ self.assertAllClose(fx(x), f(x))\n+\n@jtu.with_mesh([('x', 2), ('y', 1)])\ndef testInPJit(self):\nf = xmap(lambda x: jnp.sin(x) + x, in_axes=['i'], out_axes=['i'], axis_resources={'i': 'x'})\n@@ -724,6 +732,13 @@ class XMapTestManualSPMD(ManualSPMDTestMixin, XMapTestCase):\nx = jnp.arange(20, dtype=jnp.float32)\nself.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+ @jtu.with_mesh([('x', 2), ('y', 1)])\n+ def testInPJitReplicated(self):\n+ f = xmap(lambda x: jnp.sin(x) + x, in_axes={}, out_axes={}, axis_sizes={'i': 4}, axis_resources={'i': 'x'})\n+ h = pjit(lambda x: f(x * x) + x, in_axis_resources=P('y'), out_axis_resources=None)\n+ x = jnp.arange(20, dtype=jnp.float32)\n+ self.assertAllClose(h(x), jnp.sin(x * x) + x * x + x)\n+\n@jtu.with_mesh([('x', 2), ('y', 1)])\ndef testNestedConstraint(self):\n# TODO(b/219691408): Using P('y') instead of P() causes an XLA crash!\n" } ]
Python
Apache License 2.0
google/jax
Always treat all mesh axes controlled by xmap as MANUAL PiperOrigin-RevId: 430192736
260,335
22.02.2022 10:31:05
28,800
4b1d0a466b0b330ecb4285a0a80920497343b429
fixing scan and other control flow
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify/checkify_impl.py", "new_path": "jax/experimental/checkify/checkify_impl.py", "diff": "@@ -540,12 +540,13 @@ error_checks[lax.cond_p] = cond_error_check\ndef scan_error_check(error, enabled_errors, *in_flat, reverse, length, jaxpr,\nnum_consts, num_carry, linear, unroll):\nconsts, carry, xs = split_list(in_flat, [num_consts, num_carry])\n- checked_jaxpr, msgs_ = checkify_jaxpr(jaxpr, error, enabled_errors)\n+ checked_jaxpr_, msgs_ = checkify_jaxpr(jaxpr, error, enabled_errors)\n+ tomove = [False] * 2 + [True] * len(consts) + [False] * (len(carry) + len(xs))\n+ checked_jaxpr = pe.move_binders_to_front(checked_jaxpr_, tomove)\nnew_linear = (False, False, *linear)\nnew_in_flat = [*consts, error.err, error.code, *carry, *xs]\nerr, code, *outs = lax.scan_p.bind(\n- *consts, *new_in_flat,\n- reverse=reverse, length=length, jaxpr=checked_jaxpr,\n+ *new_in_flat, reverse=reverse, length=length, jaxpr=checked_jaxpr,\nnum_consts=len(consts), num_carry=len(carry)+2,\nlinear=new_linear, unroll=unroll)\nnew_msgs = {**error.msgs, **msgs_}\n@@ -576,22 +577,25 @@ def ignore_errors_jaxpr(jaxpr, error):\ndef while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\ncond_jaxpr, body_nconsts, body_jaxpr):\n- cond_jaxpr_, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\n- checked_cond_fun = core.jaxpr_as_fun(cond_jaxpr_)\n+ c_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n+\n# Check if the first cond application will error.\n- cond_err, cond_code, _ = checked_cond_fun(error.err, error.code, *in_flat)\n+ cond_jaxpr_, msgs_cond = checkify_jaxpr(cond_jaxpr, error, enabled_errors)\n+ cond_err, cond_code, _ = core.jaxpr_as_fun(cond_jaxpr_)(error.err, error.code,\n+ *c_consts, *carry)\n+ del cond_jaxpr_\n- checked_body_jaxpr, msgs_body = checkify_while_body_jaxpr(\n+ checked_body_jaxpr_, msgs_body = checkify_while_body_jaxpr(\ncond_jaxpr, body_jaxpr, error, enabled_errors)\n- compat_cond_jaxpr = ignore_errors_jaxpr(cond_jaxpr, error)\n- c_consts, b_consts, carry = split_list(in_flat, [cond_nconsts, body_nconsts])\n+ to_move = [False] * 2 + [True] * body_nconsts + [False] * len(carry)\n+ checked_body_jaxpr = pe.move_binders_to_front(checked_body_jaxpr_, to_move)\n+ compat_cond_jaxpr_ = ignore_errors_jaxpr(cond_jaxpr, error)\n+ to_move = [False] * 2 + [True] * cond_nconsts + [False] * len(carry)\n+ compat_cond_jaxpr = pe.move_binders_to_front(compat_cond_jaxpr_, to_move)\nnew_in_flat = [*c_consts, *b_consts, cond_err, cond_code, *carry]\nerr, code, *out = lax.while_p.bind(\n- *new_in_flat,\n- cond_nconsts=cond_nconsts,\n- cond_jaxpr=compat_cond_jaxpr,\n- body_nconsts=body_nconsts,\n- body_jaxpr=checked_body_jaxpr)\n+ *new_in_flat, cond_nconsts=cond_nconsts, cond_jaxpr=compat_cond_jaxpr,\n+ body_nconsts=body_nconsts, body_jaxpr=checked_body_jaxpr)\nnew_msgs = {**error.msgs, **msgs_body, **msgs_cond}\nreturn out, Error(err, code, new_msgs)\nerror_checks[lax.while_p] = while_loop_error_check\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1177,11 +1177,11 @@ def _reconstruct_pval(pval1: PartialVal, const2: core.Value):\ndef move_binders_to_front(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]) -> ClosedJaxpr:\n\"\"\"Reorder the `invars` to move to front the ones for which `to_move` is True.\"\"\"\n- assert not closed_jaxpr.jaxpr.constvars\n+ # assert not closed_jaxpr.jaxpr.constvars\nassert len(closed_jaxpr.in_avals) == len(to_move)\nnew_invars = _move_to_front(closed_jaxpr.jaxpr.invars, to_move)\n- new_jaxpr = Jaxpr((), new_invars, closed_jaxpr.jaxpr.outvars,\n- closed_jaxpr.jaxpr.eqns)\n+ new_jaxpr = Jaxpr(closed_jaxpr.jaxpr.constvars, new_invars,\n+ closed_jaxpr.jaxpr.outvars, closed_jaxpr.jaxpr.eqns)\nnew_closed_jaxpr = core.ClosedJaxpr(new_jaxpr, closed_jaxpr.consts)\nreturn new_closed_jaxpr\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -17,6 +17,7 @@ import unittest\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n+import numpy as np\nimport jax\nfrom jax import lax\n@@ -515,6 +516,53 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"nan generated by primitive sin\")\n+ def test_scan_consts(self):\n+ def f(xs):\n+ def scan_body(carry, _):\n+ return carry+1, xs[carry]\n+ return lax.scan(scan_body, 1, xs)[1]\n+\n+ checked_f = checkify.checkify(f, errors=checkify.index_checks)\n+ _, xs = 1, jnp.ones((7, 3))\n+ err, _ = checked_f(xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n+\n+ def test_scan_consts2(self):\n+ def f(xs):\n+ def scan_body(carry, _):\n+ # add more consts!\n+ _ = xs[carry], xs[carry], jnp.sin(np.arange(11.))\n+ return carry+1, xs[carry]\n+ return lax.scan(scan_body, 1, xs)[1]\n+\n+ checked_f = checkify.checkify(f, errors=checkify.index_checks)\n+ _, xs = 1, jnp.ones((7, 3))\n+ err, _ = checked_f(xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n+\n+ def test_while_consts(self):\n+ raise unittest.SkipTest(\"not quite working...\")\n+ def f(xs):\n+\n+ def while_cond(carry):\n+ i, _ = carry\n+ return i < 2\n+\n+ def while_body(carry):\n+ i, _ = carry\n+ return i + 1, xs[i]\n+\n+ return lax.while_loop(while_cond, while_body, (0, jnp.zeros_like(xs[0])))\n+\n+ checked_f = checkify.checkify(f, errors=checkify.index_checks)\n+ _, xs = 1, jnp.ones((7, 3))\n+ err, _ = checked_f(xs)\n+ self.assertIsNotNone(err.get())\n+ self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n+\n+\nclass AssertPrimitiveTests(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
fixing scan and other control flow Co-authored-by: Lena Martens <lenamartens@google.com>
260,424
22.02.2022 23:08:22
0
45d3ddda3193c2006a1471d3a949f6d91683e1a7
Fix tests and handle cond consts.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify/checkify_impl.py", "new_path": "jax/experimental/checkify/checkify_impl.py", "diff": "@@ -553,12 +553,13 @@ def scan_error_check(error, enabled_errors, *in_flat, reverse, length, jaxpr,\nreturn outs, Error(err, code, new_msgs)\nerror_checks[lax.scan_p] = scan_error_check\n-def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors):\n+def checkify_while_body_jaxpr(cond_jaxpr, body_jaxpr, error, enabled_errors, c_consts):\ncond_f = core.jaxpr_as_fun(cond_jaxpr)\nbody_f = core.jaxpr_as_fun(body_jaxpr)\ndef new_body_f(*vals):\nout = body_f(*vals)\n- _ = cond_f(*out) # this checks if the next cond application will error\n+ # This checks if the next cond application will error\n+ _ = cond_f(*c_consts, *out)\nreturn out\nreturn checkify_fun_to_jaxpr(lu.wrap_init(new_body_f), error, enabled_errors,\nbody_jaxpr.in_avals)\n@@ -586,7 +587,7 @@ def while_loop_error_check(error, enabled_errors, *in_flat, cond_nconsts,\ndel cond_jaxpr_\nchecked_body_jaxpr_, msgs_body = checkify_while_body_jaxpr(\n- cond_jaxpr, body_jaxpr, error, enabled_errors)\n+ cond_jaxpr, body_jaxpr, error, enabled_errors, c_consts)\nto_move = [False] * 2 + [True] * body_nconsts + [False] * len(carry)\nchecked_body_jaxpr = pe.move_binders_to_front(checked_body_jaxpr_, to_move)\ncompat_cond_jaxpr_ = ignore_errors_jaxpr(cond_jaxpr, error)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1177,7 +1177,6 @@ def _reconstruct_pval(pval1: PartialVal, const2: core.Value):\ndef move_binders_to_front(closed_jaxpr: ClosedJaxpr, to_move: Sequence[bool]) -> ClosedJaxpr:\n\"\"\"Reorder the `invars` to move to front the ones for which `to_move` is True.\"\"\"\n- # assert not closed_jaxpr.jaxpr.constvars\nassert len(closed_jaxpr.in_avals) == len(to_move)\nnew_invars = _move_to_front(closed_jaxpr.jaxpr.invars, to_move)\nnew_jaxpr = Jaxpr(closed_jaxpr.jaxpr.constvars, new_invars,\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -519,12 +519,12 @@ class CheckifyTransformTests(jtu.JaxTestCase):\ndef test_scan_consts(self):\ndef f(xs):\ndef scan_body(carry, _):\n+ # closes oves xs\nreturn carry+1, xs[carry]\nreturn lax.scan(scan_body, 1, xs)[1]\nchecked_f = checkify.checkify(f, errors=checkify.index_checks)\n- _, xs = 1, jnp.ones((7, 3))\n- err, _ = checked_f(xs)\n+ err, _ = checked_f(jnp.ones((7, 3)))\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n@@ -537,30 +537,28 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nreturn lax.scan(scan_body, 1, xs)[1]\nchecked_f = checkify.checkify(f, errors=checkify.index_checks)\n- _, xs = 1, jnp.ones((7, 3))\n- err, _ = checked_f(xs)\n+ err, _ = checked_f(jnp.ones((7, 3)))\nself.assertIsNotNone(err.get())\nself.assertStartsWith(err.get(), \"out-of-bounds indexing\")\ndef test_while_consts(self):\n- raise unittest.SkipTest(\"not quite working...\")\ndef f(xs):\n-\ndef while_cond(carry):\ni, _ = carry\n- return i < 2\n+ _ = xs[i], jnp.sin(np.arange(11.))\n+ return i > -1\ndef while_body(carry):\ni, _ = carry\n- return i + 1, xs[i]\n+ x = xs[i]\n+ return i - 1, x/i\nreturn lax.while_loop(while_cond, while_body, (0, jnp.zeros_like(xs[0])))\n- checked_f = checkify.checkify(f, errors=checkify.index_checks)\n- _, xs = 1, jnp.ones((7, 3))\n- err, _ = checked_f(xs)\n+ checked_f = checkify.checkify(f, errors=checkify.float_checks)\n+ err, _ = checked_f(jnp.ones((7, 3)))\nself.assertIsNotNone(err.get())\n- self.assertStartsWith(err.get(), \"out-of-bounds indexing\")\n+ self.assertStartsWith(err.get(), \"divided by zero\")\n" } ]
Python
Apache License 2.0
google/jax
Fix tests and handle cond consts.
260,631
24.02.2022 07:22:52
28,800
8372b98c4856b6b2363b7bb28abdb4579440a656
[JAX] Move ann.ann_recall back to tests. The function is simple enough for users to implement their own on the host.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/ann.py", "new_path": "jax/experimental/ann.py", "diff": "@@ -212,45 +212,6 @@ def approx_min_k(operand: Array,\naggregate_to_topk=aggregate_to_topk)\n-def ann_recall(result_neighbors: Array, ground_truth_neighbors: Array) -> float:\n- \"\"\"Computes the recall of an approximate nearest neighbor search.\n-\n- Note, this is NOT a JAX-compatible op. This is a host function that only takes\n- numpy arrays as the inputs.\n-\n- Args:\n- result_neighbors: int32 numpy array of the shape\n- [num_queries, neighbors_per_query] where the values are the indices of the\n- dataset.\n- ground_truth_neighbors: int32 numpy array of with shape\n- [num_queries, ground_truth_neighbors_per_query] where the values are the\n- indices of the dataset.\n-\n- Example:\n- # shape [num_queries, 100]\n- ground_truth_neighbors = ... # pre-computed top 100 sorted neighbors\n- # shape [num_queries, 200]\n- result_neighbors = ... # Retrieves 200 neighbors from some ann algorithms.\n-\n- # Computes the recall with k = 100\n- ann_recall(result_neighbors, ground_truth_neighbors)\n-\n- # Computes the recall with k = 10\n- ann_recall(result_neighbors, ground_truth_neighbors[:,0:10])\n-\n- Returns:\n- The recall.\n- \"\"\"\n- assert len(result_neighbors.shape) == 2, 'shape = [num_queries, neighbors_per_query]'\n- assert len(ground_truth_neighbors.shape) == 2, 'shape = [num_queries, ground_truth_neighbors_per_query]'\n- assert result_neighbors.shape[0] == ground_truth_neighbors.shape[0]\n- gt_sets = [set(np.asarray(x)) for x in ground_truth_neighbors]\n- hits = sum(\n- len(list(x for x in nn_per_q if x.item() in gt_sets[q]))\n- for q, nn_per_q in enumerate(result_neighbors))\n- return hits / ground_truth_neighbors.size\n-\n-\ndef _approx_top_k_abstract_eval(operand, *, k, reduction_dimension,\nrecall_target, is_max_k,\nreduction_input_size_override,\n" }, { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "@@ -32,6 +32,34 @@ config.parse_flags_with_absl()\nignore_jit_of_pmap_warning = partial(\njtu.ignore_warning,message=\".*jit-of-pmap.*\")\n+\n+def compute_recall(result_neighbors, ground_truth_neighbors) -> float:\n+ \"\"\"Computes the recall of an approximate nearest neighbor search.\n+\n+ Args:\n+ result_neighbors: int32 numpy array of the shape [num_queries,\n+ neighbors_per_query] where the values are the indices of the dataset.\n+ ground_truth_neighbors: int32 numpy array of with shape [num_queries,\n+ ground_truth_neighbors_per_query] where the values are the indices of the\n+ dataset.\n+\n+ Returns:\n+ The recall.\n+ \"\"\"\n+ assert len(\n+ result_neighbors.shape) == 2, \"shape = [num_queries, neighbors_per_query]\"\n+ assert len(ground_truth_neighbors.shape\n+ ) == 2, \"shape = [num_queries, ground_truth_neighbors_per_query]\"\n+ assert result_neighbors.shape[0] == ground_truth_neighbors.shape[0]\n+ gt_sets = [set(np.asarray(x)) for x in ground_truth_neighbors]\n+ hits = sum(\n+ len(list(x\n+ for x in nn_per_q\n+ if x.item() in gt_sets[q]))\n+ for q, nn_per_q in enumerate(result_neighbors))\n+ return hits / ground_truth_neighbors.size\n+\n+\nclass AnnTest(jtu.JaxTestCase):\n@parameterized.named_parameters(\n@@ -54,7 +82,7 @@ class AnnTest(jtu.JaxTestCase):\n_, gt_args = lax.top_k(scores, k)\n_, ann_args = ann.approx_max_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\n- ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ ann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\nself.assertGreater(ann_recall, recall)\n@parameterized.named_parameters(\n@@ -77,7 +105,7 @@ class AnnTest(jtu.JaxTestCase):\n_, gt_args = lax.top_k(-scores, k)\n_, ann_args = ann.approx_min_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\n- ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ ann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\nself.assertGreater(ann_recall, recall)\n@parameterized.named_parameters(\n@@ -140,7 +168,7 @@ class AnnTest(jtu.JaxTestCase):\nann_args = lax.collapse(ann_args, 1, 3)\nann_vals, ann_args = lax.sort_key_val(ann_vals, ann_args, dimension=1)\nann_args = lax.slice_in_dim(ann_args, start_index=0, limit_index=k, axis=1)\n- ann_recall = ann.ann_recall(np.asarray(ann_args), np.asarray(gt_args))\n+ ann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\nself.assertGreater(ann_recall, recall)\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Move ann.ann_recall back to tests. The function is simple enough for users to implement their own on the host. PiperOrigin-RevId: 430696789
260,314
24.02.2022 22:34:00
18,000
e28ec78d7a0812dd8ec5753d03b52b156131a0fa
Make negative dimension return consistent results for image.scale_and_translate
[ { "change_type": "MODIFY", "old_path": "jax/_src/image/scale.py", "new_path": "jax/_src/image/scale.py", "diff": "@@ -89,7 +89,10 @@ def _scale_and_translate(x, output_shape: core.Shape,\ncontractions = []\nin_indices = list(range(len(output_shape)))\nout_indices = list(range(len(output_shape)))\n+ spatial_ndim = len(spatial_dims)\nfor i, d in enumerate(spatial_dims):\n+ if d < 0:\n+ d = spatial_ndim + d\nm = input_shape[d]\nn = output_shape[d]\nw = compute_weight_mat(m, n, scale[i], translation[i],\n" }, { "change_type": "MODIFY", "old_path": "tests/image_test.py", "new_path": "tests/image_test.py", "diff": "@@ -382,6 +382,13 @@ class ImageTest(jtu.JaxTestCase):\ntranslate_out = jax.grad(translate_fn)(translation_a)\nself.assertTrue(jnp.all(jnp.isfinite(translate_out)))\n+ def testScaleAndTranslateNegativeDims(self):\n+ data = jnp.full((3, 3), 0.5)\n+ actual = jax.image.scale_and_translate(\n+ data, (5, 5), (-2, -1), jnp.ones(2), jnp.zeros(2), \"linear\")\n+ expected = jax.image.scale_and_translate(\n+ data, (5, 5), (0, 1), jnp.ones(2), jnp.zeros(2), \"linear\")\n+ self.assertAllClose(actual, expected)\ndef testResizeWithUnusualShapes(self):\nx = jnp.ones((3, 4))\n" } ]
Python
Apache License 2.0
google/jax
Make negative dimension return consistent results for image.scale_and_translate
260,314
25.02.2022 17:39:47
18,000
0a859453b3a6ba4b71f33cc1eeb15bdd5e00d392
Use canonicalize_axis
[ { "change_type": "MODIFY", "old_path": "jax/_src/image/scale.py", "new_path": "jax/_src/image/scale.py", "diff": "@@ -20,6 +20,7 @@ from jax import core\nfrom jax import jit\nfrom jax import lax\nfrom jax import numpy as jnp\n+from jax._src.util import canonicalize_axis\nimport numpy as np\n@@ -91,8 +92,7 @@ def _scale_and_translate(x, output_shape: core.Shape,\nout_indices = list(range(len(output_shape)))\nspatial_ndim = len(spatial_dims)\nfor i, d in enumerate(spatial_dims):\n- if d < 0:\n- d = spatial_ndim + d\n+ d = canonicalize_axis(d, spatial_ndim)\nm = input_shape[d]\nn = output_shape[d]\nw = compute_weight_mat(m, n, scale[i], translation[i],\n" } ]
Python
Apache License 2.0
google/jax
Use canonicalize_axis
260,314
25.02.2022 21:48:39
18,000
0b022b71a5d1dd12bb53211c0bfd20fc06b892ff
Fix incorrect implementation to find canonicalize_axis
[ { "change_type": "MODIFY", "old_path": "jax/_src/image/scale.py", "new_path": "jax/_src/image/scale.py", "diff": "@@ -90,9 +90,8 @@ def _scale_and_translate(x, output_shape: core.Shape,\ncontractions = []\nin_indices = list(range(len(output_shape)))\nout_indices = list(range(len(output_shape)))\n- spatial_ndim = len(spatial_dims)\nfor i, d in enumerate(spatial_dims):\n- d = canonicalize_axis(d, spatial_ndim)\n+ d = canonicalize_axis(d, x.ndim)\nm = input_shape[d]\nn = output_shape[d]\nw = compute_weight_mat(m, n, scale[i], translation[i],\n" } ]
Python
Apache License 2.0
google/jax
Fix incorrect implementation to find canonicalize_axis
260,631
01.03.2022 14:24:21
28,800
1a1bf122d98852cf2803dfdf494da12e023d0c47
[JAX] Fix github lint_and_typecheck for Primitives
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -265,9 +265,12 @@ Atom = Union[Var, Literal]\nclass Primitive:\nname: str\n- multiple_results = False # set for multi-output primitives\n- call_primitive = False # set for call primitives processed in final style\n- map_primitive = False # set for map primitives processed in final style\n+ # set for multi-output primitives.\n+ multiple_results: bool = False\n+ # set for call primitives processed in final style.\n+ call_primitive: bool = False\n+ # set for map primitives processed in final style.\n+ map_primitive: bool = False\ndef __init__(self, name: str):\nself.name = name\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Fix github lint_and_typecheck for Primitives PiperOrigin-RevId: 431776305
260,631
01.03.2022 14:46:04
28,800
d9f82f7b9b51e0c27b2210f1e549518dcd27f498
[JAX] Move `experimental.ann.approx_*_k` into `lax`. Updated docs, tests and the example code snippets.
[ { "change_type": "DELETE", "old_path": "docs/jax.experimental.ann.rst", "new_path": null, "diff": "-jax.experimental.ann module\n-===========================\n-\n-.. automodule:: jax.experimental.ann\n-\n-API\n----\n-\n-.. autosummary::\n- :toctree: _autosummary\n-\n- approx_max_k\n- approx_min_k\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.experimental.rst", "new_path": "docs/jax.experimental.rst", "diff": "@@ -6,13 +6,14 @@ jax.experimental package\n``jax.experimental.optix`` has been moved into its own Python package\n(https://github.com/deepmind/optax).\n+``jax.experimental.ann`` has been moved into ``jax.lax``.\n+\nExperimental Modules\n--------------------\n.. toctree::\n:maxdepth: 1\n- jax.experimental.ann\njax.experimental.global_device_array\njax.experimental.host_callback\njax.experimental.loops\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.lax.rst", "new_path": "docs/jax.lax.rst", "diff": "@@ -26,6 +26,8 @@ Operators\nabs\nadd\nacos\n+ approx_max_k\n+ approx_min_k\nargmax\nargmin\nasin\n" }, { "change_type": "RENAME", "old_path": "jax/experimental/ann.py", "new_path": "jax/_src/lax/ann.py", "diff": "@@ -21,7 +21,6 @@ Usage::\nimport functools\nimport jax\n- from jax.experimental import ann\n# MIPS := maximal inner product search\n# Inputs:\n@@ -35,12 +34,7 @@ Usage::\ndists = jax.lax.dot(qy, db.transpose())\n# Computes max_k along the last dimension\n# returns (f32[qy_size, k], i32[qy_size, k])\n- return ann.approx_max_k(dists, k=k, recall_target=recall_target)\n-\n- # Obtains the top-10 dot products and its offsets in db.\n- dot_products, neighbors = mips(qy, db, k=10)\n- # Computes the recall against the true neighbors.\n- recall = ann.ann_recall(neighbors, true_neighbors)\n+ return jax.lax.approx_max_k(dists, k=k, recall_target=recall_target)\n# Multi-core example\n# Inputs:\n@@ -58,7 +52,7 @@ Usage::\nout_axes=(1, 1))\ndef pmap_mips(qy, db, db_offset, db_size, k, recall_target):\ndists = jax.lax.dot(qy, db.transpose())\n- dists, neighbors = ann.approx_max_k(\n+ dists, neighbors = jax.lax.approx_max_k(\ndists, k=k, recall_target=recall_target,\nreduction_input_size_override=db_size)\nreturn (dists, neighbors + db_offset)\n@@ -79,7 +73,8 @@ from functools import partial\nfrom typing import (Any, Tuple)\nimport numpy as np\n-from jax import lax, core\n+from jax import core\n+from jax._src.lax import lax\nfrom jax._src.lib import xla_client as xc\nfrom jax._src import ad_util, dtypes\n@@ -125,12 +120,11 @@ def approx_max_k(operand: Array,\n>>> import functools\n>>> import jax\n>>> import numpy as np\n- >>> from jax.experimental import ann\n>>> @functools.partial(jax.jit, static_argnames=[\"k\", \"recall_target\"])\n... def mips(qy, db, k=10, recall_target=0.95):\n... dists = jax.lax.dot(qy, db.transpose())\n... # returns (f32[qy_size, k], i32[qy_size, k])\n- ... return ann.approx_max_k(dists, k=k, recall_target=recall_target)\n+ ... return jax.lax.approx_max_k(dists, k=k, recall_target=recall_target)\n>>>\n>>> qy = jax.numpy.array(np.random.rand(50, 64))\n>>> db = jax.numpy.array(np.random.rand(1024, 64))\n@@ -185,11 +179,10 @@ def approx_min_k(operand: Array,\n>>> import functools\n>>> import jax\n>>> import numpy as np\n- >>> from jax.experimental import ann\n>>> @functools.partial(jax.jit, static_argnames=[\"k\", \"recall_target\"])\n... def l2_ann(qy, db, half_db_norms, k=10, recall_target=0.95):\n... dists = half_db_norms - jax.lax.dot(qy, db.transpose())\n- ... return ann.approx_min_k(dists, k=k, recall_target=recall_target)\n+ ... return jax.lax.approx_min_k(dists, k=k, recall_target=recall_target)\n>>>\n>>> qy = jax.numpy.array(np.random.rand(50, 64))\n>>> db = jax.numpy.array(np.random.rand(1024, 64))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -986,6 +986,7 @@ tf_not_yet_impl = [\n# Not high priority?\n\"after_all\",\n\"all_to_all\",\n+ \"approx_top_k\",\n\"create_token\",\n\"custom_transpose_call\",\n\"custom_vmap_call\",\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -369,5 +369,10 @@ from jax._src.lax.other import (\nconv_general_dilated_local as conv_general_dilated_local,\nconv_general_dilated_patches as conv_general_dilated_patches\n)\n+from jax._src.lax.ann import (\n+ approx_max_k as approx_max_k,\n+ approx_min_k as approx_min_k,\n+ approx_top_k_p as approx_top_k_p\n+)\nfrom jax._src.ad_util import stop_gradient_p as stop_gradient_p\nfrom jax.lax import linalg as linalg\n" }, { "change_type": "MODIFY", "old_path": "tests/ann_test.py", "new_path": "tests/ann_test.py", "diff": "@@ -21,7 +21,6 @@ import numpy as np\nimport jax\nfrom jax import lax\n-from jax.experimental import ann\nfrom jax._src import test_util as jtu\nfrom jax._src.util import prod\n@@ -80,7 +79,7 @@ class AnnTest(jtu.JaxTestCase):\ndb = rng(db_shape, dtype)\nscores = lax.dot(qy, db)\n_, gt_args = lax.top_k(scores, k)\n- _, ann_args = ann.approx_max_k(scores, k, recall_target=recall)\n+ _, ann_args = lax.approx_max_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\nann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\nself.assertGreater(ann_recall, recall)\n@@ -103,7 +102,7 @@ class AnnTest(jtu.JaxTestCase):\ndb = rng(db_shape, dtype)\nscores = lax.dot(qy, db)\n_, gt_args = lax.top_k(-scores, k)\n- _, ann_args = ann.approx_min_k(scores, k, recall_target=recall)\n+ _, ann_args = lax.approx_min_k(scores, k, recall_target=recall)\nself.assertEqual(k, len(ann_args[0]))\nann_recall = compute_recall(np.asarray(ann_args), np.asarray(gt_args))\nself.assertGreater(ann_recall, recall)\n@@ -122,9 +121,9 @@ class AnnTest(jtu.JaxTestCase):\nvals = np.arange(prod(shape), dtype=dtype)\nvals = self.rng().permutation(vals).reshape(shape)\nif is_max_k:\n- fn = lambda vs: ann.approx_max_k(vs, k=k)[0]\n+ fn = lambda vs: lax.approx_max_k(vs, k=k)[0]\nelse:\n- fn = lambda vs: ann.approx_min_k(vs, k=k)[0]\n+ fn = lambda vs: lax.approx_min_k(vs, k=k)[0]\njtu.check_grads(fn, (vals,), 2, [\"fwd\", \"rev\"], eps=1e-2)\n@@ -153,7 +152,10 @@ class AnnTest(jtu.JaxTestCase):\ndb_offsets = np.arange(num_devices, dtype=np.int32) * db_per_device\ndef parallel_topk(qy, db, db_offset):\nscores = lax.dot_general(qy, db, (([1],[1]),([],[])))\n- ann_vals, ann_args = ann.approx_min_k(scores, k=k, reduction_dimension=1,\n+ ann_vals, ann_args = lax.approx_min_k(\n+ scores,\n+ k=k,\n+ reduction_dimension=1,\nrecall_target=recall,\nreduction_input_size_override=db_size,\naggregate_to_topk=False)\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Move `experimental.ann.approx_*_k` into `lax`. Updated docs, tests and the example code snippets. PiperOrigin-RevId: 431781401
260,631
02.03.2022 08:58:22
28,800
fb44d7c12f8d1c060d54cfe4a3aed23db5285845
[JAX] Add release note for the graduration of the experimental.ann module.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -16,6 +16,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\ndeprecated in 0.2.22, have been removed. Please use\n[the `.at` property on JAX arrays](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html)\ninstead, e.g., `x.at[idx].set(y)`.\n+ * Moved `jax.experimental.ann.approx_*_k` into `jax.lax`. These functions are\n+ optimized alternatives to `jax.lax.top_k`.\n## jaxlib 0.3.1 (Unreleased)\n" } ]
Python
Apache License 2.0
google/jax
[JAX] Add release note for the graduration of the experimental.ann module. PiperOrigin-RevId: 431951602
260,631
02.03.2022 10:11:09
28,800
f1e71c11d729e0f16e84e76fe85051d223e9bb0b
[Jax] Format ann docstring.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/ann.py", "new_path": "jax/_src/lax/ann.py", "diff": "@@ -97,21 +97,21 @@ def approx_max_k(operand: Array,\nreduction_dimension : Integer dimension along which to search. Default: -1.\nrecall_target : Recall target for the approximation.\nreduction_input_size_override : When set to a positive value, it overrides\n- the size determined by operands[reduction_dim] for evaluating the recall.\n- This option is useful when the given operand is only a subset of the\n- overall computation in SPMD or distributed pipelines, where the true input\n- size cannot be deferred by the operand shape.\n+ the size determined by ``operands[reduction_dim]`` for evaluating the\n+ recall. This option is useful when the given operand is only a subset of\n+ the overall computation in SPMD or distributed pipelines, where the true\n+ input size cannot be deferred by the operand shape.\naggregate_to_topk : When true, aggregates approximate results to top-k. When\nfalse, returns the approximate results. The number of the approximate\nresults is implementation defined and is greater equals to the specified\n- k.\n+ ``k``.\nReturns:\n- Tuple[Array, Array] : The two arrays are the max k values and the\n+ Tuple of two arrays. The arrays are the max ``k`` values and the\ncorresponding indices along the reduction_dimension of the input operand.\nThe arrays' dimensions are the same as the input operand except for the\n- reduction_dimension: when aggregate_to_topk is true, the reduction\n- dimension is k; otherwise, it is greater equals to k where the size is\n+ ``reduction_dimension``: when ``aggregate_to_topk`` is true, the reduction\n+ dimension is ``k``; otherwise, it is greater equals to k where the size is\nimplementation-defined.\nWe encourage users to wrap the approx_*_k with jit. See the following example\n@@ -156,21 +156,21 @@ def approx_min_k(operand: Array,\nreduction_dimension: Integer dimension along which to search. Default: -1.\nrecall_target: Recall target for the approximation.\nreduction_input_size_override : When set to a positive value, it overrides\n- the size determined by operands[reduction_dim] for evaluating the recall.\n- This option is useful when the given operand is only a subset of the\n- overall computation in SPMD or distributed pipelines, where the true input\n- size cannot be deferred by the operand shape.\n+ the size determined by ``operands[reduction_dim]`` for evaluating the\n+ recall. This option is useful when the given operand is only a subset of\n+ the overall computation in SPMD or distributed pipelines, where the true\n+ input size cannot be deferred by the operand shape.\naggregate_to_topk: When true, aggregates approximate results to top-k. When\nfalse, returns the approximate results. The number of the approximate\nresults is implementation defined and is greater equals to the specified\n- k.\n+ ``k``.\nReturns:\n- Tuple[Array, Array] : The two arrays are the least k values and the\n+ Tuple of two arrays. The arrays are the least ``k`` values and the\ncorresponding indices along the reduction_dimension of the input operand.\nThe arrays' dimensions are the same as the input operand except for the\n- reduction_dimension: when aggregate_to_topk is true, the reduction\n- dimension is k; otherwise, it is greater equals to k where the size is\n+ ``reduction_dimension``: when ``aggregate_to_topk`` is true, the reduction\n+ dimension is ``k``; otherwise, it is greater equals to k where the size is\nimplementation-defined.\nWe encourage users to wrap the approx_*_k with jit. See the following example\n" } ]
Python
Apache License 2.0
google/jax
[Jax] Format ann docstring. PiperOrigin-RevId: 431968329
260,578
03.03.2022 12:19:04
28,800
f0df7b7348debbc6db314e6387756f4f7582f568
Fix the display of GDA docs
[ { "change_type": "MODIFY", "old_path": "docs/jax.experimental.global_device_array.rst", "new_path": "docs/jax.experimental.global_device_array.rst", "diff": "@@ -6,8 +6,6 @@ jax.experimental.global_device_array module\nAPI\n---\n-.. autosummary::\n- :toctree: _autosummary\n-\n- GlobalDeviceArray\n- Shard\n\\ No newline at end of file\n+.. autoclass:: GlobalDeviceArray\n+ :members:\n+.. autoclass:: Shard\n" } ]
Python
Apache License 2.0
google/jax
Fix the display of GDA docs
260,578
03.03.2022 13:40:42
28,800
852e39e2edb6e82a21ac07e352a65599881467ce
convert to doctest
[ { "change_type": "MODIFY", "old_path": "jax/experimental/global_device_array.py", "new_path": "jax/experimental/global_device_array.py", "diff": "@@ -219,40 +219,51 @@ class GlobalDeviceArray:\nis_fully_replicated : True if the full array value is present on all devices\nof the global mesh.\n- Example::\n-\n- # Logical mesh is (hosts, devices)\n- assert global_mesh.shape == {'x': 4, 'y': 8}\n-\n- global_input_shape = (64, 32)\n- mesh_axes = P('x', 'y')\n-\n- # Dummy example data; in practice we wouldn't necessarily materialize global data\n- # in a single process.\n- global_input_data = np.arange(\n- np.prod(global_input_shape)).reshape(global_input_shape)\n-\n- def get_local_data_slice(index):\n- # index will be a tuple of slice objects, e.g. (slice(0, 16), slice(0, 4))\n- # This method will be called per-local device from the GDA constructor.\n- return global_input_data[index]\n-\n- gda = GlobalDeviceArray.from_callback(\n- global_input_shape, global_mesh, mesh_axes, get_local_data_slice)\n-\n- f = pjit(lambda x: x @ x.T, out_axis_resources = P('y', 'x'))\n-\n+ Example:\n+\n+ >>> from jax.experimental.maps import Mesh\n+ >>> from jax.experimental import PartitionSpec as P\n+ >>> import numpy as np\n+\n+ >>> assert jax.device_count() == 8\n+ >>> global_mesh = Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n+ >>> # Logical mesh is (hosts, devices)\n+ >>> assert global_mesh.shape == {'x': 4, 'y': 2}\n+\n+ >>> global_input_shape = (8, 2)\n+ >>> mesh_axes = P('x', 'y')\n+\n+ >>> # Dummy example data; in practice we wouldn't necessarily materialize global data\n+ >>> # in a single process.\n+ >>> global_input_data = np.arange(\n+ ... np.prod(global_input_shape)).reshape(global_input_shape)\n+\n+ >>> def get_local_data_slice(index):\n+ ... # index will be a tuple of slice objects, e.g. (slice(0, 16), slice(0, 4))\n+ ... # This method will be called per-local device from the GDA constructor.\n+ ... return global_input_data[index]\n+\n+ >>> gda = GlobalDeviceArray.from_callback(\n+ ... global_input_shape, global_mesh, mesh_axes, get_local_data_slice)\n+\n+ >>> print(gda.shape)\n+ (8, 2)\n+ >>> print(gda.local_shards[0].data) # Access the data on a single local device\n+ [[0]\n+ [2]]\n+ >>> print(gda.local_shards[0].data.shape)\n+ (2, 1)\n+ >>> # Numpy-style index into the global array that this data shard corresponds to\n+ >>> print(gda.local_shards[0].index)\n+ (slice(0, 2, None), slice(0, 1, None))\n+\n+ # Allow pjit to output GDAs\n+ jax.config.update('jax_parallel_functions_output_gda', True)\n+\n+ f = pjit(lambda x: x @ x.T, in_axis_resources=P('x', 'y'), out_axis_resources = P('x', 'y'))\nwith global_mesh:\nout = f(gda)\n- print(type(out)) # GlobalDeviceArray\n- print(out.shape) # global shape == (64, 64)\n- print(out.local_shards[0].data) # Access the data on a single local device,\n- # e.g. for checkpointing\n- print(out.local_shards[0].data.shape) # per-device shape == (8, 16)\n- print(out.local_shards[0].index) # Numpy-style index into the global array that\n- # this data shard corresponds to\n-\n# `out` can be passed to another pjit call, out.local_shards can be used to\n# export the data to non-jax systems (e.g. for checkpointing or logging), etc.\n\"\"\"\n@@ -394,11 +405,17 @@ class GlobalDeviceArray:\nExample::\n- global_input_shape = (8, 2)\n- global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n- def cb(index):\n- return global_input_data[index]\n- gda = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, mesh_axes, cb)\n+ >>> from jax.experimental.maps import Mesh\n+ >>> import numpy as np\n+ >>> global_input_shape = (8, 8)\n+ >>> mesh_axes = ['x', 'y']\n+ >>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(2, 4), ('x', 'y'))\n+ >>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ >>> def cb(index):\n+ ... return global_input_data[index]\n+ >>> gda = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, mesh_axes, cb)\n+ >>> gda.local_data(0).shape\n+ (4, 2)\nArgs:\nglobal_shape : The global shape of the array\n@@ -431,13 +448,18 @@ class GlobalDeviceArray:\nExample::\n- global_input_shape = (8, 2)\n- global_input_data = np.arange(\n- prod(global_input_shape)).reshape(global_input_shape)\n- def batched_cb(indices):\n- self.assertEqual(len(indices),len(global_mesh.local_devices))\n- return [global_input_data[index] for index in indices]\n- gda = GlobalDeviceArray.from_batched_callback(global_input_shape, global_mesh, mesh_axes, batched_cb)\n+ >>> from jax.experimental.maps import Mesh\n+ >>> import numpy as np\n+ >>> global_input_shape = (8, 2)\n+ >>> mesh_axes = ['x']\n+ >>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n+ >>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ >>> def batched_cb(indices):\n+ ... assert len(indices) == len(global_mesh.local_devices)\n+ ... return [global_input_data[index] for index in indices]\n+ >>> gda = GlobalDeviceArray.from_batched_callback(global_input_shape, global_mesh, mesh_axes, batched_cb)\n+ >>> gda.local_data(0).shape\n+ (2, 2)\nArgs:\nglobal_shape : The global shape of the array\n@@ -469,17 +491,23 @@ class GlobalDeviceArray:\nExample::\n- global_input_shape = (8, 2)\n- global_input_data = np.arange(prod(global_input_shape), dtype=np.float32).reshape(global_input_shape)\n- def cb(cb_inp):\n- self.assertLen(cb_inp, len(global_mesh.local_devices))\n- dbs = []\n- for inp in cb_inp:\n- index, devices = inp\n- array = global_input_data[index]\n- dbs.extend([jax.device_put(array, device) for device in devices])\n- return dbs\n- gda = GlobalDeviceArray.from_batched_callback_with_devices(global_input_shape, global_mesh, mesh_axes, cb)\n+ >>> from jax.experimental.maps import Mesh\n+ >>> import numpy as np\n+ >>> global_input_shape = (8, 2)\n+ >>> mesh_axes = [('x', 'y')]\n+ >>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n+ >>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ >>> def cb(cb_inp):\n+ ... dbs = []\n+ ... for inp in cb_inp:\n+ ... index, devices = inp\n+ ... array = global_input_data[index]\n+ ... dbs.extend([jax.device_put(array, device) for device in devices])\n+ ... return dbs\n+ >>> gda = GlobalDeviceArray.from_batched_callback_with_devices(\n+ ... global_input_shape, global_mesh, mesh_axes, cb)\n+ >>> gda.local_data(0).shape\n+ (1, 2)\nArgs:\nglobal_shape : The global shape of the array\n" } ]
Python
Apache License 2.0
google/jax
convert to doctest
260,447
03.03.2022 20:58:46
28,800
2d17b4d637f3db7a707ae8d7ef167cfdfe1b0f68
[linalg] Fix type promotion in QDWH.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/qdwh.py", "new_path": "jax/_src/lax/qdwh.py", "diff": "@@ -36,7 +36,7 @@ def _use_qr(u, params):\n\"\"\"Uses QR decomposition.\"\"\"\na, b, c = params\nm, n = u.shape\n- y = jnp.concatenate([jnp.sqrt(c) * u, jnp.eye(n)])\n+ y = jnp.concatenate([jnp.sqrt(c) * u, jnp.eye(n, dtype=jnp.dtype(u))])\nq, _ = lax_linalg.qr(y, full_matrices=False)\nq1 = q[:m, :]\nq2 = (q[m:, :]).T.conj()\n@@ -49,7 +49,7 @@ def _use_cholesky(u, params):\n\"\"\"Uses Cholesky decomposition.\"\"\"\na, b, c = params\n_, n = u.shape\n- x = c * u.T.conj() @ u + jnp.eye(n)\n+ x = c * (u.T.conj() @ u) + jnp.eye(n, dtype=jnp.dtype(u))\n# `y` is lower triangular.\ny = lax_linalg.cholesky(x, symmetrize_input=False)\n" } ]
Python
Apache License 2.0
google/jax
[linalg] Fix type promotion in QDWH. PiperOrigin-RevId: 432352839
260,403
04.03.2022 04:20:57
28,800
f6a5f0dca2d19d621e68d15e501f47a109ccd117
Use real Precision type for lax.PrecisionType
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -19,7 +19,7 @@ from functools import partial\nimport itertools\nimport operator\nfrom typing import (Any, Callable, Optional, Sequence, Tuple, List, TypeVar,\n- Union)\n+ Union, cast as type_cast)\nimport warnings\nimport numpy as np\n@@ -606,7 +606,7 @@ class Precision(xla_client.PrecisionConfig.Precision): # type: ignore\nreturn self.name\n-PrecisionType = Any\n+PrecisionType = Precision\nPrecisionLike = Union[None, str, PrecisionType, Tuple[str, str],\nTuple[PrecisionType, PrecisionType]]\n@@ -2610,10 +2610,12 @@ xla.register_translation(dot_general_p, _dot_general_cpu_translation_rule,\ndef precision_attr(precision: PrecisionType) -> ir.ArrayAttr:\nif precision is None:\n- precision = (Precision.DEFAULT, Precision.DEFAULT)\n+ full_precision = (Precision.DEFAULT, Precision.DEFAULT)\nelif not isinstance(precision, tuple):\n- precision = (precision, precision)\n- return ir.ArrayAttr.get([ir.StringAttr.get(str(p)) for p in precision])\n+ full_precision = (precision, precision)\n+ else:\n+ full_precision = precision\n+ return ir.ArrayAttr.get([ir.StringAttr.get(str(p)) for p in full_precision])\ndef _dot_general_lower(ctx, lhs, rhs, *, dimension_numbers,\nprecision, preferred_element_type: Optional[np.dtype]):\n@@ -4653,25 +4655,29 @@ def canonicalize_precision(precision: PrecisionLike) -> Optional[Tuple[Precision\nif config.jax_default_matmul_precision is None:\nreturn None\ntry:\n- precision = Precision(config.jax_default_matmul_precision)\n- return (precision, precision)\n+ return type_cast(\n+ Tuple[PrecisionType, PrecisionType],\n+ (Precision(config.jax_default_matmul_precision),\n+ Precision(config.jax_default_matmul_precision)))\nexcept TypeError:\nraise ValueError(\n\"jax_default_matmul_precision flag must be set to None or a value in \"\nf\"{list(Precision._strings)}, but got {config.jax_default_matmul_precision}\"\n) from None\nelif isinstance(precision, str) and precision in Precision._strings:\n- precision = Precision(precision)\n- return (precision, precision)\n+ return type_cast(Tuple[PrecisionType, PrecisionType],\n+ (Precision(precision), Precision(precision)))\nelif isinstance(precision, xla_client.PrecisionConfig.Precision):\n- return (precision, precision)\n+ return type_cast(Tuple[PrecisionType, PrecisionType], (precision, precision))\nelif (isinstance(precision, (list, tuple)) and len(precision) == 2 and\nall(isinstance(p, xla_client.PrecisionConfig.Precision) for p in precision)):\n- return precision # type: ignore[return-value]\n+ return type_cast(Tuple[PrecisionType, PrecisionType], precision)\nelif (isinstance(precision, (list, tuple)) and len(precision) == 2 and\nall(isinstance(s, str) for s in precision)):\ns1, s2 = precision\n- return (canonicalize_precision(s1)[0], canonicalize_precision(s2)[0]) # type: ignore\n+ p1 = type_cast(Tuple[PrecisionType, PrecisionType], canonicalize_precision(s1))[0]\n+ p2 = type_cast(Tuple[PrecisionType, PrecisionType], canonicalize_precision(s2))[0]\n+ return (p1, p2)\nelse:\nraise ValueError(\nf\"Precision argument must be None, a string in {list(Precision._strings)}, \"\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/other.py", "new_path": "jax/_src/lax/other.py", "diff": "# limitations under the License.\n-from typing import Any, Optional, Sequence, Tuple, Union\n+from typing import Any, Optional, Sequence, Tuple, Union, cast as type_cast\nfrom jax._src.numpy import lax_numpy as jnp\nfrom jax._src.util import prod\nfrom jax._src.lax import lax\n@@ -125,7 +125,7 @@ def conv_general_dilated_local(\nlhs_dilation: Optional[Sequence[int]] = None,\nrhs_dilation: Optional[Sequence[int]] = None,\ndimension_numbers: Optional[convolution.ConvGeneralDilatedDimensionNumbers] = None,\n- precision: Optional[lax.PrecisionLike] = None\n+ precision: lax.PrecisionLike = None\n) -> jnp.ndarray:\n\"\"\"General n-dimensional unshared convolution operator with optional dilation.\n@@ -195,9 +195,12 @@ def conv_general_dilated_local(\nIf `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`\n(for a 2D convolution).\n\"\"\"\n- lhs_precision = (precision[0]\n- if (isinstance(precision, tuple) and len(precision) == 2)\n- else precision)\n+ c_precision = lax.canonicalize_precision(precision)\n+ lhs_precision = type_cast(\n+ Optional[lax.PrecisionType],\n+ (c_precision[0]\n+ if (isinstance(c_precision, tuple) and len(c_precision) == 2)\n+ else c_precision))\npatches = conv_general_dilated_patches(\nlhs=lhs,\n" } ]
Python
Apache License 2.0
google/jax
Use real Precision type for lax.PrecisionType PiperOrigin-RevId: 432413742
260,531
04.03.2022 20:22:59
-28,800
ee2377b47d259a59cf7b530852a9414d993dbf33
[Doc] Add jaxlib build instructions for TPU Currently the documentation only contains build instructions for CUDA support, but does not mention TPU. This pull request add build instructions for TPU alongside CUDA.
[ { "change_type": "MODIFY", "old_path": "docs/developer.md", "new_path": "docs/developer.md", "diff": "@@ -53,26 +53,22 @@ You can install the necessary Python dependencies using `pip`:\npip install numpy six wheel\n```\n-To build `jaxlib` with CUDA support, you can run:\n+To build `jaxlib` without CUDA GPU or TPU support (CPU only), you can run:\n```\n-python build/build.py --enable_cuda\n+python build/build.py\npip install dist/*.whl # installs jaxlib (includes XLA)\n```\n+To build `jaxlib` with CUDA support, use `python build/build.py --enable_cuda`;\n+to build with TPU support, use `python build/build.py --enable_tpu`.\n+\nSee `python build/build.py --help` for configuration options, including ways to\nspecify the paths to CUDA and CUDNN, which you must have installed. Here\n`python` should be the name of your Python 3 interpreter; on some systems, you\nmay need to use `python3` instead. By default, the wheel is written to the\n`dist/` subdirectory of the current directory.\n-To build `jaxlib` without CUDA GPU support (CPU only), drop the `--enable_cuda`:\n-\n-```\n-python build/build.py\n-pip install dist/*.whl # installs jaxlib (includes XLA)\n-```\n-\n### Additional Notes for Building `jaxlib` from source on Windows\nOn Windows, follow [Install Visual Studio](https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2019)\n" } ]
Python
Apache License 2.0
google/jax
[Doc] Add jaxlib build instructions for TPU Currently the documentation only contains build instructions for CUDA support, but does not mention TPU. This pull request add build instructions for TPU alongside CUDA.
260,578
04.03.2022 11:59:16
28,800
403eae0efee064e023881f69e38818d8830585fc
format nicely
[ { "change_type": "MODIFY", "old_path": "jax/experimental/global_device_array.py", "new_path": "jax/experimental/global_device_array.py", "diff": "@@ -411,12 +411,15 @@ class GlobalDeviceArray:\n>>> from jax.experimental.maps import Mesh\n>>> import numpy as np\n+ ...\n>>> global_input_shape = (8, 8)\n>>> mesh_axes = ['x', 'y']\n>>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(2, 4), ('x', 'y'))\n>>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ ...\n>>> def cb(index):\n... return global_input_data[index]\n+ ...\n>>> gda = GlobalDeviceArray.from_callback(global_input_shape, global_mesh, mesh_axes, cb)\n>>> gda.local_data(0).shape\n(4, 2)\n@@ -454,13 +457,16 @@ class GlobalDeviceArray:\n>>> from jax.experimental.maps import Mesh\n>>> import numpy as np\n+ ...\n>>> global_input_shape = (8, 2)\n>>> mesh_axes = ['x']\n>>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n>>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ ...\n>>> def batched_cb(indices):\n... assert len(indices) == len(global_mesh.local_devices)\n... return [global_input_data[index] for index in indices]\n+ ...\n>>> gda = GlobalDeviceArray.from_batched_callback(global_input_shape, global_mesh, mesh_axes, batched_cb)\n>>> gda.local_data(0).shape\n(2, 2)\n@@ -497,10 +503,12 @@ class GlobalDeviceArray:\n>>> from jax.experimental.maps import Mesh\n>>> import numpy as np\n+ ...\n>>> global_input_shape = (8, 2)\n>>> mesh_axes = [('x', 'y')]\n>>> global_mesh = global_mesh = Mesh(np.array(jax.devices()).reshape(4, 2), ('x', 'y'))\n>>> global_input_data = np.arange(prod(global_input_shape)).reshape(global_input_shape)\n+ ...\n>>> def cb(cb_inp):\n... dbs = []\n... for inp in cb_inp:\n@@ -508,6 +516,7 @@ class GlobalDeviceArray:\n... array = global_input_data[index]\n... dbs.extend([jax.device_put(array, device) for device in devices])\n... return dbs\n+ ...\n>>> gda = GlobalDeviceArray.from_batched_callback_with_devices(\n... global_input_shape, global_mesh, mesh_axes, cb)\n>>> gda.local_data(0).shape\n" } ]
Python
Apache License 2.0
google/jax
format nicely
260,335
07.03.2022 12:44:50
28,800
24a7afdbf4655349950cd4a2575f3f8b6e960c14
improve batch_jaxpr caching from In I missed a related utilty function which needed memoization.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -448,7 +448,6 @@ def batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name,\nreturn _batch_jaxpr(closed_jaxpr, axis_size, tuple(in_batched), inst,\naxis_name, main_type)\n-@cache()\ndef _batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name,\nmain_type):\nassert (isinstance(instantiate, bool) or\n@@ -463,6 +462,12 @@ def _batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name,\ndef batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest, axis_name,\nmain_type):\n+ return _batch_jaxpr_axes(closed_jaxpr, axis_size, tuple(in_axes),\n+ tuple(out_axes_dest), axis_name, main_type)\n+\n+@cache()\n+def _batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes_dest, axis_name,\n+ main_type):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\nf, out_batched = _batch_jaxpr_inner(f, axis_size, out_axes_dest)\nf = _batch_jaxpr_outer(f, axis_name, axis_size, in_axes, main_type)\n" } ]
Python
Apache License 2.0
google/jax
improve batch_jaxpr caching from #9196 In #9196 I missed a related utilty function which needed memoization. Co-authored-by: Adam Paszke <apaszke@google.com>
260,308
09.03.2022 17:05:28
28,800
caf094d06be78fbe069eb627181cab91225ef472
Support gamma distribution with PRNGKeys other than threefry2x32.
[ { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -940,15 +940,14 @@ def _gamma_grad(sample, a):\ngrads = vmap(lax.random_gamma_grad)(alphas, samples)\nreturn grads.reshape(np.shape(a))\n-def _gamma_impl(key, a, use_vmap=False):\n+def _gamma_impl(raw_key, a, *, prng_impl, use_vmap=False):\na_shape = jnp.shape(a)\n# split key to match the shape of a\n- key_ndim = jnp.ndim(key) - 1\n- split_impl = prng.threefry_prng_impl.split\n- key = jnp.reshape(key, (-1, 2))\n- key = vmap(split_impl, in_axes=(0, None))(key, prod(a_shape[key_ndim:]))\n- keys = jnp.reshape(key, (-1, 2))\n- keys = prng.PRNGKeyArray(prng.threefry_prng_impl, keys)\n+ key_ndim = len(raw_key.shape) - len(prng_impl.key_shape)\n+ key = raw_key.reshape((-1,) + prng_impl.key_shape)\n+ key = vmap(prng_impl.split, in_axes=(0, None))(key, prod(a_shape[key_ndim:]))\n+ keys = key.reshape((-1,) + prng_impl.key_shape)\n+ keys = prng.PRNGKeyArray(prng_impl, keys)\nalphas = jnp.reshape(a, -1)\nif use_vmap:\nsamples = vmap(_gamma_one)(keys, alphas)\n@@ -957,18 +956,18 @@ def _gamma_impl(key, a, use_vmap=False):\nreturn jnp.reshape(samples, a_shape)\n-def _gamma_batching_rule(batched_args, batch_dims):\n+def _gamma_batching_rule(batched_args, batch_dims, *, prng_impl):\nk, a = batched_args\nbk, ba = batch_dims\nsize = next(t.shape[i] for t, i in zip(batched_args, batch_dims) if i is not None)\nk = batching.bdim_at_front(k, bk, size)\na = batching.bdim_at_front(a, ba, size)\n- return random_gamma_p.bind(k, a), 0\n+ return random_gamma_p.bind(k, a, prng_impl=prng_impl), 0\nrandom_gamma_p = core.Primitive('random_gamma')\nrandom_gamma_p.def_impl(_gamma_impl)\n-random_gamma_p.def_abstract_eval(lambda key, a: core.raise_to_shaped(a))\n-ad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a: tangent * _gamma_grad(ans, a))\n+random_gamma_p.def_abstract_eval(lambda key, a, **_: core.raise_to_shaped(a))\n+ad.defjvp2(random_gamma_p, None, lambda tangent, ans, key, a, **_: tangent * _gamma_grad(ans, a))\nxla.register_translation(random_gamma_p, xla.lower_fun(\npartial(_gamma_impl, use_vmap=True),\nmultiple_results=False, new_style=True))\n@@ -998,15 +997,6 @@ def gamma(key: KeyArray,\n``shape`` is not None, or else by ``a.shape``.\n\"\"\"\nkey, _ = _check_prng_key(key)\n- if key.impl is not prng.threefry_prng_impl:\n- raise NotImplementedError(\n- f'`gamma` is only implemented for the threefry2x32 RNG, not {key.impl}')\n- return gamma_threefry2x32(key.unsafe_raw_array(), a, shape, dtype)\n-\n-def gamma_threefry2x32(key: jnp.ndarray, # raw ndarray form of a 2x32 key\n- a: RealArray,\n- shape: Optional[Sequence[int]] = None,\n- dtype: DTypeLikeFloat = dtypes.float_) -> jnp.ndarray:\nif not dtypes.issubdtype(dtype, np.floating):\nraise ValueError(f\"dtype argument to `gamma` must be a float \"\nf\"dtype, got {dtype}\")\n@@ -1025,7 +1015,7 @@ def _gamma(key, a, shape, dtype):\na = lax.convert_element_type(a, dtype)\nif np.shape(a) != shape:\na = jnp.broadcast_to(a, shape)\n- return random_gamma_p.bind(key, a)\n+ return random_gamma_p.bind(key.unsafe_raw_array(), a, prng_impl=key.impl)\n@partial(jit, static_argnums=(2, 3, 4), inline=True)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -2480,7 +2480,7 @@ for dtype in (np.float32, np.float64):\ndefine(\n\"random_gamma\",\nf\"shape={jtu.format_shape_dtype_string(shape, dtype)}\",\n- jax.jit(jax._src.random.gamma_threefry2x32),\n+ jax.jit(jax._src.random.gamma),\n[np.array([42, 43], dtype=np.uint32),\nRandArg(shape, dtype)],\ndtype=dtype)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -699,12 +699,14 @@ class LaxRandomTest(jtu.JaxTestCase):\nself._CheckKolmogorovSmirnovCDF(samples, scipy.stats.expon().cdf)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_a={}_dtype={}\".format(a, np.dtype(dtype).name),\n- \"a\": a, \"dtype\": dtype}\n+ {\"testcase_name\": \"_a={}_dtype={}_prng={}\".format(a, np.dtype(dtype).name,\n+ prng_name),\n+ \"a\": a, \"dtype\": dtype, \"prng_impl\": prng_impl}\n+ for prng_name, prng_impl in PRNG_IMPLS\nfor a in [0.1, 1., 10.]\nfor dtype in jtu.dtypes.floating))\n- def testGamma(self, a, dtype):\n- key = self.seed_prng(0)\n+ def testGamma(self, prng_impl, a, dtype):\n+ key = prng.seed_with_impl(prng_impl, 0)\nrand = lambda key, a: random.gamma(key, a, (10000,), dtype)\ncrand = jax.jit(rand)\n@@ -720,10 +722,12 @@ class LaxRandomTest(jtu.JaxTestCase):\nassert x.shape == (3, 2)\n@parameterized.named_parameters(jtu.cases_from_list(\n- {\"testcase_name\": \"_a={}\".format(alpha), \"alpha\": alpha}\n+ {\"testcase_name\": \"_a={}_prng={}\".format(alpha, prng_name),\n+ \"alpha\": alpha, \"prng_impl\": prng_impl}\n+ for prng_name, prng_impl in PRNG_IMPLS\nfor alpha in [1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4]))\n- def testGammaGrad(self, alpha):\n- rng = self.seed_prng(0)\n+ def testGammaGrad(self, prng_impl, alpha):\n+ rng = prng.seed_with_impl(prng_impl, 0)\nalphas = np.full((100,), alpha)\nz = random.gamma(rng, alphas)\nactual_grad = jax.grad(lambda x: random.gamma(rng, x).sum())(alphas)\n@@ -735,8 +739,9 @@ class LaxRandomTest(jtu.JaxTestCase):\npdf = scipy.stats.gamma.pdf(z, alpha)\nexpected_grad = -cdf_dot / pdf\n+ rtol = 2e-2 if jtu.device_under_test() == \"tpu\" else 7e-4\nself.assertAllClose(actual_grad, expected_grad, check_dtypes=True,\n- rtol=2e-2 if jtu.device_under_test() == \"tpu\" else 7e-4)\n+ rtol=rtol)\ndef testGammaGradType(self):\n# Regression test for https://github.com/google/jax/issues/2130\n" } ]
Python
Apache License 2.0
google/jax
Support gamma distribution with PRNGKeys other than threefry2x32. PiperOrigin-RevId: 433614014
260,510
09.03.2022 12:20:28
28,800
2988901e6ccbd88dcac0720f36a77202162a350d
Refactor Jaxpr pretty-printing to use a `JaxprPpSettings` named tuple and thread it into `pp_eqn_rules` so the settings are used recursively
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2298,13 +2298,13 @@ def _convert_elt_type_fwd_rule(eqn):\nelse:\nreturn [None], eqn\n-def _convert_elt_type_pp_rule(eqn, context):\n+def _convert_elt_type_pp_rule(eqn, context, settings):\n# don't print new_dtype because the output binder shows it\nprinted_params = {}\nif eqn.params['weak_type']:\nprinted_params['weak_type'] = True\nreturn [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context),\n+ core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\npp.text(\" \") + core.pp_vars(eqn.invars, context)]\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -77,15 +77,16 @@ class Jaxpr:\nself.eqns = list(eqns)\ndef __str__(self):\n- return str(pp_jaxpr(self, JaxprPpContext(), custom_pp_eqn_rules=True))\n+ return str(pp_jaxpr(self, JaxprPpContext(), JaxprPpSettings()))\n__repr__ = __str__\ndef pretty_print(self, *, source_info=False, print_shapes=True,\ncustom_pp_eqn_rules=True, name_stack=False, **kw):\n- doc = pp_jaxpr(self, JaxprPpContext(), source_info=source_info,\n+ doc = pp_jaxpr(self, JaxprPpContext(),\n+ JaxprPpSettings(source_info=source_info,\nprint_shapes=print_shapes,\ncustom_pp_eqn_rules=custom_pp_eqn_rules,\n- name_stack=name_stack)\n+ name_stack=name_stack))\nreturn doc.format(**kw)\ndef _repr_pretty_(self, p, cycle):\n@@ -143,9 +144,11 @@ class ClosedJaxpr:\ndef __repr__(self): return repr(self.jaxpr)\ndef pretty_print(self, *, source_info=False, print_shapes=True,\n- name_stack=False, **kw):\n- return pp_jaxpr(self.jaxpr, JaxprPpContext(), source_info=source_info,\n- print_shapes=print_shapes, name_stack=name_stack).format(**kw)\n+ name_stack=False, custom_pp_eqn_rules=True, **kw):\n+ settings = JaxprPpSettings(source_info=source_info,\n+ print_shapes=print_shapes, name_stack=name_stack,\n+ custom_pp_eqn_rules=custom_pp_eqn_rules)\n+ return pp_jaxpr(self.jaxpr, JaxprPpContext(), settings).format(**kw)\ndef _repr_pretty_(self, p, cycle):\n@@ -164,8 +167,7 @@ class JaxprEqn(NamedTuple):\nsource_info: source_info_util.SourceInfo\ndef __repr__(self):\n- return str(pp_eqn(self, JaxprPpContext(), custom_pp_eqn_rules=False)\n- ).rstrip()\n+ return str(pp_eqn(self, JaxprPpContext(), JaxprPpSettings())).rstrip()\ndef new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\nif primitive.call_primitive:\n@@ -2107,24 +2109,28 @@ def check_jaxpr(jaxpr: Jaxpr):\n@functools.lru_cache(maxsize=None)\ndef ctx_factory():\nctx = JaxprPpContext()\n- try: pp_jaxpr(jaxpr, ctx) # side-effect on ctx, build variable names\n+ pp_settings = JaxprPpSettings()\n+ try: pp_jaxpr(jaxpr, ctx, pp_settings) # side-effect on ctx, build variable names\nexcept: pass\n- return ctx\n+ return ctx, pp_settings\ntry:\n_check_jaxpr(ctx_factory, jaxpr, [v.aval for v in jaxpr.invars])\nexcept JaxprTypeError as e:\n- ctx = ctx_factory()\n+ ctx, pp_settings = ctx_factory()\nif len(e.args) == 2:\nmsg, eqnidx = e.args\n- jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, eqnidx - 10, eqnidx + 10, ctx))\n+ jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, eqnidx - 10, eqnidx + 10, ctx,\n+ pp_settings))\nelse:\nmsg, = e.args\n- jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, 0, 20, ctx))\n+ jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, 0, 20, ctx, pp_settings))\nmsg = \"\\n\\n\".join([msg, \"while checking jaxpr:\", jaxpr_str])\nraise JaxprTypeError(msg) from None\n-def _check_jaxpr(ctx_factory: Callable[[], 'JaxprPpContext'], jaxpr: Jaxpr,\n+def _check_jaxpr(\n+ ctx_factory: Callable[[], Tuple['JaxprPpContext', 'JaxprPpSettings']],\n+ jaxpr: Jaxpr,\nin_avals: Sequence[AbstractValue]) -> None:\ndef read(v: Atom) -> AbstractValue:\n@@ -2132,17 +2138,17 @@ def _check_jaxpr(ctx_factory: Callable[[], 'JaxprPpContext'], jaxpr: Jaxpr,\nreturn raise_to_shaped(get_aval(v.val))\nelse:\nif v not in env:\n- ctx = ctx_factory()\n+ ctx, _ = ctx_factory()\nraise JaxprTypeError(f\"Variable '{pp_var(v, ctx)}' not defined\")\nreturn env[v]\ndef write(v: Var, a: AbstractValue) -> None:\nif v in env:\n- ctx = ctx_factory()\n+ ctx, _ = ctx_factory()\nraise JaxprTypeError(f\"Variable '{pp_var(v, ctx)}' already bound\")\nif not isinstance(v, DropVar):\nif not typecompat(v.aval, a):\n- ctx = ctx_factory()\n+ ctx, _ = ctx_factory()\nraise JaxprTypeError(\nf\"Variable '{pp_var(v, ctx)}' inconsistently typed as \"\nf\"{pp_aval(a, ctx)}, bound as {pp_aval(v.aval, ctx)}\")\n@@ -2172,10 +2178,10 @@ def _check_jaxpr(ctx_factory: Callable[[], 'JaxprPpContext'], jaxpr: Jaxpr,\nout_avals = check_eqn(prim, in_avals, eqn.params)\nmap(write, eqn.outvars, out_avals)\nexcept JaxprTypeError as e:\n- ctx = ctx_factory()\n+ ctx, settings = ctx_factory()\nmsg, = e.args\nsrc = source_info_util.summarize(eqn.source_info)\n- msg = \"\\n\\n\".join([msg, \"in equation:\", str(pp.nest(2, pp_eqn(eqn, ctx))),\n+ msg = \"\\n\\n\".join([msg, \"in equation:\", str(pp.nest(2, pp_eqn(eqn, ctx, settings))),\nf\"from source: {src}\"])\nraise JaxprTypeError(msg, eqn_idx) from None\n@@ -2251,6 +2257,13 @@ def check_map(ctx_factory, prim, in_avals, params):\n# ------------------- Jaxpr printed representation -------------------\n+\n+class JaxprPpSettings(NamedTuple):\n+ print_shapes: bool = True\n+ source_info: bool = False\n+ name_stack: bool = False\n+ custom_pp_eqn_rules: bool = True\n+\n# A JaxprPpContext allows us to globally uniquify variable names within nested\n# Jaxprs.\nclass JaxprPpContext:\n@@ -2288,53 +2301,48 @@ def pp_vars(vs: Sequence[Any], context: JaxprPpContext,\n[pp.text(pp_var(v, context)) for v in vs])\n))\n-def pp_kv_pair(k:str, v: Any, context: JaxprPpContext, name_stack: bool = False) -> pp.Doc:\n+def pp_kv_pair(k:str, v: Any, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\nif type(v) is tuple and all(isinstance(j, (Jaxpr, ClosedJaxpr)) for j in v):\n- pp_v = pp_jaxprs(v, context, name_stack=name_stack)\n+ pp_v = pp_jaxprs(v, context, settings)\nelif isinstance(v, Jaxpr):\n- pp_v = pp_jaxpr(v, context, name_stack=name_stack)\n+ pp_v = pp_jaxpr(v, context, settings)\nelif isinstance(v, ClosedJaxpr):\n- pp_v = pp_jaxpr(v.jaxpr, context, name_stack=name_stack)\n+ pp_v = pp_jaxpr(v.jaxpr, context, settings)\nelse:\npp_v = pp.text(str(v))\nreturn pp.text(f'{k}=') + pp_v\n-def pp_kv_pairs(kv_pairs, context: JaxprPpContext, name_stack: bool = False) -> pp.Doc:\n+def pp_kv_pairs(kv_pairs, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\nif not kv_pairs:\nreturn pp.nil()\nreturn pp.group(\npp.nest(2, pp.concat([\npp.text(\"[\"), pp.brk(\"\"),\n- pp.join(pp.brk(), [pp_kv_pair(k, v, context, name_stack=name_stack) for k, v in kv_pairs])\n+ pp.join(pp.brk(), [pp_kv_pair(k, v, context, settings) for k, v in kv_pairs])\n]))\n+ pp.brk(\"\") + pp.text(\"]\")\n)\n-def pp_eqn(eqn, context: JaxprPpContext, *, print_shapes=True,\n- source_info=False, custom_pp_eqn_rules=True, name_stack=False) -> pp.Doc:\n- lhs = pp_vars(eqn.outvars, context, print_shapes=print_shapes)\n+def pp_eqn(eqn, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\n+ lhs = pp_vars(eqn.outvars, context, print_shapes=settings.print_shapes)\nannotation = (source_info_util.summarize(eqn.source_info)\n- if source_info else None)\n+ if settings.source_info else None)\nrule = pp_eqn_rules.get(eqn.primitive)\n- name_stack_annotation = f'[{eqn.source_info.name_stack}]' if name_stack else None\n- if rule and custom_pp_eqn_rules:\n- rhs = rule(eqn, context)\n+ name_stack_annotation = f'[{eqn.source_info.name_stack}]' if settings.name_stack else None\n+ if rule and settings.custom_pp_eqn_rules:\n+ rhs = rule(eqn, context, settings)\nelse:\nrhs = [pp.text(eqn.primitive.name, annotation=name_stack_annotation),\n- pp_kv_pairs(sorted(eqn.params.items()), context, name_stack=name_stack),\n+ pp_kv_pairs(sorted(eqn.params.items()), context, settings),\npp.text(\" \") + pp_vars(eqn.invars, context)]\nreturn pp.concat([lhs, pp.text(\" = \", annotation=annotation), *rhs])\n-CustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext], Sequence[pp.Doc]]\n+CustomPpEqnRule = Callable[[JaxprEqn, JaxprPpContext, JaxprPpSettings], Sequence[pp.Doc]]\npp_eqn_rules: Dict[Primitive, CustomPpEqnRule] = {}\n-def pp_eqns(eqns, context: JaxprPpContext, *, print_shapes=True,\n- source_info=False, custom_pp_eqn_rules=True, name_stack=False,\n- ) -> pp.Doc:\n+def pp_eqns(eqns, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\nreturn pp.join(\npp.brk(\"; \"),\n- [pp_eqn(e, context, print_shapes=print_shapes, source_info=source_info,\n- name_stack=name_stack,\n- custom_pp_eqn_rules=custom_pp_eqn_rules) for e in eqns])\n+ [pp_eqn(e, context, settings) for e in eqns])\ndef _compact_eqn_should_include(k: str, v: Any) -> bool:\nif k == 'branches': return False\n@@ -2349,10 +2357,10 @@ def str_eqn_compact(primitive_name: str, params: Dict) -> str:\nif _compact_eqn_should_include(k, v))\nreturn f\"{primitive_name}[{kvs}]\" if len(kvs) > 0 else primitive_name\n-def pp_jaxpr_skeleton(jaxpr, eqns_fn, context: JaxprPpContext, *,\n- print_shapes=True) -> pp.Doc:\n- constvars = pp_vars(jaxpr.constvars, context, print_shapes=print_shapes)\n- invars = pp_vars(jaxpr.invars, context, print_shapes=print_shapes)\n+def pp_jaxpr_skeleton(jaxpr, eqns_fn, context: JaxprPpContext,\n+ settings: JaxprPpSettings) -> pp.Doc:\n+ constvars = pp_vars(jaxpr.constvars, context, print_shapes=settings.print_shapes)\n+ invars = pp_vars(jaxpr.invars, context, print_shapes=settings.print_shapes)\neqns = eqns_fn()\noutvars = pp.concat([\npp.text(\"(\"), pp_vars(jaxpr.outvars, context, separator=\",\"),\n@@ -2366,26 +2374,21 @@ def pp_jaxpr_skeleton(jaxpr, eqns_fn, context: JaxprPpContext, *,\n])) + pp.text(\" }\"))\n-def pp_jaxpr(jaxpr, context: JaxprPpContext, *, print_shapes=True,\n- source_info=False, custom_pp_eqn_rules=True, name_stack=False) -> pp.Doc:\n- eqns_fn = lambda: pp_eqns(jaxpr.eqns, context, print_shapes=print_shapes,\n- source_info=source_info,\n- custom_pp_eqn_rules=custom_pp_eqn_rules,\n- name_stack=name_stack)\n- return pp_jaxpr_skeleton(jaxpr, eqns_fn, context, print_shapes=print_shapes)\n+def pp_jaxpr(jaxpr, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\n+ eqns_fn = lambda: pp_eqns(jaxpr.eqns, context, settings)\n+ return pp_jaxpr_skeleton(jaxpr, eqns_fn, context, settings)\n-def pp_jaxprs(jaxprs, context: JaxprPpContext, name_stack: bool = False) -> pp.Doc:\n+def pp_jaxprs(jaxprs, context: JaxprPpContext, settings: JaxprPpSettings) -> pp.Doc:\njaxprs = [j.jaxpr if isinstance(j, ClosedJaxpr) else j for j in jaxprs]\nreturn pp.group(pp.nest(2, pp.concat([\npp.text('('), pp.brk(\"\"),\n- pp.join(pp.brk(), map(lambda x: pp_jaxpr(x, context, name_stack=name_stack), jaxprs))]\n+ pp.join(pp.brk(), map(lambda x: pp_jaxpr(x, context, settings), jaxprs))]\n)) + pp.brk(\"\") + pp.text(')')\n)\ndef pp_jaxpr_eqn_range(jaxpr: Jaxpr, lo: int, hi: int, context: JaxprPpContext,\n- print_shapes=True, source_info: bool = False,\n- name_stack: bool = False) -> pp.Doc:\n+ settings: JaxprPpSettings) -> pp.Doc:\nlo = max(lo, 0)\nhi = max(lo, min(hi, len(jaxpr.eqns)))\neqns = jaxpr.eqns[lo:hi]\n@@ -2396,13 +2399,11 @@ def pp_jaxpr_eqn_range(jaxpr: Jaxpr, lo: int, hi: int, context: JaxprPpContext,\nelse:\nif lo != 0:\npps.append(pp.text('...'))\n- pps.extend(map((lambda e: pp_eqn(e, context, print_shapes=print_shapes,\n- source_info=source_info,\n- name_stack=name_stack)), eqns))\n+ pps.extend(map((lambda e: pp_eqn(e, context, settings)), eqns))\nif hi != len(jaxpr.eqns):\npps.append(pp.text('...'))\nreturn pp.join(pp.brk(\"; \"), pps)\n- return pp_jaxpr_skeleton(jaxpr, eqns_fn, context, print_shapes=print_shapes)\n+ return pp_jaxpr_skeleton(jaxpr, eqns_fn, context, settings)\n# TODO(mattjj,frostig): remove these stubs, which are a temporary hack for\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/djax.py", "new_path": "jax/experimental/djax.py", "diff": "@@ -200,7 +200,8 @@ def pp_eqn(eqn: core.JaxprEqn) -> pp.Doc:\nlhs = pp_vars(eqn.outvars)\npp_lhs = pp.text(f'{lhs} =')\npp_rhs = (pp.text(eqn.primitive.name) +\n- core.pp_kv_pairs(sorted(eqn.params.items()), core.JaxprPpContext())\n+ core.pp_kv_pairs(sorted(eqn.params.items()), core.JaxprPpContext(),\n+ core.JaxprPpSettings())\n+ pp.text(' ') + pp.text(' '.join(map(str, eqn.invars))))\nreturn pp_lhs + pp.text(' ') + pp_rhs\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1257,7 +1257,7 @@ class DynamicJaxprTracer(core.Tracer):\nf\"of {dbg.arg_info(invar_pos)}.\")\nelif progenitor_eqns:\nmsts = [\" operation \"\n- f\"{core.pp_eqn(eqn, core.JaxprPpContext(), print_shapes=True)}\\n\"\n+ f\"{core.pp_eqn(eqn, core.JaxprPpContext(), core.JaxprPpSettings(print_shapes=True))}\\n\"\nf\" from line {source_info_util.summarize(eqn.source_info)}\"\nfor eqn in progenitor_eqns[:5]] # show at most 5\norigin = (f\"While tracing the function {dbg.func_src_info} \"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -888,7 +888,8 @@ pe.partial_eval_jaxpr_custom_rules[xla_call_p] = \\\npe.dce_rules[xla_call_p] = pe.dce_jaxpr_call_rule\n-def _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext\n+def _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext,\n+ settings: core.JaxprPpSettings,\n) -> List[pp.Doc]:\nprinted_params = {k:v for k, v in eqn.params.items() if\nk == 'call_jaxpr' or k == 'name' or\n@@ -896,7 +897,7 @@ def _pp_xla_call(eqn: core.JaxprEqn, context: core.JaxprPpContext\nk == 'device' and v is not None or\nk == 'donated_invars' and any(v)}\nreturn [pp.text(eqn.primitive.name),\n- core.pp_kv_pairs(sorted(printed_params.items()), context),\n+ core.pp_kv_pairs(sorted(printed_params.items()), context, settings),\npp.text(\" \") + core.pp_vars(eqn.invars, context)]\ncore.pp_eqn_rules[xla_call_p] = _pp_xla_call\n" } ]
Python
Apache License 2.0
google/jax
Refactor Jaxpr pretty-printing to use a `JaxprPpSettings` named tuple and thread it into `pp_eqn_rules` so the settings are used recursively
260,424
10.03.2022 13:31:24
0
76e1021cadc036ace21f076cf52b59820eec25b4
Checkify: Fix empty enabled_errors case wrt user checks. What looked like a quick win (short-cut on empty enabled_error, don't trace) was actually a quick bug (user_checks throw error in eager).
[ { "change_type": "MODIFY", "old_path": "jax/experimental/checkify/checkify_impl.py", "new_path": "jax/experimental/checkify/checkify_impl.py", "diff": "@@ -750,11 +750,6 @@ def checkify(fun: Callable[..., Out],\nValueError: nan generated by primitive sin\n\"\"\"\n- if not errors:\n- def checked_fun_trivial(*args, **kwargs):\n- return init_error, fun(*args, **kwargs)\n- return checked_fun_trivial\n-\n@traceback_util.api_boundary\ndef checked_fun(*args, **kwargs):\nargs_flat, in_tree = tree_flatten((args, kwargs))\n" }, { "change_type": "MODIFY", "old_path": "tests/checkify_test.py", "new_path": "tests/checkify_test.py", "diff": "@@ -382,12 +382,11 @@ class CheckifyTransformTests(jtu.JaxTestCase):\nx = x/0 # DIV\nx = jnp.sin(x) # NAN\nx = x[500] # OOB\n- # TODO(lenamartens): this error should also be disabled.\n- # checkify.check(x < 0, \"must be negative!\") # ASSERT\n+ checkify.check(x < 0, \"must be negative!\") # ASSERT\nreturn x\nx = jnp.ones((2,))\n- err, _ = checkify.checkify(multi_errors, errors={})(x)\n+ err, _ = checkify.checkify(multi_errors, errors=set())(x)\nself.assertIsNone(err.get())\n@parameterized.named_parameters(\n@@ -400,10 +399,10 @@ class CheckifyTransformTests(jtu.JaxTestCase):\n@jtu.skip_on_devices(\"tpu\")\ndef test_enabled_errors(self, error_set, expected_error):\ndef multi_errors(x):\n+ checkify.check(jnp.all(x < 0), \"must be negative!\") # ASSERT\nx = x/0 # DIV\nx = jnp.sin(x) # NAN\nx = x[500] # OOB\n- checkify.check(x < 0, \"must be negative!\") # ASSERT\nreturn x\nx = jnp.ones((2,))\n" } ]
Python
Apache License 2.0
google/jax
Checkify: Fix empty enabled_errors case wrt user checks. What looked like a quick win (short-cut on empty enabled_error, don't trace) was actually a quick bug (user_checks throw error in eager).
260,392
09.03.2022 13:03:45
18,000
c5d4aba2a939ae1a2171a33f2e723490d9197b71
Fix fft dtype for norm='ortho'
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/fft.py", "new_path": "jax/_src/numpy/fft.py", "diff": "@@ -86,7 +86,8 @@ def _fft_core(func_name, fft_type, a, s, axes, norm):\ns += [max(0, 2 * (a.shape[axes[-1]] - 1))]\nelse:\ns = [a.shape[axis] for axis in axes]\n- transformed = lax.fft(a, fft_type, tuple(s)) * _fft_norm(jnp.array(s), func_name, norm)\n+ transformed = lax.fft(a, fft_type, tuple(s))\n+ transformed *= _fft_norm(jnp.array(s, dtype=transformed.real.dtype), func_name, norm)\nif orig_axes is not None:\ntransformed = jnp.moveaxis(transformed, axes, orig_axes)\n" }, { "change_type": "MODIFY", "old_path": "tests/fft_test.py", "new_path": "tests/fft_test.py", "diff": "@@ -138,6 +138,11 @@ class FftTest(jtu.JaxTestCase):\ntol = 0.15\njtu.check_grads(jnp_fn, args_maker(), order=2, atol=tol, rtol=tol)\n+ # check dtypes\n+ dtype = jnp_fn(rng(shape, dtype)).dtype\n+ expected_dtype = jnp.promote_types(float if inverse and real else complex, dtype)\n+ self.assertEqual(dtype, expected_dtype)\n+\ndef testIrfftTranspose(self):\n# regression test for https://github.com/google/jax/issues/6223\ndef build_matrix(linear_func, size):\n" } ]
Python
Apache License 2.0
google/jax
Fix fft dtype for norm='ortho'
260,335
11.03.2022 11:36:13
28,800
39c2f8b051bd80cfd6de2a7d965d1b3cb2920456
fixup from remove extraneous lines also add test
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/windowed_reductions.py", "new_path": "jax/_src/lax/windowed_reductions.py", "diff": "@@ -278,8 +278,6 @@ def _generic_reduce_window_batch_rule(\noperands, init_values = util.split_list(batched_args, [num_operands])\noperand_bdims, init_value_bdims = util.split_list(batch_dims, [num_operands])\n- operand, init = batched_args\n- bdim, init_bdim = batch_dims\nif any(init_bdim is not None for init_bdim in init_value_bdims):\nraise NotImplementedError(\"reduce_window batching is not implemented for \"\n\"initial values\")\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_vmap_test.py", "new_path": "tests/lax_vmap_test.py", "diff": "@@ -24,6 +24,7 @@ from absl.testing import parameterized\nimport numpy as np\nimport jax\n+import jax.numpy as jnp\nfrom jax import dtypes\nfrom jax import lax\n@@ -790,6 +791,37 @@ class LaxVmapTest(jtu.JaxTestCase):\n# TODO Collapse\n# TODO Scatter\n+ # TODO(b/183233858): variadic reduce-window is not implemented on XLA:GPU\n+ @jtu.skip_on_devices(\"gpu\")\n+ def test_variadic_reduce_window(self):\n+ # https://github.com/google/jax/discussions/9818 and\n+ # https://github.com/google/jax/issues/9837\n+ def normpool(x):\n+ norms = jnp.linalg.norm(x, axis=-1)\n+ idxs = jnp.arange(x.shape[0])\n+\n+ def g(a, b):\n+ an, ai = a\n+ bn, bi = b\n+ which = an >= bn\n+ return (jnp.where(which, an, bn), jnp.where(which, ai, bi))\n+\n+ _, idxs = lax.reduce_window((norms, idxs), (-np.inf, -1), g,\n+ window_dimensions=(2,), window_strides=(2,),\n+ padding=((0, 0),))\n+ return x[idxs]\n+\n+\n+ inpt = jnp.array([\n+ [1.0, 0.0, 1.0],\n+ [2.0, 2.0, 0.0],\n+ [3.0, 0.0, 1.0],\n+ [0.0, 1.0, 1.0],\n+ ])\n+ output = jax.vmap(normpool)(inpt[None, ...]) # doesn't crash\n+ expected = jnp.array([[[2.0, 2.0, 0.0], [3.0, 0.0, 1.0]]])\n+ self.assertAllClose(output, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
fixup from 5415306: remove extraneous lines also add test