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,411
24.02.2021 09:21:36
-3,600
4800fbb28596f360665aa6d253c01c126f312e15
[jax2tf] Updated documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "-# JAX to TensorFlow converter (jax2tf)\n+# JAX and TensorFlow interoperation (jax2tf/call_tf)\n-This package provides an experimental JAX converter that can take a function\n+This package provides experimental support for interoperation between JAX and TensorFlow.\n+The `jax2tf.convert` mechanism can wrap a function\nwritten in JAX, possibly including JAX transformations, and turn it into\na function that uses only TensorFlow operations. The converted function\n-can be used in a TensorFlow context and will behave as if it was written in TensorFlow.\n+can 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\nTensorFlow eager mode, or stage it out as a TensorFlow graph, even save it\nas a SavedModel for use with TensorFlow tools such as serving stack,\nor TensorFlow Hub.\n-The package also contains an experimental mechanism to call TensorFlow functions\n-from JAX. See [below](#calling-tensorflow-functions-from-jax).\n+The package also contains the `call_tf` mechanism to call TensorFlow functions\n+from JAX. These functions can be called in JAX's op-by-op execution mode,\n+in which case the callee is executed in eager mode, or in JAX's jit (staged) context,\n+in which case the callee is compiled to XLA and embedded in JAX's staged XLA.\n+\n+Both interoperation directions rely on the ability of\n+TensorFlow to use the XLA compiler (`tf.function(jit_compile=True)`). For the\n+`jax2tf` direction the jit compilation of the resulting TensorFlow code ensures\n+that the performance characteristics of the code match those of the JAX source.\n+For the `call_tf` direction, jit compilation is used to compile the TensorFlow\n+code to an XLA function that is called from JAX's XLA computation. In fact,\n+for this interoperation direction, only TensorFlow function that can be jit-compiled\n+are supported. In particular, this mechanism supports calling from JAX the TensorFlow\n+functions that are the result of `jax2tf.convert`, thus enabling a round-trip from\n+JAX to TensorFlow (e.g., a SavedModel), and back.\n+\n+We describe below some general concepts and capabilities, first for\n+`jax2tf.convert` and [later](#calling-tensorflow-functions-from-jax)\n+for `call_tf`.\n-We describe below some general concepts and capabilities.\nMore involved examples, including using jax2tf with\nFlax models and their use with TensorFlow Hub and Keras, are described in the\n[examples directory](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/README.md).\n@@ -129,7 +146,7 @@ for CUDA. One must be mindful to install a version of CUDA that is compatible\nwith both [jaxlib](https://github.com/google/jax/blob/master/README.md#pip-installation) and\n[TensorFlow](https://www.tensorflow.org/install/source#tested_build_configurations).\n-As of today, the tests are run using `tf_nightly==2.5.0-dev20210114`.\n+As of today, the tests are run using `tf_nightly==2.5.0-dev20210223`.\n## Caveats\n@@ -235,7 +252,7 @@ before conversion. (This is a hypothesis, we have not verified it extensively.)\n# Calling TensorFlow functions from JAX\n-The experimental function ```call_tf``` allows JAX to call\n+The function ```call_tf``` allows JAX to call\nTensorFlow functions. These functions can be called anywhere in a JAX\ncomputation, including in staging contexts ``jax.jit``, ``jax.pmap``, ``jax.xmap``,\nor inside JAX's control-flow primitives. In non-staging contexts,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Updated documentation
260,299
24.02.2021 09:56:01
0
661914ecfd597afeb9de324a673d1c8edc847a91
Add some more detail to the sharded_jit docstring
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/sharded_jit.py", "new_path": "jax/interpreters/sharded_jit.py", "diff": "@@ -290,19 +290,24 @@ def sharded_jit(fun: Callable, in_parts, out_parts, num_partitions: int = None,\nArgs:\nfun: Function to be jitted.\n- in_parts: The input partitions, i.e. how each argument to ``fun`` should be\n+ in_parts: Specifications for how each argument to ``fun`` should be\npartitioned or replicated. This should be a PartitionSpec indicating into\n- how many partitions each dimension should be sharded, None indicating\n+ how many partitions each dimension should be sharded, ``None`` indicating\nreplication, or (nested) standard Python containers thereof. For example,\n``in_parts=PartitionSpec(2,1)`` means all arguments should be partitioned\nover two devices across the first dimension;\n``in_parts=(PartitionSpec(2,2), PartitionSpec(4,1), None)`` means the\n- first argument should be partitioned over four devices by splitting the\n- first two dimensions in half, the second argument should be partitioned\n- over the four devices across the first dimension, and the third argument\n- is replicated across the four devices. All PartitionSpecs in a given\n- ``sharded_jit`` call must correspond to the same total number of\n- partitions, i.e. the product of all PartitionSpecs must be equal.\n+ first argument should be partitioned over four devices by splitting both\n+ of its dimensions in half, the second argument should be partitioned over\n+ the four devices across the first dimension, and the third argument is\n+ replicated across the four devices.\n+\n+ All PartitionSpecs in a given ``sharded_jit`` call must correspond to the\n+ same total number of partitions, i.e. the product of all PartitionSpecs\n+ must be equal, and the number of dimensions in the PartitionSpec\n+ corresponding to an array ``a`` should equal ``a.ndim``. Arguments marked\n+ as static using ``static_argnums`` (see below) do not require a\n+ PartitionSpec.\nout_parts: The output partitions, i.e. how each output of ``fun`` should be\npartitioned or replicated. This follows the same convention as\n``in_parts``.\n@@ -329,9 +334,11 @@ def sharded_jit(fun: Callable, in_parts, out_parts, num_partitions: int = None,\nfunction with different values for these constants will trigger\nrecompilation. If the jitted function is called with fewer positional\narguments than indicated by ``static_argnums`` then an error is raised.\n- Each of the static arguments will be broadcasted to all devices.\n- Arguments that are not arrays or containers thereof must be marked as\n- static. Defaults to ().\n+ Each of the static arguments will be broadcasted to all devices, and\n+ cannot be partitioned - these arguments will be removed from the *args\n+ list before matching each remaining argument with its corresponding\n+ PartitionSpec. Arguments that are not arrays or containers thereof must\n+ be marked as static. Defaults to ``()``.\nReturns:\nA version of ``fun`` that will be distributed across multiple devices.\n" } ]
Python
Apache License 2.0
google/jax
Add some more detail to the sharded_jit docstring
260,411
24.02.2021 18:26:38
-3,600
192647898140bbda474958ba3b5600a371a65182
[jax2tf] Fine-tuning the documentation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "# JAX and TensorFlow interoperation (jax2tf/call_tf)\nThis package provides experimental support for interoperation between JAX and TensorFlow.\n+There are two interoperation directions:\n+(a) `jax2tf.convert`: using JAX functions in a TensorFlow context, e.g.,\n+for eager or graph execution, or for saving as a SavedModel,\n+and (b) `call_tf`: using TensorFlow\n+functions in a JAX context, e.g., to use a TensorFlow library or a SavedModel.\n+\nThe `jax2tf.convert` mechanism can wrap a function\nwritten 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\nTensorFlow eager mode, or stage it out as a TensorFlow graph, even save it\n-as a SavedModel for use with TensorFlow tools such as serving stack,\n+as a SavedModel for archival, or for use with TensorFlow tools such as serving stack,\nor TensorFlow Hub.\n-The package also contains the `call_tf` mechanism to call TensorFlow functions\n+This package also contains the `call_tf` mechanism to call TensorFlow functions\nfrom JAX. These functions can be called in JAX's op-by-op execution mode,\nin which case the callee is executed in eager mode, or in JAX's jit (staged) context,\nin which case the callee is compiled to XLA and embedded in JAX's staged XLA.\nBoth interoperation directions rely on the ability of\nTensorFlow to use the XLA compiler (`tf.function(jit_compile=True)`). For the\n-`jax2tf` direction the jit compilation of the resulting TensorFlow code ensures\n+`jax2tf.convert` direction the JIT compilation of the resulting TensorFlow code ensures\nthat the performance characteristics of the code match those of the JAX source.\n-For the `call_tf` direction, jit compilation is used to compile the TensorFlow\n-code to an XLA function that is called from JAX's XLA computation. In fact,\n-for this interoperation direction, only TensorFlow function that can be jit-compiled\n-are supported. In particular, this mechanism supports calling from JAX the TensorFlow\n-functions that are the result of `jax2tf.convert`, thus enabling a round-trip from\n-JAX to TensorFlow (e.g., a SavedModel), and back.\n+For the `call_tf` direction, JIT compilation is an essential part of the implementation\n+mechanism. Only TensorFlow functions that can be JIT-compiled can be called from\n+JAX. Since the TensorFlow functions that are produced by `jax2tf.convert` can\n+be JIT-compiled by design, we can round-trip from JAX to TensorFlow\n+(e.g., a SavedModel) and back.\nWe describe below some general concepts and capabilities, first for\n`jax2tf.convert` and [later](#calling-tensorflow-functions-from-jax)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fine-tuning the documentation
260,719
06.02.2021 23:56:07
-19,080
c223ef9d07d602152d0d69601edd32869f632f73
add support for setxor1d
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -317,6 +317,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nselect\nset_printoptions\nsetdiff1d\n+ setxor1d\nshape\nsign\nsignbit\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1525,6 +1525,30 @@ def union1d(ar1, ar2):\nreturn unique(conc)\n+@_wraps(np.setxor1d, lax_description=\"\"\"\n+In the JAX version, the input arrays are explicilty flattened regardless\n+of assume_unique value.\n+\"\"\")\n+def setxor1d(ar1, ar2, assume_unique=False):\n+ ar1 = core.concrete_or_error(asarray, ar1, \"The error arose in setxor1d()\")\n+ ar2 = core.concrete_or_error(asarray, ar2, \"The error arose in setxor1d()\")\n+\n+ ar1 = ravel(ar1)\n+ ar2 = ravel(ar2)\n+\n+ if not assume_unique:\n+ ar1 = unique(ar1)\n+ ar2 = unique(ar2)\n+\n+ aux = concatenate((ar1, ar2))\n+ if aux.size == 0:\n+ return aux\n+\n+ aux = sort(aux)\n+ flag = concatenate((array([True]), aux[1:] != aux[:-1], array([True])))\n+ return aux[flag[1:] & flag[:-1]]\n+\n+\n@partial(jit, static_argnums=2)\ndef _intersect1d_sorted_mask(ar1, ar2, return_indices=False):\n\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/__init__.py", "new_path": "jax/numpy/__init__.py", "diff": "@@ -55,7 +55,7 @@ from jax._src.numpy.lax_numpy import (\nprod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, ravel_multi_index, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\n- save, savez, searchsorted, select, set_printoptions, setdiff1d, shape, sign, signbit,\n+ save, savez, searchsorted, select, set_printoptions, setdiff1d, setxor1d, shape, sign, signbit,\nsignedinteger, sin, sinc, single, sinh, size, sometrue, sort, sort_complex, split, sqrt,\nsquare, squeeze, stack, std, subtract, sum, swapaxes, take, take_along_axis,\ntan, tanh, tensordot, tile, trace, trapz, transpose, tri, tril, tril_indices, tril_indices_from,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1179,6 +1179,30 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nreturn np.union1d(arg1, arg2).astype(dtype)\nself._CheckAgainstNumpy(np_fun, jnp.union1d, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}_assume_unique={}\".format(\n+ jtu.format_shape_dtype_string(shape1, dtype1),\n+ jtu.format_shape_dtype_string(shape2, dtype2),\n+ assume_unique),\n+ \"shape1\": shape1, \"dtype1\": dtype1, \"shape2\": shape2, \"dtype2\": dtype2,\n+ \"assume_unique\": assume_unique}\n+ for dtype1 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for dtype2 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for shape1 in all_shapes\n+ for shape2 in all_shapes\n+ for assume_unique in [False, True]))\n+ def testSetxor1d(self, shape1, dtype1, shape2, dtype2, assume_unique):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape1, dtype1), rng(shape2, dtype2)]\n+ jnp_fun = lambda ar1, ar2: jnp.setxor1d(ar1, ar2, assume_unique=assume_unique)\n+ def np_fun(ar1, ar2):\n+ if assume_unique:\n+ # pre-flatten the arrays to match with jax implementation\n+ ar1 = np.ravel(ar1)\n+ ar2 = np.ravel(ar2)\n+ return np.setxor1d(ar1, ar2, assume_unique)\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}_assume_unique={}_return_indices={}\".format(\njtu.format_shape_dtype_string(shape1, dtype1),\n" } ]
Python
Apache License 2.0
google/jax
add support for setxor1d
260,335
24.02.2021 20:25:24
28,800
9789677e85f43f8fa0f1c96e0b91276017af3dcf
reviewer comments, delint
[ { "change_type": "MODIFY", "old_path": "docs/autodidax.ipynb", "new_path": "docs/autodidax.ipynb", "diff": "\"where we apply primitive functions to numerical inputs to produce numerical\\n\",\n\"outputs, we want to override primitive application and let different values\\n\",\n\"flow through our program. For example, we might want to replace the\\n\",\n- \"application of every primitive with type `a -> b` with an application of its\\n\",\n- \"JVP rule with type `(a, T a) -> (b, T b)`, and let primal-tangent pairs flow\\n\",\n- \"through our program. Moreover, we want to apply a composition of multiple\\n\",\n- \"transformations, leading to stacks of interpreters.\"\n+ \"application of every primitive with an application of [its JVP\\n\",\n+ \"rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\\n\",\n+ \"and let primal-tangent pairs flow through our program. Moreover, we want to\\n\",\n+ \"apply a composition of multiple transformations, leading to stacks of\\n\",\n+ \"interpreters.\"\n]\n},\n{\n\"source\": [\n\"When we're about to apply a transformed function, we'll push another\\n\",\n\"interpreter onto the stack using `new_main`. Then, as we apply primitives in\\n\",\n- \"the function, we can think of the `bind` first being interprted by the trace\\n\",\n+ \"the function, we can think of the `bind` first being interpreted by the trace\\n\",\n\"at the top of the stack (i.e. with the highest level). If that first\\n\",\n\"interpreter itself binds other primitives in its interpretation rule for the\\n\",\n\"primitive, like how the JVP rule of `sin_p` might bind `cos_p` and `mul_p`,\\n\",\n\"\\n\",\n\" @staticmethod\\n\",\n\" def _nonzero(tracer):\\n\",\n- \" return nonzero(tracer.aval.val)\\n\",\n+ \" return bool(tracer.aval.val)\\n\",\n\"\\n\",\n\"def get_aval(x):\\n\",\n\" if isinstance(x, Tracer):\\n\",\n\"source\": [\n\"### Forward-mode autodiff with `jvp`\\n\",\n\"\\n\",\n- \"First, a couple helper functions:\"\n+ \"First, a couple of helper functions:\"\n]\n},\n{\n\"\\n\",\n\"def reduce_sum_jvp(primals, tangents, *, axis):\\n\",\n\" (x,), (x_dot,) = primals, tangents\\n\",\n- \" return reduce_sum(x_dot, axis), reduce_sum(x_dot, axis)\\n\",\n+ \" return reduce_sum(x, axis), reduce_sum(x_dot, axis)\\n\",\n\"jvp_rules[reduce_sum_p] = reduce_sum_jvp\\n\",\n\"\\n\",\n\"def greater_jvp(primals, tangents):\\n\",\n\"cell_type\": \"markdown\",\n\"metadata\": {},\n\"source\": [\n- \"Here we've implemented the optional `Tracer.full_lower` method, which lets\\n\",\n+ \"Here we've implemented the optional `Tracer.full_lower` method, which lets us\\n\",\n\"peel off a batching tracer if it's not needed because it doesn't represent a\\n\",\n\"batched value.\\n\",\n\"\\n\",\n\"carry a little bit of extra context, but for both `jit` and `vjp` we need\\n\",\n\"much richer context: we need to represent _programs_. That is, we need jaxprs!\\n\",\n\"\\n\",\n- \"We need a program representation for `jit` because the purpose of `jit` is to\\n\",\n- \"stage computation out of Python. For any computation we want to stage out,\\n\",\n- \"we need to be able to represent it as data, and build it up as we trace a\\n\",\n- \"Python function. Similarly, `vjp` needs a way to represent the computation for\\n\",\n- \"the backward pass of reverse-mode autodiff. We use the same jaxpr program\\n\",\n- \"representation for both needs.\\n\",\n+ \"Jaxprs are JAX's internal intermediate representation of programs. Jaxprs are\\n\",\n+ \"an explicitly typed, functional, first-order language. We need a program\\n\",\n+ \"representation for `jit` because the purpose of `jit` is to stage computation\\n\",\n+ \"out of Python. For any computation we want to stage out, we need to be able to\\n\",\n+ \"represent it as data, and build it up as we trace a Python function.\\n\",\n+ \"Similarly, `vjp` needs a way to represent the computation for the backward\\n\",\n+ \"pass of reverse-mode autodiff. We use the same jaxpr program representation\\n\",\n+ \"for both needs.\\n\",\n\"\\n\",\n\"(Building a program representation is the most\\n\",\n- \"[free](https://en.wikipedia.org/wiki/Free_object) kind of trace-\\n\",\n- \"transformation, and so except for issues around handling native Python control\\n\",\n- \"flow, any transformation could be implemented by first tracing to a jaxpr\\n\",\n- \"and then interpreting the jaxpr.)\\n\",\n+ \"[free](https://en.wikipedia.org/wiki/Free_object) kind of\\n\",\n+ \"trace- transformation, and so except for issues around handling native Python\\n\",\n+ \"control flow, any transformation could be implemented by first tracing to a\\n\",\n+ \"jaxpr and then interpreting the jaxpr.)\\n\",\n\"\\n\",\n\"The jaxpr term syntax is roughly:\\n\",\n\"\\n\",\n\" primitive: Primitive\\n\",\n\" inputs: List[Atom]\\n\",\n\" params: Dict[str, Any]\\n\",\n- \" out_binder: List[Var]\\n\",\n+ \" out_binder: Var\\n\",\n\"\\n\",\n\"class Jaxpr(NamedTuple):\\n\",\n\" in_binders: List[Var]\\n\",\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.md", "new_path": "docs/autodidax.md", "diff": "@@ -6,7 +6,7 @@ jupytext:\nextension: .md\nformat_name: myst\nformat_version: 0.13\n- jupytext_version: 1.10.0\n+ jupytext_version: 1.10.2\nkernelspec:\ndisplay_name: Python 3\nname: python3\n@@ -40,10 +40,11 @@ atomic units of processing rather than compositions.\nwhere we apply primitive functions to numerical inputs to produce numerical\noutputs, we want to override primitive application and let different values\nflow through our program. For example, we might want to replace the\n-application of every primitive with type `a -> b` with an application of its\n-JVP rule with type `(a, T a) -> (b, T b)`, and let primal-tangent pairs flow\n-through our program. Moreover, we want to apply a composition of multiple\n-transformations, leading to stacks of interpreters.\n+application of every primitive with an application of [its JVP\n+rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\n+and let primal-tangent pairs flow through our program. Moreover, we want to\n+apply a composition of multiple transformations, leading to stacks of\n+interpreters.\n+++\n@@ -124,7 +125,7 @@ def new_main(trace_type: Type['Trace'], global_data=None):\nWhen we're about to apply a transformed function, we'll push another\ninterpreter onto the stack using `new_main`. Then, as we apply primitives in\n-the function, we can think of the `bind` first being interprted by the trace\n+the function, we can think of the `bind` first being interpreted by the trace\nat the top of the stack (i.e. with the highest level). If that first\ninterpreter itself binds other primitives in its interpretation rule for the\nprimitive, like how the JVP rule of `sin_p` might bind `cos_p` and `mul_p`,\n@@ -247,7 +248,7 @@ class ConcreteArray(ShapedArray):\n@staticmethod\ndef _nonzero(tracer):\n- return nonzero(tracer.aval.val)\n+ return bool(tracer.aval.val)\ndef get_aval(x):\nif isinstance(x, Tracer):\n@@ -370,7 +371,7 @@ that now we can add some real transformations.\n### Forward-mode autodiff with `jvp`\n-First, a couple helper functions:\n+First, a couple of helper functions:\n```{code-cell}\ndef zeros_like(val):\n@@ -445,7 +446,7 @@ jvp_rules[neg_p] = neg_jvp\ndef reduce_sum_jvp(primals, tangents, *, axis):\n(x,), (x_dot,) = primals, tangents\n- return reduce_sum(x_dot, axis), reduce_sum(x_dot, axis)\n+ return reduce_sum(x, axis), reduce_sum(x_dot, axis)\njvp_rules[reduce_sum_p] = reduce_sum_jvp\ndef greater_jvp(primals, tangents):\n@@ -575,7 +576,7 @@ class BatchTrace(Trace):\nvmap_rules = {}\n```\n-Here we've implemented the optional `Tracer.full_lower` method, which lets\n+Here we've implemented the optional `Tracer.full_lower` method, which lets us\npeel off a batching tracer if it's not needed because it doesn't represent a\nbatched value.\n@@ -678,18 +679,20 @@ wrapper around `vjp`.) For `jvp` and `vmap` we only needed each `Tracer` to\ncarry a little bit of extra context, but for both `jit` and `vjp` we need\nmuch richer context: we need to represent _programs_. That is, we need jaxprs!\n-We need a program representation for `jit` because the purpose of `jit` is to\n-stage computation out of Python. For any computation we want to stage out,\n-we need to be able to represent it as data, and build it up as we trace a\n-Python function. Similarly, `vjp` needs a way to represent the computation for\n-the backward pass of reverse-mode autodiff. We use the same jaxpr program\n-representation for both needs.\n+Jaxprs are JAX's internal intermediate representation of programs. Jaxprs are\n+an explicitly typed, functional, first-order language. We need a program\n+representation for `jit` because the purpose of `jit` is to stage computation\n+out of Python. For any computation we want to stage out, we need to be able to\n+represent it as data, and build it up as we trace a Python function.\n+Similarly, `vjp` needs a way to represent the computation for the backward\n+pass of reverse-mode autodiff. We use the same jaxpr program representation\n+for both needs.\n(Building a program representation is the most\n-[free](https://en.wikipedia.org/wiki/Free_object) kind of trace-\n-transformation, and so except for issues around handling native Python control\n-flow, any transformation could be implemented by first tracing to a jaxpr\n-and then interpreting the jaxpr.)\n+[free](https://en.wikipedia.org/wiki/Free_object) kind of\n+trace- transformation, and so except for issues around handling native Python\n+control flow, any transformation could be implemented by first tracing to a\n+jaxpr and then interpreting the jaxpr.)\nThe jaxpr term syntax is roughly:\n@@ -742,7 +745,7 @@ class JaxprEqn(NamedTuple):\nprimitive: Primitive\ninputs: List[Atom]\nparams: Dict[str, Any]\n- out_binder: List[Var]\n+ out_binder: Var\nclass Jaxpr(NamedTuple):\nin_binders: List[Var]\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.py", "new_path": "docs/autodidax.py", "diff": "# extension: .py\n# format_name: light\n# format_version: '1.5'\n-# jupytext_version: 1.10.2\n+# jupytext_version: 1.10.0\n# kernelspec:\n# display_name: Python 3\n# name: python3\n# where we apply primitive functions to numerical inputs to produce numerical\n# outputs, we want to override primitive application and let different values\n# flow through our program. For example, we might want to replace the\n-# application of every primitive with type `a -> b` with an application of its\n-# JVP rule with type `(a, T a) -> (b, T b)`, and let primal-tangent pairs flow\n-# through our program. Moreover, we want to apply a composition of multiple\n-# transformations, leading to stacks of interpreters.\n+# application of every primitive with an application of [its JVP\n+# rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\n+# and let primal-tangent pairs flow through our program. Moreover, we want to\n+# apply a composition of multiple transformations, leading to stacks of\n+# interpreters.\n# ### JAX core machinery\n#\n@@ -125,7 +126,7 @@ def new_main(trace_type: Type['Trace'], global_data=None):\n# When we're about to apply a transformed function, we'll push another\n# interpreter onto the stack using `new_main`. Then, as we apply primitives in\n-# the function, we can think of the `bind` first being interprted by the trace\n+# the function, we can think of the `bind` first being interpreted by the trace\n# at the top of the stack (i.e. with the highest level). If that first\n# interpreter itself binds other primitives in its interpretation rule for the\n# primitive, like how the JVP rule of `sin_p` might bind `cos_p` and `mul_p`,\n@@ -375,7 +376,7 @@ print(f(3.0))\n# ### Forward-mode autodiff with `jvp`\n#\n-# First, a couple helper functions:\n+# First, a couple of helper functions:\n# +\ndef zeros_like(val):\n@@ -586,7 +587,7 @@ class BatchTrace(Trace):\nvmap_rules = {}\n# -\n-# Here we've implemented the optional `Tracer.full_lower` method, which lets\n+# Here we've implemented the optional `Tracer.full_lower` method, which lets us\n# peel off a batching tracer if it's not needed because it doesn't represent a\n# batched value.\n#\n@@ -688,18 +689,20 @@ jacfwd(f, np.arange(3.))\n# carry a little bit of extra context, but for both `jit` and `vjp` we need\n# much richer context: we need to represent _programs_. That is, we need jaxprs!\n#\n-# We need a program representation for `jit` because the purpose of `jit` is to\n-# stage computation out of Python. For any computation we want to stage out,\n-# we need to be able to represent it as data, and build it up as we trace a\n-# Python function. Similarly, `vjp` needs a way to represent the computation for\n-# the backward pass of reverse-mode autodiff. We use the same jaxpr program\n-# representation for both needs.\n+# Jaxprs are JAX's internal intermediate representation of programs. Jaxprs are\n+# an explicitly typed, functional, first-order language. We need a program\n+# representation for `jit` because the purpose of `jit` is to stage computation\n+# out of Python. For any computation we want to stage out, we need to be able to\n+# represent it as data, and build it up as we trace a Python function.\n+# Similarly, `vjp` needs a way to represent the computation for the backward\n+# pass of reverse-mode autodiff. We use the same jaxpr program representation\n+# for both needs.\n#\n# (Building a program representation is the most\n-# [free](https://en.wikipedia.org/wiki/Free_object) kind of trace-\n-# transformation, and so except for issues around handling native Python control\n-# flow, any transformation could be implemented by first tracing to a jaxpr\n-# and then interpreting the jaxpr.)\n+# [free](https://en.wikipedia.org/wiki/Free_object) kind of\n+# trace- transformation, and so except for issues around handling native Python\n+# control flow, any transformation could be implemented by first tracing to a\n+# jaxpr and then interpreting the jaxpr.)\n#\n# The jaxpr term syntax is roughly:\n#\n" } ]
Python
Apache License 2.0
google/jax
reviewer comments, delint
260,411
01.03.2021 21:56:13
-3,600
b43cd47b33315a72cfc5e7797d4f505ca2749b5d
Update jax/experimental/jax2tf/README.md
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "This package provides experimental support for interoperation between JAX and TensorFlow.\nThere are two interoperation directions:\n-(a) `jax2tf.convert`: using JAX functions in a TensorFlow context, e.g.,\n-for eager or graph execution, or for saving as a SavedModel,\n-and (b) `call_tf`: using TensorFlow\n-functions in a JAX context, e.g., to use a TensorFlow library or a SavedModel.\n+\n+- `jax2tf.convert`: using JAX functions in a TensorFlow context, e.g.,\n+for eager or graph execution, or for saving as a SavedModel; and\n+- `call_tf`: using TensorFlow functions in a JAX context, e.g., to use a\n+TensorFlow library or a SavedModel.\nThe `jax2tf.convert` mechanism can wrap a function\nwritten in JAX, possibly including JAX transformations, and turn it into\n@@ -375,4 +376,3 @@ the ``a_inference_cos_tf_68__``HLO function that was compiled by TF from ``cos_t\n* Ensure that there is no array copy through the host when running in eager\nmode (JAX op-by-op).\n* Show how use ``call_tf`` to load a SavedModel into JAX.\n-\n" } ]
Python
Apache License 2.0
google/jax
Update jax/experimental/jax2tf/README.md Co-authored-by: 8bitmp3 <19637339+8bitmp3@users.noreply.github.com>
260,411
01.03.2021 23:27:11
-3,600
410f24af6bf625c2194e1fc42f72a12d7682bf3e
[jax2tf] Fix conversion for integer division for TF 1 It seems that TF 1 has a different broadcasting behavior than TF2. Change the conversion of integer division to use `tf.not_equal` instead of `!=`.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -956,8 +956,9 @@ tf_impl[lax.iota_p] = _iota\ndef _div(lhs, rhs):\nif lhs.dtype.is_integer:\nquotient = tf.math.floordiv(lhs, rhs)\n- select = tf.math.logical_and(tf.math.sign(lhs) != tf.math.sign(rhs),\n- tf.math.floormod(lhs, rhs) != 0)\n+ select = tf.math.logical_and(\n+ tf.not_equal(tf.math.sign(lhs), tf.math.sign(rhs)),\n+ tf.not_equal(tf.math.floormod(lhs, rhs), 0))\nreturn tf.where(select, quotient + 1, quotient)\nelse:\nreturn tf.math.truediv(lhs, rhs)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -65,9 +65,11 @@ from jax import lax\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\nfrom jax.config import config\n+from jax.experimental import jax2tf\nfrom jax.interpreters import xla\nimport numpy as np\n+import tensorflow as tf\nconfig.parse_flags_with_absl()\n@@ -242,6 +244,16 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ny = np.array([3, 4], dtype=y_dtype)\nself.ConvertAndCompare(f_jax, x, y)\n+ def test_integer_div(self):\n+ x = jnp.array([-4, -3, -1, 0, 1, 3, 6])\n+ y = np.int32(3)\n+ self.ConvertAndCompare(jnp.floor_divide, x, y)\n+ expected = jnp.floor_divide(x, y)\n+ # Try it with TF 1 as well (#5831)\n+ with tf.compat.v1.Session() as sess:\n+ tf1_res = sess.run(jax2tf.convert(jnp.floor_divide)(x, y))\n+ self.assertAllClose(expected, tf1_res)\n+\ndef test_disable_xla(self):\ndef fun(x):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix conversion for integer division for TF 1 Bug: #5831 It seems that TF 1 has a different broadcasting behavior than TF2. Change the conversion of integer division to use `tf.not_equal` instead of `!=`.
260,335
02.03.2021 22:54:49
28,800
4a0f6e35e6d609de23a9ebfdfb76b4ce654fb313
relax tolerance in jax2tf qr to avoid flakiness
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -949,7 +949,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n# compiling with TF is expected to have worse performance than the\n# custom calls made in JAX.\nreturn [\n- custom_numeric(tol=1e-5),\n+ custom_numeric(tol=1e-4),\nmissing_tf_kernel(\ndtypes=[dtypes.bfloat16],\ndevices=\"tpu\",\n" } ]
Python
Apache License 2.0
google/jax
relax tolerance in jax2tf qr to avoid flakiness PiperOrigin-RevId: 360596515
260,411
03.03.2021 12:37:01
-3,600
469e1f05e14964e5f0f0095e808cf2cd5c974fd7
[jax2tf] Updated the limitations Update the documentation to reflect the improvements in TF support for dtypes
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "new_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "diff": "# Primitives with limited JAX support\n-*Last generated on: 2021-02-02* (YYYY-MM-DD)\n+*Last generated on: 2021-03-03* (YYYY-MM-DD)\n## Supported data types for primitives\n@@ -191,8 +191,7 @@ and search for \"limitation\".\n|eig|only supported on CPU in JAX|all|tpu, gpu|\n|eig|unimplemented|bfloat16, float16|cpu|\n|eigh|complex eigh not supported |complex|tpu|\n-|eigh|unimplemented|bfloat16, float16|cpu, gpu, tpu|\n-|fft|only 1D FFT is currently supported b/140351181.|all|tpu|\n+|eigh|unimplemented|bfloat16, float16|cpu, gpu|\n|lu|unimplemented|bfloat16, float16|cpu, gpu, tpu|\n|qr|unimplemented|bfloat16, float16|cpu, gpu|\n|reduce_window_max|unimplemented in XLA|complex64|tpu|\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "diff": "# Primitives with limited support for jax2tf\n-*Last generated on (YYYY-MM-DD): 2021-02-02*\n+*Last generated on (YYYY-MM-DD): 2021-03-03*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -91,12 +91,13 @@ More detailed information can be found in the\n| eig | TF error: TF Conversion of eig is not implemented when both compute_left_eigenvectors and compute_right_eigenvectors are set to True | all | cpu, gpu, tpu | compiled, eager, graph |\n| eig | TF error: function not compilable | all | cpu | compiled |\n| eigh | TF test skipped: Not implemented in JAX: complex eigh not supported | complex | tpu | compiled, eager, graph |\n-| eigh | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n-| eigh | TF error: function not compilable | complex | cpu, gpu, tpu | compiled |\n+| eigh | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n+| eigh | TF test skipped: TF error: XLA lowering bug | complex | gpu | compiled |\n+| eigh | TF test skipped: TF error: function not yet compilable | complex | cpu, gpu, tpu | compiled |\n+| eigh | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n| erf | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| erf_inv | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| erfc | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n-| fft | TF test skipped: Not implemented in JAX: only 1D FFT is currently supported b/140351181. | all | tpu | compiled, eager, graph |\n| fft | TF error: TF function not compileable | complex128, float64 | cpu, gpu | compiled |\n| ge | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| gt | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n@@ -115,7 +116,6 @@ More detailed information can be found in the\n| min | TF error: op not defined for dtype | bool, complex64, int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| neg | TF error: op not defined for dtype | unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| nextafter | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n-| population_count | TF error: op not defined for dtype | uint32, uint64 | cpu, gpu | eager, graph |\n| qr | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n| qr | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n| reduce_max | TF error: op not defined for dtype | complex128 | cpu, gpu, tpu | compiled, eager, graph |\n@@ -179,7 +179,6 @@ with jax2tf. The following table lists that cases when this does not quite hold:\n| digamma | May return different results at singularity points 0 and -1.JAX returns nan and TF returns inf | bfloat16 | cpu, gpu, tpu | eager, graph |\n| eig | May return the eigenvalues and eigenvectors in a potentially different order. The eigenvectors may also be different, but equally valid. | all | cpu, gpu, tpu | eager, graph |\n| eigh | May return the eigenvalues and eigenvectors in a potentially different order. The eigenvectors may also be different, but equally valid. | all | cpu, gpu, tpu | compiled, eager, graph |\n-| eigh | Numeric comparision disabled: TODO: numeric discrepancies | float64 | cpu, gpu | compiled |\n| eigh | Numeric comparision disabled: TODO: numeric discrepancies | float16 | tpu | compiled, eager, graph |\n| erf_inv | May return different results at undefined points (< -1 or > 1): JAX returns `NaN` and TF returns `+inf` or `-inf`. | float32, float64 | cpu, gpu, tpu | compiled, eager, graph |\n| igamma | May return different results at undefined points (both arguments 0). JAX returns `NaN` and TF returns 0 or JAX returns 1 and TF returns `NaN` | all | cpu, gpu, tpu | eager, graph |\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -313,7 +313,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nJax2TfLimitation(\n\"jax2tf BUG: batch_group_count > 1 not yet converted\",\nenabled=(harness.params[\"batch_group_count\"] > 1)),\n- missing_tf_kernel(dtypes=[np.complex64, np.complex128], devices=\"gpu\"),\ncustom_numeric(devices=\"gpu\", tol=1e-4),\ncustom_numeric(devices=\"tpu\", tol=1e-3),\n# TODO(bchetioui): significant discrepancies in some float16 cases.\n@@ -456,7 +455,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nnp.int16\n],),\nmissing_tf_kernel(\n- dtypes=[np.int64], devices=(\"cpu\", \"gpu\"), modes=\"compiled\"),\n+ dtypes=np.int64, devices=(\"cpu\", \"gpu\"),\n+ modes=\"compiled\",\n+ # Works for 2D matrices.\n+ enabled=(len(harness.params[\"lhs_shape\"]) > 2)),\ncustom_numeric(dtypes=dtypes.bfloat16, tol=0.3),\ncustom_numeric(\ndtypes=[np.complex64, np.float32], devices=(\"cpu\", \"gpu\"),\n@@ -555,7 +557,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ntst.assertAllClose(\nnp.matmul(a, vr) - w[..., None, :] * vr,\nnp.zeros(a.shape, dtype=vr.dtype),\n- atol=tol)\n+ atol=tol,\n+ # For bfloat16 the np.matmul returns float32 result.\n+ check_dtypes=False)\ndef check_eigenvalue_is_in_array(eigenvalue, eigenvalues_array):\ntol = None\n@@ -583,19 +587,24 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n# TODO(b/181414529): enable after XLA/GPU bug is fixed.\nJax2TfLimitation(\n\"XLA lowering bug\",\n- dtypes=[np.complex64, np.complex128],\n+ dtypes=(np.complex64, np.complex128),\ndevices=(\"gpu\",),\nmodes=\"compiled\",\nskip_tf_run=True),\n+ missing_tf_kernel(\n+ dtypes=dtypes.bfloat16,\n+ devices=\"tpu\",\n+ enabled=(harness.params[\"shape\"] != (0, 0)), # This actually works!\n+ ),\nJax2TfLimitation(\n\"function not yet compilable\",\n- dtypes=[np.complex64, np.complex128],\n+ dtypes=(np.complex64, np.complex128),\nmodes=\"compiled\",\nskip_tf_run=True),\nJax2TfLimitation(\n\"TODO: numeric discrepancies\",\n- dtypes=[np.float16],\n- devices=(\"tpu\",),\n+ dtypes=np.float16,\n+ devices=\"tpu\",\nexpect_tf_error=False,\nskip_comparison=True),\ncustom_numeric(\n@@ -720,12 +729,10 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nnp.full((nr_special_cases,), 0., dtype=dtype),\nresult_tf[special_cases])\n# non-special cases are equal\n- tst.assertAllClose(result_jax[~special_cases], result_tf[~special_cases])\n+ tst.assertAllClose(result_jax[~special_cases], result_tf[~special_cases],\n+ atol=tol, rtol=tol)\nreturn [\n- # TODO(necula): Produces mismatched outputs on GPU.\n- Jax2TfLimitation(\"mismatched outputs on GPU\",\n- devices=(\"gpu\",), skip_comparison=True),\nmissing_tf_kernel(\ndtypes=[dtypes.bfloat16, np.float16]),\ncustom_numeric(\n@@ -761,9 +768,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nrtol=tol)\nreturn [\n- # TODO(necula): Produces mismatched outputs on GPU.\n- Jax2TfLimitation(\"mismatched outputs on GPU\",\n- devices=(\"gpu\",), skip_comparison=True),\nmissing_tf_kernel(\ndtypes=[dtypes.bfloat16, np.float16]),\ncustom_numeric(dtypes=np.float64, tol=1e-9),\n@@ -933,12 +937,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef population_count(cls, harness: primitive_harness.Harness):\n- return [\n- missing_tf_kernel(\n- dtypes=[np.uint32, np.uint64],\n- devices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\"))\n- ]\n+ return []\n@classmethod\ndef qr(cls, harness: primitive_harness.Harness):\n@@ -1263,11 +1262,13 @@ def missing_tf_kernel(\ndescription=\"op not defined for dtype\",\ndtypes,\nmodes=(\"eager\", \"graph\", \"compiled\"),\n- devices=(\"cpu\", \"gpu\", \"tpu\")\n+ devices=(\"cpu\", \"gpu\", \"tpu\"),\n+ enabled=True\n) -> Jax2TfLimitation:\nreturn Jax2TfLimitation(\ndescription,\ndtypes=dtypes,\ndevices=devices,\n- modes=modes)\n+ modes=modes,\n+ enabled=enabled)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1527,12 +1527,6 @@ def _make_fft_harness(name,\n[RandArg(shape, dtype),\nStaticArg(fft_type),\nStaticArg(fft_lengths)],\n- jax_unimplemented=[\n- Limitation(\n- \"only 1D FFT is currently supported b/140351181.\",\n- devices=\"tpu\",\n- enabled=len(fft_lengths) > 1),\n- ],\nrng_factory=_fft_rng_factory(dtype),\nshape=shape,\ndtype=dtype,\n@@ -1659,7 +1653,7 @@ for dtype in jtu.dtypes.all_inexact:\ndevices=\"tpu\",\ndtypes=[np.complex64, np.complex128]),\nLimitation(\n- \"unimplemented\", devices=(\"cpu\", \"gpu\", \"tpu\"),\n+ \"unimplemented\", devices=(\"cpu\", \"gpu\"),\ndtypes=[np.float16, dtypes.bfloat16]),\n],\nshape=shape,\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Updated the limitations Update the documentation to reflect the improvements in TF support for dtypes
260,496
04.03.2021 16:59:40
-3,600
70444df6ded1d5f5f8131dfdf9b6a102cf5042b1
Add python to codeblocks
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -74,7 +74,7 @@ Just like for regular TensorFlow functions, it is possible to include in the\nSavedModel multiple versions of a function for different input shapes, by\n\"warming up\" the function on different input shapes:\n-```\n+```python\nmy_model.f = tf.function(jax2tf.convert(f_jax), autograph=False)\nmy_model.f(tf.ones([1, 28, 28])) # a batch size of 1\nmy_model.f(tf.ones([16, 28, 28])) # a batch size of 16\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -50,7 +50,7 @@ To achieve this you should extract a pair from your trained model:\nIf you are using Flax, then the recipe to obtain this pair is as follows:\n- ```\n+ ```python\nclass MyModel(nn.Module):\n...\n@@ -70,7 +70,7 @@ and the same strategy should work for other neural-network libraries for JAX.\nIf your Flax model takes multiple inputs, then you need to change the last\nline above to:\n- ```\n+ ```python\npredict_fn = lambda params, input: model.apply({\"params\": params}, *input)\n```\n@@ -81,7 +81,7 @@ You can control which parameters you want to save as variables, and\nwhich you want to embed in the computation graph. For example, to\nembed all parameters in the graph:\n- ```\n+ ```python\nparams = ()\npredict_fn = lambda _, input: model.apply({\"params\": optimizer.target}, input)\n```\n@@ -97,7 +97,7 @@ the compiler to generate faster code by constant-folding some computations.)\nIf you are using Haiku, then the recipe is along these lines:\n- ```\n+ ```python\nmodel_fn = ...define your Haiku model...\nnet = hk.transform(model_fn) # get a pair of init and apply functions\nparams = ... train your model starting from net.init() ...\n" } ]
Python
Apache License 2.0
google/jax
Add python to codeblocks
260,287
04.03.2021 13:11:19
0
84c00653491577c9c085df71141ef2fe807904c3
Only vectorize xmap axes that have only one element per resource To make the jaxpr much less noisy. size-1 vmaps are quite pointless.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -562,10 +562,9 @@ def make_xmap_callable(fun: lu.WrappedFun,\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n- resource_env: ResourceEnv\n- axis_sizes: Dict[AxisName, int]\nphysical_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]]\naxis_subst: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n+ axis_vmap_size: Dict[AxisName, Optional[int]]\n@classmethod\ndef from_axis_resources(cls,\n@@ -574,21 +573,33 @@ class EvaluationPlan(NamedTuple):\naxis_sizes: Dict[AxisName, int]):\n# TODO: Support sequential resources\nphysical_axis_resources = axis_resources # NB: We only support physical resources at the moment\n- axis_subst = {name: axes + (fresh_resource_name(name),) for name, axes in axis_resources.items()}\n- return cls(resource_env, axis_sizes, physical_axis_resources, axis_subst)\n+ resource_shape = resource_env.shape\n+ axis_subst = dict(axis_resources)\n+ axis_vmap_size: Dict[AxisName, Optional[int]] = {}\n+ for naxis, raxes in axis_resources.items():\n+ num_resources = int(np.prod([resource_shape[axes] for axes in raxes], dtype=np.int64))\n+ if axis_sizes[naxis] % num_resources != 0:\n+ raise ValueError(f\"Size of axis {naxis} ({axis_sizes[naxis]}) is not divisible \"\n+ f\"by the total number of resources assigned to this axis ({raxes}, \"\n+ f\"{num_resources} in total)\")\n+ tile_size = axis_sizes[naxis] // num_resources\n+ # We have to vmap when there are no resources (to handle the axis name!) or\n+ # when every resource gets chunks of values.\n+ if not raxes or tile_size > 1:\n+ axis_vmap_size[naxis] = tile_size\n+ axis_subst[naxis] += (fresh_resource_name(naxis),)\n+ else:\n+ axis_vmap_size[naxis] = None\n+ return cls(physical_axis_resources, axis_subst, axis_vmap_size)\ndef vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\n- resource_shape = self.resource_env.shape\nfor naxis, raxes in self.axis_subst.items():\n- paxes, vaxis = raxes[:-1], raxes[-1]\n+ tile_size = self.axis_vmap_size[naxis]\n+ if tile_size is None:\n+ continue\n+ vaxis = raxes[-1]\nmap_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\n- paxes_size = int(np.prod([resource_shape[paxis] for paxis in paxes], dtype=np.int64))\n- if self.axis_sizes[naxis] % paxes_size != 0:\n- raise ValueError(f\"Size of axis {naxis} ({self.axis_sizes[naxis]}) is not divisible \"\n- f\"by the total number of resources assigned to this axis ({paxes}, \"\n- f\"{paxes_size} in total)\")\n- tile_size = self.axis_sizes[naxis] // paxes_size\nf = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=tile_size, axis_name=vaxis)\nreturn f\n" } ]
Python
Apache License 2.0
google/jax
Only vectorize xmap axes that have only one element per resource To make the jaxpr much less noisy. size-1 vmaps are quite pointless.
260,287
04.03.2021 18:08:45
0
6884f21b60bfb4ea181ab943cadfb7b38dfcaedb
Fix batching formula of xmap Turns out that once you insert multiple dimensions things become much more tricky than in the case of batching a one-dimensional map. Also strenghten our tests to make sure we don't depend too much on the semantics of the einsum batching rule.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -686,17 +686,24 @@ def _batch_trace_process_xmap(self, primitive, f: lu.WrappedFun, tracers, params\nfor d, in_axis in zip(dims, params['in_axes']))\nf, mapped_dims_out = batching.batch_subtrace(f, self.main, mapped_dims_in)\nout_axes_thunk = params['out_axes_thunk']\n+ def axis_after_insertion(axis, inserted_named_axes):\n+ for inserted_axis in sorted(inserted_named_axes.values()):\n+ if inserted_axis >= axis:\n+ break\n+ axis += 1\n+ return axis\n# NOTE: This assumes that the choice of the dimensions over which outputs\n# are batched is entirely dependent on the function and not e.g. on the\n# data or its shapes.\n@as_hashable_function(closure=out_axes_thunk)\ndef new_out_axes_thunk():\nreturn tuple(\n- fmap_dims(out_axes, lambda a: a + (d is not not_mapped and d <= a))\n+ out_axes if d is not_mapped else\n+ fmap_dims(out_axes, lambda a, nd=axis_after_insertion(d, out_axes): a + (nd <= a))\nfor out_axes, d in zip(out_axes_thunk(), mapped_dims_out()))\nnew_params = dict(params, in_axes=new_in_axes, out_axes_thunk=new_out_axes_thunk)\nvals_out = primitive.bind(f, *vals, **new_params)\n- dims_out = tuple(d if d is not_mapped else d + sum(a < d for a in out_axes.values())\n+ dims_out = tuple(d if d is not_mapped else axis_after_insertion(d, out_axes)\nfor d, out_axes in zip(mapped_dims_out(), out_axes_thunk()))\nreturn [batching.BatchTracer(self, v, d) for v, d in zip(vals_out, dims_out)]\nbatching.BatchTrace.process_xmap = _batch_trace_process_xmap # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -35,13 +35,14 @@ import jax.scipy as jscipy\nfrom jax import test_util as jtu\nfrom jax import vmap\nfrom jax import lax\n+from jax import core\nfrom jax.core import NamedShape\nfrom jax.experimental.maps import Mesh, mesh, xmap\nfrom jax.lib import xla_bridge\nfrom jax._src.util import curry, unzip2, split_list, prod\nfrom jax._src.lax.lax import DotDimensionNumbers\nfrom jax._src.lax.parallel import pgather\n-from jax.interpreters import pxla\n+from jax.interpreters import batching, pxla\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -112,6 +113,23 @@ def powerset(s):\ns = list(s)\nreturn it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))\n+# -------------------- vmap test helpers --------------------\n+\n+ensure_bdim_p = core.Primitive('ensure_bdim')\n+ensure_bdim_p.def_abstract_eval(lambda x, **kwargs: core.raise_to_shaped(x))\n+def _ensure_bdim_batcher(frame, vals_in, dims_in, axis_name, bdim):\n+ v, = vals_in\n+ d, = dims_in\n+ assert d is not batching.not_mapped\n+ return jnp.moveaxis(v, d, bdim), bdim\n+batching.collective_rules[ensure_bdim_p] = _ensure_bdim_batcher\n+batching.primitive_batchers[ensure_bdim_p] = lambda v, d: (v[0], d[0])\n+core.axis_substitution_rules[ensure_bdim_p] = partial(jax._src.lax.parallel._subst_all_names_in_param,\n+ 'axis_name')\n+\n+def ensure_bdim(x, axis_name, bdim):\n+ return ensure_bdim_p.bind(x, axis_name=(axis_name,), bdim=bdim)\n+\n# -------------------- Axis resources generation --------------------\nAxisResources = Dict[str, Union[str, Tuple[str, ...]]]\n@@ -444,21 +462,26 @@ class XMapTest(XMapTestCase):\nfor vmap_dim_y in [*range(2 + len(xmap_dim_y)), None]:\nif vmap_dim_x is None and vmap_dim_y is None:\ncontinue\n+ for vmap_dim_result in range(3):\nfor vmap_dim_z in range(2 + len(xmap_axes)):\nfor vmap_as_xmap in [False, True]:\nyield {\"testcase_name\":\nf\"_xin={(sorted(xmap_dim_x.items()), sorted(xmap_dim_y.items()))}_\"\nf\"xout={sorted(xmap_dim_z.items())}_vin={(vmap_dim_x, vmap_dim_y)}_\"\n- f\"vout={vmap_dim_z}_vmap_as_xmap={vmap_as_xmap}\",\n+ f\"vout={vmap_dim_z}_vresult={vmap_dim_result}_vmap_as_xmap={vmap_as_xmap}\",\n\"xmap_in_axes\": (xmap_dim_x, xmap_dim_y),\n\"xmap_out_axes\": xmap_dim_z,\n\"vmap_in_axes\": (vmap_dim_x, vmap_dim_y),\n\"vmap_out_axes\": vmap_dim_z,\n+ \"vmap_result_axis\": vmap_dim_result,\n\"vmap_as_xmap\": vmap_as_xmap}\n@parameterized.named_parameters(jtu.cases_from_list(VmapOfXmapCases()))\n@ignore_xmap_warning()\n- def testNestedMap(self, xmap_in_axes, xmap_out_axes, vmap_in_axes, vmap_out_axes, vmap_as_xmap):\n+ def testNestedMap(self,\n+ xmap_in_axes, xmap_out_axes,\n+ vmap_in_axes, vmap_out_axes, vmap_result_axis,\n+ vmap_as_xmap):\n\"\"\"Test various vmap(xmap) and xmap(xmap) combinations.\nThe outer map always introduces a single dimension, the inner map introduces one or two.\n@@ -474,7 +497,7 @@ class XMapTest(XMapTestCase):\nxind = ['n', 'k']\nyind = ['k', 'm']\nzind = ['n', 'm']\n- f = partial(jnp.einsum, 'nk,km->nm')\n+ f = lambda x, y: ensure_bdim(jnp.einsum('nk,km->nm', x, y), 'v', vmap_result_axis)\nfor pos, name in sorted(xin_x.items()):\nxshape.insert(pos, xmap_sizes[name])\n@@ -501,7 +524,7 @@ class XMapTest(XMapTestCase):\n{vin_y: 'v'} if vin_y is not None else {}),\nout_axes={vmap_out_axes: 'v'})\nelse:\n- do_vmap = partial(vmap, in_axes=vmap_in_axes, out_axes=vmap_out_axes)\n+ do_vmap = partial(vmap, in_axes=vmap_in_axes, out_axes=vmap_out_axes, axis_name='v')\nfm = do_vmap(xmap(f, in_axes=xmap_in_axes, out_axes=xmap_out_axes))\nfref = partial(jnp.einsum, f\"{''.join(xind)},{''.join(yind)}->{''.join(zind)}\")\n" } ]
Python
Apache License 2.0
google/jax
Fix batching formula of xmap Turns out that once you insert multiple dimensions things become much more tricky than in the case of batching a one-dimensional map. Also strenghten our tests to make sure we don't depend too much on the semantics of the einsum batching rule.
260,335
05.03.2021 10:12:58
28,800
206acc1ed26950ec9c5a0834d6a06763ffceb383
update jax for pypi
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.md", "new_path": "docs/CHANGELOG.md", "diff": "# Change Log\n-<!---\n-This is a comment.\n+<!--\nRemember to align the itemized text with the first line of an item within a list.\nPLEASE REMEMBER TO CHANGE THE '..master' WITH AN ACTUAL TAG in GITHUB LINK.\n-->\n-## jax 0.2.10 (Unreleased)\n+## jax 0.2.11 (unreleased)\n-* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.9...master).\n+* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.10...master).\n+* New features:\n+* Bug fixes:\n+* Breaking changes:\n+\n+## jax 0.2.10 (March 5 2021)\n+\n+* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.9...jax-v0.2.10).\n* New features:\n* {func}`jax.scipy.stats.chi2` is now available as a distribution with logpdf and pdf methods.\n* {func}`jax.scipy.stats.betabinom` is now available as a distribution with logpmf and pmf methods.\n" }, { "change_type": "MODIFY", "old_path": "jax/version.py", "new_path": "jax/version.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-__version__ = \"0.2.9\"\n+__version__ = \"0.2.10\"\n" } ]
Python
Apache License 2.0
google/jax
update jax for pypi
260,335
05.03.2021 12:47:20
28,800
b3fed79ad607ec71d563533f418b2fca203c2441
add test for issue once jaxlib is updated
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2566,6 +2566,36 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nscan_v(jnp.ones([1]), jnp.arange(5).reshape((1, 5))),\n(jnp.array([1.]), jnp.array([[0., 1., 2., 3., 4.]])))\n+ def test_xla_cpu_gpu_loop_cond_bug(self):\n+ # https://github.com/google/jax/issues/5900\n+ if jax.lib.version < (0, 1, 62):\n+ raise SkipTest(\"test is broken on jaxlib==0.1.61 and 0.1.60\")\n+\n+ def deriv(f):\n+ return lambda x, *args: jax.linearize(lambda x: f(x, *args), x)[1](1.0)\n+\n+ def _while_loop(cond_fun, body_fun, init_val, max_iter):\n+ def _iter(val):\n+ next_val = body_fun(val)\n+ next_cond = True\n+ return next_val, next_cond\n+\n+ def _fun(tup, _):\n+ val, cond = tup\n+ return jax.lax.cond(cond, _iter, lambda x: (x, False), val), _\n+\n+ init = (init_val, cond_fun(init_val))\n+ return jax.lax.scan(_fun, init, None, length=max_iter)[0][0]\n+\n+ def my_pow(x, y):\n+ def body_fun(val):\n+ return val * x\n+ def cond_fun(val):\n+ return True\n+ return _while_loop(cond_fun, body_fun, 1.0, y)\n+\n+ self.assertAllClose(deriv(my_pow)(3.0, 1), 1.0, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
add test for issue #5900, once jaxlib is updated
260,287
05.03.2021 17:59:16
0
2c7c86a4ba00d286361561b3d3a39d2bed287557
Reenable multi-axis all_to_all
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -911,12 +911,17 @@ def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_axis, concat_axis,\ndef _all_to_all_batched_collective(frame, vals_in, dims_in,\naxis_name, split_axis, concat_axis,\naxis_index_groups):\n- if isinstance(axis_name, (list, tuple)) and len(axis_name) > 1:\n- raise NotImplementedError(\"update after #4835\") # TODO(mattjj,apaszke)\nif axis_index_groups is not None:\nraise NotImplementedError(\"Please open a feature request!\")\nx, = vals_in\nd, = dims_in\n+ if isinstance(axis_name, (list, tuple)):\n+ pos = axis_name.index(frame.name)\n+ major_axes, minor_axes = axis_name[:pos], axis_name[pos + 1:]\n+ else:\n+ major_axes, minor_axes = (), ()\n+ # Optimized case when no splitting is necessary\n+ if not major_axes and not minor_axes:\nif split_axis == concat_axis:\naxis = split_axis + (d <= split_axis)\nd_pre_split = d\n@@ -926,6 +931,32 @@ def _all_to_all_batched_collective(frame, vals_in, dims_in,\nelse:\nx_concat = _foldaxis(concat_axis, _moveaxis(d, concat_axis, x))\nreturn _splitaxis(split_axis, frame.size, x_concat), split_axis\n+ # Here we have to handle either the major or the minor dimensions\n+ # We will be accumulating chunks into the three leading dims: [Major, Current, Minor, ...]\n+ x, d = lax.expand_dims(_moveaxis(d, 0, x), (0, 2)), 1\n+ split_axis += 3; concat_axis += 3 # Offset by extra three leading dims\n+\n+ if major_axes:\n+ x = all_to_all_p.bind(x, axis_name=major_axes,\n+ split_axis=split_axis, concat_axis=0,\n+ axis_index_groups=axis_index_groups)\n+ # Split out the local part into axis new_d (NOTE: d is already in axis 1)\n+ x = _splitaxis(split_axis, frame.size, x)\n+ new_d = split_axis\n+ concat_axis += (split_axis <= concat_axis) # Offset the existing axes by the new batch axis\n+ split_axis += 1\n+ if minor_axes:\n+ x = all_to_all_p.bind(x, axis_name=minor_axes,\n+ split_axis=split_axis, concat_axis=2,\n+ axis_index_groups=axis_index_groups)\n+\n+ # Fold the chunk axes into a single one\n+ x = _foldaxis(0, _foldaxis(0, x))\n+ split_axis -= 2; concat_axis -= 2; new_d -= 2\n+ # Fold gathered axes into concat_axis\n+ x = _foldaxis(concat_axis - 1, _moveaxis(0, concat_axis - 1, x))\n+ new_d -= 1 # We've removed 0th dimension, so new_d needs to be adjusted\n+ return x, new_d\ndef _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis, axis_index_groups):\ninput_aval = raise_to_shaped(x)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1698,6 +1698,7 @@ def check_map(prim, in_avals, params):\nmapped_avals = [mapped_aval(axis_size, in_axis, aval)\nif in_axis is not None else aval\nfor aval, in_axis in zip(in_avals, in_axes)]\n+ with extend_axis_env(params['axis_name'], axis_size, None):\n_check_jaxpr(call_jaxpr, mapped_avals)\nmapped_out_avals = [v.aval for v in call_jaxpr.outvars]\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -172,7 +172,9 @@ class JaxprTrace(Trace):\nreturn call_partial_eval_rules[primitive](self, primitive, f, tracers, params)\nin_pvals = [t.pval for t in tracers]\n+ ctx: Any\nif primitive.map_primitive:\n+ ctx = core.extend_axis_env(params['axis_name'], params['axis_size'], None)\nmapped_aval = partial(core.mapped_aval, params['axis_size'])\nin_pvals = [pval if pval.is_known() or in_axis is None\nelse PartialVal.unknown(mapped_aval(in_axis, pval[0]))\n@@ -188,7 +190,9 @@ class JaxprTrace(Trace):\npe_params = dict(params, out_axes_thunk=new_out_axes_thunk)\nreturn primitive.bind(f, *args, **pe_params)\nelse:\n+ ctx = contextlib.suppress() # This is a no-op\napp = partial(primitive.bind, **params)\n+ with ctx:\njaxpr, out_pvals, consts, env_tracers = self.partial_eval(\nf, in_pvals, app, instantiate=False)\nif primitive.map_primitive:\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "import itertools as it\nimport numpy as np\n-from unittest import skipIf, SkipTest\n+from unittest import skipIf\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\nimport jax.numpy as jnp\n-from jax.interpreters import batching\nfrom jax import test_util as jtu\nfrom jax import lax\nfrom jax._src.lax import parallel\n@@ -1032,7 +1031,6 @@ class BatchingTest(jtu.JaxTestCase):\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\ndef testAllToAllSplitAxis(self, vmap_axis, split_axis, concat_axis):\n- raise SkipTest(\"all_to_all split axis broken after #4835\") # TODO(mattjj,apaszke)\nshape = (4, 4, 4)\nx = np.arange(np.prod(shape)).reshape(shape)\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -618,6 +618,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @ignore_slow_all_to_all_warning()\ndef testGradOfGather(self):\nif not config.omnistaging_enabled:\nself.skipTest(\"all_to_all doesn't work without omnistaging\")\n@@ -1146,6 +1147,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(expected_bz1, bz1, check_dtypes=False)\nself.assertAllClose(bz2, bz2, check_dtypes=False)\n+ @ignore_slow_all_to_all_warning()\ndef testPswapaxes(self):\nif not config.omnistaging_enabled:\nself.skipTest(\"all_to_all doesn't work without omnistaging\")\n@@ -1157,6 +1159,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.swapaxes(x, 0, 2)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @ignore_slow_all_to_all_warning()\ndef testGradOfPswapaxes(self):\nif not config.omnistaging_enabled:\nself.skipTest(\"all_to_all doesn't work without omnistaging\")\n" } ]
Python
Apache License 2.0
google/jax
Reenable multi-axis all_to_all
260,287
08.03.2021 12:27:01
0
ec29275d7e40d8908fb85a9b8cf0a6719e1f9fda
Substitute axis names in nested jaxprs Previously any collectives buried inside control flow would fail to compile with xmap, because it would not traverse those with its name substitution. This adds a "catch-all" default substitution rule which recursively applies to all jaxpr found in the params (at the top level).
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1529,7 +1529,31 @@ def used_axis_names(primitive: Primitive, params: ParamDict) -> Set[AxisName]:\ndef subst_axis_names(primitive: Primitive, params: ParamDict, subst: AxisSubst) -> ParamDict:\nif primitive in axis_substitution_rules:\nreturn axis_substitution_rules[primitive](params, subst)\n+ # Default implementation: substitute names in all jaxpr parameters\n+ if isinstance(primitive, MapPrimitive):\n+ def shadowed_subst(name):\n+ return (name,) if name == params['axis_name'] else subst(name)\n+ else:\n+ shadowed_subst = subst\n+ jaxpr_params = [(n, v) for n, v in params.items() if isinstance(v, (Jaxpr, ClosedJaxpr))]\n+ if not jaxpr_params:\nreturn params\n+ new_params = dict(params)\n+ for name, jaxpr in jaxpr_params:\n+ new_params[name] = subst_axis_names_jaxpr(jaxpr, shadowed_subst)\n+ return new_params\n+\n+def subst_axis_names_jaxpr(jaxpr: Union[Jaxpr, ClosedJaxpr], subst: AxisSubst):\n+ consts = None\n+ if isinstance(jaxpr, ClosedJaxpr):\n+ consts = jaxpr.consts\n+ jaxpr = jaxpr.jaxpr\n+ eqns = [eqn._replace(params=subst_axis_names(eqn.primitive, eqn.params, subst))\n+ for eqn in jaxpr.eqns]\n+ new_jaxpr = Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, eqns)\n+ if consts is not None:\n+ return ClosedJaxpr(new_jaxpr, consts)\n+ return new_jaxpr\naxis_substitution_rules: Dict[Primitive, Callable[[ParamDict, AxisSubst], ParamDict]] = {}\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -535,7 +535,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nwith core.extend_axis_env_nd(axis_sizes.items()):\njaxpr, _, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\nout_axes = out_axes_thunk()\n- jaxpr = subst_jaxpr_axis_names(jaxpr, plan.axis_subst)\n+ jaxpr = core.subst_axis_names_jaxpr(jaxpr, plan.axis_subst)\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(jaxpr, consts)))\nf = hide_mapped_axes(f, tuple(in_axes), tuple(out_axes))\n@@ -563,9 +563,13 @@ def make_xmap_callable(fun: lu.WrappedFun,\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\nphysical_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n- axis_subst: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n+ axis_subst_dict: Dict[AxisName, Tuple[ResourceAxisName, ...]]\naxis_vmap_size: Dict[AxisName, Optional[int]]\n+ @property\n+ def axis_subst(self) -> core.AxisSubst:\n+ return lambda name: self.axis_subst_dict.get(name, (name,))\n+\n@classmethod\ndef from_axis_resources(cls,\naxis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]],\n@@ -574,7 +578,7 @@ class EvaluationPlan(NamedTuple):\n# TODO: Support sequential resources\nphysical_axis_resources = axis_resources # NB: We only support physical resources at the moment\nresource_shape = resource_env.shape\n- axis_subst = dict(axis_resources)\n+ axis_subst_dict = dict(axis_resources)\naxis_vmap_size: Dict[AxisName, Optional[int]] = {}\nfor naxis, raxes in axis_resources.items():\nnum_resources = int(np.prod([resource_shape[axes] for axes in raxes], dtype=np.int64))\n@@ -587,13 +591,13 @@ class EvaluationPlan(NamedTuple):\n# when every resource gets chunks of values.\nif not raxes or tile_size > 1:\naxis_vmap_size[naxis] = tile_size\n- axis_subst[naxis] += (fresh_resource_name(naxis),)\n+ axis_subst_dict[naxis] += (fresh_resource_name(naxis),)\nelse:\naxis_vmap_size[naxis] = None\n- return cls(physical_axis_resources, axis_subst, axis_vmap_size)\n+ return cls(physical_axis_resources, axis_subst_dict, axis_vmap_size)\ndef vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\n- for naxis, raxes in self.axis_subst.items():\n+ for naxis, raxes in self.axis_subst_dict.items():\ntile_size = self.axis_vmap_size[naxis]\nif tile_size is None:\ncontinue\n@@ -643,6 +647,13 @@ def _process_xmap_default(self, call_primitive, f, tracers, params):\nraise NotImplementedError(f\"{type(self)} must override process_xmap to handle xmap\")\ncore.Trace.process_xmap = _process_xmap_default # type: ignore\n+def _xmap_axis_subst(params, subst):\n+ def shadowed_subst(name):\n+ return (name,) if name in params['axis_sizes'] else subst(name)\n+ new_jaxpr = core.subst_axis_names_jaxpr(params['call_jaxpr'], shadowed_subst)\n+ return dict(params, call_jaxpr=new_jaxpr)\n+core.axis_substitution_rules[xmap_p] = _xmap_axis_subst\n+\n# This is DynamicJaxprTrace.process_map with some very minor modifications\ndef _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\n@@ -747,7 +758,7 @@ def _xmap_translation_rule_replica(c, axis_env,\nin zip(call_jaxpr.invars, in_axes, mesh_in_axes)]\n# We have to substitute before tracing, because we want the vectorized\n# axes to be used in the jaxpr.\n- resource_call_jaxpr = subst_jaxpr_axis_names(call_jaxpr, plan.axis_subst)\n+ resource_call_jaxpr = core.subst_axis_names_jaxpr(call_jaxpr, plan.axis_subst)\nf = lu.wrap_init(core.jaxpr_as_fun(core.ClosedJaxpr(resource_call_jaxpr, ())))\nf = hide_mapped_axes(f, tuple(in_axes), tuple(out_axes))\nf = plan.vectorize(f, in_axes, out_axes)\n@@ -922,7 +933,7 @@ def hide_mapped_axes(flat_in_axes, flat_out_axes, *flat_args):\nyield map(_unsqueeze_mapped_axes, flat_outputs, flat_out_axes)\n-def _jaxpr_resources(jaxpr, resource_env) -> Set[ResourceAxisName]:\n+def _jaxpr_resources(jaxpr: core.Jaxpr, resource_env) -> Set[ResourceAxisName]:\nused_resources = set()\nfor eqn in jaxpr.eqns:\nif eqn.primitive is xmap_p:\n@@ -936,36 +947,6 @@ def _jaxpr_resources(jaxpr, resource_env) -> Set[ResourceAxisName]:\nused_resources |= update\nreturn used_resources\n-def subst_jaxpr_axis_names(jaxpr, axis_subst: Dict[AxisName, Tuple[AxisName]]):\n- eqns = [subst_eqn_axis_names(eqn, axis_subst) for eqn in jaxpr.eqns]\n- return core.Jaxpr(jaxpr.constvars, jaxpr.invars, jaxpr.outvars, eqns)\n-\n-def subst_eqn_axis_names(eqn, axis_subst: Dict[AxisName, Tuple[AxisName]]):\n- # TODO: Support custom_vjp, custom_jvp\n- if eqn.primitive is xmap_p:\n- shadowed_axes = set(eqn.params['axis_sizes']) & set(axis_subst)\n- if shadowed_axes:\n- shadowed_subst = dict(axis_subst)\n- for saxis in shadowed_axes:\n- del shadowed_subst[saxis]\n- else:\n- shadowed_subst = axis_subst\n- new_call_jaxpr = subst_jaxpr_axis_names(eqn.params['call_jaxpr'], shadowed_subst)\n- return eqn._replace(params=dict(eqn.params, call_jaxpr=new_call_jaxpr))\n- if isinstance(eqn.primitive, (core.CallPrimitive, core.MapPrimitive)):\n- bound_name = eqn.params.get('axis_name', None)\n- if bound_name in axis_subst: # Check for shadowing\n- sub_subst = dict(axis_subst)\n- del sub_subst[bound_name]\n- else:\n- sub_subst = axis_subst\n- new_call_jaxpr = subst_jaxpr_axis_names(eqn.params['call_jaxpr'], sub_subst)\n- return eqn._replace(params=dict(eqn.params, call_jaxpr=new_call_jaxpr))\n- new_params = core.subst_axis_names(eqn.primitive, eqn.params,\n- lambda name: axis_subst.get(name, (name,)))\n- return eqn if new_params is eqn.params else eqn._replace(params=new_params)\n-\n-\n# -------- soft_pmap --------\ndef soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -437,6 +437,12 @@ class XMapTest(XMapTestCase):\nself.assertNotDeleted(y)\nself.assertDeleted(x)\n+ @ignore_xmap_warning()\n+ def testControlFlow(self):\n+ x = jnp.arange(5)\n+ xmap(lambda x: lax.fori_loop(0, 10, lambda _, x: lax.psum(x, 'i'), x),\n+ in_axes=['i', ...], out_axes=['i', ...])(x)\n+\n@with_and_without_mesh\n@ignore_xmap_warning()\ndef testAxisSizes(self, mesh, axis_resources):\n" } ]
Python
Apache License 2.0
google/jax
Substitute axis names in nested jaxprs Previously any collectives buried inside control flow would fail to compile with xmap, because it would not traverse those with its name substitution. This adds a "catch-all" default substitution rule which recursively applies to all jaxpr found in the params (at the top level).
260,389
24.02.2021 11:03:11
28,800
ba0f785a1fbfd7edb602345c52545075ba981dab
allow named axes on while_loop condition aval
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -271,7 +271,9 @@ def while_loop(cond_fun: Callable[[T], bool],\nif not treedef_is_leaf(cond_tree) or len(cond_jaxpr.out_avals) != 1:\nmsg = \"cond_fun must return a boolean scalar, but got pytree {}.\"\nraise TypeError(msg.format(cond_tree))\n- if cond_jaxpr.out_avals[0].strip_weak_type() != ShapedArray((), np.bool_):\n+ pred_aval = cond_jaxpr.out_avals[0]\n+ if (not isinstance(pred_aval, ShapedArray)\n+ or pred_aval.strip_weak_type().strip_named_shape() != ShapedArray((), np.bool_)):\nmsg = \"cond_fun must return a boolean scalar, but got output type(s) {}.\"\nraise TypeError(msg.format(cond_jaxpr.out_avals))\nreturn init_vals, init_avals, body_jaxpr, in_tree, cond_jaxpr, cond_consts, body_consts, body_tree\n" } ]
Python
Apache License 2.0
google/jax
allow named axes on while_loop condition aval
260,389
04.03.2021 04:13:04
28,800
47f17f04804ea7318cf0e7d8bd8a8e046ab10ffd
add (broken) test
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -335,6 +335,20 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = np.array([4, 3, 4, 3])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testWhileLoopAxisIndexBatched(self):\n+ raise SkipTest(\"leaks axis_index tracer\")\n+ def fun(x):\n+ return lax.while_loop(lambda x: x < lax.axis_index('i'), lambda x: x + 2, x)\n+\n+ ans = api.vmap(fun, axis_name='i')(np.array([0, 0, 0, 0]))\n+ expected = np.array([0, 2, 2, 4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ fun = api.jit(fun)\n+ ans = api.vmap(fun, axis_name='i')(np.array([0, 0, 0, 0]))\n+ expected = np.array([0, 2, 2, 4])\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef testWhileLoopCondConstsBatched(self):\ndef fun(x, y):\nreturn lax.while_loop(lambda x: x < y, lambda x: x + 2, x)\n" } ]
Python
Apache License 2.0
google/jax
add (broken) test
260,335
08.03.2021 19:49:10
28,800
2b9ffb1fb3a72fea413c0f034ce4a31baf657631
make axis_index bind respect dynamic traces
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1097,13 +1097,9 @@ def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_\ndef _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n# TODO(cjfj): Add reduce-scatter op to XLA?\nconcat_axis = 0\n- return (lax_numpy.sum(\n- all_to_all(\n- cts,\n- axis_name=axis_name,\n- split_axis=all_gather_dimension,\n- concat_axis=concat_axis,\n- axis_index_groups=axis_index_groups),\n+ return (lax_numpy.sum(all_to_all(\n+ cts, axis_name=axis_name, split_axis=all_gather_dimension,\n+ concat_axis=concat_axis, axis_index_groups=axis_index_groups),\naxis=concat_axis),)\ndef _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n@@ -1162,26 +1158,30 @@ core.axis_substitution_rules[axis_index_p] = partial(_subst_all_names_in_param,\n# wants to bind an axis name has to additionally implement `process_axis_index`\n# and put its main trace on the axis env stack.\ndef _axis_index_bind(*, axis_name):\n+ def name_idx(name):\n+ frame = core.axis_frame(name)\n+ dynamic = core.thread_local_state.trace_state.trace_stack.dynamic\n+ if (frame.main_trace is None or dynamic.level > frame.main_trace.level):\n+ return core.Primitive.bind(axis_index_p, axis_name=name)\n+ else:\n+ trace = frame.main_trace.with_cur_sublevel()\n+ return trace.process_axis_index(frame)\n+\nif not isinstance(axis_name, (tuple, list)):\n- axis_name = (axis_name,)\n+ return name_idx(axis_name)\n+ else:\ninner_size = 1\nindex = 0\nfor name in reversed(axis_name):\n- frame = core.axis_frame(name)\n- if frame.main_trace is not None:\n- trace = frame.main_trace.with_cur_sublevel()\n- name_idx = trace.process_axis_index(frame)\n- else:\n- name_idx = core.Primitive.bind(axis_index_p, axis_name=name)\n- index += name_idx * inner_size\n+ index += name_idx(name) * inner_size\ninner_size *= psum(1, name)\nreturn index\naxis_index_p.def_custom_bind(_axis_index_bind)\n-def _process_axis_index(self, frame):\n+def _vmap_process_axis_index(self, frame):\nassert frame.size is not None\n- return batching.BatchTracer(self, lax_numpy.arange(frame.size, dtype=np.int32), 0)\n-batching.BatchTrace.process_axis_index = _process_axis_index # type: ignore\n+ return batching.BatchTracer(self, lax.iota(np.int32, frame.size), 0)\n+batching.BatchTrace.process_axis_index = _vmap_process_axis_index # type: ignore\npdot_p = core.Primitive('pdot')\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -335,8 +335,8 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nexpected = np.array([4, 3, 4, 3])\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ @skipIf(not config.omnistaging_enabled, \"test only works with omnistaging\")\ndef testWhileLoopAxisIndexBatched(self):\n- raise SkipTest(\"leaks axis_index tracer\")\ndef fun(x):\nreturn lax.while_loop(lambda x: x < lax.axis_index('i'), lambda x: x + 2, x)\n" } ]
Python
Apache License 2.0
google/jax
make axis_index bind respect dynamic traces
260,510
09.03.2021 15:21:07
28,800
ddaef193fe5188ba8cc83062baafd4976d40c974
Add scan and while rule for jax.experimental.callback transformation
[ { "change_type": "MODIFY", "old_path": "jax/experimental/callback.py", "new_path": "jax/experimental/callback.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import itertools as it\n+\nfrom typing import Any, Callable, Dict, Sequence, Union\nimport jax.numpy as jnp\nfrom jax import core\n-from jax.core import Trace, Tracer\n+from jax.core import Trace, Tracer, jaxpr_as_fun\n+from jax import lax\nfrom jax import linear_util as lu\n-from jax._src.util import partial, safe_map, wraps\n+from jax._src.util import partial, safe_map, wraps, split_list\n+from jax._src.lax import control_flow as lcf\nimport inspect\nfrom jax.api_util import flatten_fun_nokwargs\n-from jax.tree_util import tree_flatten, tree_unflatten\n+from jax.tree_util import tree_flatten, tree_unflatten, tree_structure, tree_leaves, tree_map\nmap = safe_map\n@@ -143,6 +147,8 @@ class CallbackTrace(Trace):\nreturn CallbackTracer(self, val.val)\ndef process_primitive(self, primitive, tracers, params):\n+ if primitive in custom_callback_rules:\n+ return custom_callback_rules[primitive](self, *tracers, **params)\nvals_in = [t.val for t in tracers]\nvals_out = self.main.callback(primitive, vals_in, params) # type: ignore\nif primitive.multiple_results:\n@@ -169,3 +175,70 @@ class CallbackTrace(Trace):\n# TODO(sharadmv): don't drop the custom derivative rule\ndel primitive, fwd, bwd, out_trees # Unused.\nreturn fun.call_wrapped(*tracers)\n+\n+\n+custom_callback_rules: Dict[Any, Any] = {}\n+\n+def _scan_callback_rule(trace, *tracers, reverse, length, num_consts, num_carry,\n+ jaxpr, linear, unroll):\n+ const_tracers, carry_tracers, xs_tracers = split_list(tracers, [num_consts, num_carry])\n+ carry_avals, xs_avals = tree_map(lambda x: x.aval, (carry_tracers, xs_tracers))\n+ const_vals, carry_vals, xs_vals = tree_map(lambda x: x.val, (const_tracers, carry_tracers, xs_tracers))\n+\n+ x_tracers = [t[0] for t in xs_tracers]\n+ x_avals = [t.aval for t in x_tracers]\n+\n+ body_fun = jaxpr_as_fun(jaxpr)\n+\n+ def new_body(carry, x):\n+ flat_args = tree_leaves((carry, x))\n+ out = body_fun(*(const_vals + flat_args))\n+ out_carry, y = split_list(out, [num_carry])\n+ return out_carry, y\n+ main = trace.main\n+ new_body = callback_transform(new_body, main.callback, strip_calls=main.strip_calls) # type: ignore\n+ in_tree = tree_structure(tuple(carry_avals + xs_avals))\n+ new_jaxpr, new_consts, _ = lcf._initial_style_jaxpr(\n+ new_body, in_tree, tuple(carry_avals + x_avals))\n+ vals = tuple(it.chain(new_consts, carry_vals, xs_vals))\n+ out_vals = lax.scan_p.bind(*vals, reverse=reverse, length=length,\n+ num_consts=len(new_consts), num_carry=num_carry,\n+ jaxpr=new_jaxpr, linear=linear, unroll=unroll)\n+ return safe_map(trace.pure, out_vals)\n+\n+custom_callback_rules[lax.scan_p] = _scan_callback_rule\n+\n+\n+def _while_callback_rule(trace, *tracers, cond_jaxpr, body_jaxpr,\n+ cond_nconsts, body_nconsts):\n+ cond_const_tracers, body_const_tracers, init_tracers = split_list(\n+ tracers, [cond_nconsts, body_nconsts])\n+ init_avals = safe_map(lambda x: x.aval, init_tracers)\n+ cond_const_vals, body_const_vals, init_vals = tree_map(\n+ lambda x: x.val, (cond_const_tracers, body_const_tracers, init_tracers))\n+\n+ body_fun = jaxpr_as_fun(body_jaxpr)\n+ cond_fun = jaxpr_as_fun(cond_jaxpr)\n+\n+ def cond(*carry):\n+ return cond_fun(*it.chain(cond_const_vals, carry))\n+\n+ def body(*carry):\n+ return body_fun(*it.chain(body_const_vals, carry))\n+\n+ main = trace.main\n+ new_cond = callback_transform(cond, main.callback, strip_calls=main.strip_calls) # type: ignore\n+ new_body = callback_transform(body, main.callback, strip_calls=main.strip_calls) # type: ignore\n+ in_tree = tree_structure(init_avals)\n+\n+ new_cond_jaxpr, new_cond_consts, _ = lcf._initial_style_jaxpr(new_cond, in_tree, tuple(init_avals))\n+ new_body_jaxpr, new_body_consts, _ = lcf._initial_style_jaxpr(new_body, in_tree, tuple(init_avals))\n+ out = lcf.while_p.bind(\n+ *it.chain(new_cond_consts, new_body_consts, init_vals),\n+ cond_nconsts=len(new_cond_consts),\n+ body_nconsts=len(new_body_consts),\n+ cond_jaxpr=new_cond_jaxpr,\n+ body_jaxpr=new_body_jaxpr)\n+ return safe_map(trace.pure, out)\n+\n+custom_callback_rules[lax.while_p] = _while_callback_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/callback_test.py", "new_path": "tests/callback_test.py", "diff": "@@ -101,6 +101,63 @@ class CallbackTest(jtu.JaxTestCase):\nrewrite(f, {})(x),\njnp.array([2.0, 4.0]))\n+ def testRewriteThroughScan(self):\n+ def f(xs):\n+ def body(carry, x):\n+ carry = carry * 2.\n+ return carry, x - 2.\n+ return lax.scan(body, 1., xs)\n+\n+ xs = jnp.arange(4.)\n+ carry, ys = f(xs)\n+ self.assertAllClose(carry, 16.)\n+ self.assertAllClose(ys, jnp.arange(4.) - 2.)\n+\n+ rewrites = {\n+ lax.mul_p: lambda x, y: x + y,\n+ lax.sub_p: lambda x, y: x / y\n+ }\n+ carry, ys = rewrite(f, rewrites)(xs)\n+ self.assertAllClose(carry, 1. + 8.)\n+ self.assertAllClose(ys, jnp.arange(4.) / 2.)\n+\n+\n+ def testRewriteThroughWhile(self):\n+ def f(x):\n+ def cond(x):\n+ return x < 5\n+ def body(x):\n+ return x + 1\n+ return lax.while_loop(cond, body, x)\n+\n+ x = 0\n+ self.assertAllClose(f(x), 5)\n+\n+ rewrites = {\n+ lax.add_p: lambda x, y: x + y + 100,\n+ }\n+ self.assertAllClose(rewrite(f, rewrites)(x), 101)\n+\n+ rewrites = {\n+ lax.lt_p: lambda x, y: x < y + 5\n+ }\n+ self.assertAllClose(rewrite(f, rewrites)(x), 10)\n+\n+\n+ def testRewriteThroughForLoop(self):\n+ def f(x):\n+ def body(i, x):\n+ return x * i\n+ return lax.fori_loop(1, 5, body, x)\n+\n+ x = 1\n+ self.assertAllClose(f(x), 24)\n+\n+ rewrites = {\n+ lax.mul_p: lambda x, y: x + y\n+ }\n+ self.assertAllClose(rewrite(f, rewrites)(x), 11)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add scan and while rule for jax.experimental.callback transformation
260,335
10.03.2021 12:20:36
28,800
d11bba9cafcaea1c469f5a49e7abf1cfefbd5967
tweak broken tests
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2134,9 +2134,9 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(core.ConcretizationTypeError, msg):\nf()\n- # TODO(jakevdp): re-enable this if possible.\n- @unittest.skipIf(True, \"broken by convert_element_type change.\")\ndef test_xla_computation_zeros_doesnt_device_put(self):\n+ raise SkipTest(\"broken test\") # TODO(mattjj): fix\n+\nif not config.omnistaging_enabled:\nraise unittest.SkipTest(\"test is omnistaging-specific\")\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -967,13 +967,17 @@ class LaxRandomTest(jtu.JaxTestCase):\nwith self.assertRaises(OverflowError):\napi.jit(random.PRNGKey)(seed)\n- def test_random_split_doesnt_device_put(self):\n- # TODO(mattjj): Enable this after fixing convert_element_type.\n- raise SkipTest(\"Broken by convert_element_type.\")\n+ def test_random_split_doesnt_device_put_during_tracing(self):\n+ raise SkipTest(\"broken test\") # TODO(mattjj): fix\n+\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"test is omnistaging-specific\")\n+\nkey = random.PRNGKey(1)\nwith jtu.count_device_put() as count:\n+ api.jit(random.split)(key)\nkey, _ = random.split(key, 2)\n- self.assertEqual(count[0], 0)\n+ self.assertEqual(count[0], 1) # 1 for the argument device_put call\n" } ]
Python
Apache License 2.0
google/jax
tweak broken tests
260,293
11.03.2021 11:32:43
-3,600
6470094f04ba7c02c8574051ec3128eff3f11def
Fix import of datasets in differentially private SGD example
[ { "change_type": "MODIFY", "old_path": "examples/differentially_private_sgd.py", "new_path": "examples/differentially_private_sgd.py", "diff": "@@ -79,7 +79,7 @@ from jax.experimental import optimizers\nfrom jax.experimental import stax\nfrom jax.tree_util import tree_flatten, tree_unflatten\nimport jax.numpy as jnp\n-from examples import datasets\n+from jax.examples import datasets\nimport numpy.random as npr\n# https://github.com/tensorflow/privacy\n" } ]
Python
Apache License 2.0
google/jax
Fix import of datasets in differentially private SGD example
260,482
06.03.2021 11:53:01
-3,600
d743aa5803be9264cbcfcd98f679954309d6517e
Added 'where' keyword to 'jnp.{mean, var, std}'
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -2013,15 +2013,15 @@ def min(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None,\n@_wraps(np.all)\ndef all(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None,\n- keepdims=None):\n+ keepdims=None, *, where=None):\nreturn _reduction(a, \"all\", np.all, lax.bitwise_and, True, preproc=_cast_to_bool,\n- axis=axis, out=out, keepdims=keepdims)\n+ axis=axis, out=out, keepdims=keepdims, where_=where)\n@_wraps(np.any)\ndef any(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, out=None,\n- keepdims=None):\n+ keepdims=None, *, where=None):\nreturn _reduction(a, \"any\", np.any, lax.bitwise_or, False, preproc=_cast_to_bool,\n- axis=axis, out=out, keepdims=keepdims)\n+ axis=axis, out=out, keepdims=keepdims, where_=where)\nproduct = prod\namin = min\n@@ -2040,16 +2040,20 @@ def _axis_size(a, axis):\n@_wraps(np.mean)\ndef mean(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\n- out=None, keepdims=False):\n+ out=None, keepdims=False, *, where=None):\n_check_arraylike(\"mean\", a)\nlax._check_user_dtype_supported(dtype, \"mean\")\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.mean is not supported.\")\n+ if where is None:\nif axis is None:\nnormalizer = size(a)\nelse:\nnormalizer = _axis_size(a, axis)\n+ else:\n+ normalizer = sum(broadcast_to(where, a.shape), axis, dtype=dtype, keepdims=keepdims)\n+\nif dtype is None:\nif issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):\ndtype = float_\n@@ -2058,7 +2062,7 @@ def mean(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\ndtype = dtypes.canonicalize_dtype(dtype)\nreturn lax.div(\n- sum(a, axis, dtype=dtype, keepdims=keepdims),\n+ sum(a, axis, dtype=dtype, keepdims=keepdims, where=where),\nlax.convert_element_type(normalizer, dtype))\n@_wraps(np.average)\n@@ -2113,27 +2117,30 @@ def average(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, weights=None,\n@_wraps(np.var)\ndef var(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\n- out=None, ddof=0, keepdims=False):\n+ out=None, ddof=0, keepdims=False, *, where=None):\n_check_arraylike(\"var\", a)\nlax._check_user_dtype_supported(dtype, \"var\")\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.var is not supported.\")\na_dtype, dtype = _var_promote_types(_dtype(a), dtype)\n- a_mean = mean(a, axis, dtype=a_dtype, keepdims=True)\n+ a_mean = mean(a, axis, dtype=a_dtype, keepdims=True, where=where)\ncentered = a - a_mean\nif issubdtype(centered.dtype, complexfloating):\ncentered = lax.real(lax.mul(centered, lax.conj(centered)))\nelse:\ncentered = lax.square(centered)\n+ if where is None:\nif axis is None:\nnormalizer = size(a)\nelse:\nnormalizer = _axis_size(a, axis)\n+ else:\n+ normalizer = sum(broadcast_to(where, a.shape), axis, dtype=dtype, keepdims=keepdims)\nnormalizer = normalizer - ddof\n- result = sum(centered, axis, keepdims=keepdims)\n+ result = sum(centered, axis, keepdims=keepdims, where=where)\nout = lax.div(result, lax.convert_element_type(normalizer, result.dtype))\nreturn lax.convert_element_type(out, dtype)\n@@ -2160,12 +2167,12 @@ def _var_promote_types(a_dtype, dtype):\n@_wraps(np.std)\ndef std(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\n- out=None, ddof=0, keepdims=False):\n+ out=None, ddof=0, keepdims=False, *, where=None):\n_check_arraylike(\"std\", a)\nlax._check_user_dtype_supported(dtype, \"std\")\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.std is not supported.\")\n- return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))\n+ return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims, where=where))\n@_wraps(np.ptp)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -351,6 +351,17 @@ JAX_REDUCER_INITIAL_RECORDS = [\nop_record(\"min\", 1, all_dtypes, all_shapes, jtu.rand_default, []),\n]\n+JAX_REDUCER_WHERE_NO_INITIAL_RECORDS = [\n+ op_record(\"all\", 1, bool_dtypes, all_shapes, jtu.rand_some_zero, []),\n+ op_record(\"any\", 1, bool_dtypes, all_shapes, jtu.rand_some_zero, []),\n+ op_record(\"mean\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],\n+ inexact=True),\n+ op_record(\"var\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],\n+ inexact=True),\n+ op_record(\"std\", 1, all_dtypes, nonempty_shapes, jtu.rand_default, [],\n+ inexact=True),\n+]\n+\nJAX_REDUCER_NO_DTYPE_RECORDS = [\nop_record(\"all\", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),\nop_record(\"any\", 1, all_dtypes, all_shapes, jtu.rand_some_zero, []),\n@@ -853,6 +864,48 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\nself._CompileAndCheck(jnp_fun, args_maker)\n+ @unittest.skipIf(numpy_version < (1, 20), \"where parameter not supported in older numpy\")\n+ @parameterized.named_parameters(itertools.chain.from_iterable(\n+ jtu.cases_from_list(\n+ {\"testcase_name\": \"{}_inshape={}_axis={}_keepdims={}_whereshape={}\".format(\n+ rec.test_name.capitalize(),\n+ jtu.format_shape_dtype_string(shape, dtype), axis, keepdims,\n+ jtu.format_shape_dtype_string(whereshape, bool)),\n+ \"rng_factory\": rec.rng_factory, \"shape\": shape, \"dtype\": dtype,\n+ \"np_op\": getattr(np, rec.name), \"jnp_op\": getattr(jnp, rec.name), \"whereshape\": whereshape,\n+ \"axis\": axis, \"keepdims\": keepdims, \"inexact\": rec.inexact}\n+ for shape in rec.shapes for dtype in rec.dtypes\n+ for whereshape in _compatible_shapes(shape)\n+ for axis in list(range(-len(shape), len(shape))) + [None]\n+ for keepdims in [False, True])\n+ for rec in JAX_REDUCER_WHERE_NO_INITIAL_RECORDS))\n+ def testReducerWhereNoInitial(self, np_op, jnp_op, rng_factory, shape, dtype, axis,\n+ keepdims, inexact, whereshape):\n+ rng = rng_factory(self.rng())\n+ is_bf16_nan_test = dtype == jnp.bfloat16\n+ # Do not pass where via args_maker as that is incompatible with _promote_like_jnp.\n+ where = jtu.rand_bool(self.rng())(whereshape, np.bool_)\n+ @jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"Degrees of freedom <= 0 for slice.*\")\n+ @jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"Mean of empty slice.*\")\n+ @jtu.ignore_warning(category=RuntimeWarning,\n+ message=\"invalid value encountered in true_divide*\")\n+ def np_fun(x):\n+ x_cast = x if not is_bf16_nan_test else x.astype(np.float32)\n+ res = np_op(x_cast, axis, keepdims=keepdims, where=where)\n+ res = res if not is_bf16_nan_test else res.astype(jnp.bfloat16)\n+ return res\n+\n+ np_fun = _promote_like_jnp(np_fun, inexact)\n+ np_fun = jtu.ignore_warning(category=np.ComplexWarning)(np_fun)\n+ jnp_fun = lambda x: jnp_op(x, axis, keepdims=keepdims, where=where)\n+ jnp_fun = jtu.ignore_warning(category=jnp.ComplexWarning)(jnp_fun)\n+ args_maker = lambda: [rng(shape, dtype)]\n+ if numpy_version >= (1, 20, 2) or np_op.__name__ in (\"all\", \"any\"):\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker)\n+ self._CompileAndCheck(jnp_fun, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_axis={}\".format(\njtu.format_shape_dtype_string(shape, dtype), axis),\n" } ]
Python
Apache License 2.0
google/jax
Added 'where' keyword to 'jnp.{mean, var, std}'
260,490
15.03.2021 23:26:31
14,400
9d28b67022030d324f501339e1032ce72de2e8ab
Fixed two small typos in jax.lax.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3848,7 +3848,7 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nraise TypeError(msg.format(start_indices, operand.shape))\nif len(start_indices) != len(limit_indices):\nmsg = (\"slice limit_indices must have the same length as start_indices, \"\n- \"got start_inidices {} and limit_indices {}.\")\n+ \"got start_indices {} and limit_indices {}.\")\nraise TypeError(msg.format(start_indices, limit_indices))\nif (not masking.is_polymorphic(limit_indices) and\nnot masking.is_polymorphic(operand.shape) and\n@@ -3948,7 +3948,7 @@ def _dynamic_slice_shape_rule(operand, *start_indices, slice_sizes):\nraise TypeError(msg.format(start_indices, operand.shape))\nif len(start_indices) != len(slice_sizes):\nmsg = (\"dynamic_slice slice_sizes must have the same length as \"\n- \"start_indices, got start_inidices length {} and slice_sizes {}.\")\n+ \"start_indices, got start_indices length {} and slice_sizes {}.\")\nraise TypeError(msg.format(len(start_indices), slice_sizes))\nif not np.all(np.less_equal(slice_sizes, operand.shape)):\nmsg = (\"slice slice_sizes must be less than or equal to operand shape, \"\n" } ]
Python
Apache License 2.0
google/jax
Fixed two small typos in jax.lax.
260,411
16.03.2021 11:38:57
-3,600
840d5162030576d45edb7830408fdf867b8ff6b8
[jax2tf] Removed more traces of support for batch polymorphism See issue * Also cleanup the examples
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -152,7 +152,7 @@ for CUDA. One must be mindful to install a version of CUDA that is compatible\nwith both [jaxlib](https://github.com/google/jax/blob/master/README.md#pip-installation) and\n[TensorFlow](https://www.tensorflow.org/install/source#tested_build_configurations).\n-As of today, the tests are run using `tf_nightly==2.5.0-dev20210223`.\n+As of today, the tests are run using `tf_nightly==2.5.0-dev20210315`.\n## Caveats\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -131,10 +131,10 @@ following sequence of steps:\n* optionally plot images with the training digits and the inference results.\n-There are a number of flags to select the Flax model (`--model=mnist_flag`),\n+There are a number of flags to select the Flax model (`--model=mnist_flax`),\nto skip the training and just test a previously loaded\nSavedModel (`--nogenerate_model`), to choose the saving path, etc.\n-The default saving location is `/tmp/jax2tf/saved_models/1`.\n+The default saving location is `/tmp/jax2tf/saved_models/`.\nBy default, this example will convert the inference function for three separate\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "new_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "diff": "@@ -20,6 +20,7 @@ See README.md for how these are used.\n\"\"\"\nimport functools\nimport logging\n+import re\nimport time\nfrom typing import Any, Callable, Optional, Sequence, Tuple\nfrom absl import flags\n@@ -63,7 +64,18 @@ def load_mnist(split: tfds.Split, batch_size: int):\n\"\"\"\nif FLAGS.mock_data:\nwith tfds.testing.mock_data(num_examples=batch_size):\n+ try:\nds = tfds.load(\"mnist\", split=split)\n+ except Exception as e:\n+ m = re.search(r'metadata files were not found in (.+/)mnist/', str(e))\n+ if m:\n+ msg = (\"TFDS mock_data is missing the mnist metadata files. Run the \"\n+ \"`saved_model_main.py` binary and see where TFDS downloads \"\n+ \"the mnist data set (typically ~/tensorflow_datasets/mnist). \"\n+ f\"Copy the `mnist` directory to {m.group(1)} and re-run the test\")\n+ raise ValueError(msg) from e\n+ else:\n+ raise e\nelse:\nds = tfds.load(\"mnist\", split=split)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "diff": "@@ -37,7 +37,6 @@ def convert_and_save_model(\nmodel_dir: str,\n*,\ninput_signatures: Sequence[tf.TensorSpec],\n- shape_polymorphic_input_spec: Optional[str] = None,\nwith_gradient: bool = False,\nenable_xla: bool = True,\ncompile_model: bool = True,\n@@ -75,12 +74,6 @@ def convert_and_save_model(\nthe default serving signature. The additional signatures will be used\nonly to ensure that the `jax_fn` is traced and converted to TF for the\ncorresponding input shapes.\n- shape_polymorphic_input_spec: if given then it will be used as the\n- `in_shapes` argument to jax2tf.convert for the second parameter of\n- `jax_fn`. In this case, a single `input_signatures` is supported, and\n- should have `None` in the polymorphic dimensions. Should be a string, or a\n- (nesteD) tuple/list/dictionary thereof with a structure matching the\n- second argument of `jax_fn`.\nwith_gradient: whether the SavedModel should support gradients. If True,\nthen a custom gradient is saved. If False, then a\ntf.raw_ops.PreventGradient is saved to error if a gradient is attempted.\n@@ -95,14 +88,9 @@ def convert_and_save_model(\n\"\"\"\nif not input_signatures:\nraise ValueError(\"At least one input_signature must be given\")\n- if shape_polymorphic_input_spec is not None:\n- if len(input_signatures) > 1:\n- raise ValueError(\"For shape-polymorphic conversion a single \"\n- \"input_signature is supported.\")\ntf_fn = jax2tf.convert(\njax_fn,\nwith_gradient=with_gradient,\n- in_shapes=[None, shape_polymorphic_input_spec],\nenable_xla=enable_xla)\n# Create tf.Variables for the parameters. If you want more useful variable\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "By default, uses a pure JAX implementation of MNIST. There are flags to choose\na Flax CNN version of MNIST, or to skip the training and just test a\n-previously saved SavedModel. It is possible to save a batch-polymorphic\n-version of the model, or a model prepared for specific batch sizes.\n+previously saved SavedModel.\n+\nTry --help to see all flags.\nThis file is used both as an executable, and as a library in two other examples.\n@@ -36,8 +36,8 @@ import numpy as np\nimport tensorflow as tf # type: ignore\nimport tensorflow_datasets as tfds # type: ignore\n-flags.DEFINE_string(\"model\", \"mnist_pure_jax\",\n- \"Which model to use: mnist_pure_jax, mnist_flax.\")\n+flags.DEFINE_string(\"model\", \"mnist_flax\",\n+ \"Which model to use: mnist_flax, mnist_pure_jax.\")\nflags.DEFINE_boolean(\"model_classifier_layer\", True,\n(\"The model should include the classifier layer, or just \"\n\"the last layer of logits. Set this to False when you \"\n@@ -49,7 +49,8 @@ flags.DEFINE_integer(\"model_version\", 1,\n(\"The version number for the SavedModel. Needed for \"\n\"serving, larger versions will take precedence\"))\nflags.DEFINE_integer(\"serving_batch_size\", 1,\n- (\"For what batch size to prepare the serving signature. \"))\n+ \"For what batch size to prepare the serving signature. \",\n+ lower_bound=1)\nflags.DEFINE_integer(\"num_epochs\", 3, \"For how many epochs to train.\")\nflags.DEFINE_boolean(\n\"generate_model\", True,\n@@ -91,13 +92,6 @@ def train_and_save():\nFLAGS.num_epochs,\nwith_classifier=FLAGS.model_classifier_layer)\n- if FLAGS.serving_batch_size == -1:\n- # Batch-polymorphic SavedModel\n- input_signatures = [\n- tf.TensorSpec((None,) + mnist_lib.input_shape, tf.float32),\n- ]\n- shape_polymorphic_input_spec = \"(batch, _, _, _)\"\n- else:\ninput_signatures = [\n# The first one will be the serving signature\ntf.TensorSpec((FLAGS.serving_batch_size,) + mnist_lib.input_shape,\n@@ -107,14 +101,13 @@ def train_and_save():\ntf.TensorSpec((mnist_lib.test_batch_size,) + mnist_lib.input_shape,\ntf.float32),\n]\n- shape_polymorphic_input_spec = None\n+\nlogging.info(f\"Saving model for {model_descr}\")\nsaved_model_lib.convert_and_save_model(\npredict_fn,\npredict_params,\nmodel_dir,\ninput_signatures=input_signatures,\n- shape_polymorphic_input_spec=shape_polymorphic_input_spec,\ncompile_model=FLAGS.compile_model)\nif FLAGS.test_savedmodel:\n@@ -168,8 +161,8 @@ def model_description() -> str:\ndef savedmodel_dir(with_version: bool = True) -> str:\n\"\"\"The directory where we save the SavedModel.\"\"\"\nmodel_dir = os.path.join(\n- FLAGS.model_path,\n- f\"{'mnist' if FLAGS.model_classifier_layer else 'mnist_features'}\"\n+ FLAGS.model_path, FLAGS.model,\n+ FLAGS.model + ('' if FLAGS.model_classifier_layer else '_features')\n)\nif with_version:\nmodel_dir = os.path.join(model_dir, str(FLAGS.model_version))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "diff": "@@ -36,15 +36,15 @@ class SavedModelMainTest(tf_test_util.JaxToTfTestCase):\nFLAGS.test_savedmodel = True\nFLAGS.mock_data = True\n- @parameterized.named_parameters(\n- dict(\n- testcase_name=f\"_{model}_batch={serving_batch_size}\",\n- model=model,\n- serving_batch_size=serving_batch_size)\n- for model in [\"mnist_pure_jax\", \"mnist_flax\"]\n- for serving_batch_size in [1])\n+ # @parameterized.named_parameters(\n+ # dict(\n+ # testcase_name=f\"_{model}_batch={serving_batch_size}\",\n+ # model=model,\n+ # serving_batch_size=serving_batch_size)\n+ # for model in [\"mnist_pure_jax\", \"mnist_flax\"]\n+ # for serving_batch_size in [1])\ndef test_train_and_save_full(self,\n- model=\"mnist_pure_jax\",\n+ model=\"mnist_flax\",\nserving_batch_size=1):\nFLAGS.model = model\nFLAGS.model_classifier_layer = True\n@@ -54,7 +54,7 @@ class SavedModelMainTest(tf_test_util.JaxToTfTestCase):\n@parameterized.named_parameters(\ndict(testcase_name=f\"_{model}\", model=model)\nfor model in [\"mnist_pure_jax\", \"mnist_flax\"])\n- def test_train_and_save_features(self, model=\"mnist_pure_jax\"):\n+ def test_train_and_save_features(self, model=\"mnist_flax\"):\nFLAGS.model = model\nFLAGS.model_classifier_layer = False\nsaved_model_main.train_and_save()\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tflite/README.md", "new_path": "jax/experimental/jax2tf/examples/tflite/README.md", "diff": "-This directory contains examples of using the jax2tf converter to produce models that can be used with TensorFlow Lite. Note that this is still highly experimental.\n\\ No newline at end of file\n+This directory contains examples of using the jax2tf converter to produce\n+models that can be used with TensorFlow Lite.\n+Note that this is still highly experimental.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -130,37 +130,7 @@ def convert(fun: Callable, *,\nJAX arrays, or (nested) standard Python containers (tuple/list/dict)\nthereof.\n- in_shapes: an optional sequence of shape specifications,\n- one for each argument of the function to be converted. Default is a\n- list of `None`, in which case the argument shape specifications are taken\n- from the shapes of the actual arguments.\n-\n- A non-default `in_shapes` is needed sometimes when the actual arguments\n- have partially-specified shapes. If an argument is a pytree, then the\n- shape specification must be a matching pytree or `None`.\n- See [how optional parameters are matched to arguments](https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).\n- A shape specification should be a string, with comma-separated dimension\n- specifications, and optionally wrapped in parentheses. A dimension\n- specification is either a number, or the placeholder `_`, or a lowercase\n- word denoting a name for a dimension variable, or an arithmetic expression\n- with integer literals, dimension variables, and the operators `+` and `*`.\n- In presence of dimension variables, the conversion is done with a\n- shape abstraction that allows any concrete value for the variable.\n-\n- Examples of shape specifications:\n- * `[None, \"(batch, 16)\"]`: no specification for the first argument (takes\n- the shape from the actual argument); the second argument is a 2D\n- array with the first dimension size set to a variable `batch` and the\n- second dimension 16.\n- * `[\"(batch, _)\", \"(batch,)\"]`: the leading dimensions of the two arguments\n- must match. The second dimension of the first argument is taken from the\n- actual argument shape.\n- * `[(batch, 2 * batch)]`: a 2D matrix with the second dimension having\n- double the size of the first one.\n-\n- See [the README](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#shape-polymorphic-conversion)\n- for more details.\n-\n+ in_shapes: Not used. This is kept for backwards compatibility (see #6080).\nwith_gradient: if set, will add a tf.custom_gradient to the converted\nfunction, by converting the ``jax.vjp(fun)``. Only first-order\ndifferentiation is supported for now. If the converted function is\n@@ -212,11 +182,8 @@ def convert(fun: Callable, *,\nif in_shapes is None:\nin_shapes_ = (None,) * len(args)\nelse:\n- if not isinstance(in_shapes, Sequence) or len(args) != len(in_shapes):\n- msg = (\"in_shapes must be a sequence as long as the argument list \"\n- f\"({len(args)}). Got in_shapes={in_shapes}.\")\n- raise TypeError(msg)\n- in_shapes_ = tuple(in_shapes)\n+ raise ValueError(\"The `in_shapes` parameter is not supported\")\n+\n# Expand the in_shapes to match the argument pytree\nin_shapes_flat = tuple(api_util.flatten_axes(\"jax2tf.convert in_shapes\",\nin_tree.children()[0], in_shapes_))\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": "@@ -42,6 +42,9 @@ config.parse_flags_with_absl()\nclass ShapePolyTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ raise unittest.SkipTest(\"shape polymorphism not supported anymore. See #6080.\")\n+\ndef test_simple(self):\n\"\"\"Test shape polymorphism for a simple case.\"\"\"\ndef f_jax(x):\n@@ -333,6 +336,9 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nclass ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\n+ def setUp(self):\n+ raise unittest.SkipTest(\"shape polymorphism not supported anymore. See #6080.\")\n+\ndef test_concrete_shapes(self):\n# Test shape_as_value with concrete shapes. All transformations work.\ndef f(x):\n@@ -429,6 +435,9 @@ class ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n+ def setUp(self):\n+ raise unittest.SkipTest(\"shape polymorphism not supported anymore. See #6080.\")\n+\ndef test_matmul(self):\nraise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\ndef f_jax(x, y):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Removed more traces of support for batch polymorphism See issue #6080 * Also cleanup the examples
260,287
15.03.2021 13:23:21
0
92bca61737a434deb7500c86d8fe944a42a7e3fb
Fix incorrect handling of constants in xmap's partial_eval rule
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -659,7 +659,7 @@ core.axis_substitution_rules[xmap_p] = _xmap_axis_subst\ndef _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nfrom jax.interpreters.partial_eval import (\ntrace_to_subjaxpr_dynamic, DynamicJaxprTracer, source_info_util,\n- convert_constvars_jaxpr, call_param_updaters, new_jaxpr_eqn)\n+ convert_constvars_jaxpr, new_jaxpr_eqn)\nassert primitive is xmap_p\nin_avals = [t.aval for t in tracers]\naxis_sizes = params['axis_sizes']\n@@ -676,13 +676,12 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\ninvars = map(self.getvar, tracers)\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\n- new_in_axes = (None,) * len(consts) + params['in_axes']\n+ new_in_axes = (AxisNamePos(user_repr='{}'),) * len(consts) + params['in_axes']\n+ new_donated_invars = (False,) * len(consts) + params['donated_invars']\nnew_params = dict(params, in_axes=new_in_axes, out_axes=out_axes,\n+ donated_invars=new_donated_invars,\ncall_jaxpr=convert_constvars_jaxpr(jaxpr))\ndel new_params['out_axes_thunk']\n- update_params = call_param_updaters.get(primitive)\n- if update_params:\n- new_params = update_params(new_params, [True] * len(tracers))\neqn = new_jaxpr_eqn([*constvars, *invars], outvars, primitive,\nnew_params, source_info)\nself.frame.eqns.append(eqn)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -390,13 +390,14 @@ class XMapTest(XMapTestCase):\n@partial(xmap, in_axes={0: 'b'}, out_axes=({1: 'b'}, {}),\naxis_resources=dict([axis_resources[1]]))\ndef h(y):\n- return jnp.sin(y), lax.psum(y, ('a', 'b'))\n+ # Multiply by a constant array to better exercise the partial_eval rule\n+ return jnp.sin(y) * np.arange(y.size), lax.psum(y, ('a', 'b'))\nreturn h(y)\nxshape = (4, 2, 5)\nx = jnp.arange(np.prod(xshape)).reshape(xshape)\ny = f(x)\n- self.assertAllClose(y, (jnp.sin(x * 2).transpose((1, 2, 0)), (x * 2).sum((0, 1))))\n+ self.assertAllClose(y, ((jnp.sin(x * 2) * np.arange(xshape[-1])).transpose((1, 2, 0)), (x * 2).sum((0, 1))))\nself.assertEqual(y[0].sharding_spec.sharding,\n(pxla.Chunked([2]), pxla.NoSharding(), pxla.NoSharding()))\nself.assertEqual(y[0].sharding_spec.mesh_mapping,\n" } ]
Python
Apache License 2.0
google/jax
Fix incorrect handling of constants in xmap's partial_eval rule
260,335
17.03.2021 12:40:23
25,200
0181d03902dbc8e251e1b6b190d801f4f29c751e
add a memory leak test for jit jaxpr construction Tweak implementation for `_inline_literals` not to include a class defined in a function, since that seemed to cause leaking!
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -986,11 +986,8 @@ class JaxprStackFrame:\ndef _inline_literals(jaxpr, constvals):\nconsts = dict(zip(jaxpr.constvars, constvals))\nnewvar = core.gensym()\n- class var(dict):\n- def __missing__(self, v):\n- new_v = self[v] = newvar(v.aval)\n- return new_v\n- var = var()\n+ newvars = {}\n+ var = lambda v: newvars.get(v) or newvars.setdefault(v, newvar(v.aval))\ndef lit(var: core.Var) -> Optional[Any]:\nval = consts.get(var)\n@@ -1000,14 +997,14 @@ def _inline_literals(jaxpr, constvals):\nreturn None\nused = {v for eqn in jaxpr.eqns for v in eqn.invars} | set(jaxpr.outvars)\n- new_constvars = [var[v] for v in jaxpr.constvars if not lit(v)]\n+ new_constvars = [var(v) for v in jaxpr.constvars if not lit(v)]\nnew_constvals = [c for v, c in zip(jaxpr.constvars, constvals) if not lit(v)]\n- new_invars = [var[v] for v in jaxpr.invars]\n- new_eqns = [new_jaxpr_eqn([lit(v) or var[v] for v in eqn.invars],\n- [var[v] if v in used else dropvar for v in eqn.outvars],\n+ new_invars = [var(v) for v in jaxpr.invars]\n+ new_eqns = [new_jaxpr_eqn([lit(v) or var(v) for v in eqn.invars],\n+ [var(v) if v in used else dropvar for v in eqn.outvars],\neqn.primitive, eqn.params, eqn.source_info)\nfor eqn in jaxpr.eqns]\n- new_outvars = [lit(v) or var[v] for v in jaxpr.outvars]\n+ new_outvars = [lit(v) or var(v) for v in jaxpr.outvars]\nnew_jaxpr = Jaxpr(new_constvars, new_invars, new_outvars, new_eqns)\nreturn new_jaxpr, new_constvals\n" }, { "change_type": "MODIFY", "old_path": "tests/core_test.py", "new_path": "tests/core_test.py", "diff": "@@ -275,7 +275,24 @@ class CoreTest(jtu.JaxTestCase):\ntry:\nfn(params)\ngc.set_debug(gc.DEBUG_SAVEALL)\n- self.assertEqual(gc.collect(), 0)\n+ self.assertEqual(gc.collect(), 0, msg=str(gc.garbage))\n+ finally:\n+ gc.set_debug(debug)\n+\n+ def test_reference_cycles_jit(self):\n+ gc.collect()\n+\n+ def f(x):\n+ return x.sum()\n+\n+ fn = jit(f)\n+ params = jnp.zeros([])\n+\n+ debug = gc.get_debug()\n+ try:\n+ fn(params).block_until_ready()\n+ gc.set_debug(gc.DEBUG_SAVEALL)\n+ self.assertEqual(gc.collect(), 0, msg=str(gc.garbage))\nfinally:\ngc.set_debug(debug)\n" } ]
Python
Apache License 2.0
google/jax
add a memory leak test for jit jaxpr construction Tweak implementation for `_inline_literals` not to include a class defined in a function, since that seemed to cause leaking!
260,411
17.03.2021 08:40:48
-3,600
dace15572b2249684da8aa1b813f695ad6f21f28
[jax2tf] Added instructions for using OSS TensorFlow model server.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "new_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "diff": "@@ -178,8 +178,8 @@ class PureJaxMNIST:\ntest_acc = PureJaxMNIST.accuracy(PureJaxMNIST.predict, params, test_ds)\nlogging.info(\nf\"{PureJaxMNIST.name}: Epoch {epoch} in {epoch_time:0.2f} sec\")\n- logging.info(f\"{PureJaxMNIST.name}: Training set accuracy {train_acc}\")\n- logging.info(f\"{PureJaxMNIST.name}: Test set accuracy {test_acc}\")\n+ logging.info(f\"{PureJaxMNIST.name}: Training set accuracy {100. * train_acc:0.2f}%\")\n+ logging.info(f\"{PureJaxMNIST.name}: Test set accuracy {100. * test_acc:0.2f}%\")\nreturn (functools.partial(\nPureJaxMNIST.predict, with_classifier=with_classifier), params)\n@@ -269,8 +269,8 @@ class FlaxMNIST:\ntest_acc = PureJaxMNIST.accuracy(FlaxMNIST.predict, optimizer.target,\ntest_ds)\nlogging.info(f\"{FlaxMNIST.name}: Epoch {epoch} in {epoch_time:0.2f} sec\")\n- logging.info(f\"{FlaxMNIST.name}: Training set accuracy {train_acc}\")\n- logging.info(f\"{FlaxMNIST.name}: Test set accuracy {test_acc}\")\n+ logging.info(f\"{FlaxMNIST.name}: Training set accuracy {100. * train_acc:0.2f}%\")\n+ logging.info(f\"{FlaxMNIST.name}: Test set accuracy {100. * test_acc:0.2f}%\")\n# See discussion in README.md for packaging Flax models for conversion\npredict_fn = functools.partial(FlaxMNIST.predict,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "@@ -36,8 +36,8 @@ import numpy as np\nimport tensorflow as tf # type: ignore\nimport tensorflow_datasets as tfds # type: ignore\n-flags.DEFINE_string(\"model\", \"mnist_flax\",\n- \"Which model to use: mnist_flax, mnist_pure_jax.\")\n+flags.DEFINE_enum(\"model\", \"mnist_flax\", [\"mnist_flax\", \"mnist_pure_jax\"],\n+ \"Which model to use.\")\nflags.DEFINE_boolean(\"model_classifier_layer\", True,\n(\"The model should include the classifier layer, or just \"\n\"the last layer of logits. Set this to False when you \"\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/jax2tf/examples/serving/README.md", "diff": "+Using jax2tf with TensorFlow serving\n+====================================\n+\n+This is a supplement to the\n+[examples/README.md](https://g3doc.corp.google.com/third_party/py/jax/experimental/jax2tf/examples/README.md)\n+with example code and\n+instructions for using `jax2tf` with the OSS TensorFlow model server.\n+For Google-internal versions of model server, see the `internal` subdirectory.\n+\n+The goal of `jax2tf` is to convert JAX functions\n+into Python functions that behave as if they had been written with TensorFlow.\n+These functions can be tracerd and saved in a SavedModel using **standard TensorFlow\n+code, so the user has full control over what metadata is saved in the\n+SavedModel**.\n+\n+The only difference in the SavedModel produced with jax2tf is that the\n+function graphs may contain\n+[XLA TF ops](http://g3doc/third_party/py/jax/experimental/jax2tf/README.md#caveats)\n+that require enabling XLA for execution in the model server. This\n+is achieved using a command-line flag. There are no other differences compared\n+to using SavedModel produced by TensorFlow.\n+\n+This serving example uses\n+[saved_model_main.py](http://google3/third_party/py/jax/experimental/jax2tf/examples/saved_model_main.py)\n+for saving the SavedModel and adds code specific to interacting with the\n+model server:\n+[model_server_request.py](http://google3/third_party/py/jax/experimental/jax2tf/examples/serving/model_server_request.py).\n+\n+0. *Set up JAX and TensorFlow serving*.\n+\n+If you have already installed JAX and TensorFlow serving, you can skip most of these steps, but do set the\n+environment variables `JAX2TF_EXAMPLES` and `DOCKER_IMAGE`.\n+\n+The following will clone locally a copy of the JAX sources, and will install the `jax`, `jaxlib`, and `flax` packages.\n+We also need to install TensorFlow for the `jax2tf` feature and the rest of this example.\n+We use the `tf_nightly` package to get an up-to-date version.\n+\n+ ```shell\n+ git clone https://github.com/google/jax\n+ JAX2TF_EXAMPLES=$(pwd)/jax/jax/experimental/jax2tf/examples\n+ pip install -e jax\n+ pip install flax jaxlib tensorflow_datasets tensorflow_serving_api tf_nightly\n+ ```\n+\n+We then install [TensorFlow serving in a Docker image](https://www.tensorflow.org/tfx/serving/docker),\n+again using a recent \"nightly\" version. Install Docker and then run:\n+\n+ ```shell\n+ DOCKER_IMAGE=tensorflow/serving:nightly\n+ docker pull ${DOCKER_IMAGE}\n+ ```\n+\n+1. *Set some variables*.\n+\n+ ```shell\n+ # Shortcuts\n+ # Where to save SavedModels\n+ MODEL_PATH=/tmp/jax2tf/saved_models\n+ # The example model. The options are \"mnist_flax\" and \"mnist_pure_jax\"\n+ MODEL=mnist_flax\n+ # The batch size for the SavedModel.\n+ SERVING_BATCH_SIZE=1\n+ # Increment this when you make changes to the model parameters after the\n+ # initial model generation (Step 1 below).\n+ MODEL_VERSION=$(( 1 + ${MODEL_VERSION:-0} ))\n+ ```\n+\n+2. *Train and export a model.* You will use `saved_model_main.py` to train\n+ and export a SavedModel (see more details in README.md). Execute:\n+\n+ ```shell\n+ python ${JAX2TF_EXAMPLES}/saved_model_main.py --model=${MODEL} \\\n+ --model_path=${MODEL_PATH} --model_version=${MODEL_VERSION} \\\n+ --serving_batch_size=${SERVING_BATCH_SIZE} \\\n+ --compile_model \\\n+ --noshow_model\n+ ```\n+\n+ The SavedModel will be in ${MODEL_PATH}/${MODEL}/${MODEL_VERSION}.\n+ You can inspect the SavedModel.\n+\n+ ```shell\n+ saved_model_cli show --all --dir ${MODEL_PATH}/${MODEL}/${MODEL_VERSION}\n+ ```\n+\n+3. *Start a local model server* with XLA compilation enabled. Execute:\n+\n+ ```shell\n+ docker run -p 8500:8500 -p 8501:8501 \\\n+ --mount type=bind,source=${MODEL_PATH}/${MODEL}/,target=/models/${MODEL} \\\n+ -e MODEL_NAME=${MODEL} -t --rm --name=serving ${DOCKER_IMAGE} \\\n+ --xla_cpu_compilation_enabled=true &\n+ ```\n+\n+ Note that we are forwarding the ports 8500 (for the gRPC server) and\n+ 8501 (for the HTTP REST server).\n+\n+ You do not need to redo this step if you change the model parameters and\n+ regenerate the SavedModel, as long as you bumped the ${MODEL_VERSION}.\n+ The running model server will automatically load newer model versions.\n+\n+\n+4. *Send RPC requests.* Execute:\n+\n+ ```shell\n+ python ${JAX2TF_EXAMPLES}/serving/model_server_request.py --model_spec_name=${MODEL} \\\n+ --use_grpc --prediction_service_addr=localhost:8500 \\\n+ --serving_batch_size=${SERVING_BATCH_SIZE} \\\n+ --count_images=128\n+ ```\n+\n+ If you see an error `Input to reshape is a tensor with 12544 values, but the requested shape has 784`\n+ then your serving batch size is 16 (= 12544 / 784) while the model loaded\n+ in the model server has batch size 1 (= 784 / 784). You should check that\n+ you are using the same --serving_batch_size for the model generation and\n+ for sending the requests.\n+\n+5. *Experiment with different models and batch sizes*.\n+\n+ - You can set `MODEL=mnist_pure_jax` to use a simpler model, using just\n+ pure JAX, then restart from Step 1.\n+\n+ - You can change the batch size at which the model is converted from JAX\n+ and saved. Set `SERVING_BATCH_SIZE=16` and restart from Step 2.\n+ In Step 4, you should pass a `--count_images`\n+ parameter that is a multiple of the serving batch size you choose.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/jax2tf/examples/serving/model_server_request.py", "diff": "+# Copyright 2021 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+\"\"\"Demonstrates using jax2tf with TensorFlow model server.\n+\n+See README.md for instructions.\n+\"\"\"\n+import grpc\n+import json\n+import logging\n+import requests\n+\n+from absl import app\n+from absl import flags\n+\n+from jax.experimental.jax2tf.examples import mnist_lib\n+\n+import numpy as np\n+import tensorflow as tf # type: ignore\n+import tensorflow_datasets as tfds # type: ignore\n+from tensorflow_serving.apis import predict_pb2\n+from tensorflow_serving.apis import prediction_service_pb2_grpc\n+\n+\n+FLAGS = flags.FLAGS\n+\n+flags.DEFINE_boolean(\n+ \"use_grpc\", True,\n+ \"Use the gRPC API (default), or the HTTP REST API.\")\n+\n+flags.DEFINE_string(\n+ \"model_spec_name\", \"\",\n+ \"The name you used to export your model to model server (e.g., mnist_flax).\")\n+\n+flags.DEFINE_string(\n+ \"prediction_service_addr\",\n+ \"localhost:8500\",\n+ \"Stubby endpoint for the prediction service. If you serve your model \"\n+ \"locally using TensorFlow model server, then you can use \\\"locahost:8500\\\"\"\n+ \"for the gRPC server and \\\"localhost:8501\\\" for the HTTP REST server.\")\n+\n+flags.DEFINE_integer(\"serving_batch_size\", 1,\n+ \"Batch size for the serving request. Must match the \"\n+ \"batch size at which the model was saved. Must divide \"\n+ \"--count_images\",\n+ lower_bound=1)\n+flags.DEFINE_integer(\"count_images\", 16,\n+ \"How many images to test.\",\n+ lower_bound=1)\n+\n+\n+def serving_call_mnist(images):\n+ \"\"\"Send an RPC or REST request to the model server.\n+\n+ Args:\n+ images: A numpy.ndarray of shape [B, 28, 28, 1] with the batch of images to\n+ perform inference on.\n+\n+ Returns:\n+ A numpy.ndarray of shape [B, 10] with the one-hot inference response.\n+ \"\"\"\n+ if FLAGS.use_grpc:\n+ channel = grpc.insecure_channel(FLAGS.prediction_service_addr)\n+ stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)\n+\n+ request = predict_pb2.PredictRequest()\n+ request.model_spec.name = FLAGS.model_spec_name\n+ request.model_spec.signature_name = tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n+ # You can see the name of the input (\"inputs\") in the SavedModel dump.\n+ request.inputs[\"inputs\"].CopyFrom(\n+ tf.make_tensor_proto(images, dtype=images.dtype, shape=images.shape))\n+ response = stub.Predict(request)\n+ # We could also use response.outputs[\"output_0\"], where \"output_0\" is the\n+ # name of the output (which you can see in the SavedModel dump.)\n+ # Alternatively, we just get the first output.\n+ outputs, = response.outputs.values()\n+ return tf.make_ndarray(outputs)\n+ else:\n+ # Use the HTTP REST api\n+ images_json = json.dumps(images.tolist())\n+ # You can see the name of the input (\"inputs\") in the SavedModel dump.\n+ data = f'{{\"inputs\": {images_json}}}'\n+ predict_url = f\"http://{FLAGS.prediction_service_addr}/v1/models/{FLAGS.model_spec_name}:predict\"\n+ response = requests.post(predict_url, data=data)\n+ if response.status_code != 200:\n+ msg = (f\"Received error response {response.status_code} from model \"\n+ f\"server: {response.text}\")\n+ raise ValueError(msg)\n+ outputs = response.json()[\"outputs\"]\n+ return np.array(outputs)\n+\n+\n+def main(_):\n+ if FLAGS.count_images % FLAGS.serving_batch_size != 0:\n+ raise ValueError(f\"The count_images ({FLAGS.count_images}) must be a \"\n+ \"multiple of \"\n+ f\"serving_batch_size ({FLAGS.serving_batch_size})\")\n+ test_ds = mnist_lib.load_mnist(tfds.Split.TEST,\n+ batch_size=FLAGS.serving_batch_size)\n+ images_and_labels = tfds.as_numpy(test_ds.take(\n+ FLAGS.count_images // FLAGS.serving_batch_size))\n+\n+ accurate_count = 0\n+ for batch_idx, (images, labels) in enumerate(images_and_labels):\n+ predictions_one_hot = serving_call_mnist(images)\n+ predictions_digit = np.argmax(predictions_one_hot, axis=1)\n+ labels_digit = np.argmax(labels, axis=1)\n+ accurate_count += np.sum(labels_digit == predictions_digit)\n+ running_accuracy = (\n+ 100. * accurate_count / (1 + batch_idx) / FLAGS.serving_batch_size)\n+ logging.info(\n+ f\" predicted digits = {predictions_digit} labels {labels_digit}. \"\n+ f\"Running accuracy {running_accuracy:.3f}%\")\n+\n+\n+if __name__ == \"__main__\":\n+ app.run(main)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added instructions for using OSS TensorFlow model server.
260,411
18.03.2021 08:53:00
-3,600
917db30d9bc1c1eadb4c85f930caa6a8c6ac1714
Fix links and reviewer-suggested edits
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/serving/README.md", "new_path": "jax/experimental/jax2tf/examples/serving/README.md", "diff": "@@ -2,29 +2,29 @@ Using jax2tf with TensorFlow serving\n====================================\nThis is a supplement to the\n-[examples/README.md](https://g3doc.corp.google.com/third_party/py/jax/experimental/jax2tf/examples/README.md)\n+[examples/README.md](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/README.md)\nwith example code and\ninstructions for using `jax2tf` with the OSS TensorFlow model server.\n-For Google-internal versions of model server, see the `internal` subdirectory.\n+Specific instructions for Google-internal versions of model server are in the `internal` subdirectory.\nThe goal of `jax2tf` is to convert JAX functions\ninto Python functions that behave as if they had been written with TensorFlow.\n-These functions can be tracerd and saved in a SavedModel using **standard TensorFlow\n+These functions can be traced and saved in a SavedModel using **standard TensorFlow\ncode, so the user has full control over what metadata is saved in the\nSavedModel**.\nThe only difference in the SavedModel produced with jax2tf is that the\nfunction graphs may contain\n-[XLA TF ops](http://g3doc/third_party/py/jax/experimental/jax2tf/README.md#caveats)\n-that require enabling XLA for execution in the model server. This\n+[XLA TF ops](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#caveats)\n+that require enabling CPU/GPU XLA for execution in the model server. This\nis achieved using a command-line flag. There are no other differences compared\nto using SavedModel produced by TensorFlow.\nThis serving example uses\n-[saved_model_main.py](http://google3/third_party/py/jax/experimental/jax2tf/examples/saved_model_main.py)\n+[saved_model_main.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/saved_model_main.py)\nfor saving the SavedModel and adds code specific to interacting with the\nmodel server:\n-[model_server_request.py](http://google3/third_party/py/jax/experimental/jax2tf/examples/serving/model_server_request.py).\n+[model_server_request.py](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/serving/model_server_request.py).\n0. *Set up JAX and TensorFlow serving*.\n" } ]
Python
Apache License 2.0
google/jax
Fix links and reviewer-suggested edits
260,411
18.03.2021 10:23:28
-3,600
8f846a3aa96074bf5c9acdb7ccc88f9223cd429e
[host_callback] Enable configuring the outfeed receiver buffer size The C++ runtime is already configurable. We are adding here the ability to pass the configuration parameter by environment variable and commmand-line flag. Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -229,7 +229,8 @@ the send operations were performed on the device.\nThe host callback functions for multiple devices may be interleaved.\nThe data from the devices is received by separate threads managed by the JAX\nruntime (one thread per device). The runtime maintains a buffer of\n-configurable size. When the buffer is full, all the receiving threads are paused\n+configurable size (see the flag ``--jax_host_callback_max_queue_byte_size``).\n+When the buffer is full, all the receiving threads are paused\nwhich eventually pauses the computation on devices. The runtime has one\nadditional thread that invokes the Python user functions with the received data.\nIf the processing of the callbacks is slow, it may actually lead to the runtime\n@@ -342,7 +343,7 @@ from absl import logging\nfrom jax import api\nfrom jax import core\n-from jax.config import config, bool_env\n+from jax.config import config, bool_env, int_env\nfrom jax import custom_derivatives\nfrom jax import dtypes\nfrom jax import lax\n@@ -364,6 +365,15 @@ config.DEFINE_bool(\nbool_env('JAX_HOST_CALLBACK_INLINE', False),\nhelp='Inline the host_callback, if not in a staged context.'\n)\n+config.DEFINE_integer(\n+ 'jax_host_callback_max_queue_byte_size',\n+ int_env('JAX_HOST_CALLBACK_MAX_QUEUE_BYTE_SIZE', int(256 * 1e6)),\n+ help=('The size in bytes of the buffer used to hold outfeeds from each '\n+ 'device. When this capacity is reached consuming outfeeds from the '\n+ 'device is paused, thus potentially pausing the device computation, '\n+ 'until the Python callback consume more outfeeds.'),\n+ lower_bound=int(16 * 1e6)\n+)\ndef inline_host_callback() -> bool:\ntry:\n@@ -545,7 +555,9 @@ def _call(callback_func: Callable, arg, *,\nresult_shape=None,\ncall_with_device=False,\nidentity=False):\n- _initialize_outfeed_receiver() # Lazy initialization\n+ # Lazy initialization\n+ _initialize_outfeed_receiver(\n+ max_callback_queue_size_bytes=FLAGS.jax_host_callback_max_queue_byte_size)\napi._check_callable(callback_func)\nflat_args, arg_treedef = pytree.flatten(arg)\nfor arg in flat_args:\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Enable configuring the outfeed receiver buffer size The C++ runtime is already configurable. We are adding here the ability to pass the configuration parameter by environment variable and commmand-line flag. Fixes: #5782
260,411
18.03.2021 11:09:33
-3,600
52408b35a8943ee69ba709f6ba7f9792924d27be
Move the flag definitions to config Without this when running tests the flag parsing may happen before the host_callback module is loaded and then the host_callback flags may be left undefined.
[ { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -191,3 +191,18 @@ flags.DEFINE_bool(\n'Enabling leak checking may have performance impacts: some caching '\n'is disabled, and other overheads may be added.'),\n)\n+\n+flags.DEFINE_bool(\n+ 'jax_host_callback_inline',\n+ bool_env('JAX_HOST_CALLBACK_INLINE', False),\n+ help='Inline the host_callback, if not in a staged context.'\n+)\n+flags.DEFINE_integer(\n+ 'jax_host_callback_max_queue_byte_size',\n+ int_env('JAX_HOST_CALLBACK_MAX_QUEUE_BYTE_SIZE', int(256 * 1e6)),\n+ help=('The size in bytes of the buffer used to hold outfeeds from each '\n+ 'device. When this capacity is reached consuming outfeeds from the '\n+ 'device is paused, thus potentially pausing the device computation, '\n+ 'until the Python callback consume more outfeeds.'),\n+ lower_bound=int(16 * 1e6)\n+)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -360,28 +360,6 @@ import numpy as np\nFLAGS = config.FLAGS\n-config.DEFINE_bool(\n- 'jax_host_callback_inline',\n- bool_env('JAX_HOST_CALLBACK_INLINE', False),\n- help='Inline the host_callback, if not in a staged context.'\n-)\n-config.DEFINE_integer(\n- 'jax_host_callback_max_queue_byte_size',\n- int_env('JAX_HOST_CALLBACK_MAX_QUEUE_BYTE_SIZE', int(256 * 1e6)),\n- help=('The size in bytes of the buffer used to hold outfeeds from each '\n- 'device. When this capacity is reached consuming outfeeds from the '\n- 'device is paused, thus potentially pausing the device computation, '\n- 'until the Python callback consume more outfeeds.'),\n- lower_bound=int(16 * 1e6)\n-)\n-\n-def inline_host_callback() -> bool:\n- try:\n- return FLAGS.jax_host_callback_inline\n- except AttributeError:\n- # TODO: I cannot get this flag to be seen for py3.6 tests in Github\n- return False\n-\nxops = xla_client._xla.ops\n# TODO(necula): fix mypy errors if I define the type aliases below\n@@ -774,7 +752,7 @@ outside_call_p.def_abstract_eval(_outside_call_abstract_eval)\ndef _outside_call_impl(*args, **params):\nassert not \"has_token\" in params\n- if inline_host_callback():\n+ if FLAGS.jax_host_callback_inline:\ndevice = api.devices()[0]\nresults = _outside_call_run_callback(args, device, send_infeed=False, **params)\nreturn results\n" } ]
Python
Apache License 2.0
google/jax
Move the flag definitions to config Without this when running tests the flag parsing may happen before the host_callback module is loaded and then the host_callback flags may be left undefined.
260,424
18.03.2021 17:32:33
0
d86dd24bf8c9341fbe2ebb54900fc71606f5d09b
Make sublevel weak-referable, and enable the leak checker on sublevels. Reimplement Sublevel to not inherit from `int`. See docs on weakref: "CPython implementation detail: Other built-in types such as tuple and int do not support weak references even when subclassed."
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -688,7 +688,23 @@ class TraceStack:\nnew.dynamic = self.dynamic\nreturn new\n-class Sublevel(int): pass\n+\n+@total_ordering\n+class Sublevel:\n+\n+ def __init__(self, level: int):\n+ self.level = level\n+\n+ def __repr__(self):\n+ return str(self.level)\n+\n+ def __eq__(self, other):\n+ return type(other) is Sublevel and self.level == other.level\n+\n+ def __lt__(self, other):\n+ return type(other) is Sublevel and self.level < other.level\n+\n+\nAxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'main_trace'])\nAxisName = Hashable\n@@ -793,12 +809,11 @@ def new_sublevel() -> Generator[None, None, None]:\nfinally:\nthread_local_state.trace_state.substack.pop()\n- # TODO(mattjj): to check sublevel leaks, we need to make Sublevel weakref-able\n- # if debug_state.check_leaks:\n- # t = ref(sublevel)\n- # del sublevel\n- # if t() is not None:\n- # raise Exception('Leaked sublevel {}'.format(t()))\n+ if debug_state.check_leaks:\n+ t = ref(sublevel)\n+ del sublevel\n+ if t() is not None:\n+ raise Exception(f'Leaked sublevel {t()}.')\ndef maybe_new_sublevel(trace):\n# dynamic traces run the WrappedFun, so we raise the sublevel for them\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2329,6 +2329,25 @@ class APITest(jtu.JaxTestCase):\nlax.scan(to_scan, x, None, length=1)\nf(np.arange(5.)) # doesn't crash\n+ def test_leak_checker_catches_a_sublevel_leak(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ @jit\n+ def f(x):\n+ lst = []\n+ @jit\n+ def g(x):\n+ lst.append(x)\n+ return x\n+\n+ x = g(x)\n+ return x\n+\n+ with self.assertRaisesRegex(Exception, r\"Leaked sublevel\"):\n+ f(3)\n+\ndef test_default_backend(self):\nfirst_local_device = api.local_devices()[0]\nself.assertEqual(first_local_device.platform, api.default_backend())\n" } ]
Python
Apache License 2.0
google/jax
Make sublevel weak-referable, and enable the leak checker on sublevels. Reimplement Sublevel to not inherit from `int`. See docs on weakref: "CPython implementation detail: Other built-in types such as tuple and int do not support weak references even when subclassed."
260,287
18.03.2021 11:53:10
25,200
79040f109ea8ef7d7dc299314f2af742dd174ec3
Reenable multi-host xmap Apparently the implementation has regressed quite a bit since I've last tried it. Also added some tests to the internal CI (not visible on GitHub) to make sure that we don't regress again.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -16,7 +16,7 @@ import threading\nimport contextlib\nimport numpy as np\nimport itertools as it\n-from collections import OrderedDict\n+from collections import OrderedDict, namedtuple\nfrom typing import (Callable, Iterable, Tuple, Optional, Dict, Any, Set,\nNamedTuple, Union, Sequence)\nfrom warnings import warn\n@@ -98,7 +98,11 @@ class ResourceEnv:\n@property\ndef shape(self):\n- return OrderedDict(self.physical_mesh.shape)\n+ return self.physical_mesh.shape\n+\n+ @property\n+ def local_shape(self):\n+ return self.physical_mesh.local_mesh.shape\ndef __setattr__(self, name, value):\nraise RuntimeError(\"ResourceEnv is immutable!\")\n@@ -338,6 +342,8 @@ def xmap(fun: Callable,\naxis_sizes: A dict mapping axis names to their sizes. All axes defined by xmap\nhave to appear either in ``in_axes`` or ``axis_sizes``. Sizes of axes\nthat appear in ``in_axes`` are inferred from arguments whenever possible.\n+ In multi-host scenarios, the user-specified sizes are expected to be the\n+ global axis sizes (and might not match the expected size of local inputs).\naxis_resources: A dictionary mapping the axes introduced in this\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\n@@ -481,13 +487,25 @@ def xmap(fun: Callable,\nout_axes_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"xmap out_axes\", out_tree(), out_axes)),\nclosure=out_axes)\n- frozen_axis_sizes = FrozenDict(_get_axis_sizes(args_flat, in_axes_flat, axis_sizes))\n- missing_sizes = defined_names - set(frozen_axis_sizes.keys())\n+\n+ axis_resource_count = _get_axis_resource_count(normalized_axis_resources, resource_env)\n+ for axis, size in axis_sizes.items():\n+ resources = axis_resource_count[axis]\n+ if size % resources.nglobal != 0:\n+ global_size = \"Global size\" if resources.distributed else \"Size\"\n+ raise ValueError(f\"{global_size} of axis {axis} ({size}) is not divisible \"\n+ f\"by the total number of resources assigned to this axis \"\n+ f\"({normalized_axis_resources[axis]}, {resources.nglobal} in total)\")\n+ frozen_global_axis_sizes = _get_axis_sizes(args_flat, in_axes_flat,\n+ axis_sizes, axis_resource_count)\n+\n+ missing_sizes = defined_names - set(frozen_global_axis_sizes.keys())\nif missing_sizes:\nraise ValueError(f\"Failed to infer size of axes: {', '.join(unsafe_map(str, missing_sizes))}. \"\nf\"You've probably passed in empty containers in place of arguments that had \"\nf\"those axes in their in_axes. Provide the sizes of missing axes explicitly \"\nf\"via axis_sizes to fix this error.\")\n+\nif has_input_rank_assertions:\nfor arg, spec in zip(args_flat, in_axes_flat):\nif spec.expected_rank is not None and spec.expected_rank != arg.ndim:\n@@ -500,7 +518,7 @@ def xmap(fun: Callable,\nin_axes=tuple(in_axes_flat),\nout_axes_thunk=out_axes_thunk,\ndonated_invars=donated_invars,\n- axis_sizes=frozen_axis_sizes,\n+ global_axis_sizes=frozen_global_axis_sizes,\naxis_resources=frozen_axis_resources,\nresource_env=resource_env,\nbackend=backend)\n@@ -515,24 +533,24 @@ def xmap(fun: Callable,\nreturn fun_mapped\ndef xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes_thunk, donated_invars,\n- axis_sizes, axis_resources, resource_env, backend):\n+ global_axis_sizes, axis_resources, resource_env, backend):\nin_avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n- return make_xmap_callable(fun, name, in_axes, out_axes_thunk, donated_invars, axis_sizes,\n+ return make_xmap_callable(fun, name, in_axes, out_axes_thunk, donated_invars, global_axis_sizes,\naxis_resources, resource_env, backend, *in_avals)(*args)\n@lu.cache\ndef make_xmap_callable(fun: lu.WrappedFun,\nname,\nin_axes, out_axes_thunk, donated_invars,\n- axis_sizes, axis_resources, resource_env, backend,\n+ global_axis_sizes, axis_resources, resource_env, backend,\n*in_avals):\n- plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\n+ plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, global_axis_sizes)\n# TODO: Making axis substitution final style would allow us to avoid\n# tracing to jaxpr here\nmapped_in_avals = [_delete_aval_axes(aval, in_axes)\nfor aval, in_axes in zip(in_avals, in_axes)]\n- with core.extend_axis_env_nd(axis_sizes.items()):\n+ with core.extend_axis_env_nd(global_axis_sizes.items()):\njaxpr, _, consts = pe.trace_to_jaxpr_final(fun, mapped_in_avals)\nout_axes = out_axes_thunk()\njaxpr = core.subst_axis_names_jaxpr(jaxpr, plan.axis_subst)\n@@ -574,23 +592,20 @@ class EvaluationPlan(NamedTuple):\ndef from_axis_resources(cls,\naxis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]],\nresource_env: ResourceEnv,\n- axis_sizes: Dict[AxisName, int]):\n+ global_axis_sizes: Dict[AxisName, int]):\n# TODO: Support sequential resources\nphysical_axis_resources = axis_resources # NB: We only support physical resources at the moment\n- resource_shape = resource_env.shape\n+ axis_resource_count = _get_axis_resource_count(axis_resources, resource_env)\naxis_subst_dict = dict(axis_resources)\naxis_vmap_size: Dict[AxisName, Optional[int]] = {}\nfor naxis, raxes in axis_resources.items():\n- num_resources = int(np.prod([resource_shape[axes] for axes in raxes], dtype=np.int64))\n- if axis_sizes[naxis] % num_resources != 0:\n- raise ValueError(f\"Size of axis {naxis} ({axis_sizes[naxis]}) is not divisible \"\n- f\"by the total number of resources assigned to this axis ({raxes}, \"\n- f\"{num_resources} in total)\")\n- tile_size = axis_sizes[naxis] // num_resources\n+ num_resources = axis_resource_count[naxis]\n+ assert global_axis_sizes[naxis] % num_resources.nglobal == 0\n+ local_tile_size = global_axis_sizes[naxis] // num_resources.nglobal\n# We have to vmap when there are no resources (to handle the axis name!) or\n# when every resource gets chunks of values.\n- if not raxes or tile_size > 1:\n- axis_vmap_size[naxis] = tile_size\n+ if not raxes or local_tile_size > 1:\n+ axis_vmap_size[naxis] = local_tile_size\naxis_subst_dict[naxis] += (fresh_resource_name(naxis),)\nelse:\naxis_vmap_size[naxis] = None\n@@ -598,13 +613,13 @@ class EvaluationPlan(NamedTuple):\ndef vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\nfor naxis, raxes in self.axis_subst_dict.items():\n- tile_size = self.axis_vmap_size[naxis]\n- if tile_size is None:\n+ local_tile_size = self.axis_vmap_size[naxis]\n+ if local_tile_size is None:\ncontinue\nvaxis = raxes[-1]\nmap_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\n- f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=tile_size, axis_name=vaxis)\n+ f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=local_tile_size, axis_name=vaxis)\nreturn f\ndef to_mesh_axes(self, in_axes, out_axes):\n@@ -649,7 +664,7 @@ core.Trace.process_xmap = _process_xmap_default # type: ignore\ndef _xmap_axis_subst(params, subst):\ndef shadowed_subst(name):\n- return (name,) if name in params['axis_sizes'] else subst(name)\n+ return (name,) if name in params['global_axis_sizes'] else subst(name)\nnew_jaxpr = core.subst_axis_names_jaxpr(params['call_jaxpr'], shadowed_subst)\nreturn dict(params, call_jaxpr=new_jaxpr)\ncore.axis_substitution_rules[xmap_p] = _xmap_axis_subst\n@@ -662,14 +677,18 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nconvert_constvars_jaxpr, call_param_updaters, new_jaxpr_eqn)\nassert primitive is xmap_p\nin_avals = [t.aval for t in tracers]\n- axis_sizes = params['axis_sizes']\n+ global_axis_sizes = params['global_axis_sizes']\nmapped_in_avals = [_delete_aval_axes(a, a_in_axes)\nfor a, a_in_axes in zip(in_avals, params['in_axes'])]\n- with core.extend_axis_env_nd(params['axis_sizes'].items()):\n+ with core.extend_axis_env_nd(global_axis_sizes.items()):\njaxpr, mapped_out_avals, consts = trace_to_subjaxpr_dynamic(\nf, self.main, mapped_in_avals)\nout_axes = params['out_axes_thunk']()\n- out_avals = [_insert_aval_axes(a, a_out_axes, axis_sizes)\n+ axis_resource_count = _get_axis_resource_count(params['axis_resources'],\n+ params['resource_env'])\n+ local_axis_sizes = {axis: axis_resource_count[axis].to_local(global_size)\n+ for axis, global_size in global_axis_sizes.items()}\n+ out_avals = [_insert_aval_axes(a, a_out_axes, local_axis_sizes)\nfor a, a_out_axes in zip(mapped_out_avals, out_axes)]\nsource_info = source_info_util.current()\nout_tracers = [DynamicJaxprTracer(self, a, source_info) for a in out_avals]\n@@ -744,8 +763,15 @@ def _xmap_translation_rule_replica(c, axis_env,\nin_nodes, name_stack, *,\ncall_jaxpr, name,\nin_axes, out_axes, donated_invars,\n- axis_sizes, axis_resources, resource_env, backend):\n- plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\n+ global_axis_sizes,\n+ axis_resources, resource_env, backend):\n+ plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, global_axis_sizes)\n+\n+ axis_resource_count = _get_axis_resource_count(axis_resources, resource_env)\n+ if any(resource_count.distributed for resource_count in axis_resource_count.values()):\n+ raise NotImplementedError\n+ local_axis_sizes = {axis: axis_resource_count[axis].to_local(global_size)\n+ for axis, global_size in global_axis_sizes.items()}\nlocal_mesh = resource_env.physical_mesh.local_mesh\nlocal_mesh_shape = local_mesh.shape\n@@ -753,7 +779,7 @@ def _xmap_translation_rule_replica(c, axis_env,\nlocal_avals = [pxla.tile_aval_nd(\nlocal_mesh_shape, aval_mesh_in_axes,\n- _insert_aval_axes(v.aval, aval_in_axes, axis_sizes))\n+ _insert_aval_axes(v.aval, aval_in_axes, local_axis_sizes))\nfor v, aval_in_axes, aval_mesh_in_axes\nin zip(call_jaxpr.invars, in_axes, mesh_in_axes)]\n# We have to substitute before tracing, because we want the vectorized\n@@ -850,7 +876,8 @@ def _xmap_translation_rule_spmd(c, axis_env,\nin_nodes, name_stack, *,\ncall_jaxpr, name,\nin_axes, out_axes, donated_invars,\n- axis_sizes, axis_resources, resource_env, backend):\n+ global_axis_sizes,\n+ axis_resources, resource_env, backend):\n# TODO(apaszke): This is quite difficult to implement given the current\n# lowering in mesh_callable. There, we vmap the mapped axes,\n# but we have no idea which positional axes they end up being\n@@ -875,27 +902,60 @@ def _insert_aval_axes(aval, axes: AxisNamePos, axis_sizes):\nreturn aval.update(shape=tuple(shape))\n+class ResourceCount(namedtuple('ResourceCount', ['nglobal', 'nlocal'])):\n+ def to_local(self, global_size):\n+ assert global_size % self.nglobal == 0, \"Please report this issue!\"\n+ return (global_size // self.nglobal) * self.nlocal\n+\n+ def to_global(self, local_size):\n+ assert local_size % self.nlocal == 0, \"Please report this issue!\"\n+ return (local_size // self.nlocal) * self.nglobal\n+\n+ @property\n+ def distributed(self):\n+ return self.nglobal != self.nlocal\n+\n+\n+def _get_axis_resource_count(axis_resources, resource_env) -> Dict[AxisName, ResourceCount]:\n+ global_res_shape = resource_env.shape\n+ local_res_shape = resource_env.local_shape\n+ return {axis: ResourceCount(int(np.prod(map(global_res_shape.get, resources), dtype=np.int64)),\n+ int(np.prod(map(local_res_shape.get, resources), dtype=np.int64)))\n+ for axis, resources in axis_resources.items()}\n+\n+\ndef _get_axis_sizes(args_flat: Iterable[Any],\nin_axes_flat: Iterable[AxisNamePos],\n- axis_sizes: Dict[AxisName, int]):\n- axis_sizes = dict(axis_sizes)\n+ global_axis_sizes: Dict[AxisName, int],\n+ axis_resource_count: Dict[AxisName, ResourceCount]):\n+ global_axis_sizes = dict(global_axis_sizes)\nfor arg, in_axes in zip(args_flat, in_axes_flat):\nfor name, dim in in_axes.items():\n- if name in axis_sizes and axis_sizes[name] != arg.shape[dim]:\n- raise ValueError(f\"The size of axis {name} was previously inferred to be \"\n- f\"{axis_sizes[name]}, but found an argument of shape {arg.shape} \"\n- f\"with in_axes specification {in_axes.user_repr}. Shape mismatch \"\n- f\"occurs in dimension {dim}: {arg.shape[dim]} != {axis_sizes[name]}\")\n- else:\n+ resources = axis_resource_count[name]\n+ local_ = \"local \" if resources.distributed else \"\"\ntry:\n- axis_sizes[name] = arg.shape[dim]\n+ local_dim_size = arg.shape[dim]\nexcept IndexError:\n# TODO(apaszke): Handle negative indices. Check for overlap too!\nraise ValueError(f\"One of xmap arguments has an in_axes specification of \"\nf\"{in_axes.user_repr}, which implies that it has at least \"\nf\"{max(in_axes.values()) + 1} dimensions, but the argument \"\nf\"has rank {arg.ndim}\")\n- return axis_sizes\n+ if local_dim_size % resources.nlocal != 0:\n+ raise ValueError(f\"One of xmap arguments has an in_axes specification of \"\n+ f\"{in_axes.user_repr}, which implies that its size in dimension \"\n+ f\"{dim} ({local_dim_size}) should be divisible by the number of \"\n+ f\"{local_}resources assigned to axis {name} ({resources.nlocal})\")\n+ global_dim_size = resources.to_global(local_dim_size)\n+ if name in global_axis_sizes:\n+ expected_local_dim_size = resources.to_local(global_axis_sizes[name])\n+ if local_dim_size != expected_local_dim_size:\n+ raise ValueError(f\"The {local_}size of axis {name} was previously inferred to be \"\n+ f\"{expected_local_dim_size}, but found an argument of shape {arg.shape} \"\n+ f\"with in_axes specification {in_axes.user_repr}. Shape mismatch \"\n+ f\"occurs in dimension {dim}: {local_dim_size} != {expected_local_dim_size}\")\n+ global_axis_sizes[name] = global_dim_size\n+ return FrozenDict(global_axis_sizes)\ndef lookup_exactly_one_of(d: AxisNamePos, names: Set[AxisName]) -> Optional[int]:\n" } ]
Python
Apache License 2.0
google/jax
Reenable multi-host xmap Apparently the implementation has regressed quite a bit since I've last tried it. Also added some tests to the internal CI (not visible on GitHub) to make sure that we don't regress again. PiperOrigin-RevId: 363709635
260,424
18.03.2021 20:08:33
0
276645dd593466be695492073af6aa4d111ab1ab
Fix error when running a jvp of a jit of a custom_vjp. Error before: NotImplementedError: XLA translation rule for primitive 'custom_lin' not found Error after: TypeError: can't apply forward-mode autodiff (jvp) to a custom_vjp function.
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -671,6 +671,7 @@ xla.initial_style_translations[custom_vjp_call_jaxpr_p] = \\\nxla.lower_fun_initial_style(_custom_vjp_call_jaxpr_impl)\nbatching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\n+xla.translations[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\n@config.register_omnistaging_disabler\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3803,6 +3803,10 @@ class CustomVJPTest(jtu.JaxTestCase):\nTypeError,\nr\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\nlambda: api.jvp(api.vmap(f), (jnp.arange(3.),), (jnp.ones(3),)))\n+ self.assertRaisesRegex(\n+ TypeError,\n+ r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n+ lambda: api.jvp(jit(f), (3.,), (1.,)))\ndef test_kwargs(self):\n# from https://github.com/google/jax/issues/1938\n" } ]
Python
Apache License 2.0
google/jax
Fix error when running a jvp of a jit of a custom_vjp. Error before: NotImplementedError: XLA translation rule for primitive 'custom_lin' not found Error after: TypeError: can't apply forward-mode autodiff (jvp) to a custom_vjp function.
260,335
18.03.2021 18:05:22
25,200
ee4ec867ec94cc490f1213dddb6a65b99a624554
make constant handlers follow type mro fixes
[ { "change_type": "MODIFY", "old_path": "jax/lib/xla_bridge.py", "new_path": "jax/lib/xla_bridge.py", "diff": "@@ -29,11 +29,13 @@ from absl import logging\nlogging._warn_preinit_stderr = 0\nfrom ..config import flags\n-from jax._src import util\n+from jax._src import util, traceback_util\nfrom .. import dtypes\nimport numpy as np\nimport threading\n+traceback_util.register_exclusion(__file__)\n+\ntry:\nfrom . import tpu_client\nexcept ImportError:\n@@ -335,11 +337,12 @@ def constant(builder, py_val, canonicalize_types=True):\nReturns:\nA representation of the constant, either a ComputationDataHandle or None\n\"\"\"\n- py_type = type(py_val)\n- if py_type in _constant_handlers:\n- return _constant_handlers[py_type](builder, py_val, canonicalize_types)\n- else:\n- raise TypeError(\"No constant handler for type: {}\".format(py_type))\n+ for t in type(py_val).mro():\n+ handler = _constant_handlers.get(t)\n+ if handler: return handler(builder, py_val, canonicalize_types)\n+ if hasattr(py_val, '__jax_array__'):\n+ return constant(builder, py_val.__jax_array__(), canonicalize_types)\n+ raise TypeError(\"No constant handler for type: {}\".format(type(py_val)))\n# HLO instructions optionally can be annotated to say how the output should be\n# spatially partitioned (represented in XLA as OpSharding protos, see\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "import collections\nfrom contextlib import contextmanager\nimport copy\n+import enum\nfrom functools import partial\nimport re\nimport unittest\n@@ -2359,6 +2360,19 @@ class APITest(jtu.JaxTestCase):\nfor f in [jnp.isscalar, jnp.size, jnp.shape, jnp.dtype]:\nself.assertEqual(f(x), f(a))\n+ def test_constant_handler_mro(self):\n+ # https://github.com/google/jax/issues/6129\n+\n+ class Foo(enum.IntEnum):\n+ bar = 1\n+\n+ @api.pmap\n+ def f(_):\n+ return Foo.bar\n+\n+ ans = f(jnp.arange(1)) # doesn't crash\n+ expected = jnp.arange(1) + 1\n+ self.assertAllClose(ans, expected)\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
make constant handlers follow type mro fixes #6129
260,335
18.03.2021 18:56:47
25,200
90f8d1c8686be7e54132873d708c21a3ca2f0bcc
xla.flatten_shape don't use recursive generators This is an attempt to fix a strange memory leak failure which I can't reproduce directly but seems to fail consistently in Google internal CI.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -634,18 +634,19 @@ def flatten_shape(s: XlaShape) -> Sequence[Tuple[Sequence[int], XlaShape]]:\nAn iterable of pairs of indices and shapes for each array within the shape\ntree.\n\"\"\"\n- def _flatten_shape(s, index):\n- if s.is_array():\n- yield index, s\n+ results: List[Tuple[Tuple[int, ...], XlaShape]] = []\n+ _flatten_shape(s, (), results)\n+ return results\n+\n+def _flatten_shape(s: XlaShape, index: Tuple[int, ...],\n+ results: List[Tuple[Tuple[int, ...], XlaShape]]) -> None:\n+ if s.is_array() or s.is_token():\n+ results.append((index, s))\nelse:\nassert s.is_tuple()\nfor i, sub in enumerate(s.tuple_shapes()):\n- subindex = index + (i,)\n- if sub.is_tuple():\n- yield from _flatten_shape(sub, subindex)\n- else:\n- yield subindex, sub\n- return tuple(_flatten_shape(s, index=()))\n+ _flatten_shape(sub, index + (i,), results)\n+\ndef _xla_consts(c, consts):\nunique_consts = {id(const): const for const in consts}\n" } ]
Python
Apache License 2.0
google/jax
xla.flatten_shape don't use recursive generators This is an attempt to fix a strange memory leak failure which I can't reproduce directly but seems to fail consistently in Google internal CI.
260,335
18.03.2021 21:46:46
25,200
9802f3378edb66edaca52bfdcfc0cf773bd697a1
add simple single-primitive eager benchmarks
[ { "change_type": "MODIFY", "old_path": "benchmarks/api_benchmark.py", "new_path": "benchmarks/api_benchmark.py", "diff": "@@ -19,6 +19,7 @@ import google_benchmark\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n+from jax import lax\npartial = functools.partial\n@@ -36,6 +37,40 @@ def required_devices(num_devices_required):\nreturn helper1\n+@google_benchmark.register\n+def eager_unary_dispatch(state):\n+ a = jax.device_put(1)\n+ lax.neg(a)\n+ while state:\n+ lax.neg(a)\n+\n+\n+@google_benchmark.register\n+def eager_unary(state):\n+ a = jax.device_put(1)\n+ lax.neg(a).block_until_ready()\n+ while state:\n+ lax.neg(a).block_until_ready()\n+\n+\n+@google_benchmark.register\n+def eager_binary_dispatch(state):\n+ a = jax.device_put(1)\n+ b = jax.device_put(2)\n+ lax.add(a, b)\n+ while state:\n+ lax.add(a, b)\n+\n+\n+@google_benchmark.register\n+def eager_binary(state):\n+ a = jax.device_put(1)\n+ b = jax.device_put(2)\n+ lax.add(a, b).block_until_ready()\n+ while state:\n+ lax.add(a, b).block_until_ready()\n+\n+\n@google_benchmark.register\ndef jit_trivial_dispatch(state):\n\"\"\"Benchmarks only the duration for jitted_f to return the future.\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
add simple single-primitive eager benchmarks
260,335
19.03.2021 10:09:14
25,200
5c6ff67e4e042b64518ac03f7599039c99c35daa
generalize ravel_pytree to handle int types, add tests
[ { "change_type": "MODIFY", "old_path": "jax/flatten_util.py", "new_path": "jax/flatten_util.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import warnings\n+\n+import numpy as np\nfrom .tree_util import tree_flatten, tree_unflatten\n-from ._src.util import safe_zip\n+from ._src.util import safe_zip, unzip2\nimport jax.numpy as jnp\n-from jax.api import vjp\n+from jax import dtypes\n+from jax import lax\nzip = safe_zip\n@@ -26,18 +30,40 @@ def ravel_pytree(pytree):\n\"\"\"Ravel (i.e. flatten) a pytree of arrays down to a 1D array.\nArgs:\n- pytree: a pytree to ravel.\n+ pytree: a pytree of arrays and scalars to ravel.\nReturns:\nA pair where the first element is a 1D array representing the flattened and\n- concatenated leaf values, and the second element is a callable for\n- unflattening a 1D vector of the same length back to a pytree of of the same\n- structure as the input ``pytree``.\n+ concatenated leaf values, with dtype determined by promoting the dtypes of\n+ leaf values, and the second element is a callable for unflattening a 1D\n+ vector of the same length back to a pytree of of the same structure as the\n+ input ``pytree``. If the input pytree is empty (i.e. has no leaves) then as\n+ a convention a 1D empty array of dtype float32 is returned in the first\n+ component of the output.\n+\n+ For details on dtype promotion, see\n+ https://jax.readthedocs.io/en/latest/type_promotion.html.\n+\n\"\"\"\nleaves, treedef = tree_flatten(pytree)\n- flat, unravel_list = vjp(_ravel_list, *leaves)\n+ flat, unravel_list = _ravel_list(leaves)\nunravel_pytree = lambda flat: tree_unflatten(treedef, unravel_list(flat))\nreturn flat, unravel_pytree\n-def _ravel_list(*lst):\n- return jnp.concatenate([jnp.ravel(elt) for elt in lst]) if lst else jnp.array([])\n+def _ravel_list(lst):\n+ if not lst: return jnp.array([], jnp.float32), lambda _: []\n+ from_dtypes = [dtypes.dtype(l) for l in lst]\n+ to_dtype = dtypes.result_type(*from_dtypes)\n+ sizes, shapes = unzip2((jnp.size(x), jnp.shape(x)) for x in lst)\n+ indices = np.cumsum(sizes)\n+\n+ def unravel(arr):\n+ chunks = jnp.split(arr, indices[:-1])\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"ignore\") # ignore complex-to-real cast warning\n+ return [lax.convert_element_type(chunk.reshape(shape), dtype)\n+ for chunk, shape, dtype in zip(chunks, shapes, from_dtypes)]\n+\n+ ravel = lambda e: jnp.ravel(lax.convert_element_type(e, to_dtype))\n+ raveled = jnp.concatenate([ravel(e) for e in lst])\n+ return raveled, unravel\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_test.py", "new_path": "tests/tree_util_test.py", "diff": "@@ -20,6 +20,9 @@ from absl.testing import parameterized\nfrom jax import test_util as jtu\nfrom jax import tree_util\n+from jax import flatten_util\n+from jax import dtypes\n+import jax.numpy as jnp\ndef _dummy_func(*args, **kwargs):\n@@ -274,5 +277,56 @@ class TreeTest(jtu.JaxTestCase):\nFlatCache({\"a\": [3, 4], \"b\": [5, 6]}))\nself.assertEqual(expected, actual)\n+\n+class RavelUtilTest(jtu.JaxTestCase):\n+\n+ def testFloats(self):\n+ tree = [jnp.array([3.], jnp.float32),\n+ jnp.array([[1., 2.], [3., 4.]], jnp.float32)]\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, jnp.float32)\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+ def testInts(self):\n+ tree = [jnp.array([3], jnp.int32),\n+ jnp.array([[1, 2], [3, 4]], jnp.int32)]\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, jnp.int32)\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+ def testMixedFloatInt(self):\n+ tree = [jnp.array([3], jnp.int32),\n+ jnp.array([[1., 2.], [3., 4.]], jnp.float32)]\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, dtypes.promote_types(jnp.float32, jnp.int32))\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+ def testMixedIntBool(self):\n+ tree = [jnp.array([0], jnp.bool_),\n+ jnp.array([[1, 2], [3, 4]], jnp.int32)]\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, dtypes.promote_types(jnp.bool_, jnp.int32))\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+ def testMixedFloatComplex(self):\n+ tree = [jnp.array([1.], jnp.float32),\n+ jnp.array([[1, 2 + 3j], [3, 4]], jnp.complex64)]\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, dtypes.promote_types(jnp.float32, jnp.complex64))\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+ def testEmpty(self):\n+ tree = []\n+ raveled, unravel = flatten_util.ravel_pytree(tree)\n+ self.assertEqual(raveled.dtype, jnp.float32) # convention\n+ tree_ = unravel(raveled)\n+ self.assertAllClose(tree, tree_, atol=0., rtol=0.)\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
generalize ravel_pytree to handle int types, add tests
260,335
09.03.2021 15:58:39
28,800
bf15ba5310d5f9009571928f70548bcbc7e856c3
don't device transfer in convert_element_type
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -437,10 +437,8 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n- if not isinstance(operand, (core.Tracer, xla.DeviceArray)):\n- return _device_put_raw(np.asarray(operand, dtype=new_dtype),\n- weak_type=new_weak_type)\n- elif (old_dtype, old_weak_type) == (new_dtype, new_weak_type):\n+ if ((old_dtype, old_weak_type) == (new_dtype, new_weak_type)\n+ and isinstance(operand, (core.Tracer, xla.DeviceArray))):\nreturn operand\nelse:\nreturn convert_element_type_p.bind(operand, new_dtype=new_dtype,\n@@ -2687,10 +2685,13 @@ def _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nelse:\nreturn convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\n-convert_element_type_p = standard_primitive(\n+convert_element_type_p = core.convert_element_type_p\n+convert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n+convert_element_type_p.def_abstract_eval(\n+ partial(standard_abstract_eval, convert_element_type_p,\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n- 'convert_element_type', _convert_element_type_translation_rule,\n- weak_type_rule=_convert_element_type_weak_type_rule)\n+ _convert_element_type_weak_type_rule, standard_named_shape_rule))\n+xla.translations[convert_element_type_p] = _convert_element_type_translation_rule\nad.defjvp(convert_element_type_p, _convert_element_type_jvp_rule)\nad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpose_rule\nbatching.defvectorized(convert_element_type_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -156,13 +156,14 @@ def entr(x):\n@_wraps(osp_special.multigammaln, update_doc=False)\ndef multigammaln(a, d):\nd = core.concrete_or_error(int, d, \"d argument of multigammaln\")\n- a, d = _promote_args_inexact(\"multigammaln\", a, d)\n+ a, d_ = _promote_args_inexact(\"multigammaln\", a, d)\n- constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d),\n- lax.sub(d, _constant_like(a, 1))),\n+ constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d_),\n+ lax.sub(d_, _constant_like(a, 1))),\nlax.log(_constant_like(a, np.pi)))\nres = jnp.sum(gammaln(jnp.expand_dims(a, axis=-1) -\n- lax.div(jnp.arange(d), _constant_like(a, 2))),\n+ lax.div(jnp.arange(d, dtype=d_.dtype),\n+ _constant_like(a, 2))),\naxis=-1)\nreturn res + constant\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -978,6 +978,8 @@ def concrete_or_error(force: Any, val: Any, context=\"\"):\nelse:\nreturn force(val)\n+convert_element_type_p = Primitive('convert_element_type')\n+\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\narray_abstraction_level = 2\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1000,10 +1000,17 @@ def _inline_literals(jaxpr, constvals):\nnew_constvars = [var(v) for v in jaxpr.constvars if not lit(v)]\nnew_constvals = [c for v, c in zip(jaxpr.constvars, constvals) if not lit(v)]\nnew_invars = [var(v) for v in jaxpr.invars]\n- new_eqns = [new_jaxpr_eqn([lit(v) or var(v) for v in eqn.invars],\n- [var(v) if v in used else dropvar for v in eqn.outvars],\n- eqn.primitive, eqn.params, eqn.source_info)\n- for eqn in jaxpr.eqns]\n+ new_eqns = []\n+ for eqn in jaxpr.eqns:\n+ invars = [lit(v) or var(v) for v in eqn.invars]\n+ if (eqn.primitive is core.convert_element_type_p and type(invars[0]) is Literal):\n+ # constant-fold dtype conversion of literals to be inlined\n+ consts[eqn.outvars[0]] = np.array(invars[0].val, eqn.params['new_dtype'])\n+ else:\n+ # might do DCE here, but we won't until we're more careful about effects\n+ outvars = [var(v) if v in used else dropvar for v in eqn.outvars]\n+ new_eqns.append(new_jaxpr_eqn(invars, outvars, eqn.primitive, eqn.params,\n+ eqn.source_info))\nnew_outvars = [lit(v) or var(v) for v in jaxpr.outvars]\nnew_jaxpr = Jaxpr(new_constvars, new_invars, new_outvars, new_eqns)\nreturn new_jaxpr, new_constvals\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4671,49 +4671,40 @@ class CustomTransposeTest(jtu.JaxTestCase):\nclass InvertibleADTest(jtu.JaxTestCase):\n+ @jtu.ignore_warning(message=\"Values that an @invertible function closes\")\ndef test_invertible_basic(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"Test requires omnistaging\")\n+\ndef f(x):\nreturn (jnp.exp(x) * 4) * x\nfinv = jax.invertible(f)\n-\nx = jnp.ones((5,))\n- if config.omnistaging_enabled:\n- expected = \"\"\"\n- { lambda ; a b.\n- let c = exp a\n- d = mul c 4.0\n- e = mul d a\n- f = mul b a\n- g = div e a\n- h = mul b g\n- i = div g 4.0\n- j = mul f 4.0\n- _ = log i\n- k = mul j i\n- l = add_any h k\n- in (l,) }\n- \"\"\"\n- else:\n- expected = \"\"\"\n- { lambda ; a b.\n- let c = exp a\n- d = mul c 4.0\n- e = mul d a\n- f = div e a\n- g = mul b f\n- h = mul b a\n- i = mul h 4.0\n- j = div f 4.0\n- k = mul i j\n- l = add_any g k\n- in (l,) }\n- \"\"\"\n-\njaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n- self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n+ # expected = \"\"\"\n+ # { lambda ; a b.\n+ # let c = exp a\n+ # d = mul c 4.0\n+ # e = mul d a\n+ # f = mul b a\n+ # g = div e a\n+ # h = mul b g\n+ # i = mul f 4.0\n+ # j = div g 4.0\n+ # k = mul f j\n+ # _ = reduce_sum[ axes=(0,) ] k\n+ # _ = log j\n+ # l = mul i j\n+ # m = add_any h l\n+ # in (m,) }\n+ # \"\"\"\n+ # self.assertMultiLineStrippedEqual(expected, str(jaxpr)) # no jaxpr test\n+\n+ self.assertIn('div', str(jaxpr))\n+ self.assertIn('log', str(jaxpr)) # assumes no DCE\nself.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\njax.value_and_grad(lambda x: np.sum(finv(x)))(x),\ncheck_dtypes=True)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -969,18 +969,12 @@ class LaxRandomTest(jtu.JaxTestCase):\napi.jit(random.PRNGKey)(seed)\ndef test_random_split_doesnt_device_put_during_tracing(self):\n- raise SkipTest(\"broken test\") # TODO(mattjj): fix\n-\nif not config.omnistaging_enabled:\n- raise SkipTest(\"test is omnistaging-specific\")\n-\n- key = random.PRNGKey(1)\n+ raise SkipTest(\"test requires omnistaging\")\n+ key = random.PRNGKey(1).block_until_ready()\nwith jtu.count_device_put() as count:\napi.jit(random.split)(key)\n- key, _ = random.split(key, 2)\n- self.assertEqual(count[0], 1) # 1 for the argument device_put call\n-\n-\n+ self.assertEqual(count[0], 1) # 1 for the argument device_put\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
don't device transfer in convert_element_type Co-authored-by: Qiao Zhang <zhangqiaorjc@google.com>
260,631
19.03.2021 16:35:12
25,200
4f8814a760122450287eefe30a8e9fd16a83a412
Copybara import of the project: by Matthew Johnson don't device transfer in convert_element_type
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -437,8 +437,10 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n- if ((old_dtype, old_weak_type) == (new_dtype, new_weak_type)\n- and isinstance(operand, (core.Tracer, xla.DeviceArray))):\n+ if not isinstance(operand, (core.Tracer, xla.DeviceArray)):\n+ return _device_put_raw(np.asarray(operand, dtype=new_dtype),\n+ weak_type=new_weak_type)\n+ elif (old_dtype, old_weak_type) == (new_dtype, new_weak_type):\nreturn operand\nelse:\nreturn convert_element_type_p.bind(operand, new_dtype=new_dtype,\n@@ -2685,13 +2687,10 @@ def _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nelse:\nreturn convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\n-convert_element_type_p = core.convert_element_type_p\n-convert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n-convert_element_type_p.def_abstract_eval(\n- partial(standard_abstract_eval, convert_element_type_p,\n+convert_element_type_p = standard_primitive(\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n- _convert_element_type_weak_type_rule, standard_named_shape_rule))\n-xla.translations[convert_element_type_p] = _convert_element_type_translation_rule\n+ 'convert_element_type', _convert_element_type_translation_rule,\n+ weak_type_rule=_convert_element_type_weak_type_rule)\nad.defjvp(convert_element_type_p, _convert_element_type_jvp_rule)\nad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpose_rule\nbatching.defvectorized(convert_element_type_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -156,14 +156,13 @@ def entr(x):\n@_wraps(osp_special.multigammaln, update_doc=False)\ndef multigammaln(a, d):\nd = core.concrete_or_error(int, d, \"d argument of multigammaln\")\n- a, d_ = _promote_args_inexact(\"multigammaln\", a, d)\n+ a, d = _promote_args_inexact(\"multigammaln\", a, d)\n- constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d_),\n- lax.sub(d_, _constant_like(a, 1))),\n+ constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d),\n+ lax.sub(d, _constant_like(a, 1))),\nlax.log(_constant_like(a, np.pi)))\nres = jnp.sum(gammaln(jnp.expand_dims(a, axis=-1) -\n- lax.div(jnp.arange(d, dtype=d_.dtype),\n- _constant_like(a, 2))),\n+ lax.div(jnp.arange(d), _constant_like(a, 2))),\naxis=-1)\nreturn res + constant\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -978,8 +978,6 @@ def concrete_or_error(force: Any, val: Any, context=\"\"):\nelse:\nreturn force(val)\n-convert_element_type_p = Primitive('convert_element_type')\n-\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\narray_abstraction_level = 2\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1000,17 +1000,10 @@ def _inline_literals(jaxpr, constvals):\nnew_constvars = [var(v) for v in jaxpr.constvars if not lit(v)]\nnew_constvals = [c for v, c in zip(jaxpr.constvars, constvals) if not lit(v)]\nnew_invars = [var(v) for v in jaxpr.invars]\n- new_eqns = []\n- for eqn in jaxpr.eqns:\n- invars = [lit(v) or var(v) for v in eqn.invars]\n- if (eqn.primitive is core.convert_element_type_p and type(invars[0]) is Literal):\n- # constant-fold dtype conversion of literals to be inlined\n- consts[eqn.outvars[0]] = np.array(invars[0].val, eqn.params['new_dtype'])\n- else:\n- # might do DCE here, but we won't until we're more careful about effects\n- outvars = [var(v) if v in used else dropvar for v in eqn.outvars]\n- new_eqns.append(new_jaxpr_eqn(invars, outvars, eqn.primitive, eqn.params,\n- eqn.source_info))\n+ new_eqns = [new_jaxpr_eqn([lit(v) or var(v) for v in eqn.invars],\n+ [var(v) if v in used else dropvar for v in eqn.outvars],\n+ eqn.primitive, eqn.params, eqn.source_info)\n+ for eqn in jaxpr.eqns]\nnew_outvars = [lit(v) or var(v) for v in jaxpr.outvars]\nnew_jaxpr = Jaxpr(new_constvars, new_invars, new_outvars, new_eqns)\nreturn new_jaxpr, new_constvals\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4671,40 +4671,49 @@ class CustomTransposeTest(jtu.JaxTestCase):\nclass InvertibleADTest(jtu.JaxTestCase):\n- @jtu.ignore_warning(message=\"Values that an @invertible function closes\")\ndef test_invertible_basic(self):\n- if not config.omnistaging_enabled:\n- raise unittest.SkipTest(\"Test requires omnistaging\")\n-\ndef f(x):\nreturn (jnp.exp(x) * 4) * x\nfinv = jax.invertible(f)\n+\nx = jnp.ones((5,))\n+ if config.omnistaging_enabled:\n+ expected = \"\"\"\n+ { lambda ; a b.\n+ let c = exp a\n+ d = mul c 4.0\n+ e = mul d a\n+ f = mul b a\n+ g = div e a\n+ h = mul b g\n+ i = div g 4.0\n+ j = mul f 4.0\n+ _ = log i\n+ k = mul j i\n+ l = add_any h k\n+ in (l,) }\n+ \"\"\"\n+ else:\n+ expected = \"\"\"\n+ { lambda ; a b.\n+ let c = exp a\n+ d = mul c 4.0\n+ e = mul d a\n+ f = div e a\n+ g = mul b f\n+ h = mul b a\n+ i = mul h 4.0\n+ j = div f 4.0\n+ k = mul i j\n+ l = add_any g k\n+ in (l,) }\n+ \"\"\"\n+\njaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n+ self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n- # expected = \"\"\"\n- # { lambda ; a b.\n- # let c = exp a\n- # d = mul c 4.0\n- # e = mul d a\n- # f = mul b a\n- # g = div e a\n- # h = mul b g\n- # i = mul f 4.0\n- # j = div g 4.0\n- # k = mul f j\n- # _ = reduce_sum[ axes=(0,) ] k\n- # _ = log j\n- # l = mul i j\n- # m = add_any h l\n- # in (m,) }\n- # \"\"\"\n- # self.assertMultiLineStrippedEqual(expected, str(jaxpr)) # no jaxpr test\n-\n- self.assertIn('div', str(jaxpr))\n- self.assertIn('log', str(jaxpr)) # assumes no DCE\nself.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\njax.value_and_grad(lambda x: np.sum(finv(x)))(x),\ncheck_dtypes=True)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -969,12 +969,18 @@ class LaxRandomTest(jtu.JaxTestCase):\napi.jit(random.PRNGKey)(seed)\ndef test_random_split_doesnt_device_put_during_tracing(self):\n+ raise SkipTest(\"broken test\") # TODO(mattjj): fix\n+\nif not config.omnistaging_enabled:\n- raise SkipTest(\"test requires omnistaging\")\n- key = random.PRNGKey(1).block_until_ready()\n+ raise SkipTest(\"test is omnistaging-specific\")\n+\n+ key = random.PRNGKey(1)\nwith jtu.count_device_put() as count:\napi.jit(random.split)(key)\n- self.assertEqual(count[0], 1) # 1 for the argument device_put\n+ key, _ = random.split(key, 2)\n+ self.assertEqual(count[0], 1) # 1 for the argument device_put call\n+\n+\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- bf15ba5310d5f9009571928f70548bcbc7e856c3 by Matthew Johnson <mattjj@google.com>: don't device transfer in convert_element_type Co-authored-by: Qiao Zhang <zhangqiaorjc@google.com> PiperOrigin-RevId: 363995032
260,335
19.03.2021 22:35:31
25,200
57d5c6af5f6fb43579747d5102c2d1985f9f5279
add clz primitive
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -335,6 +335,10 @@ def population_count(x: Array) -> Array:\nr\"\"\"Elementwise popcount, count the number of set bits in each element.\"\"\"\nreturn population_count_p.bind(x)\n+def clz(x: Array) -> Array:\n+ r\"\"\"Elementwise count-leading-zeros.\"\"\"\n+ return clz_p.bind(x)\n+\ndef add(x: Array, y: Array) -> Array:\nr\"\"\"Elementwise addition: :math:`x + y`.\"\"\"\nreturn add_p.bind(x, y)\n@@ -2531,6 +2535,8 @@ ad.defjvp_zero(xor_p)\npopulation_count_p = standard_unop(_int, 'population_count')\n+clz_p = standard_unop(_int, 'clz')\n+\ndef _add_transpose(t, x, y):\n# The following linearity assertion is morally true, but because in some cases we\n# instantiate zeros for convenience, it doesn't always hold.\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -75,6 +75,7 @@ from jax._src.lax.lax import (\nceil_p,\nclamp,\nclamp_p,\n+ clz,\ncollapse,\ncomplex,\ncomplex_p,\n" }, { "change_type": "MODIFY", "old_path": "jax/lax_reference.py", "new_path": "jax/lax_reference.py", "diff": "@@ -149,6 +149,15 @@ def population_count(x):\nx = (x & m[5]) + ((x >> 32) & m[5]) # put count of each 64 bits into those 64 bits\nreturn x.astype(dtype)\n+def clz(x):\n+ assert np.issubdtype(x.dtype, np.integer)\n+ nbits = np.iinfo(x.dtype).bits\n+ mask = (2 ** np.arange(nbits, dtype=x.dtype))[::-1]\n+ bits = (x[..., None] & mask).astype(np.bool_)\n+ out = np.argmax(bits, axis=-1).astype(x.dtype)\n+ out[x == 0] = nbits\n+ return out\n+\neq = np.equal\nne = np.not_equal\nge = np.greater_equal\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -146,6 +146,7 @@ LAX_OPS = [\nop_record(\"bitwise_or\", 2, bool_dtypes, jtu.rand_small),\nop_record(\"bitwise_xor\", 2, bool_dtypes, jtu.rand_small),\nop_record(\"population_count\", 1, int_dtypes + uint_dtypes, jtu.rand_int),\n+ op_record(\"clz\", 1, int_dtypes + uint_dtypes, jtu.rand_int),\nop_record(\"add\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\nop_record(\"sub\", 2, default_dtypes + complex_dtypes, jtu.rand_small),\n" } ]
Python
Apache License 2.0
google/jax
add clz primitive
260,335
19.03.2021 23:13:20
25,200
97aca25ec48be0696e44cbf2f9547e44416e3ee3
tell jax2tf to ignore clz
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -797,7 +797,7 @@ for unexpected in xla.call_translations: # Call primitives are inlined\n# Primitives that are not yet implemented must be explicitly declared here.\ntf_not_yet_impl = [\n- \"reduce\", \"rng_uniform\",\n+ \"reduce\", \"rng_uniform\", \"clz\",\n\"igamma_grad_a\",\n\"random_gamma_grad\",\n" } ]
Python
Apache License 2.0
google/jax
tell jax2tf to ignore clz
260,335
21.03.2021 13:39:57
25,200
af59542d00fee4394ff24b70d41500e155a05a2a
Re-applying the changes in after they had to be rolled-back.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -441,10 +441,8 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n- if not isinstance(operand, (core.Tracer, xla.DeviceArray)):\n- return _device_put_raw(np.asarray(operand, dtype=new_dtype),\n- weak_type=new_weak_type)\n- elif (old_dtype, old_weak_type) == (new_dtype, new_weak_type):\n+ if ((old_dtype, old_weak_type) == (new_dtype, new_weak_type)\n+ and isinstance(operand, (core.Tracer, xla.DeviceArray))):\nreturn operand\nelse:\nreturn convert_element_type_p.bind(operand, new_dtype=new_dtype,\n@@ -2694,10 +2692,13 @@ def _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nelse:\nreturn convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\n-convert_element_type_p = standard_primitive(\n+convert_element_type_p = core.convert_element_type_p\n+convert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n+convert_element_type_p.def_abstract_eval(\n+ partial(standard_abstract_eval, convert_element_type_p,\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n- 'convert_element_type', _convert_element_type_translation_rule,\n- weak_type_rule=_convert_element_type_weak_type_rule)\n+ _convert_element_type_weak_type_rule, standard_named_shape_rule))\n+xla.translations[convert_element_type_p] = _convert_element_type_translation_rule\nad.defjvp(convert_element_type_p, _convert_element_type_jvp_rule)\nad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpose_rule\nbatching.defvectorized(convert_element_type_p)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -156,13 +156,14 @@ def entr(x):\n@_wraps(osp_special.multigammaln, update_doc=False)\ndef multigammaln(a, d):\nd = core.concrete_or_error(int, d, \"d argument of multigammaln\")\n- a, d = _promote_args_inexact(\"multigammaln\", a, d)\n+ a, d_ = _promote_args_inexact(\"multigammaln\", a, d)\n- constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d),\n- lax.sub(d, _constant_like(a, 1))),\n+ constant = lax.mul(lax.mul(lax.mul(_constant_like(a, 0.25), d_),\n+ lax.sub(d_, _constant_like(a, 1))),\nlax.log(_constant_like(a, np.pi)))\nres = jnp.sum(gammaln(jnp.expand_dims(a, axis=-1) -\n- lax.div(jnp.arange(d), _constant_like(a, 2))),\n+ lax.div(jnp.arange(d, dtype=d_.dtype),\n+ _constant_like(a, 2))),\naxis=-1)\nreturn res + constant\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -978,6 +978,8 @@ def concrete_or_error(force: Any, val: Any, context=\"\"):\nelse:\nreturn force(val)\n+convert_element_type_p = Primitive('convert_element_type')\n+\nclass UnshapedArray(AbstractValue):\n__slots__ = ['dtype', 'weak_type']\narray_abstraction_level = 2\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1000,10 +1000,17 @@ def _inline_literals(jaxpr, constvals):\nnew_constvars = [var(v) for v in jaxpr.constvars if not lit(v)]\nnew_constvals = [c for v, c in zip(jaxpr.constvars, constvals) if not lit(v)]\nnew_invars = [var(v) for v in jaxpr.invars]\n- new_eqns = [new_jaxpr_eqn([lit(v) or var(v) for v in eqn.invars],\n- [var(v) if v in used else dropvar for v in eqn.outvars],\n- eqn.primitive, eqn.params, eqn.source_info)\n- for eqn in jaxpr.eqns]\n+ new_eqns = []\n+ for eqn in jaxpr.eqns:\n+ invars = [lit(v) or var(v) for v in eqn.invars]\n+ if (eqn.primitive is core.convert_element_type_p and type(invars[0]) is Literal):\n+ # constant-fold dtype conversion of literals to be inlined\n+ consts[eqn.outvars[0]] = np.array(invars[0].val, eqn.params['new_dtype'])\n+ else:\n+ # might do DCE here, but we won't until we're more careful about effects\n+ outvars = [var(v) if v in used else dropvar for v in eqn.outvars]\n+ new_eqns.append(new_jaxpr_eqn(invars, outvars, eqn.primitive, eqn.params,\n+ eqn.source_info))\nnew_outvars = [lit(v) or var(v) for v in jaxpr.outvars]\nnew_jaxpr = Jaxpr(new_constvars, new_invars, new_outvars, new_eqns)\nreturn new_jaxpr, new_constvals\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4671,49 +4671,40 @@ class CustomTransposeTest(jtu.JaxTestCase):\nclass InvertibleADTest(jtu.JaxTestCase):\n+ @jtu.ignore_warning(message=\"Values that an @invertible function closes\")\ndef test_invertible_basic(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"Test requires omnistaging\")\n+\ndef f(x):\nreturn (jnp.exp(x) * 4) * x\nfinv = jax.invertible(f)\n-\nx = jnp.ones((5,))\n- if config.omnistaging_enabled:\n- expected = \"\"\"\n- { lambda ; a b.\n- let c = exp a\n- d = mul c 4.0\n- e = mul d a\n- f = mul b a\n- g = div e a\n- h = mul b g\n- i = div g 4.0\n- j = mul f 4.0\n- _ = log i\n- k = mul j i\n- l = add_any h k\n- in (l,) }\n- \"\"\"\n- else:\n- expected = \"\"\"\n- { lambda ; a b.\n- let c = exp a\n- d = mul c 4.0\n- e = mul d a\n- f = div e a\n- g = mul b f\n- h = mul b a\n- i = mul h 4.0\n- j = div f 4.0\n- k = mul i j\n- l = add_any g k\n- in (l,) }\n- \"\"\"\n-\njaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n- self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n+ # expected = \"\"\"\n+ # { lambda ; a b.\n+ # let c = exp a\n+ # d = mul c 4.0\n+ # e = mul d a\n+ # f = mul b a\n+ # g = div e a\n+ # h = mul b g\n+ # i = mul f 4.0\n+ # j = div g 4.0\n+ # k = mul f j\n+ # _ = reduce_sum[ axes=(0,) ] k\n+ # _ = log j\n+ # l = mul i j\n+ # m = add_any h l\n+ # in (m,) }\n+ # \"\"\"\n+ # self.assertMultiLineStrippedEqual(expected, str(jaxpr)) # no jaxpr test\n+\n+ self.assertIn('div', str(jaxpr))\n+ self.assertIn('log', str(jaxpr)) # assumes no DCE\nself.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\njax.value_and_grad(lambda x: np.sum(finv(x)))(x),\ncheck_dtypes=True)\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -969,18 +969,12 @@ class LaxRandomTest(jtu.JaxTestCase):\napi.jit(random.PRNGKey)(seed)\ndef test_random_split_doesnt_device_put_during_tracing(self):\n- raise SkipTest(\"broken test\") # TODO(mattjj): fix\n-\nif not config.omnistaging_enabled:\n- raise SkipTest(\"test is omnistaging-specific\")\n-\n- key = random.PRNGKey(1)\n+ raise SkipTest(\"test requires omnistaging\")\n+ key = random.PRNGKey(1).block_until_ready()\nwith jtu.count_device_put() as count:\napi.jit(random.split)(key)\n- key, _ = random.split(key, 2)\n- self.assertEqual(count[0], 1) # 1 for the argument device_put call\n-\n-\n+ self.assertEqual(count[0], 1) # 1 for the argument device_put\nif __name__ == \"__main__\":\n" } ]
Python
Apache License 2.0
google/jax
Re-applying the changes in #6014, after they had to be rolled-back. PiperOrigin-RevId: 364200195
260,335
21.03.2021 15:53:24
25,200
8c3125c172b5868c29fe58863457362cbd144f3d
fix convert_element_type on large Py int inputs
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2658,6 +2658,12 @@ lt_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'lt')\nad.defjvp_zero(lt_p)\n+def _convert_element_type_impl(operand, *, new_dtype, weak_type):\n+ if dtypes.is_python_scalar(operand):\n+ operand = np.asarray(operand, dtype=new_dtype)\n+ return xla.apply_primitive(convert_element_type_p, operand,\n+ new_dtype=new_dtype, weak_type=weak_type)\n+\ndef _convert_element_type_shape_rule(operand, *, new_dtype, weak_type):\nreturn operand.shape\n@@ -2693,7 +2699,7 @@ def _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nreturn convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\nconvert_element_type_p = core.convert_element_type_p\n-convert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n+convert_element_type_p.def_impl(_convert_element_type_impl)\nconvert_element_type_p.def_abstract_eval(\npartial(standard_abstract_eval, convert_element_type_p,\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n" }, { "change_type": "MODIFY", "old_path": "jax/abstract_arrays.py", "new_path": "jax/abstract_arrays.py", "diff": "@@ -68,8 +68,7 @@ def _zeros_like_python_scalar(t, x):\nreturn np.array(0, dtypes.python_scalar_dtypes[t])\ndef _make_concrete_python_scalar(t, x):\n- return ConcreteArray(\n- np.array(x, dtype=dtypes.python_scalar_dtypes[t]),\n+ return ConcreteArray(np.array(x, dtype=dtypes.python_scalar_dtypes[t]),\nweak_type=True)\nfor t in dtypes.python_scalar_dtypes:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -934,6 +934,7 @@ def _outside_call_jvp_rule(primals, tangents, **params):\nif not params[\"identity\"]:\nraise NotImplementedError(\"JVP rule is implemented only for id_tap, not for call.\")\ntangent_instantiated = tuple(map(_instantiate_zeros, primals, tangents))\n+ tangent_instantiated = tuple(map(ad.replace_float0s, primals, tangent_instantiated))\narg_treedef = params[\"arg_treedef\"]\n# The argument to the jvp tap is a pair of the tapped primals and tangents\n@@ -946,6 +947,7 @@ def _outside_call_jvp_rule(primals, tangents, **params):\narg_treedef=jvp_arg_treedef,\n))\nout_primals_tapped, out_tangents_tapped = util.split_list(out_all, [len(primals)])\n+ out_tangents_tapped = map(ad.recast_to_float0, out_primals_tapped, out_tangents_tapped)\nreturn tuple(out_primals_tapped), tuple(out_tangents_tapped)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2393,6 +2393,20 @@ class APITest(jtu.JaxTestCase):\nexpected = jnp.arange(1) + 1\nself.assertAllClose(ans, expected)\n+ def test_large_python_int_to_float(self):\n+ # https://github.com/google/jax/pull/6165\n+ # We skip checks because otherwise we end up calling valid_jaxtype(2**100),\n+ # which tries to form a ConcreteArray with that value and thus leads to a\n+ # NumPy OverflowError. It's true that 2**100 does not inhabit a jax type,\n+ # but as an issue of Python embedding we can handle operations like\n+ # lax.convert_element_type(2 ** 100, jnp.float32) as in the tests below.\n+ # That is, lax.convert_element_type(2 ** 100, jnp.int32) is an error while\n+ # lax.convert_element_type(2 ** 100, jnp.float32) is not.\n+ with jax.core.skipping_checks():\n+ jnp.multiply(2 ** 100, 3.) # doesn't crash\n+ out = lax.convert_element_type(2 ** 100, jnp.float32) # doesn't crash\n+ self.assertArraysEqual(out, np.float32(2 ** 100))\n+\nclass RematTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1028,7 +1028,7 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n2 )\ntransforms: ['jvp', 'transpose'] what: pair\n( 2.00\n- False )\"\"\", testing_stream.output)\n+ 0 )\"\"\", testing_stream.output)\ntesting_stream.reset()\ndef test_tap_vmap(self):\n@@ -1590,8 +1590,8 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n( 3 ) ) )\n( ( [0. 0.1 0.2 0.3 0.4]\n[0. 0.2 0.4 0.6 0.8] )\n- ( ( False )\n- ( False ) ) ) )\"\"\", testing_stream.output)\n+ ( ( 0 )\n+ ( 0 ) ) ) )\"\"\", testing_stream.output)\ntesting_stream.reset()\n# Now with JIT\n" }, { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -746,6 +746,8 @@ class LaxRandomTest(jtu.JaxTestCase):\ngrad(lambda x: jnp.sum(vmap(f)(x)))(jnp.ones(2))\ndef testNoOpByOpUnderHash(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"test requires omnistaging\")\ndef fail(*args, **kwargs): assert False\napply_primitive, xla.apply_primitive = xla.apply_primitive, fail\ntry:\n" } ]
Python
Apache License 2.0
google/jax
fix convert_element_type on large Py int inputs
260,335
21.03.2021 19:38:12
25,200
fe4d12c10fb0cb50b811b10ecd0b417db1cb886f
move logic to traceable
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -428,8 +428,8 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nif hasattr(operand, '__jax_array__'):\noperand = operand.__jax_array__()\n- # Note: don't canonicalize old_dtype because x64 context might\n- # cause un-canonicalized operands to be passed in.\n+ # Don't canonicalize old_dtype because x64 context might cause\n+ # un-canonicalized operands to be passed in.\nold_dtype = np.result_type(operand)\nold_weak_type = dtypes.is_weakly_typed(operand)\n@@ -441,6 +441,12 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nmsg = \"Casting complex values to real discards the imaginary part\"\nwarnings.warn(msg, np.ComplexWarning, stacklevel=2)\n+ # Python has big integers, but convert_element_type(2 ** 100, np.float32) need\n+ # not be an error since the target dtype fits the value. Handle this case by\n+ # converting to a NumPy array before calling bind.\n+ if type(operand) is int:\n+ operand = np.asarray(operand, new_dtype)\n+\nif ((old_dtype, old_weak_type) == (new_dtype, new_weak_type)\nand isinstance(operand, (core.Tracer, xla.DeviceArray))):\nreturn operand\n@@ -2658,12 +2664,6 @@ lt_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'lt')\nad.defjvp_zero(lt_p)\n-def _convert_element_type_impl(operand, *, new_dtype, weak_type):\n- if dtypes.is_python_scalar(operand):\n- operand = np.asarray(operand, dtype=new_dtype)\n- return xla.apply_primitive(convert_element_type_p, operand,\n- new_dtype=new_dtype, weak_type=weak_type)\n-\ndef _convert_element_type_shape_rule(operand, *, new_dtype, weak_type):\nreturn operand.shape\n@@ -2699,7 +2699,7 @@ def _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nreturn convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\nconvert_element_type_p = core.convert_element_type_p\n-convert_element_type_p.def_impl(_convert_element_type_impl)\n+convert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\nconvert_element_type_p.def_abstract_eval(\npartial(standard_abstract_eval, convert_element_type_p,\n_convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2395,14 +2395,6 @@ class APITest(jtu.JaxTestCase):\ndef test_large_python_int_to_float(self):\n# https://github.com/google/jax/pull/6165\n- # We skip checks because otherwise we end up calling valid_jaxtype(2**100),\n- # which tries to form a ConcreteArray with that value and thus leads to a\n- # NumPy OverflowError. It's true that 2**100 does not inhabit a jax type,\n- # but as an issue of Python embedding we can handle operations like\n- # lax.convert_element_type(2 ** 100, jnp.float32) as in the tests below.\n- # That is, lax.convert_element_type(2 ** 100, jnp.int32) is an error while\n- # lax.convert_element_type(2 ** 100, jnp.float32) is not.\n- with jax.core.skipping_checks():\njnp.multiply(2 ** 100, 3.) # doesn't crash\nout = lax.convert_element_type(2 ** 100, jnp.float32) # doesn't crash\nself.assertArraysEqual(out, np.float32(2 ** 100))\n" } ]
Python
Apache License 2.0
google/jax
move logic to traceable
260,335
21.03.2021 19:41:04
25,200
214d273d8cbf05b7c8ccf3b96f778fb581425e52
undo changes to host_callback (not needed anymore)
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -443,7 +443,9 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\n# Python has big integers, but convert_element_type(2 ** 100, np.float32) need\n# not be an error since the target dtype fits the value. Handle this case by\n- # converting to a NumPy array before calling bind.\n+ # converting to a NumPy array before calling bind. Without this step, we'd\n+ # first canonicalize the input to a value of dtype int32 or int64, leading to\n+ # an overflow error.\nif type(operand) is int:\noperand = np.asarray(operand, new_dtype)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -934,7 +934,6 @@ def _outside_call_jvp_rule(primals, tangents, **params):\nif not params[\"identity\"]:\nraise NotImplementedError(\"JVP rule is implemented only for id_tap, not for call.\")\ntangent_instantiated = tuple(map(_instantiate_zeros, primals, tangents))\n- tangent_instantiated = tuple(map(ad.replace_float0s, primals, tangent_instantiated))\narg_treedef = params[\"arg_treedef\"]\n# The argument to the jvp tap is a pair of the tapped primals and tangents\n@@ -947,7 +946,6 @@ def _outside_call_jvp_rule(primals, tangents, **params):\narg_treedef=jvp_arg_treedef,\n))\nout_primals_tapped, out_tangents_tapped = util.split_list(out_all, [len(primals)])\n- out_tangents_tapped = map(ad.recast_to_float0, out_primals_tapped, out_tangents_tapped)\nreturn tuple(out_primals_tapped), tuple(out_tangents_tapped)\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1028,7 +1028,7 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n2 )\ntransforms: ['jvp', 'transpose'] what: pair\n( 2.00\n- 0 )\"\"\", testing_stream.output)\n+ False )\"\"\", testing_stream.output)\ntesting_stream.reset()\ndef test_tap_vmap(self):\n@@ -1590,8 +1590,8 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n( 3 ) ) )\n( ( [0. 0.1 0.2 0.3 0.4]\n[0. 0.2 0.4 0.6 0.8] )\n- ( ( 0 )\n- ( 0 ) ) ) )\"\"\", testing_stream.output)\n+ ( ( False )\n+ ( False ) ) ) )\"\"\", testing_stream.output)\ntesting_stream.reset()\n# Now with JIT\n" } ]
Python
Apache License 2.0
google/jax
undo changes to host_callback (not needed anymore)
260,510
09.03.2021 18:40:25
28,800
252bd6c0c8cb9f337eb29415fdd56033b53a3385
Add support for custom derivatives in jax.experimental.callback
[ { "change_type": "MODIFY", "old_path": "jax/experimental/callback.py", "new_path": "jax/experimental/callback.py", "diff": "@@ -21,13 +21,15 @@ import jax.numpy as jnp\nfrom jax import core\nfrom jax.core import Trace, Tracer, jaxpr_as_fun\nfrom jax import lax\n+from jax import custom_derivatives as cd\n+from jax.interpreters import partial_eval as pe\nfrom jax import linear_util as lu\nfrom jax._src.util import partial, safe_map, wraps, split_list\nfrom jax._src.lax import control_flow as lcf\nimport inspect\nfrom jax.api_util import flatten_fun_nokwargs\n-from jax.tree_util import tree_flatten, tree_unflatten, tree_structure, tree_leaves, tree_map\n+from jax.tree_util import tree_flatten, tree_unflatten, tree_structure, tree_map\nmap = safe_map\n@@ -114,6 +116,14 @@ def _callback_fun(callback, strip_calls, *in_vals, **params):\ndel main\nyield out_vals\n+def callback_jaxpr(closed_jaxpr, callback, strip_calls):\n+ fun = lu.wrap_init(jaxpr_as_fun(closed_jaxpr))\n+ fun = callback_subtrace(fun)\n+ fun = _callback_fun(fun, callback, strip_calls)\n+ avals_in = closed_jaxpr.in_avals\n+ jaxpr_out, consts = cd._initial_style_jaxpr(fun, avals_in)\n+ return core.ClosedJaxpr(jaxpr_out, consts)\n+\ndef _check_callable(fun):\nif not callable(fun):\nraise TypeError(f\"Expected a callable value, got {fun}\")\n@@ -164,18 +174,20 @@ class CallbackTrace(Trace):\nreturn [CallbackTracer(self, val) for val in vals_out]\ndef process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n- # This implementation just drops the custom derivative rule.\n- # TODO(sharadmv): don't drop the custom derivative rule\n- del primitive, jvp # Unused.\n- return fun.call_wrapped(*tracers)\n+ vals_in = [t.val for t in tracers]\n+ fun = callback_subtrace(fun, self.main)\n+ jvp = callback_subtrace(jvp, self.main)\n+ out = primitive.bind(fun, jvp, *vals_in)\n+ return safe_map(self.pure, out)\ndef process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers,\nout_trees):\n- # This implementation just drops the custom derivative rule.\n- # TODO(sharadmv): don't drop the custom derivative rule\n- del primitive, fwd, bwd, out_trees # Unused.\n- return fun.call_wrapped(*tracers)\n-\n+ vals_in = [t.val for t in tracers]\n+ fun = callback_subtrace(fun, self.main)\n+ fwd = callback_subtrace(fwd, self.main)\n+ bwd = callback_subtrace(bwd, self.main)\n+ out = primitive.bind(fun, fwd, bwd, *vals_in, out_trees=out_trees)\n+ return safe_map(self.pure, out)\ncustom_callback_rules: Dict[Any, Any] = {}\n@@ -190,14 +202,13 @@ def _scan_callback_rule(trace, *tracers, reverse, length, num_consts, num_carry,\nbody_fun = jaxpr_as_fun(jaxpr)\n- def new_body(carry, x):\n- flat_args = tree_leaves((carry, x))\n- out = body_fun(*(const_vals + flat_args))\n+ def new_body(*vals):\n+ out = body_fun(*vals)\nout_carry, y = split_list(out, [num_carry])\nreturn out_carry, y\nmain = trace.main\nnew_body = callback_transform(new_body, main.callback, strip_calls=main.strip_calls) # type: ignore\n- in_tree = tree_structure(tuple(carry_avals + xs_avals))\n+ in_tree = tree_structure(carry_avals + xs_avals)\nnew_jaxpr, new_consts, _ = lcf._initial_style_jaxpr(\nnew_body, in_tree, tuple(carry_avals + x_avals))\nvals = tuple(it.chain(new_consts, carry_vals, xs_vals))\n@@ -242,3 +253,37 @@ def _while_callback_rule(trace, *tracers, cond_jaxpr, body_jaxpr,\nreturn safe_map(trace.pure, out)\ncustom_callback_rules[lax.while_p] = _while_callback_rule\n+\n+def _custom_derivative_call_jaxpr_callback_rule(primitive, trace, *tracers,\n+ fun_jaxpr, num_consts, **params):\n+ main = trace.main\n+ vals = [t.val for t in tracers]\n+\n+ new_closed_jaxpr = callback_jaxpr(fun_jaxpr, main.callback, strip_calls=main.strip_calls)\n+ if primitive == cd.custom_jvp_call_jaxpr_p:\n+ thunk_name = 'jvp_jaxpr_thunk'\n+ elif primitive == cd.custom_vjp_call_jaxpr_p:\n+ thunk_name = 'fwd_jaxpr_thunk'\n+ params['bwd'] = callback_subtrace(params['bwd'], main)\n+ else:\n+ raise NotImplementedError(primitive)\n+\n+ thunk = params.pop(thunk_name)\n+ @pe._memoize\n+ def new_thunk():\n+ thunk_jaxpr = core.ClosedJaxpr(*thunk())\n+ closed_jaxpr = callback_jaxpr(thunk_jaxpr, main.callback, main.strip_calls)\n+ return closed_jaxpr.jaxpr, closed_jaxpr.literals\n+\n+ params[thunk_name] = new_thunk\n+ new_fun_jaxpr, new_consts = new_closed_jaxpr.jaxpr, new_closed_jaxpr.literals\n+ closed_fun_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(new_fun_jaxpr), ())\n+ new_num_consts = len(new_consts) + num_consts\n+ out = primitive.bind(*it.chain(new_consts, vals), fun_jaxpr=closed_fun_jaxpr,\n+ num_consts=new_num_consts, **params)\n+ return safe_map(trace.pure, out)\n+\n+custom_callback_rules[cd.custom_jvp_call_jaxpr_p] = partial(\n+ _custom_derivative_call_jaxpr_callback_rule, cd.custom_jvp_call_jaxpr_p)\n+custom_callback_rules[cd.custom_vjp_call_jaxpr_p] = partial(\n+ _custom_derivative_call_jaxpr_callback_rule, cd.custom_vjp_call_jaxpr_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/callback_test.py", "new_path": "tests/callback_test.py", "diff": "@@ -21,6 +21,7 @@ from jax.experimental.callback import find_by_value, rewrite, FoundValue\nimport jax.numpy as jnp\nfrom jax import lax\nfrom jax import jit\n+from jax import grad\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n@@ -158,6 +159,136 @@ class CallbackTest(jtu.JaxTestCase):\n}\nself.assertAllClose(rewrite(f, rewrites)(x), 11)\n+ def testRewriteThroughCustomVJP(self):\n+\n+ @jax.custom_gradient\n+ def f(x):\n+ return x * 2, lambda g: g + x\n+\n+ x = 2.\n+ self.assertAllClose(f(x), 4.)\n+ self.assertAllClose(grad(f)(x), 3.)\n+\n+ rewrites = {\n+ lax.mul_p: lambda x, y: x / y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 1.)\n+ self.assertAllClose(grad(g)(x), 3.)\n+\n+ rewrites = {\n+ lax.add_p: lambda x, y: x - y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 4.)\n+ self.assertAllClose(grad(g)(x), -1.)\n+\n+ def testRewriteThroughCustomVJPInScan(self):\n+\n+ @jax.custom_gradient\n+ def foo(x):\n+ return x * 2, lambda g: g + x\n+\n+ def f(x):\n+ out, _ = lax.scan(lambda c, _: (foo(c), None), x, None, length=1)\n+ return out\n+\n+ x = 2.\n+ self.assertAllClose(f(x), 4.)\n+ self.assertAllClose(grad(f)(x), 3.)\n+\n+ rewrites = {\n+ lax.mul_p: lambda x, y: x / y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 1.)\n+ self.assertAllClose(grad(g)(x), 3.)\n+\n+ rewrites = {\n+ lax.add_p: lambda x, y: x * y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 4.)\n+ self.assertAllClose(grad(g)(x), 2.)\n+\n+ def testRewriteThroughCustomJVP(self):\n+\n+ @jax.custom_jvp\n+ def f(x):\n+ return x + 2\n+\n+ @f.defjvp\n+ def f_jvp(primals, tangents):\n+ x, = primals\n+ d, = tangents\n+ return f(x), x * d\n+\n+ x = 2.\n+ self.assertAllClose(f(x), 4.)\n+ f_primal, jvp = jax.jvp(f, (x,), (1.,))\n+ self.assertAllClose(f_primal, 4.)\n+ self.assertAllClose(jvp, 2.)\n+ self.assertAllClose(grad(f)(x), 2.)\n+\n+ rewrites = {\n+ lax.add_p: lambda x, y: x - y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 0.)\n+ g_primal, jvp = jax.jvp(g, (x,), (1.,))\n+ self.assertAllClose(g_primal, 0.)\n+ self.assertAllClose(jvp, 2.)\n+ self.assertAllClose(grad(g)(x), 2.)\n+\n+ def testRewriteThroughCustomJVPInScan(self):\n+\n+ @jax.custom_jvp\n+ def foo(x):\n+ return x + 2\n+\n+ @foo.defjvp\n+ def foo_jvp(primals, tangents):\n+ x, = primals\n+ d, = tangents\n+ return f(x), x * d\n+ def f(x):\n+ out, _ = lax.scan(lambda c, _: (foo(c), None), x, None, length=1)\n+ return out\n+\n+ x = 2.\n+ self.assertAllClose(f(x), 4.)\n+ f_primal, jvp = jax.jvp(f, (x,), (1.,))\n+ self.assertAllClose(f_primal, 4.)\n+ self.assertAllClose(jvp, 2.)\n+ self.assertAllClose(grad(f)(x), 2.)\n+\n+ rewrites = {\n+ lax.add_p: lambda x, y: x - y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 0.)\n+ g_primal, jvp = jax.jvp(g, (x,), (1.,))\n+ self.assertAllClose(g_primal, 0.)\n+ self.assertAllClose(jvp, 2.)\n+ self.assertAllClose(grad(g)(x), 2.)\n+\n+ rewrites = {\n+ lax.mul_p: lambda x, y: x + y\n+ }\n+ g = rewrite(f, rewrites)\n+\n+ self.assertAllClose(g(x), 4.)\n+ g_primal, jvp = jax.jvp(g, (x,), (1.,))\n+ self.assertAllClose(g_primal, 4.)\n+ self.assertAllClose(jvp, 3.)\n+ self.assertAllClose(grad(g)(x), 1.)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add support for custom derivatives in jax.experimental.callback
260,677
22.03.2021 21:29:39
0
809d6895824fd82cecc60a67d70bdfe913e7efb1
Increase threshold for switching to unbatched triangular solve on GPU
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -707,7 +707,7 @@ def _triangular_solve_gpu_translation_rule(trsm_impl,\nif conjugate_a and not transpose_a:\na = xops.Conj(a)\nconjugate_a = False\n- if batch > 1 and m <= 32 and n <= 32:\n+ if batch > 1 and m <= 256 and n <= 256:\nreturn trsm_impl(\nc, a, b, left_side, lower, transpose_a,\nconjugate_a, unit_diagonal)\n" } ]
Python
Apache License 2.0
google/jax
Increase threshold for switching to unbatched triangular solve on GPU
260,335
23.03.2021 19:13:15
25,200
70cd62d5454c07d6a7b1141c597afca594eaaebc
disable disable_omnistaging
[ { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -154,19 +154,14 @@ class Config:\nraise Exception(\"can't re-enable omnistaging after it's been disabled\")\ndef disable_omnistaging(self):\n+ return\n+\n+ def temporary_hack_do_not_call_me(self):\nif self.omnistaging_enabled:\nfor disabler in self._omnistaging_disablers:\ndisabler()\nself.omnistaging_enabled = False\n-# # TODO(jakevdp, mattjj): unify this with `define_bool_state` stuff below\n-# @property\n-# def x64_enabled(self):\n-# return lib.jax_jit.get_enable_x64()\n-\n-# def _set_x64_enabled(self, state):\n-# lib.jax_jit.thread_local_state().enable_x64 = bool(state)\n-\ndef define_bool_state(self, name: str, default: bool, help: str):\n\"\"\"Set up thread-local state and return a contextmanager for managing it.\n" } ]
Python
Apache License 2.0
google/jax
disable disable_omnistaging
260,335
23.03.2021 20:58:52
25,200
89768a3d2898ee7e08425f90ccf1435449c07ee6
add jax_default_matmul_precision flag & context mngr
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -31,7 +31,8 @@ del _cloud_tpu_init\n# flake8: noqa: F401\nfrom .config import (config, enable_checks, check_tracer_leaks, checking_leaks,\n- debug_nans, debug_infs, log_compiles)\n+ debug_nans, debug_infs, log_compiles,\n+ default_matmul_precision, numpy_rank_promotion)\nfrom .api import (\nad, # TODO(phawkins): update users to avoid this.\nargnums_partial, # TODO(phawkins): update Haiku to not use this.\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -506,8 +506,17 @@ def concatenate(operands: Sequence[Array], dimension: int) -> Array:\nPrecision = xla_client.PrecisionConfig.Precision\nPrecision.__str__ = lambda precision: precision.name\nPrecisionType = Any\n-PrecisionLike = Union[None, PrecisionType, Tuple[PrecisionType, PrecisionType]]\n-\n+PrecisionLike = Union[None, str, PrecisionType, Tuple[str, str],\n+ Tuple[PrecisionType, PrecisionType]]\n+_precision_strings = {\n+ 'highest': Precision.HIGHEST,\n+ 'float32': Precision.HIGHEST,\n+ 'bfloat16_3x': Precision.HIGH,\n+ 'tensorfloat32': Precision.HIGH,\n+ 'bfloat16': Precision.DEFAULT,\n+ 'fastest': Precision.DEFAULT,\n+ None: Precision.DEFAULT,\n+}\nclass ConvDimensionNumbers(NamedTuple):\n\"\"\"Describes batch, spatial, and feature dimensions of a convolution.\n@@ -555,23 +564,25 @@ def conv_general_dilated(\nrhs_dilation: `None`, or a sequence of `n` integers, giving the\ndilation factor to apply in each spatial dimension of `rhs`. RHS dilation\nis also known as atrous convolution.\n- dimension_numbers: either `None`, a `ConvDimensionNumbers` object, or\n- a 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\n- of length `n+2`.\n+ dimension_numbers: either `None`, a ``ConvDimensionNumbers`` object, or\n+ a 3-tuple ``(lhs_spec, rhs_spec, out_spec)``, where each element is a\n+ string of length `n+2`.\nfeature_group_count: integer, default 1. See XLA HLO docs.\nbatch_group_count: integer, default 1. See XLA HLO docs.\nprecision: Optional. Either ``None``, which means the default precision for\nthe backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n- ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n- ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n+ ``Precision.HIGH`` or ``Precision.HIGHEST``), a string (e.g. 'highest' or\n+ 'fastest', see the ``jax.default_matmul_precision`` context manager), or a\n+ tuple of two ``lax.Precision`` enums or strings indicating precision of\n+ ``lhs`` and ``rhs``.\nReturns:\nAn array containing the convolution result.\n- In the string case of `dimension_numbers`, each character identifies by\n+ In the string case of ``dimension_numbers``, each character identifies by\nposition:\n- - the batch dimensions in `lhs`, `rhs`, and the output with the character\n+ - the batch dimensions in ``lhs``, ``rhs``, and the output with the character\n'N',\n- the feature dimensions in `lhs` and the output with the character 'C',\n- the input and output feature dimensions in rhs with the characters 'I'\n@@ -579,18 +590,18 @@ def conv_general_dilated(\n- spatial dimension correspondences between lhs, rhs, and the output using\nany distinct characters.\n- For example, to indicate dimension numbers consistent with the `conv` function\n- with two spatial dimensions, one could use `('NCHW', 'OIHW', 'NCHW')`. As\n- another example, to indicate dimension numbers consistent with the TensorFlow\n- Conv2D operation, one could use `('NHWC', 'HWIO', 'NHWC')`. When using the\n- latter form of convolution dimension specification, window strides are\n- associated with spatial dimension character labels according to the order in\n- which the labels appear in the `rhs_spec` string, so that `window_strides[0]`\n- is matched with the dimension corresponding to the first character\n- appearing in rhs_spec that is not `'I'` or `'O'`.\n-\n- If `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`\n- (for a 2D convolution).\n+ For example, to indicate dimension numbers consistent with the ``conv``\n+ function with two spatial dimensions, one could use ``('NCHW', 'OIHW',\n+ 'NCHW')``. As another example, to indicate dimension numbers consistent with\n+ the TensorFlow Conv2D operation, one could use ``('NHWC', 'HWIO', 'NHWC')``.\n+ When using the latter form of convolution dimension specification, window\n+ strides are associated with spatial dimension character labels according to\n+ the order in which the labels appear in the ``rhs_spec`` string, so that\n+ ``window_strides[0]`` is matched with the dimension corresponding to the first\n+ character appearing in rhs_spec that is not ``'I'`` or ``'O'``.\n+\n+ If ``dimension_numbers`` is ``None``, the default is ``('NCHW', 'OIHW',\n+ 'NCHW')`` (for a 2D convolution).\n\"\"\"\ndnums = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\nif lhs_dilation is None:\n@@ -6394,16 +6405,31 @@ def remaining(original, *removed_lists):\ndef _canonicalize_precision(precision):\nif precision is None:\n+ if config.jax_default_matmul_precision is None:\nreturn None\n- if isinstance(precision, Precision) or (\n- isinstance(precision, tuple)\n- and len(precision) == 2\n- and all(isinstance(p, Precision) for p in precision)\n- ):\n+ try:\n+ return _precision_strings[config.jax_default_matmul_precision]\n+ except KeyError:\n+ raise ValueError(\n+ \"jax_default_matmul_precision flag must be set to None or a value in \"\n+ f\"{_precision_strings}, but got {config.jax_default_matmul_precision}\"\n+ ) from None\n+ elif isinstance(precision, str) and precision in _precision_strings:\n+ return _precision_strings.get(precision)\n+ elif isinstance(precision, Precision):\nreturn precision\n+ elif (isinstance(precision, (list, tuple)) and len(precision) == 2 and\n+ all(isinstance(p, Precision) for p in precision)):\n+ return precision\n+ elif (isinstance(precision, (list, tuple)) and len(precision) == 2 and\n+ all(isinstance(s, str) for s in precision)):\n+ s1, s2 = precision\n+ return (_canonicalize_precision(s1), _canonicalize_precision(s2))\nelse:\n- raise ValueError(\"Precision argument must be None, a lax.Precision value \"\n- f\"or a tuple of two lax.Precision values; got {precision}\")\n+ raise ValueError(\n+ f\"Precision argument must be None, a string in {_precision_strings}, \"\n+ \"a lax.Precision value or a tuple of two lax.Precision values or \"\n+ f\"strings; got {precision}.\")\ndef conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -28,7 +28,6 @@ import builtins\nimport collections\nimport collections.abc\nimport operator\n-import os\nimport types\nfrom typing import Any, Sequence, FrozenSet, Optional, Tuple, Union, cast\nfrom textwrap import dedent as _dedent\n@@ -45,7 +44,7 @@ from jax import core\nfrom jax import dtypes\nfrom jax import errors\nfrom jax.core import UnshapedArray, ShapedArray, ConcreteArray, canonicalize_shape\n-from jax.config import flags, config\n+from jax.config import config\nfrom jax.interpreters.xla import DeviceArray, _DeviceArray, _CppDeviceArray\nfrom jax.interpreters.masking import Poly\nfrom jax import lax\n@@ -55,14 +54,6 @@ from jax._src.util import (partial, unzip2, prod as _prod, subvals, safe_zip,\ncanonicalize_axis as _canonicalize_axis, maybe_named_axis)\nfrom jax.tree_util import tree_leaves, tree_flatten, tree_map\n-FLAGS = flags.FLAGS\n-flags.DEFINE_enum(\n- 'jax_numpy_rank_promotion', os.getenv('JAX_NUMPY_RANK_PROMOTION', 'allow'),\n- enum_values=['allow', 'warn', 'raise'],\n- help=\n- 'Control NumPy-style automatic rank promotion broadcasting '\n- '(\"allow\", \"warn\", or \"raise\").')\n-\nnewaxis = None\n# Common docstring additions:\n@@ -247,20 +238,20 @@ def _promote_shapes(fun_name, *args):\nif not nonscalar_ranks or len(set(nonscalar_ranks)) == 1:\nreturn args\nelse:\n- if FLAGS.jax_numpy_rank_promotion != \"allow\":\n+ if config.jax_numpy_rank_promotion != \"allow\":\n_rank_promotion_warning_or_error(fun_name, shapes)\nresult_rank = len(lax.broadcast_shapes(*shapes))\nreturn [broadcast_to(arg, (1,) * (result_rank - len(shp)) + shp)\nfor arg, shp in zip(args, shapes)]\ndef _rank_promotion_warning_or_error(fun_name, shapes):\n- if FLAGS.jax_numpy_rank_promotion == \"warn\":\n+ if config.jax_numpy_rank_promotion == \"warn\":\nmsg = (\"Following NumPy automatic rank promotion for {} on shapes {}. \"\n\"Set the jax_numpy_rank_promotion config option to 'allow' to \"\n\"disable this warning; for more information, see \"\n\"https://jax.readthedocs.io/en/latest/rank_promotion_warning.html.\")\nwarnings.warn(msg.format(fun_name, ' '.join(map(str, shapes))))\n- elif FLAGS.jax_numpy_rank_promotion == \"raise\":\n+ elif config.jax_numpy_rank_promotion == \"raise\":\nmsg = (\"Operands could not be broadcast together for {} on shapes {} \"\n\"and with the config option jax_numpy_rank_promotion='raise'. \"\n\"For more information, see \"\n" }, { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -17,9 +17,9 @@ import functools\nimport os\nimport sys\nimport threading\n+from typing import List, Callable, Optional\nfrom jax import lib\n-from typing import Callable, Optional\ndef bool_env(varname: str, default: bool) -> bool:\n\"\"\"Read an environment variable and interpret it as a boolean.\n@@ -52,7 +52,7 @@ class Config:\ndef __init__(self):\nself.values = {}\nself.meta = {}\n- self.FLAGS = NameSpace(self.read)\n+ self.FLAGS = NameSpace(self.read, self.update)\nself.use_absl = False\nself._contextmanager_flags = set()\n@@ -255,18 +255,70 @@ class Config:\nset_state.__doc__ = f\"Context manager for `{name}` config option.\\n\\n{help}\"\nreturn set_state\n+ def define_enum_state(self, name: str, enum_values: List[str],\n+ default: Optional[str], help: str):\n+ \"\"\"Set up thread-local state and return a contextmanager for managing it.\n+ Args:\n+ name: string, converted to lowercase to define the name of the config\n+ option (and absl flag). It is converted to uppercase to define the\n+ corresponding shell environment variable.\n+ enum_values: list of strings representing the possible values for the\n+ option.\n+ default: optional string, default value.\n+ help: string, used to populate the flag help information as well as the\n+ docstring of the returned context manager.\n+ Returns:\n+ A contextmanager to control the thread-local state value.\n+ See docstring for ``define_bool_state``.\n+ \"\"\"\n+ name = name.lower()\n+ self.DEFINE_enum(name, os.getenv(name.upper(), default),\n+ enum_values=enum_values, help=help)\n+ self._contextmanager_flags.add(name)\n+\n+ def get_state(self):\n+ val = getattr(_thread_local_state, name, unset)\n+ return val if val is not unset else self._read(name)\n+ setattr(Config, name, property(get_state))\n+\n+ @contextlib.contextmanager\n+ def set_state(new_val: Optional[str]):\n+ if (new_val is not None and\n+ (type(new_val) is not str or new_val not in enum_values)):\n+ raise ValueError(f\"new enum value must be None or in {enum_values}, \"\n+ f\"got {new_val} of type {type(new_val)}.\")\n+ prev_val = getattr(_thread_local_state, name, unset)\n+ setattr(_thread_local_state, name, new_val)\n+ try:\n+ yield\n+ finally:\n+ if prev_val is unset:\n+ delattr(_thread_local_state, name)\n+ else:\n+ setattr(_thread_local_state, name, prev_val)\n+ set_state.__name__ = name[4:] if name.startswith('jax_') else name\n+ set_state.__doc__ = f\"Context manager for `{name}` config option.\\n\\n{help}\"\n+ return set_state\n+\n+\n_thread_local_state = threading.local()\nclass Unset: pass\nunset = Unset()\n-class NameSpace(object):\n- def __init__(self, getter):\n- self._getter = getter\n+class NameSpace:\n+ def __init__(self, getter, setter):\n+ # must use super because we override this class's __setattr__, see\n+ # https://docs.python.org/3/reference/datamodel.html#object.__setattr__\n+ super().__setattr__('_getter', getter)\n+ super().__setattr__('_setter', setter)\ndef __getattr__(self, name):\nreturn self._getter(name)\n+ def __setattr__(self, name, val):\n+ self._setter(name, val)\n+\nconfig = Config()\nflags = config\n@@ -357,3 +409,32 @@ enable_x64 = config.define_bool_state(\nconfig._contextmanager_flags.remove(\"jax_enable_x64\")\nConfig.x64_enabled = Config.jax_enable_x64 # type: ignore\n+\n+\n+numpy_rank_promotion = config.define_enum_state(\n+ name='jax_numpy_rank_promotion',\n+ enum_values=['allow', 'warn', 'raise'],\n+ default='allow',\n+ help=('Control NumPy-style automatic rank promotion broadcasting '\n+ '(\"allow\", \"warn\", or \"raise\").'))\n+\n+default_matmul_precision = config.define_enum_state(\n+ name='jax_default_matmul_precision',\n+ enum_values=['bfloat16', 'tensorfloat32', 'float32'],\n+ default=None,\n+ help=('Control the default matmul and conv precision for 32bit inputs.\\n\\n'\n+\n+ 'Some platforms, like TPU, offer configurable precision levels for '\n+ 'matrix multiplication and convolution computations, trading off '\n+ 'accuracy for speed. The precision can be controlled for each '\n+ 'operation; for example, see the :func:`jax.lax.conv_general_dilated` '\n+ 'and :func:`jax.lax.dot` docstrings. But it can be useful to control '\n+ 'the default behavior obtained when an operation is not given a '\n+ 'specific precision.\\n\\n'\n+\n+ 'This option can be used to control the default precision '\n+ 'level for computations involved in matrix multiplication and '\n+ 'convolution on 32bit inputs. The levels roughly describe the '\n+ \"precision at which scalar products are computed. The 'bfloat16' \"\n+ \"option is the fastest and least precise; 'float32' is similar to \"\n+ \"full float32 precision; 'tensorfloat32' is intermediate.\\n\\n\"))\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -25,6 +25,7 @@ import warnings\nimport weakref\nimport functools\nimport itertools as it\n+import operator as op\nfrom absl import logging\nfrom absl.testing import absltest, parameterized\n@@ -2399,6 +2400,58 @@ class APITest(jtu.JaxTestCase):\nout = lax.convert_element_type(2 ** 100, jnp.float32) # doesn't crash\nself.assertArraysEqual(out, np.float32(2 ** 100))\n+ def test_dot_precision_context_manager(self):\n+ x = jnp.zeros((2, 2))\n+\n+ with jax.default_matmul_precision(None):\n+ jnp.dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n+ self.assertIn('precision=None', str(jaxpr))\n+\n+ with jax.default_matmul_precision(\"bfloat16\"):\n+ x @ x # doesn't crash\n+ jaxpr = jax.make_jaxpr(op.matmul)(x, x)\n+ self.assertIn('precision=DEFAULT', str(jaxpr))\n+\n+ with jax.default_matmul_precision(\"tensorfloat32\"):\n+ jnp.dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n+ self.assertIn('precision=HIGH\\n', str(jaxpr))\n+\n+ with jax.default_matmul_precision(\"float32\"):\n+ jnp.dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n+ self.assertIn('precision=HIGHEST', str(jaxpr))\n+\n+ dot = partial(jnp.dot, precision=lax.Precision.HIGHEST)\n+ with jax.default_matmul_precision(\"tensorfloat32\"):\n+ dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(dot)(x, x)\n+ self.assertIn('precision=HIGHEST', str(jaxpr))\n+\n+ def test_dot_precision_flag(self):\n+ x = jnp.zeros((2, 2))\n+\n+ prev_val = config._read(\"jax_default_matmul_precision\")\n+ try:\n+ config.FLAGS.jax_default_matmul_precision = \"tensorfloat32\"\n+ jnp.dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n+ finally:\n+ config.FLAGS.jax_default_matmul_precision = prev_val\n+ self.assertIn('precision=HIGH', str(jaxpr))\n+ self.assertEqual(prev_val, config._read(\"jax_default_matmul_precision\"))\n+\n+ prev_val = config._read(\"jax_default_matmul_precision\")\n+ try:\n+ config.update('jax_default_matmul_precision','tensorfloat32')\n+ jnp.dot(x, x) # doesn't crash\n+ jaxpr = jax.make_jaxpr(jnp.dot)(x, x)\n+ finally:\n+ config.update('jax_default_matmul_precision', prev_val)\n+ self.assertIn('precision=HIGH', str(jaxpr))\n+ self.assertEqual(prev_val, config._read(\"jax_default_matmul_precision\"))\n+\nclass RematTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -4769,21 +4769,21 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\ndef testDisableNumpyRankPromotionBroadcasting(self):\ntry:\n- prev_flag = FLAGS.jax_numpy_rank_promotion\n+ prev_flag = config.jax_numpy_rank_promotion\nFLAGS.jax_numpy_rank_promotion = \"allow\"\njnp.ones(2) + jnp.ones((1, 2)) # works just fine\nfinally:\nFLAGS.jax_numpy_rank_promotion = prev_flag\ntry:\n- prev_flag = FLAGS.jax_numpy_rank_promotion\n+ prev_flag = config.jax_numpy_rank_promotion\nFLAGS.jax_numpy_rank_promotion = \"raise\"\nself.assertRaises(ValueError, lambda: jnp.ones(2) + jnp.ones((1, 2)))\nfinally:\nFLAGS.jax_numpy_rank_promotion = prev_flag\ntry:\n- prev_flag = FLAGS.jax_numpy_rank_promotion\n+ prev_flag = config.jax_numpy_rank_promotion\nFLAGS.jax_numpy_rank_promotion = \"warn\"\nwith warnings.catch_warnings(record=True) as w:\nwarnings.simplefilter(\"always\")\n@@ -4800,6 +4800,27 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfinally:\nFLAGS.jax_numpy_rank_promotion = prev_flag\n+ def testDisableNumpyRankPromotionBroadcastingDecorator(self):\n+ with jax.numpy_rank_promotion(\"allow\"):\n+ jnp.ones(2) + jnp.ones((1, 2)) # works just fine\n+\n+ with jax.numpy_rank_promotion(\"raise\"):\n+ self.assertRaises(ValueError, lambda: jnp.ones(2) + jnp.ones((1, 2)))\n+\n+ with jax.numpy_rank_promotion(\"warn\"):\n+ with warnings.catch_warnings(record=True) as w:\n+ warnings.simplefilter(\"always\")\n+ jnp.ones(2) + jnp.ones((1, 2))\n+ assert len(w) > 0\n+ msg = str(w[-1].message)\n+ expected_msg = (\"Following NumPy automatic rank promotion for add on \"\n+ \"shapes (2,) (1, 2).\")\n+ self.assertEqual(msg[:len(expected_msg)], expected_msg)\n+\n+ prev_len = len(w)\n+ jnp.ones(2) + 3\n+ self.assertEqual(len(w), prev_len) # don't want to warn for scalars\n+\ndef testStackArrayArgument(self):\n# tests https://github.com/google/jax/issues/1271\n@api.jit\n" } ]
Python
Apache License 2.0
google/jax
add jax_default_matmul_precision flag & context mngr
260,335
24.03.2021 16:25:50
25,200
a261c768f2c216a54673c4c7a89336f399a50292
simplify cotangent dropping in ad.backward_pass Since variables in jaxprs are only assigned-to once, when we transpose them we end up reading a variable's cotangent value only once. That means we can pop the cotangent environment's reference to a cotangent value in read_cotangent.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "import functools\nimport itertools as it\n-from typing import Any, Callable, Dict, Set, List\n+from typing import Any, Callable, Dict\nfrom . import partial_eval as pe\nfrom ..config import config\n@@ -180,7 +180,7 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\nassert v.aval.strip_weak_type() == joined_aval, (prim, v.aval, ct_aval)\ndef read_cotangent(v):\n- return ct_env.get(v, Zero(v.aval))\n+ return ct_env.pop(v, Zero(v.aval))\ndef read_primal(v):\nif type(v) is Literal:\n@@ -199,18 +199,9 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\n# forces primal_in to contain UndefinedPrimals for tangent values!\nmap(write_primal, jaxpr.invars, primals_in)\n- # Find the last use of each cotangent so that they can be removed\n- # as soon as possible.\n- drop_cts: List[Set[Any]] = []\n- seen_vars: Set[Any] = set(jaxpr.invars)\n- for eqn in jaxpr.eqns:\n- read_set = set(eqn.outvars) # NOTE: eqn is not transposed yet!\n- drop_cts.append(read_set - seen_vars)\n- seen_vars |= read_set\n-\nct_env: Dict[Any, Any] = {}\nmap(partial(write_cotangent, 'outvars'), jaxpr.outvars, cotangents_in)\n- for eqn, to_drop in zip(jaxpr.eqns[::-1], drop_cts[::-1]):\n+ for eqn in jaxpr.eqns[::-1]:\n# FIXME: Some invars correspond to tangents\ninvals = map(read_primal, eqn.invars)\nif eqn.primitive.multiple_results:\n@@ -229,8 +220,6 @@ def backward_pass(jaxpr: core.Jaxpr, consts, primals_in, cotangents_in):\ncts_out = [Zero(v.aval) for v in eqn.invars] if cts_out is Zero else cts_out\n# FIXME: Some invars correspond to primals!\nmap(partial(write_cotangent, eqn.primitive), eqn.invars, cts_out)\n- for var in to_drop:\n- ct_env.pop(var, None) # NB: Constant cotangents might be missing\ncotangents_out = map(read_cotangent, jaxpr.invars)\nreturn cotangents_out\n" } ]
Python
Apache License 2.0
google/jax
simplify cotangent dropping in ad.backward_pass Since variables in jaxprs are only assigned-to once, when we transpose them we end up reading a variable's cotangent value only once. That means we can pop the cotangent environment's reference to a cotangent value in read_cotangent.
260,335
24.03.2021 23:00:51
25,200
278b3ae16e8d883e6a2763519fe13350e2e78c10
add test for backward pass ref dropping
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2452,6 +2452,23 @@ class APITest(jtu.JaxTestCase):\nself.assertIn('precision=HIGH', str(jaxpr))\nself.assertEqual(prev_val, config._read(\"jax_default_matmul_precision\"))\n+ def test_backward_pass_ref_dropping(self):\n+ refs = []\n+\n+ @api.custom_vjp\n+ def f(x):\n+ return x\n+ def f_fwd(x):\n+ return x, None\n+ def f_rev(_, g):\n+ assert len(refs) != 2 or refs[0]() is None\n+ zero = np.zeros(())\n+ refs.append(weakref.ref(zero))\n+ return (zero,)\n+ f.defvjp(f_fwd, f_rev)\n+\n+ api.grad(lambda x: f(f(f(x))))(1.)\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add test for backward pass ref dropping
260,424
25.03.2021 19:15:45
0
25a2e1a66ab1abd0361664cb1c77d0ea6a272c78
Fix the changelog link in the README.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "| [**Transformations**](#transformations)\n| [**Install guide**](#installation)\n| [**Neural net libraries**](#neural-network-libraries)\n-| [**Change logs**](https://jax.readthedocs.io/en/latest/CHANGELOG.html)\n+| [**Change logs**](https://jax.readthedocs.io/en/latest/changelog.html)\n| [**Reference docs**](https://jax.readthedocs.io/en/latest/)\n| [**Code search**](https://cs.opensource.google/jax/jax)\n" } ]
Python
Apache License 2.0
google/jax
Fix the changelog link in the README.
260,335
25.03.2021 22:15:18
25,200
848fed8b873e41c7d4b746aa5bcfffe5700c8005
Work around CPython bug exposed by changes to C++ JIT dispatch path.
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -133,9 +133,17 @@ float0 = dtypes.float0\ndef _check_callable(fun):\nif not callable(fun):\nraise TypeError(f\"Expected a callable value, got {fun}\")\n- if inspect.isgeneratorfunction(fun):\n+ if _isgeneratorfunction(fun):\nraise TypeError(f\"Expected a function, got a generator function: {fun}\")\n+def _isgeneratorfunction(fun):\n+ # re-implemented here because of https://bugs.python.org/issue33261\n+ while inspect.ismethod(fun):\n+ fun = fun.__func__\n+ while isinstance(fun, functools.partial):\n+ fun = fun.func\n+ return inspect.isfunction(fun) and bool(fun.__code__.co_flags & inspect.CO_GENERATOR)\n+\ndef jit(\nfun: F,\n" } ]
Python
Apache License 2.0
google/jax
Work around CPython bug https://bugs.python.org/issue33261 exposed by changes to C++ JIT dispatch path. PiperOrigin-RevId: 365189779
260,299
26.03.2021 10:50:24
0
0a3ba6f2cea609dfbdddea3ef82cbb10fc02e5a7
Instantiate zero outputs of linear_transpose
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1963,7 +1963,9 @@ def linear_transpose(fun: Callable, *primals) -> Callable:\nraise TypeError(\"cotangent type does not match function output, \"\nf\"expected {out_avals} but got {out_cotangents}\")\ndummies = [ad.UndefinedPrimal(a) for a in in_avals]\n- in_cotangents = ad.backward_pass(jaxpr, consts, dummies, out_cotangents)\n+ in_cotangents = map(\n+ ad.instantiate_zeros,\n+ ad.backward_pass(jaxpr, consts, dummies, out_cotangents))\nreturn tree_unflatten(in_tree, in_cotangents)\nreturn transposed_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1048,6 +1048,13 @@ class APITest(jtu.JaxTestCase):\nexpected = -5 + 10j\nself.assertEqual(actual, expected)\n+ def test_linear_transpose_zeros(self):\n+ f = lambda x: x[0]\n+ transpose = api.linear_transpose(f, [1., 2.])\n+ actual, = transpose(3.)\n+ expected = [3., 0.]\n+ self.assertEqual(actual, expected)\n+\ndef test_complex_grad_raises_error(self):\nself.assertRaises(TypeError, lambda: grad(lambda x: jnp.sin(x))(1 + 2j))\n" } ]
Python
Apache License 2.0
google/jax
Instantiate zero outputs of linear_transpose
260,335
27.03.2021 19:34:42
25,200
5a055b1dad0adfe147d67c2b59d35af6e7719322
add WIP disclaimer to autodidax, fix some typos
[ { "change_type": "MODIFY", "old_path": "docs/autodidax.ipynb", "new_path": "docs/autodidax.ipynb", "diff": "\"\\n\",\n\"Ever want to learn how JAX works, but the implementation seemed impenetrable?\\n\",\n\"Well, you're in luck! By reading this tutorial, you'll learn every big idea in\\n\",\n- \"JAX's core system. You'll even get clued into our weird jargon!\"\n+ \"JAX's core system. You'll even get clued into our weird jargon!\\n\",\n+ \"\\n\",\n+ \"**This is a work-in-progress draft.** There are some important ingredients\\n\",\n+ \"missing, still to come in parts 5 and 6 (and more?). There are also some\\n\",\n+ \"simplifications here that we haven't yet applied to the main system, but we\\n\",\n+ \"will.\"\n]\n},\n{\n\"\\n\",\n\"trace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack\\n\",\n\"\\n\",\n+ \"# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\\n\",\n\"impl_rules = {}\\n\",\n\"\\n\",\n\"impl_rules[add_p] = lambda x, y: [np.add(x, y)]\\n\",\n\"types](https://en.wikipedia.org/wiki/Substructural_type_system).)\\n\",\n\"\\n\",\n\"All that remains is to write `tree_flatten`, `tree_unflatten`, and\\n\",\n- \"`flatten_fun`:\"\n+ \"`flatten_fun`.\"\n]\n},\n{\n\"cell_type\": \"code\",\n\"execution_count\": null,\n\"metadata\": {\n- \"lines_to_next_cell\": 1\n+ \"lines_to_next_cell\": 1,\n+ \"tags\": [\n+ \"hide-input\"\n+ ]\n},\n\"outputs\": [],\n\"source\": [\n\"execution_count\": null,\n\"metadata\": {\n\"lines_to_end_of_cell_marker\": 0,\n- \"lines_to_next_cell\": 1\n+ \"lines_to_next_cell\": 1,\n+ \"tags\": [\n+ \"hide-input\"\n+ ]\n},\n\"outputs\": [],\n\"source\": [\n\" def builder(self):\\n\",\n\" return self.main.global_data\\n\",\n\"\\n\",\n- \"# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\\n\",\n+ \"# NB: in JAX, we instead attach abstract eval rules to Primitive instances\\n\",\n\"abstract_eval_rules = {}\"\n]\n},\n\" x, = in_vals\\n\",\n\" dims_complement = [i for i in range(len(shape)) if i not in axes]\\n\",\n\" return [xops.BroadcastInDim(x, shape, dims_complement)]\\n\",\n- \"xla_translations[broadcast_p] = broadcast_translation\\n\",\n- \"\\n\",\n- \"def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\\n\",\n- \" del num_consts # Only used at top-level.\\n\",\n- \" # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\\n\",\n- \" subc = xb.make_computation_builder('inner xla_call')\\n\",\n- \" xla_params = _xla_params(subc, in_avals)\\n\",\n- \" outs = jaxpr_subcomp(subc, jaxpr, xla_params)\\n\",\n- \" subc = subc.build(xops.Tuple(subc, outs))\\n\",\n- \" return destructure_tuple(c, xops.Call(c, subc, in_vals))\\n\",\n- \"xla_translations[xla_call_p] = xla_call_translation\\n\",\n- \"\\n\",\n- \"def destructure_tuple(c, tup):\\n\",\n- \" num_elements = len(c.get_shape(tup).tuple_shapes())\\n\",\n- \" return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\"\n+ \"xla_translations[broadcast_p] = broadcast_translation\"\n]\n},\n{\n\" if not all(t1 == t2 for t1, t2 in zip(jaxpr_type.in_types, in_types)):\\n\",\n\" raise TypeError\\n\",\n\" return jaxpr_type.out_types\\n\",\n- \"abstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule\"\n+ \"abstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule\\n\",\n+ \"\\n\",\n+ \"def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\\n\",\n+ \" del num_consts # Only used at top-level.\\n\",\n+ \" # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\\n\",\n+ \" subc = xb.make_computation_builder('inner xla_call')\\n\",\n+ \" xla_params = _xla_params(subc, in_avals)\\n\",\n+ \" outs = jaxpr_subcomp(subc, jaxpr, xla_params)\\n\",\n+ \" subc = subc.build(xops.Tuple(subc, outs))\\n\",\n+ \" return destructure_tuple(c, xops.Call(c, subc, in_vals))\\n\",\n+ \"xla_translations[xla_call_p] = xla_call_translation\\n\",\n+ \"\\n\",\n+ \"def destructure_tuple(c, tup):\\n\",\n+ \" num_elements = len(c.get_shape(tup).tuple_shapes())\\n\",\n+ \" return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\"\n]\n},\n{\n\"source\": [\n\"Partial evaluation will take a list of `PartialVal`s representing inputs, and\\n\",\n\"return a list of `PartialVal` outputs along with a jaxpr representing the\\n\",\n- \"dleayed computation:\"\n+ \"delayed computation:\"\n]\n},\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {},\n\"source\": [\n- \"To handle linearize-of-jit, we still need to write a partial evaluation rule\\n\",\n- \"for `xla_call_p`. Other than tracer bookkeeping, the main task is to perform\\n\",\n- \"partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\"\n+ \"To handle `linearize`-of-`jit`, we still need to write a partial evaluation\\n\",\n+ \"rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to\\n\",\n+ \"perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.md", "new_path": "docs/autodidax.md", "diff": "@@ -42,6 +42,11 @@ Ever want to learn how JAX works, but the implementation seemed impenetrable?\nWell, you're in luck! By reading this tutorial, you'll learn every big idea in\nJAX's core system. You'll even get clued into our weird jargon!\n+**This is a work-in-progress draft.** There are some important ingredients\n+missing, still to come in parts 5 and 6 (and more?). There are also some\n+simplifications here that we haven't yet applied to the main system, but we\n+will.\n+\n+++\n## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap`\n@@ -405,6 +410,7 @@ class EvalTrace(Trace):\ntrace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack\n+# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\nimpl_rules = {}\nimpl_rules[add_p] = lambda x, y: [np.add(x, y)]\n@@ -633,9 +639,11 @@ the \"linear\" name in `linear_util.py`, in the sense of [linear\ntypes](https://en.wikipedia.org/wiki/Substructural_type_system).)\nAll that remains is to write `tree_flatten`, `tree_unflatten`, and\n-`flatten_fun`:\n+`flatten_fun`.\n```{code-cell}\n+:tags: [hide-input]\n+\ndef flatten_fun(f, in_tree):\nstore = Store()\n@@ -663,6 +671,8 @@ class Store:\n```\n```{code-cell}\n+:tags: [hide-input]\n+\nimport itertools as it\nfrom typing import Callable, Type, Hashable, Dict, Iterable, Iterator\n@@ -1114,7 +1124,7 @@ class JaxprTrace(Trace):\ndef builder(self):\nreturn self.main.global_data\n-# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\n+# NB: in JAX, we instead attach abstract eval rules to Primitive instances\nabstract_eval_rules = {}\n```\n@@ -1582,20 +1592,6 @@ def broadcast_translation(c, in_avals, in_vals, *, shape, axes):\ndims_complement = [i for i in range(len(shape)) if i not in axes]\nreturn [xops.BroadcastInDim(x, shape, dims_complement)]\nxla_translations[broadcast_p] = broadcast_translation\n-\n-def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\n- del num_consts # Only used at top-level.\n- # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\n- subc = xb.make_computation_builder('inner xla_call')\n- xla_params = _xla_params(subc, in_avals)\n- outs = jaxpr_subcomp(subc, jaxpr, xla_params)\n- subc = subc.build(xops.Tuple(subc, outs))\n- return destructure_tuple(c, xops.Call(c, subc, in_vals))\n-xla_translations[xla_call_p] = xla_call_translation\n-\n-def destructure_tuple(c, tup):\n- num_elements = len(c.get_shape(tup).tuple_shapes())\n- return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\n```\nWith that, we can now use `jit` to stage out, compile, and execute programs\n@@ -1713,6 +1709,20 @@ def xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts):\nraise TypeError\nreturn jaxpr_type.out_types\nabstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule\n+\n+def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\n+ del num_consts # Only used at top-level.\n+ # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\n+ subc = xb.make_computation_builder('inner xla_call')\n+ xla_params = _xla_params(subc, in_avals)\n+ outs = jaxpr_subcomp(subc, jaxpr, xla_params)\n+ subc = subc.build(xops.Tuple(subc, outs))\n+ return destructure_tuple(c, xops.Call(c, subc, in_vals))\n+xla_translations[xla_call_p] = xla_call_translation\n+\n+def destructure_tuple(c, tup):\n+ num_elements = len(c.get_shape(tup).tuple_shapes())\n+ return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\n```\n```{code-cell}\n@@ -1972,7 +1982,7 @@ class PartialVal(NamedTuple):\nPartial evaluation will take a list of `PartialVal`s representing inputs, and\nreturn a list of `PartialVal` outputs along with a jaxpr representing the\n-dleayed computation:\n+delayed computation:\n```{code-cell}\ndef partial_eval_flat(f, pvals_in: List[PartialVal]):\n@@ -2195,9 +2205,9 @@ print(y, sin(3.))\nprint(sin_lin(1.), cos(3.))\n```\n-To handle linearize-of-jit, we still need to write a partial evaluation rule\n-for `xla_call_p`. Other than tracer bookkeeping, the main task is to perform\n-partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\n+To handle `linearize`-of-`jit`, we still need to write a partial evaluation\n+rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to\n+perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\n```{code-cell}\ndef xla_call_partial_eval(trace, tracers, *, jaxpr, num_consts):\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.py", "new_path": "docs/autodidax.py", "diff": "# Ever want to learn how JAX works, but the implementation seemed impenetrable?\n# Well, you're in luck! By reading this tutorial, you'll learn every big idea in\n# JAX's core system. You'll even get clued into our weird jargon!\n+#\n+# **This is a work-in-progress draft.** There are some important ingredients\n+# missing, still to come in parts 5 and 6 (and more?). There are also some\n+# simplifications here that we haven't yet applied to the main system, but we\n+# will.\n# ## Part 1: Transformations as interpreters: standard evaluation, `jvp`, and `vmap`\n#\n@@ -386,6 +391,7 @@ class EvalTrace(Trace):\ntrace_stack.append(MainTrace(0, EvalTrace, None)) # special bottom of the stack\n+# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\nimpl_rules = {}\nimpl_rules[add_p] = lambda x, y: [np.add(x, y)]\n@@ -600,9 +606,9 @@ def jvp(f, primals, tangents):\n# types](https://en.wikipedia.org/wiki/Substructural_type_system).)\n#\n# All that remains is to write `tree_flatten`, `tree_unflatten`, and\n-# `flatten_fun`:\n+# `flatten_fun`.\n-# +\n+# + tags=[\"hide-input\"]\ndef flatten_fun(f, in_tree):\nstore = Store()\n@@ -628,7 +634,7 @@ class Store:\ndef __call__(self):\nreturn self.val\n-# +\n+# + tags=[\"hide-input\"]\nimport itertools as it\nfrom typing import Callable, Type, Hashable, Dict, Iterable, Iterator\n@@ -1074,7 +1080,7 @@ class JaxprTrace(Trace):\ndef builder(self):\nreturn self.main.global_data\n-# NB: in JAX, instead of a dict we attach impl rules to the Primitive instance\n+# NB: in JAX, we instead attach abstract eval rules to Primitive instances\nabstract_eval_rules = {}\n# -\n@@ -1524,20 +1530,6 @@ def broadcast_translation(c, in_avals, in_vals, *, shape, axes):\ndims_complement = [i for i in range(len(shape)) if i not in axes]\nreturn [xops.BroadcastInDim(x, shape, dims_complement)]\nxla_translations[broadcast_p] = broadcast_translation\n-\n-def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\n- del num_consts # Only used at top-level.\n- # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\n- subc = xb.make_computation_builder('inner xla_call')\n- xla_params = _xla_params(subc, in_avals)\n- outs = jaxpr_subcomp(subc, jaxpr, xla_params)\n- subc = subc.build(xops.Tuple(subc, outs))\n- return destructure_tuple(c, xops.Call(c, subc, in_vals))\n-xla_translations[xla_call_p] = xla_call_translation\n-\n-def destructure_tuple(c, tup):\n- num_elements = len(c.get_shape(tup).tuple_shapes())\n- return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\n# -\n# With that, we can now use `jit` to stage out, compile, and execute programs\n@@ -1636,9 +1628,7 @@ def unmapped_aval(axis_size: int, batch_dim: BatchAxis, aval: ShapedArray\nshape.insert(batch_dim, axis_size)\nreturn ShapedArray(tuple(shape), aval.dtype)\n-\n-# -\n-\n+# +\ndef xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts):\ndel num_consts # Unused.\njaxpr_type = typecheck_jaxpr(jaxpr)\n@@ -1647,6 +1637,20 @@ def xla_call_abstract_eval_rule(*in_types, jaxpr, num_consts):\nreturn jaxpr_type.out_types\nabstract_eval_rules[xla_call_p] = xla_call_abstract_eval_rule\n+def xla_call_translation(c, in_avals, in_vals, *, jaxpr, num_consts):\n+ del num_consts # Only used at top-level.\n+ # Calling jaxpr_subcomp directly would inline. We generate a Call HLO instead.\n+ subc = xb.make_computation_builder('inner xla_call')\n+ xla_params = _xla_params(subc, in_avals)\n+ outs = jaxpr_subcomp(subc, jaxpr, xla_params)\n+ subc = subc.build(xops.Tuple(subc, outs))\n+ return destructure_tuple(c, xops.Call(c, subc, in_vals))\n+xla_translations[xla_call_p] = xla_call_translation\n+\n+def destructure_tuple(c, tup):\n+ num_elements = len(c.get_shape(tup).tuple_shapes())\n+ return [xops.GetTupleElement(tup, i) for i in range(num_elements)]\n+\n# +\n@jit\ndef f(x):\n@@ -1895,7 +1899,7 @@ class PartialVal(NamedTuple):\n# Partial evaluation will take a list of `PartialVal`s representing inputs, and\n# return a list of `PartialVal` outputs along with a jaxpr representing the\n-# dleayed computation:\n+# delayed computation:\ndef partial_eval_flat(f, pvals_in: List[PartialVal]):\nwith new_main(PartialEvalTrace) as main:\n@@ -2113,9 +2117,9 @@ y, sin_lin = linearize(sin, 3.)\nprint(y, sin(3.))\nprint(sin_lin(1.), cos(3.))\n-# To handle linearize-of-jit, we still need to write a partial evaluation rule\n-# for `xla_call_p`. Other than tracer bookkeeping, the main task is to perform\n-# partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\n+# To handle `linearize`-of-`jit`, we still need to write a partial evaluation\n+# rule for `xla_call_p`. Other than tracer bookkeeping, the main task is to\n+# perform partial evaluation of a jaxpr, 'unzipping' it into two jaxprs.\n# +\ndef xla_call_partial_eval(trace, tracers, *, jaxpr, num_consts):\n" } ]
Python
Apache License 2.0
google/jax
add WIP disclaimer to autodidax, fix some typos
260,470
27.03.2021 21:47:07
25,200
0d19b7c082c555ceb6fa963791a23cf27eb1c33a
Mirror the minor spelling fixes over the {.ipynb, .md, .py}.
[ { "change_type": "MODIFY", "old_path": "docs/autodidax.ipynb", "new_path": "docs/autodidax.ipynb", "diff": "\"interpreter will build a jaxpr on the fly while tracking data dependencies. To\\n\",\n\"do so, it builds a bipartite directed acyclic graph (DAG) between\\n\",\n\"`PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe`\\n\",\n- \"nodes, representing formulas for how to compute some values from others. One kind\\n\",\n- \"of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\\n\",\n+ \"nodes, representing formulas for how to compute some values from others. One\\n\",\n+ \"kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\\n\",\n\"application, but we also have recipe types for constants and lambda binders:\"\n]\n},\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.md", "new_path": "docs/autodidax.md", "diff": "@@ -71,7 +71,7 @@ flow through our program. For example, we might want to replace the\napplication of every primitive with an application of [its JVP\nrule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\nand let primal-tangent pairs flow through our program. Moreover, we want to be\n-able to comopse multiple transformations, leading to stacks of interpreters.\n+able to compose multiple transformations, leading to stacks of interpreters.\n+++\n@@ -125,7 +125,7 @@ to `bind`, and in particular we follow a handy internal convention: when we\ncall `bind`, we pass values representing array data as positional arguments,\nand we pass metadata like the `axis` argument to `sum_p` via keyword. This\ncalling convention simplifies some core logic (since e.g. instances of the\n-`Tracer` class to be defined below can only occurr in positional arguments to\n+`Tracer` class to be defined below can only occur in positional arguments to\n`bind`). The wrappers can also provide docstrings!\nWe represent active interpreters as a stack. The stack is just a simple\n@@ -174,7 +174,7 @@ evaluation. So at the bottom we'll put an evaluation interpreter.\nLet's sketch out the interface for interpreters, which is based on the `Trace`\nand `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps\ncarrying some extra context data used by the interpreter. A `Trace` handles\n-boxing up vales into `Tracers` and also handles primitive application.\n+boxing up values into `Tracers` and also handles primitive application.\n```{code-cell}\nclass Trace:\n@@ -1750,7 +1750,7 @@ print(ys)\nOne piece missing is device memory persistence for arrays. That is, we've\ndefined `handle_result` to transfer results back to CPU memory as NumPy\n-arrays, but it's often preferrable to avoid transferring results just to\n+arrays, but it's often preferable to avoid transferring results just to\ntransfer them back for the next operation. We can do that by introducing a\n`DeviceArray` class, which can wrap XLA buffers and otherwise duck-type\n`numpy.ndarray`s:\n@@ -1831,7 +1831,7 @@ we evaluate all the primal values as we trace, but stage the tangent\ncomputations into a jaxpr. This is our second way to build jaxprs. But where\n`make_jaxpr` and its underlying `JaxprTrace`/`JaxprTracer` interpreters aim\nto stage out every primitive bind, this second approach stages out only those\n-primitive binds with a data dependence on tagent inputs.\n+primitive binds with a data dependence on tangent inputs.\nFirst, some utilities:\n@@ -1897,7 +1897,7 @@ behavior relies on the data dependencies inside the given Python callable and\nnot just its type. Nevertheless a heuristic type signature is useful. If we\nassume the input function's type signature is `(a1, a2) -> (b1, b2)`, where\n`a1` and `a2` represent the known and unknown inputs, respectively, and where\n-`b1` only has a data depenence on `a1` while `b2` has some data dependnece on\n+`b1` only has a data dependency on `a1` while `b2` has some data dependency on\n`a2`, then we might write\n```\n@@ -2000,8 +2000,8 @@ Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This\ninterpreter will build a jaxpr on the fly while tracking data dependencies. To\ndo so, it builds a bipartite directed acyclic graph (DAG) between\n`PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe`\n-nodes, representing formulas for how compute some values from others. One kind\n-of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\n+nodes, representing formulas for how to compute some values from others. One\n+kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\napplication, but we also have recipe types for constants and lambda binders:\n```{code-cell}\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.py", "new_path": "docs/autodidax.py", "diff": "# application of every primitive with an application of [its JVP\n# rule](https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html),\n# and let primal-tangent pairs flow through our program. Moreover, we want to be\n-# able to comopse multiple transformations, leading to stacks of interpreters.\n+# able to compose multiple transformations, leading to stacks of interpreters.\n# ### JAX core machinery\n#\n@@ -113,7 +113,7 @@ def bind1(prim, *args, **params):\n# call `bind`, we pass values representing array data as positional arguments,\n# and we pass metadata like the `axis` argument to `sum_p` via keyword. This\n# calling convention simplifies some core logic (since e.g. instances of the\n-# `Tracer` class to be defined below can only occurr in positional arguments to\n+# `Tracer` class to be defined below can only occur in positional arguments to\n# `bind`). The wrappers can also provide docstrings!\n#\n# We represent active interpreters as a stack. The stack is just a simple\n@@ -162,7 +162,7 @@ def new_main(trace_type: Type['Trace'], global_data=None):\n# Let's sketch out the interface for interpreters, which is based on the `Trace`\n# and `Tracer` base classes. A `Tracer` represents a boxed-up value, perhaps\n# carrying some extra context data used by the interpreter. A `Trace` handles\n-# boxing up vales into `Tracers` and also handles primitive application.\n+# boxing up values into `Tracers` and also handles primitive application.\nclass Trace:\nmain: MainTrace\n@@ -1672,7 +1672,7 @@ print(ys)\n# One piece missing is device memory persistence for arrays. That is, we've\n# defined `handle_result` to transfer results back to CPU memory as NumPy\n-# arrays, but it's often preferrable to avoid transferring results just to\n+# arrays, but it's often preferable to avoid transferring results just to\n# transfer them back for the next operation. We can do that by introducing a\n# `DeviceArray` class, which can wrap XLA buffers and otherwise duck-type\n# `numpy.ndarray`s:\n@@ -1750,7 +1750,7 @@ print(ydot)\n# computations into a jaxpr. This is our second way to build jaxprs. But where\n# `make_jaxpr` and its underlying `JaxprTrace`/`JaxprTracer` interpreters aim\n# to stage out every primitive bind, this second approach stages out only those\n-# primitive binds with a data dependence on tagent inputs.\n+# primitive binds with a data dependence on tangent inputs.\n#\n# First, some utilities:\n@@ -1816,7 +1816,7 @@ def vspace(aval: ShapedArray) -> ShapedArray:\n# not just its type. Nevertheless a heuristic type signature is useful. If we\n# assume the input function's type signature is `(a1, a2) -> (b1, b2)`, where\n# `a1` and `a2` represent the known and unknown inputs, respectively, and where\n-# `b1` only has a data depenence on `a1` while `b2` has some data dependnece on\n+# `b1` only has a data dependency on `a1` while `b2` has some data dependency on\n# `a2`, then we might write\n#\n# ```\n@@ -1915,9 +1915,10 @@ def partial_eval_flat(f, pvals_in: List[PartialVal]):\n# interpreter will build a jaxpr on the fly while tracking data dependencies. To\n# do so, it builds a bipartite directed acyclic graph (DAG) between\n# `PartialEvalTracer` nodes, representing staged-out values, and `JaxprRecipe`\n-# nodes, representing formulas for how compute some values from others. One kind\n-# of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s primitive\n-# application, but we also have recipe types for constants and lambda binders:\n+# nodes, representing formulas for how to compute some values from others. One\n+# kind of recipe is a `JaxprEqnRecipe`, corresponding to a `JaxprEqn`'s\n+# primitive application, but we also have recipe types for constants and lambda\n+# binders:\n# +\nfrom weakref import ref, ReferenceType\n" } ]
Python
Apache License 2.0
google/jax
Mirror the minor spelling fixes over the {.ipynb, .md, .py}.
260,335
28.03.2021 10:32:02
25,200
8547c71bfd26f96d00ddb8bbe825d90014e2adf5
simplify public lax.convert_element_type api Specifically: 1. don't expose weak_type in the public api, as it's jax-internal 2. don't make new_dtype optional, which could make bugs easier This change keeps the public API simpler, and also makes convert_element_type match the ConvertElementType HLO. As an internal API we can call lax._convert_element_type just like before.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -409,9 +409,9 @@ def lt(x: Array, y: Array) -> Array:\nr\"\"\"Elementwise less-than: :math:`x < y`.\"\"\"\nreturn lt_p.bind(x, y)\n-def convert_element_type(operand: Array, new_dtype: DType = None,\n- weak_type: bool = False) -> Array:\n+def convert_element_type(operand: Array, new_dtype: DType) -> Array:\n\"\"\"Elementwise cast.\n+\nWraps XLA's `ConvertElementType\n<https://www.tensorflow.org/xla/operation_semantics#convertelementtype>`_\noperator, which performs an elementwise conversion from one type to another.\n@@ -419,15 +419,17 @@ def convert_element_type(operand: Array, new_dtype: DType = None,\nArgs:\noperand: an array or scalar value to be cast\n- new_dtype: the new type. Should be a NumPy type.\n- weak_type: whether the new dtype should be weak.\n+ new_dtype: a NumPy dtype representing the target type.\nReturns:\nAn array with the same shape as `operand`, cast elementwise to `new_dtype`.\n\"\"\"\nif hasattr(operand, '__jax_array__'):\noperand = operand.__jax_array__()\n+ return _convert_element_type(operand, new_dtype, weak_type=False)\n+def _convert_element_type(operand: Array, new_dtype: Optional[DType] = None,\n+ weak_type: bool = False):\n# Don't canonicalize old_dtype because x64 context might cause\n# un-canonicalized operands to be passed in.\nold_dtype = np.result_type(operand)\n@@ -1169,7 +1171,8 @@ def reduce(operands: Array, init_values: Array, computation: Callable,\nif monoid_reducer:\n# monoid reducers bypass the weak_type_rule, so we set it explicitly.\nweak_type = dtypes.is_weakly_typed(*flat_operands) and dtypes.is_weakly_typed(*flat_init_values)\n- return convert_element_type(monoid_reducer(*flat_operands, dimensions), weak_type=weak_type)\n+ return _convert_element_type(monoid_reducer(*flat_operands, dimensions),\n+ weak_type=weak_type)\nelse:\nflat_init_avals = safe_map(_abstractify, flat_init_values)\njaxpr, consts, out_tree = _variadic_reduction_jaxpr(\n@@ -1495,7 +1498,7 @@ def full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Arra\nraise TypeError(msg.format(np.shape(fill_value)))\nweak_type = dtype is None and dtypes.is_weakly_typed(fill_value)\ndtype = dtypes.canonicalize_dtype(dtype or _dtype(fill_value))\n- fill_value = convert_element_type(fill_value, dtype, weak_type)\n+ fill_value = _convert_element_type(fill_value, dtype, weak_type)\nreturn broadcast(fill_value, shape)\ndef _device_put_raw(x, weak_type=None):\n@@ -1540,7 +1543,8 @@ def _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\niotas = [broadcasted_iota(np.uint32, base_shape, i)\nfor i in range(len(base_shape))]\neyes = [eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]\n- result = convert_element_type_p.bind(_reduce(operator.and_, eyes), new_dtype=dtype, weak_type=False)\n+ result = convert_element_type_p.bind(_reduce(operator.and_, eyes),\n+ new_dtype=dtype, weak_type=False)\nreturn broadcast_in_dim(result, shape, axes)\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n@@ -1765,7 +1769,7 @@ def full_like(x: Array, fill_value: Array, dtype: Optional[DType] = None,\ndtype = dtype or _dtype(x)\nif not config.omnistaging_enabled:\nfill_value = tie_in(x, fill_value)\n- return full(fill_shape, convert_element_type(fill_value, dtype, weak_type))\n+ return full(fill_shape, _convert_element_type(fill_value, dtype, weak_type))\ndef collapse(operand: Array, start_dimension: int,\n@@ -2703,13 +2707,15 @@ def _convert_element_type_transpose_rule(ct, operand, *, new_dtype, weak_type):\nelif core.primal_dtype_to_tangent_dtype(old_dtype) is dtypes.float0:\nreturn [ad_util.Zero(operand.aval.update(dtype=dtypes.float0, weak_type=False))]\nelse:\n- return [convert_element_type_p.bind(ct, new_dtype=old_dtype, weak_type=old_weak_type)]\n+ return [convert_element_type_p.bind(ct, new_dtype=old_dtype,\n+ weak_type=old_weak_type)]\ndef _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, weak_type):\nif core.primal_dtype_to_tangent_dtype(new_dtype) is dtypes.float0:\nreturn ad_util.Zero(tangent.aval.update(dtype=dtypes.float0, weak_type=False))\nelse:\n- return convert_element_type_p.bind(tangent, new_dtype=new_dtype, weak_type=weak_type)\n+ return convert_element_type_p.bind(tangent, new_dtype=new_dtype,\n+ weak_type=weak_type)\nconvert_element_type_p = core.convert_element_type_p\nconvert_element_type_p.def_impl(partial(xla.apply_primitive, convert_element_type_p))\n@@ -5900,7 +5906,8 @@ def _top_k_abstract_eval(operand, *, k):\nmsg = \"k argument to top_k must be no larger than minor dimension; {} vs {}\"\nraise ValueError(msg.format(k, shape))\nshape[-1] = k\n- return (operand.update(shape=shape, dtype=operand.dtype, weak_type=operand.weak_type),\n+ return (operand.update(shape=shape, dtype=operand.dtype,\n+ weak_type=operand.weak_type),\noperand.update(shape=shape, dtype=np.dtype(np.int32)))\ndef _top_k_jvp(primals, tangents, *, k):\n@@ -6101,7 +6108,8 @@ def _rng_uniform_abstract_eval(a, b, *, shape):\nraise ValueError(\n\"Arguments to rng_uniform must be scalars; got shapes {} and {}.\"\n.format(a.shape, b.shape))\n- return a.update(shape=shape, dtype=a.dtype, weak_type=(a.weak_type and b.weak_type))\n+ return a.update(shape=shape, dtype=a.dtype,\n+ weak_type=(a.weak_type and b.weak_type))\ndef _rng_uniform_translation_rule(c, a, b, *, shape):\nxla_shape = xc.Shape.array_shape(c.get_shape(a).xla_element_type(), shape)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -266,7 +266,7 @@ def _promote_dtypes(*args):\nelse:\nto_dtype, weak_type = dtypes._lattice_result_type(*args)\nto_dtype = dtypes.canonicalize_dtype(to_dtype)\n- return [lax.convert_element_type(x, to_dtype, weak_type) for x in args]\n+ return [lax._convert_element_type(x, to_dtype, weak_type) for x in args]\ndef _promote_dtypes_inexact(*args):\n\"\"\"Convenience function to apply Numpy argument dtype promotion.\n@@ -276,7 +276,7 @@ def _promote_dtypes_inexact(*args):\nto_dtype = dtypes.canonicalize_dtype(to_dtype)\nto_dtype_inexact = _to_inexact_dtype(to_dtype)\nweak_type = (weak_type and to_dtype == to_dtype_inexact)\n- return [lax.convert_element_type(x, to_dtype_inexact, weak_type) for x in args]\n+ return [lax._convert_element_type(x, to_dtype_inexact, weak_type) for x in args]\ndef _to_inexact_dtype(dtype):\n\"\"\"Promotes a dtype into an inexact dtype, if it is not already one.\"\"\"\n@@ -2922,7 +2922,7 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nraise TypeError(\"Unexpected input type for array: {}\".format(type(object)))\n- out = lax.convert_element_type(out, dtype, weak_type=weak_type)\n+ out = lax._convert_element_type(out, dtype, weak_type=weak_type)\nif ndmin > ndim(out):\nout = lax.broadcast(out, (1,) * (ndmin - ndim(out)))\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -94,6 +94,7 @@ from jax._src.lax.lax import (\nconv_transpose_shape_tuple,\nconv_with_general_padding,\nconvert_element_type,\n+ _convert_element_type,\nconvert_element_type_p,\ncos,\ncos_p,\n" }, { "change_type": "MODIFY", "old_path": "tests/dtypes_test.py", "new_path": "tests/dtypes_test.py", "diff": "@@ -340,7 +340,7 @@ class TestPromotionTables(jtu.JaxTestCase):\n)\ndef testUnaryPromotion(self, dtype, weak_type):\n# Regression test for https://github.com/google/jax/issues/6051\n- x = lax.convert_element_type(0, dtype, weak_type=weak_type)\n+ x = lax._convert_element_type(0, dtype, weak_type=weak_type)\ny = jnp.array(0, dtype=dtypes.result_type(x))\nassert x.dtype == y.dtype\n@@ -352,7 +352,7 @@ class TestPromotionTables(jtu.JaxTestCase):\n)\ndef testBinaryNonPromotion(self, dtype, weak_type):\n# Regression test for https://github.com/google/jax/issues/6051\n- x = lax.convert_element_type(0, dtype, weak_type=weak_type)\n+ x = lax._convert_element_type(0, dtype, weak_type=weak_type)\ny = (x + x)\nassert x.dtype == y.dtype\nassert dtypes.is_weakly_typed(y) == dtypes.is_weakly_typed(x)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -2857,7 +2857,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nif numpy_version < (1, 19) and out_shape == ():\nraise SkipTest(\"Numpy < 1.19 treats out_shape=() like out_shape=None\")\nrng = jtu.rand_default(self.rng())\n- x = lax.convert_element_type(rng(shape, in_dtype), weak_type=weak_type)\n+ x = lax._convert_element_type(rng(shape, in_dtype), weak_type=weak_type)\nfun = lambda x: getattr(jnp, func)(x, *args, dtype=out_dtype, shape=out_shape)\nexpected_weak_type = weak_type and (out_dtype is None)\nself.assertEqual(dtypes.is_weakly_typed(fun(x)), expected_weak_type)\n@@ -2889,7 +2889,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nfor slc in [slice(None), slice(0), slice(3), 0, ...]))\ndef testSliceWeakTypes(self, shape, dtype, weak_type, slc):\nrng = jtu.rand_default(self.rng())\n- x = lax.convert_element_type(rng(shape, dtype), weak_type=weak_type)\n+ x = lax._convert_element_type(rng(shape, dtype), weak_type=weak_type)\nop = lambda x: x[slc]\nself.assertEqual(op(x).aval.weak_type, weak_type)\nself.assertEqual(api.jit(op)(x).aval.weak_type, weak_type)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -217,7 +217,7 @@ class LaxTest(jtu.JaxTestCase):\ndef testConvertElementType(self, from_dtype, to_dtype, weak_type):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: [rng((2, 3), from_dtype)]\n- op = lambda x: lax.convert_element_type(x, to_dtype, weak_type)\n+ op = lambda x: lax._convert_element_type(x, to_dtype, weak_type)\nself._CompileAndCheck(op, args_maker)\nx = rng((1,), from_dtype)\n@@ -272,7 +272,8 @@ class LaxTest(jtu.JaxTestCase):\nfor weak_type in [True, False]))\ndef testBitcastConvertWeakType(self, from_dtype, to_dtype, weak_type):\nrng = jtu.rand_default(self.rng())\n- x_in = lax.convert_element_type(rng((2, 3), from_dtype), weak_type=weak_type)\n+ x_in = lax._convert_element_type(rng((2, 3), from_dtype),\n+ weak_type=weak_type)\nop = lambda x: lax.bitcast_convert_type(x, to_dtype)\nself.assertEqual(dtypes.is_weakly_typed(x_in), weak_type)\nx_out = op(x_in)\n@@ -1535,8 +1536,8 @@ class LaxTest(jtu.JaxTestCase):\nfor init_weak_type in [True, False]))\ndef testReduceWeakType(self, op_namespace, op, arr_weak_type, init_weak_type):\nop = getattr(op_namespace, op)\n- arr = lax.convert_element_type(np.arange(10), int, weak_type=arr_weak_type)\n- init = lax.convert_element_type(1, int, weak_type=init_weak_type)\n+ arr = lax._convert_element_type(np.arange(10), int, weak_type=arr_weak_type)\n+ init = lax._convert_element_type(1, int, weak_type=init_weak_type)\nfun = lambda arr, init: lax.reduce(arr, init, op, (0,))\nout = fun(arr, init)\nself.assertEqual(dtypes.is_weakly_typed(out), arr_weak_type and init_weak_type)\n@@ -2309,7 +2310,7 @@ class LaxTest(jtu.JaxTestCase):\nif dtype in set(python_scalar_types):\nval = dtype(0)\nelse:\n- val = lax.convert_element_type(0, dtype, weak_type=weak_type)\n+ val = lax._convert_element_type(0, dtype, weak_type=weak_type)\nconst = lax._const(val, 0)\nself.assertEqual(dtypes.result_type(val), dtypes.result_type(const))\n@@ -2445,7 +2446,7 @@ class LazyConstantTest(jtu.JaxTestCase):\nfor weak_type in [True, False]))\ndef testArgMinMaxWeakType(self, jax_fn, weak_type):\nop = lambda x: jax_fn(x, axis=0, index_dtype=np.int32)\n- x_in = lax.convert_element_type(np.ones((2, 2)), weak_type=weak_type)\n+ x_in = lax._convert_element_type(np.ones((2, 2)), weak_type=weak_type)\nself.assertEqual(dtypes.is_weakly_typed(x_in), weak_type)\nx_out = op(x_in)\nself.assertEqual(dtypes.is_weakly_typed(x_out), False)\n" } ]
Python
Apache License 2.0
google/jax
simplify public lax.convert_element_type api Specifically: 1. don't expose weak_type in the public api, as it's jax-internal 2. don't make new_dtype optional, which could make bugs easier This change keeps the public API simpler, and also makes convert_element_type match the ConvertElementType HLO. As an internal API we can call lax._convert_element_type just like before.
260,335
28.03.2021 11:17:41
25,200
4253c929ec06060a5150362d885979cdc1f97323
use correct batching util in custom_vjp_call_jaxpr fixes
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -654,7 +654,7 @@ def _custom_vjp_call_jaxpr_vmap(\nfwd_args_batched = [0 if b else not_mapped for b in args_batched]\nfwd_out_dims = lambda: out_dims2[0]\n- batched_bwd = batching.batch(bwd, axis_name, axis_size, fwd_out_dims,\n+ batched_bwd = batching.batch_custom_vjp_bwd(bwd, axis_name, axis_size, fwd_out_dims,\nfwd_args_batched)\nbatched_outs = custom_vjp_call_jaxpr_p.bind(\n" } ]
Python
Apache License 2.0
google/jax
use correct batching util in custom_vjp_call_jaxpr fixes #5832
260,411
29.03.2021 14:15:27
-10,800
5fce79ed441f40b73d29fd95ec312bc9ed3fa912
Update fft_test.py Trivial change to re-trigger the presubmit checks
[ { "change_type": "MODIFY", "old_path": "tests/fft_test.py", "new_path": "tests/fft_test.py", "diff": "@@ -119,7 +119,6 @@ class FftTest(jtu.JaxTestCase):\ndef testIrfftTranspose(self):\n# regression test for https://github.com/google/jax/issues/6223\n-\ndef build_matrix(linear_func, size):\nreturn jax.vmap(linear_func)(jnp.eye(size, size))\n" } ]
Python
Apache License 2.0
google/jax
Update fft_test.py Trivial change to re-trigger the presubmit checks
260,411
29.03.2021 14:20:15
-10,800
514709963d93cc4a0424d6b354b12d49c367ff63
[jax2tf] Fixed typos, and updated the jax2tf documentation
[ { "change_type": "MODIFY", "old_path": "docs/developer.md", "new_path": "docs/developer.md", "diff": "@@ -239,7 +239,7 @@ $ jupytext --sync docs/notebooks/*\n```\nAlternatively, you can run this command via the [pre-commit](https://pre-commit.com/)\n-framework by executing the folloing in the main JAX directory:\n+framework by executing the following in the main JAX directory:\n```\n$ pre-commit run --all\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -6,10 +6,10 @@ Link: go/jax2tf-examples.\nThis directory contains a number of examples of using the\n[jax2tf converter](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md) to:\n- * save SavedModel from trained MNIST models, using both pure JAX and Flax.\n- * reuse the feature-extractor part of the trained MNIST model in\n- TensorFlow Hub, and in a larger TensorFlow Keras model.\n- * use jax2tf with TensorFlow Serving and TensorFlow JavaScript.\n+ * save SavedModel from trained MNIST models, using both Flax and pure JAX.\n+ * reuse the feature-extractor part of the trained MNIST model\n+ in a larger TensorFlow Keras model.\n+ * use Flax models with TensorFlow Serving, TensorFlow JavaScript, and TensorFlow Lite.\n# Generating TensorFlow SavedModel\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/keras_reuse_main.py", "new_path": "jax/experimental/jax2tf/examples/keras_reuse_main.py", "diff": "@@ -32,8 +32,8 @@ FLAGS = flags.FLAGS\ndef main(_):\nFLAGS.model_classifier_layer = False # We only need the features\n- saved_model_main.train_and_save(\n- ) # Train the model and save the feature extractor\n+ # Train the model and save the feature extractor\n+ saved_model_main.train_and_save()\ntf_accelerator, _ = saved_model_main.tf_accelerator_and_tolerances()\nfeature_model_dir = saved_model_main.savedmodel_dir()\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/serving/README.md", "new_path": "jax/experimental/jax2tf/examples/serving/README.md", "diff": "@@ -4,7 +4,7 @@ Using jax2tf with TensorFlow serving\nThis is a supplement to the\n[examples/README.md](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/README.md)\nwith example code and\n-instructions for using `jax2tf` with the OSS TensorFlow model server.\n+instructions for using `jax2tf` with the open source TensorFlow model server.\nSpecific instructions for Google-internal versions of model server are in the `internal` subdirectory.\nThe goal of `jax2tf` is to convert JAX functions\n@@ -43,7 +43,7 @@ We use the `tf_nightly` package to get an up-to-date version.\n```\nWe then install [TensorFlow serving in a Docker image](https://www.tensorflow.org/tfx/serving/docker),\n-again using a recent \"nightly\" version. Install Docker and then run:\n+again using a recent \"nightly\" version. Install Docker and then run.\n```shell\nDOCKER_IMAGE=tensorflow/serving:nightly\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "diff": "@@ -12,10 +12,10 @@ There are several kinds of limitations.\n* There are some cases when the converted program computes different results than\nthe JAX program, see [below](#generated-summary-of-primitives-with-known-numerical-discrepancies-in-tensorflow).\n-Note that automated tests will fail if new limitations appear, but\n-they won't when limitations are fixed. If you see a limitation that\n-you think it does not exist anymore, please ask for this file to\n-be updated.\n+Note that automated tests will ensure that this list of limitations is a\n+superset of the actual limitations. If you see a limitation that\n+you think it does not exist anymore in a recent TensorFlow version,\n+please ask for this file to be updated.\n## Generated summary of primitives with unimplemented support in Tensorflow\n@@ -32,6 +32,8 @@ The errors apply only for certain devices and compilation modes (\"eager\",\n\"graph\", and \"compiled\"). In general, \"eager\" and \"graph\" mode share the same errors.\nOn TPU only the \"compiled\" mode is relevant.\n+Our first priority is to ensure that the coverage of data types is complete for the \"compiled\" mode.\n+\nThis table only shows errors for cases that are working in JAX (see [separate\nlist of unsupported or partially-supported primitives](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md) )\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fixed typos, and updated the jax2tf documentation
260,411
29.03.2021 15:03:38
-10,800
e0a87ef062378a5526aafd86c66eb78f5daacf88
[jax2tf] Update limitations due to updates in TF
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "new_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "diff": "# Primitives with limited JAX support\n-*Last generated on: 2021-03-23* (YYYY-MM-DD)\n+*Last generated on: 2021-03-29* (YYYY-MM-DD)\n## Supported data types for primitives\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "new_path": "jax/experimental/jax2tf/g3doc/primitives_with_limited_support.md", "diff": "# Primitives with limited support for jax2tf\n-*Last generated on (YYYY-MM-DD): 2021-03-23*\n+*Last generated on (YYYY-MM-DD): 2021-03-29*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -134,7 +134,6 @@ More detailed information can be found in the\n| reduce_window_mul | TF test skipped: Not implemented in JAX: unimplemented in XLA | complex64 | tpu | compiled, eager, graph |\n| regularized_incomplete_beta | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| rem | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n-| rem | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n| rem | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| rev | TF error: op not defined for dtype | uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| round | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -1029,10 +1029,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n],\n# Only the harnesses with \"singularity\" will have divide by 0\nenabled=(\"singularity\" in harness.name)),\n- missing_tf_kernel(\n- dtypes=[np.float16],\n- devices=(\"cpu\", \"gpu\"),\n- modes=(\"eager\", \"graph\")),\n]\n@classmethod\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Update limitations due to updates in TF
260,335
29.03.2021 16:18:29
25,200
399f330f5a5d4bf0d30eb7dce7ef53c8a812d824
disable_omnistaging error, enable_omnistaging warn
[ { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -61,8 +61,7 @@ class Config:\nself._contextmanager_flags = set()\nself._update_hooks = {}\n- # TODO(mattjj): delete these when only omnistaging is available\n- self.omnistaging_enabled = bool_env('JAX_OMNISTAGING', True)\n+ self.omnistaging_enabled = True # TODO(mattjj): remove this\ndef update(self, name, val):\nif self.use_absl:\n@@ -154,25 +153,21 @@ class Config:\nalready_configured_with_absl = True\nif not FLAGS.jax_omnistaging:\n- warnings.warn(\n+ raise Exception(\n\"Disabling of omnistaging is no longer supported in JAX version 0.2.12 and higher: \"\n\"see https://github.com/google/jax/blob/master/design_notes/omnistaging.md.\\n\"\n\"To remove this warning, unset the JAX_OMNISTAGING environment variable.\")\ndef enable_omnistaging(self):\n- return # TODO(mattjj): remove all callers\n+ warnings.warn(\n+ \"enable_omnistaging() is a no-op in JAX versions 0.2.12 and higher;\\n\"\n+ \"see https://github.com/google/jax/blob/master/design_notes/omnistaging.md\")\ndef disable_omnistaging(self):\n- warnings.warn(\n+ raise Exception(\n\"Disabling of omnistaging is no longer supported in JAX version 0.2.12 and higher: \"\n\"see https://github.com/google/jax/blob/master/design_notes/omnistaging.md.\")\n- def temporary_hack_do_not_call_me(self):\n- if self.omnistaging_enabled:\n- for disabler in self._omnistaging_disablers:\n- disabler()\n- self.omnistaging_enabled = False\n-\ndef define_bool_state(\nself, name: str, default: bool, help: str, *,\nupdate_global_hook: Optional[Callable[[bool], None]] = None,\n@@ -339,7 +334,8 @@ already_configured_with_absl = False\nflags.DEFINE_bool(\n'jax_omnistaging',\nbool_env('JAX_OMNISTAGING', True),\n- help='Enable staging based on dynamic context rather than data dependence.'\n+ help=('Deprecated. Setting this flag to False raises an error. Setting it '\n+ 'to True has no effect.'),\n)\nflags.DEFINE_integer(\n" } ]
Python
Apache License 2.0
google/jax
disable_omnistaging error, enable_omnistaging warn
260,411
29.03.2021 17:21:56
-10,800
d323ad0f2b44a3178e02867992ba7243d7e0f70c
[host_callback] Add support for tapping empty arrays We make sure that both the inputs and the outputs of callbacks can contain empty arrays. Most platforms do not support empty infeed, so we ensure we do not send those.
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -25,7 +25,8 @@ PLEASE REMEMBER TO CHANGE THE '..master' WITH AN ACTUAL TAG in GITHUB LINK.\nfor more information.\n* Python integers larger than the maximum `int64` value will now lead to an overflow\nin all cases, rather than being silently converted to `uint64` in some cases ({jax-issue}`#6047`).\n-\n+* Bug fixes:\n+ * `host_callback` now supports empty arrays in arguments and results ({jax-issue}`#6262`).\n## jaxlib 0.1.65 (unreleased)\n" }, { "change_type": "MODIFY", "old_path": "docs/sphinxext/jax_extensions.py", "new_path": "docs/sphinxext/jax_extensions.py", "diff": "from docutils import nodes\ndef jax_issue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n- \"\"\"Generate links to jax issues in sphinx.\n+ \"\"\"Generate links to jax issues or PRs in sphinx.\nUsage::\n:jax-issue:`1234`\nThis will output a hyperlink of the form\n- `#1234 <http://github.com/google.jax/issues/1234>`_.\n+ `#1234 <http://github.com/google/jax/issues/1234>`_. These links work even\n+ for PR numbers.\n\"\"\"\ntext = text.lstrip('#')\nif not text.isdigit():\n- raise RuntimeError(f\"Invalid content in {rawtext}: expected an issue number.\")\n+ raise RuntimeError(f\"Invalid content in {rawtext}: expected an issue or PR number.\")\nurl = \"https://github.com/google/jax/issues/{}\".format(text)\nnode = nodes.reference(rawtext, '#' + text, refuri=url, **options)\nreturn [node], []\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -272,6 +272,8 @@ program as:\nRET_CHECK failure ... Mismatch between infeed source buffer shape s8[12345] ...\n```\n+To debug the underlying cause for these messages, see the Debugging section.\n+\nOn TPU, there is currently no shape check for infeed, so we take the safer\nroute to not send anything in case of errors, and let the computation hang.\n@@ -318,9 +320,14 @@ for the C++ outfeed `receiver backend\nYou should also use the ``--verbosity=2`` flag so that you see the logs from Python.\n-For example:\n+For example, you can try to enable logging in the ``host_callback`` module:\n```\n-TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=outfeed_receiver=3,host_callback=3,outfeed_receiver_py=3,outfeed_thunk=3,infeed_thunk=3,cpu_transfer_manager=3,cpu_runtime=3,xfeed_manager=3,pjrt_client=3 python tests/host_callback_test.py --verbosity=2 HostCallbackIdTapTest.test_jit_simple\n+TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=host_callback=3 python tests/host_callback_test.py --verbosity=2 HostCallbackIdTapTest.test_tap_jit_simple\n+```\n+\n+If you want to enable logging in lower-level implementation modules try:\n+```\n+TF_CPP_MIN_LOG_LEVEL=0 TF_CPP_VMODULE=outfeed_receiver=3,host_callback=3,outfeed_receiver_py=3,outfeed_thunk=3,infeed_thunk=3,cpu_transfer_manager=3,cpu_runtime=3,xfeed_manager=3,pjrt_client=3 python tests/host_callback_test.py --verbosity=2 HostCallbackIdTapTest.test_tap_jit_simple\n```\n(For bazel tests use --test_arg=--vmodule=...\n@@ -783,30 +790,47 @@ def _outside_call_translation_rule(\n\"The last two arguments must be tokens\")\nargs_to_outfeed = args_op[:-2]\n- send_infeed = not params[\"identity\"] and len(params[\"flat_results_aval\"]) > 0\n+ identity = params[\"identity\"]\n+ flat_results_aval = params[\"flat_results_aval\"] if not identity else []\n+ # Many platforms refuse to infeed empty arrays. We generate constants\n+ # instead.\n+ non_empty_flat_results_aval = list(filter(lambda aval: not (_aval_is_empty(aval)),\n+ flat_results_aval))\n+ send_infeed = not identity and len(non_empty_flat_results_aval) > 0\ncallback_id = _register_callback(\nfunctools.partial(_outside_call_run_callback, send_infeed=send_infeed, **params))\nnext_token = _outfeed_receiver.receiver.add_outfeed(comp, current_token,\ncallback_id,\nargs_to_outfeed)\nexpecting_infeed = False\n- if params[\"identity\"]:\n+ if identity:\nresults = list(args_to_outfeed)\nnext_itoken = current_itoken\nelse:\n- flat_results_aval = params[\"flat_results_aval\"]\n- if flat_results_aval:\n+ empty_results = [\n+ xops.ConstantLiteral(comp, np.zeros(aval.shape, aval.dtype))\n+ for aval in flat_results_aval\n+ if _aval_is_empty(aval)\n+ ]\n+ if non_empty_flat_results_aval:\nafter_outfeed_itoken = xops.AfterAll(comp, [current_itoken, next_token])\nresults_and_token = xla.translations[lax.infeed_p](comp, after_outfeed_itoken,\n- shapes=flat_results_aval, partitions=None)\n+ shapes=non_empty_flat_results_aval,\n+ partitions=None)\nexpecting_infeed = True\n- next_itoken = xops.GetTupleElement(results_and_token, len(flat_results_aval))\n- results = [xops.GetTupleElement(results_and_token, i) for i in range(len(flat_results_aval))]\n+ next_itoken = xops.GetTupleElement(results_and_token, len(non_empty_flat_results_aval))\n+ non_empty_results = [xops.GetTupleElement(results_and_token, i)\n+ for i in range(len(non_empty_flat_results_aval))]\n+ results = [\n+ empty_results.pop(0) if _aval_is_empty(result_aval) else non_empty_results.pop(0)\n+ for result_aval in flat_results_aval]\nelse:\n- results = []\n+ results = empty_results\nnext_itoken = current_itoken\n+ assert len(results) == len(flat_results_aval)\n+\nassert expecting_infeed == send_infeed\nreturn xops.Tuple(comp, results + [next_token, next_itoken])\n@@ -877,7 +901,10 @@ def _outside_call_run_callback(\nraise TypeError(msg)\nif send_infeed:\n- device.transfer_to_infeed(tuple(canonical_flat_results))\n+ # Do not send the 0-sized arrays\n+ non_empty_canonical_flat_results = tuple(filter(lambda r: not _aval_is_empty(r),\n+ canonical_flat_results))\n+ device.transfer_to_infeed(non_empty_canonical_flat_results)\nreturn canonical_flat_results\nexcept Exception as e:\n@@ -910,6 +937,9 @@ def _add_transform(params: Dict, name: str, *transform_params) -> Dict:\nparams, transforms=(params.get(\"transforms\", ()) + (new_transform,)))\n+def _aval_is_empty(aval) -> bool:\n+ return np.prod(aval.shape) == 0\n+\n# TODO(necula): there must be a better way to do this.\n# The AttributeError is for regular values, the KeyError is for ConcreteArray\ndef _instantiate_zeros(arg, tan):\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -330,6 +330,18 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n3\"\"\", testing_stream.output)\ntesting_stream.reset()\n+ def test_tap_empty(self):\n+ \"\"\"Tap empty arrays.\"\"\"\n+ hcb.id_print((), output_stream=testing_stream)\n+ hcb.id_print((1., np.ones((2, 0))), what=\"second\", output_stream=testing_stream)\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"\"\"\n+ ( )\n+ what: second\n+ ( 1.00\n+ [] )\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\ndef test_tap_jit_simple(self):\njit_fun1 = api.jit(lambda x: 3. * hcb.id_print(\n2. * x, what=\"here\", output_stream=testing_stream))\n@@ -1740,6 +1752,58 @@ class HostCallbackCallTest(jtu.JaxTestCase):\nres_inside = fun(2, use_outside=False)\nself.assertAllClose(res_inside, fun(2, use_outside=True))\n+ def test_call_empty_arg(self):\n+ \"\"\"Call with empty array.\"\"\"\n+ result = np.ones((2,), dtype=np.float32)\n+ def f_outside(_):\n+ return result\n+ def fun(x):\n+ return x + hcb.call(f_outside, (),\n+ result_shape=api.ShapeDtypeStruct(result.shape, result.dtype))\n+ self.assertAllClose(2. + result, fun(2.))\n+\n+ def test_call_empty_result(self):\n+ \"\"\"Call returning empty array.\"\"\"\n+ result_shape = (2, 0)\n+ def f_outside(_):\n+ return np.ones(result_shape, dtype=np.float32)\n+ def fun(x):\n+ return x + hcb.call(f_outside, 1.,\n+ result_shape=api.ShapeDtypeStruct(result_shape, np.float32))\n+ self.assertAllClose(f_outside(0.), fun(2.))\n+\n+ def test_call_empty_result_inside_pytree(self):\n+ \"\"\"Call returning a tuple with an empty array and a non-empty one.\"\"\"\n+ result_shape_0 = (2, 0)\n+ result_shape_2 = (0,)\n+ def f_outside(_):\n+ return (np.ones(result_shape_0, dtype=np.float32),\n+ np.ones((1,), dtype=np.float32),\n+ np.ones(result_shape_2, dtype=np.float32))\n+ def fun(x):\n+ res = hcb.call(f_outside, 1.,\n+ result_shape=(api.ShapeDtypeStruct(result_shape_0, np.float32),\n+ api.ShapeDtypeStruct((1,), np.float32),\n+ api.ShapeDtypeStruct(result_shape_2, np.float32)))\n+ self.assertEqual(result_shape_0, res[0].shape)\n+ self.assertEqual(result_shape_2, res[2].shape)\n+ return x + res[1]\n+ self.assertAllClose(2 + np.ones((1,), dtype=np.float32), fun(2.))\n+\n+ def test_call_empty_result_all_pytree(self):\n+ \"\"\"Call returning a tuple of empty arrays.\"\"\"\n+ result_shape = (2, 0)\n+ def f_outside(_):\n+ return (np.ones(result_shape, dtype=np.float32),\n+ np.ones(result_shape, dtype=np.float32))\n+ def fun(x):\n+ res = hcb.call(f_outside, 1.,\n+ result_shape=(api.ShapeDtypeStruct(result_shape, np.float32),\n+ api.ShapeDtypeStruct(result_shape, np.float32)))\n+ return x + res[0] + res[1]\n+ self.assertAllClose(np.ones(result_shape, dtype=np.float32),\n+ fun(2.))\n+\ndef test_call_no_result(self):\ndef f_outside(arg):\nself.call_log_testing_stream(lambda x: None, arg,\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Add support for tapping empty arrays We make sure that both the inputs and the outputs of callbacks can contain empty arrays. Most platforms do not support empty infeed, so we ensure we do not send those.
260,424
23.03.2021 19:47:58
0
be70820ca147ca3e9a2df7d53a1c24a8e9899908
Thread through transform name.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -63,14 +63,18 @@ T = TypeVar('T')\nArray = Any\n@cache()\n-def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):\n+def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals,\n+ transform_name: str = \"\"):\nwrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n- jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)\n+ jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals,\n+ transform_name=transform_name)\nreturn jaxpr, consts, out_tree()\n@cache()\n-def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):\n- jaxpr, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)\n+def _initial_style_jaxpr(fun: Callable, in_tree, in_avals,\n+ transform_name: str = \"\"):\n+ jaxpr, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals,\n+ transform_name)\nclosed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())\nreturn closed_jaxpr, consts, out_tree\n@@ -266,8 +270,8 @@ def while_loop(cond_fun: Callable[[T], bool],\ndef _create_jaxpr(init_val):\ninit_vals, in_tree = tree_flatten((init_val,))\ninit_avals = tuple(_map(_abstractify, init_vals))\n- cond_jaxpr, cond_consts, cond_tree = _initial_style_jaxpr(cond_fun, in_tree, init_avals)\n- body_jaxpr, body_consts, body_tree = _initial_style_jaxpr(body_fun, in_tree, init_avals)\n+ cond_jaxpr, cond_consts, cond_tree = _initial_style_jaxpr(cond_fun, in_tree, init_avals, \"while_cond\")\n+ body_jaxpr, body_consts, body_tree = _initial_style_jaxpr(body_fun, in_tree, init_avals, \"while_loop\")\nif not treedef_is_leaf(cond_tree) or len(cond_jaxpr.out_avals) != 1:\nmsg = \"cond_fun must return a boolean scalar, but got pytree {}.\"\nraise TypeError(msg.format(cond_tree))\n@@ -1256,7 +1260,7 @@ def scan(f: Callable[[Carry, X], Tuple[Carry, Y]],\nin_flat, in_tree = tree_flatten((init, xs))\ncarry_avals = tuple(_map(_abstractify, init_flat))\n- jaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals)\n+ jaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals, \"scan\")\nout_tree_children = out_tree.children()\nif len(out_tree_children) != 2:\nmsg = \"scan body output must be a pair, got {}.\"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1169,9 +1169,11 @@ def _memoize(thunk):\nreturn memoized\n-def trace_to_jaxpr_dynamic(fun: lu.WrappedFun, in_avals: Sequence[AbstractValue]):\n+def trace_to_jaxpr_dynamic(fun: lu.WrappedFun,\n+ in_avals: Sequence[AbstractValue],\n+ transform_name: str = \"\"):\nwith core.new_main(DynamicJaxprTrace, dynamic=True) as main: # type: ignore\n- main.source_info = fun_sourceinfo(fun.f) # type: ignore\n+ main.source_info = fun_sourceinfo(fun.f, transform_name) # type: ignore\nmain.jaxpr_stack = () # type: ignore\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)\ndel main, fun\n@@ -1198,9 +1200,11 @@ def extend_jaxpr_stack(main, frame):\nassert frame is main.jaxpr_stack[-1]\nmain.jaxpr_stack = main.jaxpr_stack[:-1]\n-def trace_to_jaxpr_final(fun: lu.WrappedFun, in_avals: Sequence[AbstractValue]):\n+def trace_to_jaxpr_final(fun: lu.WrappedFun,\n+ in_avals: Sequence[AbstractValue],\n+ transform_name: str = \"\"):\nwith core.new_base_main(DynamicJaxprTrace) as main: # type: ignore\n- main.source_info = fun_sourceinfo(fun.f) # type: ignore\n+ main.source_info = fun_sourceinfo(fun.f, transform_name) # type: ignore\nmain.jaxpr_stack = () # type: ignore\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)\ndel fun, main\n@@ -1214,12 +1218,15 @@ def partial_eval_to_jaxpr_dynamic(fun: lu.WrappedFun, in_pvals: Sequence[Partial\nwith core.new_main(core.EvalTrace, dynamic=True) as _: # type: ignore\nreturn trace_to_jaxpr(fun, in_pvals)\n-def fun_sourceinfo(fun):\n+def fun_sourceinfo(fun, transform_name: str = \"\"):\nif isinstance(fun, functools.partial):\nfun = fun.func\ntry:\nfilename = fun.__code__.co_filename\nlineno = fun.__code__.co_firstlineno\n- return f\"{fun.__name__} at {filename}:{lineno}\"\n+ line_info = f\"{fun.__name__} at {filename}:{lineno}\"\n+ if transform_name:\n+ line_info += f', transformed by {transform_name}.'\n+ return line_info\nexcept AttributeError:\nreturn \"<unknown>\"\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -685,7 +685,7 @@ def parallel_callable(fun: lu.WrappedFun,\nlogging.vlog(2, \"global_sharded_avals: %s\", global_sharded_avals)\nwith core.extend_axis_env(axis_name, global_axis_size, None): # type: ignore\n- jaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(fun, global_sharded_avals)\n+ jaxpr, out_sharded_avals, consts = pe.trace_to_jaxpr_final(fun, global_sharded_avals, transform_name=\"pmap\")\njaxpr = xla.apply_outfeed_rewriter(jaxpr)\nout_axes = out_axes_thunk()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -649,7 +649,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\n\"got device={} and backend={}\".format(device, backend))\nabstract_args, arg_devices = unzip2(arg_specs)\n- jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, abstract_args)\n+ jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, abstract_args, transform_name=\"jit\")\nif any(isinstance(c, core.Tracer) for c in consts):\nraise core.UnexpectedTracerError(\"Encountered an unexpected tracer.\")\nmap(prefetch, it.chain(consts, jaxpr_literals(jaxpr)))\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2070,6 +2070,17 @@ class APITest(jtu.JaxTestCase):\n# level, which is no longer live.\njax.jit(jnp.add)(jnp.ones(()), count)\n+ def test_escaped_tracer_transform_name(self):\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ \"transformed by jit\"):\n+ jax.jit(self.helper_save_tracer)(1)\n+ _ = self._saved_tracer+1\n+\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ \"transformed by pmap\"):\n+ jax.pmap(self.helper_save_tracer)(jnp.ones((1, 2)))\n+ _ = self._saved_tracer+1\n+\ndef test_pmap_static_kwarg_error_message(self):\n# https://github.com/google/jax/issues/3007\ndef f(a, b):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2602,6 +2602,24 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(deriv(my_pow)(3.0, 1), 1.0, check_dtypes=False)\n+ def test_unexpected_tracer_error(self):\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ \"transformed by while_loop\"):\n+ lst = []\n+ def side_effecting_body(val):\n+ lst.append(val)\n+ return val+1\n+ lax.while_loop(lambda x: x < 2, side_effecting_body, 1)\n+ lst[0] += 1\n+\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ \"transformed by scan\"):\n+ lst = []\n+ def side_effecting_scan(carry, val):\n+ lst.append(val)\n+ return carry, val+1\n+ lax.scan(side_effecting_scan, None, jnp.ones((2, 2)))\n+ lst[0] += 1\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Thread through transform name.
260,335
28.03.2021 19:58:01
25,200
aa2472db0c6f14b737710d6f5ee6dfc42be808eb
add scatter_add jet rule, fixes could use a better test though...
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -4555,6 +4555,7 @@ def _scatter_add_jvp(primals, tangents, *, update_jaxpr, update_consts,\ndimension_numbers, indices_are_sorted, unique_indices):\noperand, scatter_indices, updates = primals\ng_operand, g_scatter_indices, g_updates = tangents\n+ del g_scatter_indices # ignored\nval_out = scatter_add_p.bind(\noperand, scatter_indices, updates, update_jaxpr=update_jaxpr,\nupdate_consts=update_consts, dimension_numbers=dimension_numbers,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jet.py", "new_path": "jax/experimental/jet.py", "diff": "@@ -163,11 +163,11 @@ class JetTrace(core.Trace):\nreturn fun.call_wrapped(*tracers)\n-class ZeroTerm(object): pass\n+class ZeroTerm: pass\nzero_term = ZeroTerm()\nregister_pytree_node(ZeroTerm, lambda z: ((), None), lambda _, xs: zero_term)\n-class ZeroSeries(object): pass\n+class ZeroSeries: pass\nzero_series = ZeroSeries()\nregister_pytree_node(ZeroSeries, lambda z: ((), None), lambda _, xs: zero_series)\n@@ -549,7 +549,6 @@ def _select_taylor_rule(primal_in, series_in, **params):\nreturn primal_out, series_out\njet_rules[lax.select_p] = _select_taylor_rule\n-\ndef _lax_max_taylor_rule(primal_in, series_in):\nx, y = primal_in\n@@ -589,3 +588,14 @@ def _custom_jvp_call_jaxpr_rule(primals_in, series_in, *, fun_jaxpr,\ndel jvp_jaxpr_thunk\nreturn jet(core.jaxpr_as_fun(fun_jaxpr), primals_in, series_in)\njet_rules[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_rule\n+\n+def _scatter_add_rule(primals_in, series_in, *, update_jaxpr, update_consts,\n+ dimension_numbers, indices_are_sorted, unique_indices):\n+ bind = partial(lax.scatter_add_p.bind, update_jaxpr=update_jaxpr,\n+ update_consts=update_consts, dimension_numbers=dimension_numbers,\n+ indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n+ operand, scatter_indices, updates = primals_in\n+ primal_out = bind(operand, scatter_indices, updates)\n+ series_out = [bind(d1, scatter_indices, d2) for d1, _, d2 in zip(*series_in)]\n+ return primal_out, series_out\n+jet_rules[lax.scatter_add_p] = _scatter_add_rule\n" } ]
Python
Apache License 2.0
google/jax
add scatter_add jet rule, fixes #5365 could use a better test though...
260,335
31.03.2021 13:50:34
25,200
632876d773b5451ac83bb3a05bdffb164a7036cc
Copybara import of the project: by Matthew Johnson remove deprecated custom_transforms code
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -43,12 +43,7 @@ from .api import (\ncustom_gradient,\ncustom_jvp,\ncustom_vjp,\n- custom_transforms,\ndefault_backend,\n- defjvp,\n- defjvp_all,\n- defvjp,\n- defvjp_all,\ndevice_count,\ndevice_get,\ndevice_put,\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -2454,144 +2454,6 @@ def named_call(\nreturn named_f\n-# TODO(mattjj): delete everything below here (deprecated custom_transforms)\n-\n-class CustomTransformsFunction(object):\n- def __init__(self, fun, prim):\n- self.fun = fun\n- self.prim = prim\n- wraps(fun)(self)\n-\n- def __repr__(self):\n- return f'<jax.custom_transforms function {self.__name__}>'\n-\n- def __call__(self, *args):\n- args_flat, in_tree = tree_flatten(args)\n- flat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(self.fun), in_tree)\n- in_pvals = [pe.PartialVal.unknown(raise_to_shaped(core.get_aval(x)))\n- for x in args_flat]\n- jaxpr, _, consts = pe.trace_to_jaxpr(flat_fun, in_pvals, instantiate=True)\n- outs = self.prim.bind(*it.chain(consts, args_flat), jaxpr=jaxpr,\n- in_tree=in_tree, out_tree=out_tree(),\n- num_consts=len(consts))\n- return tree_unflatten(out_tree(), outs)\n-\n-def custom_transforms(fun):\n- \"\"\"Deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp`.\"\"\"\n-\n- name = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\n- fun_p = core.Primitive(name)\n- fun_p.multiple_results = True\n-\n- def fun_impl(*args, **params):\n- consts, args = split_list(args, [params['num_consts']])\n- return core.eval_jaxpr(params['jaxpr'], consts, *args)\n- fun_p.def_impl(fun_impl)\n-\n- def fun_jvp(primals, tangents, **params):\n- return ad.jvp(lu.wrap_init(fun_impl, params)).call_wrapped(primals, tangents)\n- ad.primitive_jvps[fun_p] = fun_jvp\n-\n- def fun_batch(args, dims, **params):\n- batched, out_dims = batching.batch_fun2(lu.wrap_init(fun_impl, params), dims)\n- return batched.call_wrapped(*args), out_dims()\n- batching.primitive_batchers[fun_p] = fun_batch\n-\n- def fun_abstract_eval(*avals, **params):\n- return pe.abstract_eval_fun(fun_impl, *avals, **params)\n- fun_p.def_abstract_eval(fun_abstract_eval)\n-\n- def fun_translation(c, *xla_args, **params):\n- return xla.lower_fun(fun_impl, multiple_results=True)(c, *xla_args, **params)\n- xla.translations[fun_p] = fun_translation\n-\n- return CustomTransformsFunction(fun, fun_p)\n-\n-def _check_custom_transforms_type(name, fun):\n- if type(fun) is not CustomTransformsFunction:\n- raise TypeError(f\"{name} requires a custom_transforms function as its first argument, \"\n- f\"but got type {type(fun)}.\")\n-\n-def defjvp_all(fun, custom_jvp):\n- \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n-\n- _check_custom_transforms_type(\"defjvp_all\", fun)\n- def custom_transforms_jvp(primals, tangents, **params):\n- num_consts, in_tree = params['num_consts'], params['in_tree']\n- _, args_flat = split_list(primals, [num_consts])\n- consts_dot, args_dot_flat = split_list(tangents, [num_consts])\n- if not all(type(t) is ad_util.Zero for t in consts_dot):\n- raise ValueError(\"Detected differentiation with respect to closed-over values with \"\n- \"custom JVP rule, which isn't supported.\")\n- args_dot_flat = map(ad.instantiate_zeros, args_dot_flat)\n- args = tree_unflatten(in_tree, args_flat)\n- args_dot = tree_unflatten(in_tree, args_dot_flat)\n- out, out_dot = custom_jvp(args, args_dot)\n- out_flat, out_tree = tree_flatten(out)\n- out_dot_flat, out_tree2 = tree_flatten(out_dot)\n- if out_tree != out_tree2:\n- raise TypeError(\"Custom JVP rule returned different tree structures for primals \"\n- f\"and tangents, but they must be equal: {out_tree} and {out_tree2}.\")\n- return out_flat, out_dot_flat\n- ad.primitive_jvps[fun.prim] = custom_transforms_jvp\n-\n-def defjvp(fun, *jvprules):\n- \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n-\n- _check_custom_transforms_type(\"defjvp\", fun)\n- def custom_jvp(primals, tangents):\n- ans = fun(*primals)\n- tangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)\n- if rule is not None and type(t) is not ad_util.Zero]\n- return ans, functools.reduce(ad.add_tangents, tangents_out, ad_util.Zero.from_value(ans))\n- defjvp_all(fun, custom_jvp)\n-\n-def defvjp_all(fun, custom_vjp):\n- \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n-\n- _check_custom_transforms_type(\"defvjp_all\", fun)\n- def custom_transforms_vjp(*consts_and_args, **params):\n- num_consts, in_tree = params['num_consts'], params['in_tree']\n- consts, args_flat = split_list(consts_and_args, [num_consts])\n- args = tree_unflatten(params['in_tree'], args_flat)\n- out, vjp = custom_vjp(*args)\n- out_flat, out_tree = tree_flatten(out)\n- if out_tree != params['out_tree']:\n- raise TypeError(\n- f\"First output of `custom_vjp`: {custom_vjp} doesn't match the structure of \"\n- f\"the output of `fun`: {fun}\\n\"\n- f\"{out_tree}\\n\"\n- \"vs\\n\"\n- f\"{params['out_tree']}\\n\"\n- )\n- def vjp_flat(*cts_flat):\n- cts = tree_unflatten(out_tree, cts_flat)\n- args_cts_flat, in_tree2 = tree_flatten(vjp(cts))\n- if in_tree != in_tree2:\n- raise TypeError(\n- f\"Output of the `vjp`: {vjp} doesn't match the structure of args of \"\n- f\"`fun`: {fun}\\n\"\n- f\"{in_tree2}\\n\"\n- \"vs\\n\"\n- f\"{in_tree}\\n\"\n- )\n- return [core.unit] * num_consts + list(args_cts_flat)\n- return out_flat, vjp_flat\n- ad.defvjp_all(fun.prim, custom_transforms_vjp)\n-\n-def defvjp(fun, *vjprules):\n- \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n-\n- _check_custom_transforms_type(\"defvjp\", fun)\n- def custom_vjp(*primals):\n- ans = fun(*primals)\n- # TODO(mattjj): avoid instantiating zeros?\n- def vjpfun(ct):\n- return tuple(vjp(ct, ans, *primals) if vjp else ad_util.zeros_like_jaxval(x)\n- for x, vjp in zip(primals, vjprules))\n- return ans, vjpfun\n- defvjp_all(fun, custom_vjp)\n-\ndef invertible(fun: Callable) -> Callable:\n\"\"\"Asserts that the decorated function is invertible.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/djax.py", "new_path": "jax/experimental/djax.py", "diff": "@@ -940,10 +940,18 @@ def batch_jaxpr(jaxpr, axis_size, in_dims):\nif d is not batching.not_mapped else aval\nfor d, aval in zip(in_dims, in_avals)]\n- f, out_dims = batching.batch_fun2(lu.wrap_init(jaxpr_as_fun(jaxpr)), in_dims)\n+ fun, out_dims = batching.batch_subtrace(lu.wrap_init(jaxpr_as_fun(jaxpr)))\n+ f = _batch_fun(fun, in_dims)\njaxpr, consts, _ = trace_to_jaxpr_dynamic(f, in_avals)\nreturn jaxpr, consts, out_dims()\n+@lu.transformation\n+def _batch_fun(in_dims, *in_vals, **params):\n+ with core.new_main(batching.BatchTrace, axis_name=None) as main:\n+ out_vals = yield (main, in_dims, *in_vals), params\n+ del main\n+ yield out_vals\n+\ndef _map_array(size: int, axis: int, aval: AbsArray) -> AbsArray:\nreturn AbsArray(tuple_delete(aval.shape, axis), aval._eltTy)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -674,67 +674,6 @@ def _custom_lin_transpose(cts_out, *invals, num_res, bwd, avals_out):\nprimitive_transposes[custom_lin_p] = _custom_lin_transpose\n-# TODO(mattjj): delete everything below here (deprecated custom_transforms)\n-\n-def defvjp_all(prim, custom_vjp):\n- # see https://github.com/google/jax/pull/636\n- name = prim.name\n-\n- def fun_jvp(xs, ts, **params):\n- ts = map(instantiate_zeros, ts)\n- primals_and_tangents = fun_jvp_p.bind(*it.chain(xs, ts), **params)\n- primals, tangents = split_list(primals_and_tangents, [len(primals_and_tangents) // 2])\n- if prim.multiple_results:\n- return primals, tangents\n- else:\n- primal, = primals\n- tangent, = tangents\n- return primal, tangent\n- primitive_jvps[prim] = fun_jvp\n-\n- fun_jvp_p = core.Primitive('{name}_jvp'.format(name=name))\n- fun_jvp_p.multiple_results = True\n- def fun_jvp_partial_eval(trace, *tracers, **params):\n- primals, tangents = split_list(tracers, [len(tracers) // 2])\n- primals_out, vjp_py = custom_vjp(*primals, **params)\n- if not prim.multiple_results:\n- primals_out = [primals_out]\n- out_avals = [raise_to_shaped(get_aval(x)) for x in primals_out]\n- ct_pvals = [pe.PartialVal.unknown(aval) for aval in out_avals]\n- jaxpr, _, res = pe.trace_to_jaxpr(lu.wrap_init(vjp_py), ct_pvals, instantiate=True)\n- tangents_out = fun_lin_p.bind(*it.chain(res, tangents), trans_jaxpr=jaxpr,\n- num_res=len(res), out_avals=out_avals)\n- return primals_out + tangents_out\n- pe.custom_partial_eval_rules[fun_jvp_p] = fun_jvp_partial_eval\n-\n- fun_lin_p = core.Primitive('{name}_lin'.format(name=name))\n- fun_lin_p.multiple_results = True\n- fun_lin_p.def_abstract_eval(lambda *_, **kwargs: kwargs['out_avals'])\n- def fun_lin_transpose(cts, *args, **kwargs):\n- num_res, trans_jaxpr = kwargs['num_res'], kwargs['trans_jaxpr']\n- res, _ = split_list(args, [num_res])\n- cts = map(instantiate_zeros_aval, kwargs['out_avals'], cts)\n- outs = core.eval_jaxpr(trans_jaxpr, res, *cts)\n- return [None] * num_res + outs\n- primitive_transposes[fun_lin_p] = fun_lin_transpose\n-\n-def defvjp(prim, *vjps):\n- def vjpmaker(*primals):\n- ans = prim.bind(*primals)\n- vjpfun = lambda ct: [vjp(ct, *primals) if vjp else zeros_like_jaxval(x)\n- for x, vjp in zip(primals, vjps)]\n- return ans, vjpfun\n- defvjp_all(prim, vjpmaker)\n-\n-def defvjp2(prim, *vjps):\n- def vjpmaker(*primals):\n- ans = prim.bind(*primals)\n- vjpfun = lambda ct: [vjp(ct, ans, *primals) if vjp else zeros_like_jaxval(x)\n- for x, vjp in zip(primals, vjps)]\n- return ans, vjpfun\n- defvjp_all(prim, vjpmaker)\n-\n-\nclass CustomJVPException(Exception):\ndef __init__(self):\n# TODO(mattjj): track source provenance on AD tracers, improve error\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -81,23 +81,6 @@ def _match_axes(axis_size, in_dims, out_dims_thunk, out_dim_dests, *in_vals):\nyield map(partial(matchaxis, axis_size), out_dims, out_dim_dests, out_vals)\n-# These next two functions, `batch_fun2` and `_batch_fun2`, are deprecated; the\n-# former is only called from `custom_transforms`, which itself is deprecated.\n-# TODO(mattjj): delete these along with custom_transforms\n-\n-def batch_fun2(fun: lu.WrappedFun, in_dims):\n- # like `batch_fun` but returns output batch dims (so no out_dim_dests)\n- fun, out_dims = batch_subtrace(fun)\n- return _batch_fun2(fun, in_dims), out_dims\n-\n-@lu.transformation\n-def _batch_fun2(in_dims, *in_vals, **params):\n- with core.new_main(BatchTrace, axis_name=None) as main:\n- out_vals = yield (main, in_dims,) + in_vals, params\n- del main\n- yield out_vals\n-\n-\n### tracer\n# TODO(mattjj): use a special sentinel type rather than None\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4766,202 +4766,6 @@ class InvertibleADTest(jtu.JaxTestCase):\ncheck_dtypes=True)\n-class DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n-\n- def test_defvjp_all(self):\n- foo_p = Primitive('foo')\n- def foo(x): return 2. * foo_p.bind(x)\n-\n- ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * jnp.sin(x),)))\n- val_ans, grad_ans = api.value_and_grad(foo)(3.)\n- self.assertAllClose(val_ans, 2 * 3.**2, check_dtypes=False)\n- self.assertAllClose(grad_ans, 4 * 2 * np.sin(3.), check_dtypes=False)\n-\n- def test_defvjp_all_const(self):\n- foo_p = Primitive('foo')\n- def foo(x): return foo_p.bind(x)\n-\n- ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\n- val_ans, grad_ans = api.value_and_grad(foo)(3.)\n- self.assertAllClose(val_ans, 9., check_dtypes=False)\n- self.assertAllClose(grad_ans, 12.)\n-\n- def test_defvjp_all_higher_order_revmode(self):\n- foo_p = Primitive('foo')\n- def foo(x): return 2. * foo_p.bind(x)\n-\n- ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\n- ans = api.grad(api.grad(foo))(3.)\n- self.assertAllClose(ans, 2 * 2 * 3., check_dtypes=False)\n-\n- def test_defvjp_all_multiple_arguments(self):\n- # also tests passing in symbolic zero tangents b/c we differentiate wrt only\n- # the first argument in one case\n-\n- foo_p = Primitive('foo')\n- def foo(x, y): return foo_p.bind(x, y)\n-\n- def vjpfun(x, y):\n- out = x**2 + y**3\n- vjp = lambda g: (g + x + y, g * x * 9.)\n- return out, vjp\n-\n- ad.defvjp_all(foo_p, vjpfun)\n- val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n- self.assertAllClose(val_ans, 3.**2 + 4.**3, check_dtypes=False)\n- self.assertAllClose(grad_ans, 1. + 3. + 4., check_dtypes=False)\n-\n- ans = api.grad(foo, (0, 1))(3., 4.)\n- self.assertAllClose(ans, (1. + 3. + 4., 1. * 3. * 9.), check_dtypes=False)\n-\n- def test_defvjp_all_custom_transforms(self):\n- @api.custom_transforms\n- def foo(x):\n- return jnp.sin(x)\n-\n- api.defvjp_all(foo, lambda x: (jnp.sin(x), lambda g: (g * x,)))\n- val_ans, grad_ans = api.value_and_grad(foo)(3.)\n- self.assertAllClose(val_ans, np.sin(3.), check_dtypes=False)\n- self.assertAllClose(grad_ans, 3., check_dtypes=False)\n-\n- # TODO(mattjj): add defvjp_all test with pytree arguments\n-\n- def test_defvjp(self):\n- @api.custom_transforms\n- def foo(x, y):\n- return jnp.sin(x * y)\n-\n- api.defvjp(foo, None, lambda g, _, x, y: g * x * y)\n- val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n- self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n- self.assertAllClose(grad_ans, 0., check_dtypes=False)\n-\n- ans_0, ans_1 = api.grad(foo, (0, 1))(3., 4.)\n- self.assertAllClose(ans_0, 0., check_dtypes=False)\n- self.assertAllClose(ans_1, 3. * 4., check_dtypes=False)\n-\n- def test_defvjp_higher_order(self):\n- @api.custom_transforms\n- def foo(x):\n- return jnp.sin(2. * x)\n-\n- api.defvjp(foo, lambda g, _, x: g * jnp.cos(x))\n- ans = api.grad(api.grad(foo))(2.)\n- expected = api.grad(api.grad(jnp.sin))(2.)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\n- def test_defvjp_use_ans(self):\n- @api.custom_transforms\n- def foo(x, y):\n- return jnp.sin(x * y)\n-\n- api.defvjp(foo, None, lambda g, ans, x, y: g * x * y + jnp.cos(ans))\n- val_ans, grad_ans = api.value_and_grad(foo, 1)(3., 4.)\n- self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n- self.assertAllClose(grad_ans, 3. * 4. + np.cos(np.sin(3. * 4)),\n- check_dtypes=False)\n-\n- def test_custom_transforms_eval_with_pytrees(self):\n- @api.custom_transforms\n- def f(x):\n- a, b = x[0], x[1]\n- return {'hi': 2 * a, 'bye': 2 * b}\n-\n- ans = f((1, 2))\n- self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n-\n- def test_custom_transforms_jit_with_pytrees(self):\n- @api.custom_transforms\n- def f(x):\n- a, b = x[0], x[1]\n- return {'hi': 2 * a, 'bye': 2 * b}\n-\n- ans = jit(f)((1, 2))\n- self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n-\n- def test_custom_transforms_jit_with_pytrees_consts(self):\n- # The purpose of this test is to exercise the custom_transforms default\n- # translation rule in how it deals with constants that are too large to be\n- # treated as literals (at the time of writing).\n- z = np.arange(10.)\n-\n- @api.custom_transforms\n- def f(x):\n- a, b = x[0], x[1]\n- return {'hi': 2 * a, 'bye': z * b}\n-\n- ans = jit(f)((1, 2))\n- self.assertAllClose(ans, {'hi': 2 * 1, 'bye': z * 2}, check_dtypes=False)\n-\n- def test_custom_transforms_jvp_with_pytrees(self):\n- @api.custom_transforms\n- def f(x):\n- a, b = x[0], x[1]\n- return {'hi': 2 * a, 'bye': 2 * b}\n-\n- ans, out_tangent = api.jvp(f, ((1., 2.),), ((3., 4.),))\n- self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n- self.assertEqual(out_tangent, {'hi': 2 * 3, 'bye': 2 * 4})\n-\n- def test_custom_transforms_vmap_with_pytrees(self):\n- raise unittest.SkipTest(\"Test deprecated custom_transforms\")\n- @api.custom_transforms\n- def f(x):\n- a, b = x[0], x[1]\n- return {'hi': 2 * a, 'bye': 2 * b}\n-\n- ans = api.vmap(f)((np.arange(3), np.ones((3, 2))))\n- expected = {'hi': 2 * np.arange(3), 'bye': 2 * np.ones((3, 2))}\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\n- def test_custom_transforms_jvp_with_closure(self):\n- def f(x):\n- @api.custom_transforms\n- def g(y):\n- return x * y\n- return g(x)\n-\n- ans = api.grad(f)(1.)\n- expected = 2.\n- self.assertAllClose(ans, expected, check_dtypes=False)\n-\n- def test_custom_vjp_zeros(self):\n- @api.custom_transforms\n- def f(x, y):\n- return 2 * x, 3 * y\n-\n- def f_vjp(x, y):\n- return (2 * x, 3 * y), lambda ts: (4 * ts[0], 5 * ts[1])\n-\n- api.defvjp_all(f, f_vjp, )\n- api.grad(lambda x, y: f(x, y)[0])(1., 2.) # doesn't crash\n-\n- def test_custom_transforms_vjp_nones(self):\n- with jax.enable_checks(False): # fails with checks\n- # issue raised by jsnoek@ and jumper@\n- @jax.custom_transforms\n- def solve(a, b):\n- return jnp.dot(jnp.linalg.inv(a), b)\n- # print(solve(a, b))\n-\n- def solve_vjp(a, b):\n- x = solve(a, b)\n- def vjp(x_tangent):\n- dx = jnp.dot(solve(a, x_tangent), x.T)\n- out = (dx, b * 0.)\n- return out\n- return x, vjp\n- jax.defvjp_all(solve, solve_vjp)\n- gf = grad(lambda a,b: jnp.sum(solve(a, b)))\n-\n- n = 3\n- a_in = jnp.linspace(0, 1, n)[:, None]\n- a = jnp.dot(a_in, a_in.T) + jnp.eye(n) * 0.1\n- real_x = np.random.RandomState(0).randn(n)\n- b = jnp.dot(a + jnp.eye(a.shape[0]), real_x)\n- print(gf(a, b)) # doesn't crash\n-\n-\nclass BufferDonationTest(jtu.BufferDonationTestCase):\n@jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- 35fcf2e2fd5b4c56cbb591f4c8bf01222a23dfe5 by Matthew Johnson <mattjj@google.com>: remove deprecated custom_transforms code PiperOrigin-RevId: 366108489
260,335
02.04.2021 12:52:37
25,200
d4af8cd08afbbd2929d4834cfe6100d825e47b6e
improve djax dim indexing type checking
[ { "change_type": "MODIFY", "old_path": "jax/experimental/djax.py", "new_path": "jax/experimental/djax.py", "diff": "@@ -261,10 +261,16 @@ def typecheck_type(env, aval):\nif not (isinstance(d.name.aval, AbsArray) and\nisinstance(d.name.aval._eltTy, BoundedIntTy)):\nraise TypeError(f'dim var of unexpected type: {d.name.aval}')\n- if not all(j < i for j in d.indices):\n- raise TypeError(f'out-of-bounds dim indexing: {aval}')\n- expected_shape = tuple(aval.shape[j] for j in d.indices)\n- if d.name.aval.shape != expected_shape:\n+ d_indices_set = set(d.indices)\n+ if i in d_indices_set:\n+ raise TypeError(f\"circular dim indexing expression: {d}\")\n+ for j in d.indices:\n+ d_j = aval.shape[j]\n+ if (isinstance(d_j, DimIndexingExpr) and\n+ not d_indices_set.issuperset(d_j.indices)):\n+ raise TypeError(f\"dim indexing not transitively closed: {d}\")\n+ expected_idx_array_shape = tuple(aval.shape[j] for j in d.indices)\n+ if d.name.aval.shape != expected_idx_array_shape:\nraise TypeError(f'incompatible shapes in dim indexing: {aval}')\nelse:\nraise TypeError(f'unexpected type in shape: {type(d)}')\n" } ]
Python
Apache License 2.0
google/jax
improve djax dim indexing type checking Co-authored-by: Edward Loper <edloper@google.com>
260,335
02.04.2021 13:25:53
25,200
9205b6f1258f419a1b8256c737f53a25582cba19
remove dead lax._dot_using_sum_of_products
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -693,8 +693,8 @@ def dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,\nAn array containing the result.\n\"\"\"\ncontract_dims_seq, batch_dims_seq = dimension_numbers\n- contract_dims = tuple(map(lambda x: tuple(x), contract_dims_seq))\n- batch_dims = tuple(map(lambda x: tuple(x), batch_dims_seq))\n+ contract_dims = tuple(map(tuple, contract_dims_seq)) # type: ignore\n+ batch_dims = tuple(map(tuple, batch_dims_seq)) # type: ignore\nreturn dot_general_p.bind(lhs, rhs,\ndimension_numbers=(contract_dims, batch_dims),\nprecision=_canonicalize_precision(precision),\n@@ -3273,34 +3273,6 @@ def _dot_general_batch_dim_nums(ndims, batch_dims, dimension_numbers):\nnew_dimension_numbers = ((lhs_contract, rhs_contract), (lhs_batch, rhs_batch))\nreturn new_dimension_numbers, int(result_batch_dim)\n-def _dot_using_sum_of_products(lhs, rhs, *, dimension_numbers):\n- contract_dims, batch_dims = dimension_numbers\n- lhs_contract_dims, rhs_contract_dims = contract_dims\n- lhs_batch_dims, rhs_batch_dims = batch_dims\n- lhs_noncontract_dims = tuple(sorted(\n- set(range(np.ndim(lhs))) - set(lhs_batch_dims) - set(lhs_contract_dims)))\n- rhs_noncontract_dims = tuple(sorted(\n- set(range(np.ndim(rhs))) - set(rhs_batch_dims) - set(rhs_contract_dims)))\n- lhs = transpose(lhs,\n- lhs_batch_dims + lhs_noncontract_dims + lhs_contract_dims)\n- rhs = transpose(rhs,\n- rhs_batch_dims + rhs_noncontract_dims + rhs_contract_dims)\n-\n- lhs_start_expand = len(lhs_batch_dims) + len(lhs_noncontract_dims)\n- lhs_end_expand = lhs_start_expand + len(rhs_noncontract_dims)\n- lhs = expand_dims(lhs, tuple(range(lhs_start_expand, lhs_end_expand)))\n-\n- rhs_start_expand = len(lhs_batch_dims)\n- rhs_end_expand = rhs_start_expand + len(lhs_noncontract_dims)\n- rhs = expand_dims(rhs, tuple(range(rhs_start_expand, rhs_end_expand)))\n-\n- out_ndim = (len(lhs_batch_dims) + len(lhs_noncontract_dims) +\n- len(rhs_noncontract_dims))\n- op_product = bitwise_and if lhs.dtype == np.bool_ else mul\n- op_sum = bitwise_or if lhs.dtype == np.bool_ else add\n- return reduce(op_product(lhs, rhs), _zero(lhs), op_sum,\n- tuple(range(out_ndim, out_ndim + len(lhs_contract_dims))))\n-\ndef _dot_general_translation_rule(c, lhs, rhs, *, dimension_numbers, precision,\npreferred_element_type: Optional[DType]):\nif preferred_element_type is not None:\n" } ]
Python
Apache License 2.0
google/jax
remove dead lax._dot_using_sum_of_products
260,709
31.03.2021 18:35:15
25,200
a19098d4627e352ceee0a0c534e847709a334b72
Reimplement as JAX Primitive
[ { "change_type": "MODIFY", "old_path": "build/BUILD.bazel", "new_path": "build/BUILD.bazel", "diff": "@@ -39,6 +39,7 @@ py_binary(\n]) + if_cuda([\n\"//jaxlib:cublas_kernels\",\n\"//jaxlib:cusolver_kernels\",\n+ \"//jaxlib:cuda_lu_pivot_kernels\",\n\"//jaxlib:cuda_prng_kernels\",\n]) + if_rocm([\n\"//jaxlib:rocblas_kernels\",\n" }, { "change_type": "MODIFY", "old_path": "build/build_wheel.py", "new_path": "build/build_wheel.py", "diff": "@@ -143,13 +143,16 @@ def prepare_wheel(sources_path):\nif r.Rlocation(\"__main__/jaxlib/cusolver_kernels.so\") is not None:\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cusolver_kernels.so\"))\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cublas_kernels.so\"))\n+ copy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_lu_pivot_kernels.so\"))\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_prng_kernels.so\"))\nif r.Rlocation(\"__main__/jaxlib/cusolver_kernels.pyd\") is not None:\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cusolver_kernels.pyd\"))\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cublas_kernels.pyd\"))\n+ copy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_lu_pivot_kernels.pyd\"))\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_prng_kernels.pyd\"))\nif r.Rlocation(\"__main__/jaxlib/cusolver.py\") is not None:\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cusolver.py\"))\n+ copy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_linalg.py\"))\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/cuda_prng.py\"))\nif r.Rlocation(\"__main__/jaxlib/rocblas_kernels.so\") is not None:\ncopy_to_jaxlib(r.Rlocation(\"__main__/jaxlib/rocblas_kernels.so\"))\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -33,6 +33,7 @@ from jax._src.lax.lax import (\nfrom jax._src.lax import lax as lax_internal\nfrom jax.lib import lapack\n+from jax.lib import cuda_linalg\nfrom jax.lib import cusolver\nfrom jax.lib import rocsolver\n@@ -111,6 +112,25 @@ def eigh(x, lower: bool = True, symmetrize_input: bool = True):\nv, w = eigh_p.bind(x, lower=lower)\nreturn v, w\n+\n+def lu_pivots_to_permutation(pivots, permutation_size: int):\n+ \"\"\"Converts the pivots (row swaps) returned by LU to a permutation.\n+\n+ We build a permutation rather than applying `pivots` directly to the rows\n+ of a matrix because lax loops aren't differentiable.\n+\n+ Args:\n+ pivots: an int32 array of shape (..., k) of row swaps to perform\n+ permutation_size: the size of the output permutation. Has to be >= k.\n+\n+ Returns:\n+ An int32 array of shape (..., permutation_size).\n+ \"\"\"\n+ permutation = lu_pivots_to_permutation_p.bind(\n+ pivots, permutation_size=int(permutation_size))\n+ return permutation\n+\n+\ndef lu(x):\n\"\"\"LU decomposition with partial pivoting.\n@@ -729,6 +749,100 @@ if rocsolver is not None:\nxla.backend_specific_translations['gpu'][triangular_solve_p] = \\\npartial(_triangular_solve_gpu_translation_rule, rocsolver.trsm)\n+# Support operation for LU decomposition: Transformation of the pivots returned\n+# by LU decomposition into permutations.\n+\n+\n+# Define this outside lu_pivots_to_permutation to ensure fori_loop cache hits\n+def _lu_pivots_body_fn(i, permutation_and_swaps):\n+ permutation, swaps = permutation_and_swaps\n+ batch_dims = swaps.shape[:-1]\n+ j = swaps[..., i]\n+ iotas = jnp.ix_(*(lax.iota(jnp.int32, b) for b in batch_dims))\n+ x = permutation[..., i]\n+ y = permutation[iotas + (j,)]\n+ permutation = ops.index_update(permutation, ops.index[..., i], y)\n+ return ops.index_update(permutation, ops.index[iotas + (j,)], x), swaps\n+\n+\n+@partial(api.jit, static_argnums=(1,))\n+def _generic_lu_pivots_to_permutation(swaps, m):\n+ \"\"\"Converts the pivots (row swaps) returned by LU to a permutation.\n+\n+ We build a permutation rather than applying `swaps` directly to the rows\n+ of a matrix because lax loops aren't differentiable.\n+\n+ Args:\n+ swaps: an array of shape (..., k) of row swaps to perform\n+ m: the size of the output permutation. m should be >= k.\n+ Returns:\n+ An int32 array of shape (..., m).\n+ \"\"\"\n+ assert len(swaps.shape) >= 1\n+ batch_dims = swaps.shape[:-1]\n+ k = swaps.shape[-1]\n+\n+ permutation = lax.broadcasted_iota(jnp.int32, batch_dims + (m,),\n+ len(batch_dims))\n+ if m == 0:\n+ return permutation\n+ result, _ = lax.fori_loop(np.array(0, np.int32), np.array(k, np.int32),\n+ _lu_pivots_body_fn, (permutation, swaps))\n+ return result\n+\n+\n+def _lu_pivots_to_permutation_abstract_eval(pivots, *, permutation_size):\n+ pivots = raise_to_shaped(pivots)\n+ if isinstance(pivots, ShapedArray):\n+ if pivots.ndim < 1 or pivots.dtype != np.dtype(np.int32):\n+ raise ValueError(\n+ 'Argument to lu_pivots_to_permutation must have rank >= 1 and dtype '\n+ 'int32. Got shape={} and dtype={}'.format(pivots.shape, pivots.dtype))\n+\n+ if permutation_size < pivots.shape[-1]:\n+ raise ValueError(\n+ 'Output permutation size {} has to exceed the trailing dimension of '\n+ 'the pivots. Got shape {}'.format(permutation_size, pivots.shape))\n+\n+ batch_dims = pivots.shape[:-1]\n+ permutations = pivots.update(shape=batch_dims + (permutation_size,))\n+ else:\n+ permutations = pivots\n+\n+ return permutations\n+\n+\n+def _lu_pivots_to_permutation_batching_rule(batched_args, batch_dims, *,\n+ permutation_size):\n+ x, = batched_args\n+ bd, = batch_dims\n+ x = batching.moveaxis(x, bd, 0)\n+ return lu_pivots_to_permutation_p.bind(\n+ x, permutation_size=permutation_size), 0\n+\n+\n+def _lu_pivots_to_permutation_translation_rule(c, pivots, *, permutation_size):\n+ lowered_fun = xla.lower_fun(\n+ lambda x: _generic_lu_pivots_to_permutation(x, permutation_size),\n+ multiple_results=False)\n+ return lowered_fun(c, pivots)\n+\n+\n+lu_pivots_to_permutation_p = Primitive('lu_pivots_to_permutation')\n+lu_pivots_to_permutation_p.multiple_results = False\n+lu_pivots_to_permutation_p.def_impl(\n+ partial(xla.apply_primitive, lu_pivots_to_permutation_p))\n+lu_pivots_to_permutation_p.def_abstract_eval(\n+ _lu_pivots_to_permutation_abstract_eval)\n+batching.primitive_batchers[lu_pivots_to_permutation_p] = (\n+ _lu_pivots_to_permutation_batching_rule)\n+xla.translations[lu_pivots_to_permutation_p] = (\n+ _lu_pivots_to_permutation_translation_rule)\n+\n+if cuda_linalg:\n+ xla.backend_specific_translations['gpu'][lu_pivots_to_permutation_p] = (\n+ cuda_linalg.lu_pivots_to_permutation)\n+\n# LU decomposition\n# Computes a pivoted LU decomposition such that\n@@ -933,44 +1047,6 @@ if rocsolver is not None:\nxla.backend_specific_translations['tpu'][lu_p] = _lu_tpu_translation_rule\n-# Define this outside lu_pivots_to_permutation to ensure fori_loop cache hits\n-def _lu_pivots_body_fn(i, permutation_and_swaps):\n- permutation, swaps = permutation_and_swaps\n- batch_dims = swaps.shape[:-1]\n- j = swaps[..., i]\n- iotas = jnp.ix_(*(lax.iota(jnp.int32, b) for b in batch_dims))\n- x = permutation[..., i]\n- y = permutation[iotas + (j,)]\n- permutation = ops.index_update(permutation, ops.index[..., i], y)\n- return ops.index_update(permutation, ops.index[iotas + (j,)], x), swaps\n-\n-\n-@partial(api.jit, static_argnums=(1,))\n-def lu_pivots_to_permutation(swaps, m):\n- \"\"\"Converts the pivots (row swaps) returned by LU to a permutation.\n-\n- We build a permutation rather than applying `swaps` directly to the rows\n- of a matrix because lax loops aren't differentiable.\n-\n- Args:\n- swaps: an array of shape (..., k) of row swaps to perform\n- m: the size of the output permutation. m should be >= k.\n- Returns:\n- An int32 array of shape (..., m).\n- \"\"\"\n- assert len(swaps.shape) >= 1\n- batch_dims = swaps.shape[:-1]\n- k = swaps.shape[-1]\n-\n- permutation = lax.broadcasted_iota(jnp.int32, batch_dims + (m,),\n- len(batch_dims))\n- if m == 0:\n- return permutation\n- result, _ = lax.fori_loop(np.array(0, np.int32), np.array(k, np.int32),\n- _lu_pivots_body_fn, (permutation, swaps))\n- return result\n-\n-\n@partial(vectorize, excluded={3}, signature='(n,n),(n),(n,k)->(n,k)')\ndef _lu_solve_core(lu, permutation, b, trans):\nm = lu.shape[0]\n" }, { "change_type": "MODIFY", "old_path": "jax/lib/__init__.py", "new_path": "jax/lib/__init__.py", "diff": "# checking on import.\n__all__ = [\n- 'cuda_prng', 'cusolver', 'rocsolver', 'jaxlib', 'lapack',\n+ 'cuda_linalg', 'cuda_prng', 'cusolver', 'rocsolver', 'jaxlib', 'lapack',\n'pocketfft', 'pytree', 'tpu_client', 'version', 'xla_client'\n]\n@@ -79,6 +79,11 @@ try:\nexcept ImportError:\ncuda_prng = None\n+try:\n+ from jaxlib import cuda_linalg # pytype: disable=import-error\n+except ImportError:\n+ cuda_linalg = None\n+\n# Jaxlib code is split between the Jax and the Tensorflow repositories.\n# Only for the internal usage of the JAX developers, we expose a version\n# number that can be used to perform changes without breaking the master\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/BUILD", "new_path": "jaxlib/BUILD", "diff": "@@ -116,6 +116,7 @@ py_library(\n\"pocketfft.py\",\n\"version.py\",\n] + if_cuda_is_configured([\n+ \"cuda_linalg.py\",\n\"cuda_prng.py\",\n\"cusolver.py\",\n]) + if_rocm_is_configured([\n@@ -133,6 +134,7 @@ py_library(\nname = \"gpu_support\",\ndeps = [\n\":cublas_kernels\",\n+ \":cuda_lu_pivot_kernels\",\n\":cuda_prng_kernels\",\n\":cusolver_kernels\",\n],\n@@ -197,6 +199,35 @@ pybind_extension(\n],\n)\n+cuda_library(\n+ name = \"cuda_lu_pivot_kernels_lib\",\n+ srcs = [\"cuda_lu_pivot_kernels.cu.cc\"],\n+ hdrs = [\"cuda_lu_pivot_kernels.h\"],\n+ deps = [\n+ \":cuda_gpu_kernel_helpers\",\n+ \":kernel_helpers\",\n+ \"@local_config_cuda//cuda:cuda_headers\",\n+ ],\n+)\n+\n+pybind_extension(\n+ name = \"cuda_lu_pivot_kernels\",\n+ srcs = [\"cuda_lu_pivot_kernels.cc\"],\n+ copts = [\n+ \"-fexceptions\",\n+ \"-fno-strict-aliasing\",\n+ ],\n+ features = [\"-use_header_modules\"],\n+ module_name = \"cuda_lu_pivot_kernels\",\n+ deps = [\n+ \":cuda_lu_pivot_kernels_lib\",\n+ \":kernel_pybind11_helpers\",\n+ \"@org_tensorflow//tensorflow/stream_executor/cuda:cudart_stub\",\n+ \"@local_config_cuda//cuda:cuda_headers\",\n+ \"@pybind11\",\n+ ],\n+)\n+\ncuda_library(\nname = \"cuda_prng_kernels_lib\",\nsrcs = [\"cuda_prng_kernels.cu.cc\"],\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jaxlib/cuda_linalg.py", "diff": "+# Copyright 2021 Google LLC\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# https://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import functools\n+import operator\n+\n+import numpy as np\n+\n+from jaxlib import xla_client\n+\n+try:\n+ from . import cuda_lu_pivot_kernels\n+ for _name, _value in cuda_lu_pivot_kernels.registrations().items():\n+ xla_client.register_custom_call_target(_name, _value, platform=\"CUDA\")\n+except ImportError:\n+ pass\n+\n+_prod = lambda xs: functools.reduce(operator.mul, xs, 1)\n+\n+\n+def lu_pivots_to_permutation(c, pivots, *, permutation_size):\n+ \"\"\"Kernel for the transformation of pivots to permutations on GPU.\"\"\"\n+ pivots_shape = c.get_shape(pivots)\n+ dims = pivots_shape.dimensions()\n+ dtype = np.dtype(np.int32)\n+\n+ assert pivots_shape.element_type() == dtype\n+\n+ batch_size = _prod(dims[:-1])\n+ pivot_size = dims[-1]\n+\n+ opaque = cuda_lu_pivot_kernels.cuda_lu_pivots_to_permutation_descriptor(\n+ batch_size, pivot_size, permutation_size)\n+ pivots_layout = tuple(range(len(dims) - 1, -1, -1))\n+ pivots_shape_with_layout = xla_client.Shape.array_shape(\n+ dtype, dims, pivots_layout)\n+\n+ permutations_layout = pivots_layout\n+ permutations_dims = list(dims)\n+ permutations_dims[-1] = permutation_size\n+ permutations_shape_with_layout = xla_client.Shape.array_shape(\n+ dtype, permutations_dims, permutations_layout)\n+\n+ return xla_client.ops.CustomCallWithLayout(\n+ c,\n+ b\"cuda_lu_pivots_to_permutation\",\n+ operands=(pivots,),\n+ shape_with_layout=permutations_shape_with_layout,\n+ operand_shapes_with_layout=(pivots_shape_with_layout,),\n+ opaque=opaque)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jaxlib/cuda_lu_pivot_kernels.cc", "diff": "+/* Copyright 2021 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+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+==============================================================================*/\n+\n+#include \"jaxlib/cuda_lu_pivot_kernels.h\"\n+\n+#include \"jaxlib/kernel_pybind11_helpers.h\"\n+#include \"include/pybind11/pybind11.h\"\n+\n+namespace jax {\n+namespace {\n+\n+pybind11::dict Registrations() {\n+ pybind11::dict dict;\n+ dict[\"cuda_lu_pivots_to_permutation\"] =\n+ EncapsulateFunction(CudaLuPivotsToPermutation);\n+ return dict;\n+}\n+\n+PYBIND11_MODULE(cuda_lu_pivot_kernels, m) {\n+ m.def(\"registrations\", &Registrations);\n+ m.def(\"cuda_lu_pivots_to_permutation_descriptor\",\n+ [](std::int64_t batch_size, std::int32_t pivot_size,\n+ std::int32_t permutation_size) {\n+ std::string result = BuildCudaLuPivotsToPermutationDescriptor(\n+ batch_size, pivot_size, permutation_size);\n+ return pybind11::bytes(result);\n+ });\n+}\n+\n+} // namespace\n+} // namespace jax\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jaxlib/cuda_lu_pivot_kernels.cu.cc", "diff": "+/* Copyright 2021 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+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+==============================================================================*/\n+\n+#include \"jaxlib/cuda_lu_pivot_kernels.h\"\n+\n+#include <array>\n+#include <iostream>\n+\n+#include \"jaxlib/cuda_gpu_kernel_helpers.h\"\n+#include \"jaxlib/kernel_helpers.h\"\n+\n+namespace jax {\n+namespace {\n+\n+__device__ void ComputePermutation(const std::int32_t* pivots,\n+ std::int32_t* permutation_out,\n+ const std::int32_t pivot_size,\n+ const std::int32_t permutation_size) {\n+ for (int i = 0; i < permutation_size; ++i) {\n+ permutation_out[i] = i;\n+ }\n+\n+ // Compute the permutation from a sequence of transpositions encoded in the\n+ // pivot array by applying the transpositions in order on the identity\n+ // permutation.\n+ for (int i = 0; i < pivot_size; ++i) {\n+ if ((pivots[i] < 0) || (pivots[i] >= permutation_size)) {\n+ continue;\n+ }\n+ std::int32_t swap_temporary = permutation_out[i];\n+ permutation_out[i] = permutation_out[pivots[i]];\n+ permutation_out[pivots[i]] = swap_temporary;\n+ }\n+}\n+\n+__global__ void LuPivotsToPermutationKernel(\n+ const std::int32_t* pivots, std::int32_t* permutation_out,\n+ const std::int64_t batch_size, const std::int32_t pivot_size,\n+ const std::int32_t permutation_size) {\n+ for (std::int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n+ idx < batch_size; idx += blockDim.x * gridDim.x) {\n+ // Fill in the output array with the identity permutation.\n+ ComputePermutation(pivots + idx * pivot_size,\n+ permutation_out + idx * permutation_size, pivot_size,\n+ permutation_size);\n+ }\n+}\n+\n+} // namespace\n+\n+struct LuPivotsToPermutationDescriptor {\n+ std::int64_t batch_size;\n+ std::int32_t pivot_size;\n+ std::int32_t permutation_size;\n+};\n+\n+std::string BuildCudaLuPivotsToPermutationDescriptor(\n+ std::int64_t batch_size, std::int32_t pivot_size,\n+ std::int32_t permutation_size) {\n+ return PackDescriptorAsString(LuPivotsToPermutationDescriptor{\n+ batch_size, pivot_size, permutation_size});\n+}\n+\n+void CudaLuPivotsToPermutation(cudaStream_t stream, void** buffers,\n+ const char* opaque, std::size_t opaque_len) {\n+ const std::int32_t* pivots =\n+ reinterpret_cast<const std::int32_t*>(buffers[0]);\n+ std::int32_t* permutation_out = reinterpret_cast<std::int32_t*>(buffers[1]);\n+ const auto& descriptor =\n+ *UnpackDescriptor<LuPivotsToPermutationDescriptor>(opaque, opaque_len);\n+\n+ const int block_dim = 128;\n+ const std::int64_t grid_dim = std::min<std::int64_t>(\n+ 1024, (descriptor.batch_size + block_dim - 1) / block_dim);\n+\n+ LuPivotsToPermutationKernel<<<grid_dim, block_dim,\n+ /*dynamic_shared_mem_bytes=*/0, stream>>>(\n+ pivots, permutation_out, descriptor.batch_size, descriptor.pivot_size,\n+ descriptor.permutation_size);\n+ ThrowIfError(cudaGetLastError());\n+}\n+\n+} // namespace jax\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jaxlib/cuda_lu_pivot_kernels.h", "diff": "+/* Copyright 2021 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+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+==============================================================================*/\n+\n+#ifndef JAXLIB_CUDA_LU_PIVOT_KERNELS_H_\n+#define JAXLIB_CUDA_LU_PIVOT_KERNELS_H_\n+\n+#include <cstddef>\n+#include <string>\n+\n+#include \"third_party/gpus/cuda/include/cuda_runtime_api.h\"\n+\n+namespace jax {\n+\n+std::string BuildCudaLuPivotsToPermutationDescriptor(\n+ std::int64_t batch_size, std::int32_t pivot_size,\n+ std::int32_t permutation_size);\n+\n+void CudaLuPivotsToPermutation(cudaStream_t stream, void** buffers,\n+ const char* opaque, std::size_t opaque_len);\n+\n+} // namespace jax\n+\n+#endif // JAXLIB_CUDA_LU_PIVOT_KERNELS_H_\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -473,6 +473,45 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nself.assertTrue(np.all(np.linalg.norm(\nnp.matmul(args, vs) - ws[..., None, :] * vs) < 1e-3))\n+ @parameterized.named_parameters(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 [(1,), (4,), (5,)]\n+ for dtype in (np.int32,)))\n+ def testLuPivotsToPermutation(self, shape, dtype):\n+ jtu.skip_if_unsupported_type(dtype)\n+ pivots_size = shape[-1]\n+ permutation_size = 2 * pivots_size\n+\n+ pivots = jnp.arange(permutation_size - 1, pivots_size - 1, -1, dtype=dtype)\n+ pivots = jnp.broadcast_to(pivots, shape)\n+ actual = lax.linalg.lu_pivots_to_permutation(pivots, permutation_size)\n+ expected = jnp.arange(permutation_size - 1, -1, -1, dtype=dtype)\n+ expected = jnp.broadcast_to(expected, actual.shape)\n+ self.assertArraysEqual(actual, expected)\n+\n+ @parameterized.named_parameters(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 [(1,), (4,), (5,)]\n+ for dtype in (np.int32,)))\n+ def testLuPivotsToPermutationBatching(self, shape, dtype):\n+ jtu.skip_if_unsupported_type(dtype)\n+ shape = (10,) + shape\n+ pivots_size = shape[-1]\n+ permutation_size = 2 * pivots_size\n+\n+ pivots = jnp.arange(permutation_size - 1, pivots_size - 1, -1, dtype=dtype)\n+ pivots = jnp.broadcast_to(pivots, shape)\n+ batched_fn = vmap(\n+ lambda x: lax.linalg.lu_pivots_to_permutation(x, permutation_size))\n+ actual = batched_fn(pivots)\n+ expected = jnp.arange(permutation_size - 1, -1, -1, dtype=dtype)\n+ expected = jnp.broadcast_to(expected, actual.shape)\n+ self.assertArraysEqual(actual, expected)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_ord={}_axis={}_keepdims={}\".format(\njtu.format_shape_dtype_string(shape, dtype), ord, axis, keepdims),\n" } ]
Python
Apache License 2.0
google/jax
Reimplement as JAX Primitive
260,411
05.04.2021 15:56:38
-10,800
6176ac1cb606e0fcbbb711f3999930f0d7270142
[jax2tf] Fix bug in dot_general. The case when there were batch dimensions but RHS has only one inner dimmension was handled incorrectly. Add test also.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1262,7 +1262,7 @@ def _dot_general(lhs, rhs, dimension_numbers, precision, preferred_element_type)\ndel precision\ndel preferred_element_type\n(lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n- lhs_dim, rhs_dim = len(lhs.shape), len(rhs.shape)\n+ lhs_ndim, rhs_ndim = len(lhs.shape), len(rhs.shape)\n# This condition ensures that:\n# 1) the considered dtype is not tf.bfloat16/tf.int32, which are supported by\n# tf.linalg.einsum but not by tf.linalg.matmul;\n@@ -1275,9 +1275,9 @@ def _dot_general(lhs, rhs, dimension_numbers, precision, preferred_element_type)\n# matrix/matrix, vector/matrix or matrix/vector multiplication.\nif (not lhs.dtype in [tf.bfloat16, tf.int32]\nand lhs_batch == rhs_batch == tuple(range(len(lhs_batch)))\n- and lhs_dim - rhs_dim in [-1, 0, 1]\n- and 1 <= lhs_dim - len(lhs_batch) <= 2\n- and 1 <= rhs_dim - len(rhs_batch) <= 2\n+ and lhs_ndim - rhs_ndim in [-1, 0, 1]\n+ and 1 <= lhs_ndim - len(lhs_batch) <= 2\n+ and 1 <= rhs_ndim - len(rhs_batch) <= 2\nand lhs_contracting == (len(lhs.shape) - 1,)\nand rhs_contracting == (len(lhs_batch),)):\n# All the inputs to tf.linalg.matmul must have 2 inner dimensions,\n@@ -1299,14 +1299,15 @@ def _dot_general(lhs, rhs, dimension_numbers, precision, preferred_element_type)\n# and the resulting shape is (). We need to squeeze the result of\n# tf.linalg.matmul as it will have shape [1, 1].\nsqueeze_idxs = []\n- if lhs_dim - len(lhs_batch) == 1:\n- lhs = tf.expand_dims(lhs, lhs_dim - 1)\n+ if lhs_ndim - len(lhs_batch) == 1:\n+ lhs = tf.expand_dims(lhs, lhs_ndim - 1)\nsqueeze_idxs.append(len(lhs.shape) - 2)\n- if rhs_dim - len(rhs_batch) == 1:\n- rhs = tf.expand_dims(rhs, rhs_dim - 2)\n+ if rhs_ndim - len(rhs_batch) == 1:\n+ rhs = tf.expand_dims(rhs, rhs_ndim)\nsqueeze_idxs.append(len(rhs.shape) - 1)\nresult = tf.linalg.matmul(lhs, rhs)\nif len(squeeze_idxs) != 0:\n+ assert all([result.shape[i] == 1 for i in squeeze_idxs])\nresult = tf.squeeze(result, squeeze_idxs)\nreturn result\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -2379,7 +2379,9 @@ for dtype in jtu.dtypes.all:\n]:\nfor lhs_shape, rhs_shape, dimension_numbers in [\n((3, 4), (4, 2), (((1,), (0,)), ((), ()))),\n- ((1, 3, 4), (1, 4, 3), (((2, 1), (1, 2)), ((0,), (0,))))\n+ ((1, 3, 4), (1, 4, 3), (((2, 1), (1, 2)), ((0,), (0,)))),\n+ # Some batch dimensions\n+ ((7, 3, 4), (7, 4), (((2,), (1,)), ((0,), (0,)))),\n]:\n_make_dot_general_harness(\n\"dtypes_and_precision\",\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -99,7 +99,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# If you want to run this test for only one harness, add parameter\n# `one_containing=\"foo\"` to parameterized below.\n@primitive_harness.parameterized(\n- primitive_harness.all_harnesses, include_jax_unimpl=False,\n+ primitive_harness.all_harnesses, include_jax_unimpl=False\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix bug in dot_general. The case when there were batch dimensions but RHS has only one inner dimmension was handled incorrectly. Add test also.
260,411
05.04.2021 19:29:41
-10,800
4e2e30da0cdae166fb981d0752bd7b2e5c47b5b3
Increase tolerange for dot_general
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -464,6 +464,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ncustom_numeric(\ndtypes=[np.complex64, np.float32], devices=(\"cpu\", \"gpu\"),\ntol=1e-5),\n+ custom_numeric(\n+ dtypes=[np.complex128, np.float64], devices=(\"cpu\", \"gpu\"),\n+ tol=1e-12),\ncustom_numeric(dtypes=np.float32, devices=\"tpu\", tol=0.1),\ncustom_numeric(dtypes=np.complex64, devices=\"tpu\", tol=0.3),\ncustom_numeric(dtypes=np.float16, devices=(\"gpu\", \"tpu\"), tol=0.1),\n" } ]
Python
Apache License 2.0
google/jax
Increase tolerange for dot_general
260,416
06.04.2021 17:08:33
-7,200
73bc03794c9b9531ffccaf0efcb294f055c8ec6b
Fix jnp.flip for axis tuples
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1111,7 +1111,8 @@ def flip(m, axis: Optional[Union[int, Tuple[int, ...]]] = None):\n_check_arraylike(\"flip\", m)\nif axis is None:\nreturn lax.rev(m, list(range(len(shape(m)))))\n- return lax.rev(m, [_canonicalize_axis(axis, ndim(m))])\n+ axis = _ensure_index_tuple(axis)\n+ return lax.rev(m, [_canonicalize_axis(ax, ndim(m)) for ax in axis])\n@_wraps(np.fliplr)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -3449,7 +3449,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n\"shape\": shape, \"dtype\": dtype, \"axis\": axis}\nfor shape in [(3,), (2, 3)]\nfor dtype in default_dtypes\n- for axis in list(range(-len(shape), len(shape))) + [None] # Test negative axes\n+ for axis in list(range(-len(shape), len(shape))) + [None] + [tuple(range(len(shape)))] # Test negative axes and tuples\n))\ndef testFlip(self, shape, dtype, axis):\nrng = jtu.rand_default(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
Fix jnp.flip for axis tuples
260,335
02.04.2021 13:23:43
25,200
abf2d69262c581813bd8da4728b669a5ecd7cd10
djax: add analogue of lower_fun, dot
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3174,11 +3174,15 @@ def _dot_general_shape_rule(lhs, rhs, *, dimension_numbers, precision,\n\"shape, got {} and {}.\")\nraise TypeError(msg.format(lhs_contracting_shape, rhs_contracting_shape))\n- batch_shape = tuple(lhs_batch_shape)\n+ return _dot_general_shape_computation(lhs.shape, rhs.shape, dimension_numbers)\n+\n+def _dot_general_shape_computation(lhs_shape, rhs_shape, dimension_numbers):\n+ (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n+ batch_shape = tuple(np.take(lhs_shape, lhs_batch))\nlhs_contract_or_batch = tuple(sorted(tuple(lhs_contracting) + tuple(lhs_batch)))\n- lhs_tensored_shape = tuple(np.delete(lhs.shape, lhs_contract_or_batch))\n+ lhs_tensored_shape = tuple(np.delete(lhs_shape, lhs_contract_or_batch))\nrhs_contract_or_batch = tuple(sorted(tuple(rhs_contracting) + tuple(rhs_batch)))\n- rhs_tensored_shape = tuple(np.delete(rhs.shape, rhs_contract_or_batch))\n+ rhs_tensored_shape = tuple(np.delete(rhs_shape, rhs_contract_or_batch))\nreturn batch_shape + lhs_tensored_shape + rhs_tensored_shape\ndef _dot_general_dtype_rule(lhs, rhs, *, dimension_numbers, precision,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/djax.py", "new_path": "jax/experimental/djax.py", "diff": "from functools import partial, reduce\nimport itertools as it\n+import operator as op\nfrom typing import (Tuple, List, Sequence, Set, Dict, Any, Callable, Union,\nOptional)\n@@ -479,8 +480,10 @@ def _place_in_dim_tracers_in_shapes(trace, in_avals):\nif dim_tracer is None:\ndim_tracer = dim_tracers[id(d)] = trace.new_arg(d)\nnew_shape.append(dim_tracer)\n- else:\n+ elif isinstance(d, (int, BoundedInt)):\nnew_shape.append(d)\n+ else:\n+ raise NotImplementedError(d) # TODO\nnew_aval = AbsArray(tuple(new_shape), aval._eltTy)\nnew_in_avals.append(new_aval)\nreturn list(dim_tracers.values()), new_in_avals\n@@ -573,10 +576,11 @@ def partition_list(bs, lst):\ndef _raise_absarray_to_type_level(aval: AbsArray, weak_type: bool):\nassert isinstance(aval, AbsArray)\n+ unique_avals: Dict[int, AbsArray] = {}\nshape = []\nfor d in aval.shape:\nif isinstance(d, BoundedInt):\n- shape.append(AbsArray((), BoundedIntTy(d._bound)))\n+ shape.append(unique_avals.setdefault(id(d), AbsArray((), BoundedIntTy(d._bound))))\nelif isinstance(d, DimIndexer):\nraise NotImplementedError # TODO\nelse:\n@@ -584,7 +588,7 @@ def _raise_absarray_to_type_level(aval: AbsArray, weak_type: bool):\nreturn AbsArray(tuple(shape), aval._eltTy)\ncore.raise_to_shaped_mappings[AbsArray] = _raise_absarray_to_type_level\n-def _abstractify_array_for_ad(x: Array):\n+def _abstractify_array_for_ad(x: Array): # TODO misleading name, used in djit\nreturn AbsArray(x.shape, x._eltTy)\ncore.pytype_aval_mappings[Array] = _abstractify_array_for_ad\n@@ -751,6 +755,9 @@ def djit(fun):\ndef f_jitted(*args, **kwargs):\nargs, in_tree = tree_flatten((args, kwargs))\nf, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n+ # TODO we shouldn't dedup avals one array at a time; need to do it for the\n+ # full argument list!\n+ # unique_avals: Dict[int, core.AbstractValue] = {}\nin_avals = [core.raise_to_shaped(core.get_aval(x)) for x in args]\njaxpr, consts, unconverted_binders = trace_to_jaxpr_dynamic(f, in_avals)\nnum_consts = len(consts)\n@@ -772,6 +779,45 @@ def _extract_dim_vals(in_dim_binders, in_binders, unconverted_binders, args):\nreturn in_dim_vals, args\n+def traceable_to_padded_translation(traceable):\n+ def translation(c, dims, avals, operands, **params):\n+ dim_avals = [core.ShapedArray((), np.int32) for _ in dims]\n+ padded_avals = map(_replace_vars_with_bounds, avals)\n+\n+ @lu.wrap_init\n+ def fun(*args):\n+ dim_sizes, args = split_list(args, [len(dims)])\n+ logical_sizes = dict(zip(dims, dim_sizes))\n+ logical_shapes = [tuple([logical_sizes.get(d, d) for d in aval.shape])\n+ for aval in avals] # TODO more cases\n+ return traceable(logical_shapes, *args, **params)\n+\n+ in_avals = [*dim_avals, *padded_avals]\n+ jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(fun, in_avals)\n+\n+ operands_ = it.chain.from_iterable([*dims.values(), *operands])\n+ outs = xla.jaxpr_subcomp(c, jaxpr, None, xla.AxisEnv(1, (), ()),\n+ xla._xla_consts(c, consts), '', *operands_)\n+ return xla._partition_outputs(out_avals, outs)\n+ return translation\n+\n+def _replace_vars_with_bounds(aval):\n+ if not isinstance(aval, AbsArray):\n+ return aval\n+ else:\n+ new_shape = []\n+ for d in aval.shape:\n+ if isinstance(d, Var):\n+ assert d.aval.shape == () and isinstance(d.aval._eltTy, BoundedIntTy)\n+ new_shape.append(d.aval._eltTy._bound)\n+ elif isinstance(d, int):\n+ new_shape.append(d)\n+ elif isinstance(d, BoundedInt):\n+ new_shape.append(d._bound)\n+ else:\n+ raise NotImplementedError(d)\n+ return core.ShapedArray(tuple(new_shape), aval._eltTy._dtype)\n+\n# AD\nfrom jax.interpreters import ad\n@@ -1046,31 +1092,89 @@ def _reduce_sum_typecheck_rule(x, *, axes):\nreturn [reduce_sum_p.abstract_eval(x.aval, axes=axes)]\ntypecheck_rules[reduce_sum_p] = _reduce_sum_typecheck_rule\n-def _reduce_sum_translation_rule(c, dims, avals, operands, *, axes):\n- (x,), = operands\n- shape = c.get_shape(x)\n- dtype = shape.numpy_dtype()\n- iota_shape = xc.Shape.array_shape(xc.PrimitiveType.S32, shape.dimensions())\n- if dims:\n- aval, = avals\n- masks = [xops.Lt(xops.Iota(c, iota_shape, i), dims[v][0])\n- for i, v in enumerate(aval.shape) if isinstance(v, Var)\n- and i in axes]\n- map(c.get_shape, masks)\n- x = xops.Select(reduce(xops.And, masks), x,\n- xops.Broadcast(xb.constant(c, np.zeros((), dtype)),\n- shape.dimensions()))\n- scalar = core.ShapedArray((), dtype)\n- out = xops.Reduce(c, [x], [xb.constant(c, np.array(0, dtype))],\n- xla.primitive_subcomputation(lax.add_p, scalar, scalar), axes)\n- return [[out]]\n-translations[reduce_sum_p] = _reduce_sum_translation_rule\n+def _reduce_sum_translation_traceable(logical_shapes, x, *, axes):\n+ shape, = logical_shapes\n+ x = _replace_masked_values(shape, x, 0, axes=axes)\n+ return [lax._reduce_sum(x, axes=axes)]\n+translations[reduce_sum_p] = traceable_to_padded_translation(\n+ _reduce_sum_translation_traceable)\n+\n+def _replace_masked_values(logical_shape, x, val, axes=None):\n+ axes = axes or set(range(len(logical_shape)))\n+ masks = [lax.broadcasted_iota(np.int32, x.shape, i) < d\n+ for i, d in enumerate(logical_shape) if d is not None and i in axes]\n+ if masks:\n+ x = lax.select(reduce(op.and_, masks), x, lax.full_like(x, val))\n+ return x\ndef _reduce_sum_transpose_rule(cotangent, operand, *, axes):\nraise NotImplementedError # TODO\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\n+### lt\n+\n+def lt(x, y):\n+ return lt_p.bind(x, y)\n+lt_p = core.Primitive('lt')\n+\n+@lt_p.def_abstract_eval\n+def _lt_abstract_eval(x, y):\n+ if isinstance(x, AbsArray) or isinstance(y, AbsArray):\n+ # TODO check dtypes match\n+ if not x.shape:\n+ return AbsArray(y.shape, BaseType(np.dtype('bool')))\n+ if not y.shape:\n+ return AbsArray(x.shape, BaseType(np.dtype('bool')))\n+ map(_dims_must_equal, x.shape, y.shape)\n+ return AbsArray(x.shape, BaseType(np.dtype('bool')))\n+ else:\n+ return lax.lt_p.abstract_eval(x, y)\n+\n+def _lt_typecheck_rule(x, y):\n+ return [lt_p.abstract_eval(x.aval, y.aval)]\n+\n+def _lt_translation_rule(c, dims, avals, operands):\n+ (x,), (y,) = operands\n+ return [[xops.Lt(x, y)]]\n+\n+\n+### dot\n+\n+def dot(x, y):\n+ assert len(x.shape) == len(y.shape) == 2\n+ return dot_general(x, y, ([1], [0]), ([], []))\n+\n+Dims = Tuple[Sequence[int], Sequence[int]]\n+\n+def dot_general(x: Any, y: Any, contract: Dims, batch: Dims) -> Any:\n+ return dot_general_p.bind(x, y, contract=contract, batch=batch)\n+dot_general_p = core.Primitive('dot_general')\n+\n+@dot_general_p.def_abstract_eval\n+def _dot_general_abstract_eval(x, y, *, contract, batch):\n+ for i, j in zip(*contract): _dims_must_equal(x.shape[i], y.shape[j])\n+ for i, j in zip(*batch): _dims_must_equal(x.shape[i], y.shape[j])\n+ shape = lax._dot_general_shape_computation(x.shape, y.shape, (contract, batch))\n+ return AbsArray(shape, x._eltTy)\n+\n+def _dot_general_typecheck_rule(x, y, *, contract, batch):\n+ return [_dot_general_abstract_eval(x.aval, y.aval,\n+ contract=contract, batch=batch)]\n+typecheck_rules[dot_general_p] = _dot_general_typecheck_rule\n+\n+def _dot_general_trans(logical_shapes, x, y, *, contract, batch):\n+ x_shape, _ = logical_shapes\n+ lhs_contract, _ = contract\n+ x = _replace_masked_values(x_shape, x, 0, axes=lhs_contract)\n+ return [lax.dot_general(x, y, dimension_numbers=(contract, batch))]\n+translations[dot_general_p] = traceable_to_padded_translation(_dot_general_trans)\n+\n+def _dot_general_transpose_rule(cotangent, x, y, *, contract, batch):\n+ assert False # TODO\n+ad.primitive_transposes[dot_general_p] = _dot_general_transpose_rule\n+\n+\n## add\ndef add(x: Any, y: Any) -> Any:\n@@ -1174,32 +1278,18 @@ def _nonzero_typecheck_rule(invar):\nreturn out_dim_var, out_val_aval\ntypecheck_rules[nonzero_p] = _nonzero_typecheck_rule\n-def _nonzero_translation_rule(c, dims, avals, operands):\n- (vals,), = operands\n- shape = c.get_shape(vals)\n- last_axis = len(shape.dimensions()) - 1\n- zeros = xops.Broadcast(xb.constant(c, np.zeros((), shape.numpy_dtype())),\n- shape.dimensions())\n- s32_etype = xc.dtype_to_etype(np.dtype('int32'))\n- nonzero_indicators = xops.ConvertElementType(xops.Ne(vals, zeros), s32_etype)\n- i = core.ShapedArray((), np.dtype('int32'))\n- out_dim = xops.Reduce(c, [nonzero_indicators],\n- [xb.constant(c, np.array(0, np.dtype('int32')))],\n- xla.primitive_subcomputation(lax.add_p, i, i),\n- (last_axis,))\n- c.get_shape(out_dim) # xla type checking\n-\n- subc = xb.make_computation_builder(\"sort_gt_comparator\")\n- params = [xb.parameter(subc, i, xc.Shape.array_shape(s32_etype, ()))\n- for i in range(4)]\n- comparator = subc.build(xops.Gt(params[0], params[1]))\n- iota_shape = xc.Shape.array_shape(xc.PrimitiveType.S32, shape.dimensions())\n- ans = xops.Sort(c, [nonzero_indicators, xops.Iota(c, iota_shape, last_axis)],\n- is_stable=True, comparator=comparator)\n- _, out_val = xla.xla_destructure(c, ans)\n- c.get_shape(out_val) # xla type checking\n- return [[out_dim], [out_val]]\n-translations[nonzero_p] = _nonzero_translation_rule\n+def _nonzero_translation_traceable(logical_shapes, x):\n+ shape, = logical_shapes\n+ assert shape\n+ x = _replace_masked_values(shape, x, 0)\n+ nonzero_indicators = x != 0\n+ last_axis = len(shape) - 1\n+ out_sizes = lax._reduce_sum(nonzero_indicators.astype(np.int32), [last_axis])\n+ iota = lax.broadcasted_iota(np.int32, x.shape, dimension=last_axis)\n+ _, idx = lax.sort_key_val(~nonzero_indicators, iota, dimension=last_axis)\n+ return out_sizes, idx\n+translations[nonzero_p] = traceable_to_padded_translation(\n+ _nonzero_translation_traceable)\ndef _nonzero_vmap_rule(args, in_dims):\n(x,), (d,) = args, in_dims\n@@ -1309,8 +1399,10 @@ translations[broadcast_p] = _broadcast_translation_rule\nimport jax.numpy as jnp\n-def bbarray(bound_shape: Tuple[int], x: NDArray):\n- shape = tuple(BoundedInt(d, bound) for d, bound in zip(x.shape, bound_shape))\n+def bbarray(bound_shape: Tuple[int, ...], x: NDArray):\n+ sizes: Dict[int, BoundedInt] = {}\n+ shape = tuple(sizes.setdefault(d, BoundedInt(d, bound))\n+ for d, bound in zip(x.shape, bound_shape))\nslices = tuple(slice(d) for d in x.shape)\npadded_x = jnp.ones(bound_shape, x.dtype).at[slices].set(x)\nreturn Array(shape, BaseType(x.dtype), padded_x)\n@@ -1442,3 +1534,15 @@ if __name__ == '__main__':\nxs = jnp.array([[0, 1, 0, 1, 0, 1],\n[1, 1, 1, 1, 0, 1]])\nprint(jax.vmap(f)(xs))\n+\n+\n+ ## dot\n+\n+ @djit\n+ def f(x):\n+ return dot(x, x)\n+ p('dot(x, x)')\n+ x = bbarray((4, 4), np.arange(9., dtype=np.float32).reshape(3, 3))\n+ print(f(x))\n+ y = np.arange(9.).reshape(3, 3)\n+ print(f'should be\\n{np.dot(y, y)}')\n" } ]
Python
Apache License 2.0
google/jax
djax: add analogue of lower_fun, dot
260,709
06.04.2021 13:38:36
25,200
e186b9e591d4b6d3bda2bda841ba6d4335aee888
Mark lu_pivots_to_permutation as "not yet implemented" in JAX2TF.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -800,6 +800,7 @@ tf_not_yet_impl = [\n\"infeed\", \"outfeed\", \"pmax_p\",\n\"pmin\", \"ppermute\", \"psum\", \"pmax\", \"pgather\",\n\"axis_index\", \"pdot\", \"all_gather\",\n+ \"lu_pivots_to_permutation\",\n\"rng_bit_generator\",\n\"xla_pmap\",\n" } ]
Python
Apache License 2.0
google/jax
Mark lu_pivots_to_permutation as "not yet implemented" in JAX2TF.
260,411
07.04.2021 11:24:31
-10,800
dce31e9631f5cba7d4cc292072697dfb173c3fb6
[jax2tf] Fix handling of float0
[ { "change_type": "MODIFY", "old_path": "CHANGELOG.md", "new_path": "CHANGELOG.md", "diff": "@@ -9,9 +9,13 @@ PLEASE REMEMBER TO CHANGE THE '..master' WITH AN ACTUAL TAG in GITHUB LINK.\n-->\n## jax 0.2.13 (unreleased)\n+* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.12...master).\n+* Bug fixes:\n+ * The {func}`jax2tf.convert` now works in presence of gradients for functions\n+ with integer inputs ({jax-issue}`#6360`).\n## jax 0.2.12 (April 1 2021)\n-* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.11...master).\n+* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.11...v0.2.12).\n* New features\n* New profiling APIs: {func}`jax.profiler.start_trace`,\n{func}`jax.profiler.stop_trace`, and {func}`jax.profiler.trace`\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -153,6 +153,23 @@ is attempted. The plan is to fix this. Note that if no gradients are requested,\nthe PreventGradient ops will be saved along with the converted code and will\ngive a nice error if differentiation of the converted code is attempted.\n+### Converting gradients for integer-argument functions\n+\n+When JAX differentiates over functions with integer arguments, the gradients will\n+be zero-vectors with a special `float0` type (see PR 4039](https://github.com/google/jax/pull/4039)).\n+This type is translated to `bfloat16` when converting to TF. For example,\n+\n+```python\n+def f_jax(x): # x: int32\n+ return x * 2.\n+\n+jax.grad(f_jax, allow_int=True)(2)\n+# returns a special `float0`: array((b'',), dtype=[('float0', 'V')])\n+\n+jax2tf.convert(jax.grad(f_jax, allow_int=True))(2))\n+# returns a `bfloat16` zero: tf.Tensor(0, shape=(), dtype=bfloat16)\n+```\n+\n### TensorFlow XLA ops\nFor most JAX primitives there is a natural TF op that fits the needed semantics.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -81,8 +81,9 @@ def _is_tfval(v: TfVal) -> bool:\ndef _safe_convert_to_tensor(val, dtype=None) -> TfVal:\ndtype = dtype if dtype else (val.dtype if hasattr(val, \"dtype\") else None)\nconversion_type = to_tf_dtype(dtype) if dtype else None\n- # We can convert directly, because all dtypes (even bfloat16) are the same\n- # in JAX and TF.\n+ # The float0 type is not known to TF.\n+ if dtype and dtype == dtypes.float0:\n+ val = np.zeros(np.shape(val), conversion_type.as_numpy_dtype)\nreturn tf.convert_to_tensor(val, dtype=conversion_type)\n@@ -774,8 +775,7 @@ class TensorFlowTrace(core.Trace):\ndef to_tf_dtype(jax_dtype):\nif jax_dtype == dtypes.float0:\n- return tf.float32\n- else:\n+ jax_dtype = dtypes.bfloat16\nreturn tf.dtypes.as_dtype(jax_dtype)\ndef to_jax_dtype(tf_dtype):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -284,6 +284,43 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(4. * 4., y)\nself.assertAllClose(3. * 4., tape.gradient(y, x))\n+ def test_gradient_with_float0_intermediate(self):\n+ # Gradient over integer-argument functions\n+ def f(x, y): # x is an int, y is a float\n+ return 2 * x + y\n+\n+ def g(x): # x: f32\n+ return 2. * f(3 * x.astype(\"int32\"), x * 4.)\n+\n+ x = np.float_(2.)\n+ grad_g = jax.grad(g)\n+ self.ConvertAndCompare(grad_g, x)\n+\n+\n+ def test_gradient_with_float0_result(self):\n+ # Gradient over integer-argument functions, with float0 result\n+ def f(x, y): # x is an int, y is a float\n+ return 2 * x + y\n+\n+ def g(x): # x: i32\n+ return jnp.sum(2. * f(3 * x, 4. * x.astype(\"float32\")))\n+\n+ grad_g = jax.grad(g, allow_int=True)\n+ x = 2\n+ d_dx_jax = grad_g(x)\n+ d_dx_tf = jax2tf.convert(grad_g)(x)\n+ self.assertEqual(d_dx_jax.dtype, dtypes.float0)\n+ self.assertAllClose(jnp.zeros(np.shape(d_dx_jax), dtypes.bfloat16),\n+ d_dx_tf.numpy())\n+\n+ shape = (3, 4)\n+ x = np.ones(shape, dtype=np.int32)\n+ d_dx_jax = grad_g(x)\n+ d_dx_tf = jax2tf.convert(grad_g)(x)\n+ self.assertEqual(d_dx_jax.dtype, dtypes.float0)\n+ self.assertAllClose(jnp.zeros(np.shape(d_dx_jax), dtypes.bfloat16),\n+ d_dx_tf.numpy())\n+\ndef test_convert_argument_non_callable_error(self):\nwith self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\njax2tf.convert(5.)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "new_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "diff": "@@ -44,6 +44,8 @@ def _make_tf_args(args):\ndef _make_tf_input_signature(*tf_args) -> List[tf.TensorSpec]:\n# tf_args can be PyTrees\ndef _make_one_arg_signature(tf_arg):\n+ if np.isscalar(tf_arg):\n+ tf_arg = np.array(tf_arg)\nreturn tf.TensorSpec(np.shape(tf_arg), tf_arg.dtype)\nreturn tf.nest.map_structure(_make_one_arg_signature, list(tf_args))\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix handling of float0
260,287
25.03.2021 11:31:55
0
ba8430605dbd583210854c0bc0c8bbddf6034048
Fix lax.all_gather inside xmap The batching rule didn't properly handle tupled axis names.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -1119,7 +1119,11 @@ def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, ax\ndef _all_gather_batched_collective(frame, vals_in, dims_in, all_gather_dimension, axis_name, axis_index_groups, axis_size):\nassert axis_index_groups is None, \"axis_index_groups not supported in vmap\"\nassert axis_size == frame.size, \"axis size doesn't match\"\n- assert axis_name == frame.name, \"batcher called with wrong axis name\"\n+ if not isinstance(axis_name, tuple):\n+ axis_name = (axis_name,)\n+ if len(axis_name) > 1:\n+ raise NotImplementedError(\"Please open a feature request!\")\n+ assert axis_name == (frame.name,), \"batcher called with wrong axis name\"\n(x,), (d,) = vals_in, dims_in\nassert d is not batching.not_mapped\nreturn _moveaxis(d, all_gather_dimension, x), batching.not_mapped\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -314,6 +314,13 @@ class XMapTest(XMapTestCase):\nout_axes=['i', ...])(x)\nself.assertAllClose(result, perm)\n+ @ignore_xmap_warning()\n+ def testCollectiveAllGather(self):\n+ x = jnp.arange(4)\n+ result = xmap(lambda x: lax.all_gather(x, 'i') + lax.axis_index('i'),\n+ in_axes=['i', ...], out_axes=['i', ...])(x)\n+ self.assertAllClose(result, x + x[jnp.newaxis].T)\n+\n@ignore_xmap_warning()\n@with_mesh([('x', 2), ('y', 2)])\ndef testOneLogicalTwoMeshAxesBasic(self):\n" } ]
Python
Apache License 2.0
google/jax
Fix lax.all_gather inside xmap The batching rule didn't properly handle tupled axis names.
260,411
04.04.2021 16:23:24
-10,800
56e41b7cd76aa85f1e1b7c2a8d39efd818a05987
Add support for cummax
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -5432,10 +5432,9 @@ def reduce_window_shape_tuple(operand_shape, window_dimensions, window_strides,\noperand_shape = _dilate_shape(operand_shape, base_dilation)\nif window_dilation is not None:\nwindow_dimensions = _dilate_shape(window_dimensions, window_dilation)\n- operand_padded = np.add(operand_shape, np.add(*zip(*padding)))\n- t = np.floor_divide(\n- np.subtract(operand_padded, window_dimensions), window_strides) + 1\n- return tuple(t)\n+ pads_lo, pads_hi = zip(*padding)\n+ operand_padded = core.shapes_sum(operand_shape, pads_lo, pads_hi)\n+ return core.shape_stride(operand_padded, window_dimensions, window_strides)\n_reduce_window_max_translation_rule = partial(\n_reduce_window_chooser_translation_rule, max_p, _get_max_identity)\n@@ -6231,8 +6230,7 @@ def _dilate_shape(shape, dilation):\nmsg = \"All dilations must be positive, got {}.\"\nraise TypeError(msg.format(dilation))\ndilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)\n- return np.where(shape == 0, 0,\n- np.multiply(dilation, np.subtract(shape, 1)) + 1)\n+ return core.dim_dilate_shape(shape, dilation)\ndef _ceil_divide(x1, x2):\nreturn -np.floor_divide(np.negative(x1), x2)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1252,6 +1252,17 @@ class DimensionHandler:\nraise ValueError(f\"Cannot divide evenly the sizes of shapes {tuple(s1)} and {tuple(s2)}\")\nreturn sz1 // sz2\n+ def stride(self, d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n+ \"\"\"(d - window_size) // window_stride + 1\"\"\"\n+ return (d - window_size) // window_stride + 1\n+\n+ def dilate(self, d: DimSize, dilation: int) -> DimSize:\n+ \"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\n+ return 0 if d == 0 else 1 + dilation * (d - 1)\n+\n+ def add(self, *d: DimSize):\n+ return sum(d)\n+\n_dimension_handler_int = DimensionHandler()\n_SPECIAL_DIMENSION_HANDLERS: Dict[type, DimensionHandler] = {}\n@@ -1305,6 +1316,29 @@ def dim_divide_shape_sizes(s1: Shape, s2: Shape) -> DimSize:\ndef dim_same_total_size(s1: Shape, s2: Shape) -> bool:\nreturn 1 == dim_divide_shape_sizes(s1, s2)\n+def dim_dilate(d: DimSize, dilation: DimSize) -> DimSize:\n+ \"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\n+ return _get_dim_handler(d, dilation).dilate(d, dilation)\n+\n+def dim_dilate_shape(s: Shape, dilations: Sequence[int]) -> Shape:\n+ \"\"\"Implements `dim_dilate` for each dimension.\"\"\"\n+ return tuple(safe_map(dim_dilate, s, dilations))\n+\n+def dim_sum(*d: DimSize) -> Shape:\n+ \"\"\"sum(d)\"\"\"\n+ return _get_dim_handler(*d).add(*d)\n+\n+def shapes_sum(*s: Shape) -> Shape:\n+ \"\"\"Implements sum(s)\"\"\"\n+ return tuple(safe_map(dim_sum, *s))\n+\n+def dim_stride(d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n+ return _get_dim_handler(d, window_size, window_stride).stride(d, window_size, window_stride)\n+\n+def shape_stride(s: Shape, window_size: Shape, window_stride: Shape) -> Shape:\n+ \"\"\"(s - window_size) // window_stride + 1\"\"\"\n+ return tuple(safe_map(dim_stride, s, window_size, window_stride))\n+\ndef _canonicalize_dimension(dim: DimSize) -> DimSize:\nif type(dim) in _SPECIAL_DIMENSION_HANDLERS:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -67,6 +67,7 @@ class DimVar:\ndef __ne__(self, other):\nreturn not self == other\n+## TODO: add unit tests\nclass DimensionHandlerVar(core.DimensionHandler):\n\"\"\"See core.DimensionHandler.\"\"\"\n@@ -105,6 +106,26 @@ class DimensionHandlerVar(core.DimensionHandler):\nraise TypeError(msg)\nreturn super(DimensionHandlerVar, self).divide_shape_sizes(s1_ints, s2_ints)\n+ def dilate(self, d: DimSize, dilation: DimSize) -> DimSize:\n+ \"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\n+ if dilation not in {1}:\n+ raise TypeError(f\"Dilation is not supported for shape variables (d = {dilation})\")\n+ return d\n+\n+ def stride(self, d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n+ \"\"\"Implements `(d - window_size) // window_stride + 1`\"\"\"\n+ if {window_size, window_stride} != {1}:\n+ raise TypeError(f\"Striding is not supported for shape variables (window_size = {window_size}, stride = {window_stride}\")\n+ return d\n+\n+ def add(self, *d: DimSize):\n+ d_ints, d_vars = _split_shape_ints(d)\n+ if len(d_vars) != 1:\n+ raise TypeError(f\"Adding shape variables is not supported ({' + '.join(map(str, d))})\")\n+ if sum(d_ints) != 0:\n+ raise TypeError(f\"Adding non-zero to shape variables is not supported {' + '.join(map(str, d))}\")\n+ return d_vars[0]\n+\ncore._SPECIAL_DIMENSION_HANDLERS[DimVar] = DimensionHandlerVar()\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": "@@ -28,7 +28,7 @@ from jax.experimental.jax2tf import shape_poly\nfrom jax import lax\nimport jax.numpy as jnp\nfrom jax import test_util as jtu\n-from jax._src import util\n+from jax._src.lax import control_flow as lax_control_flow\nimport numpy as np\n@@ -545,7 +545,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1]),\ninput_signature=[tf.TensorSpec([None, 2, 3])],\n- polymorphic_shapes=[\"(batch, 2, 3)\"],\n+ polymorphic_shapes=[\"(batch, _, _)\"],\nexpected_output_signature=tf.TensorSpec([None, 6]))\nself.CheckShapePolymorphism(\n@@ -567,7 +567,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1, 3]),\ninput_signature=[tf.TensorSpec([None, 2, 4])],\n- polymorphic_shapes=[\"(batch, 2, 4)\"],\n+ polymorphic_shapes=[\"(batch, _, _)\"],\nexpected_output_signature=tf.TensorSpec([None, 1]))\ndef test_reshape_compiled(self):\n@@ -612,7 +612,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nf_jax,\ninput_signature=[tf.TensorSpec([None, 4], dtype=x.dtype),\ntf.TensorSpec([None, None, 4], dtype=y.dtype)],\n- polymorphic_shapes=[\"(d, 4)\", \"(batch, d, 4)\"],\n+ polymorphic_shapes=[\"(d, _)\", \"(batch, d, _)\"],\nexpected_output_signature=tf.TensorSpec([None, None, 4]))\nself.assertAllClose(f_jax(x, y), f_tf(x, y))\n@@ -628,7 +628,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ninput_signature=[tf.TensorSpec([None, 2, 3]),\ntf.TensorSpec([None, 2, 3]),\ntf.TensorSpec([None, 2, 3]),],\n- polymorphic_shapes=[\"b, 2, 3\", \"b, 2, 3\", \"b, 2, 3\"],\n+ polymorphic_shapes=[\"b, _, _\", \"b, _, _\", \"b, _, _\"],\nexpected_output_signature=tf.TensorSpec([None, 2, 3]))\nself.assertAllClose(f_jax(x, x, x), f_tf(x, x, x))\n@@ -663,6 +663,21 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 2, 3]))\nself.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n+ def test_cummax(self):\n+ @jax.vmap\n+ def f_jax(x):\n+ return lax_control_flow.cummax(x, axis=0, reverse=False)\n+\n+ batch_size = 7\n+ shape = (8, 9)\n+ x = np.ones((batch_size,) + shape, dtype=np.float32)\n+\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec((None,) + shape)],\n+ polymorphic_shapes=[\"b, _, _\"],\n+ expected_output_signature=tf.TensorSpec([None, 8, 9]))\n+ self.assertAllClose(f_jax(x), f_tf(x))\ndef test_squeeze(self):\ndef f_jax(x):\n" } ]
Python
Apache License 2.0
google/jax
Add support for cummax
260,411
04.04.2021 17:05:18
-10,800
4f9ac031d74c871be2f95c38cc3d605d2282a161
Add some support for convolutions
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -2786,7 +2786,7 @@ def _conv_general_dilated_shape_rule(\n\"must be a positive integer, got {}.\")\nraise ValueError(msg.format(batch_group_count))\nlhs_batch_count = lhs.shape[dimension_numbers.lhs_spec[0]]\n- if lhs_batch_count % batch_group_count != 0:\n+ if batch_group_count > 1 and lhs_batch_count % batch_group_count != 0:\nmsg = (\"conv_general_dilated batch_group_count must divide lhs batch \"\n\"dimension size, but {} does not divide {}.\")\nraise ValueError(msg.format(batch_group_count, lhs_batch_count))\n@@ -3861,18 +3861,15 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nmsg = (\"slice limit_indices must have the same length as start_indices, \"\n\"got start_indices {} and limit_indices {}.\")\nraise TypeError(msg.format(start_indices, limit_indices))\n- if (not masking.is_polymorphic(limit_indices) and\n- not masking.is_polymorphic(operand.shape) and\n- not np.all(np.less_equal(limit_indices, operand.shape))):\n+ if not core.shape_greater_equal(operand.shape, limit_indices):\nmsg = (\"slice limit_indices must be less than or equal to operand shape, \"\n\"got limit_indices {} for operand shape {}.\")\nraise TypeError(msg.format(limit_indices, operand.shape))\n- if not np.all(np.greater_equal(start_indices, 0)):\n+ if not core.shape_greater_equal(start_indices, (0,) * len(start_indices)):\nmsg = (\"slice start_indices must be greater than or equal to zero, \"\n\"got start_indices of {}.\")\nraise TypeError(msg.format(start_indices))\n- if (not masking.is_polymorphic(limit_indices) and\n- not np.all(np.greater_equal(limit_indices, start_indices))):\n+ if not core.shape_greater_equal(limit_indices, start_indices):\nmsg = (\"slice limit_indices must be greater than or equal to start_indices,\"\n\" got start_indices {} and limit_indices {}.\")\nraise TypeError(msg.format(start_indices, limit_indices))\n@@ -3884,13 +3881,15 @@ def _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\nmsg = (\"slice strides must have length equal to the number of dimensions \"\n\"of the operand, got strides {} for operand shape {}.\")\nraise TypeError(msg.format(strides, operand.shape))\n- if not np.all(np.greater(strides, 0)):\n+ if not core.shape_greater_equal(strides, (0,) * len(strides)):\nmsg = \"slice strides must be positive, got {}\"\nraise TypeError(msg.format(strides))\n- diff = np.subtract(limit_indices, start_indices)\n+ diff = core.shape_diff(limit_indices, start_indices)\n+ #diff = np.subtract(limit_indices, start_indices)\n# Not np.divmod since Poly.__rdivmod__ is ignored by NumPy, breaks poly stride\n- return tuple(q + (r > 0) for q, r in map(divmod, diff, strides))\n+ #return tuple(q + (r > 0) for q, r in map(divmod, diff, strides))\n+ return core.shape_stride(diff, (1,) * len(diff), strides)\ndef _slice_translation_rule(c, operand, *, start_indices, limit_indices,\nstrides):\n@@ -3961,11 +3960,11 @@ def _dynamic_slice_shape_rule(operand, *start_indices, slice_sizes):\nmsg = (\"dynamic_slice slice_sizes must have the same length as \"\n\"start_indices, got start_indices length {} and slice_sizes {}.\")\nraise TypeError(msg.format(len(start_indices), slice_sizes))\n- if not np.all(np.less_equal(slice_sizes, operand.shape)):\n+ if not core.shape_greater_equal(operand.shape, slice_sizes):\nmsg = (\"slice slice_sizes must be less than or equal to operand shape, \"\n\"got slice_sizes {} for operand shape {}.\")\nraise TypeError(msg.format(slice_sizes, operand.shape))\n- if not np.all(np.greater_equal(slice_sizes, 0)):\n+ if not core.shape_greater_equal(slice_sizes, (0,) * len(slice_sizes)):\nmsg = (\"slice slice_sizes must be greater than or equal to zero, \"\n\"got slice_sizes of {}.\")\nraise TypeError(msg.format(slice_sizes))\n@@ -6309,11 +6308,14 @@ def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\nlhs_padded = np.add(lhs_shape[2:], np.sum(np.array(pads).reshape(-1, 2),\naxis=1))\n- out_space = np.floor_divide(\n- np.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\n+ out_space = core.shape_stride(lhs_padded, rhs_shape[2:], strides)\nout_space = np.maximum(0, out_space)\n+ if batch_group_count > 1:\nassert lhs_shape[0] % batch_group_count == 0\n- out_shape = (lhs_shape[0] // batch_group_count, rhs_shape[0])\n+ out_shape_0 = lhs_shape[0] // batch_group_count\n+ else:\n+ out_shape_0 = lhs_shape[0]\n+ out_shape = (out_shape_0, rhs_shape[0])\nreturn tuple(out_shape + tuple(out_space))\n@@ -6373,8 +6375,6 @@ def _dynamic_slice_indices(operand, start_indices):\nmsg = (\"Length of slice indices must match number of operand dimensions ({} \"\n\"vs {})\")\nraise ValueError(msg.format(len(start_indices), operand.shape))\n- # map int over operand.shape to raise any dynamic-shape errors\n- safe_map(int, operand.shape)\nif not isinstance(start_indices, (tuple, list)):\nif start_indices.ndim != 1:\nraise ValueError(\"Slice indices must be a 1D sequence, got {}\"\n@@ -6559,8 +6559,12 @@ def _conv_general_vjp_rhs_padding(\nlhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)\nrhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)\nout_dilated_shape = _dilate_shape(out_shape, window_strides)\n- total_in_pad = out_dilated_shape + rhs_dilated_shape - lhs_dilated_shape - 1\n- return [(pad[0], tot - pad[0]) for pad, tot in zip(padding, total_in_pad)]\n+ pads_lo, _ = zip(*padding)\n+ pads_from_lhs = core.shape_diff(out_dilated_shape, lhs_dilated_shape)\n+ pads_from_rhs = core.shape_diff(core.shape_diff(rhs_dilated_shape, pads_lo),\n+ (1,) * len(pads_lo))\n+ pads_hi = core.shapes_sum(pads_from_lhs, pads_from_rhs)\n+ return list(zip(pads_lo, pads_hi))\ndef _balanced_eq(x, z, y):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1763,7 +1763,7 @@ def broadcast_to(arr, shape):\nshape = (shape,) if ndim(shape) == 0 else shape\nshape = canonicalize_shape(shape) # check that shape is concrete\narr_shape = _shape(arr)\n- if core.dim_symbolic_equal_shape(arr_shape, shape):\n+ if core.shape_symbolic_equal(arr_shape, shape):\nreturn arr\nelse:\nnlead = len(shape) - len(arr_shape)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1263,6 +1263,8 @@ class DimensionHandler:\ndef add(self, *d: DimSize):\nreturn sum(d)\n+ def diff(self, d1: DimSize, d2: DimSize) -> DimSize:\n+ return d1 - d2\n_dimension_handler_int = DimensionHandler()\n_SPECIAL_DIMENSION_HANDLERS: Dict[type, DimensionHandler] = {}\n@@ -1297,13 +1299,17 @@ def dim_symbolic_equal_one_of(d1: DimSize, dlist: Sequence[DimSize]) -> bool:\n\"\"\"True iff `d1` is symbolic equal to one of `dlist`\"\"\"\nreturn _get_dim_handler(d1, *dlist).symbolic_equal_one_of(d1, dlist)\n-def dim_symbolic_equal_shape(s1: Shape, s2: Shape) -> bool:\n+def shape_symbolic_equal(s1: Shape, s2: Shape) -> bool:\nreturn (len(s1) == len(s2) and\nall(dim_symbolic_equal(d1, d2) for d1, d2 in safe_zip(s1, s2)))\ndef dim_greater_equal(d1: DimSize, d2: DimSize) -> bool:\nreturn _get_dim_handler(d1, d2).greater_equal(d1, d2)\n+def shape_greater_equal(s1: Shape, s2: Shape) -> bool:\n+ return all(safe_map(dim_greater_equal, s1, s2))\n+\n+\ndef dim_divide_shape_sizes(s1: Shape, s2: Shape) -> DimSize:\n\"\"\"Computes the division of the size of arr_shape and newshape.\n@@ -1332,6 +1338,13 @@ def shapes_sum(*s: Shape) -> Shape:\n\"\"\"Implements sum(s)\"\"\"\nreturn tuple(safe_map(dim_sum, *s))\n+def dim_diff(d1: DimSize, d2: DimSize) -> DimSize:\n+ return _get_dim_handler(d1, d2).diff(d1, d2)\n+\n+def shape_diff(s1: Shape, s2: Shape) -> Shape:\n+ return tuple(safe_map(dim_diff, s1, s2))\n+\n+\ndef dim_stride(d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\nreturn _get_dim_handler(d, window_size, window_stride).stride(d, window_size, window_stride)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -572,10 +572,9 @@ class TensorFlowTracer(core.Tracer):\nelif not isinstance(aval_dim, shape_poly.DimVar):\nassert aval_dim == val_dim, f\"expected {self._aval.shape} == {val_shape}\" # type: ignore[attr-defined]\nelse:\n- # We have a TF value with known shape, and the abstract shape is a polynomial\n- # As an extra check, verify the value if the shape env are only constants\n+ # We have a TF value with known shape, and the abstract shape is a shape variable.\ntry:\n- aval_int = int(masking.eval_poly(aval_dim, _shape_env))\n+ aval_int = int(_eval_shape([aval_dim]))\nexcept TypeError:\ncontinue\nassert aval_int == val_dim, f\"expected {self._aval.shape} == {val_shape}. Found {aval_int} != {val_dim}.\" # type: ignore\n@@ -1757,7 +1756,10 @@ tf_impl_with_avals[lax.gather_p] = _gather\ndef _slice(operand, start_indices, limit_indices, strides):\nif strides is None:\nstrides = [1] * len(start_indices)\n- slices = tuple(map(slice, start_indices, limit_indices, strides))\n+ slices = tuple(map(slice,\n+ _eval_shape(start_indices),\n+ _eval_shape(limit_indices),\n+ _eval_shape(strides)))\nreturn operand[slices]\ntf_impl[lax.slice_p] = _slice\n@@ -1774,9 +1776,9 @@ def _dynamic_slice(operand, *start_indices, slice_sizes):\nif not _enable_xla:\nraise _xla_path_disabled_error(\"dynamic_slice\")\nres = tfxla.dynamic_slice(operand, tf.stack(start_indices),\n- size_indices=slice_sizes)\n+ size_indices=_eval_shape(slice_sizes))\n# TODO: implement shape inference for XlaDynamicSlice\n- res.set_shape(tuple(slice_sizes))\n+ res.set_shape(tuple(map(_poly_dim_to_tf_dim, slice_sizes)))\nreturn res\ntf_impl[lax.dynamic_slice_p] = _dynamic_slice\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -126,6 +126,12 @@ class DimensionHandlerVar(core.DimensionHandler):\nraise TypeError(f\"Adding non-zero to shape variables is not supported {' + '.join(map(str, d))}\")\nreturn d_vars[0]\n+ def diff(self, d1: DimSize, d2: DimSize) -> DimSize:\n+ if self.symbolic_equal(d1, d2):\n+ return 0\n+ if d2 in {0}:\n+ return d1\n+ raise TypeError(f\"Subtracting shape variables is not supported ({d1} - {d2})\")\ncore._SPECIAL_DIMENSION_HANDLERS[DimVar] = DimensionHandlerVar()\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": "@@ -633,6 +633,37 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x, x, x), f_tf(x, x, x))\ndef test_conv_general_dilated(self):\n+ batch_size = 7\n+ lhs_shape = (batch_size, 3, 9, 10) # 2 spatial dimensions (9, 10)\n+ rhs_shape = (3, 3, 4, 5)\n+ window_strides = (2, 3)\n+ padding = ((0, 0), (0, 0))\n+ lhs_dilation = (1, 1)\n+ rhs_dilation = (1, 2)\n+ dimension_numbers = ('NCHW','OIHW','NCHW')\n+ feature_group_count = 1\n+ batch_group_count = 1\n+ precision = None\n+\n+ lhs = np.ones(lhs_shape, dtype=np.float32)\n+ rhs = np.ones(rhs_shape, dtype=np.float32)\n+\n+ def f_jax(lhs, rhs):\n+ return lax.conv_general_dilated(lhs, rhs,\n+ window_strides, padding, lhs_dilation, rhs_dilation,\n+ dimension_numbers, feature_group_count,\n+ batch_group_count, precision)\n+\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec(lhs_shape),\n+ tf.TensorSpec(rhs_shape)],\n+ polymorphic_shapes=[\"b, _, _, _\", \"_, _, _, _\"],\n+ expected_output_signature=tf.TensorSpec([None, 3, 3, 1]))\n+ self.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n+\n+\n+ def test_conv_general_dilated_vmap(self):\nlhs_shape = (2, 3, 9, 10)\nrhs_shape = (3, 3, 4, 5)\nwindow_strides = (2, 3)\n@@ -679,6 +710,21 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 8, 9]))\nself.assertAllClose(f_jax(x), f_tf(x))\n+ def test_dynamic_slice(self):\n+\n+ def f_jax(x):\n+ return lax.dynamic_slice(x, (0, 1,), (x.shape[0], 2,))\n+ batch_size = 7\n+ x = np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :4]\n+\n+ res = f_jax(x)\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec((None, 4))],\n+ polymorphic_shapes=[\"b, _\"],\n+ expected_output_signature=tf.TensorSpec([None, 2]))\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\ndef test_squeeze(self):\ndef f_jax(x):\nreturn jnp.squeeze(x, axis=1)\n" } ]
Python
Apache License 2.0
google/jax
Add some support for convolutions
260,411
05.04.2021 10:13:02
-10,800
3ae73a91a4c7e4b219a878fcb2a34cb4d7a14858
Improve harness selection for shape_poly_test
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1943,7 +1943,6 @@ def _sort(*operands: TfVal, dimension: int, is_stable: bool,\nif not _enable_xla:\nraise _xla_path_disabled_error(\"sort\")\nassert 1 <= num_keys <= len(operands)\n- assert all([operands[0].shape == op.shape for op in operands[1:]])\nassert 0 <= dimension < len(\noperands[0].shape\n), f\"Invalid {dimension} for ndim {len(operands[0].shape)}\"\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": "@@ -33,6 +33,7 @@ import numpy as np\nfrom jax.experimental.jax2tf.tests import tf_test_util\n+from jax.experimental.jax2tf.tests.jax2tf_limitations import Jax2TfLimitation\nimport tensorflow as tf # type: ignore[import]\nimport unittest\n@@ -472,10 +473,18 @@ class ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\ndef _all_harnesses() -> Sequence[primitive_harness.Harness]:\n\"\"\"For each harness group, pick a single dtype.\"\"\"\nall_h = primitive_harness.all_harnesses\n- # Index by group; value is a harness\n+\n+ # Index by group\nharness_groups: Dict[str, Sequence[primitive_harness.Harness]] = collections.defaultdict(list)\n+ device = jtu.device_under_test()\n+\n+\nfor h in all_h:\n- if not h.filter(device_under_test=jtu.device_under_test(), include_jax_unimpl=False):\n+ # Drop the the JAX limitations\n+ if not h.filter(device_under_test=device, include_jax_unimpl=False):\n+ continue\n+ # And the jax2tf limitations\n+ if _get_jax2tf_limitations(device, h):\ncontinue\nharness_groups[h.group_name].append(h)\n@@ -489,6 +498,16 @@ def _all_harnesses() -> Sequence[primitive_harness.Harness]:\nreturn res\n+def _get_jax2tf_limitations(device, h: primitive_harness.Harness) -> Sequence[Jax2TfLimitation]:\n+ # And the jax2tf limitations\n+ def applicable_jax2tf_limitation(l: Jax2TfLimitation) -> bool:\n+ return (l.filter(device=device,\n+ dtype=h.dtype,\n+ mode=\"graph\") and l.expect_tf_error)\n+ limitations = Jax2TfLimitation.limitations_for_harness(h)\n+ return tuple(filter(applicable_jax2tf_limitation, limitations))\n+\n+\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n@@ -527,6 +546,9 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ninput_signature=func_jax_vmap_input_signature,\npolymorphic_shapes=func_jax_vmap_polymorphic_shapes,\nexpected_output_signature=func_jax_vmap_output_signature)\n+\n+ limitations = _get_jax2tf_limitations(jtu.device_under_test(), harness)\n+ if any([l.custom_assert or l.skip_comparison for l in limitations]):\nself.assertAllClose(res_jax_vmap, f_tf(*batched_args))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "new_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "diff": "@@ -27,6 +27,7 @@ from jax import tree_util\nfrom jax.config import config\nfrom jax.experimental import jax2tf\nfrom jax.interpreters import masking\n+from jax._src import util\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -255,11 +256,17 @@ class JaxToTfTestCase(jtu.JaxTestCase):\ninput_signature=input_signature)\nconcrete_f_tf = f_tf.get_concrete_function(*input_signature)\nif expected_output_signature:\n+ # Strangely, output_shapes can be a single shape for a function with a\n+ # single result, or a list/tuple of shapes.\nconcrete_output_tf_shape = concrete_f_tf.output_shapes\n- assert not isinstance(concrete_output_tf_shape, tuple) # A single result\n- self.assertEqual(\n- tuple(expected_output_signature.shape),\n- tuple(concrete_output_tf_shape))\n+ if not isinstance(concrete_output_tf_shape, (tuple, list)): # Single result\n+ assert not isinstance(expected_output_signature, (tuple, list))\n+ expected_output_signature = [expected_output_signature]\n+ concrete_output_tf_shape = [concrete_output_tf_shape]\n+\n+ for expected, found in util.safe_zip(expected_output_signature,\n+ concrete_output_tf_shape):\n+ self.assertEqual(tuple(expected.shape), tuple(found))\nreturn f_tf\ndef MakeInputSignature(self, *polymorphic_shapes):\n" } ]
Python
Apache License 2.0
google/jax
Improve harness selection for shape_poly_test
260,411
05.04.2021 11:08:46
-10,800
cbe5f54ccaf8a8242dba62446b298613979c9e60
Added support for lax.pad, and more error checking
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3487,15 +3487,22 @@ def _pad_dtype_rule(operand, padding_value, *, padding_config):\ndef _pad_shape_rule(operand, padding_value, *, padding_config):\ndel padding_value\n+ op_shape = np.shape(operand)\nif not len(padding_config) == np.ndim(operand):\nraise ValueError(\"length of padding_config must equal the number of axes \"\nf\"of operand, got padding_config {padding_config} \"\n- f\"for operand shape {np.shape(operand)}\")\n+ f\"for operand shape {op_shape}\")\nif not all(i >= 0 for _, _, i in padding_config):\nraise ValueError(\"interior padding in padding_config must be nonnegative, \"\nf\"got padding_config {padding_config}\")\n- return tuple(l + h + d + (_max(0, d - 1) * i if i > 0 else 0)\n- for (l, h, i), d in zip(padding_config, np.shape(operand)))\n+ result = tuple(core.dim_sum(l, h, core.dim_dilate(d, i + 1))\n+ for (l, h, i), d in zip(padding_config, op_shape))\n+ if not all(core.dim_greater_equal(d, 0) for d in result):\n+ msg = (f\"Dimension size after padding is not at least 0, \"\n+ f\"got result shape {result}, for padding_config {padding_config}\"\n+ f\" and operand shape {op_shape}\")\n+ raise ValueError(msg)\n+ return result\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\nif type(t) is ad_util.Zero:\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1260,8 +1260,8 @@ class DimensionHandler:\n\"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\nreturn 0 if d == 0 else 1 + dilation * (d - 1)\n- def add(self, *d: DimSize):\n- return sum(d)\n+ def sum(self, *ds: DimSize):\n+ return sum(ds)\ndef diff(self, d1: DimSize, d2: DimSize) -> DimSize:\nreturn d1 - d2\n@@ -1330,9 +1330,9 @@ def dim_dilate_shape(s: Shape, dilations: Sequence[int]) -> Shape:\n\"\"\"Implements `dim_dilate` for each dimension.\"\"\"\nreturn tuple(safe_map(dim_dilate, s, dilations))\n-def dim_sum(*d: DimSize) -> Shape:\n+def dim_sum(*ds: DimSize) -> Shape:\n\"\"\"sum(d)\"\"\"\n- return _get_dim_handler(*d).add(*d)\n+ return _get_dim_handler(*ds).sum(*ds)\ndef shapes_sum(*s: Shape) -> Shape:\n\"\"\"Implements sum(s)\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1354,6 +1354,8 @@ def _pad(operand, padding_value, *, padding_config,\nif not _enable_xla:\nraise _xla_path_disabled_error(\"pad\")\nout = tfxla.pad(operand, padding_value, low, high, interior)\n+ # TODO(b/184499027): improve shape inference for XlaPad\n+ out.set_shape(_aval_to_tf_shape(_out_aval))\nreturn out\ntf_impl_with_avals[lax.pad_p] = _pad\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -118,12 +118,12 @@ class DimensionHandlerVar(core.DimensionHandler):\nraise TypeError(f\"Striding is not supported for shape variables (window_size = {window_size}, stride = {window_stride}\")\nreturn d\n- def add(self, *d: DimSize):\n- d_ints, d_vars = _split_shape_ints(d)\n+ def sum(self, *ds: DimSize):\n+ d_ints, d_vars = _split_shape_ints(ds)\nif len(d_vars) != 1:\n- raise TypeError(f\"Adding shape variables is not supported ({' + '.join(map(str, d))})\")\n+ raise TypeError(f\"Adding shape variables is not supported ({' + '.join(map(str, ds))})\")\nif sum(d_ints) != 0:\n- raise TypeError(f\"Adding non-zero to shape variables is not supported {' + '.join(map(str, d))}\")\n+ raise TypeError(f\"Adding non-zero to shape variables is not supported {' + '.join(map(str, ds))}\")\nreturn d_vars[0]\ndef diff(self, d1: DimSize, d2: DimSize) -> DimSize:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -551,79 +551,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nif any([l.custom_assert or l.skip_comparison for l in limitations]):\nself.assertAllClose(res_jax_vmap, f_tf(*batched_args))\n-\n- def test_matmul(self):\n- def f_jax(x, y):\n- return jnp.matmul(x, y)\n-\n- self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None, 8, 4]), tf.TensorSpec([None, 4, None])],\n- polymorphic_shapes=[\"(batch, _, 4)\", \"(batch, 4, w)\"],\n- expected_output_signature=tf.TensorSpec([None, 8, None]))\n-\n- def test_reshape(self):\n-\n- self.CheckShapePolymorphism(\n- lambda x: x.reshape([x.shape[0], -1]),\n- input_signature=[tf.TensorSpec([None, 2, 3])],\n- polymorphic_shapes=[\"(batch, _, _)\"],\n- expected_output_signature=tf.TensorSpec([None, 6]))\n-\n- self.CheckShapePolymorphism(\n- lambda x: x.reshape([x.shape[0], -1, x.shape[3], x.shape[2]]),\n- input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n- polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n- expected_output_signature=tf.TensorSpec([None, 6, None, None]))\n-\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"Shapes (batch, 2, batch, height, 3) and (batch, -1, batch) must have the same set of shape variables\")):\n- self.CheckShapePolymorphism(\n- lambda x: x.reshape([x.shape[0], -1, x.shape[2]]),\n- input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n- polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n- expected_output_signature=tf.TensorSpec([None, 6, None]))\n-\n- with self.assertRaisesRegex(ValueError,\n- re.escape(\"Cannot divide evenly the sizes of shapes (2, 4) and (-1, 3)\")):\n- self.CheckShapePolymorphism(\n- lambda x: x.reshape([x.shape[0], -1, 3]),\n- input_signature=[tf.TensorSpec([None, 2, 4])],\n- polymorphic_shapes=[\"(batch, _, _)\"],\n- expected_output_signature=tf.TensorSpec([None, 1]))\n-\n- def test_reshape_compiled(self):\n- # raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n- # We compile the result of conversion for two shapes, hence we need to\n- # involve the TF compiler twice, but we trace only once with shape polymorphism\n- traced = False\n- def f_jax(x):\n- nonlocal traced\n- traced = True\n- y = jnp.sin(x)\n- return y.reshape([x.shape[0], -1])\n-\n- x = np.ones((4, 2, 3), dtype=np.float32)\n- res_jax = f_jax(x)\n-\n- traced = False\n- # If we get_concrete_function we trace once\n- f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, _, _)\"]),\n- autograph=False,\n- jit_compile=True).get_concrete_function(tf.TensorSpec([None, 2, 3], tf.float32))\n- self.assertTrue(traced)\n- traced = False\n- self.assertAllClose(res_jax, f_tf(x))\n- self.assertFalse(traced) # We are not tracing again\n-\n- x = np.ones((6, 2, 3), dtype=np.float32)\n- res_jax = f_jax(x)\n- traced = False\n-\n- self.assertAllClose(res_jax, f_tf(x))\n- self.assertFalse(traced) # We are not tracing again\n-\n-\ndef test_add_with_broadcast(self):\ndef f_jax(x, y):\nreturn jnp.add(x, y)\n@@ -639,6 +566,33 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x, y), f_tf(x, y))\n+ def test_broadcast(self):\n+ def f_jax(x):\n+ return jnp.broadcast_to(x, [x.shape[0], x.shape[0], x.shape[1]])\n+\n+ x = np.arange(12.).reshape((3, 4))\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 4], dtype=x.dtype)],\n+ polymorphic_shapes=[(\"batch, _\")],\n+ expected_output_signature=tf.TensorSpec([None, None, 4]))\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\n+ def test_ones(self):\n+ def f_jax(x):\n+ return jnp.ones(x.shape, dtype=x.dtype)\n+\n+ x_shape = (5, 6, 4)\n+ x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape)\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, None, 4], dtype=x.dtype)],\n+ polymorphic_shapes=[(\"width, height, _\")],\n+ expected_output_signature=tf.TensorSpec([None, None, 4]))\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\ndef test_clamp(self):\n@jax.vmap\ndef f_jax(mi, x, ma):\n@@ -747,70 +701,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 2]))\nself.assertAllClose(f_jax(x), f_tf(x))\n- def test_squeeze(self):\n- def f_jax(x):\n- return jnp.squeeze(x, axis=1)\n- x = np.ones((4, 1))\n- res_jax = f_jax(x)\n-\n- # Trace with a known dimension to squeeze\n- f_tf = self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None, 1], dtype=x.dtype)],\n- polymorphic_shapes=[\"(b, _)\"],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- self.assertAllClose(res_jax, f_tf(x))\n-\n- with self.assertRaisesRegex(\n- shape_poly.InconclusiveDimensionOperation,\n- re.escape(\"Shape variable comparison b2 == 1 is inconclusive\")):\n- # Trace with unknown dimension to squeeze\n- self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None, None])],\n- polymorphic_shapes=[\"(b1, b2)\"],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- def test_broadcast(self):\n- def f_jax(x):\n- return jnp.broadcast_to(x, [x.shape[0], x.shape[0], x.shape[1]])\n-\n- x = np.arange(12.).reshape((3, 4))\n- f_tf = self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None, 4], dtype=x.dtype)],\n- polymorphic_shapes=[(\"batch, _\")],\n- expected_output_signature=tf.TensorSpec([None, None, 4]))\n-\n- self.assertAllClose(f_jax(x), f_tf(x))\n-\n- def test_ones(self):\n- def f_jax(x):\n- return jnp.ones(x.shape, dtype=x.dtype)\n-\n- x_shape = (5, 6, 4)\n- x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape)\n- f_tf = self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None, None, 4], dtype=x.dtype)],\n- polymorphic_shapes=[(\"width, height, _\")],\n- expected_output_signature=tf.TensorSpec([None, None, 4]))\n-\n- self.assertAllClose(f_jax(x), f_tf(x))\n-\n- def test_iota(self):\n- def f_jax(x):\n- x + lax.iota(np.float32, x.shape[0])\n-\n- x = np.arange(12.)\n- f_tf = self.CheckShapePolymorphism(\n- f_jax,\n- input_signature=[tf.TensorSpec([None], dtype=x.dtype)],\n- polymorphic_shapes=[\"d\"],\n- expected_output_signature=None)\n-\n- self.assertAllClose(f_jax(x), f_tf(x))\ndef test_gather(self):\ndef f(a, i):\n@@ -852,6 +742,129 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f(x, i), f_tf(x, i))\n+ def test_iota(self):\n+ def f_jax(x):\n+ x + lax.iota(np.float32, x.shape[0])\n+\n+ x = np.arange(12.)\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None], dtype=x.dtype)],\n+ polymorphic_shapes=[\"d\"],\n+ expected_output_signature=None)\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\n+ def test_matmul(self):\n+ def f_jax(x, y):\n+ return jnp.matmul(x, y)\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 8, 4]), tf.TensorSpec([None, 4, None])],\n+ polymorphic_shapes=[\"(batch, _, 4)\", \"(batch, 4, w)\"],\n+ expected_output_signature=tf.TensorSpec([None, 8, None]))\n+\n+ def test_pad(self):\n+ def f_jax(x):\n+ return lax.pad(x, 5., ((0, 0, 0), (0, 0, 0), (1, 1, 1)))\n+\n+ batch_size = 7\n+ x = np.ones((batch_size,) + (2, 3))\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 2, 3])],\n+ polymorphic_shapes=[\"(batch, _, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 2, 7]))\n+\n+ def test_reshape(self):\n+\n+ self.CheckShapePolymorphism(\n+ lambda x: x.reshape([x.shape[0], -1]),\n+ input_signature=[tf.TensorSpec([None, 2, 3])],\n+ polymorphic_shapes=[\"(batch, _, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 6]))\n+\n+ self.CheckShapePolymorphism(\n+ lambda x: x.reshape([x.shape[0], -1, x.shape[3], x.shape[2]]),\n+ input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n+ polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n+ expected_output_signature=tf.TensorSpec([None, 6, None, None]))\n+\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"Shapes (batch, 2, batch, height, 3) and (batch, -1, batch) must have the same set of shape variables\")):\n+ self.CheckShapePolymorphism(\n+ lambda x: x.reshape([x.shape[0], -1, x.shape[2]]),\n+ input_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n+ polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n+ expected_output_signature=tf.TensorSpec([None, 6, None]))\n+\n+ with self.assertRaisesRegex(ValueError,\n+ re.escape(\"Cannot divide evenly the sizes of shapes (2, 4) and (-1, 3)\")):\n+ self.CheckShapePolymorphism(\n+ lambda x: x.reshape([x.shape[0], -1, 3]),\n+ input_signature=[tf.TensorSpec([None, 2, 4])],\n+ polymorphic_shapes=[\"(batch, _, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 1]))\n+\n+ def test_reshape_compiled(self):\n+ # raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n+ # We compile the result of conversion for two shapes, hence we need to\n+ # involve the TF compiler twice, but we trace only once with shape polymorphism\n+ traced = False\n+ def f_jax(x):\n+ nonlocal traced\n+ traced = True\n+ y = jnp.sin(x)\n+ return y.reshape([x.shape[0], -1])\n+\n+ x = np.ones((4, 2, 3), dtype=np.float32)\n+ res_jax = f_jax(x)\n+\n+ traced = False\n+ # If we get_concrete_function we trace once\n+ f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, _, _)\"]),\n+ autograph=False,\n+ jit_compile=True).get_concrete_function(tf.TensorSpec([None, 2, 3], tf.float32))\n+ self.assertTrue(traced)\n+ traced = False\n+ self.assertAllClose(res_jax, f_tf(x))\n+ self.assertFalse(traced) # We are not tracing again\n+\n+ x = np.ones((6, 2, 3), dtype=np.float32)\n+ res_jax = f_jax(x)\n+ traced = False\n+\n+ self.assertAllClose(res_jax, f_tf(x))\n+ self.assertFalse(traced) # We are not tracing again\n+\n+\n+ def test_squeeze(self):\n+ def f_jax(x):\n+ return jnp.squeeze(x, axis=1)\n+ x = np.ones((4, 1))\n+ res_jax = f_jax(x)\n+\n+ # Trace with a known dimension to squeeze\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 1], dtype=x.dtype)],\n+ polymorphic_shapes=[\"(b, _)\"],\n+ expected_output_signature=tf.TensorSpec([None]))\n+\n+ self.assertAllClose(res_jax, f_tf(x))\n+\n+ with self.assertRaisesRegex(\n+ shape_poly.InconclusiveDimensionOperation,\n+ re.escape(\"Shape variable comparison b2 == 1 is inconclusive\")):\n+ # Trace with unknown dimension to squeeze\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, None])],\n+ polymorphic_shapes=[\"(b1, b2)\"],\n+ expected_output_signature=tf.TensorSpec([None]))\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -1277,8 +1277,12 @@ class LaxTest(jtu.JaxTestCase):\ndef testPadErrors(self):\nwith self.assertRaisesRegex(ValueError, \"padding_config\"):\nlax.pad(np.zeros(2), 0., [(0, 1, 0), (0, 1, 0)])\n- with self.assertRaisesRegex(ValueError, \"padding_config\"):\n+ with self.assertRaisesRegex(ValueError, \"interior padding in padding_config must be nonnegative\"):\nlax.pad(np.zeros(2), 0., [(0, 1, -1)])\n+ with self.assertRaisesRegex(ValueError, \"Dimension size after padding is not at least 0\"):\n+ lax.pad(np.zeros(2), 0., [(-3, 0, 0)])\n+ with self.assertRaisesRegex(ValueError, \"Dimension size after padding is not at least 0\"):\n+ lax.pad(np.zeros(2), 0., [(-4, 0, 1)])\ndef testReverse(self):\nrev = api.jit(lambda operand: lax.rev(operand, dimensions))\n" } ]
Python
Apache License 2.0
google/jax
Added support for lax.pad, and more error checking
260,411
05.04.2021 15:00:15
-10,800
99d5f09b29dfbe7da8ea87b90274746a7ec22677
Fix select and eigh
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -3812,7 +3812,7 @@ def _select_batch_rule(batched_args, batch_dims, **unused_kwargs):\nreturn select(pred, on_true, on_false), ot_bdim\npred = batching.bdim_at_front(pred, pred_bdim, size) if np.shape(pred) else pred\n- if not np.shape(on_true) == np.shape(on_false) == ():\n+ if not () == np.shape(on_true) == np.shape(on_false):\non_true = batching.bdim_at_front(on_true, ot_bdim, size)\non_false = batching.bdim_at_front(on_false, of_bdim, size)\nassert np.shape(on_true) == np.shape(on_false)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -437,7 +437,8 @@ _shape_env = {} # type: _ShapeEnv\ndef _eval_shape(shape: Sequence[shape_poly.DimSize]) -> Sequence[TfVal]:\nassert all(map(lambda x: x is not None, shape)), (\nf\"Argument shape should be a valid JAX shape but got {shape}\")\n- return tuple(d if type(d) is int else _shape_env[d] for d in shape)\n+ return tuple(_shape_env[d] if type(d) is shape_poly.DimVar else d\n+ for d in shape)\ndef shape_as_value(x):\n\"\"\"Injects the shape of `x` as an array value.\n@@ -2058,20 +2059,20 @@ def _eig(operand: TfVal, compute_left_eigenvectors: bool,\ntf_impl[lax_linalg.eig_p] = _eig\n-def _eigh(operand: TfVal, lower: bool):\n+def _eigh(operand: TfVal, lower: bool, _in_avals, _out_aval):\nif operand.shape[-1] == 0:\n- v, w = operand, tf.reshape(operand, operand.shape[:-1])\n+ v, w = operand, tf.reshape(operand, _eval_shape(_in_avals[0].shape[:-1]))\nelse:\nif not lower:\noperand = tf.linalg.adjoint(operand)\nw, v = tf.linalg.eigh(operand)\n- cast_type = { tf.complex64: tf.float32\n- , tf.complex128: tf.float64 }.get(operand.dtype)\n+ cast_type = { tf.complex64: tf.float32,\n+ tf.complex128: tf.float64 }.get(operand.dtype)\nif cast_type is not None:\nw = tf.cast(w, cast_type)\nreturn v, w\n-tf_impl[lax_linalg.eigh_p] = _eigh\n+tf_impl_with_avals[lax_linalg.eigh_p] = _eigh\ndef _lu(operand: TfVal, _in_avals, _out_aval):\nreturn _convert_jax_impl(lax_linalg._lu_python)(operand, _in_avals=_in_avals,\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": "@@ -221,7 +221,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndef test_with_custom_vjp(self):\n\"\"\"Shape-polymorphic custom VJP.\"\"\"\n- raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n@jax.custom_vjp\ndef f(x):\n# x: [b1, b2, d1, d2] (a batch of matrices)\n@@ -312,7 +311,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual((None, 3, 4), tuple(tf_grad.output_shapes[1][\"grad\"]))\ndef test_cond(self):\n- raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n# Test the primitive under conditional\ndef f(x, y):\n# x: f32[B, H], y : f32[H]\n@@ -327,7 +325,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndef test_shape_error(self):\n\"\"\"Some of the examples from the README.\"\"\"\n- raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"add got incompatible shapes for broadcasting: (v,), (4,)\")):\nself.CheckShapePolymorphism(\n@@ -343,17 +340,11 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\njax2tf.convert(lambda x, y: x + y,\npolymorphic_shapes=[\"(v,)\", \"(4,)\"])(four_ones, four_ones)\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"dot_general requires contracting dimensions to have the same shape, got [4] and [v].\")):\n+ with self.assertRaisesRegex(shape_poly.InconclusiveDimensionOperation,\n+ re.escape(\"Shape variable comparison v == 4 is inconclusive\")):\njax2tf.convert(lambda x: jnp.matmul(x, x),\npolymorphic_shapes=[\"(v, 4)\"])(np.ones((4, 4)))\n- # TODO: this is an opportunity to improve the translation, should not error\n- with self.assertRaisesRegex(TypeError,\n- \"Only integers, .* tensors are valid indices, got 0\"):\n- jax2tf.convert(lambda x: jnp.split(x, 2),\n- polymorphic_shapes=[\"(2*v,)\"])(four_ones)\n-\ndef test_dim_vars(self):\nda, db = shape_poly.parse_spec(\"a, b\", (2, 3))\n@@ -509,6 +500,21 @@ def _get_jax2tf_limitations(device, h: primitive_harness.Harness) -> Sequence[Ja\nlimitations = Jax2TfLimitation.limitations_for_harness(h)\nreturn tuple(filter(applicable_jax2tf_limitation, limitations))\n+# We do not yet support shape polymorphism for vmap for all primitives\n+_VMAP_NOT_POLY_YET = {\n+ # In the random._gamma_impl we do reshape(-1, 2) for the keys\n+ \"random_gamma\",\n+\n+ # We do *= shapes in the batching rule for conv_general_dilated\n+ \"conv_general_dilated\",\n+\n+ # vmap(clamp) fails in JAX\n+ \"clamp\",\n+\n+ # Getting error: Can not squeeze dim[2], expected a dimension of 1, got 4 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[2]](MatMul)' with input shapes: [?,4,4]\n+ \"custom_linear_solve\",\n+\n+}\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n\"\"\"Tests for primitives that take shape values as parameters.\"\"\"\n@@ -520,6 +526,8 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\ndef test_prim_vmap(self, harness: primitive_harness.Harness):\n+ if harness.group_name in _VMAP_NOT_POLY_YET:\n+ raise unittest.SkipTest(f\"TODO: vmap({harness.group_name}) not yet supported\")\nfunc_jax = harness.dyn_fun\nargs = harness.dyn_args_maker(self.rng())\nif len(args) == 0:\n@@ -643,6 +651,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ndef test_conv_general_dilated_vmap(self):\n+ raise unittest.SkipTest(\"TODO: vmap(conv_general_dilated) not yet supported\")\nlhs_shape = (2, 3, 9, 10)\nrhs_shape = (3, 3, 4, 5)\nwindow_strides = (2, 3)\n@@ -778,11 +787,14 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ndef f_jax(x, y):\nreturn jnp.matmul(x, y)\n- self.CheckShapePolymorphism(\n+ f_tf = self.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec([None, 8, 4]), tf.TensorSpec([None, 4, None])],\npolymorphic_shapes=[\"(batch, _, 4)\", \"(batch, 4, w)\"],\nexpected_output_signature=tf.TensorSpec([None, 8, None]))\n+ x = np.ones((7, 8, 4))\n+ y = np.ones((7, 4, 5))\n+ self.assertAllClose(f_jax(x, y), f_tf(x, y))\ndef test_pad(self):\ndef f_jax(x):\n@@ -790,11 +802,30 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nbatch_size = 7\nx = np.ones((batch_size,) + (2, 3))\n- self.CheckShapePolymorphism(\n+ f_tf = self.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec([None, 2, 3])],\npolymorphic_shapes=[\"(batch, _, _)\"],\nexpected_output_signature=tf.TensorSpec([None, 2, 7]))\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\n+ def test_random_gamma(self):\n+ if \"random_gamma\" in _VMAP_NOT_POLY_YET:\n+ raise unittest.SkipTest(\"TODO: vmap(random_gamma) not yet supported\")\n+\n+ def f_jax(key, a):\n+ return jax.random.gamma(key, a)\n+ batch_size = 7\n+ key = np.ones((batch_size, 2), dtype=np.uint32)\n+ a = np.ones((batch_size, 3))\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 2], dtype=key.dtype),\n+ tf.TensorSpec([None, 3], dtype=a.dtype)],\n+ polymorphic_shapes=[\"(batch, _)\", \"(batch, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 3]))\n+ self.assertAllClose(f_jax(key, a), f_tf(key, a))\ndef test_reshape(self):\n@@ -827,7 +858,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 1]))\ndef test_reshape_compiled(self):\n- # raise unittest.SkipTest(\"Failing after fixing Poly unsoundness #4878\")\n# We compile the result of conversion for two shapes, hence we need to\n# involve the TF compiler twice, but we trace only once with shape polymorphism\ntraced = False\n@@ -879,6 +909,45 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x, upd), f_tf(x, upd))\n+ def test_select(self):\n+ def f_jax(x): # x.shape = (b, 3)\n+ return lax.select(x > 5., x, x)\n+ x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype)],\n+ polymorphic_shapes=[\"(b, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 3]))\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\n+ def test_select_vmap_0(self):\n+ @jax.vmap\n+ def f_jax(x): # x.shape = (3,)\n+ return lax.select(x > 5., x, x)\n+ x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype)],\n+ polymorphic_shapes=[\"(b, _)\"],\n+ expected_output_signature=tf.TensorSpec([None, 3]))\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\n+ def test_select_vmap_1(self):\n+ @functools.partial(jax.vmap, in_axes=(0, None))\n+ def f_jax(x, y): # x.shape = (3,)\n+ return lax.select(x > 5., x, y)\n+ x = np.arange(100, dtype=np.float32).reshape((10, 10))[:7, :3]\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, 3], dtype=x.dtype),\n+ tf.TensorSpec([3], dtype=x.dtype)],\n+ polymorphic_shapes=[\"(b, _)\", \"_\"],\n+ expected_output_signature=tf.TensorSpec([None, 3]))\n+\n+ self.assertAllClose(f_jax(x, x[0]), f_tf(x, x[0]))\n+\ndef test_slice(self):\ndef f_jax(x): # x.shape = (b, 3)\nreturn lax.slice(x, start_indices=(0, 1),\n" } ]
Python
Apache License 2.0
google/jax
Fix select and eigh
260,411
05.04.2021 15:56:30
-10,800
0386ee38ff83d70354b7aefc6548ef5eadc21ede
Add more tests for dot_general
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py", "diff": "@@ -505,6 +505,9 @@ _VMAP_NOT_POLY_YET = {\n# In the random._gamma_impl we do reshape(-1, 2) for the keys\n\"random_gamma\",\n+ # In linalg._lu_python we do reshape(-1, ...)\n+ \"lu\",\n+\n# We do *= shapes in the batching rule for conv_general_dilated\n\"conv_general_dilated\",\n@@ -513,7 +516,6 @@ _VMAP_NOT_POLY_YET = {\n# Getting error: Can not squeeze dim[2], expected a dimension of 1, got 4 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[2]](MatMul)' with input shapes: [?,4,4]\n\"custom_linear_solve\",\n-\n}\nclass ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n@@ -632,8 +634,8 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nbatch_group_count = 1\nprecision = None\n- lhs = np.ones(lhs_shape, dtype=np.float32)\n- rhs = np.ones(rhs_shape, dtype=np.float32)\n+ lhs = np.random.rand(*lhs_shape)\n+ rhs = np.random.rand(*rhs_shape)\ndef f_jax(lhs, rhs):\nreturn lax.conv_general_dilated(lhs, rhs,\n@@ -665,8 +667,8 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nbatch_size = 7\n- lhs = np.ones((batch_size,) + lhs_shape, dtype=np.float32)\n- rhs = np.ones((batch_size,) + rhs_shape, dtype=np.float32)\n+ lhs = np.random.rand(batch_size, *lhs_shape)\n+ rhs = np.random.rand(batch_size, *rhs_shape)\n@jax.vmap\ndef f_jax(lhs, rhs):\nreturn lax.conv_general_dilated(lhs, rhs,\n@@ -688,16 +690,33 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nreturn lax_control_flow.cummax(x, axis=0, reverse=False)\nbatch_size = 7\n- shape = (8, 9)\n- x = np.ones((batch_size,) + shape, dtype=np.float32)\n+ x = np.random.rand(batch_size, 8, 9)\nf_tf = self.CheckShapePolymorphism(\nf_jax,\n- input_signature=[tf.TensorSpec((None,) + shape)],\n+ input_signature=[tf.TensorSpec((None, 8, 9))],\npolymorphic_shapes=[\"b, _, _\"],\nexpected_output_signature=tf.TensorSpec([None, 8, 9]))\nself.assertAllClose(f_jax(x), f_tf(x))\n+ def test_dot_general(self):\n+ dimension_numbers = (((2,), (1,)), ((0,), (0,)))\n+ def f_jax(lhs, rhs): # lhs: [b, 4, 4], rhs: [b, 4]\n+ return lax.dot_general(lhs, rhs, dimension_numbers=dimension_numbers)\n+\n+ batch_size = 7\n+ lhs = np.random.rand(batch_size, 4, 4)\n+ rhs = np.random.rand(batch_size, 4)\n+\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec((None, 4, 4)),\n+ tf.TensorSpec((None, 4))],\n+ polymorphic_shapes=[\"b, _, _\", \"b, _\"],\n+ expected_output_signature=tf.TensorSpec([None, 4]))\n+ self.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n+\n+\ndef test_dynamic_slice(self):\ndef f_jax(x): # x:shape: (b, 4)\n@@ -705,7 +724,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nbatch_size = 7\nx = np.arange(100, dtype=np.float32).reshape((10, 10))[:batch_size, :4]\n- res = f_jax(x)\nf_tf = self.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec((None, 4))],\n@@ -729,7 +747,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 2]))\nself.assertAllClose(f_jax(x, idx), f_tf(x, idx))\n-\ndef test_gather(self):\ndef f(a, i):\nreturn jnp.take(a, i, axis=1)\n@@ -792,8 +809,8 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ninput_signature=[tf.TensorSpec([None, 8, 4]), tf.TensorSpec([None, 4, None])],\npolymorphic_shapes=[\"(batch, _, 4)\", \"(batch, 4, w)\"],\nexpected_output_signature=tf.TensorSpec([None, 8, None]))\n- x = np.ones((7, 8, 4))\n- y = np.ones((7, 4, 5))\n+ x = np.random.rand(7, 8, 4)\n+ y = np.random.rand(7, 4, 5)\nself.assertAllClose(f_jax(x, y), f_tf(x, y))\ndef test_pad(self):\n@@ -801,7 +818,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nreturn lax.pad(x, 5., ((0, 0, 0), (0, 0, 0), (1, 1, 1)))\nbatch_size = 7\n- x = np.ones((batch_size,) + (2, 3))\n+ x = np.random.rand(batch_size, 2, 3)\nf_tf = self.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec([None, 2, 3])],\n@@ -816,8 +833,8 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ndef f_jax(key, a):\nreturn jax.random.gamma(key, a)\nbatch_size = 7\n- key = np.ones((batch_size, 2), dtype=np.uint32)\n- a = np.ones((batch_size, 3))\n+ key = np.random.rand(batch_size, 2)\n+ a = np.random.rand(batch_size, 3)\nself.CheckShapePolymorphism(\nf_jax,\n@@ -867,20 +884,20 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ny = jnp.sin(x)\nreturn y.reshape([x.shape[0], -1])\n- x = np.ones((4, 2, 3), dtype=np.float32)\n+ x = np.random.rand(4, 2, 3)\nres_jax = f_jax(x)\ntraced = False\n# If we get_concrete_function we trace once\nf_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, _, _)\"]),\nautograph=False,\n- jit_compile=True).get_concrete_function(tf.TensorSpec([None, 2, 3], tf.float32))\n+ jit_compile=True).get_concrete_function(tf.TensorSpec([None, 2, 3], x.dtype))\nself.assertTrue(traced)\ntraced = False\nself.assertAllClose(res_jax, f_tf(x))\nself.assertFalse(traced) # We are not tracing again\n- x = np.ones((6, 2, 3), dtype=np.float32)\n+ x = np.random.rand(6, 2, 3)\nres_jax = f_jax(x)\ntraced = False\n@@ -964,7 +981,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ndef test_squeeze(self):\ndef f_jax(x):\nreturn jnp.squeeze(x, axis=1)\n- x = np.ones((4, 1))\n+ x = np.random.rand(4, 1)\nres_jax = f_jax(x)\n# Trace with a known dimension to squeeze\n" } ]
Python
Apache License 2.0
google/jax
Add more tests for dot_general
260,411
05.04.2021 19:23:30
-10,800
14737e365eb07b82fc9738ae5fcf49e316f1c995
Rewrite for python 3.8
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1314,7 +1314,8 @@ def _compute_newshape(a, newshape):\nexcept: iterable = False\nelse: iterable = True\nnewshape = core.canonicalize_shape(newshape if iterable else [newshape])\n- return tuple(d if d is not -1 else - core.divide_shape_sizes(np.shape(a), newshape)\n+ return tuple(- core.divide_shape_sizes(np.shape(a), newshape)\n+ if core.symbolic_equal_dim(d, -1) else d\nfor d in newshape)\n" } ]
Python
Apache License 2.0
google/jax
Rewrite for python 3.8
260,411
06.04.2021 11:43:06
-10,800
d9468c7513b60d35003f4032b2ab7449ad2242ed
Cleanup the API, and more documentation
[ { "change_type": "MODIFY", "old_path": "docs/developer.md", "new_path": "docs/developer.md", "diff": "@@ -129,7 +129,7 @@ sets up symbolic links from site-packages into the repository.\nTo run all the JAX tests, we recommend using `pytest-xdist`, which can run tests in\nparallel. First, install `pytest-xdist` and `pytest-benchmark` by running\n-`pip install pytest-xdist pytest-benchmark`.\n+`ip install -r build/test-requirements.txt`.\nThen, from the repository root directory run:\n```\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1316,25 +1316,25 @@ def symbolic_equal_one_of_dim(d1: DimSize, dlist: Sequence[DimSize]) -> bool:\ndef symbolic_equal_shape(s1: Shape, s2: Shape) -> bool:\n\"\"\"See DimensionHandler.symbolic_equal.\"\"\"\nreturn (len(s1) == len(s2) and\n- all(safe_map(symbolic_equal_dim, s1, s2)))\n+ all(map(symbolic_equal_dim, s1, s2)))\ndef greater_equal_dim(d1: DimSize, d2: DimSize) -> bool:\nreturn _get_dim_handler(d1, d2).greater_equal(d1, d2)\ndef greater_equal_shape(s1: Shape, s2: Shape) -> bool:\n- return all(safe_map(greater_equal_dim, s1, s2))\n+ return all(map(greater_equal_dim, s1, s2))\ndef sum_dim(*ds: DimSize) -> DimSize:\nreturn _get_dim_handler(*ds).sum(*ds)\ndef sum_shapes(*ss: Shape) -> Shape:\n- return tuple(safe_map(sum_dim, *ss))\n+ return tuple(map(sum_dim, *ss))\ndef diff_dim(d1: DimSize, d2: DimSize) -> DimSize:\nreturn _get_dim_handler(d1, d2).diff(d1, d2)\ndef diff_shape(s1: Shape, s2: Shape) -> Shape:\n- return tuple(safe_map(diff_dim, s1, s2))\n+ return tuple(map(diff_dim, s1, s2))\ndef divide_shape_sizes(s1: Shape, s2: Shape) -> int:\ns1 = s1 or (1,)\n@@ -1349,14 +1349,14 @@ def dilate_dim(d: DimSize, dilation: DimSize) -> DimSize:\nreturn _get_dim_handler(d, dilation).dilate(d, dilation)\ndef dilate_shape(s: Shape, dilations: Sequence[int]) -> Shape:\n- return tuple(safe_map(dilate_dim, s, dilations))\n+ return tuple(map(dilate_dim, s, dilations))\ndef stride_dim(d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\nreturn _get_dim_handler(d, window_size, window_stride).stride(d, window_size, window_stride)\ndef stride_shape(s: Shape, window_size: Shape, window_stride: Shape) -> Shape:\n\"\"\"(s - window_size) // window_stride + 1\"\"\"\n- return tuple(safe_map(stride_dim, s, window_size, window_stride))\n+ return tuple(map(stride_dim, s, window_size, window_stride))\ndef _canonicalize_dimension(dim: DimSize) -> DimSize:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/__init__.py", "new_path": "jax/experimental/jax2tf/__init__.py", "diff": "# limitations under the License.\n# flake8: noqa: F401\n-from .jax2tf import convert, shape_as_value, split_to_logical_devices\n+from .jax2tf import convert, shape_as_value, split_to_logical_devices, PolyShape\nfrom .call_tf import call_tf\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -34,7 +34,7 @@ from jax._src.lax import linalg as lax_linalg\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax._src.lax import fft as lax_fft\nimport jax._src.random\n-from . import shape_poly\n+from jax.experimental.jax2tf import shape_poly\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n@@ -48,6 +48,7 @@ from tensorflow.compiler.xla.experimental.xla_sharding import xla_sharding # ty\nfrom jax.lib import xla_client\n+PolyShape = shape_poly.PolyShape\n# The scope name need to be a valid TensorFlow name. See\n# https://github.com/tensorflow/tensorflow/blob/r2.3/tensorflow/core/framework/node_def_util.cc#L731\n@@ -119,8 +120,8 @@ def _xla_path_disabled_error(primitive_name: str) -> Exception:\n@functools.partial(api_util.api_hook, tag=\"jax2tf_convert\")\ndef convert(fun: Callable, *,\n- polymorphic_shapes_experimental: Optional[Sequence[Any]]=None,\n- in_shapes=None,\n+ polymorphic_shapes: Optional[Sequence[Any]]=None,\n+ in_shapes=None, # DEPRECATED\nwith_gradient=True, enable_xla=True) -> Callable:\n\"\"\"Transforms `fun` to be executed by TensorFlow.\n@@ -129,43 +130,45 @@ def convert(fun: Callable, *,\nArgs:\nfun: Function to be transformed. Its arguments and return value should be\n- JAX arrays, or (nested) standard Python containers (tuple/list/dict)\n- thereof.\n+ JAX arrays, or nested standard Python containers (tuple/list/dict)\n+ thereof (pytrees).\n+\n+ polymorphic_shapes: Specifies input shapes to be treated polymorphically\n+ during conversion.\n+\n+ .. warning::\n+ The shape-polymorphic conversion is an experimental feature. It is meant\n+ to be sound, but it is known to reject some JAX programs that are\n+ shape polymorphic. The details of this feature can change.\n+\n+ It should be a Python object with the same pytree structure as,\n+ or a prefix of, the tuple of arguments to the function,\n+ but with a shape specification corresponding to each argument.\n+ The default value is `None`, which is a shortcut for a tuple of `None`\n+ one for each argument, denoting that all shapes are monomorphic.\n+ See [how optional parameters are matched to arguments](https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).\n- polymorphic_shapes_experimental: an optional sequence of shape specifications,\n- one for each argument of the function to be converted. Default is `None`,\n- in which case the argument shape specifications are taken from the shapes\n- of the actual arguments.\n- A non-default `polymorphic_shapes` is used to specify shape variables for\n- some of the input dimensions, to specify that the conversion to TF must be\n- done for any possible non-zero values for the shape variables.\n+ A shape specification for an array argument\n+ should be an object `PolyShape(dim0, dim1, ..., dimn)`\n+ where each `dim` is a dimension specification: a positive integer denoting\n+ a monomorphic dimension of the given size,\n+ or a string denoting a dimension variable assumed to range over non-zero\n+ dimension sizes,\n+ or the special placeholder string \"_\" denoting a monomorphic dimension\n+ whose size is given by the actual argument.\n+ As a shortcut, an Ellipsis suffix in the\n+ list of dimension specifications stands for a list of \"_\" placeholders.\n+ For convenience, a shape specification can also be given as a string\n+ representation, e.g.: \"batch, ...\", \"batch, height, width, _\", possibly\n+ with surrounding parentheses: \"(batch, ...)\".\nThe conversion fails if it cannot ensure that the it would produce the same\n- sequence of TF ops for any non-zero values of shape variables. This feature\n- is experimental, and it may fail loudly even for code that is actually\n- shape polymorphic.\n+ sequence of TF ops for any non-zero values of the dimension variables.\n- If an argument is a pytree, then the\n- shape specification must be a matching pytree or `None`.\n- See [how optional parameters are matched to arguments](https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).\n- A shape specification should be a string, with comma-separated dimension\n- specifications, and optionally wrapped in parentheses. A dimension\n- specification is either a number, or the placeholder `_`, or a lowercase\n- word denoting a name for a dimension variable.\n- In presence of dimension variables, the conversion is done with a\n- shape abstraction that allows any non-zero concrete value for the variable.\n- Examples of shape specifications:\n- * `[None, \"(batch, 16)\"]`: no specification for the first argument (takes\n- the shape from the actual argument); the second argument is a 2D\n- array with the first dimension size set to a variable `batch` and the\n- second dimension 16.\n- * `[\"(batch, _)\", \"(batch,)\"]`: the leading dimensions of the two arguments\n- must match. The second dimension of the first argument is taken from the\n- actual argument shape.\nSee [the README](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#shape-polymorphic-conversion)\nfor more details.\n- in_shapes: DEPRECATED in favor of `polymorphic_shapes_experimental`.\n+ in_shapes: DEPRECATED in favor of `polymorphic_shapes`.\nwith_gradient: if set, will add a tf.custom_gradient to the converted\nfunction, by converting the ``jax.vjp(fun)``. Only first-order\n@@ -185,7 +188,6 @@ def convert(fun: Callable, *,\nglobal _enable_xla\n_enable_xla = enable_xla\napi._check_callable(fun)\n- polymorphic_shapes = polymorphic_shapes_experimental\ndef converted_fun(*args: TfVal) -> TfVal:\n# TODO: is there a better way to check if we are inside a transformation?\n@@ -214,13 +216,14 @@ def convert(fun: Callable, *,\nelse:\nif not isinstance(polymorphic_shapes, Sequence) or len(args) != len(polymorphic_shapes):\nmsg = (\"polymorphic_shapes must be a sequence with the same length as the argument list \"\n- f\"({len(args)}). Got polymorphic_shapes_experimental={polymorphic_shapes}.\")\n+ f\"({len(args)}). Got polymorphic_shapes={polymorphic_shapes}.\")\nraise TypeError(msg)\npolymorphic_shapes_ = tuple(polymorphic_shapes)\n# Expand the in_shapes to match the argument pytree\npolymorphic_shapes_flat = tuple(api_util.flatten_axes(\"jax2tf.convert polymorphic_shapes\",\n- in_tree.children()[0], polymorphic_shapes_))\n+ in_tree.children()[0],\n+ polymorphic_shapes_))\n# Construct the abstract values for the flat arguments, possibly based on\n# the input shapes and the in_shapes if given. May create new shape\n@@ -262,7 +265,7 @@ def convert(fun: Callable, *,\n# TODO: enable higher-order gradients\nwith tf.name_scope(\"jax2tf_vjp\"):\nin_cts = convert(fun_vjp_jax, with_gradient=False,\n- polymorphic_shapes_experimental=vjp_polymorphic_shapes)(args, out_cts)\n+ polymorphic_shapes=vjp_polymorphic_shapes)(args, out_cts)\nreturn in_cts\ntry:\n@@ -295,6 +298,7 @@ def convert(fun: Callable, *,\nreturn converted_fun\n+\n# Internals\n@@ -388,7 +392,7 @@ def _tfval_shape_dtype(val: TfVal) -> Tuple[Sequence[Optional[int]], DType]:\n# function arguments.\n_ShapeEnv = Dict[shape_poly.DimVar, TfVal]\ndef _args_to_avals_and_env(args: Sequence[TfVal],\n- polymorphic_shapes: Sequence[Optional[str]]) -> \\\n+ polymorphic_shapes: Sequence[Optional[Union[str, PolyShape]]]) -> \\\nTuple[Sequence[core.AbstractValue], _ShapeEnv]:\n\"\"\"Computes abstract values and a dimension environment for arguments.\n@@ -421,7 +425,7 @@ def _args_to_avals_and_env(args: Sequence[TfVal],\nreturn core.ShapedArray(aval_shape, dtype)\n- avals = tuple(map(input_aval, args, polymorphic_shapes))\n+ avals = tuple(map(input_aval, args, polymorphic_shapes)) # type: ignore\nreturn avals, shapeenv\n# A shape environment maps shape variables to TfVal.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -18,8 +18,7 @@ For usage instructions, read the jax2tf.convert docstring, and the\n\"\"\"\nimport collections\n-import string\n-from typing import Dict, List, Optional, Sequence, Set, Tuple, Union\n+from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Union\nfrom jax import core\n@@ -114,14 +113,20 @@ def _split_shape_ints(shape: Shape) -> Tuple[Sequence[int], Sequence[DimVar]]:\nreturn shape_ints, shape_vars\n-class ShapeSyntaxError(Exception): pass\n+class PolyShape(tuple):\n+ \"\"\"Tuple of polymorphic dimension specifications.\n-_identifiers = frozenset(string.ascii_lowercase)\n-def parse_spec(spec: Optional[str],\n+ See docstring of :func:`jax2tf.convert`.\n+ \"\"\"\n+ def __new__(cls, *dim_specs):\n+ return tuple.__new__(PolyShape, dim_specs)\n+\n+\n+def parse_spec(spec: Optional[Union[str, PolyShape]],\narg_shape: Sequence[Optional[int]]) -> Tuple[DimSize, ...]:\n\"\"\"Parse the shape polymorphic specification for one array argument.\nArgs:\n- spec: a shape polymorphic specification.\n+ spec: a shape polymorphic specification, either a string, or a PolyShape.\narg_shape: an actual shape, possibly containing unknown dimensions (None).\nThe placeholders `_` in the specification are replaced with the values from\n@@ -129,55 +134,75 @@ def parse_spec(spec: Optional[str],\nSee the README.md for usage.\n\"\"\"\n+ if spec is None:\n+ spec_tuple = (...,) # type: Tuple[Any,...]\n+ elif isinstance(spec, PolyShape):\n+ spec_tuple = tuple(spec)\n+ elif isinstance(spec, str):\n+ spec_ = spec.replace(\" \", \"\")\n+ if spec_[0] == \"(\":\n+ if spec_[-1] != \")\":\n+ raise ValueError(spec)\n+ spec_ = spec_[1:-1]\n+ spec_ = spec_.rstrip(\",\")\n+ if not spec_:\n+ spec_tuple = ()\n+ else:\n+ specs = spec_.split(',')\n+ def parse_dim(ds: str):\n+ if ds == \"...\":\n+ return ...\n+ elif ds.isdigit():\n+ return int(ds)\n+ elif ds == \"_\" or ds.isalnum():\n+ return ds\n+ else:\n+ raise ValueError(f\"PolyShape '{spec}' has invalid syntax\")\n+\n+ spec_tuple = tuple(map(parse_dim, specs))\n+ else:\n+ raise ValueError(f\"PolyShape '{spec}' must be either None, a string, or PolyShape.\")\n+\n+ ds_ellipses = tuple(ds for ds in spec_tuple if ds == ...)\n+ if ds_ellipses:\n+ if len(ds_ellipses) > 1 or spec_tuple[-1] != ...:\n+ raise ValueError(f\"PolyShape '{spec}' can contain Ellipsis only at the end.\")\n+ spec_tuple = spec_tuple[0:-1]\n+ if len(arg_shape) >= len(spec_tuple):\n+ spec_tuple = spec_tuple + (\"_\",) * (len(arg_shape) - len(spec_tuple))\n+\n+ if len(arg_shape) != len(spec_tuple):\n+ raise ValueError(f\"PolyShape '{spec}' must match the rank of arguments {arg_shape}.\")\n+\nshape_var_map: Dict[str, Set[int]] = collections.defaultdict(set)\n- def _parse_dim(dim_spec: str, dim_size: Optional[int]) -> Union[int, DimSize]:\n- if dim_spec == '_':\n+ def _process_dim(i: int, dim_spec):\n+ if not isinstance(dim_spec, (str, int)):\n+ raise ValueError(f\"PolyShape '{spec}' in axis {i} must contain only integers, strings, or Ellipsis.\")\n+ dim_size = arg_shape[i]\nif dim_size is None:\n- msg = (f\"polymorphic_shape '{spec}' has `_` placeholders for argument shape \"\n- f\"dimensions that are unknown: {arg_shape}\")\n+ if dim_spec == \"_\" or not isinstance(dim_spec, str):\n+ msg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\n+ f\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\n+ return DimVar(dim_spec)\n+ else: # dim_size is known\n+ if dim_spec == \"_\":\nreturn dim_size\n- elif dim_spec.isdigit():\n- spec_size = int(dim_spec)\n- if dim_size != spec_size:\n- if dim_size is None:\n- msg = (f\"polymorphic_shape '{spec}' must contain shape variables for argument shape \"\n- f\"dimensions that are unknown: {arg_shape}\")\n- else:\n- msg = (f\"polymorphic_shape '{spec}' does not match argument shape {arg_shape}\")\n+ if isinstance(dim_spec, int):\n+ if dim_spec != dim_size:\n+ msg = (f\"PolyShape '{spec}' in axis {i} must contain a constant or '_' \"\n+ f\"for known dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\n- return spec_size\n- elif dim_spec[0] in _identifiers:\n- if dim_size is not None:\n+ return dim_size\n+ # We have a dimension variable for a known dimension.\nshape_var_map[dim_spec].add(dim_size)\nreturn DimVar(dim_spec)\n- else:\n- raise ShapeSyntaxError(dim_spec)\n-\n- if not spec:\n- if any(d is None for d in arg_shape):\n- msg = (\"polymorphic_shape must be specified when the argument \"\n- f\"shape {arg_shape} is partially known.\")\n- raise ValueError(msg)\n- return tuple(arg_shape)\n-\n- if spec[0] == '(':\n- if spec[-1] != ')':\n- raise ShapeSyntaxError(spec)\n- spec_ = spec[1:-1]\n- else:\n- spec_ = spec\n- specs = spec_.replace(' ', '').strip(',').split(',')\n- if len(specs) != len(arg_shape):\n- msg = (f\"polymorphic_shape '{spec}' has different rank than argument \"\n- f\"shape {arg_shape}\")\n- raise ValueError(msg)\n- dims = tuple(map(_parse_dim, specs, arg_shape))\n+ dims = tuple([_process_dim(i, ds) for i, ds in enumerate(spec_tuple)])\nfor dim_var, dim_var_values in shape_var_map.items():\nif len(dim_var_values) != 1:\n- msg = (f\"polymorphic shape variable '{dim_var}' corresponds to multiple \"\n- f\"values ({sorted(dim_var_values)}), in polymorphic_shape '{spec}' and \"\n+ msg = (f\"PolyShape '{spec}' has dimension variable '{dim_var}' \"\n+ f\"corresponding to multiple values ({sorted(dim_var_values)}), for \"\nf\"argument shape {arg_shape}\")\nraise ValueError(msg)\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": "\"\"\"Tests for the jax2tf conversion for control-flow primitives.\"\"\"\nfrom absl.testing import absltest\n-from typing import Dict, Optional, Sequence\n+from typing import Dict, Optional, Sequence, Union\nimport collections\nimport functools\n@@ -44,6 +44,8 @@ config.parse_flags_with_absl()\n# Import after parsing flags\nfrom jax.experimental.jax2tf.tests import primitive_harness\n+PS = jax2tf.PolyShape\n+\nclass ShapePolyTest(tf_test_util.JaxToTfTestCase):\ndef setUp(self):\n@@ -61,18 +63,18 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(f_jax,\ninput_signature=[tf.TensorSpec([2, None])],\n- polymorphic_shapes=[\"(_, h)\"],\n+ polymorphic_shapes=[\"_, h\"],\nexpected_output_signature=tf.TensorSpec([2, None]))\nself.CheckShapePolymorphism(f_jax,\ninput_signature=[tf.TensorSpec([None, None])],\n- polymorphic_shapes=[\"(h, h)\"],\n+ polymorphic_shapes=[\"h, h\"],\nexpected_output_signature=tf.TensorSpec([None, None]))\ndef test_arg_avals(self):\n\"\"\"Test conversion of actual arguments to abstract values\"\"\"\ndef check_avals(*, args: Sequence[jax2tf.jax2tf.TfVal],\n- polymorphic_shapes: Sequence[Optional[str]],\n+ polymorphic_shapes: Sequence[Optional[Union[str, PS]]],\nexpected_avals: Sequence[core.ShapedArray]):\navals, shape_env = jax2tf.jax2tf._args_to_avals_and_env(args,\npolymorphic_shapes) # The function under test\n@@ -98,11 +100,11 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ncheck_avals(args=[tf_const((2, 3))],\npolymorphic_shapes=[None],\n- expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+ expected_avals=(shaped_array(\"2, 3,\", [2, 3]),))\ncheck_avals(args=[tf_var((2, 3))],\npolymorphic_shapes=[None],\n- expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+ expected_avals=(shaped_array(\"(2, 3)\", [2, 3]),))\ncheck_avals(args=[const((2, 3))],\npolymorphic_shapes=[\"(2, 3)\"],\n@@ -112,13 +114,17 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"(_, 3)\"],\nexpected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+ check_avals(args=[tf_const((2, 3))],\n+ polymorphic_shapes=[PS(\"_\", 3)],\n+ expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+\n# Partially known shapes for the arguments\ncheck_avals(args=[tf_var([None, 3], initializer_shape=(2, 3))],\n- polymorphic_shapes=[\"(b, 3)\"],\n+ polymorphic_shapes=[PS(\"b\", ...)],\nexpected_avals=(shaped_array(\"(b, 3)\", (2, 3)),))\ncheck_avals(args=[tf_var([None, None], initializer_shape=(2, 3))],\n- polymorphic_shapes=[(\"h, h\")],\n+ polymorphic_shapes=[\"h, h\"],\nexpected_avals=(shaped_array(\"(h, h)\", (2, 2)),))\ncheck_avals(args=[tf_var([2, None], initializer_shape=(2, 3))],\n@@ -130,66 +136,72 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nexpected_avals=(shaped_array(\"(c, b, a)\", (2, 3, 4)),),)\n# Some errors\n+ with self.assertRaisesRegex(\n+ ValueError, re.escape(\"PolyShape ')(' has invalid syntax\")):\n+ check_avals(args=[const((2, 3))],\n+ polymorphic_shapes=[\")(\"],\n+ expected_avals=None)\n+\n+ with self.assertRaisesRegex(ValueError,\n+ re.escape(\"PolyShape '..., 3' can contain Ellipsis only at the end.\")):\n+ check_avals(args=[const((2, 3))],\n+ polymorphic_shapes=[\"..., 3\"],\n+ expected_avals=None)\n+\n+ with self.assertRaisesRegex(ValueError,\n+ re.escape(\"PolyShape '2, 3, 4, ...' must match the rank of arguments (2, 3).\")):\n+ check_avals(args=[const((2, 3))],\n+ polymorphic_shapes=[\"2, 3, 4, ...\"],\n+ expected_avals=None)\n+\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"polymorphic_shape must be specified when the argument shape (2, None) is partially known\")):\n+ re.escape(\"PolyShape '(Ellipsis, 3)' can contain Ellipsis only at the end.\")):\n+ check_avals(args=[const((2, 3))],\n+ polymorphic_shapes=[PS(..., 3)],\n+ expected_avals=None)\n+\n+ with self.assertRaisesRegex(ValueError,\n+ re.escape(\"PolyShape 'None' in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\")):\ncheck_avals(args=[tf_var([2, None], initializer_shape=(2, 3))],\npolymorphic_shapes=[None],\nexpected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"polymorphic_shape '()' has different rank than argument shape (2, 3)\")):\n+ re.escape(\"PolyShape '()' must match the rank of arguments (2, 3)\")):\ncheck_avals(args=[const((2, 3))],\npolymorphic_shapes=[\"()\"],\nexpected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"polymorphic_shape '(_, _)' has `_` placeholders for argument shape dimensions that are unknown: (2, None)\")):\n+ re.escape(\"PolyShape '(_, _)' in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\")):\ncheck_avals(args=[tf_var([2, None], initializer_shape=(2, 3))],\npolymorphic_shapes=[\"(_, _)\"],\nexpected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"polymorphic_shape '(2, 13)' does not match argument shape (2, 3)\")):\n+ re.escape(\"PolyShape '(2, 13)' in axis 1 must contain a constant or '_' for known dimension in argument shape (2, 3)\")):\ncheck_avals(args=[const((2, 3))],\npolymorphic_shapes=[\"(2, 13)\"],\nexpected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"polymorphic_shape '(2, 3)' must contain shape variables for argument shape dimensions that are unknown: (2, None)\")):\n+ re.escape(\"PolyShape '(2, 3)' in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\")):\ncheck_avals(args=[tf_var([2, None], initializer_shape=(2, 3))],\npolymorphic_shapes=[\"(2, 3)\"],\nexpected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"polymorphic shape variable 'a' corresponds to multiple values ([2, 3]), in polymorphic_shape '(a, a)' and argument shape (2, 3)\")):\n+ re.escape(\"PolyShape '(a, a)' has dimension variable 'a' corresponding to multiple values ([2, 3]), for argument shape (2, 3)\")):\ncheck_avals(args=[tf_var([2, 3], initializer_shape=(2, 3))],\npolymorphic_shapes=[\"(a, a)\"],\nexpected_avals=None)\n- def test_bad_polymorphic_shapes(self):\n- def add2(x, y):\n- return x + y\n-\n- with self.assertRaisesRegex(shape_poly.ShapeSyntaxError, \"\"):\n- self.CheckShapePolymorphism(add2,\n- input_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n- polymorphic_shapes=[\") + (\", None],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- with self.assertRaisesRegex(TypeError,\n- re.escape(\"polymorphic_shapes must be a sequence with the same length as the argument list (2). \"\n- \"Got polymorphic_shapes_experimental=['(b, 4)']\")):\n- self.CheckShapePolymorphism(add2,\n- input_signature=[tf.TensorSpec([None]), tf.TensorSpec([None])],\n- polymorphic_shapes=[\"(b, 4)\"],\n- expected_output_signature=tf.TensorSpec([None]))\n-\ndef test_pytree(self):\n\"\"\"Arguments and polymorphic_shapes are pytrees.\"\"\"\n@@ -204,8 +216,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ninput_signature=[([tf.TensorSpec([None]), tf.TensorSpec([None])],\n[tf.TensorSpec([None])]),\ndict(a=tf.TensorSpec([None]), b=tf.TensorSpec([None]))],\n- polymorphic_shapes=[([\"(v,)\", \"(v,)\"], [(\"v,\")]),\n- dict(a=\"(v,)\", b=\"(v,)\")],\n+ polymorphic_shapes=[([\"v\", \"v\"], [(\"v\")]),\n+ dict(a=\"v\", b=\"v\")],\nexpected_output_signature=tf.TensorSpec([None]))\n# Now partial polymorphic_shapes; the parts of the polymorphic_shapes that are not specified\n@@ -322,7 +334,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ny = np.ones((3,))\nres_jax = f(x, y)\nself.assertAllClose(res_jax,\n- jax2tf.convert(f, polymorphic_shapes_experimental=[\"(b, h)\", \"h\"])(x, y))\n+ jax2tf.convert(f, polymorphic_shapes=[\"(b, h)\", \"h\"])(x, y))\ndef test_shape_error(self):\n\"\"\"Some of the examples from the README.\"\"\"\n@@ -339,12 +351,21 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(TypeError,\nre.escape(\"add got incompatible shapes for broadcasting: (v,), (4,)\")):\njax2tf.convert(lambda x, y: x + y,\n- polymorphic_shapes_experimental=[\"(v,)\", \"(4,)\"])(four_ones, four_ones)\n+ polymorphic_shapes=[\"(v,)\", \"(4,)\"])(four_ones, four_ones)\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\nre.escape(\"Shape variable comparison v == 4 is inconclusive\")):\njax2tf.convert(lambda x: jnp.matmul(x, x),\n- polymorphic_shapes_experimental=[\"(v, 4)\"])(np.ones((4, 4)))\n+ polymorphic_shapes=[\"(v, 4)\"])(np.ones((4, 4)))\n+\n+\n+ def test_parse_poly_spec(self):\n+ self.assertEqual((2, 3), shape_poly.parse_spec(None, (2, 3)))\n+ self.assertEqual((2, 3), shape_poly.parse_spec(\"2, 3\", (2, 3)))\n+ self.assertEqual((2, 3), shape_poly.parse_spec(\"2, _\", (2, 3)))\n+ self.assertEqual((2, 3), shape_poly.parse_spec(\"2, ...\", (2, 3)))\n+ self.assertEqual((2, 3), shape_poly.parse_spec(\"...\", (2, 3)))\n+ self.assertEqual((2, 3), shape_poly.parse_spec(\" ( 2 , 3 ) \", (2, 3)))\ndef test_dim_vars(self):\n@@ -432,9 +453,9 @@ class ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\nreturn jnp.sum(x, axis=0) * jax2tf.shape_as_value(x)[0]\nx = np.arange(3.)\n- self.assertAllClose(9., jax2tf.convert(f, polymorphic_shapes_experimental=[\"(b,)\"])(x))\n- self.assertAllClose(9., jax2tf.convert(jax.jit(f), polymorphic_shapes_experimental=[\"(b,)\"])(x))\n- self.assertAllClose(9., tf.function(jax2tf.convert(f, polymorphic_shapes_experimental=[\"(b,)\"]))(x))\n+ self.assertAllClose(9., jax2tf.convert(f, polymorphic_shapes=[\"(b,)\"])(x))\n+ self.assertAllClose(9., jax2tf.convert(jax.jit(f), polymorphic_shapes=[\"(b,)\"])(x))\n+ self.assertAllClose(9., tf.function(jax2tf.convert(f, polymorphic_shapes=[\"(b,)\"]))(x))\nres_primal, res_tangent = jax2tf.convert(\nlambda x, xt: jax.jvp(f, (x,), (xt,)),\n@@ -443,7 +464,7 @@ class ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(np.array([3., 3., 3.]),\njax2tf.convert(jax.grad(f),\n- polymorphic_shapes_experimental=[\"b\"])(x))\n+ polymorphic_shapes=[\"b\"])(x))\nxv = np.arange(24.).reshape((2, 3, 4))\nres_vmap = jax.vmap(f, in_axes=1)(xv)\n@@ -466,7 +487,7 @@ class ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\noperand=None)\nx = np.ones((2, 3, 4))\nself.assertAllClose(1., f(x))\n- self.assertAllClose(1., jax2tf.convert(f, polymorphic_shapes_experimental=[\"(a, b, 4)\"])(x))\n+ self.assertAllClose(1., jax2tf.convert(f, polymorphic_shapes=[\"(a, b, 4)\"])(x))\ndef test_mean0(self):\ndef f_jax(x):\n@@ -676,7 +697,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nf_jax,\ninput_signature=[tf.TensorSpec(lhs_shape),\ntf.TensorSpec(rhs_shape)],\n- polymorphic_shapes=[\"b, _, _, _\", \"_, _, _, _\"],\n+ polymorphic_shapes=[\"B, ...\", None],\nexpected_output_signature=tf.TensorSpec([None, 3, 3, 1]))\nself.assertAllClose(f_jax(lhs, rhs), f_tf(lhs, rhs))\n@@ -785,7 +806,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nf_tf = self.CheckShapePolymorphism(\nf,\ninput_signature=[tf.TensorSpec([None, 3, 4]), tf.TensorSpec([2], np.int32)],\n- polymorphic_shapes=[\"batch, _, _\", \"_\"],\n+ polymorphic_shapes=[\"(batch, _, _)\", \"(_)\"],\nexpected_output_signature=tf.TensorSpec([None, 2, 4]))\nself.assertAllClose(f(x, i), f_tf(x, i))\n@@ -877,13 +898,13 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1]),\ninput_signature=[tf.TensorSpec([None, 2, 3])],\n- polymorphic_shapes=[\"(batch, _, _)\"],\n+ polymorphic_shapes=[\"batch, _, _\"],\nexpected_output_signature=tf.TensorSpec([None, 6]))\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1, x.shape[3], x.shape[2]]),\ninput_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n- polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n+ polymorphic_shapes=[\"batch, 2, batch, height, 3\"],\nexpected_output_signature=tf.TensorSpec([None, 6, None, None]))\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n@@ -891,7 +912,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1, x.shape[2]]),\ninput_signature=[tf.TensorSpec([None, 2, None, None, 3])],\n- polymorphic_shapes=[\"(batch, 2, batch, height, 3)\"],\n+ polymorphic_shapes=[\"batch, 2, batch, height, 3\"],\nexpected_output_signature=tf.TensorSpec([None, 6, None]))\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n@@ -899,7 +920,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nlambda x: x.reshape([x.shape[0], -1, 3]),\ninput_signature=[tf.TensorSpec([None, 2, 4])],\n- polymorphic_shapes=[\"(batch, _, _)\"],\n+ polymorphic_shapes=[PS(\"batch\", ...)],\nexpected_output_signature=tf.TensorSpec([None, 1]))\ndef test_reshape_compiled(self):\n@@ -917,7 +938,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ntraced = False\n# If we get_concrete_function we trace once\n- f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes_experimental=[\"(b, _, _)\"]),\n+ f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes=[PS(\"b\", ...)]),\nautograph=False,\njit_compile=True).get_concrete_function(tf.TensorSpec([None, 2, 3], x.dtype))\nself.assertTrue(traced)\n@@ -1016,7 +1037,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nf_tf = self.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec([None, 1], dtype=x.dtype)],\n- polymorphic_shapes=[\"(b, _)\"],\n+ polymorphic_shapes=[PS(\"b\", ...)],\nexpected_output_signature=tf.TensorSpec([None]))\nself.assertAllClose(res_jax, f_tf(x))\n@@ -1028,7 +1049,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.CheckShapePolymorphism(\nf_jax,\ninput_signature=[tf.TensorSpec([None, None])],\n- polymorphic_shapes=[\"(b1, b2)\"],\n+ polymorphic_shapes=[PS(\"b1\", \"b2\")],\nexpected_output_signature=tf.TensorSpec([None]))\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "new_path": "jax/experimental/jax2tf/tests/tf_test_util.py", "diff": "@@ -251,7 +251,7 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nmust match the `input_signature`. (see jax2tf.convert).\n\"\"\"\nf_tf = tf.function(\n- jax2tf.convert(f_jax, polymorphic_shapes_experimental=polymorphic_shapes),\n+ jax2tf.convert(f_jax, polymorphic_shapes=polymorphic_shapes),\nautograph=False,\ninput_signature=input_signature)\nconcrete_f_tf = f_tf.get_concrete_function(*input_signature)\n" }, { "change_type": "MODIFY", "old_path": "pytest.ini", "new_path": "pytest.ini", "diff": "@@ -9,6 +9,8 @@ filterwarnings =\nignore:the imp module is deprecated in favour of importlib.*:DeprecationWarning\nignore:can't resolve package from __spec__ or __package__:ImportWarning\nignore:Using or importing the ABCs.*:DeprecationWarning\n+ # jax2tf tests due to mix of JAX and TF\n+ ignore:numpy.ufunc size changed\ndoctest_optionflags = NUMBER NORMALIZE_WHITESPACE\naddopts = --doctest-glob=\"*.rst\"\n" } ]
Python
Apache License 2.0
google/jax
Cleanup the API, and more documentation
260,631
08.04.2021 10:42:25
25,200
438b56c4830d09e1bdf95f4ab7dc12195560f417
Fix typo in rng_bit_generator comment.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -6183,7 +6183,7 @@ def rng_bit_generator(key,\n\"\"\"Stateless PRNG bit generator. Experimental and its use is discouraged.\nReturns uniformly distributed random bits with the specified shape and dtype\n- (what is requirted to be an integer type) using the platform specific\n+ (what is required to be an integer type) using the platform specific\ndefault algorithm or the one specified.\nIt provides direct acces to the RngBitGenerator primitive exposed by XLA\n" } ]
Python
Apache License 2.0
google/jax
Fix typo in rng_bit_generator comment. PiperOrigin-RevId: 367460802
260,303
08.04.2021 18:24:49
25,200
e3cb192e1d63c91b5a4e4fbd248accb37773e467
Make mesh thread-safe
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -149,7 +149,7 @@ def mesh(devices: np.ndarray, axis_names: Sequence[ResourceAxisName]):\nout_axes=['left', 'right', ...],\naxis_resources={'left': 'x', 'right': 'y'})(x, x.T)\n\"\"\"\n- old_env = thread_resources.env\n+ old_env = getattr(thread_resources, \"env\", None)\nthread_resources.env = ResourceEnv(Mesh(devices, axis_names))\ntry:\nyield\n" } ]
Python
Apache License 2.0
google/jax
Make mesh thread-safe
260,411
09.04.2021 11:10:32
-10,800
7667fc3be71e36ba779177fc0f889e014ebcfc87
[jax2tf] Added support for shape-polymorphic reductionsxs
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1975,7 +1975,7 @@ def _reduction(a, name, np_fun, op, init_val, has_identity=True,\naxis = core.concrete_or_error(None, axis, f\"axis argument to jnp.{name}().\")\nif initial is None and not has_identity:\n- if not size(a):\n+ if not _all(core.greater_equal_dim(d, 1) for d in np.shape(a)):\nraise ValueError(f\"zero-size array to reduction operation {name} which has no identity\")\nif where_ is not None:\nraise ValueError(f\"reduction operation {name} does not have an identity, so to use a \"\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": "\"\"\"Tests for the shape-polymorphic jax2tf conversion.\"\"\"\nfrom absl.testing import absltest\n+from absl.testing import parameterized\nfrom typing import Dict, Optional, Sequence, Union\nimport collections\n@@ -992,7 +993,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x), f_tf(x))\ndef test_random_gamma(self):\n- if \"random_gamma\" in _VMAP_NOT_POLY_YET:\n+ assert \"random_gamma\" in _VMAP_NOT_POLY_YET\nraise unittest.SkipTest(\"TODO: vmap(random_gamma) not yet supported\")\ndef f_jax(key, a):\n@@ -1012,6 +1013,24 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec([None, 3]))\nself.assertAllClose(f_jax(key, a), f_tf(key, a))\n+ @parameterized.named_parameters(\n+ jtu.cases_from_list(\n+ dict(testcase_name=f\"_{op.__name__}\", op=op)\n+ for op in [jnp.all, jnp.any, jnp.max, jnp.min, jnp.prod, jnp.sum]))\n+ def test_reduce(self, op=jnp.max):\n+ f_jax = lambda x: op(x, axis=-1, keepdims=True)\n+\n+ x = np.random.rand(7, 8)\n+ f_tf = self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[\n+ tf.TensorSpec([None, 8], dtype=x.dtype),\n+ ],\n+ polymorphic_shapes=[\"(batch, ...)\"],\n+ expected_output_signature=tf.TensorSpec([None, 1], dtype=x.dtype))\n+\n+ self.assertAllClose(f_jax(x), f_tf(x))\n+\ndef test_reshape(self):\nself.CheckShapePolymorphism(\n" }, { "change_type": "MODIFY", "old_path": "tests/masking_test.py", "new_path": "tests/masking_test.py", "diff": "@@ -742,7 +742,7 @@ class MaskingTest(jtu.JaxTestCase):\n'testcase_name': \"operator={}\".format(operator.__name__), 'operator': operator}\nfor operator in [jnp.sum, jnp.prod, jnp.max, jnp.min]]))\ndef test_reduce(self, operator):\n- self.check(operator, ['(m, n)'], '', {'m': 3, 'n': 4}, [(4, 5)], ['float_'],\n+ self.check(operator, ['(m+1, n+1)'], '', {'m': 3, 'n': 4}, [(4, 5)], ['float_'],\njtu.rand_default(self.rng()))\ndef test_output_shape_error(self):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added support for shape-polymorphic reductionsxs
260,411
09.04.2021 13:46:28
-10,800
8815425e369412dc71d6b888556d045caddd0f55
Cleanup of the dispatch to shape polymorphic dimension handlers
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1226,7 +1226,11 @@ class DimensionHandler:\nDimension sizes are normally integer constants, but can also be symbolic,\ne.g., masking.Poly or jax2tf.shape_poly.DimVar.\n- The base class works for integers only.\n+ The base class works for integers only. Subclasses are invoked when at\n+ least one of the operands has a type registered in _SPECIAL_DIMENSION_HANDLERS.\n+ In that case, all operands are guaranteed to be either the special dimension\n+ type, or Python integer scalars.\n+\nSubclasses should raise InconclusiveDimensionOperation if the result cannot\nbe computed in some contexts.\n\"\"\"\n@@ -1283,80 +1287,83 @@ class DimensionHandler:\n_dimension_handler_int = DimensionHandler()\n_SPECIAL_DIMENSION_HANDLERS: Dict[type, DimensionHandler] = {}\n-def _get_dim_handler(*dlist: DimSize) -> DimensionHandler:\n- \"\"\"Finds the handler that works for all dimension sizes.\n- At most one special dimension type is allowed. Non-special dimension\n- must be convertible to integers.\n+def _dim_handler_and_canonical(*dlist: DimSize) -> Tuple[DimensionHandler, Tuple[DimSize, ...]]:\n+ \"\"\"Finds the handler for the given dimensions; also returns the canonical dimensions.\n+\n+ A dimension is canonical if it is a Python integer scalar, or has a type\n+ registered in _SPECIAL_DIMENSION_HANDLERS.\n\"\"\"\nspecial_handlers = set()\n+ canonical = []\nfor d in dlist:\nhandler = _SPECIAL_DIMENSION_HANDLERS.get(type(d))\nif handler:\nspecial_handlers.add(handler)\n-\n- if special_handlers:\n- handler, *others = special_handlers\n- if others:\n- msg = (f\"Dimension size operation involves multiple non-int types {dlist}\")\n- raise TypeError(msg)\n- return handler\n+ canonical.append(d)\nelse:\n- return _dimension_handler_int\n+ try:\n+ canonical.append(operator.index(d))\n+ except TypeError:\n+ raise _invalid_shape_error(dlist)\n+\n+ if len(special_handlers) > 1:\n+ msg = (f\"Dimension size operation involves multiple special dimension types {dlist}\")\n+ raise ValueError(msg)\n+ return next(iter(special_handlers), _dimension_handler_int), tuple(canonical)\ndef symbolic_equal_dim(d1: DimSize, d2: DimSize) -> bool:\n- d1, d2 = canonicalize_shape((d1, d2))\n- return _get_dim_handler(d1, d2).symbolic_equal(d1, d2)\n+ handler, ds = _dim_handler_and_canonical(d1, d2)\n+ return handler.symbolic_equal(*ds)\ndef symbolic_equal_one_of_dim(d1: DimSize, dlist: Sequence[DimSize]) -> bool:\n- d1, *dlist = canonicalize_shape((d1, *dlist))\n- handler = _get_dim_handler(d1, *dlist)\n- return any([handler.symbolic_equal(d1, d2) for d2 in dlist])\n+ handler, ds = _dim_handler_and_canonical(d1, *dlist)\n+ return any([handler.symbolic_equal(ds[0], d) for d in ds[1:]])\ndef symbolic_equal_shape(s1: Shape, s2: Shape) -> bool:\n- \"\"\"See DimensionHandler.symbolic_equal.\"\"\"\nreturn (len(s1) == len(s2) and\nall(map(symbolic_equal_dim, s1, s2)))\ndef greater_equal_dim(d1: DimSize, d2: DimSize) -> bool:\n- d1, d2 = canonicalize_shape((d1, d2))\n- return _get_dim_handler(d1, d2).greater_equal(d1, d2)\n+ handler, ds = _dim_handler_and_canonical(d1, d2)\n+ return handler.greater_equal(*ds)\ndef greater_equal_shape(s1: Shape, s2: Shape) -> bool:\nreturn all(map(greater_equal_dim, s1, s2))\ndef sum_dim(*ds: DimSize) -> DimSize:\n- ds_tuple = canonicalize_shape(ds)\n- return _get_dim_handler(*ds_tuple).sum(*ds_tuple)\n+ handler, ds = _dim_handler_and_canonical(*ds)\n+ return handler.sum(*ds)\ndef sum_shapes(*ss: Shape) -> Shape:\nreturn tuple(map(sum_dim, *ss))\ndef diff_dim(d1: DimSize, d2: DimSize) -> DimSize:\n- d1, d2 = canonicalize_shape((d1, d2))\n- return _get_dim_handler(d1, d2).diff(d1, d2)\n+ handler, ds = _dim_handler_and_canonical(d1, d2)\n+ return handler.diff(*ds)\ndef diff_shape(s1: Shape, s2: Shape) -> Shape:\nreturn tuple(map(diff_dim, s1, s2))\ndef divide_shape_sizes(s1: Shape, s2: Shape) -> int:\n- s1 = canonicalize_shape(s1) or (1,)\n- s2 = canonicalize_shape(s2) or (1,)\n- return _get_dim_handler(*s1, *s2).divide_shape_sizes(s1, s2)\n+ s1 = s1 or (1,)\n+ s2 = s2 or (1,)\n+ handler, ds = _dim_handler_and_canonical(*s1, *s2)\n+ return handler.divide_shape_sizes(ds[:len(s1)], ds[len(s1):])\ndef same_shape_sizes(s1: Shape, s2: Shape) -> bool:\nreturn 1 == divide_shape_sizes(s1, s2)\ndef dilate_dim(d: DimSize, dilation: DimSize) -> DimSize:\n\"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\n- d, dilation = canonicalize_shape((d, dilation))\n- return _get_dim_handler(d, dilation).dilate(d, dilation)\n+ handler, ds = _dim_handler_and_canonical(d, dilation)\n+ return handler.dilate(*ds)\ndef dilate_shape(s: Shape, dilations: Sequence[int]) -> Shape:\nreturn tuple(map(dilate_dim, s, dilations))\ndef stride_dim(d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n- d, window_size, window_stride = canonicalize_shape((d, window_size, window_stride))\n- return _get_dim_handler(d, window_size, window_stride).stride(d, window_size, window_stride)\n+ handler, ds = _dim_handler_and_canonical(d, window_size, window_stride)\n+ return handler.stride(*ds)\ndef stride_shape(s: Shape, window_size: Shape, window_stride: Shape) -> Shape:\n\"\"\"(s - window_size) // window_stride + 1\"\"\"\n@@ -1382,13 +1389,16 @@ def canonicalize_shape(shape: Shape) -> Shape:\nreturn tuple(map(_canonicalize_dimension, shape))\nexcept TypeError:\npass\n+ raise _invalid_shape_error(shape)\n+\n+def _invalid_shape_error(shape: Shape):\nmsg = (\"Shapes must be 1D sequences of concrete values of integer type, \"\n\"got {}.\")\nif any(isinstance(x, Tracer) and isinstance(get_aval(x), ShapedArray)\nand not isinstance(get_aval(x), ConcreteArray) for x in shape):\nmsg += (\"\\nIf using `jit`, try using `static_argnums` or applying `jit` to \"\n\"smaller subfunctions.\")\n- raise TypeError(msg.format(shape))\n+ return TypeError(msg.format(shape))\n# ------------------- Named shapes -------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -39,7 +39,7 @@ from jax.lib import xla_client\nfrom . import shape_poly\nimport numpy as np\n-import tensorflow as tf\n+import tensorflow as tf # type: ignore[import]\n# These don't have public equivalents.\n# pylint: disable=g-direct-tensorflow-import\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/shape_poly.py", "new_path": "jax/experimental/jax2tf/shape_poly.py", "diff": "@@ -79,7 +79,8 @@ class DimensionHandlerVar(core.DimensionHandler):\nreturn 0\nif d2 in {0}:\nreturn d1\n- raise core.InconclusiveDimensionOperation(f\"Subtracting shape variables is not supported ({d1} - {d2})\")\n+ raise core.InconclusiveDimensionOperation(\n+ f\"Subtracting shape variables is not supported ({d1} - {d2})\")\ndef divide_shape_sizes(self, s1: Shape, s2: Shape) -> int:\ns1_ints, s1_vars = _split_shape_ints(s1)\n@@ -92,13 +93,18 @@ class DimensionHandlerVar(core.DimensionHandler):\ndef dilate(self, d: DimSize, dilation: DimSize) -> DimSize:\n\"\"\"Implements `0 if d == 0 else 1 + dilation * (d - 1))`\"\"\"\nif dilation not in {1}:\n- raise core.InconclusiveDimensionOperation(f\"Dilation is not supported for shape variables (d = {dilation})\")\n+ raise core.InconclusiveDimensionOperation(\n+ f\"Only dilation == 1 is supported for shape variables (var = {d}, \"\n+ f\"dilation = {dilation})\")\nreturn d\ndef stride(self, d: DimSize, window_size: DimSize, window_stride: DimSize) -> DimSize:\n\"\"\"Implements `(d - window_size) // window_stride + 1`\"\"\"\nif {window_size, window_stride} != {1}:\n- raise core.InconclusiveDimensionOperation(f\"Striding is not supported for shape variables (window_size = {window_size}, stride = {window_stride}\")\n+ raise core.InconclusiveDimensionOperation(\n+ \"Only striding with window_size == window_stride == 1 is supported \"\n+ f\"for shape variables (var = {d}, window_size = {window_size}, \"\n+ f\"stride = {window_stride}\")\nreturn d\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": "@@ -458,6 +458,11 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertFalse(core.symbolic_equal_one_of_dim(1, [2, db]))\nself.assertFalse(core.symbolic_equal_one_of_dim(3, []))\n+ self.assertTrue(core.symbolic_equal_dim(1, jnp.add(0, 1))) # A DeviceArray\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"Shapes must be 1D sequences of concrete values of integer type, got (1, 'a').\")):\n+ self.assertTrue(core.symbolic_equal_dim(1, \"a\"))\n+\ndef test_dim_vars_greater_equal(self):\nda, db = shape_poly.parse_spec(\"a, b\", (2, 3))\nself.assertTrue(core.greater_equal_dim(da, da))\n@@ -474,6 +479,31 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n\"Shape variable comparison .* is inconclusive\"):\ncore.greater_equal_dim(da, db)\n+ def test_dilate_shape(self):\n+ da, = shape_poly.parse_spec(\"a,\", (2,))\n+\n+ self.assertEqual((4, 7), core.dilate_shape((2, 3), (3, 3)))\n+ self.assertEqual((0, 7), core.dilate_shape((0, 3), (3, 3)))\n+ self.assertEqual((da, 7), core.dilate_shape((da, 3), (1, 3)))\n+\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n+ re.escape(\"Only dilation == 1 is supported for shape variables (var = a, dilation = 2)\")):\n+ core.dilate_shape((da, 3), (2, 3))\n+\n+ def test_stride_shape(self):\n+ da, = shape_poly.parse_spec(\"a,\", (2,))\n+\n+ self.assertEqual((8, 9), core.stride_shape((10, 20), (3, 3), (1, 2)))\n+ self.assertEqual((da, 9), core.stride_shape((da, 20), (1, 3), (1, 2)))\n+\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n+ re.escape(\"Only striding with window_size == window_stride == 1 is supported for shape variables (var = a, window_size = 2, stride = 1\")):\n+ core.stride_shape((da, 20), (2, 3), (1, 2))\n+\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n+ re.escape(\"Only striding with window_size == window_stride == 1 is supported for shape variables (var = a, window_size = 1, stride = 2\")):\n+ core.stride_shape((da, 20), (1, 3), (2, 2))\n+\nclass ShapeAsValueTest(tf_test_util.JaxToTfTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Cleanup of the dispatch to shape polymorphic dimension handlers
260,335
09.04.2021 14:43:13
25,200
60828e9b19eacdc20b6f62975c58ea143bc10b6e
raise error if vmap/pmap in_axes are booleans fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1259,14 +1259,12 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\n# rather than raising an error. https://github.com/google/jax/issues/2367\nin_axes = tuple(in_axes)\n- in_axes_, out_axes_ = tree_leaves(in_axes), tree_leaves(out_axes)\n- if not all(isinstance(l, (type(None), int)) for l in in_axes_):\n+ if not all(type(l) is int for l in tree_leaves(in_axes)):\nraise TypeError(\"vmap in_axes must be an int, None, or (nested) container \"\nf\"with those types as leaves, but got {in_axes}.\")\n- if not all(isinstance(l, (type(None), int)) for l in out_axes_):\n+ if not all(type(l) is int for l in tree_leaves(out_axes)):\nraise TypeError(\"vmap out_axes must be an int, None, or (nested) container \"\nf\"with those types as leaves, but got {out_axes}.\")\n- del in_axes_, out_axes_\n@wraps(fun, docstr=docstr)\n@api_boundary\n@@ -1560,6 +1558,13 @@ def pmap(\ndonate_tuple = rebase_donate_argnums(_ensure_index_tuple(donate_argnums),\nstatic_broadcasted_tuple)\n+ if not all(type(l) is int for l in tree_leaves(in_axes)):\n+ raise TypeError(\"pmap in_axes must be an int, None, or (nested) container \"\n+ f\"with those types as leaves, but got {in_axes}.\")\n+ if not all(type(l) is int for l in tree_leaves(out_axes)):\n+ raise TypeError(\"pmap out_axes must be an int, None, or (nested) container \"\n+ f\"with those types as leaves, but got {out_axes}.\")\n+\n@wraps(fun)\n@api_boundary\ndef f_pmapped(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1939,6 +1939,16 @@ class APITest(jtu.JaxTestCase):\nfoo, in_axes=((0, collections.OrderedDict([('a', 1), ('b', 2)])),))\nself.assertEqual(vfoo(tree).shape, (6, 2, 5))\n+ def test_vmap_in_axes_bool_error(self):\n+ # https://github.com/google/jax/issues/6372\n+ with self.assertRaisesRegex(TypeError, \"must be an int\"):\n+ api.vmap(lambda x: x, in_axes=False)(jnp.zeros(3))\n+\n+ def test_pmap_in_axes_bool_error(self):\n+ # https://github.com/google/jax/issues/6372\n+ with self.assertRaisesRegex(TypeError, \"must be an int\"):\n+ api.pmap(lambda x: x, in_axes=False)(jnp.zeros(1))\n+\ndef test_pmap_global_cache(self):\ndef f(x, y):\nreturn x, y\n" } ]
Python
Apache License 2.0
google/jax
raise error if vmap/pmap in_axes are booleans fixes #6372
260,335
09.04.2021 18:10:20
25,200
5f6bce4bfe5bdf35019845e2ad9a3cef4b82ca64
add 'open in colab' button, add numpy<1.18 compat
[ { "change_type": "MODIFY", "old_path": "docs/autodidax.ipynb", "new_path": "docs/autodidax.ipynb", "diff": "]\n},\n{\n- \"cell_type\": \"code\",\n- \"execution_count\": null,\n+ \"cell_type\": \"markdown\",\n\"metadata\": {\n- \"lines_to_next_cell\": 0\n+ \"lines_to_next_cell\": 2\n},\n- \"outputs\": [],\n- \"source\": []\n+ \"source\": [\n+ \"[![Open in\\n\",\n+ \"Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/master/docs/autodidax.ipynb)\"\n+ ]\n},\n{\n\"cell_type\": \"markdown\",\n\"impl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)]\\n\",\n\"\\n\",\n\"def broadcast_impl(x, *, shape, axes):\\n\",\n- \" return [np.broadcast_to(np.expand_dims(x, axes), shape)]\\n\",\n+ \" for axis in sorted(axes):\\n\",\n+ \" x = np.expand_dims(x, axis)\\n\",\n+ \" return [np.broadcast_to(x, shape)]\\n\",\n\"impl_rules[broadcast_p] = broadcast_impl\"\n]\n},\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.md", "new_path": "docs/autodidax.md", "diff": "@@ -32,9 +32,10 @@ limitations under the License.\n---\n```\n-```{code-cell}\n+[![Open in\n+Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/master/docs/autodidax.ipynb)\n-```\n++++\n# Autodidax: JAX core from scratch\n@@ -423,7 +424,9 @@ impl_rules[greater_p] = lambda x, y: [np.greater(x, y)]\nimpl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)]\ndef broadcast_impl(x, *, shape, axes):\n- return [np.broadcast_to(np.expand_dims(x, axes), shape)]\n+ for axis in sorted(axes):\n+ x = np.expand_dims(x, axis)\n+ return [np.broadcast_to(x, shape)]\nimpl_rules[broadcast_p] = broadcast_impl\n```\n" }, { "change_type": "MODIFY", "old_path": "docs/autodidax.py", "new_path": "docs/autodidax.py", "diff": "# name: python3\n# ---\n+# [![Open in\n+# Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/master/docs/autodidax.ipynb)\n+\n# # Autodidax: JAX core from scratch\n#\n@@ -404,7 +407,9 @@ impl_rules[greater_p] = lambda x, y: [np.greater(x, y)]\nimpl_rules[transpose_p] = lambda x, *, perm: [np.transpose(x, perm)]\ndef broadcast_impl(x, *, shape, axes):\n- return [np.broadcast_to(np.expand_dims(x, axes), shape)]\n+ for axis in sorted(axes):\n+ x = np.expand_dims(x, axis)\n+ return [np.broadcast_to(x, shape)]\nimpl_rules[broadcast_p] = broadcast_impl\n# -\n" } ]
Python
Apache License 2.0
google/jax
add 'open in colab' button, add numpy<1.18 compat Co-authored-by: Edward Loper <edloper@google.com>
260,496
09.04.2021 16:31:46
-7,200
9e3001b9b342247ce8758ba3b81da6907dea33b4
Some updates to jax2tf
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md", "new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/README.md", "diff": "@@ -12,24 +12,28 @@ and is a part of the code featured in the aforementioned blog post.\n## Training the model\nYou can train and export the model yourself by running\n+\n```bash\n$ python3 quickdraw.py\n```\n-The training itself lasts roughly 30 minutes, assuming the dataset has already\n-been downloaded. You can also skip to the [next section](#interacting-with-the-model)\n-to see instructions for playing with a pre-trained model.\n+This will first download the dataset if it is not downloaded yet, which is about\n+11Gb in total. Assuming the dataset has been downloaded already, training for 5\n+epochs takes roughly 10 minutes on a CPU (3,5 GHz Dual-Core Intel Core i7). You\n+can also skip to the [next section](#interacting-with-the-model) to see\n+instructions for playing with a pre-trained model.\nThe dataset will be downloaded directly into a `data/` directory in the\n`/tmp/jax2tf/tf_js_quickdraw` directory; by default, the model is configured to\n-classify inputs into 100 different classes, which corresponds to a dataset of\n-roughly 11 Gb. This can be tweaked by modifying the value of the `NB_CLASSES`\n-global variable in `quickdraw.py` (max number of classes: 100). Only the files\n-corresponding to the first `NB_CLASSES` classes in the dataset will be\n+classify inputs into 100 different classes. This can be tweaked using the\n+command-line argument `--num_classes` (max number of classes: 100). Only the\n+files corresponding to the first `num_classes` classes in the dataset will be\ndownloaded.\n-The training loop runs for 5 epochs, and the model as well as its equivalent\n-TF.js-loadable model are subsequently saved into `/tmp/jax2tf/tf_js_quickdraw`.\n+The training loop runs for 5 epochs by default (this can be changed using\n+the command-line argument `--num_epochs`), and the model as well as its\n+equivalent TF.js-loadable model are subsequently saved into\n+`/tmp/jax2tf/tf_js_quickdraw`.\n## Interacting with the model\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom absl import app # type: ignore\n+from absl import flags\n+\nimport os # type: ignore\nimport time\nfrom typing import Callable\n@@ -35,7 +37,18 @@ config.config_with_absl()\nimport utils\n-NB_CLASSES = 100\n+flags.DEFINE_boolean(\"run_eval_on_train\", False,\n+ (\"Also run eval on the train set after each epoch. This \"\n+ \"slows down training considerably.\"))\n+flags.DEFINE_integer(\"num_epochs\", 5,\n+ (\"Number of epochs to train for.\"))\n+flags.DEFINE_integer(\"num_classes\", 100, \"Number of classification classes.\")\n+\n+flags.register_validator('num_classes',\n+ lambda value: value >= 1 and value <= 100,\n+ message='--num_classes must be in range [1, 100]')\n+\n+FLAGS = flags.FLAGS\n# The code below is an adaptation for Flax from the work published here:\n# https://blog.tensorflow.org/2018/07/train-model-in-tfkeras-with-colab-and-run-in-browser-tensorflowjs.html\n@@ -59,7 +72,7 @@ class QuickDrawModule(nn.Module):\nx = nn.Dense(features=128)(x)\nx = nn.relu(x)\n- x = nn.Dense(features=NB_CLASSES)(x)\n+ x = nn.Dense(features=FLAGS.num_classes)(x)\nx = nn.softmax(x)\nreturn x\n@@ -110,25 +123,31 @@ def init_model():\ndef train(train_ds, test_ds, classes):\noptimizer, params = init_model()\n- for epoch in range(5):\n+ for epoch in range(1, FLAGS.num_epochs+1):\nstart_time = time.time()\noptimizer = train_one_epoch(optimizer, train_ds)\n- epoch_time = time.time() - start_time\n+\n+ if FLAGS.run_eval_on_train:\ntrain_acc = accuracy(predict, optimizer.target, train_ds)\n- test_acc = accuracy(predict, optimizer.target, test_ds)\n- print(\"Epoch {} in {:0.2f} sec\".format(epoch, epoch_time))\nprint(\"Training set accuracy {}\".format(train_acc))\n+\n+ test_acc = accuracy(predict, optimizer.target, test_ds)\nprint(\"Test set accuracy {}\".format(test_acc))\n+ epoch_time = time.time() - start_time\n+ print(\"Epoch {} in {:0.2f} sec\".format(epoch, epoch_time))\nreturn optimizer.target\ndef main(*args):\nbase_model_path = \"/tmp/jax2tf/tf_js_quickdraw\"\ndataset_path = os.path.join(base_model_path, \"data\")\n- classes = utils.download_dataset(dataset_path, NB_CLASSES)\n- assert len(classes) == NB_CLASSES, classes\n+ num_classes = FLAGS.num_classes\n+ classes = utils.download_dataset(dataset_path, num_classes)\n+ assert len(classes) == num_classes, classes\nprint(f\"Classes are: {classes}\")\n+ print(\"Loading dataset into memory...\")\ntrain_ds, test_ds = utils.load_classes(dataset_path, classes)\n+ print(f\"Starting training for {FLAGS.num_epochs} epochs...\")\nflax_params = train(train_ds, test_ds, classes)\nmodel_dir = os.path.join(base_model_path, \"saved_models\")\n" } ]
Python
Apache License 2.0
google/jax
Some updates to jax2tf
260,424
12.04.2021 12:59:12
-3,600
b4f66d267694d055f2fbfdbbb06da87ccfe28428
Fix handling of ad.Zero in _select_and_scatter_add_transpose. Fixes
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -5573,6 +5573,8 @@ def _select_and_scatter_add_transpose(\nt, source, operand, *, select_prim, window_dimensions, window_strides,\npadding):\nassert ad.is_undefined_primal(source) and not ad.is_undefined_primal(operand)\n+ if type(t) is ad_util.Zero:\n+ return [ad_util.Zero(source.aval), None]\nones = (1,) * len(window_dimensions)\nsource_t = _select_and_gather_add(t, operand, select_prim, window_dimensions,\nwindow_strides, padding, ones, ones)\n" } ]
Python
Apache License 2.0
google/jax
Fix handling of ad.Zero in _select_and_scatter_add_transpose. Fixes #6403.
260,510
12.04.2021 14:10:11
25,200
577c6011916f0e9f2ff51788bc765e07cb323d1b
Update references in custom interpreter notebook
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb", "diff": "},\n\"outputs\": [],\n\"source\": [\n- \"def examine_jaxpr(typed_jaxpr):\\n\",\n- \" jaxpr = typed_jaxpr.jaxpr\\n\",\n+ \"def examine_jaxpr(closed_jaxpr):\\n\",\n+ \" jaxpr = closed_jaxpr.jaxpr\\n\",\n\" print(\\\"invars:\\\", jaxpr.invars)\\n\",\n\" print(\\\"outvars:\\\", jaxpr.outvars)\\n\",\n\" print(\\\"constvars:\\\", jaxpr.constvars)\\n\",\n\"id\": \"CpTml2PTrzZ4\"\n},\n\"source\": [\n- \"This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `pe.trace_to_jaxpr` function is used to then trace a function into a Jaxpr\\n\",\n+ \"This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `jax.make_jaxpr` function is used to then trace a function into a Jaxpr\\n\",\n\"from a list of partial value inputs.\"\n]\n},\n\"source\": [\n\"Notice that `eval_jaxpr` will always return a flat list even if the original function does not.\\n\",\n\"\\n\",\n- \"Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py#L185-L212)) to see the edge cases that this interpreter does not cover.\"\n+ \"Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py)) to see the edge cases that this interpreter does not cover.\"\n]\n},\n{\n" }, { "change_type": "MODIFY", "old_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.md", "new_path": "docs/notebooks/Writing_custom_interpreters_in_Jax.md", "diff": "@@ -78,8 +78,8 @@ are structured.\n```{code-cell} ipython3\n:id: RSxEiWi-EeYW\n-def examine_jaxpr(typed_jaxpr):\n- jaxpr = typed_jaxpr.jaxpr\n+def examine_jaxpr(closed_jaxpr):\n+ jaxpr = closed_jaxpr.jaxpr\nprint(\"invars:\", jaxpr.invars)\nprint(\"outvars:\", jaxpr.outvars)\nprint(\"constvars:\", jaxpr.constvars)\n@@ -156,7 +156,7 @@ from jax._src.util import safe_map\n+++ {\"id\": \"CpTml2PTrzZ4\"}\n-This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `pe.trace_to_jaxpr` function is used to then trace a function into a Jaxpr\n+This function first flattens its arguments into a list, which are the abstracted and wrapped as partial values. The `jax.make_jaxpr` function is used to then trace a function into a Jaxpr\nfrom a list of partial value inputs.\n```{code-cell} ipython3\n@@ -226,7 +226,7 @@ eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, jnp.ones(5))\nNotice that `eval_jaxpr` will always return a flat list even if the original function does not.\n-Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py#L185-L212)) to see the edge cases that this interpreter does not cover.\n+Furthermore, this interpreter does not handle `subjaxprs`, which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/google/jax/blob/master/jax/core.py)) to see the edge cases that this interpreter does not cover.\n+++ {\"id\": \"0vb2ZoGrCMM4\"}\n" } ]
Python
Apache License 2.0
google/jax
Update references in custom interpreter notebook
260,287
14.04.2021 14:01:28
0
c13efc12234df22ef19e8b6e5f41cecfbc1c37eb
Add JVP of xmap
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -35,6 +35,7 @@ from ..interpreters import partial_eval as pe\nfrom ..interpreters import pxla\nfrom ..interpreters import xla\nfrom ..interpreters import batching\n+from ..interpreters import ad\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom .._src.util import safe_map, safe_zip, HashableFunction, as_hashable_function, unzip2\n@@ -638,10 +639,7 @@ 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.Primitive):\n- multiple_results = True\n- map_primitive = True # Not really, but it gives us a few good behaviors\n-\n+class XMapPrimitive(core.MapPrimitive): # Not really a map, but it gives us a few good defaults\ndef __init__(self):\nsuper().__init__('xmap')\nself.def_impl(xmap_impl)\n@@ -670,6 +668,8 @@ def _xmap_axis_subst(params, subst):\nreturn dict(params, call_jaxpr=new_jaxpr)\ncore.axis_substitution_rules[xmap_p] = _xmap_axis_subst\n+ad.JVPTrace.process_xmap = ad.JVPTrace.process_call # type: ignore\n+ad.call_param_updaters[xmap_p] = ad.call_param_updaters[xla.xla_call_p]\n# This is DynamicJaxprTrace.process_map with some very minor modifications\ndef _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -543,6 +543,14 @@ class XMapTest(XMapTestCase):\ny = rng.randn(*yshape)\nself.assertAllClose(fm(x, y), fref(x, y))\n+ def testJVP(self):\n+ f = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\n+ precision=lax.Precision.HIGHEST)),\n+ in_axes=[['i', ...], {}], out_axes=['i', ...])\n+ x = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100\n+ y = jnp.arange(20, dtype=jnp.float32).reshape((4, 5)) / 100\n+ jtu.check_grads(f, (x, y), order=2, modes=['fwd'])\n+\nclass XMapTestSPMD(SPMDTestMixin, XMapTest):\n\"\"\"Re-executes all basic tests with the SPMD partitioner enabled\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Add JVP of xmap
260,411
15.04.2021 09:50:00
-10,800
3c6f3e50373a17be481886db68a4a875eafc0f3c
[jax2tf] Added documentation for shape polymorphism
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -40,6 +40,8 @@ More involved examples, including using jax2tf with\nFlax models and their use with TensorFlow Hub and Keras, are described in the\n[examples directory](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/examples/README.md).\n+For details on saving a batch-polymorphic SavedModel see [below](#shape-polymorphic-conversion).\n+\nSee also some internal ongoing design discussions at `go/jax2tf-doc`.\n## Usage: converting basic functions.\n@@ -130,6 +132,260 @@ computation is attempted.\nCurrently, there is a bug that prevents using custom gradients with SavedModel\n(see [Caveats](#caveats) below).\n+## Shape-polymorphic conversion\n+\n+**The shape polymorphism support is work in progress. It is meant to be sound,\n+but it may fail to convert some programs. Please report any bugs you encounter.**\n+\n+We described above how to include in the SavedModel several specializations\n+of a converted function for a few specific input shapes. The converter can\n+also produce a shape-polymorphic TensorFlow graph that is usable with inputs\n+of any shape matching\n+certain constraints. This is useful, e.g., to allow a single SavedModel\n+to be used for multiple batch sizes.\n+\n+The standard TensorFlow technique for producing a shape-polymorphic graph is\n+to warm the function on partially-specified (shape-polymorphic) inputs, e.g.,\n+`tf.TensorSpec([None, 28, 28], tf.float32)` for a function that processes a\n+batch (of unspecified batch size) of 28x28 images.\n+For jax2tf it is also necessary to specify an additional `polymorphic_shapes` parameter\n+for the `jax2tf.convert` function:\n+\n+```\n+f_tf = tf.function(jax2tf.convert(f_jax,\n+ polymorphic_shapes=[\"(b, 28, 28)\"]),\n+ autograph=False)\n+f_tf.get_concrete_function(tf.TensorSpec([None, 28, 28], tf.float32))\n+```\n+\n+The `polymorphic_shapes` parameter, in the form of a list of strings corresponding\n+to the list of\n+arguments, introduces one or more shape variables, e.g., `b`, to stand for shape\n+dimensions that are unknown at JAX tracing time.\n+In this particular example, we can\n+also use the `polymorphic_shapes=[\"(b, _, _)\"]`,\n+because the `_` placeholders take their value\n+from the corresponding dimension of the `tf.TensorSpec` (which must be known).\n+As a shortcut for a series of `_` at the end of a shape specification you can\n+use `...`: `polymorphic_shapes=[\"(b, ...)\"]`\n+\n+In the example above, the `polymorphic_shapes` specification does\n+not convey more information than the partial `tf.TensorSpec`,\n+except that it gives a name to the unknown dimension so that it\n+can be recognized in the error messages. The need for named shape\n+variables arises when there are\n+multiple unknown dimensions and there is a relationship between them.\n+For example,\n+if the function to be converted is also polymorphic on the size of each\n+image while requiring the images to be square,\n+we would add a shape variable `d` to stand for\n+the unknown image size:\n+\n+```\n+f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, d, d)\"]), autograph=False)\n+f_tf.get_concrete_function(tf.TensorSpec([None, None, None], tf.float32))\n+```\n+\n+The JAX tracing mechanism performs shape checking using the same strict rules as\n+when the shapes are fully known. For example, given the `\"(b, d, d)\"`\n+specification for the argument `x` of a function, JAX will know that a conditional\n+`x.shape[-2] == x.shape[-1]` is `True`, will know that `x` and `jnp.sin(x)` have the\n+same shape of a batch of square matrices that can be passed to `jnp.matmul`.\n+\n+\n+### Correctness of shape-polymorphic tracing\n+\n+We want to trust that the converted program produces the same results as the\n+original JAX program:\n+\n+For any function `f_jax` and any input signature `abs_sig` containing partially\n+known `tf.TensorSpec`, and any concrete input `x` whose shape matches `abs_sig`:\n+\n+ * If the conversion to TensorFlow succeeds: `f_tf = tf.function(jax2tf.convert(f_jax, polymorphic_shapes)).get_concrete_function(abs_sig)`\n+ * and if the TensorFlow execution succeeds with result `y`: `f_tf(x) = y`\n+ * then the JAX execution would produce the same result: `f_jax(x) = y`,\n+\n+It is crucial to understand that `f_jax(x)` has the freedom to re-invoke the JAX tracing machinery,\n+and in fact it does so for each distinct concrete input shape, while the generation of `f_tf`\n+uses JAX tracing only once, and invoking `f_tf(x)` does not use JAX tracing anymore. In fact,\n+invoking the latter invocation may happen after the `f_tf` has been serialized\n+to a SavedModel and reloaded in an environment where `f_jax` and the JAX\n+tracing machinery are not available anymore.\n+\n+Correctness is very important because it would be nasty to debug a subtle discrepancy\n+of the code running in production from the expected behavior written in JAX.\n+We help ensure correctness\n+by reusing the same JAX tracing and shape checking mechanism as when the shapes are fully known.\n+\n+### Coverage of shape-polymorphic tracing\n+\n+A complementary goal is to be able to convert many shape-polymorphic programs, but at the very\n+least batch-size-polymorphic programs, so that one SavedModel can be used for any batch sizes.\n+For example, we want to ensure that any function written using `jax.vmap` at the top level can be\n+converted with the batch dimension polymorphic and the remaining dimensions concrete.\n+\n+It is reasonable to expect that there will be JAX programs for which there is a\n+shape-polymorphic TensorFlow graph, but which will give an error when converting with jax2tf.\n+\n+### Details\n+\n+In order to be able to use shape polymorphism effectively with jax2tf, it\n+is worth considering what happens under the hood. When the converted function\n+is invoked with a `TensorSpec`, the jax2tf converter will combine the\n+`TensorSpec` from the actual argument with the `polymorphic_shapes` parameter to\n+obtain a shape abstraction to be used to specialize the converted function.\n+Normally, the shape abstraction contains the dimension sizes, but in the\n+presence of shape polymorphism, some dimensions may be dimension variables.\n+\n+The `polymorphic_shapes` parameter must be either `None`,\n+or a sequence (one per argument) of shape specifiers.\n+(A value `None` for `polymorphic_shapes` is equivalent to a list of `None`.\n+See [how optional parameters are matched to arguments](https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).)\n+A shape specifier is combined with a `TensorSpec` as follows:\n+\n+ * A shape specifier of `None` means that the shape is given\n+ by the actual argument `TensorSpec`, which must be fully known.\n+ * Otherwise, the specifier must be a comma-separated string of dimension specifiers: `(dim_1, ..., dim_n)`, denoting\n+ an n-dimensional array. The `TensorSpec` must also be of rank ``n``.\n+ An `...` at the end of the shape specifier is expanded to a list of `_` or appropriate length.\n+ The\n+ corresponding dimensions from the shape specifier and the `TensorSpec` are matched:\n+\n+ * the dimension specifier of `_` means that the size of the dimension is given by\n+ the actual `TensorSpec`, which must have a known size in the corresponding dimension.\n+ * a dimension specifier can also be a lowercase identifier, denoting a dimension-size\n+ variable ranging over strictly positive integers.\n+ The abstract value of the dimension is going to be set to this variable.\n+ The corresponding dimension in `TensorSpec` can be `None` or can be a\n+ constant.\n+ * All occurrences of a shape variable in any dimension\n+ for any argument are assumed to be equal.\n+\n+Note that `polymorphic_shapes` controls the shape abstraction used by JAX when tracing\n+the function (with `_` placeholders given by the `TensorSpec`). The `TensorSpec`\n+gives the shape abstraction that TensorFlow will associate with the produced\n+graph, and can be more specific.\n+\n+A few examples of shape specifications and uses:\n+\n+ * `polymorphic_shapes=[\"(b, _, _)\", None]` can be used for a function with two arguments, the first\n+ having a batch leading dimension that should be polymorphic. The other dimensions for the\n+ first argument and the shape of the second argument are specialized based on the actual\n+ `TensorSpec`, which must be known. The converted function can be used, e.g.,\n+ with `TensorSpec`s `[None, 28, 28]` and `[28, 16]` for the first and second argument\n+ respectively. An alternative `TensorSpec` pair can be `[1, 28, 28]` and `[28, 16]`,\n+ in which case the JAX tracing is done for the same polymorphic shape given by\n+ `polymorphic_shapes=[\"(b, 28, 28)\", \"(28, 16)\"]` but the TensorFlow graph is monomorphic\n+ for the shapes given by `TensorSpec`.\n+\n+ * `polymorphic_shapes=[\"(batch, _)\", \"(batch,)\"]`: the leading dimensions of the two arguments\n+ must match, and are assumed to be greater than 0.\n+ The second dimension of the first argument is taken from the\n+ actual `TensorSpec`. This can be used with a `TensorSpec` pair `[None, 16]`\n+ and `[None]`. It can also be used with a pair `[8, 16]` and `[5]`.\n+\n+### Shape variables used in the computation\n+\n+There are some situations when shape variables arise in the computation itself.\n+You can see in the following example how elements from the input shapes\n+`(1024, 28, 28)` and `(28, 28)` appear in the computation and specifically\n+in the `shape` parameter of the `broadcast_in_dim` JAX primitive.\n+\n+```\n+def image_mask_jax(images, mask):\n+ # images: f32[B, W, W] and mask: f32[W, W]\n+ return images * mask\n+\n+print(jax.make_jaxpr(image_mask_jax)(np.ones((1024, 28, 28)), np.ones((28, 28))))\n+>> { lambda ; a b.\n+>> let c = broadcast_in_dim[ broadcast_dimensions=(1, 2)\n+>> shape=(1, 28, 28) ] b\n+>> d = mul a c\n+>> in (d,) }\n+\n+# will invoke broadcast_in_dim with shape=(1, w, w)\n+jax2tf.convert(image_mask_jax, polymorphic_shapes=[\"(b, w, w)\", \"(w, w)\"])\n+```\n+\n+When tracing and converting with abstract shapes some primitive parameters will be dimension variables\n+instead of just constants, e.g., the `shape` parameter of `broadcast_in_dim` will be `(1, w, w)`.\n+Note that JAX primitives distinguish the inputs, which are array values,\n+e.g., `b` for `broadcast_in_dim` above, and the parameters, e.g., `broadcast_dimensions` and `shape`.\n+\n+The conversion of `image_mask_jax` would use `tf.shape` to compute the\n+values of the dimension variables `b` and `w`:\n+\n+```\n+def image_mask_tf(images, mask):\n+ b, w, _ = tf.shape(images) # Compute the dynamic values for the shape variables \"b\" and \"w\"\n+ return tf.math.multiply(images,\n+ tf.broadcast_to(tf.reshape(mask, [1, w, w]),\n+ [b, w, w]))\n+```\n+\n+To achieve this, when we start converting a function we construct a shape environment,\n+mapping the shape variables in the `polymorphic_shapes` specification to TensorFlow expressions\n+using `tf.shape` on the input parameters.\n+\n+\n+### Errors in presence of shape polymorphism\n+\n+When tracing with shape polymorphism we can encounter shape errors:\n+\n+```\n+four_ones = np.ones((4,))\n+jax2tf.convert(lambda x, y: x + y,\n+ polymorphic_shapes=[\"(v,)\", \"(4,)\"])(four_ones, four_ones)\n+```\n+\n+with result in the error `'add got incompatible shapes for broadcasting: (v,), (4,)'`\n+because the shape abstraction is given by the `polymorphic_shapes`, even though the\n+actual arguments are more specific and would actually work.\n+\n+Also,\n+```\n+jax2tf.convert(lambda x: jnp.matmul(x, x),\n+ polymorphic_shapes=[\"(v, 4)\"])(np.ones((4, 4)))\n+```\n+\n+will result in the error `Shape variable comparison v == 4 is inconclusive`. What is\n+happening here is that in the process of type checking the `matmul` operation, JAX\n+will want to ensure the size of the two axes is the same (`v == 4`).\n+Note that `v` can stand for any integer greater than 0, so the value of the\n+equality expression can be true or false. In this case you will see\n+the `core.InconclusiveDimensionOperation` exception with the above message.\n+Since the converted function work only for square matrices, the correct\n+`polymorphic_shapes` is `[\"(v, v)\"]`.\n+\n+You would also encounter shape errors if the code attempts to use the\n+dimension variables in arithmetic operations, such as in the code\n+below that attempts to flatten an array with a polymorphic batch\n+dimension:\n+\n+```\n+jax2tf.convert(lambda x: jnp.reshape(x, np.prod(x.shape)),\n+ polymorphic_shapes=[\"(b, ...)\"])(np.ones((3, 4, 5)))\n+```\n+\n+In this case you will see the error `TypeError: unsupported operand type(s) for *: 'DimVar' and 'int'`.\n+The most flattening you can do is on the known dimensions, keeping the variable\n+dimension intact:\n+\n+```\n+jax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0], np.prod(x.shape[1:]))),\n+ polymorphic_shapes=[\"(b, _, _)\"])(np.ones((3, 4, 5)))\n+```\n+\n+\n+Finally, certain codes that use shapes in the actual computation may not yet work\n+if those shapes are polymorphic. In the code below, the expression `x.shape[0]`\n+will have the value of the shape variable `v`. This case is not yet implemented:\n+\n+```\n+jax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\n+ polymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\n+```\n+\n## Caveats\n### Incomplete TensorFlow data type coverage\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": "@@ -391,6 +391,17 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nres_jax,\njax2tf.convert(f, polymorphic_shapes=[\"(b, h)\", \"h\"])(x, y))\n+ def test_example(self):\n+ \"\"\"Some of the examples from the README.\"\"\"\n+ def image_mask_jax(images, mask):\n+ # images: f32[B, W, W] and mask: f32[W, W]\n+ return images * mask\n+\n+ print(jax.make_jaxpr(image_mask_jax)(np.ones((1024, 28, 28)), np.ones((28, 28))))\n+\n+ # will invoke broadcast_in_dim with shape=(1, w, w)\n+ jax2tf.convert(image_mask_jax, polymorphic_shapes=[\"(b, w, w)\", \"(w, w)\"])\n+\ndef test_shape_error(self):\n\"\"\"Some of the examples from the README.\"\"\"\nwith self.assertRaisesRegex(\n@@ -412,12 +423,24 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nlambda x, y: x + y, polymorphic_shapes=[\"(v,)\", \"(4,)\"])(four_ones,\nfour_ones)\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\nre.escape(\"Shape variable comparison v == 4 is inconclusive\")):\n- jax2tf.convert(\n- lambda x: jnp.matmul(x, x), polymorphic_shapes=[\"(v, 4)\"])(\n- np.ones((4, 4)))\n+ jax2tf.convert(lambda x: jnp.matmul(x, x),\n+ polymorphic_shapes=[\"(v, 4)\"])(np.ones((4, 4)))\n+\n+ with self.assertRaisesRegex(TypeError,\n+ re.escape(\"unsupported operand type(s) for *: 'DimVar' and 'int'\")):\n+ jax2tf.convert(lambda x: jnp.reshape(x, np.prod(x.shape)),\n+ polymorphic_shapes=[\"(b, ...)\"])(np.ones((3, 4, 5)))\n+\n+ jax2tf.convert(lambda x: jnp.reshape(x, (x.shape[0], np.prod(x.shape[1:]))),\n+ polymorphic_shapes=[\"(b, _, _)\"])(np.ones((3, 4, 5)))\n+\n+ with self.assertRaisesRegex(\n+ TypeError,\n+ re.escape(\"unsupported operand type(s) for /: 'TensorFlowTracer' and 'DimVar'\")):\n+ jax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\n+ polymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\ndef test_parse_poly_spec(self):\nself.assertEqual((2, 3), shape_poly.parse_spec(None, (2, 3)))\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added documentation for shape polymorphism
260,411
15.04.2021 09:57:46
-10,800
29929a8b39916d2ddb82aac1b007e44e9eba5d2f
Update quickdraw.py Minor cosmetic changes. The main reason I did this was to trigger another CI run.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "new_path": "jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py", "diff": "@@ -44,9 +44,9 @@ flags.DEFINE_integer(\"num_epochs\", 5,\n(\"Number of epochs to train for.\"))\nflags.DEFINE_integer(\"num_classes\", 100, \"Number of classification classes.\")\n-flags.register_validator('num_classes',\n+flags.register_validator(\"num_classes\",\nlambda value: value >= 1 and value <= 100,\n- message='--num_classes must be in range [1, 100]')\n+ message=\"--num_classes must be in range [1, 100]\")\nFLAGS = flags.FLAGS\n" } ]
Python
Apache License 2.0
google/jax
Update quickdraw.py Minor cosmetic changes. The main reason I did this was to trigger another CI run.
260,287
12.04.2021 12:49:35
0
2d95d5ad2b5aba1fcefe077eb808f03d4a160311
Small updates to abstract eval rules (AWN related) I've been reading the AWN-related PRs and have found a few places that could be improved a little.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -629,7 +629,9 @@ def _allreduce_abstract_eval(*args, axes, axis_index_groups):\nnamed_shapes = [{name: size for name, size in arg.named_shape.items()\nif name not in named_axes} for arg in args]\nelse:\n- assert len(pos_axes) == 0\n+ if len(pos_axes) != 0:\n+ raise ValueError(f\"axis_index_groups can only be used with reductions over \"\n+ f\"named axes, but got: {axes}\")\nreturn [ShapedArray(lax._reduce_op_shape_rule(raise_to_shaped(arg), axes=pos_axes),\narg.dtype, named_shape=named_shape)\nfor arg, named_shape in zip(args, named_shapes)]\n@@ -1036,11 +1038,13 @@ def _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_\naxis_index_groups=axis_index_groups, axis_size=axis_size, axis_env=axis_env, platform=platform)\ndef _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+ if not isinstance(axis_name, (list, tuple)):\n+ axis_name = (axis_name,)\nx_aval = raise_to_shaped(x)\nnew_shape = list(x_aval.shape)\nnew_shape.insert(all_gather_dimension, axis_size)\nnew_named_shape = {name: size for name, size in x_aval.named_shape.items()\n- if name != axis_name}\n+ if name not in axis_name}\nreturn x_aval.update(shape=new_shape, named_shape=new_named_shape)\ndef _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n@@ -1152,8 +1156,9 @@ def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\npos_aval = lax.dot_general_p.abstract_eval(\nx, y, dimension_numbers=[pos_contract, pos_batch],\nprecision=None, preferred_element_type=None)\n+ common_named_shape = core.join_named_shapes(x.named_shape, y.named_shape)\nnamed_shape = {name: size\n- for aval in (x, y) for name, size in aval.named_shape.items()\n+ for name, size in common_named_shape.items()\nif name not in axis_name}\nreturn pos_aval.update(named_shape=named_shape)\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1144,9 +1144,7 @@ class ConcreteArray(ShapedArray):\nreturn self\nelif self.shape == other.shape and self.dtype == other.dtype:\nweak_type = self.weak_type and other.weak_type\n- named_shape = {name: size\n- for ns in (self.named_shape, other.named_shape)\n- for name, size in ns.items()}\n+ named_shape = join_named_shapes(self.named_shape, other.named_shape)\nreturn ShapedArray(\nself.shape, self.dtype, weak_type=weak_type, named_shape=named_shape)\nelif self.dtype == other.dtype:\n" } ]
Python
Apache License 2.0
google/jax
Small updates to abstract eval rules (AWN related) I've been reading the AWN-related PRs and have found a few places that could be improved a little.
260,411
15.04.2021 15:48:00
-10,800
eff49fe106fa399eac0dd848a84c1927e8a76877
[jax2tf] Upgraded examples and tests to allow shape polymorphism
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/README.md", "new_path": "jax/experimental/jax2tf/examples/README.md", "diff": "@@ -68,7 +68,7 @@ one using Flax (`FlaxMNIST`). Other Flax models can be arranged similarly,\nand the same strategy should work for other neural-network libraries for JAX.\nIf your Flax model takes multiple inputs, then you need to change the last\n-line above to:\n+line in the example above to:\n```python\npredict_fn = lambda params, input: model.apply({\"params\": params}, *input)\n" }, { "change_type": "ADD", "old_path": "jax/experimental/jax2tf/examples/__init__.py", "new_path": "jax/experimental/jax2tf/examples/__init__.py", "diff": "" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/keras_reuse_main.py", "new_path": "jax/experimental/jax2tf/examples/keras_reuse_main.py", "diff": "@@ -20,8 +20,8 @@ See README.md.\nimport logging\nfrom absl import app\nfrom absl import flags\n-from jax.experimental.jax2tf.examples import mnist_lib\n-from jax.experimental.jax2tf.examples import saved_model_main\n+from jax.experimental.jax2tf.examples import mnist_lib # type: ignore\n+from jax.experimental.jax2tf.examples import saved_model_main # type: ignore\nimport tensorflow as tf # type: ignore\nimport tensorflow_datasets as tfds # type: ignore\nimport tensorflow_hub as hub # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "new_path": "jax/experimental/jax2tf/examples/mnist_lib.py", "diff": "@@ -113,9 +113,7 @@ class PureJaxMNIST:\neither the predictions (B, 10) if with_classifier=True, or the\nfinal set of logits of shape (B, 512).\n\"\"\"\n- # TODO: replace inputs.shape[1:] with -1 once we fix shape polymorphic bug\n- x = inputs.reshape(\n- (inputs.shape[0], np.prod(inputs.shape[1:]))) # flatten to f32[B, 784]\n+ x = inputs.reshape((inputs.shape[0], -1)) # flatten to f32[B, 784]\nfor w, b in params[:-1]:\nx = jnp.dot(x, w) + b\nx = jnp.tanh(x)\n@@ -206,8 +204,7 @@ class FlaxMNIST:\nx = nn.Conv(features=64, kernel_size=(3, 3))(x)\nx = nn.relu(x)\nx = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))\n- # TODO: replace np.prod(x.shape[1:]) with -1 once we fix shape_polymorphism\n- x = x.reshape((x.shape[0], np.prod(x.shape[1:]))) # flatten\n+ x = x.reshape((x.shape[0], -1)) # flatten\nx = nn.Dense(features=256)(x)\nx = nn.relu(x)\nif not with_classifier:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "diff": "@@ -25,7 +25,7 @@ uses you will probably want to copy and expand this function as needed.\n\"\"\"\n-from typing import Any, Callable, Sequence, Optional\n+from typing import Any, Callable, Sequence, Optional, Union\nfrom jax.experimental import jax2tf # type: ignore[import]\nimport tensorflow as tf # type: ignore[import]\n@@ -37,6 +37,7 @@ def convert_and_save_model(\nmodel_dir: str,\n*,\ninput_signatures: Sequence[tf.TensorSpec],\n+ polymorphic_shapes: Optional[Union[str, jax2tf.PolyShape]] = None,\nwith_gradient: bool = False,\nenable_xla: bool = True,\ncompile_model: bool = True,\n@@ -84,13 +85,22 @@ def convert_and_save_model(\nexception if it is not possible. (default: True)\ncompile_model: use TensorFlow jit_compiler on the SavedModel. This\nis needed if the SavedModel will be used for TensorFlow serving.\n+ polymorphic_shapes: if given then it will be used as the\n+ `polymorphic_shapes` argument to jax2tf.convert for the second parameter of\n+ `jax_fn`. In this case, a single `input_signatures` is supported, and\n+ should have `None` in the polymorphic dimensions.\nsave_model_options: options to pass to savedmodel.save.\n\"\"\"\nif not input_signatures:\nraise ValueError(\"At least one input_signature must be given\")\n+ if polymorphic_shapes is not None:\n+ if len(input_signatures) > 1:\n+ raise ValueError(\"For shape-polymorphic conversion a single \"\n+ \"input_signature is supported.\")\ntf_fn = jax2tf.convert(\njax_fn,\nwith_gradient=with_gradient,\n+ polymorphic_shapes=[None, polymorphic_shapes],\nenable_xla=enable_xla)\n# Create tf.Variables for the parameters. If you want more useful variable\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "By default, uses a pure JAX implementation of MNIST. There are flags to choose\na Flax CNN version of MNIST, or to skip the training and just test a\n-previously saved SavedModel.\n+previously saved SavedModel. It is possible to save a batch-polymorphic\n+version of the model, or a model prepared for specific batch sizes.\nTry --help to see all flags.\n@@ -47,11 +48,18 @@ flags.DEFINE_string(\"model_path\", \"/tmp/jax2tf/saved_models\",\n\"Path under which to save the SavedModel.\")\nflags.DEFINE_integer(\"model_version\", 1,\n(\"The version number for the SavedModel. Needed for \"\n- \"serving, larger versions will take precedence\"))\n+ \"serving, larger versions will take precedence\"),\n+ lower_bound=1)\nflags.DEFINE_integer(\"serving_batch_size\", 1,\n- \"For what batch size to prepare the serving signature. \",\n+ \"For what batch size to prepare the serving signature. \"\n+ \"Use -1 for converting and saving with batch polymorphism.\")\n+flags.register_validator(\n+ \"serving_batch_size\",\n+ lambda serving_batch_size: serving_batch_size > 0 or serving_batch_size == -1,\n+ message=\"--serving_batch_size must be either -1 or a positive integer.\")\n+\n+flags.DEFINE_integer(\"num_epochs\", 3, \"For how many epochs to train.\",\nlower_bound=1)\n-flags.DEFINE_integer(\"num_epochs\", 3, \"For how many epochs to train.\")\nflags.DEFINE_boolean(\n\"generate_model\", True,\n\"Train and save a new model. Otherwise, use an existing SavedModel.\")\n@@ -92,6 +100,13 @@ def train_and_save():\nFLAGS.num_epochs,\nwith_classifier=FLAGS.model_classifier_layer)\n+ if FLAGS.serving_batch_size == -1:\n+ # Batch-polymorphic SavedModel\n+ input_signatures = [\n+ tf.TensorSpec((None,) + mnist_lib.input_shape, tf.float32),\n+ ]\n+ polymorphic_shapes = \"(batch, ...)\"\n+ else:\ninput_signatures = [\n# The first one will be the serving signature\ntf.TensorSpec((FLAGS.serving_batch_size,) + mnist_lib.input_shape,\n@@ -101,6 +116,7 @@ def train_and_save():\ntf.TensorSpec((mnist_lib.test_batch_size,) + mnist_lib.input_shape,\ntf.float32),\n]\n+ polymorphic_shapes = None\nlogging.info(f\"Saving model for {model_descr}\")\nsaved_model_lib.convert_and_save_model(\n@@ -108,6 +124,7 @@ def train_and_save():\npredict_params,\nmodel_dir,\ninput_signatures=input_signatures,\n+ polymorphic_shapes=polymorphic_shapes,\ncompile_model=FLAGS.compile_model)\nif FLAGS.test_savedmodel:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main_test.py", "diff": "@@ -36,16 +36,16 @@ class SavedModelMainTest(tf_test_util.JaxToTfTestCase):\nFLAGS.test_savedmodel = True\nFLAGS.mock_data = True\n- # @parameterized.named_parameters(\n- # dict(\n- # testcase_name=f\"_{model}_batch={serving_batch_size}\",\n- # model=model,\n- # serving_batch_size=serving_batch_size)\n- # for model in [\"mnist_pure_jax\", \"mnist_flax\"]\n- # for serving_batch_size in [1])\n+ @parameterized.named_parameters(\n+ dict(\n+ testcase_name=f\"_{model}_batch={serving_batch_size}\",\n+ model=model,\n+ serving_batch_size=serving_batch_size)\n+ for model in [\"mnist_pure_jax\", \"mnist_flax\"]\n+ for serving_batch_size in [1, -1])\ndef test_train_and_save_full(self,\n- model=\"mnist_flax\",\n- serving_batch_size=1):\n+ model=\"mnist_pure_jax\",\n+ serving_batch_size=-1):\nFLAGS.model = model\nFLAGS.model_classifier_layer = True\nFLAGS.serving_batch_size = serving_batch_size\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/serving/README.md", "new_path": "jax/experimental/jax2tf/examples/serving/README.md", "diff": "@@ -58,8 +58,12 @@ again using a recent \"nightly\" version. Install Docker and then run.\nMODEL_PATH=/tmp/jax2tf/saved_models\n# The example model. The options are \"mnist_flax\" and \"mnist_pure_jax\"\nMODEL=mnist_flax\n- # The batch size for the SavedModel.\n- SERVING_BATCH_SIZE=1\n+ # The batch size for the SavedModel. Use -1 for batch-polymorphism,\n+ # or a strictly positive value for a fixed batch size.\n+ SERVING_BATCH_SIZE_SAVE=-1\n+ # The batch size to send to the model. Must be equal to SERVING_BATCH_SIZE_SAVE\n+ # if not -1.\n+ SERVING_BATCH_SIZE=16\n# Increment this when you make changes to the model parameters after the\n# initial model generation (Step 1 below).\nMODEL_VERSION=$(( 1 + ${MODEL_VERSION:-0} ))\n@@ -71,7 +75,7 @@ again using a recent \"nightly\" version. Install Docker and then run.\n```shell\npython ${JAX2TF_EXAMPLES}/saved_model_main.py --model=${MODEL} \\\n--model_path=${MODEL_PATH} --model_version=${MODEL_VERSION} \\\n- --serving_batch_size=${SERVING_BATCH_SIZE} \\\n+ --serving_batch_size=${SERVING_BATCH_SIZE_SAVE} \\\n--compile_model \\\n--noshow_model\n```\n@@ -83,6 +87,9 @@ again using a recent \"nightly\" version. Install Docker and then run.\nsaved_model_cli show --all --dir ${MODEL_PATH}/${MODEL}/${MODEL_VERSION}\n```\n+ If you see a `-1` as the first element of the `shape`, then you have\n+ a batch polymorphic model.\n+\n3. *Start a local model server* with XLA compilation enabled. Execute:\n```shell\n@@ -113,14 +120,18 @@ again using a recent \"nightly\" version. Install Docker and then run.\nthen your serving batch size is 16 (= 12544 / 784) while the model loaded\nin the model server has batch size 1 (= 784 / 784). You should check that\nyou are using the same --serving_batch_size for the model generation and\n- for sending the requests.\n+ for sending the requests (or are using batch-polymorphic model generation.)\n5. *Experiment with different models and batch sizes*.\n- You can set `MODEL=mnist_pure_jax` to use a simpler model, using just\npure JAX, then restart from Step 1.\n+ - If you created a batch-polymorphic models (`SERVING_BATCH_SIZE_SAVE=-1`)\n+ then you can vary `SERVING_BATCH_SIZE` and retry from Step 4.\n+\n- You can change the batch size at which the model is converted from JAX\n- and saved. Set `SERVING_BATCH_SIZE=16` and restart from Step 2.\n+ and saved. Set `SERVING_BATCH_SIZE_SAVE=16` and `SERVING_BATCH_SIZE=16`\n+ and redo Step 2 and Step 4 (do not need to restart the model server).\nIn Step 4, you should pass a `--count_images`\nparameter that is a multiple of the serving batch size you choose.\n" }, { "change_type": "ADD", "old_path": "jax/experimental/jax2tf/examples/serving/__init__.py", "new_path": "jax/experimental/jax2tf/examples/serving/__init__.py", "diff": "" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/serving/model_server_request.py", "new_path": "jax/experimental/jax2tf/examples/serving/model_server_request.py", "diff": "@@ -23,7 +23,7 @@ import requests\nfrom absl import app\nfrom absl import flags\n-from jax.experimental.jax2tf.examples import mnist_lib\n+from jax.experimental.jax2tf.examples import mnist_lib # type: ignore\nimport numpy as np\nimport tensorflow as tf # type: ignore\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Upgraded examples and tests to allow shape polymorphism
260,287
15.04.2021 09:01:49
25,200
3c003a68fcc2ecea575a58bae033b951fc0e08a5
Split up the HLO compilation from HLO generation in mesh_callable.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1430,7 +1430,20 @@ def mesh_callable(fun: lu.WrappedFun,\n# TODO: Warn about unused donations?\nbuilt = c.Build(out_tuple)\n- # 4. Compile the HLO\n+ return compile_and_wrap_mesh_hlo(built, backend, mesh, local_in_untiled_avals,\n+ local_out_untiled_avals, in_axes, out_axes,\n+ spmd_lowering, tuple_args)\n+\n+\n+def compile_and_wrap_mesh_hlo(computation: xc.XlaComputation, backend,\n+ mesh: Mesh,\n+ local_in_untiled_avals: Sequence[ShapedArray],\n+ local_out_untiled_avals: Sequence[ShapedArray],\n+ in_axes: Sequence[ArrayMapping],\n+ out_axes: Sequence[ArrayMapping],\n+ spmd_lowering: bool, tuple_args: bool):\n+ local_mesh = mesh.local_mesh\n+ local_axis_sizes = local_mesh.shape\nif spmd_lowering:\nnum_replicas, num_partitions = 1, mesh.size\nnum_local_replicas, num_local_partitions = 1, local_mesh.size\n@@ -1445,9 +1458,8 @@ def mesh_callable(fun: lu.WrappedFun,\nuse_spmd_partitioning=spmd_lowering,\n)\ncompile_options.parameter_is_tupled_arguments = tuple_args\n- compiled = xla.backend_compile(backend, built, compile_options)\n+ compiled = xla.backend_compile(backend, computation, compile_options)\n- # 5. Argument sharding / output wrapping\nlocal_sharding_spec = mesh_sharding_specs(local_axis_sizes, mesh.axis_names)\nlocal_input_specs = [local_sharding_spec(aval, aval_in_axes)\nif aval is not core.abstract_unit else None\n" } ]
Python
Apache License 2.0
google/jax
Split up the HLO compilation from HLO generation in mesh_callable. PiperOrigin-RevId: 368649553