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 | 16.06.2021 13:25:56 | -10,800 | e405a73663adaa1abf739ba789feb5943f72a54a | [call_tf] Fixed the handling of x64 values in JAX_ENABLE_X64=False
TensorFlow interprets Python scalars in x64 mode, or it may contain
explicit x64 computation. When used with call_tf, we canonicalize
inputs and outputs using the JAX rules. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -28,6 +28,7 @@ from typing import Callable, Sequence\nimport jax\nfrom jax import core\nfrom jax import dlpack\n+from jax import dtypes\nfrom jax import numpy as jnp\nfrom jax import tree_util\nfrom jax._src import util\n@@ -39,6 +40,8 @@ from . import jax2tf as jax2tf_internal\nimport numpy as np\nimport tensorflow as tf # type: ignore[import]\n+map = util.safe_map\n+zip = util.safe_zip\nxops = xla_client._xla.ops # type: ignore\n# The platforms for which to use DLPack to avoid copying (only works on GPU\n@@ -81,17 +84,21 @@ def call_tf(func_tf: Callable) -> Callable:\ndef make_call(*args_jax):\n\"\"\"We wrap it all in `make_call` so that we can attach custom VJP.\"\"\"\n- def _dtype(x):\n- return (getattr(x, \"dtype\", None) or np.asarray(x).dtype)\n-\nargs_jax_flat, args_jax_treedef = tree_util.tree_flatten(args_jax)\n+ # Canonicalize the arguments; e.g., makes them x32 if JAX is in 32-bit mode\n+ def canonical_arg(v):\n+ v = v if getattr(v, \"dtype\", None) else np.asarray(v)\n+ dtype = dtypes.canonicalize_dtype(v.dtype)\n+ if dtype != v.dtype:\n+ v = v.astype(dtype)\n+ return v\n+\n+ args_jax_flat = tuple(map(canonical_arg, args_jax_flat))\nargs_tf_sig_flat = [\n- tf.TensorSpec(np.shape(a_jax), jax2tf_internal._to_tf_dtype(_dtype(a_jax)))\n+ tf.TensorSpec(a_jax.shape, jax2tf_internal._to_tf_dtype(a_jax.dtype))\nfor a_jax in args_jax_flat\n]\n- args_tf_sig = tf.nest.map_structure(\n- lambda a_jax: tf.TensorSpec(\n- np.shape(a_jax), jax2tf_internal._to_tf_dtype(_dtype(a_jax))), args_jax)\n+ args_tf_sig = args_jax_treedef.unflatten(args_tf_sig_flat)\n# Trace once through the function to get the result shape\nwith jax2tf_internal.inside_call_tf():\n@@ -100,6 +107,11 @@ def call_tf(func_tf: Callable) -> Callable:\nres_tf_sig_flat, res_treedef = tree_util.tree_flatten(\nfunc_tf_concrete.structured_outputs)\n+ # Canonicalize the result signature; e.g., makes them x32 if JAX is in 32-bit mode\n+ def res_sig_to_aval(res_sig: tf.TensorSpec) -> core.AbstractValue:\n+ return core.ShapedArray(res_sig.shape, jax2tf_internal._to_jax_dtype(res_sig.dtype))\n+\n+ out_avals = tuple(map(res_sig_to_aval, res_tf_sig_flat))\nres_jax_flat = call_tf_p.bind(\n*args_jax_flat,\n# Carry the actual function such that op-by-op call can call in TF eager mode.\n@@ -108,9 +120,9 @@ def call_tf(func_tf: Callable) -> Callable:\nargs_treedef=args_jax_treedef,\nargs_tf_sig_flat=args_tf_sig_flat,\nres_treedef=res_treedef,\n- res_tf_sig_flat=res_tf_sig_flat)\n+ out_avals=out_avals)\n# TODO(necula): check the expected result signature\n- assert len(res_jax_flat) == len(res_tf_sig_flat)\n+ assert len(res_jax_flat) == len(out_avals)\nreturn res_treedef.unflatten(res_jax_flat)\n# Define the fwd and bwd custom_vjp functions\n@@ -161,7 +173,7 @@ call_tf_p.multiple_results = True\n# The impl will be used in op-by-op mode and calls func_tf in TF eager mode.\n-def _call_tf_impl(*args_jax_flat, args_treedef, func_tf, **_):\n+def _call_tf_impl(*args_jax_flat, args_treedef, func_tf, out_avals, **_):\n# On GPU we use dlpack to avoid copies of data to the host.\ndef _arg_jax_to_tf(arg_jax):\nif (isinstance(arg_jax, xla.DeviceArray) and\n@@ -181,7 +193,8 @@ def _call_tf_impl(*args_jax_flat, args_treedef, func_tf, **_):\nres_tf_flat, _ = tree_util.tree_flatten(res_tf)\n# TODO(necula): check the result for tree and aval\n- def _res_tf_to_jax(res_tf):\n+ def _res_tf_to_jax(res_tf: TfVal, out_aval: core.AbstractValue):\n+ res_tf, _ = jax2tf_internal._tfval_to_tensor_jax_dtype(res_tf, jax_dtype=out_aval.dtype)\nif isinstance(res_tf, tf.Tensor) and res_tf.dtype in dlpack.SUPPORTED_DTYPES:\nres_tf_platform = tf.DeviceSpec.from_string(res_tf.backing_device).device_type\nres_jax_platform = res_tf_platform.lower()\n@@ -192,24 +205,21 @@ def _call_tf_impl(*args_jax_flat, args_treedef, func_tf, **_):\nreturn jnp.asarray(np.asarray(res_tf))\n- return list(map(_res_tf_to_jax, res_tf_flat))\n+ return list(map(_res_tf_to_jax, res_tf_flat, out_avals))\ncall_tf_p.def_impl(_call_tf_impl)\n-def _call_tf_abstract_eval(*_, res_tf_sig_flat, **__):\n- return tuple([\n- core.ShapedArray(np.shape(r), jax2tf_internal._to_jax_dtype(r.dtype))\n- for r in res_tf_sig_flat\n- ])\n+def _call_tf_abstract_eval(*_, out_avals, **__):\n+ return out_avals\ncall_tf_p.def_abstract_eval(_call_tf_abstract_eval)\ndef _call_tf_translation_rule(builder, *args_op, func_tf, func_tf_concrete,\n- args_treedef, args_tf_sig_flat, res_tf_sig_flat,\n+ args_treedef, args_tf_sig_flat, out_avals,\n**_):\n# TODO(necula): It seems that we need concrete tensors for get_compiler_ir?\nargs_tf_flat = [\n@@ -248,12 +258,28 @@ def _call_tf_translation_rule(builder, *args_op, func_tf, func_tf_concrete,\nstage=\"hlo_serialized\", device_name=tf_device_name)\ncallee_xla_comp = xla_client.XlaComputation(func_tf_hlo)\nres_tf = xops.Call(builder, callee_xla_comp, args_op + tuple(captured_ops))\n- if len(res_tf_sig_flat) == 1:\n+ if len(out_avals) == 1:\n# TF does not wrap singletons as tuples, but JAX expects tuples because\n# call_tf is a multiple_results primitive.\n- return xops.Tuple(builder, [res_tf])\n+ res_untupled = (res_tf,)\n+ else:\n+ res_untupled = tuple(xops.GetTupleElement(res_tf, i)\n+ for i in range(len(out_avals)))\n+ # We may have to cast the results to x32 for JAX\n+ def canonicalize_res(res, out_aval: core.AbstractValue):\n+ res_dtype = builder.get_shape(res).numpy_dtype()\n+ if res_dtype != out_aval.dtype:\n+ new_etype = xla_client.dtype_to_etype(out_aval.dtype)\n+ return xops.ConvertElementType(res, new_element_type=new_etype)\nelse:\n- return res_tf\n+ return res\n+\n+ canonical_res_untupled = tuple(map(canonicalize_res,\n+ res_untupled,\n+ out_avals))\n+ return xops.Tuple(builder, canonical_res_untupled)\n+\n+\nxla.translations[call_tf_p] = _call_tf_translation_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -61,13 +61,13 @@ class CallTfTest(jtu.JaxTestCase):\n_ = tf.add(1, 1)\nsuper().setUp()\n- #@parameterized_jit\n+ @parameterized_jit\ndef test_eval_scalar_arg(self, with_jit=True):\ndef f_tf(x):\nreturn tf.math.sin(x)\nx = 3.\nres = _maybe_jit(with_jit, jax2tf.call_tf(f_tf))(x)\n- self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+ self.assertAllClose(jnp.sin(x), res)\n@parameterized_jit\ndef test_eval_scalar_res(self, with_jit=False):\n@@ -79,13 +79,13 @@ class CallTfTest(jtu.JaxTestCase):\ndef test_eval_numpy_arg(self, with_jit=False):\nx = np.ones((2, 3), dtype=np.float32)\nres = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\n- self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+ self.assertAllClose(jnp.sin(x), res)\n@parameterized_jit\ndef test_eval_numpy_res(self, with_jit=False):\n- x = np.ones((2, 3), dtype=np.float32)\n+ x = np.ones((2, 3))\nres = _maybe_jit(with_jit, jax2tf.call_tf(lambda _: x))(x)\n- self.assertAllClose(x, res, check_dtypes=False)\n+ self.assertAllClose(x, res)\ndef test_eval_numpy_no_copy(self):\nif jtu.device_under_test() != \"cpu\":\n@@ -100,14 +100,14 @@ class CallTfTest(jtu.JaxTestCase):\ndef test_eval_devicearray_arg(self, with_jit=False):\nx = jnp.ones((2, 3), dtype=np.float32)\nres = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\n- self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+ self.assertAllClose(jnp.sin(x), res)\ndef test_eval_devicearray_no_copy(self):\nif jtu.device_under_test() != \"cpu\":\n# TODO(necula): add tests for GPU and TPU\nraise unittest.SkipTest(\"no_copy test works only on CPU\")\n# For DeviceArray zero-copy works even if not aligned\n- x = jnp.ones((3, 3), dtype=np.float32)\n+ x = jnp.ones((3, 3))\nres = jax2tf.call_tf(lambda x: x)(x)\nself.assertAllClose(x, res)\nself.assertTrue(np.shares_memory(x, res))\n@@ -160,8 +160,7 @@ class CallTfTest(jtu.JaxTestCase):\ntestcase_name=f\"_{dtype.__name__}{'_jit' if with_jit else ''}\",\ndtype=dtype,\nwith_jit=with_jit)\n- # TF does not support yet add for uint16 and uint64\n- for dtype in set(jtu.dtypes.all) - set([np.bool_, np.uint16, np.uint64])\n+ for dtype in set(jtu.dtypes.all) - set([np.bool_])\nfor with_jit in [True, False])\ndef test_dtypes(self, dtype=np.int32, with_jit=True):\n@@ -188,6 +187,27 @@ class CallTfTest(jtu.JaxTestCase):\nself.assertAllClose(\nnp.array([True, False, False, False], dtype=np.bool_), res)\n+ def test_x64_input(self):\n+ def f_tf(x):\n+ return tf.math.sin(x)\n+\n+ x = 5. # TF interprets this as f64\n+ res_call_tf = jax2tf.call_tf(f_tf)(x)\n+ res_jax = jnp.sin(x)\n+ self.assertAllClose(res_call_tf, res_jax)\n+\n+ def test_x64_output(self):\n+ def f_tf(x):\n+ return (tf.constant(3., tf.float64), x)\n+\n+ x = np.float32(5.)\n+ res_call_tf = jax2tf.call_tf(f_tf)(x)\n+ res_jax = (3., x)\n+ self.assertAllClose(res_call_tf, res_jax)\n+\n+ res_call_tf_jit = jax.jit(jax2tf.call_tf(f_tf))(x)\n+ self.assertAllClose(res_call_tf_jit, res_jax)\n+\n@parameterized_jit\ndef test_with_var_read(self, with_jit=True):\nif jtu.device_under_test() == \"gpu\":\n"
}
] | Python | Apache License 2.0 | google/jax | [call_tf] Fixed the handling of x64 values in JAX_ENABLE_X64=False
TensorFlow interprets Python scalars in x64 mode, or it may contain
explicit x64 computation. When used with call_tf, we canonicalize
inputs and outputs using the JAX rules. |
260,411 | 15.06.2021 08:37:01 | -10,800 | d394f6917b2c3b938b7f9809e46e1930710d33f7 | Added clipping of OOB indices to match XLA behavior | [
{
"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-06-14*\n+*Last generated on (YYYY-MM-DD): 2021-06-15*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -85,7 +85,6 @@ More detailed information can be found in the\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 error: TF function not compileable | complex128, float64 | cpu, gpu | compiled |\n-| gather | TF error: TF function aborts for index out-of-bounds, when enable_xla=False | all | cpu, gpu | eager, graph |\n| igamma | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| igammac | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| integer_pow | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu | graph |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -2269,11 +2269,14 @@ def _gather_without_xla(operand: TfVal,\n\"gather\",\nf\"unexpected slice_sizes {slice_sizes} != {expected_slice_sizes}\")\n- reshape_shape = _eval_shape(start_indices_shape[0:-1])\n- start_indices_reshaped = tf.reshape(start_indices, reshape_shape)\n- # TODO: handle out-of-bounds accesses. For now in eager and graph mode\n- # TF aborts, so at least it is a loud error. JAX clamps the indices.\n- return tf.gather(operand, start_indices_reshaped, axis=axis, batch_dims=0)\n+ start_indices_reshaped = tf.reshape(start_indices,\n+ _eval_shape(start_indices_shape[0:-1]))\n+ start_indices_clipped = tf.clip_by_value(\n+ start_indices_reshaped,\n+ tf.constant(0, dtype=start_indices_reshaped.dtype),\n+ tf.subtract(tf.cast(_eval_shape(op_shape)[axis], start_indices_reshaped.dtype),\n+ tf.constant(1, dtype=start_indices_reshaped.dtype)))\n+ return tf.gather(operand, start_indices_clipped, axis=axis, batch_dims=0)\n@partial(bool_to_int8, argnums=[0])\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -128,7 +128,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n\"bitcast_convert_type\", \"broadcast\", \"broadcast_in_dim\", \"ceil\", \"clamp\",\n\"concatenate\", \"cos\", \"cosh\", \"complex\", \"conj\", \"convert_element_type\",\n\"cummax\", \"cummin\", \"device_put\", \"dynamic_slice\",\n- \"dynamic_update_slice\", \"exp\", \"eq\", \"floor\", \"ge\", \"gt\", \"imag\",\n+ \"dynamic_update_slice\", \"exp\", \"eq\", \"floor\", \"gather\", \"ge\", \"gt\", \"imag\",\n\"iota\", \"is_finite\", \"le\", \"lt\", \"log\", \"mul\", \"ne\", \"neg\", \"not\",\n\"or\", \"pad\", \"population_count\", \"random_split\",\n\"reduce_and\", \"reduce_prod\", \"reduce_or\", \"reduce_sum\",\n@@ -600,25 +600,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ncustom_numeric(tol=1e-3, modes=(\"eager\", \"graph\", \"compiled\")),\n]\n- @classmethod\n- def gather(cls, harness):\n- return [\n- Jax2TfLimitation(\n- \"TF function aborts for index out-of-bounds, when enable_xla=False\",\n- devices=\"cpu\",\n- modes=(\"eager\", \"graph\"),\n- enabled=(not harness.params[\"enable_xla\"] and harness.params.get(\"index_oob\", False))),\n- # On GPU, it seems that tf.gather returns 0s for OOB indices in eager\n- # and graph modes.\n- # TODO: Remove when we implement OOB index handling\n- custom_numeric(\n- description=\"TF produces different results for index out-of-bounds, when enable_xla=False\",\n- devices=\"gpu\",\n- modes=(\"eager\", \"graph\"),\n- custom_assert=lambda *_, **__: None, # Just skip the comparison\n- enabled=(not harness.params[\"enable_xla\"] and harness.params.get(\"index_oob\", False))),\n- ]\n-\n@classmethod\ndef _pow_test_util(cls, harness: primitive_harness.Harness):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -1123,22 +1123,22 @@ for dtype in set(jtu.dtypes.all):\n# Construct gather harnesses using take\n_gather_input = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))\n-for indices, index_oob in [\n- # Ensure each set of indices has a distinct shape\n- (np.array(2, dtype=np.int32), False),\n- (np.array([2], dtype=np.int32), False),\n- (np.array([2, 4], dtype=np.int32), False),\n- (np.array([[2, 4], [5, 6]], dtype=np.int32), False),\n- (np.array([0, 1, 10], dtype=np.int32), True), # Index out of bounds too high\n- (np.array([0, 1, 2, -1], dtype=np.int32), False), # Index out of bounds, but works\n- (np.array([0, 1, 2, 3, -10], dtype=np.int32), False), # Index out of bounds, but works\n- (np.array([0, 1, 2, 3, 4, -11], dtype=np.int32), True) # Index out of bounds, too low\n+for indices, index_oob, indices_name in [\n+ # Ensure each set of indices has a distinct name\n+ (np.array(2, dtype=np.int32), False, \"1\"),\n+ (np.array([2], dtype=np.int32), False, \"2\"),\n+ (np.array([2, 4], dtype=np.int32), False, \"3\"),\n+ (np.array([[2, 4], [5, 6]], dtype=np.int32), False, \"4\"),\n+ (np.array([[0], [1], [10]], dtype=np.int32), True, \"5_oob\"), # Index out of bounds too high\n+ (np.array([[0, 1], [2, -1]], dtype=np.int32), False, \"6_neg\"), # Negative index is from the end\n+ (np.array([0, 1, 2, 3, -10], dtype=np.int32), False, \"7_neg\"), # Index out of bounds, but works\n+ (np.array([[[0], [1]], [[3], [-11]]], dtype=np.int32), True, \"8_neg_oob\") # Index out of bounds, too low\n]:\nfor axis in [0, 1, 2]:\nfor enable_xla in [True, False]:\ndefine(\nlax.gather_p,\n- f\"from_take_indices_shape={indices.shape}_axis={axis}_enable_xla={enable_xla}\",\n+ f\"from_take_indices_name={indices_name}_axis={axis}_enable_xla={enable_xla}\",\nlambda a, i, axis: jnp.take(a, i, axis=axis),\n[_gather_input, indices, StaticArg(axis)],\ndtype=_gather_input.dtype,\n"
}
] | Python | Apache License 2.0 | google/jax | Added clipping of OOB indices to match XLA behavior |
260,374 | 02.06.2021 17:05:26 | 0 | 0e9f7de6c839c31ed1a9e5574841865921bb522f | Add LRU eviction policy to persisent compilation cache | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/file_system_cache.py",
"new_path": "jax/experimental/compilation_cache/file_system_cache.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-from typing import Optional\nimport os\n+from typing import Optional\n+import warnings\nclass FileSystemCache:\n- def __init__(self, path: str):\n+ def __init__(self, path: str, max_cache_size_bytes=32 * 2**30):\n\"\"\"Sets up a cache at 'path'. Cached values may already be present.\"\"\"\nos.makedirs(path, exist_ok=True)\nself._path = path\n+ self._max_cache_size_bytes = max_cache_size_bytes\ndef get(self, key: str) -> Optional[bytes]:\n\"\"\"Returns None if 'key' isn't present.\"\"\"\n@@ -37,6 +39,35 @@ class FileSystemCache:\n\"\"\"Adds new cache entry, possibly evicting older entries.\"\"\"\nif not key:\nraise ValueError(\"key cannot be empty\")\n- #TODO(colemanliyah):implement eviction\n- with open(os.path.join(self._path, key), \"wb\") as file:\n+ if self._evict_entries_if_necessary(key, value):\n+ path_to_new_file = os.path.join(self._path, key)\n+ with open(path_to_new_file, \"wb\") as file:\nfile.write(value)\n+ else:\n+ warnings.warn(f\"Cache value of size {len(value)} is larger than\"\n+ f\" the max cache size of {self._max_cache_size_bytes}\")\n+\n+ def _evict_entries_if_necessary(self, key: str, value: bytes) -> bool:\n+ \"\"\"Returns True if there's enough space to add 'value', False otherwise.\"\"\"\n+ new_file_size = len(value)\n+\n+ if new_file_size >= self._max_cache_size_bytes:\n+ return False\n+\n+ #TODO(colemanliyah): Refactor this section so the whole directory doesn't need to be checked\n+ while new_file_size + self._get_cache_directory_size() > self._max_cache_size_bytes:\n+ last_time = float('inf')\n+ file_to_delete = None\n+ for file_name in os.listdir(self._path):\n+ file_to_inspect = os.path.join(self._path, file_name)\n+ atime = os.stat(file_to_inspect).st_atime\n+ if atime < last_time:\n+ last_time = atime\n+ file_to_delete = file_to_inspect\n+ assert file_to_delete\n+ os.remove(file_to_delete)\n+ return True\n+\n+ def _get_cache_directory_size(self):\n+ \"\"\"Retrieves the current size of the directory, self.path\"\"\"\n+ return sum(os.path.getsize(f) for f in os.scandir(self._path) if f.is_file())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/file_system_cache_test.py",
"new_path": "tests/file_system_cache_test.py",
"diff": "@@ -16,6 +16,7 @@ from absl.testing import absltest\nfrom jax.experimental.compilation_cache.file_system_cache import FileSystemCache\nimport jax.test_util as jtu\nimport tempfile\n+import time\nclass FileSystemCacheTest(jtu.JaxTestCase):\n@@ -56,5 +57,70 @@ class FileSystemCacheTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError , r\"key cannot be empty\"):\ncache.get(\"\")\n+ def test_size_of_directory(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir)\n+ cache.put(\"foo\", b\"bar\")\n+ self.assertEqual(cache._get_cache_directory_size(), 3)\n+\n+ def test_size_of_empty_directory(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir)\n+ self.assertEqual(cache._get_cache_directory_size(), 0)\n+\n+ def test_size_of_existing_directory(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache1 = FileSystemCache(tmpdir)\n+ cache1.put(\"foo\", b\"bar\")\n+ del cache1\n+ cache2 = FileSystemCache(tmpdir)\n+ self.assertEqual(cache2._get_cache_directory_size(), 3)\n+\n+ def test_cache_is_full(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n+ cache.put(\"first\", b\"one\")\n+ # Sleep because otherwise these operations execute too fast and\n+ # the access time isn't captured properly.\n+ time.sleep(1)\n+ cache.put(\"second\", b\"two\")\n+ cache.put(\"third\", b\"the\")\n+ self.assertEqual(cache.get(\"first\"), None)\n+ self.assertEqual(cache.get(\"second\"), b\"two\")\n+ self.assertEqual(cache.get(\"third\"), b\"the\")\n+\n+ def test_delete_multiple_files(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n+ cache.put(\"first\", b\"one\")\n+ # Sleep because otherwise these operations execute too fast and\n+ # the access time isn't captured properly.\n+ time.sleep(1)\n+ cache.put(\"second\", b\"two\")\n+ cache.put(\"third\", b\"three\")\n+ self.assertEqual(cache.get(\"first\"), None)\n+ self.assertEqual(cache.get(\"second\"), None)\n+ self.assertEqual(cache.get(\"third\"), b\"three\")\n+\n+ def test_least_recently_accessed_file(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir, max_cache_size_bytes=6)\n+ cache.put(\"first\", b\"one\")\n+ cache.put(\"second\", b\"two\")\n+ # Sleep because otherwise these operations execute too fast and\n+ # the access time isn't captured properly.\n+ time.sleep(1)\n+ cache.get(\"first\")\n+ cache.put(\"third\", b\"the\")\n+ self.assertEqual(cache.get(\"first\"), b\"one\")\n+ self.assertEqual(cache.get(\"second\"), None)\n+\n+ @jtu.ignore_warning(message=(\"Cache value of size 3 is larger than the max cache size of 2\"))\n+ def test_file_bigger_than_cache(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir, max_cache_size_bytes=2)\n+ cache.put(\"foo\", b\"bar\")\n+ self.assertEqual(cache.get(\"foo\"), None)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add LRU eviction policy to persisent compilation cache |
260,411 | 17.06.2021 14:25:01 | -10,800 | a6c16119c91e61d5e9fbfd8d3bd1dcfe14cb838f | Renaming master to main: step 1.
Here we just enable the GitHub actions to run on both master and main. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci-build.yaml",
"new_path": ".github/workflows/ci-build.yaml",
"diff": "@@ -2,13 +2,15 @@ name: CI\non:\n# Trigger the workflow on push or pull request,\n- # but only for the master branch\n+ # but only for the main branch\npush:\nbranches:\n- master\n+ - main\npull_request:\nbranches:\n- master\n+ - main\njobs:\nlint_and_typecheck:\n@@ -19,7 +21,7 @@ jobs:\nuses: styfle/cancel-workflow-action@0.8.0\nwith:\naccess_token: ${{ github.token }}\n- if: ${{github.ref != 'refs/head/master'}}\n+ if: ${{github.ref != 'refs/head/master' && github.ref != 'refs/head/main'}}\n- uses: actions/checkout@v2\n- name: Set up Python 3.8\nuses: actions/setup-python@v2\n@@ -65,7 +67,7 @@ jobs:\nuses: styfle/cancel-workflow-action@0.7.0\nwith:\naccess_token: ${{ github.token }}\n- if: ${{github.ref != 'refs/head/master'}}\n+ if: ${{github.ref != 'refs/head/master' && github.ref != 'refs/head/main'}}\n- uses: actions/checkout@v2\n- name: Set up Python ${{ matrix.python-version }}\nuses: actions/setup-python@v2\n@@ -112,7 +114,7 @@ jobs:\nuses: styfle/cancel-workflow-action@0.7.0\nwith:\naccess_token: ${{ github.token }}\n- if: ${{github.ref != 'refs/head/master'}}\n+ if: ${{github.ref != 'refs/head/master' && github.ref != 'refs/head/main'}}\n- uses: actions/checkout@v2\n- name: Set up Python ${{ matrix.python-version }}\nuses: actions/setup-python@v2\n"
}
] | Python | Apache License 2.0 | google/jax | Renaming master to main: step 1.
Here we just enable the GitHub actions to run on both master and main. |
260,411 | 17.06.2021 14:48:21 | -10,800 | 0ec53eec72b855dbd053b2464ea9b3a0422b6c09 | Test PR merged to main, before making main default
Want to see the GitHub actions working, and copybara import | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -912,6 +912,7 @@ to generate tables of limitations, e.g.,\ne.g., due to unimplemented cases in TensorFlow. This list is incremental\non top of the unsupported JAX primitives.\n+\nThere are instructions for updating those documents at the end of each\ndocument.\n"
}
] | Python | Apache License 2.0 | google/jax | Test PR merged to main, before making main default
Want to see the GitHub actions working, and copybara import |
260,411 | 17.06.2021 15:58:51 | -10,800 | 268a242c65f634d5d380fa9357fe9b271d5be9e6 | Test 5 for rename master to main | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -892,6 +892,7 @@ As of today, the tests are run using `tf_nightly==2.6.0-dev20210611`.\n## Running on GPU\n+\nTo run jax2tf on GPU, both jaxlib and TensorFlow must be installed with support\nfor 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"
}
] | Python | Apache License 2.0 | google/jax | Test 5 for rename master to main |
260,411 | 17.06.2021 16:08:54 | -10,800 | 4fa1506825337c5fff343e27299ffbd94e02d980 | One more change, to tickle copybara | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -890,6 +890,7 @@ in [call_tf_test.py](https://github.com/google/jax/blob/master/jax/experimental/\nThe ``jax2tf.convert`` and `call_tf` require very recent versions of TensorFlow.\nAs of today, the tests are run using `tf_nightly==2.6.0-dev20210611`.\n+\n## Running on GPU\n"
}
] | Python | Apache License 2.0 | google/jax | One more change, to tickle copybara |
260,563 | 17.06.2021 19:25:46 | -7,200 | ccc8bb7f19321402caa9c8d6a02999f74c795ea8 | Add auxiliary data support to lax.custom_root | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -2018,7 +2018,7 @@ def _split_root_args(args, const_lengths):\n@api_boundary\n-def custom_root(f, initial_guess, solve, tangent_solve):\n+def custom_root(f, initial_guess, solve, tangent_solve, has_aux=False):\n\"\"\"Differentiably solve for a roots of a function.\nThis is a low-level routine, mostly intended for internal use in JAX.\n@@ -2049,6 +2049,8 @@ def custom_root(f, initial_guess, solve, tangent_solve):\n- For vector ``y``, you could use a linear solve with the Jacobian, if\ndimensionality of ``y`` is not too large:\n``lambda g, y: np.linalg.solve(jacobian(g)(y), y)``.\n+ has_aux: bool indicating whether the ``solve`` function returns\n+ auxiliary data like solver diagnostics as a second argument.\nReturns:\nThe result of calling solve(f, initial_guess) with gradients defined via\n@@ -2060,11 +2062,11 @@ def custom_root(f, initial_guess, solve, tangent_solve):\nf, in_args_tree, guess_avals)\nin_tree, = treedef_children(in_args_tree)\n- _check_tree(\"f\", \"initial_guess\", out_tree, in_tree)\n+ _check_tree(\"f\", \"initial_guess\", out_tree, in_tree, False)\nsolve_jaxpr, solve_consts, solution_tree = _initial_style_jaxpr(\npartial(solve, _stop_gradient_fun(f)), in_args_tree, guess_avals)\n- _check_tree(\"solve\", \"initial_guess\", solution_tree, in_tree)\n+ _check_tree(\"solve\", \"initial_guess\", solution_tree, in_tree, has_aux)\ndef linearize_and_solve(x, b):\nunchecked_zeros, f_jvp = jax.linearize(f, x)\n@@ -2072,15 +2074,15 @@ def custom_root(f, initial_guess, solve, tangent_solve):\nl_and_s_jaxpr, l_and_s_consts, out_tree = _initial_style_jaxpr(\nlinearize_and_solve, treedef_tuple((in_tree,) * 2), guess_avals * 2)\n- _check_tree(\"tangent_solve\", \"x\", out_tree, in_tree)\n+ _check_tree(\"tangent_solve\", \"x\", out_tree, in_tree, False)\nall_consts = [f_consts, solve_consts, l_and_s_consts]\nconst_lengths = _RootTuple(*_map(len, all_consts))\njaxprs = _RootTuple(f_jaxpr, solve_jaxpr, l_and_s_jaxpr)\n- out_flat = _custom_root(\n+ solution_flat = _custom_root(\nconst_lengths, jaxprs, *(_flatten(all_consts) + guess_flat))\n- return tree_unflatten(out_tree, out_flat)\n+ return tree_unflatten(solution_tree, solution_flat)\n@partial(jax.custom_jvp, nondiff_argnums=(0, 1))\n@@ -2093,7 +2095,10 @@ def _custom_root(const_lengths, jaxprs, *args):\n@_custom_root.defjvp\ndef _root_jvp(const_lengths, jaxprs, primals, tangents):\nparams, _ = _split_root_args(primals, const_lengths)\n- solution = _custom_root(const_lengths, jaxprs, *primals)\n+ sol = _custom_root(const_lengths, jaxprs, *primals)\n+\n+ f_out_vals = len(jaxprs.f.out_avals)\n+ solution, aux = split_list(sol, [f_out_vals])\nparams_dot, _ = _split_root_args(tangents, const_lengths)\n@@ -2114,6 +2119,9 @@ def _root_jvp(const_lengths, jaxprs, primals, tangents):\nparams.f, params_dot.f)\nsolution_dot = _map(\noperator.neg, linearize_and_solve(*itertools.chain(solution, rhs)))\n+ # append aux, create symbolic zero tangents for the aux values\n+ solution += aux\n+ solution_dot += _map(lax.zeros_like_array, aux)\nreturn solution, solution_dot\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -2019,6 +2019,47 @@ class LaxControlFlowTest(jtu.JaxTestCase):\njtu.check_grads(lambda x, y: linear_solve(high_precision_dot(x, x.T), y),\n(a, b), order=2, rtol={jnp.float32: 1e-2})\n+ def test_custom_root_with_aux(self):\n+ def root_aux(a, b):\n+ f = lambda x: high_precision_dot(a, x) - b\n+ factors = jsp.linalg.cho_factor(a)\n+ cho_solve = lambda f, b: (jsp.linalg.cho_solve(factors, b), orig_aux)\n+\n+ def pos_def_solve(g, b):\n+ # prune aux to allow use as tangent_solve\n+ cho_solve_noaux = lambda f, b: cho_solve(f, b)[0]\n+ return lax.custom_linear_solve(g, b, cho_solve_noaux, symmetric=True)\n+\n+ return lax.custom_root(f, b, cho_solve, pos_def_solve, has_aux=True)\n+\n+ orig_aux = {\"converged\": np.array(1.), \"nfev\": np.array(12345.), \"grad\": np.array([1.0, 2.0, 3.0])}\n+\n+ rng = np.random.RandomState(0)\n+ a = rng.randn(2, 2)\n+ b = rng.randn(2)\n+\n+ actual, actual_aux = root_aux(high_precision_dot(a, a.T), b)\n+ actual_jit, actual_jit_aux = api.jit(root_aux)(high_precision_dot(a, a.T), b)\n+ expected = jnp.linalg.solve(high_precision_dot(a, a.T), b)\n+\n+ self.assertAllClose(expected, actual)\n+ self.assertAllClose(expected, actual_jit)\n+ jtu.check_eq(actual_jit_aux, orig_aux)\n+\n+ # grad check with aux\n+ jtu.check_grads(lambda x, y: root_aux(high_precision_dot(x, x.T), y),\n+ (a, b), order=2, rtol={jnp.float32: 1e-2})\n+\n+ # test vmap and jvp combined by jacfwd\n+ fwd = jax.jacfwd(lambda x, y: root_aux(high_precision_dot(x, x.T), y), argnums=(0, 1))\n+ expected_fwd = jax.jacfwd(lambda x, y: jnp.linalg.solve(high_precision_dot(x, x.T), y), argnums=(0, 1))\n+\n+ fwd_val, fwd_aux = fwd(a, b)\n+ expected_fwd_val = expected_fwd(a, b)\n+ self.assertAllClose(fwd_val, expected_fwd_val)\n+\n+ jtu.check_close(fwd_aux, tree_util.tree_map(jnp.zeros_like, fwd_aux))\n+\ndef test_custom_root_errors(self):\nwith self.assertRaisesRegex(TypeError, re.escape(\"f() output pytree\")):\nlax.custom_root(lambda x: (x, x), 0.0, lambda f, x: x, lambda f, x: x)\n"
}
] | Python | Apache License 2.0 | google/jax | Add auxiliary data support to lax.custom_root |
260,563 | 17.06.2021 20:26:16 | -7,200 | cba5b13a39028d4389e063d6284cf68ce67afbb2 | Improve concretization errors for jnp indexing routines | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3331,6 +3331,21 @@ def meshgrid(*args, **kwargs):\nreturn output\n+def _make_1d_grid_from_slice(s: slice, op_name: str):\n+ start =core.concrete_or_error(None, s.start,\n+ f\"slice start of jnp.{op_name}\") or 0\n+ stop = core.concrete_or_error(None, s.stop,\n+ f\"slice stop of jnp.{op_name}\")\n+ step = core.concrete_or_error(None, s.step,\n+ f\"slice step of jnp.{op_name}\") or 1\n+ if np.iscomplex(step):\n+ newobj = linspace(start, stop, int(_abs(step)))\n+ else:\n+ newobj = arange(start, stop, step)\n+\n+ return newobj\n+\n+\nclass _IndexGrid:\ndef __getitem__(self, key):\nsingle_slice = isinstance(key, slice)\n@@ -3338,15 +3353,7 @@ class _IndexGrid:\nkey = (key,)\noutput = []\nfor k in key:\n- start = core.concrete_or_error(None, k.start,\n- \"slice start of jnp.mgrid\") or 0\n- stop = core.concrete_or_error(None, k.stop, \"slice stop of jnp.mgrid\")\n- step = core.concrete_or_error(None, k.step,\n- \"slice step of jnp.mgrid\") or 1\n- if np.iscomplex(step):\n- output.append(linspace(start, stop, int(_abs(step))))\n- else:\n- output.append(arange(start, stop, step))\n+ output.append(_make_1d_grid_from_slice(k, op_name=self.op_name))\nif single_slice:\nreturn output[0]\noutput = meshgrid(*output, indexing='ij', sparse=self.sparse)\n@@ -3382,6 +3389,7 @@ class _Mgrid(_IndexGrid):\n[0, 1, 2]]], dtype=int32)\n\"\"\"\nsparse = False\n+ op_name = \"mgrid\"\nmgrid = _Mgrid()\n@@ -3414,23 +3422,12 @@ class _Ogrid(_IndexGrid):\nDeviceArray([[0, 1, 2]], dtype=int32)]\n\"\"\"\nsparse = True\n+ op_name = \"ogrid\"\nogrid = _Ogrid()\n-def _make_1d_grid_from_slice(s: slice):\n- start = s.start or 0\n- stop = s.stop\n- step = s.step or 1\n- if np.iscomplex(step):\n- newobj = linspace(start, stop, int(_abs(step)))\n- else:\n- newobj = arange(start, stop, step)\n-\n- return newobj\n-\n-\nclass _AxisConcat:\n\"\"\"Concatenates slices, scalars and array-like objects along a given axis.\"\"\"\ndef __getitem__(self, key):\n@@ -3467,7 +3464,7 @@ class _AxisConcat:\noutput = []\nfor item in key:\nif isinstance(item, slice):\n- newobj = _make_1d_grid_from_slice(item)\n+ newobj = _make_1d_grid_from_slice(item, op_name=self.op_name)\nelif isinstance(item, str):\nraise ValueError(\"string directive must be placed at the beginning\")\nelse:\n@@ -3566,6 +3563,7 @@ class RClass(_AxisConcat):\naxis = 0\nndmin = 1\ntrans1d = -1\n+ op_name = \"r_\"\nr_ = RClass()\n@@ -3613,6 +3611,7 @@ class CClass(_AxisConcat):\naxis = -1\nndmin = 2\ntrans1d = 0\n+ op_name = \"c_\"\nc_ = CClass()\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -4811,6 +4811,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp.mgrid[1.3:4.2:0.3],\natol=atol,\nrtol=rtol)\n+ # abstract tracer value for jnp.mgrid slice\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError,\n+ \"slice start of jnp.mgrid\"):\n+ jax.jit(lambda a, b: jnp.mgrid[a:b])(0, 2)\ndef testOgrid(self):\ndef assertListOfArraysEqual(xs, ys):\n@@ -4846,6 +4850,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\njnp.ogrid[1.2:4.8:0.24],\natol=atol,\nrtol=rtol)\n+ # abstract tracer value for ogrid slice\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError,\n+ \"slice start of jnp.ogrid\"):\n+ jax.jit(lambda a, b: jnp.ogrid[a:b])(0, 2)\ndef testR_(self):\na = np.arange(6).reshape((2,3))\n@@ -4868,6 +4876,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n# bad directive\nwith self.assertRaisesRegex(ValueError, \"could not understand directive.*\"):\njnp.r_[\"asdfgh\",[1,2,3]]\n+ # abstract tracer value for r_ slice\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError,\n+ \"slice start of jnp.r_\"):\n+ jax.jit(lambda a, b: jnp.r_[a:b])(0, 2)\n# Complex number steps\natol = 1e-6\n@@ -4908,6 +4920,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n# bad directive\nwith self.assertRaisesRegex(ValueError, \"could not understand directive.*\"):\njnp.c_[\"asdfgh\",[1,2,3]]\n+ # abstract tracer value for c_ slice\n+ with self.assertRaisesRegex(jax.core.ConcretizationTypeError,\n+ \"slice start of jnp.c_\"):\n+ jax.jit(lambda a, b: jnp.c_[a:b])(0, 2)\n# Complex number steps\natol = 1e-6\n"
}
] | Python | Apache License 2.0 | google/jax | Improve concretization errors for jnp indexing routines |
260,372 | 11.06.2021 16:40:39 | 21,600 | c33388b1367dd0206c1fef9c1c22ca6a0e0e04ee | Support complex numbers in jax.scipy.signal.convolve/correlate | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/signal.py",
"new_path": "jax/_src/scipy/signal.py",
"diff": "@@ -66,8 +66,6 @@ def convolve(in1, in2, mode='full', method='auto',\nprecision=None):\nif method != 'auto':\nwarnings.warn(\"convolve() ignores method argument\")\n- if jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\n- raise NotImplementedError(\"convolve() does not support complex inputs\")\nreturn _convolve_nd(in1, in2, mode, precision=precision)\n@@ -76,8 +74,6 @@ def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0,\nprecision=None):\nif boundary != 'fill' or fillvalue != 0:\nraise NotImplementedError(\"convolve2d() only supports boundary='fill', fillvalue=0\")\n- if jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\n- raise NotImplementedError(\"convolve2d() does not support complex inputs\")\nif jnp.ndim(in1) != 2 or jnp.ndim(in2) != 2:\nraise ValueError(\"convolve2d() only supports 2-dimensional inputs.\")\nreturn _convolve_nd(in1, in2, mode, precision=precision)\n@@ -88,9 +84,7 @@ def correlate(in1, in2, mode='full', method='auto',\nprecision=None):\nif method != 'auto':\nwarnings.warn(\"correlate() ignores method argument\")\n- if jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\n- raise NotImplementedError(\"correlate() does not support complex inputs\")\n- return _convolve_nd(in1, jnp.flip(in2), mode, precision=precision)\n+ return _convolve_nd(in1, jnp.flip(in2.conj()), mode, precision=precision)\n@_wraps(osp_signal.correlate2d)\n@@ -98,11 +92,30 @@ def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0,\nprecision=None):\nif boundary != 'fill' or fillvalue != 0:\nraise NotImplementedError(\"correlate2d() only supports boundary='fill', fillvalue=0\")\n- if jnp.issubdtype(in1.dtype, jnp.complexfloating) or jnp.issubdtype(in2.dtype, jnp.complexfloating):\n- raise NotImplementedError(\"correlate2d() does not support complex inputs\")\nif jnp.ndim(in1) != 2 or jnp.ndim(in2) != 2:\n- raise ValueError(\"correlate2d() only supports {ndim}-dimensional inputs.\")\n- return _convolve_nd(in1[::-1, ::-1], in2, mode, precision=precision)[::-1, ::-1]\n+ raise ValueError(\"correlate2d() only supports 2-dimensional inputs.\")\n+\n+ swap = all(s1 <= s2 for s1, s2 in zip(in1.shape, in2.shape))\n+ same_shape = all(s1 == s2 for s1, s2 in zip(in1.shape, in2.shape))\n+\n+ if mode == \"same\":\n+ in1, in2 = in1[::-1, ::-1], in2.conj()\n+ result = _convolve_nd(in1, in2, mode, precision=precision)[::-1, ::-1]\n+ elif mode == \"valid\":\n+ if swap and not same_shape:\n+ in1, in2 = in2[::-1, ::-1], in1.conj()\n+ result = _convolve_nd(in1, in2, mode, precision=precision)\n+ else:\n+ in1, in2 = in1[::-1, ::-1], in2.conj()\n+ result = _convolve_nd(in1, in2, mode, precision=precision)[::-1, ::-1]\n+ else:\n+ if swap:\n+ in1, in2 = in2[::-1, ::-1], in1.conj()\n+ result = _convolve_nd(in1, in2, mode, precision=precision).conj()\n+ else:\n+ in1, in2 = in1[::-1, ::-1], in2.conj()\n+ result = _convolve_nd(in1, in2, mode, precision=precision)[::-1, ::-1]\n+ return result\n@_wraps(osp_signal.detrend)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/scipy_signal_test.py",
"new_path": "tests/scipy_signal_test.py",
"diff": "@@ -32,7 +32,7 @@ twodim_shapes = [(1, 1), (2, 2), (2, 3), (3, 4), (4, 4)]\nthreedim_shapes = [(2, 2, 2), (3, 3, 2), (4, 4, 2), (5, 5, 2)]\n-default_dtypes = jtu.dtypes.floating + jtu.dtypes.integer\n+default_dtypes = jtu.dtypes.floating + jtu.dtypes.integer + jtu.dtypes.complex\nclass LaxBackedScipySignalTests(jtu.JaxTestCase):\n@@ -58,9 +58,9 @@ class LaxBackedScipySignalTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]\nosp_fun = partial(osp_op, mode=mode)\njsp_fun = partial(jsp_op, mode=mode, precision=lax.Precision.HIGHEST)\n- tol = {np.float16: 1e-2, np.float32: 1e-2, np.float64: 1e-8}\n+ tol = {np.float16: 1e-2, np.float32: 1e-2, np.float64: 1e-12, np.complex64: 1e-2, np.complex128: 1e-12}\nself._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, check_dtypes=False, tol=tol)\n- self._CompileAndCheck(jsp_fun, args_maker)\n+ self._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"op={}_xshape={}_yshape={}_mode={}\".format(\n@@ -81,7 +81,7 @@ class LaxBackedScipySignalTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(xshape, dtype), rng(yshape, dtype)]\nosp_fun = partial(osp_op, mode=mode)\njsp_fun = partial(jsp_op, mode=mode, precision=lax.Precision.HIGHEST)\n- tol = {np.float16: 1e-2, np.float32: 1e-2, np.float64: 1e-14}\n+ tol = {np.float16: 1e-2, np.float32: 1e-2, np.float64: 1e-12, np.complex64: 1e-2, np.complex128: 1e-12}\nself._CheckAgainstNumpy(osp_fun, jsp_fun, args_maker, check_dtypes=False,\ntol=tol)\nself._CompileAndCheck(jsp_fun, args_maker, rtol=tol, atol=tol)\n@@ -91,7 +91,7 @@ class LaxBackedScipySignalTests(jtu.JaxTestCase):\njtu.format_shape_dtype_string(shape, dtype), axis, type, bp),\n\"shape\": shape, \"dtype\": dtype, \"axis\": axis, \"type\": type, \"bp\": bp}\nfor shape in [(5,), (4, 5), (3, 4, 5)]\n- for dtype in default_dtypes\n+ for dtype in jtu.dtypes.floating + jtu.dtypes.integer\nfor axis in [0, -1]\nfor type in ['constant', 'linear']\nfor bp in [0, [0, 2]]))\n"
}
] | Python | Apache License 2.0 | google/jax | Support complex numbers in jax.scipy.signal.convolve/correlate |
260,374 | 04.06.2021 19:22:57 | 0 | a87a291afd35daffd0154e64951e772842998559 | Implemented get_cache_key funtion with unit tests | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/compilation_cache/compilation_cache.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 hashlib\n+import jax\n+\n+\n+def get_cache_key(xla_computation, compile_options) -> str:\n+ \"\"\"Creates a hashed string to use as a key to the compilation cache.\n+\n+ get_cache_key takes in the xla_computation and compile_options of a program and hashes\n+ all the components into a uniuqe byte string. This byte string is returned as a regular\n+ string that is 256 characters long.\n+\n+ Typical return value example:\n+\n+ '14ac577cdb2ef6d986078b4054cc9893a9a14a16dbb0d8f37b89167c1f1aacdf'\n+\n+ \"\"\"\n+ hash_obj = hashlib.sha256()\n+ hash_obj.update(xla_computation.as_serialized_hlo_module_proto())\n+ _hash_compile_options(hash_obj, compile_options)\n+ hash_obj.update(bytes(jax.lib.version))\n+ _hash_platform(hash_obj, jax.lib.xla_bridge.get_backend())\n+ return hash_obj.digest().hex()\n+\n+def _hash_compile_options(hash_obj, compile_options_obj):\n+ assert len(dir(compile_options_obj)) == 31,(f\"Unexpected number of CompileOption fields: \"\n+ f\"{len(dir(compile_options_obj))}. This likely: means that an extra \"\n+ f\"field was added, and this function needs to be updated.\")\n+\n+ if compile_options_obj.argument_layouts is not None:\n+ map(lambda shape: hash_obj.update(shape.to_serialized_proto()),\n+ compile_options_obj.argument_layouts)\n+ _hash_int(hash_obj, compile_options_obj.parameter_is_tupled_arguments)\n+ _hash_executable_build_options(hash_obj, compile_options_obj.executable_build_options)\n+ _hash_bool(hash_obj, compile_options_obj.tuple_arguments)\n+ _hash_int(hash_obj, compile_options_obj.num_replicas)\n+ _hash_int(hash_obj, compile_options_obj.num_partitions)\n+ if compile_options_obj.device_assignment is not None:\n+ hash_obj.update(compile_options_obj.device_assignment.serialize())\n+\n+def _hash_executable_build_options(hash_obj, executable_obj):\n+ assert len(dir(executable_obj)) == 30, (f\"Unexpected number of executable_build_options fields: \"\n+ f\"{len(dir(executable_obj))}. This likely means that an extra \"\n+ f\"field was added, and this function needs to be updated.\")\n+ if executable_obj.result_layout is not None:\n+ hash_obj.update(executable_obj.result_layout.to_serialized_proto())\n+ _hash_int(hash_obj, executable_obj.num_replicas)\n+ _hash_int(hash_obj, executable_obj.num_partitions)\n+ _hash_debug_options(hash_obj, executable_obj.debug_options)\n+ if executable_obj.device_assignment is not None:\n+ hash_obj.update(executable_obj.device_assignment.serialize())\n+ _hash_bool(hash_obj, executable_obj.use_spmd_partitioning)\n+\n+def _hash_debug_options(hash_obj, debug_obj):\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_enable_fast_math)\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_fast_math_honor_infs)\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_fast_math_honor_nans)\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_fast_math_honor_division)\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_fast_math_honor_functions)\n+ _hash_bool(hash_obj, debug_obj.xla_gpu_enable_fast_min_max)\n+ _hash_int(hash_obj, debug_obj.xla_backend_optimization_level)\n+ _hash_bool(hash_obj, debug_obj.xla_cpu_enable_xprof_traceme)\n+ _hash_bool(hash_obj, debug_obj.xla_llvm_disable_expensive_passes)\n+ _hash_bool(hash_obj, debug_obj.xla_test_all_input_layouts)\n+\n+def _hash_platform(hash_obj, backend):\n+ _hash_string(hash_obj, backend.platform)\n+ _hash_string(hash_obj, backend.platform_version)\n+ _hash_string(hash_obj, backend.runtime_type)\n+\n+def _hash_int(hash_obj, int_var):\n+ hash_obj.update(int_var.to_bytes(8, byteorder='big'))\n+\n+def _hash_bool(hash_obj, bool_var):\n+ hash_obj.update(bool_var.to_bytes(1, byteorder='big'))\n+\n+def _hash_string(hash_obj, str_var):\n+ hash_obj.update(str_var.encode('utf-8').strip())\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/compilation_cache_test.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+from absl.testing import absltest\n+import hashlib\n+from jax.experimental.compilation_cache import compilation_cache as cc\n+import jax\n+import jax.test_util as jtu\n+import numpy as np\n+import random\n+import unittest\n+\n+class CompilationCacheTest(jtu.JaxTestCase):\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_compile_options(self):\n+ compile_options_not_filled = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ compile_options_filled = self.filled_compile_options()\n+ filled_hash1 = self.get_hashed_value(cc._hash_compile_options, compile_options_filled)\n+ filled_hash2 = self.get_hashed_value(cc._hash_compile_options, compile_options_filled)\n+ not_filled_hash3 = self.get_hashed_value(cc._hash_compile_options, compile_options_not_filled)\n+ self.assertEqual(filled_hash1, filled_hash2)\n+ self.assertNotEqual(filled_hash1, not_filled_hash3)\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_executable_build_options(self):\n+ compile_options_not_filled = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ compile_options_filled = self.filled_compile_options()\n+ filled_hash1 = self.get_hashed_value(cc._hash_executable_build_options,\n+ compile_options_filled.executable_build_options)\n+ filled_hash2 = self.get_hashed_value(cc._hash_executable_build_options,\n+ compile_options_filled.executable_build_options)\n+ not_filled_hash3 = self.get_hashed_value(cc._hash_executable_build_options,\n+ compile_options_not_filled.executable_build_options)\n+ self.assertEqual(filled_hash1, filled_hash2)\n+ self.assertNotEqual(filled_hash1, not_filled_hash3)\n+\n+ def test_debug_options(self):\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ hash1 = self.get_hashed_value(cc._hash_debug_options,\n+ compile_options.executable_build_options.debug_options)\n+ hash2 = self.get_hashed_value(cc._hash_debug_options,\n+ compile_options.executable_build_options.debug_options)\n+ self.assertEqual(hash1, hash2)\n+ new_debug_options = self.create_new_debug_options(compile_options.executable_build_options.debug_options)\n+ hash3 = self.get_hashed_value(cc._hash_debug_options, new_debug_options)\n+ self.assertNotEqual(hash1, hash3)\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_hash_platform(self):\n+ hash1 = self.get_hashed_value(cc._hash_platform, jax.lib.xla_bridge.get_backend())\n+ hash2 = self.get_hashed_value(cc._hash_platform, jax.lib.xla_bridge.get_backend())\n+ self.assertEqual(hash1, hash2)\n+ if jax.lib.xla_bridge.get_backend().platform != \"cpu\":\n+ cpu_backend = jax.lib.xla_bridge.get_backend(\"cpu\")\n+ hash3 = self.get_hashed_value(cc._hash_platform, cpu_backend)\n+ self.assertNotEqual(hash1, hash3)\n+\n+ def test_hash_int(self):\n+ hash1 = self.get_hashed_value(cc._hash_int, 90)\n+ hash2 = self.get_hashed_value(cc._hash_int, 8)\n+ hash3 = self.get_hashed_value(cc._hash_int, 8)\n+ self.assertEqual(hash2, hash3)\n+ self.assertNotEqual(hash1, hash2)\n+\n+ def test_hash_bool(self):\n+ hash1 = self.get_hashed_value(cc._hash_bool, False)\n+ hash2 = self.get_hashed_value(cc._hash_bool, True)\n+ hash3 = self.get_hashed_value(cc._hash_bool, True)\n+ self.assertEqual(hash2, hash3)\n+ self.assertNotEqual(hash1, hash2)\n+\n+ def test_hash_string(self):\n+ hash1 = self.get_hashed_value(cc._hash_string, \"foo\")\n+ hash2 = self.get_hashed_value(cc._hash_string, \"bar\")\n+ hash3 = self.get_hashed_value(cc._hash_string, \"bar\")\n+ self.assertEqual(hash2, hash3)\n+ self.assertNotEqual(hash1, hash2)\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_same_hash_key(self):\n+ computation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ self.assertEqual(cc.get_cache_key(computation, compile_options),\n+ cc.get_cache_key(computation, compile_options))\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_different_hash_key(self):\n+ computation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ compile_options_not_filled = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ compile_options_filled = self.filled_compile_options()\n+ self.assertNotEqual(cc.get_cache_key(computation, compile_options_not_filled),\n+ cc.get_cache_key(computation, compile_options_filled))\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n+ def test_different_computations(self):\n+ computation1 = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ computation2 = jax.xla_computation(lambda x, y: x * y)(2, 2)\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ self.assertNotEqual(cc.get_cache_key(computation1, compile_options),\n+ cc.get_cache_key(computation2, compile_options))\n+\n+ def create_new_debug_options(self, debug_options_obj):\n+ debug_options_obj.xla_cpu_enable_fast_math = False\n+ debug_options_obj.xla_cpu_fast_math_honor_infs = False\n+ debug_options_obj.xla_cpu_fast_math_honor_nans = False\n+ debug_options_obj.xla_cpu_fast_math_honor_division = False\n+ debug_options_obj.xla_cpu_fast_math_honor_functions = False\n+ debug_options_obj.xla_gpu_enable_fast_min_max = False\n+ debug_options_obj.xla_backend_optimization_level = random.randint(-1, 10)\n+ debug_options_obj.xla_cpu_enable_xprof_traceme = False\n+ debug_options_obj.xla_llvm_disable_expensive_passes = False\n+ debug_options_obj.xla_test_all_input_layouts = False\n+ return debug_options_obj\n+\n+ def filled_compile_options(self):\n+ compile_options = jax.lib.xla_client.CompileOptions()\n+ compile_options.num_replicas = 1\n+ compile_options.num_partitions = 1\n+ shape = jax.lib.xla_client.Shape.array_shape(np.dtype(np.float32), [2])\n+ shape_array = [shape, shape]\n+ compile_options.argument_layouts = shape_array\n+ compile_options.executable_build_options.result_layout = shape\n+\n+ device_assignment = jax.lib.xla_client.DeviceAssignment.create(np.ndarray(shape=(2,2)))\n+ compile_options.device_assignment = device_assignment\n+ compile_options.executable_build_options.device_assignment = device_assignment\n+ return compile_options\n+\n+ def get_hashed_value(self, hash_function, hash_function_input):\n+ hash_obj = hashlib.sha256()\n+ hash_function(hash_obj, hash_function_input)\n+ return hash_obj.digest().hex()\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Implemented get_cache_key funtion with unit tests |
260,411 | 23.06.2021 10:52:03 | -7,200 | 7e335e0e2e31057843c5c0352ebf5bc1a88faa8d | [jax2tf] Fix conversion of gradients for shape polymorphic functions.
This fixes the case when the primal shape polymorphic function has
output shapes that are polynomials of the input shapes (not just
dimension variables). | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1080,7 +1080,7 @@ class ShapedArray(UnshapedArray):\nself.weak_type, self.named_shape)\ndef join(self, other):\n- if self.shape == other.shape and self.dtype == other.dtype:\n+ if symbolic_equal_shape(self.shape, other.shape) and self.dtype == other.dtype:\nweak_type = self.weak_type and other.weak_type\nnamed_shape = join_named_shapes(self.named_shape, other.named_shape)\nreturn self.update(weak_type=weak_type, named_shape=named_shape)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -335,7 +335,7 @@ def convert(fun: Callable,\nin_tree.children()[0], polymorphic_shapes_flat)\nout_cts_polymorphic_shapes = tree_util.tree_unflatten(\nout_tree,\n- tuple(str(out_aval.shape)\n+ tuple(str(out_aval.shape) # Note: may be polynomials, not just DimVar\nfor out_aval in _out_cts_avals)) # type: ignore\nvjp_polymorphic_shapes = [\nargs_polymorphic_shapes, out_cts_polymorphic_shapes\n@@ -584,19 +584,21 @@ def _args_to_avals_and_env(\naval_shape = shape_poly.parse_spec(polymorphic_shape, arg_shape)\nfor i, d in enumerate(aval_shape):\n- if type(d) is int:\n+ if not shape_poly.is_poly_dim(d):\n+ assert isinstance(d, int)\nassert d == arg_shape[i]\n- elif shape_poly.is_poly_dim(d) and d not in shapeenv:\n+ else:\n+ d_var = d.to_var() # type: ignore\n+ if d_var is not None and d_var not in shapeenv:\n# Even if the shape of `arg` is known, we still use `tf.shape` for\n# safety, because the promise is that we will convert the function\n# to work for any value of the dimension.\n- v = d.to_var() # type: ignore\n- assert v is not None\n- shapeenv[v] = tf.shape(arg)[i] # type: ignore[index]\n+ shapeenv[d_var] = tf.shape(arg)[i] # type: ignore[index]\nelse:\n# TODO: add an assertion tf.shape(arg)[i] == env[d]\npass\n+\nreturn core.ShapedArray(aval_shape, arg_jax_dtype)\navals = tuple(map(input_aval, args, arg_jax_dtypes, polymorphic_shapes)) # type: ignore\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -21,6 +21,7 @@ import collections\nimport itertools\nimport functools\nimport operator as op\n+import re\nfrom typing import Any, Dict, Optional, Sequence, Set, Tuple, Union\n@@ -64,7 +65,7 @@ class _DimMon(dict):\nreturn hash(frozenset(self.items()))\ndef __str__(self):\n- return ' '.join(f'{key}^{exponent}' if exponent != 1 else str(key)\n+ return \"*\".join(f\"{key}^{exponent}\" if exponent != 1 else str(key)\nfor key, exponent in sorted(self.items()))\n@classmethod\n@@ -184,8 +185,14 @@ class _DimPolynomial(dict):\nreturn hash(tuple(sorted(self.items())))\ndef __str__(self):\n- return ' + '.join(f'{c} {mon}' if c != 1 or mon.degree == 0 else str(mon)\n- for mon, c in sorted(self.items(), reverse=True)).strip()\n+ def _one_monomial(mon, c):\n+ if mon.degree == 0:\n+ return str(c)\n+ if c == 1:\n+ return str(mon)\n+ return f\"{c}*{mon}\"\n+ return \" + \".join(_one_monomial(mon, c)\n+ for mon, c in sorted(self.items(), reverse=True))\ndef __repr__(self):\nreturn str(self)\n@@ -211,6 +218,12 @@ class _DimPolynomial(dict):\ncoeffs[mon] = coeffs.get(mon, 0) + coeff1 * coeff2\nreturn _DimPolynomial.from_coeffs(coeffs)\n+ def __pow__(self, power, modulo=None):\n+ assert modulo is None\n+ if not isinstance(power, int):\n+ raise InconclusiveDimensionOperation(f\"Dimension polynomial cannot be raised to non-integer power '{self}' ^ '{power}'\")\n+ return functools.reduce(op.mul, [self] * power)\n+\ndef __rmul__(self, other: DimSize) -> DimSize:\nreturn self * other # multiplication commutes\n@@ -476,32 +489,25 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nif spec is None:\nspec_tuple = (...,) # type: Tuple[Any,...]\nelif isinstance(spec, PolyShape):\n- spec_tuple = tuple(spec)\n+ spec_tuple = spec\nelif isinstance(spec, str):\n- spec_ = spec.replace(\" \", \"\")\n+ spec_ = spec.strip()\nif spec_[0] == \"(\":\nif spec_[-1] != \")\":\nraise ValueError(f\"PolyShape '{spec}' has invalid syntax\")\nspec_ = spec_[1:-1]\n+ spec_ = spec_.strip()\nspec_ = spec_.rstrip(\",\")\nif not spec_:\nspec_tuple = ()\nelse:\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+ spec_tuple = spec_.split(\",\") # type: ignore\nelse:\nraise ValueError(f\"PolyShape '{spec}' must be either None, a string, or PolyShape.\")\n+ # Process ...\n+ spec_tuple = tuple(map(lambda s: ... if isinstance(s, str) and s.strip() == \"...\" else s,\n+ spec_tuple))\nds_ellipses = tuple(ds for ds in spec_tuple if ds == ...)\nif ds_ellipses:\nif len(ds_ellipses) > 1 or spec_tuple[-1] != ...:\n@@ -513,29 +519,73 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nif len(arg_shape) != len(spec_tuple):\nraise ValueError(f\"PolyShape '{spec}' must match the rank of arguments {arg_shape}.\")\n+ # The actual parsing.\n+ # We actually parse not just dimension variables, but polynomials.\n+ # This is not a supported feature of the API, but is needed when parsing the\n+ # polymorphic_shapes of a gradient function, when the primal function has polynomial\n+ # output shapes.\n+ def _parse_dim(dim_spec: Union[str, int]) -> DimSize:\n+ if isinstance(dim_spec, int):\n+ return dim_spec #\n+ dim_spec = dim_spec.strip()\n+ if not dim_spec:\n+ raise ValueError(f\"PolyShape '{spec}' has invalid syntax (empty dimension {dim_spec}')\")\n+ # Terms are separated by \"+\"\n+ terms = dim_spec.split(\"+\")\n+ if not terms:\n+ raise ValueError(f\"PolyShape '{spec}' has invalid syntax (empty dimension {dim_spec}')\")\n+ def _parse_term(term_spec: str) -> DimSize:\n+ term_spec = term_spec.strip()\n+ # Factors are separated by \"*\"\n+ factors = term_spec.split(\"*\")\n+ if not factors:\n+ raise ValueError(f\"PolyShape '{spec}' has invalid syntax (unexpected term '{term_spec}')\")\n+ def _parse_factor(factor_spec: str) -> DimSize:\n+ factor_spec = factor_spec.strip()\n+ if re.match(r\"^-?\\d+$\", factor_spec):\n+ return int(factor_spec)\n+ m = re.match(r\"^([a-zA-Z]\\w*)(\\^(\\d+))?$\", factor_spec)\n+ if not m:\n+ raise ValueError(f\"PolyShape '{spec}' has invalid syntax (unexpected term '{factor_spec}')\")\n+ var = _DimPolynomial.from_var(m.group(1))\n+ if m.group(3) is None:\n+ return var\n+ return var ** int(m.group(3))\n+\n+ return functools.reduce(op.mul, map(_parse_factor, factors))\n+ return functools.reduce(op.add, map(_parse_term, terms))\n+\nshape_var_map: Dict[str, Set[int]] = collections.defaultdict(set)\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+ def _process_dim(i: int, dim_spec: Union[str, int]):\n+ if isinstance(dim_spec, str):\n+ dim_spec = dim_spec.strip()\ndim_size = arg_shape[i]\nif dim_size is None:\n- if dim_spec == \"_\" or not isinstance(dim_spec, str):\n+ if dim_spec == \"_\":\n+ msg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\n+ f\"for unknown dimension in argument shape {arg_shape}\")\n+ raise ValueError(msg)\n+ dim_poly = _parse_dim(dim_spec)\n+ if not isinstance(dim_poly, _DimPolynomial):\nmsg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\nf\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\n- return _DimPolynomial.from_var(dim_spec)\n+ return dim_poly\nelse: # dim_size is known\nif dim_spec == \"_\":\nreturn dim_size\n- if isinstance(dim_spec, int):\n- if dim_spec != dim_size:\n+ dim_poly = _parse_dim(dim_spec)\n+ if isinstance(dim_poly, int):\n+ if dim_poly != dim_size:\nmsg = (f\"PolyShape '{spec}' in axis {i} must contain a constant or '_' \"\nf\"for known dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_size\n- # We have a dimension variable for a known dimension.\n- shape_var_map[dim_spec].add(dim_size)\n- return _DimPolynomial.from_var(dim_spec)\n+ # We have a dimension polynomial for a known dimension.\n+ dim_var = dim_poly.to_var()\n+ if dim_var is not None:\n+ shape_var_map[dim_spec].add(dim_size) # type: ignore\n+ return dim_poly\ndims = tuple([_process_dim(i, ds) for i, ds in enumerate(spec_tuple)])\nfor dim_var, dim_var_values in shape_var_map.items():\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": "@@ -59,9 +59,28 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual((2, 3), shape_poly.parse_spec(\"...\", (2, 3)))\nself.assertEqual((2, 3), shape_poly.parse_spec(\" ( 2 , 3 ) \", (2, 3)))\n- def test_dim_vars(self):\na, b = shape_poly.parse_spec(\"a, b\", (2, 3))\n+ @parameterized.named_parameters(\n+ dict(testcase_name=f\"_dim_spec={dim_spec}\",\n+ dim_spec=dim_spec, dim_poly=dim_poly)\n+ for dim_spec, dim_poly in [\n+ (\"2*a*b\", 2 * a * b),\n+ (\"-2 * a^2 * b + b^2\", -2 * a * a * b + b * b),\n+ (\"-2 * a^2 * b + -1 *b^2*a\", -2 * a * a * b - a * b * b),\n+ (\"3 * a * b * a + -2\", 3 * a * b * a - 2),\n+ (\"a + 1\", a + 1),\n+ (\"a + -1\", a - 1),\n+ ])\n+ def test_parse_poly_spec_poly(self, dim_spec=\"3 * a * b * a + -2\", dim_poly=3 * a * b * a - 2):\n+ # For internal usage only (the polymorphic_shapes of VJP) we need to\n+ # parse polynomials.\n+ self.assertEqual((dim_poly,), shape_poly.parse_spec(dim_spec, (2,)))\n+ self.assertEqual((dim_poly,), shape_poly.parse_spec(str(dim_poly), (2,)))\n+\n+ def test_dim_vars(self):\n+ a, b, a1 = shape_poly.parse_spec(\"a, b, a\", (2, 3, 2))\nself.assertEqual(True, a == a)\n+ self.assertEqual(True, a == a1)\nself.assertEqual(False, a != a)\nwith self.assertRaisesRegex(\ncore.InconclusiveDimensionOperation,\n@@ -145,7 +164,7 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nself.assertFalse((2 * a * b * a + 1).eq(a * b * a))\nself.assertFalse((3 * a * b * a - 1).eq(a * b * a))\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n- re.escape(\"Dimension polynomial comparison '3 a^2 b + -2' == 'a^2 b' is inconclusive\")):\n+ re.escape(\"Dimension polynomial comparison '3*a^2*b + -2' == 'a^2*b' is inconclusive\")):\n(3 * a * b * a - 2).eq(a * b * a)\ndef test_poly_compare(self):\n@@ -202,7 +221,6 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual(a * 2 // a, 2)\nself.assertIsInstance(a * 2 // a, int)\n- a, b = shape_poly.parse_spec(\"a, b\", (2, 3))\n@parameterized.named_parameters(\ndict(testcase_name=f\"_D={dividend}_d={divisor}_q={quotient}_r={remainder}\",\ndividend=dividend, divisor=divisor, quotient=quotient,\n@@ -362,10 +380,12 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n)\n# Some errors\n+ for invalid_syntax in [\")(\", \"2a\", \"a@\", \"a - 2\"]:\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"PolyShape ')(' has invalid syntax\")):\n+ re.escape(\"PolyShape '\" + invalid_syntax + \"' has invalid syntax\")):\ncheck_avals(\n- args=[const((2, 3))], polymorphic_shapes=[\")(\"], expected_avals=None)\n+ args=[const((2,))], polymorphic_shapes=[invalid_syntax],\n+ expected_avals=None)\nwith self.assertRaisesRegex(\nValueError,\n@@ -592,6 +612,22 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# The shape of the gradient should match the input\nself.assertEqual((None, 3, 4), tuple(tf_grad.output_shapes[1][\"grad\"]))\n+ def test_grad_not_var_output(self):\n+ # Output of the function has poly shapes, non-variable\n+ def f_jax(x): # :[b, 3]\n+ return jnp.reshape(x, (-1,)) # : [3b]\n+ x = np.arange(12, dtype=np.float32).reshape((4, 3))\n+ xv = tf.Variable(x)\n+\n+ f_tf = jax2tf.convert(f_jax, with_gradient=True,\n+ polymorphic_shapes=[\"b, ...\"])\n+\n+ with tf.GradientTape() as tape:\n+ res_tf = f_tf(xv)\n+ grad_tf = tape.gradient(res_tf, xv)\n+ self.assertAllClose(np.ones(x.shape, dtype=np.float32), grad_tf.numpy())\n+\n+\ndef test_cond(self):\n# Test the primitive under conditional\ndef f(x, y):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix conversion of gradients for shape polymorphic functions.
This fixes the case when the primal shape polymorphic function has
output shapes that are polynomials of the input shapes (not just
dimension variables). |
260,374 | 23.06.2021 17:40:23 | 0 | d460a53a5664d17a977df124d0025d7ed163d24e | changed 1 to 0 | [
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -124,7 +124,7 @@ class CompilationCacheTest(jtu.JaxTestCase):\ndebug_options_obj.xla_cpu_fast_math_honor_division = False\ndebug_options_obj.xla_cpu_fast_math_honor_functions = False\ndebug_options_obj.xla_gpu_enable_fast_min_max = False\n- debug_options_obj.xla_backend_optimization_level = random.randint(1, 10)\n+ debug_options_obj.xla_backend_optimization_level = random.randint(0, 10)\ndebug_options_obj.xla_cpu_enable_xprof_traceme = False\ndebug_options_obj.xla_llvm_disable_expensive_passes = False\ndebug_options_obj.xla_test_all_input_layouts = False\n"
}
] | Python | Apache License 2.0 | google/jax | changed 1 to 0 |
260,411 | 24.06.2021 08:40:41 | -7,200 | 174a4779a1fb624bd6abb727b48a0871b5ebf56f | [jax2tf] Documented recipe for ensuring that model parameters are not embedded | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -94,7 +94,8 @@ is trivial:\n# You can save the model just like you would with any other TensorFlow function:\nmy_model = tf.Module()\n# Save a function that can take scalar inputs.\n-my_model.f = tf.function(jax2tf.convert(f_jax), input_signature=[tf.TensorSpec([], tf.float32)])\n+my_model.f = tf.function(jax2tf.convert(f_jax), autograph=False,\n+ input_signature=[tf.TensorSpec([], tf.float32)])\ntf.saved_model.save(my_model, '/some/directory',\noptions=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n@@ -118,6 +119,33 @@ tf.saved_model.save(my_model, '/some/directory',\noptions=tf.saved_model.SaveOptions(experimental_custom_gradients=True))\n```\n+Some special care is needed to ensure that the model parameters are not embedded\n+as constants in the graph and are instead saved separately as variables.\n+This is useful for two reasons:\n+the parameters could be very large and exceed the limits of the\n+GraphDef part of the SavedModel, or you may want to fine-tune the\n+model and change the value of the parameters.\n+\n+```python\n+def model_jax(params, inputs):\n+ return params[0] + params[1] * inputs\n+\n+# Wrap the parameter constants as tf.Variables; this will signal to the model\n+# saving code to save those constants as variables.\n+params_vars = tf.nest.map_structure(tf.Variable, params)\n+\n+# Build the prediction function by closing over the `params_vars`. If you\n+# instead were to close over `params` your SavedModel would have no variables\n+# and the parameters will be included in the function graph.\n+prediction_tf = lambda inputs: jax2tf.convert(model_jax)(params_vars, inputs)\n+\n+my_model = tf.Module()\n+# Tell the model saver what are the variables.\n+my_model.variables = tf.nest.flatten(params_vars)\n+my_model.f = tf.function(prediction_tf, jit_compile=True)\n+tf.saved_model.save(my_model)\n+```\n+\nFor examples of how to save a Flax model as a SavedModel see the\n[examples directory](https://github.com/google/jax/blob/main/jax/experimental/jax2tf/examples/README.md).\n@@ -527,9 +555,12 @@ in [savedmodel_test.py](https://github.com/google/jax/blob/main/jax/experimental\nThere is currently no support for `pmap` or`xmap`, nor for the collective\noperations. There is support for `sharded_jit` and `pjit`.\n-### SavedModel is large (contains a large amount of source information)\n+### SavedModel may be large\n+\n+If you suspect that the SavedModel is larger than it should be, check first\n+that you are not including the parameters as constants in the graph (see [above](#usage-saved-model)).\n-The SavedModel obtained from a `jax2tf.convert`-ed function includes source\n+Additionally, the SavedModel obtained from a `jax2tf.convert`-ed function may include source\nlocation information. This ensures that the debugging experience is similar\nfor JAX with XLA vs. `jax2tf.convert` with XLA. However, this debugging information\nincreases the size of the SavedModel, even possibly doubling it. You can\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Documented recipe for ensuring that model parameters are not embedded |
260,411 | 24.06.2021 09:33:29 | -7,200 | 76a3c88c451cfbe796f00c382899e271e70a447f | Improved handling of tf.TensorShape | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -585,7 +585,6 @@ def _args_to_avals_and_env(\nfor i, d in enumerate(aval_shape):\nif not shape_poly.is_poly_dim(d):\n- assert isinstance(d, int)\nassert d == arg_shape[i]\nelse:\nd_var = d.to_var() # type: ignore\n@@ -1923,7 +1922,7 @@ def _common_reduce_window(operand, init_val, reducer, window_dimensions,\nreducer_fn = tf.function(\nreducer, autograph=False).get_concrete_function(o_spec, o_spec)\n- if not isinstance(init_val, tf.Tensor):\n+ if not isinstance(init_val, (tf.Tensor, tf.Variable)):\ninit_val = tf.constant(init_val, operand.dtype)\nout = tfxla.reduce_window(\noperand,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -220,7 +220,9 @@ class _DimPolynomial(dict):\ndef __pow__(self, power, modulo=None):\nassert modulo is None\n- if not isinstance(power, int):\n+ try:\n+ power = int(power)\n+ except:\nraise InconclusiveDimensionOperation(f\"Dimension polynomial cannot be raised to non-integer power '{self}' ^ '{power}'\")\nreturn functools.reduce(op.mul, [self] * power)\n@@ -281,7 +283,7 @@ class _DimPolynomial(dict):\nerr_msg = f\"Dimension polynomial '{self}' is not a multiple of '{divisor}'\"\n# invariant: self = dividend + divisor * quotient\n# the leading term of dividend decreases through the loop.\n- while not (isinstance(dividend, int) or dividend.is_constant):\n+ while is_poly_dim(dividend) and not dividend.is_constant:\nmon, count = dividend.leading_term\ntry:\nqmon = mon.divide(dmon)\n@@ -566,16 +568,17 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nf\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\ndim_poly = _parse_dim(dim_spec)\n- if not isinstance(dim_poly, _DimPolynomial):\n+ if not is_poly_dim(dim_poly):\nmsg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\nf\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_poly\nelse: # dim_size is known\n+ dim_size = int(dim_size)\nif dim_spec == \"_\":\nreturn dim_size\ndim_poly = _parse_dim(dim_spec)\n- if isinstance(dim_poly, int):\n+ if not is_poly_dim(dim_poly):\nif dim_poly != dim_size:\nmsg = (f\"PolyShape '{spec}' in axis {i} must contain a constant or '_' \"\nf\"for known dimension in argument shape {arg_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": "@@ -326,6 +326,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nreturn tf.Variable(\nnp.ones(initializer_shape, np.float32), dtype=tf.float32, shape=shape)\n+\n# Known shapes for the arguments\ncheck_avals(\nargs=[const((2, 3))],\n@@ -379,6 +380,12 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nexpected_avals=(shaped_array(\"(c, b, a)\", (2, 3, 4)),),\n)\n+ # Check when the shapes are TensorSpec\n+ check_avals(\n+ args=[tf_var(tf.TensorShape([2, 3]), initializer_shape=(2, 3))],\n+ polymorphic_shapes=[PS(\"b\", ...)],\n+ expected_avals=(shaped_array(\"(b, 3)\", (2, 3)),))\n+\n# Some errors\nfor invalid_syntax in [\")(\", \"2a\", \"a@\", \"a - 2\"]:\nwith self.assertRaisesRegex(ValueError,\n"
}
] | Python | Apache License 2.0 | google/jax | Improved handling of tf.TensorShape |
260,411 | 28.06.2021 08:40:43 | -7,200 | 44b95426d1760c9a8cb3f69e816192eb979a1c87 | [jax2tf] Fix the conversion of reduce_sum and reduce_prod for booleans
Also update the documentation | [
{
"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-06-14* (YYYY-MM-DD)\n+*Last generated on: 2021-06-28* (YYYY-MM-DD)\n## Supported data types for primitives\n-We use a set of 2604 test harnesses to test\n+We use a set of 2668 test harnesses to test\nthe implementation of 121 numeric JAX primitives.\nWe consider a JAX primitive supported for a particular data\ntype if it is supported on at least one device type.\n@@ -78,7 +78,7 @@ be updated.\n| div | 20 | inexact, integer | bool |\n| dot_general | 245 | all | |\n| dynamic_slice | 64 | all | |\n-| dynamic_update_slice | 21 | all | |\n+| dynamic_update_slice | 42 | all | |\n| eig | 72 | inexact | bool, integer |\n| eigh | 36 | inexact | bool, integer |\n| eq | 17 | all | |\n@@ -89,7 +89,7 @@ be updated.\n| expm1 | 6 | inexact | bool, integer |\n| fft | 20 | complex, float32, float64 | bfloat16, bool, float16, integer |\n| floor | 4 | floating | bool, complex, integer |\n-| gather | 37 | all | |\n+| gather | 80 | all | |\n| ge | 17 | all | |\n| gt | 17 | all | |\n| igamma | 6 | floating | bool, complex, integer |\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-06-15*\n+*Last generated on (YYYY-MM-DD): 2021-06-28*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -71,6 +71,7 @@ More detailed information can be found in the\n| conv_general_dilated | TF error: jax2tf BUG: batch_group_count > 1 not yet converted | all | cpu, gpu, tpu | compiled, eager, graph |\n| digamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| div | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n+| dot_general | TF error: Numeric comparision disabled: Non-deterministic NaN for dot_general with preferred_element_type on GPU (b/189287598) | bfloat16, complex64, float16, float32 | gpu | compiled, eager, graph |\n| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=c128 not implemented | complex64 | tpu | compiled, eager, graph |\n| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=i64 not implemented | int16, int32, int8 | tpu | compiled, eager, graph |\n| dot_general | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1805,10 +1805,9 @@ tf_impl[lax.transpose_p] = _transpose\naxes_to_axis = lambda func: lambda operand, axes: func(operand, axis=axes)\n-tf_impl[lax.reduce_sum_p] = (\n- bool_to_int8(axes_to_axis(tf.reduce_sum), argnums=[0]))\n-tf_impl[lax.reduce_prod_p] = (\n- bool_to_int8(axes_to_axis(tf.reduce_prod), argnums=[0]))\n+# reduce_sum and reduce_prod are not supported for bool\n+tf_impl[lax.reduce_sum_p] = axes_to_axis(tf.reduce_sum)\n+tf_impl[lax.reduce_prod_p] = axes_to_axis(tf.reduce_prod)\ntf_impl[lax.reduce_max_p] = (\nbool_to_int8(axes_to_axis(tf.reduce_max), argnums=[0]))\ntf_impl[lax.reduce_min_p] = (\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix the conversion of reduce_sum and reduce_prod for booleans
Also update the documentation |
260,374 | 17.06.2021 17:40:32 | 0 | 0ea0525740c647747a767f1daf0c04add6b53844 | implementing thread saftey check | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/file_system_cache.py",
"new_path": "jax/experimental/compilation_cache/file_system_cache.py",
"diff": "# limitations under the License.\nimport os\n+import tempfile\nfrom typing import Optional\nimport warnings\n@@ -41,8 +42,16 @@ class FileSystemCache:\nraise ValueError(\"key cannot be empty\")\nif self._evict_entries_if_necessary(key, value):\npath_to_new_file = os.path.join(self._path, key)\n- with open(path_to_new_file, \"wb\") as file:\n+ # Create the path for the file in a temporary directory so we can use the\n+ # atomic move function to ensure that the file is properly stored and read\n+ # in the case of concurrent access across multiple threads or processes\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ temp_path_to_file = os.path.join(tmpdir, key)\n+ with open(temp_path_to_file, \"wb\") as file:\nfile.write(value)\n+ file.flush()\n+ os.fsync(file.fileno())\n+ os.rename(temp_path_to_file, path_to_new_file)\nelse:\nwarnings.warn(f\"Cache value of size {len(value)} is larger than\"\nf\" the max cache size of {self._max_cache_size_bytes}\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/file_system_cache_test.py",
"new_path": "tests/file_system_cache_test.py",
"diff": "@@ -16,6 +16,7 @@ from absl.testing import absltest\nfrom jax.experimental.compilation_cache.file_system_cache import FileSystemCache\nimport jax.test_util as jtu\nimport tempfile\n+import threading\nimport time\nclass FileSystemCacheTest(jtu.JaxTestCase):\n@@ -122,5 +123,28 @@ class FileSystemCacheTest(jtu.JaxTestCase):\ncache.put(\"foo\", b\"bar\")\nself.assertEqual(cache.get(\"foo\"), None)\n+ def test_threads(self):\n+ file_contents1 = \"1\" * (65536 + 1)\n+ file_contents2 = \"2\" * (65536 + 1)\n+\n+ def call_multiple_puts_and_gets(cache):\n+ for i in range(50):\n+ cache.put(\"foo\", file_contents1.encode('utf-8').strip())\n+ cache.put(\"foo\", file_contents2.encode('utf-8').strip())\n+ cache.get(\"foo\")\n+ self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n+\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cache = FileSystemCache(tmpdir)\n+ threads = []\n+ for i in range(50):\n+ t = threading.Thread(target=call_multiple_puts_and_gets(cache))\n+ t.start()\n+ threads.append(t)\n+ for t in threads:\n+ t.join()\n+\n+ self.assertEqual(cache.get(\"foo\"), file_contents2.encode('utf-8').strip())\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | implementing thread saftey check |
260,411 | 29.06.2021 14:57:42 | -10,800 | ffd8fb84b48ff658713f5b0aeea84b2255bd554c | [jax2tf] A few fixed for handling of float0 in jax2tf and call_tf
TF returns None or 0 for the gradients of functions with integer
arguments. JAX expects float0. We must convert to and from float0
at the JAX-TF boundary. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -589,6 +589,47 @@ jax2tf.convert(jax.grad(f_jax, allow_int=True))(2))\n# returns a `bfloat16` zero: tf.Tensor(0, shape=(), dtype=bfloat16)\n```\n+### Different behavior for gradients for unused arguments\n+\n+When differentiating functions with unused arguments, TF by default\n+returns the value `None` for the corresponding gradients. The\n+`tape.gradient` function takes the option `tf.UnconnectedGradients.ZERO`\n+to ask that gradients for unused arguments be zero.\n+\n+Functions converted with `jax2tf.convert` behave the same way under\n+`tf.UnconnectedGradients.ZERO`, but by default, they will return\n+`None` only for gradients corresponding to integer arguments.\n+\n+```\n+# x1 and x3 are not used. x3 has integer type.\n+def fn(x0, x1, x2, x3):\n+ return x0 * 0. + x2 * 2.\n+\n+xs = [tf.Variable(x) for x in [10., 11., 12., 13]]\n+with tf.GradientTape(persistent=True) as tape:\n+ res = fn(*xs)\n+\n+g_tf_native = tape.gradient(res, xs)\n+# Returns: 0., None, 2., None\n+\n+g_tf_native_0 = tape.gradient(res, xs,\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+# Returns: 0., 0., 2., 0\n+\n+# Now with jax2tf.convert\n+with tf.GradientTape() as tape:\n+ res = jax2tf.convert(fn, with_gradient=True)(*xs0\n+\n+g_jax2tf = tape.gradient(res, xs)\n+# Returns: 0., 0., 2., None\n+# Note that the gradient for x1 is 0.\n+\n+g_jaxx2tf_0 = tape.gradient(res, xs,\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+# Returns: 0., 0., 2., 0\n+# In this case we get the same result as for TF native.\n+```\n+\n### Different 64-bit precision in JAX and TensorFlow\nJAX behaves somewhat differently than TensorFlow in the handling\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -33,6 +33,7 @@ from jax import dtypes\nfrom jax import numpy as jnp\nfrom jax import tree_util\nfrom jax._src import util\n+from jax._src import ad_util\nfrom jax.interpreters import xla\nfrom jax.lib import xla_client\nfrom . import jax2tf as jax2tf_internal\n@@ -162,7 +163,18 @@ def call_tf(callable_tf: Callable) -> Callable:\nreturn dres_darg\n# Use call_tf to call the VJP function\n- return call_tf(tf_vjp_fun)(args_jax, ct_res_jax)\n+ ct_args_jax = call_tf(tf_vjp_fun)(args_jax, ct_res_jax)\n+ # We must make the float0s that JAX expects\n+ def fix_float0(arg_jax, ct_arg_jax):\n+ arg_dtype = dtypes.result_type(arg_jax) # May be scalar\n+ ct_arg_dtype = core.primal_dtype_to_tangent_dtype(arg_dtype)\n+ if ct_arg_dtype != ct_arg_jax.dtype:\n+ return ad_util.zeros_like_aval(core.ShapedArray(np.shape(arg_jax),\n+ ct_arg_dtype))\n+ return ct_arg_jax\n+\n+ ct_args_jax_fixed = tree_util.tree_map(fix_float0, args_jax, ct_args_jax)\n+ return ct_args_jax_fixed\nmake_call.defvjp(make_call_vjp_fwd, make_call_vjp_bwd)\nreturn util.wraps(callable_tf)(make_call)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -349,7 +349,19 @@ def convert(fun: Callable,\nfun_vjp_jax,\nwith_gradient=False,\npolymorphic_shapes=vjp_polymorphic_shapes)(args, out_cts)\n- return in_cts\n+ # We fix here the float0\n+ # TODO: it would be better to fix these somewhere inside the converter\n+ # because here we are already back in TF.\n+ def fix_float0(arg: TfVal, in_ct: TfVal) -> TfVal:\n+ _, arg_jax_dtype = _tfval_to_tensor_jax_dtype(arg) # Maybe it is a scalar\n+ if np.issubdtype(arg_jax_dtype, np.inexact):\n+ return in_ct\n+ else:\n+ assert in_ct.dtype.as_numpy_dtype == tf.bfloat16\n+ return tf.zeros(arg.shape, arg.dtype)\n+\n+ in_cts_fixed = tf.nest.map_structure(fix_float0, args, in_cts)\n+ return in_cts_fixed\ntry:\nassert not _thread_local_state.shape_env, f\"Unexpected shape environment {_thread_local_state.shape_env}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -363,6 +363,37 @@ class CallTfTest(jtu.JaxTestCase):\ng = jax.grad(lambda *args: jnp.sum(f(*args)[0]))(param, state, x)\nself.assertAllClose(g_call_tf, g)\n+ def test_grad_int_argument_unused(self):\n+ batch_size = 5\n+ inputs = np.ones((batch_size, 3), dtype=np.float32)\n+ rng = np.array([1, 2], dtype=np.uint32)\n+ params = np.float32(.5)\n+\n+ # rng is integer, unused\n+ def jax_model(params, rng, inputs):\n+ return jnp.ones([batch_size, 2], dtype=jnp.float32)\n+\n+ tf_model = jax2tf.convert(jax_model, with_gradient=True)\n+\n+ def _loss_fn(inference_fn, params, rng, inputs):\n+ prediction = inference_fn(params, rng, inputs)\n+ return jnp.mean(prediction)\n+\n+ jax_loss_fn = partial(_loss_fn, jax_model)\n+ jax_grad = jax.grad(jax_loss_fn)(params, rng, inputs)\n+\n+ paramsv = tf.Variable(params)\n+ with tf.GradientTape() as tape:\n+ tf_prediction = tf_model(paramsv, rng, inputs)\n+ tf_loss = tf.reduce_mean(tf_prediction)\n+\n+ tf_grad = tape.gradient(tf_loss, paramsv)\n+ self.assertAllClose(jax_grad, tf_grad.numpy())\n+\n+ call_tf_loss_fn = partial(_loss_fn, jax2tf.call_tf(tf_model))\n+ call_tf_grad = jax.grad(call_tf_loss_fn)(params, rng, inputs)\n+ self.assertAllClose(jax_grad, call_tf_grad)\n+\ndef test_grad_with_float0_result(self):\n# Gradient over integer-argument functions, with float0 result\ndef f_jax(x, y): # x is an int, y is a float; res is a (int, float)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -352,29 +352,176 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(jnp.zeros(np.shape(d_dx_jax), dtypes.bfloat16),\nd_dx_tf.numpy())\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_gradients_unused_argument_readme(self, with_function=True):\n+ # x2 and x3 are not used. x3 has integer type.\n+ def fn(x0, x1, x2, x3):\n+ return x0 * 0. + x2 * 2.\n- def test_tf_gradients_int_argument(self):\n- # https://github.com/google/jax/issues/6975\n- # state is a pytree that contains an integer and a boolean.\n- # The function returns an integer and a boolean.\n- def f_jax(param, state, x):\n- return param * x, state\n+ xs = [tf.Variable(x) for x in [10., 11., 12., 13]]\n+ with tf.GradientTape(persistent=True) as tape:\n+ res = fn(*xs)\n+\n+ g_tf_native = tape.gradient(res, xs)\n+ self.assertAllClose(g_tf_native[0].numpy(), np.float32(0.))\n+ self.assertIsNone(g_tf_native[1])\n+ self.assertAllClose(g_tf_native[2].numpy(), np.float32(2.))\n+ self.assertIsNone(g_tf_native[3])\n+\n+ g_tf_native_0 = tape.gradient(res, xs,\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+ self.assertAllClose(g_tf_native_0[0].numpy(), np.float32(0.))\n+ self.assertAllClose(g_tf_native_0[1].numpy(), np.float32(0.))\n+ self.assertAllClose(g_tf_native_0[2].numpy(), np.float32(2.))\n+ self.assertAllClose(g_tf_native_0[3].numpy(), np.int32(0))\n+\n+ # Now with jax2tf.convert\n+ with tf.GradientTape(persistent=True) as tape:\n+ conv_fn = jax2tf.convert(fn, with_gradient=True)\n+ if with_function:\n+ conv_fn = tf.function(conv_fn, autograph=False)\n+ res = conv_fn(*xs)\n+\n+ g_jax2tf = tape.gradient(res, xs)\n+ # Returns: 0., 0., 2., None\n+ # Note that the gradient for x1 is 0.\n+ self.assertAllClose(g_jax2tf[0].numpy(), np.float32(0.))\n+ self.assertAllClose(g_jax2tf[1].numpy(), np.float32(0.))\n+ self.assertAllClose(g_jax2tf[2].numpy(), np.float32(2.))\n+ self.assertIsNone(g_jax2tf[3])\n+\n+ g_jax2tf = tape.gradient(res, xs,\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+ self.assertAllClose(g_jax2tf[0].numpy(), np.float32(0.))\n+ self.assertAllClose(g_jax2tf[1].numpy(), np.float32(0.))\n+ self.assertAllClose(g_jax2tf[2].numpy(), np.float32(2.))\n+ self.assertAllClose(g_jax2tf[3].numpy(), np.int32(0))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_gradients_int_argument(self, with_function=False):\n+ # https://github.com/google/jax/issues/6975\n+ # An expanded version of test_gradients_unused_argument\n+ # param: f32\n+ # state: dict(array:f32, counter:i32, truth: bool)\n+ # xf: f32\n+ # xf_unused: f32 unused\n+ # xi_unused: i32 unused\n+ # return f32, state\n+ def f_jax(param, state, xf, xf_unused, xi_unused):\n+ return param * xf, state\n+\n+ # everything has different shapes\nparam = np.array([0.7, 0.9], dtype=np.float32)\nstate = dict(array=1., counter=7, truth=True)\n- x = 3.\n+ xf = np.array([11.], dtype=np.float32)\n+ xf_unused = np.array([21., 22., 23., 24.], dtype=np.float32)\n+ xi_unused = np.array([31, 32, 33, 34, 35], dtype=np.int32)\n+\n+ # Native JAX AD\n+ g_jax = jax.grad(lambda *args: jnp.sum(f_jax(*args)[0]),\n+ argnums=(0, 1, 2, 3, 4),\n+ allow_int=True)(param, state, xf, xf_unused, xi_unused)\n+ g_jax_param = np.array([11., 11.], dtype=np.float32)\n+ g_jax_x = np.array([1.6], dtype=np.float32)\n+\n+ self.assertAllClose(g_jax[0], g_jax_param)\n+ self.assertAllClose(g_jax[1][\"array\"], np.zeros_like(state[\"array\"]))\n+ self.assertEqual(g_jax[1][\"counter\"].dtype, jax.float0)\n+ self.assertEqual(g_jax[1][\"counter\"].shape, ())\n+ self.assertEqual(g_jax[1][\"truth\"].dtype, jax.float0)\n+ self.assertEqual(g_jax[1][\"truth\"].shape, ())\n+ self.assertAllClose(g_jax[2], g_jax_x)\n+ self.assertAllClose(g_jax[3], np.zeros_like(xf_unused))\n+ self.assertEqual(g_jax[4].dtype, jax.float0)\n+ self.assertEqual(g_jax[4].shape, xi_unused.shape)\n+\n+ # Now native TF gradients, only to test how TF AD works\n+ paramv = tf.Variable(param)\n+ statev = tf.nest.map_structure(tf.Variable, state)\n+ xfv = tf.Variable(xf)\n+ xf_unusedv = tf.Variable(xf_unused)\n+ xi_unusedv = tf.Variable(xi_unused)\n+ with tf.GradientTape(persistent=True) as tape:\n+ r, _ = f_jax(paramv, statev, xfv, xf_unusedv, xi_unusedv)\n+ loss = tf.reduce_sum(r)\n+\n+ g_tf_native_0 = tape.gradient(\n+ loss, (paramv, statev, xfv, xf_unusedv, xi_unusedv),\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+ self.assertAllClose(g_tf_native_0[0].numpy(), g_jax_param)\n+ self.assertAllClose(g_tf_native_0[1][\"array\"].numpy(), np.zeros_like(state[\"array\"]).astype(np.float32))\n+ self.assertAllClose(g_tf_native_0[1][\"counter\"].numpy(), np.zeros_like(state[\"counter\"]).astype(np.int32))\n+ self.assertAllClose(g_tf_native_0[1][\"truth\"].numpy(), np.zeros_like(state[\"truth\"]))\n+ self.assertAllClose(g_tf_native_0[2].numpy(), g_jax_x)\n+ self.assertAllClose(g_tf_native_0[3].numpy(), np.zeros_like(xf_unused).astype(np.float32))\n+ self.assertAllClose(g_tf_native_0[4].numpy(), np.zeros_like(xi_unused).astype(np.int32))\n+\n+ g_tf_native_None = tape.gradient(\n+ loss, (paramv, statev, xfv, xf_unusedv, xi_unusedv),\n+ unconnected_gradients=tf.UnconnectedGradients.NONE)\n+ self.assertAllClose(g_tf_native_None[0].numpy(), g_jax_param)\n+ self.assertIsNone(g_tf_native_None[1][\"array\"])\n+ self.assertIsNone(g_tf_native_None[1][\"counter\"])\n+ self.assertIsNone(g_tf_native_None[1][\"truth\"])\n+ self.assertAllClose(g_tf_native_None[2].numpy(), g_jax_x)\n+ self.assertIsNone(g_tf_native_None[3])\n+ self.assertIsNone(g_tf_native_None[4])\n# tf.function is important, without it the bug does not appear\n- f_tf = tf.function(jax2tf.convert(f_jax, with_gradient=True), autograph=False)\n+ f_tf = jax2tf.convert(f_jax, with_gradient=True)\n+ if with_function:\n+ f_tf = tf.function(f_tf, autograph=False)\n- paramv = tf.Variable(param)\n- with tf.GradientTape() as tape:\n- r, _ = f_tf(paramv, state, x)\n+ with tf.GradientTape(persistent=True) as tape:\n+ r, _ = f_tf(paramv, statev, xfv, xf_unusedv, xi_unusedv)\nloss = tf.reduce_sum(r)\n- g_tf = tape.gradient(loss, paramv)\n- self.assertAllClose(g_tf.numpy(),\n- jax.grad(lambda *args: jnp.sum(f_jax(*args)[0]))(param, state, x))\n+ g_tf_0 = tape.gradient(loss, (paramv, statev, xfv, xf_unusedv, xi_unusedv),\n+ unconnected_gradients=tf.UnconnectedGradients.ZERO)\n+ # Same results as TF native AD with tf.UnconnectedGradients.ZERO\n+ self.assertAllClose(g_tf_0[0].numpy(), g_jax_param)\n+ self.assertAllClose(g_tf_0[1][\"array\"].numpy(), np.zeros_like(state[\"array\"]).astype(np.float32))\n+ self.assertAllClose(g_tf_0[1][\"counter\"].numpy(), np.zeros_like(state[\"counter\"]).astype(np.int32))\n+ self.assertAllClose(g_tf_0[1][\"truth\"].numpy(), np.zeros_like(state[\"truth\"]))\n+ self.assertAllClose(g_tf_0[2].numpy(), g_jax_x)\n+ self.assertAllClose(g_tf_0[3].numpy(), np.zeros_like(xf_unused))\n+ self.assertAllClose(g_tf_0[4].numpy(), np.zeros_like(xi_unused))\n+\n+ g_tf_None = tape.gradient(loss, (paramv, statev, xfv, xf_unusedv, xi_unusedv),\n+ unconnected_gradients=tf.UnconnectedGradients.NONE)\n+\n+ # Almost the same results as TF native AD with tf.UnconnectedGradients.ZERO,\n+ # except that unused inputs of inexact type get 0. gradients.\n+ self.assertAllClose(g_tf_None[0].numpy(), g_jax_param)\n+ # The next one is different\n+ self.assertAllClose(g_tf_0[1][\"array\"].numpy(), np.zeros_like(state[\"array\"]).astype(np.float32))\n+ self.assertIsNone(g_tf_None[1][\"counter\"])\n+ self.assertIsNone(g_tf_None[1][\"truth\"])\n+ self.assertAllClose(g_tf_None[2].numpy(), g_jax_x)\n+ # The next one is different\n+ self.assertAllClose(g_tf_0[3].numpy(), np.zeros_like(xf_unused))\n+ self.assertIsNone(g_tf_None[4])\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_tf_gradients_int_argument(self, with_function=False):\n+ # https://github.com/google/jax/issues/6975\n+ # param: f32\n+ # state: dict(array:f32, counter:i32, truth: bool)\n+ # xf: f32\n+ # xf_unused: f32 unused\n+ # xi_unused: i32 unused\n+ # return f32, state\n+ def f_jax(param, state, xf, xf_unused, xi_unused):\n+ return param * xf, state\ndef test_convert_argument_non_callable_error(self):\nwith self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] A few fixed for handling of float0 in jax2tf and call_tf
TF returns None or 0 for the gradients of functions with integer
arguments. JAX expects float0. We must convert to and from float0
at the JAX-TF boundary. |
260,335 | 24.06.2021 15:00:19 | 25,200 | a0eb1126e4d3ce74135200468956ecc3bb26ebb8 | remat: don't apply cse-foiling widget to primal | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -2408,7 +2408,8 @@ def eval_shape(fun: Callable, *args, **kwargs):\nreturn tree_unflatten(out_tree(), out)\n-def checkpoint(fun: Callable, concrete: bool = False) -> Callable:\n+def checkpoint(fun: Callable, concrete: bool = False, prevent_cse: bool = True,\n+ ) -> Callable:\n\"\"\"Make ``fun`` recompute internal linearization points when differentiated.\nThe :func:`jax.checkpoint` decorator, aliased to ``jax.remat``, provides a\n@@ -2446,6 +2447,14 @@ def checkpoint(fun: Callable, concrete: bool = False) -> Callable:\ncontrol flow is optional, and disabled by default, because in some\nedge-case compositions with :func:`jax.jit` it can lead to some extra\ncomputation.\n+ prevent_cse: Optional, boolean indicating whether to prevent common\n+ subexpression elimination (CSE) optimizations in the HLO generated from\n+ differentiation. This CSE prevention has costs because it can foil other\n+ optimizations, and because it can incur high overheads on some backends,\n+ especially GPU. The default is True because otherwise, under a ``jit`` or\n+ ``pmap``, CSE can defeat the purpose of this decorator. But in some\n+ settings, like when used inside a ``scan``, this CSE prevention mechanism\n+ is unnecessary, in which case ``prevent_cse`` can be set to False.\nReturns:\nA function (callable) with the same input/output behavior as ``fun`` but\n@@ -2496,7 +2505,8 @@ def checkpoint(fun: Callable, concrete: bool = False) -> Callable:\nargs_flat, in_tree = tree_flatten((args, kwargs))\nflat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\nout_flat = pe.remat_call(flat_fun, *args_flat, name=flat_fun.__name__,\n- concrete=concrete)\n+ concrete=concrete, prevent_cse=prevent_cse,\n+ differentiated=False)\nreturn tree_unflatten(out_tree(), out_flat)\nreturn fun_remat\nremat = checkpoint\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/partial_eval.py",
"new_path": "jax/interpreters/partial_eval.py",
"diff": "@@ -814,12 +814,12 @@ def _remat_partial_eval(trace, _, f, tracers, params):\n# dce jaxpr outputs\nnew_jaxpr = _dce_jaxpr(closed_jaxpr, out_unknowns, drop_outputs=True).jaxpr\n- new_params = dict(params, call_jaxpr=new_jaxpr)\n+ new_params = dict(params, call_jaxpr=new_jaxpr, differentiated=True)\n# set up eqn for unknown outputs\nin_tracers = (*const_tracers, *env_tracers, *instantiated_tracers)\n- eqn = new_eqn_recipe(in_tracers, unknown_output_tracers, remat_call_p, new_params,\n- source_info_util.current())\n+ eqn = new_eqn_recipe(in_tracers, unknown_output_tracers, remat_call_p,\n+ new_params, source_info_util.current())\nfor t in unknown_output_tracers: t.recipe = eqn\nreturn _zip_knowns(known_output_tracers, unknown_output_tracers, out_unknowns)\ncall_partial_eval_rules[remat_call_p] = _remat_partial_eval\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1464,14 +1464,18 @@ def _remat_using_while(\ndef _remat_translation_rule(c, axis_env, in_nodes,\nname_stack, backend, name, call_jaxpr,\n- device=None, concrete=None):\n+ prevent_cse, differentiated, concrete, device=None):\ndel device, concrete # Unused.\n+ if differentiated and prevent_cse:\nif backend == \"gpu\":\nreturn _remat_using_while(\nc, axis_env, in_nodes, name_stack, backend, name, call_jaxpr)\nelse:\nreturn _remat_using_cond(\nc, axis_env, in_nodes, name_stack, backend, name, call_jaxpr)\n+ else:\n+ outs = jaxpr_subcomp(c, call_jaxpr, backend, axis_env, (), \"\", *in_nodes)\n+ return xops.Tuple(c, outs)\ncall_translations[pe.remat_call_p] = _remat_translation_rule # type: ignore\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -3214,6 +3214,40 @@ class RematTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(core.UnexpectedTracerError, \"global state\"):\napi.jit(f)()\n+ def test_no_cse_widget_on_primals(self):\n+ @api.remat\n+ def g(x):\n+ return lax.sin(lax.sin(x)), 3.\n+\n+ def f(x):\n+ x, _ = g(x)\n+ return x\n+\n+ c = api.xla_computation(f)(2.)\n+ self.assertNotIn('while', c.as_hlo_text())\n+ self.assertNotIn('conditional', c.as_hlo_text())\n+\n+ c = api.xla_computation(grad(f))(2.)\n+ text = c.as_hlo_text()\n+ self.assertTrue('while' in text or 'conditional' in text)\n+\n+ def test_no_cse_widget_with_prevent_cse_false(self):\n+ @partial(api.remat, prevent_cse=False)\n+ def g(x):\n+ return lax.sin(lax.sin(x)), 3.\n+\n+ def f(x):\n+ x, _ = g(x)\n+ return x\n+\n+ c = api.xla_computation(f)(2.)\n+ self.assertNotIn('while', c.as_hlo_text())\n+ self.assertNotIn('conditional', c.as_hlo_text())\n+\n+ c = api.xla_computation(grad(f))(2.)\n+ self.assertNotIn('while', c.as_hlo_text())\n+ self.assertNotIn('conditional', c.as_hlo_text())\n+\nclass JaxprTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | remat: don't apply cse-foiling widget to primal |
260,335 | 02.07.2021 10:31:28 | 25,200 | 5e92faccbb4497755c8cee901b57b5e2788fabb0 | tweak xla_bridge.py flags
* add environment variables for jax_disable_most_optimizations and
jax_cpu_backend_variant
* comment on the default values in help strings | [
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -30,7 +30,7 @@ from absl import logging\nlogging._warn_preinit_stderr = 0\nimport jax.lib\n-from .._src.config import flags\n+from .._src.config import flags, bool_env\nfrom . import tpu_driver_client\nfrom . import xla_client\nfrom jax._src import util, traceback_util\n@@ -52,21 +52,26 @@ flags.DEFINE_string(\n'provided, --jax_xla_backend takes priority. Prefer --jax_platform_name.')\nflags.DEFINE_string(\n'jax_backend_target', 'local',\n- 'Either \"local\" or \"rpc:address\" to connect to a remote service target.')\n+ 'Either \"local\" or \"rpc:address\" to connect to a remote service target. '\n+ 'The default is \"local\".')\nflags.DEFINE_string(\n'jax_platform_name',\n- os.getenv('JAX_PLATFORM_NAME', ''),\n+ os.getenv('JAX_PLATFORM_NAME', '').lower(),\n'Platform name for XLA. The default is to attempt to use a GPU or TPU if '\n'available, but fall back to CPU otherwise. To set the platform manually, '\n- 'pass \"cpu\" for CPU, \"gpu\" for GPU, etc.')\n+ 'pass \"cpu\" for CPU, \"gpu\" for GPU, etc. If intending to use CPU, '\n+ 'setting the platform name to \"cpu\" can silence warnings that appear with '\n+ 'the default setting.')\nflags.DEFINE_bool(\n- 'jax_disable_most_optimizations', False,\n+ 'jax_disable_most_optimizations',\n+ bool_env('JAX_DISABLE_MOST_OPTIMIZATIONS', False),\n'Try not to do much optimization work. This can be useful if the cost of '\n'optimization is greater than that of running a less-optimized program.')\nflags.DEFINE_string(\n- 'jax_cpu_backend_variant', 'tfrt',\n- 'jax_cpu_backend_variant selects cpu backend variant: stream_executor or '\n- 'tfrt')\n+ 'jax_cpu_backend_variant',\n+ os.getenv('JAX_CPU_BACKEND_VARIANT', 'tfrt'),\n+ 'Selects CPU backend runtime variant: \"stream_executor\" or \"tfrt\". The '\n+ 'default is \"tfrt\".')\ndef get_compile_options(\nnum_replicas: int,\n"
}
] | Python | Apache License 2.0 | google/jax | tweak xla_bridge.py flags
* add environment variables for jax_disable_most_optimizations and
jax_cpu_backend_variant
* comment on the default values in help strings |
260,447 | 02.07.2021 10:42:29 | 25,200 | d97b393694570a35fb0a092be63a30adf845c823 | Adds spherical harmonics. | [
{
"change_type": "MODIFY",
"old_path": "CHANGELOG.md",
"new_path": "CHANGELOG.md",
"diff": "@@ -10,6 +10,8 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n## jax 0.2.17 (unreleased)\n* [GitHub commits](https://github.com/google/jax/compare/jax-v0.2.16...main).\n+* New features:\n+ * New SciPy function {py:func}`jax.scipy.special.sph_harm`.\n## jaxlib 0.1.69 (unreleased)\n@@ -23,6 +25,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\nwith significant dispatch performance improvements on CPU.\n* The {func}`jax2tf.convert` supports inequalities and min/max for booleans\n({jax-issue}`#6956`).\n+ * New SciPy function {py:func}`jax.scipy.special.lpmn_values`.\n* Breaking changes:\n* Support for NumPy 1.16 has been dropped, per the\n@@ -51,6 +54,7 @@ PLEASE REMEMBER TO CHANGE THE '..main' WITH AN ACTUAL TAG in GITHUB LINK.\n* The {func}`jax2tf.convert` generates custom attributes with location information\nin TF ops. The code that XLA generates after jax2tf\nhas the same location information as JAX/XLA.\n+ * New SciPy function {py:func}`jax.scipy.special.lpmn`.\n* Bug fixes:\n* The {func}`jax2tf.convert` now ensures that it uses the same typing rules\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/jax.scipy.rst",
"new_path": "docs/jax.scipy.rst",
"diff": "@@ -105,6 +105,7 @@ jax.scipy.special\nndtr\nndtri\npolygamma\n+ sph_harm\nxlog1py\nxlogy\nzeta\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/scipy/special.py",
"new_path": "jax/_src/scipy/special.py",
"diff": "@@ -27,7 +27,7 @@ from jax._src.numpy.lax_numpy import (asarray, _reduction_dims, _constant_like,\n_promote_args_inexact)\nfrom jax._src.numpy.util import _wraps\n-from typing import Tuple\n+from typing import Optional, Tuple\n@_wraps(osp_special.gammaln)\n@@ -909,6 +909,7 @@ def _gen_associated_legendre(l_max: int,\np_val = p_val + h\nreturn p_val\n+ if l_max > 1:\np = lax.fori_loop(lower=2, upper=l_max+1, body_fun=body_fun, init_val=p)\nreturn p\n@@ -1010,3 +1011,77 @@ def lpmn_values(m: int, n: int, z: jnp.ndarray, is_normalized: bool) -> jnp.ndar\nl_max = n\nreturn _gen_associated_legendre(l_max, z, is_normalized)\n+\n+\n+\n+@partial(jit, static_argnums=(4,))\n+def _sph_harm(m: jnp.ndarray,\n+ n: jnp.ndarray,\n+ theta: jnp.ndarray,\n+ phi: jnp.ndarray,\n+ n_max: int) -> jnp.ndarray:\n+ \"\"\"Computes the spherical harmonics.\"\"\"\n+\n+ cos_colatitude = jnp.cos(phi)\n+\n+ legendre = _gen_associated_legendre(n_max, cos_colatitude, True)\n+ legendre_val = legendre[abs(m), n, jnp.arange(len(n))]\n+\n+ angle = abs(m) * theta\n+ vandermonde = lax.complex(jnp.cos(angle), jnp.sin(angle))\n+ harmonics = lax.complex(legendre_val * jnp.real(vandermonde),\n+ legendre_val * jnp.imag(vandermonde))\n+\n+ # Negative order.\n+ harmonics = jnp.where(m < 0,\n+ (-1.0)**abs(m) * jnp.conjugate(harmonics),\n+ harmonics)\n+\n+ return harmonics\n+\n+\n+def sph_harm(m: jnp.ndarray,\n+ n: jnp.ndarray,\n+ theta: jnp.ndarray,\n+ phi: jnp.ndarray,\n+ n_max: Optional[int] = None) -> jnp.ndarray:\n+ r\"\"\"Computes the spherical harmonics.\n+\n+ The JAX version has one extra argument `n_max`, the maximum value in `n`.\n+\n+ The spherical harmonic of degree `n` and order `m` can be written as\n+ :math:`Y_n^m(\\theta, \\phi) = N_n^m * P_n^m(\\cos \\phi) * \\exp(i m \\theta)`,\n+ where :math:`N_n^m = \\sqrt{\\frac{\\left(2n+1\\right) \\left(n-m\\right)!}\n+ {4 \\pi \\left(n+m\\right)!}}` is the normalization factor and :math:`\\phi` and\n+ :math:\\theta` are the colatitude and longitude, repectively. :math:`N_n^m` is\n+ chosen in the way that the spherical harmonics form a set of orthonormal basis\n+ functions of :math:`L^2(S^2)`.\n+\n+ Args:\n+ m: The order of the harmonic; must have `|m| <= n`. Return values for\n+ `|m| > n` ara undefined.\n+ n: The degree of the harmonic; must have `n >= 0`. The standard notation for\n+ degree in descriptions of spherical harmonics is `l (lower case L)`. We\n+ use `n` here to be consistent with `scipy.special.sph_harm`. Return\n+ values for `n < 0` are undefined.\n+ theta: The azimuthal (longitudinal) coordinate; must be in [0, 2*pi].\n+ phi: The polar (colatitudinal) coordinate; must be in [0, pi].\n+ n_max: The maximum degree `max(n)`. If the supplied `n_max` is not the true\n+ maximum value of `n`, the results are clipped to `n_max`. For example,\n+ `sph_harm(m=jnp.array([2]), n=jnp.array([10]), theta, phi, n_max=6)`\n+ acutually returns\n+ `sph_harm(m=jnp.array([2]), n=jnp.array([6]), theta, phi, n_max=6)`\n+ Returns:\n+ A 1D array containing the spherical harmonics at (m, n, theta, phi).\n+ \"\"\"\n+\n+ if jnp.isscalar(phi):\n+ phi = jnp.array([phi])\n+\n+ if n_max is None:\n+ n_max = jnp.max(n)\n+ n_max = core.concrete_or_error(\n+ int, n_max, 'The `n_max` argument of `jnp.scipy.special.sph_harm` must '\n+ 'be statically specified to use `sph_harm` within JAX transformations.')\n+\n+ return _sph_harm(m, n, theta, phi, n_max)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/scipy/special.py",
"new_path": "jax/scipy/special.py",
"diff": "@@ -39,6 +39,7 @@ from jax._src.scipy.special import (\nndtr,\nndtri,\npolygamma,\n+ sph_harm,\nxlogy,\nxlog1py,\nzeta,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_scipy_test.py",
"new_path": "tests/lax_scipy_test.py",
"diff": "@@ -26,6 +26,7 @@ import numpy as np\nimport scipy.special as osp_special\nfrom jax._src import api\n+from jax import numpy as jnp\nfrom jax import test_util as jtu\nfrom jax.scipy import special as lsp_special\n@@ -312,6 +313,98 @@ class LaxBackedScipyTests(jtu.JaxTestCase):\nlsp_special_fn = lambda z: lsp_special.lpmn_values(l_max, l_max, z, is_normalized)\nself._CompileAndCheck(lsp_special_fn, args_maker)\n+ def testSphHarmAccuracy(self):\n+ m = jnp.arange(-3, 3)[:, None]\n+ n = jnp.arange(3, 6)\n+ n_max = 5\n+ theta = 0.0\n+ phi = jnp.pi\n+\n+ expected = lsp_special.sph_harm(m, n, theta, phi, n_max)\n+\n+ actual = osp_special.sph_harm(m, n, theta, phi)\n+\n+ self.assertAllClose(actual, expected, rtol=1e-8, atol=9e-5)\n+\n+ def testSphHarmOrderZeroDegreeZero(self):\n+ \"\"\"Tests the spherical harmonics of order zero and degree zero.\"\"\"\n+ theta = jnp.array([0.3])\n+ phi = jnp.array([2.3])\n+ n_max = 0\n+\n+ expected = jnp.array([1.0 / jnp.sqrt(4.0 * np.pi)])\n+ actual = jnp.real(\n+ lsp_special.sph_harm(jnp.array([0]), jnp.array([0]), theta, phi, n_max))\n+\n+ self.assertAllClose(actual, expected, rtol=1.1e-7, atol=3e-8)\n+\n+ def testSphHarmOrderZeroDegreeOne(self):\n+ \"\"\"Tests the spherical harmonics of order one and degree zero.\"\"\"\n+ theta = jnp.array([2.0])\n+ phi = jnp.array([3.1])\n+ n_max = 1\n+\n+ expected = jnp.sqrt(3.0 / (4.0 * np.pi)) * jnp.cos(phi)\n+ actual = jnp.real(\n+ lsp_special.sph_harm(jnp.array([0]), jnp.array([1]), theta, phi, n_max))\n+\n+ self.assertAllClose(actual, expected, rtol=7e-8, atol=1.5e-8)\n+\n+ def testSphHarmOrderOneDegreeOne(self):\n+ \"\"\"Tests the spherical harmonics of order one and degree one.\"\"\"\n+ theta = jnp.array([2.0])\n+ phi = jnp.array([2.5])\n+ n_max = 1\n+\n+ expected = (-1.0 / 2.0 * jnp.sqrt(3.0 / (2.0 * np.pi)) *\n+ jnp.sin(phi) * jnp.exp(1j * theta))\n+ actual = lsp_special.sph_harm(\n+ jnp.array([1]), jnp.array([1]), theta, phi, n_max)\n+\n+ self.assertAllClose(actual, expected, rtol=1e-8, atol=6e-8)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {'testcase_name': '_maxdegree={}_inputsize={}_dtype={}'.format(\n+ l_max, num_z, dtype),\n+ 'l_max': l_max, 'num_z': num_z, 'dtype': dtype}\n+ for l_max, num_z in zip([1, 3, 8, 10], [2, 6, 7, 8])\n+ for dtype in jtu.dtypes.all_integer))\n+ def testSphHarmForJitAndAgainstNumpy(self, l_max, num_z, dtype):\n+ \"\"\"Tests against JIT compatibility and Numpy.\"\"\"\n+ n_max = l_max\n+ shape = (num_z,)\n+ rng = jtu.rand_int(self.rng(), -l_max, l_max + 1)\n+\n+ lsp_special_fn = partial(lsp_special.sph_harm, n_max=n_max)\n+\n+ def args_maker():\n+ m = rng(shape, dtype)\n+ n = abs(m)\n+ theta = jnp.linspace(-4.0, 5.0, num_z)\n+ phi = jnp.linspace(-2.0, 1.0, num_z)\n+ return m, n, theta, phi\n+\n+ with self.subTest('Test JIT compatibility'):\n+ self._CompileAndCheck(lsp_special_fn, args_maker)\n+\n+ with self.subTest('Test against numpy.'):\n+ self._CheckAgainstNumpy(osp_special.sph_harm, lsp_special_fn, args_maker)\n+\n+ def testSphHarmCornerCaseWithWrongNmax(self):\n+ \"\"\"Tests the corner case where `n_max` is not the maximum value of `n`.\"\"\"\n+ m = jnp.array([2])\n+ n = jnp.array([10])\n+ n_clipped = jnp.array([6])\n+ n_max = 6\n+ theta = jnp.array([0.9])\n+ phi = jnp.array([0.2])\n+\n+ expected = lsp_special.sph_harm(m, n, theta, phi, n_max)\n+\n+ actual = lsp_special.sph_harm(m, n_clipped, theta, phi, n_max)\n+\n+ self.assertAllClose(actual, expected, rtol=1e-8, atol=9e-5)\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Adds spherical harmonics.
Co-authored-by: Jake VanderPlas <jakevdp@google.com> |
260,635 | 03.07.2021 18:09:58 | -7,200 | 7b10965794be4f592d2ad1975aa45d7dde32359c | Implement complex logaddexp | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -656,45 +656,65 @@ def power(x1, x2):\n@custom_jvp\n@_wraps(np.logaddexp)\ndef logaddexp(x1, x2):\n- x1, x2 = _promote_shapes(\"logaddexp\", *_promote_dtypes_inexact(x1, x2))\n+ x1, x2 = _promote_args_inexact(\"logaddexp\", x1, x2)\namax = lax.max(x1, x2)\n+ if issubdtype(x1.dtype, np.floating):\ndelta = lax.sub(x1, x2)\nreturn lax.select(isnan(delta),\nlax.add(x1, x2), # NaNs or infinities of the same sign.\n- lax.add(amax, lax.log1p(lax.exp(-lax.abs(delta)))))\n+ lax.add(amax, lax.log1p(lax.exp(lax.neg(lax.abs(delta))))))\n+ else:\n+ delta = lax.sub(lax.add(x1, x2), lax.mul(amax, _constant_like(amax, 2)))\n+ out = lax.add(amax, lax.log1p(lax.exp(delta)))\n+ return lax.complex(lax.real(out), _wrap_between(lax.imag(out), np.pi))\n+\n+def _wrap_between(x, _a):\n+ \"\"\"Wraps `x` between `[-a, a]`.\"\"\"\n+ a = _constant_like(x, _a)\n+ two_a = _constant_like(x, 2 * _a)\n+ zero = _constant_like(x, 0)\n+ rem = lax.rem(lax.add(x, a), two_a)\n+ rem = lax.select(lax.lt(rem, zero), lax.add(rem, two_a), rem)\n+ return lax.sub(rem, a)\n@logaddexp.defjvp\ndef _logaddexp_jvp(primals, tangents):\nx1, x2 = primals\nt1, t2 = tangents\n- x1, x2, t1, t2 = broadcast_arrays(x1, x2, t1, t2)\n+ x1, x2, t1, t2 = _promote_args_inexact(\"logaddexp_jvp\", x1, x2, t1, t2)\nprimal_out = logaddexp(x1, x2)\n- tangent_out = (t1 * exp(_replace_inf(x1) - _replace_inf(primal_out)) +\n- t2 * exp(_replace_inf(x2) - _replace_inf(primal_out)))\n+ tangent_out = lax.add(lax.mul(t1, exp(lax.sub(_replace_inf(x1), _replace_inf(primal_out)))),\n+ lax.mul(t2, exp(lax.sub(_replace_inf(x2), _replace_inf(primal_out)))))\nreturn primal_out, tangent_out\ndef _replace_inf(x):\n- return lax.select(isposinf(x), zeros_like(x), x)\n+ return lax.select(isposinf(real(x)), zeros_like(x), x)\n@custom_jvp\n@_wraps(np.logaddexp2)\ndef logaddexp2(x1, x2):\n- x1, x2 = _promote_shapes(\"logaddexp2\", *_promote_dtypes_inexact(x1, x2))\n+ x1, x2 = _promote_args_inexact(\"logaddexp2\", x1, x2)\namax = lax.max(x1, x2)\n+ if issubdtype(x1.dtype, np.floating):\ndelta = lax.sub(x1, x2)\nreturn lax.select(isnan(delta),\nlax.add(x1, x2), # NaNs or infinities of the same sign.\n- lax.add(amax, lax.div(lax.log1p(exp2(-lax.abs(delta))),\n+ lax.add(amax, lax.div(lax.log1p(exp2(lax.neg(lax.abs(delta)))),\n_constant_like(x1, np.log(2)))))\n+ else:\n+ delta = lax.sub(lax.add(x1, x2), lax.mul(amax, _constant_like(amax, 2)))\n+ out = lax.add(amax, lax.div(lax.log1p(exp2(delta)), _constant_like(x1, np.log(2))))\n+ return lax.complex(lax.real(out), _wrap_between(lax.imag(out), np.pi / np.log(2)))\n+\n@logaddexp2.defjvp\ndef _logaddexp2_jvp(primals, tangents):\nx1, x2 = primals\nt1, t2 = tangents\n- x1, x2, t1, t2 = broadcast_arrays(x1, x2, t1, t2)\n+ x1, x2, t1, t2 = _promote_args_inexact(\"logaddexp2_jvp\", x1, x2, t1, t2)\nprimal_out = logaddexp2(x1, x2)\n- tangent_out = (t1 * 2 ** (_replace_inf(x1) - _replace_inf(primal_out)) +\n- t2 * 2 ** (_replace_inf(x2) - _replace_inf(primal_out)))\n+ tangent_out = lax.add(lax.mul(t1, exp2(lax.sub(_replace_inf(x1), _replace_inf(primal_out)))),\n+ lax.mul(t2, exp2(lax.sub(_replace_inf(x2), _replace_inf(primal_out)))))\nreturn primal_out, tangent_out\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -5379,6 +5379,44 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nnp_object_list = np.array(object_list)\nself.assertRaises(TypeError, jnp.array, np_object_list)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(\"\", shapes, dtypes),\n+ \"shapes\": shapes, \"dtypes\": dtypes}\n+ for shapes in filter(\n+ _shapes_are_broadcast_compatible,\n+ itertools.combinations_with_replacement(all_shapes, 2))\n+ for dtypes in itertools.product(\n+ *(_valid_dtypes_for_shape(s, complex_dtypes) for s in shapes))))\n+ def testLogaddexpComplex(self, shapes, dtypes):\n+ @jtu.ignore_warning(category=RuntimeWarning, message=\"invalid value.*\")\n+ def np_op(x1, x2):\n+ return np.log(np.exp(x1) + np.exp(x2))\n+\n+ rng = jtu.rand_some_nan(self.rng())\n+ args_maker = lambda: tuple(rng(shape, dtype) for shape, dtype in zip(shapes, dtypes))\n+ tol = {np.complex64: 1e-5, np.complex128: 5e-15}\n+ self._CheckAgainstNumpy(_promote_like_jnp(np_op), jnp.logaddexp, args_maker, tol=tol)\n+ self._CompileAndCheck(jnp.logaddexp, args_maker, rtol=tol, atol=tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(\"\", shapes, dtypes),\n+ \"shapes\": shapes, \"dtypes\": dtypes}\n+ for shapes in filter(\n+ _shapes_are_broadcast_compatible,\n+ itertools.combinations_with_replacement(all_shapes, 2))\n+ for dtypes in itertools.product(\n+ *(_valid_dtypes_for_shape(s, complex_dtypes) for s in shapes))))\n+ def testLogaddexp2Complex(self, shapes, dtypes):\n+ @jtu.ignore_warning(category=RuntimeWarning, message=\"invalid value.*\")\n+ def np_op(x1, x2):\n+ return np.log2(np.exp2(x1) + np.exp2(x2))\n+\n+ rng = jtu.rand_some_nan(self.rng())\n+ args_maker = lambda: tuple(rng(shape, dtype) for shape, dtype in zip(shapes, dtypes))\n+ tol = {np.complex64: 1e-5, np.complex128: 5e-15}\n+ self._CheckAgainstNumpy(_promote_like_jnp(np_op), jnp.logaddexp2, args_maker, tol=tol)\n+ self._CompileAndCheck(jnp.logaddexp2, args_maker, rtol=tol, atol=tol)\n+\n# Most grad tests are at the lax level (see lax_test.py), but we add some here\n# as needed for e.g. particular compound ops of interest.\n@@ -5488,6 +5526,37 @@ class NumpyGradTests(jtu.JaxTestCase):\ncheck_grads(f, (1.,), order=1)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(\"\", shapes, itertools.repeat(dtype)),\n+ \"shapes\": shapes, \"dtype\": dtype}\n+ for shapes in filter(\n+ _shapes_are_broadcast_compatible,\n+ itertools.combinations_with_replacement(nonempty_shapes, 2))\n+ for dtype in (np.complex128, )))\n+ def testGradLogaddexpComplex(self, shapes, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ args = tuple(rng(shape, dtype) for shape in shapes)\n+ if jtu.device_under_test() == \"tpu\":\n+ tol = 5e-2\n+ else:\n+ tol = 3e-2\n+ check_grads(jnp.logaddexp, args, 1, [\"fwd\", \"rev\"], tol, tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": jtu.format_test_name_suffix(\"\", shapes, itertools.repeat(dtype)),\n+ \"shapes\": shapes, \"dtype\": dtype}\n+ for shapes in filter(\n+ _shapes_are_broadcast_compatible,\n+ itertools.combinations_with_replacement(nonempty_shapes, 2))\n+ for dtype in (np.complex128, )))\n+ def testGradLogaddexp2Complex(self, shapes, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ args = tuple(rng(shape, dtype) for shape in shapes)\n+ if jtu.device_under_test() == \"tpu\":\n+ tol = 5e-2\n+ else:\n+ tol = 3e-2\n+ check_grads(jnp.logaddexp2, args, 1, [\"fwd\", \"rev\"], tol, tol)\nclass NumpySignaturesTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Implement complex logaddexp |
260,286 | 05.07.2021 11:59:27 | -3,600 | 4bae17dd703fafbc07ccb5b096af06ce6fac3748 | Add a helper decorator to disable implicit rank promotion in unit tests. | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -855,6 +855,20 @@ class JaxTestLoader(absltest.TestLoader):\nreturn names\n+def disable_implicit_rank_promotion(test_method):\n+ \"\"\"A decorator for test methods to raise error on implicit rank promotion.\"\"\"\n+ @functools.wraps(test_method)\n+ def test_method_wrapper(self, *args, **kwargs):\n+ try:\n+ prev_flag = config.jax_numpy_rank_promotion\n+ FLAGS.jax_numpy_rank_promotion = \"raise\"\n+ return test_method(self, *args, **kwargs)\n+ finally:\n+ FLAGS.jax_numpy_rank_promotion = prev_flag\n+\n+ return test_method_wrapper\n+\n+\nclass JaxTestCase(parameterized.TestCase):\n\"\"\"Base class for JAX tests including numerical checks and boilerplate.\"\"\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/test_util_test.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+from absl.testing import absltest\n+\n+from jax import test_util as jtu\n+import jax.numpy as jnp\n+\n+\n+class TestUtilTest(jtu.JaxTestCase):\n+\n+ @jtu.disable_implicit_rank_promotion\n+ def testDisableImplicitRankPromotion(self):\n+ x = jnp.zeros([2])\n+ y = jnp.zeros([2])\n+\n+ with self.assertRaises(ValueError):\n+ x[None, :] + y\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Add a helper decorator to disable implicit rank promotion in unit tests. |
260,411 | 05.07.2021 18:17:59 | -7,200 | 2fe02268b245f50cf9c656783da5c34ec21437b0 | [jax2tf] Ensure that the conversion of Round uses the same algorithm as JAX | [
{
"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-06-28* (YYYY-MM-DD)\n+*Last generated on: 2021-07-05* (YYYY-MM-DD)\n## Supported data types for primitives\n-We use a set of 2668 test harnesses to test\n+We use a set of 2667 test harnesses to test\nthe implementation of 121 numeric JAX primitives.\nWe consider a JAX primitive supported for a particular data\ntype if it is supported on at least one device type.\n@@ -132,7 +132,7 @@ be updated.\n| rem | 18 | floating, integer | bool, complex |\n| reshape | 19 | all | |\n| rev | 19 | all | |\n-| round | 7 | floating | bool, complex, integer |\n+| round | 6 | floating | bool, complex, integer |\n| rsqrt | 6 | inexact | bool, integer |\n| scatter_add | 15 | all | |\n| scatter_max | 15 | all | |\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-06-28*\n+*Last generated on (YYYY-MM-DD): 2021-07-05*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1033,8 +1033,11 @@ tf_impl[lax.floor_p] = tf.math.floor\ntf_impl[lax.ceil_p] = tf.math.ceil\n-def _round(operand, *, rounding_method):\n+def _round(operand, *, rounding_method,\n+ _in_avals: Sequence[core.AbstractValue],\n+ _out_aval: core.AbstractValue):\nif rounding_method is lax.RoundingMethod.AWAY_FROM_ZERO:\n+ # JAX uses a single HLO op Round here\nsign = _sign(operand)\noperand *= sign\nfloor = tf.math.floor(operand)\n@@ -1043,11 +1046,12 @@ def _round(operand, *, rounding_method):\nreturn sign * (\ntf.where(cond, tf.constant(np.array(1), operand.dtype),\ntf.math.round(operand)) + floor)\n- else:\n- return tf.math.round(operand)\n-\n+ else: # rounding_method is RoundingMethod.TO_NEAREST_EVEN\n+ rounding_fun = _convert_jax_impl(\n+ lax._round_to_nearest_even, multiple_results=False)\n+ return rounding_fun(operand, _in_avals=_in_avals, _out_aval=_out_aval)\n-tf_impl[lax.round_p] = _round\n+tf_impl_with_avals[lax.round_p] = _round\ntf_impl[lax.nextafter_p] = tf.math.nextafter\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -481,14 +481,6 @@ for rounding_method in [\n_make_round_harness(\n\"rounding_methods\", operand=operand, rounding_method=rounding_method)\n-# Validate edge cases\n-for name, operand in [\n- # Checks that https://github.com/google/jax/issues/4952 is resolved\n- (\"round_away_from_0\",\n- np.array([[0.5, 1.5, 2.5], [-0.5, -1.5, -2.5]], dtype=np.float32)),\n-]:\n- _make_round_harness(f\"edge_case_{name}\", operand=operand)\n-\ndef _make_convert_element_type_harness(name,\n*,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Ensure that the conversion of Round uses the same algorithm as JAX |
260,286 | 30.06.2021 13:52:32 | -3,600 | f945982b8ce9b95d47edd26afb413fa1c9baca99 | Broadcast arrays manually in categorical sampling. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/random.py",
"new_path": "jax/_src/random.py",
"diff": "@@ -1306,7 +1306,10 @@ def categorical(key: jnp.ndarray,\n_check_shape(\"categorical\", shape, batch_shape)\nsample_shape = shape[:len(shape)-len(batch_shape)]\n- return jnp.argmax(gumbel(key, sample_shape + logits.shape, logits.dtype) + logits, axis=axis)\n+ return jnp.argmax(\n+ gumbel(key, sample_shape + logits.shape, logits.dtype) +\n+ lax.expand_dims(logits, tuple(range(len(sample_shape)))),\n+ axis=axis)\ndef laplace(key: jnp.ndarray,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/random_test.py",
"new_path": "tests/random_test.py",
"diff": "@@ -379,6 +379,7 @@ class LaxRandomTest(jtu.JaxTestCase):\n]\nfor sample_shape in [(10000,), (5000, 2)]\nfor dtype in jtu.dtypes.floating))\n+ @jtu.disable_implicit_rank_promotion\ndef testCategorical(self, p, axis, dtype, sample_shape):\nkey = random.PRNGKey(0)\np = np.array(p, dtype=dtype)\n"
}
] | Python | Apache License 2.0 | google/jax | Broadcast arrays manually in categorical sampling. |
260,671 | 09.07.2021 02:23:28 | -19,080 | c60115ab9d428c0e3dfa966e8fc734e6bb2619a8 | adding s_ and index_exp | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3633,9 +3633,11 @@ class CClass(_AxisConcat):\ntrans1d = 0\nop_name = \"c_\"\n-\nc_ = CClass()\n+s_ = np.s_\n+\n+index_exp = np.index_exp\n@_wraps(np.i0)\ndef i0(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/numpy/__init__.py",
"new_path": "jax/numpy/__init__.py",
"diff": "@@ -37,7 +37,7 @@ from jax._src.numpy.lax_numpy import (\nfloat64, float_, float_power, floating, floor, floor_divide, fmax, fmin,\nfmod, frexp, full, full_like, gcd, geomspace, gradient, greater,\ngreater_equal, hamming, hanning, heaviside, histogram, histogram_bin_edges, histogram2d, histogramdd,\n- hsplit, hstack, hypot, i0, identity, iinfo, imag,\n+ hsplit, hstack, hypot, i0, identity, iinfo, imag, index_exp,\nindices, inexact, in1d, inf, inner, int16, int32, int64, int8, int_, integer,\ninterp, intersect1d, invert,\nisclose, iscomplex, iscomplexobj, isfinite, isin, isinf, isnan, isneginf,\n@@ -56,7 +56,7 @@ from jax._src.numpy.lax_numpy import (\nr_, rad2deg, radians, ravel, ravel_multi_index, real, reciprocal, remainder, repeat, reshape,\nresize, result_type, right_shift, rint, roll, rollaxis, rot90, round, round_, row_stack,\nsave, savez, searchsorted, select, set_printoptions, setdiff1d, setxor1d, shape, sign, signbit,\n- signedinteger, sin, sinc, single, sinh, size, sometrue, sort, sort_complex, split, sqrt,\n+ s_, signedinteger, 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,\ntrim_zeros, triu, triu_indices, triu_indices_from, true_divide, trunc, uint16, uint32, uint64, uint8, unique,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_numpy_test.py",
"new_path": "tests/lax_numpy_test.py",
"diff": "@@ -4946,6 +4946,12 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\natol=atol,\nrtol=rtol)\n+ def testS_(self):\n+ self.assertEqual(np.s_[1:2:20],jnp.s_[1:2:20])\n+\n+ def testIndex_exp(self):\n+ self.assertEqual(np.index_exp[5:3:2j],jnp.index_exp[5:3:2j])\n+\n@parameterized.named_parameters(\njtu.cases_from_list(\n{\"testcase_name\": (\"_start_shape={}_stop_shape={}_num={}_endpoint={}\"\n"
}
] | Python | Apache License 2.0 | google/jax | adding s_ and index_exp |
260,411 | 10.07.2021 19:08:15 | -10,800 | 5520fcb59f4cbd1a73428f2c2ea13ced2404f761 | Improve error message when vjp is called with cotangent of wrong shape.
Previously the error was an internal assertion error. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -1888,19 +1888,24 @@ def _lift_linearized(jaxpr, primal_avals, io_tree, out_pvals, consts, *py_args):\nreturn apply_flat_fun(fun, io_tree, *py_args)\n-def _vjp_pullback_wrapper(cotangent_dtypes, io_tree, fun, py_args):\n+def _vjp_pullback_wrapper(cotangent_dtypes, cotangent_shapes,\n+ io_tree, fun, py_args):\nin_tree_expected, out_tree = io_tree\nargs, in_tree = tree_flatten(py_args)\nif in_tree != in_tree_expected:\nraise TypeError(f\"Tree structure of cotangent input {in_tree}, does not match structure of \"\nf\"primal output {in_tree_expected}.\")\n- for arg, ct_dtype in safe_zip(args, cotangent_dtypes):\n+ for arg, ct_dtype, ct_shape in safe_zip(args, cotangent_dtypes, cotangent_shapes):\nexpected_tangent_dtype = core.primal_dtype_to_tangent_dtype(_dtype(arg))\nif expected_tangent_dtype != ct_dtype:\nraise TypeError(\nf\"Type of cotangent input to vjp pullback function ({ct_dtype}) is not \"\nf\"the expected tangent type ({expected_tangent_dtype}) of corresponding primal output \"\nf\"with dtype {_dtype(arg)}.\")\n+ if np.shape(arg) != cotangent_shapes:\n+ raise ValueError(\n+ f\"Shape of cotangent input to vjp pullback function ({np.shape(arg)}) is not \"\n+ f\"the expected shape ({ct_shape}) of corresponding primal output.\")\nans = fun(*args)\nreturn tree_unflatten(out_tree, ans)\n@@ -2003,10 +2008,11 @@ def _vjp(fun: lu.WrappedFun, *primals, has_aux=False, reduce_axes=()):\nout_tree, aux_tree = out_aux_trees()\nout_primal_py = tree_unflatten(out_tree, out_primal)\nct_dtypes = [core.primal_dtype_to_tangent_dtype(_dtype(x)) for x in out_primal]\n+ ct_shapes = [np.shape(x) for x in out_primal]\n# Ensure that vjp_py is a PyTree so that we can pass it from the forward to the\n# backward pass in a custom VJP.\nvjp_py = Partial(partial(_vjp_pullback_wrapper,\n- ct_dtypes,\n+ ct_dtypes, ct_shapes,\n(out_tree, in_tree)),\nout_vjp)\nif not has_aux:\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1148,6 +1148,17 @@ class APITest(jtu.JaxTestCase):\n\"Type of cotangent input to vjp pullback.*is not the expected tangent type\",\nlambda: pullback((np.float16(42))))\n+ def test_vjp_bad_cotangent_shape(self):\n+ x = np.ones((2, 5), dtype=np.float32)\n+ y = np.ones((5, 3), dtype=np.float32)\n+ def f_jax(x, y):\n+ return jnp.matmul(x, y)\n+ res, pullback = jax.vjp(f_jax, x, y)\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ \"Shape of cotangent input to vjp pullback function .* is not the expected shape\"):\n+ pullback(np.ones((2, 4), dtype=np.float32))\n+\ndef test_jvp_jit_cached(self):\n\"\"\"Bug in caching in presence of JVP and JIT.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | Improve error message when vjp is called with cotangent of wrong shape.
Previously the error was an internal assertion error. |
260,411 | 11.07.2021 10:09:19 | -10,800 | 1f946ad51ee5506b9f7bf6bbbeeb1f6e59074b27 | Fix grad of conv 0D.
This bug was introduced in and was not caught by existing tests.
Add a reproducing test. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -6921,6 +6921,9 @@ def _conv_general_vjp_lhs_padding(\ndef _conv_general_vjp_rhs_padding(\nin_shape, window_dimensions, window_strides, out_shape, padding,\nlhs_dilation, rhs_dilation):\n+\n+ if len(in_shape) == 0: # 0D conv\n+ return []\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"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_test.py",
"new_path": "tests/lax_test.py",
"diff": "@@ -764,6 +764,22 @@ class LaxTest(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker)\nself._CheckAgainstNumpy(np.dot, jnp_fun, args_maker, tol=.1)\n+ def testGradConv0D(self):\n+ # Reproduces a failure in neural_tangents not caught in our presubmit tests\n+ # See cl/367416742.\n+ lhs = np.ones((2, 5), dtype=np.float32)\n+ rhs = np.ones((5, 10), dtype=np.float32)\n+\n+ def f_jax(lhs, rhs):\n+ return lax.conv_general_dilated(\n+ lhs, rhs, window_strides=(),\n+ padding=(), lhs_dilation=(), rhs_dilation=(),\n+ dimension_numbers=lax.ConvDimensionNumbers((0, 1), (1, 0), (0, 1)),\n+ batch_group_count=1, feature_group_count=1, precision=None,\n+ preferred_element_type=None)\n+ res, pullback = jax.vjp(f_jax, lhs, rhs)\n+ grad = pullback(np.ones_like(res))\n+ self.assertAllClose((lhs * 10., rhs * 2.), grad)\n@staticmethod\ndef _conv_transpose_via_grad(data, kernel, strides, padding,\n"
}
] | Python | Apache License 2.0 | google/jax | Fix grad of conv 0D.
This bug was introduced in #6345, and was not caught by existing tests.
Add a reproducing test. |
260,411 | 13.07.2021 10:39:38 | -10,800 | caba2ed9b80f910d41f92f7c49f9ade5f198492b | [jax2tf] Support tf.compat.v1.Dimension when parsing polymorphic_shapes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -31,6 +31,7 @@ import opt_einsum\nfrom jax import config\nfrom jax import core\nimport numpy as np\n+import tensorflow as tf # type: ignore[import]\nDimSize = core.DimSize\nShape = core.Shape\n@@ -562,6 +563,8 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nif isinstance(dim_spec, str):\ndim_spec = dim_spec.strip()\ndim_size = arg_shape[i]\n+ if isinstance(dim_size, tf.compat.v1.Dimension):\n+ dim_size = dim_size.value\nif dim_size is None:\nif dim_spec == \"_\":\nmsg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\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": "@@ -59,6 +59,13 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual((2, 3), shape_poly.parse_spec(\"...\", (2, 3)))\nself.assertEqual((2, 3), shape_poly.parse_spec(\" ( 2 , 3 ) \", (2, 3)))\n+ a, b = shape_poly.parse_spec(\"a, b\", (2, 3))\n+ self.assertEqual((a, 3), shape_poly.parse_spec(\"(a, ...) \", (None, 3)))\n+ tshape = tf.TensorShape([None, 3])\n+ self.assertEqual((a, 3), shape_poly.parse_spec(\"(a, ...) \", tshape))\n+ # Test directly with tf.compat.v1.Dimension\n+ self.assertEqual((a, 3), shape_poly.parse_spec(\"(a, ...) \", tshape.dims))\n+\na, b = shape_poly.parse_spec(\"a, b\", (2, 3))\n@parameterized.named_parameters(\ndict(testcase_name=f\"_dim_spec={dim_spec}\",\n@@ -71,7 +78,9 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\n(\"a + 1\", a + 1),\n(\"a + -1\", a - 1),\n])\n- def test_parse_poly_spec_poly(self, dim_spec=\"3 * a * b * a + -2\", dim_poly=3 * a * b * a - 2):\n+ def test_parse_poly_spec_poly(self,\n+ dim_spec=\"3 * a * b * a + -2\",\n+ dim_poly=3 * a * b * a - 2):\n# For internal usage only (the polymorphic_shapes of VJP) we need to\n# parse polynomials.\nself.assertEqual((dim_poly,), shape_poly.parse_spec(dim_spec, (2,)))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Support tf.compat.v1.Dimension when parsing polymorphic_shapes |
260,374 | 07.07.2021 21:42:34 | 0 | 052062f1638c071dba3f3f7c26989af69e349d10 | initialize_cache, get_executable, and put_executable functions | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "import hashlib\nimport jax\n+from jax.experimental.compilation_cache.file_system_cache import FileSystemCache\n+from jax.lib import xla_client\n+from typing import Optional\n+_cache = None\n+\n+def initialize_cache(path):\n+ \"\"\"Creates a global cache object. Should only be called once per process.\"\"\"\n+ global _cache\n+ assert _cache == None, f\"The cache path has already been initialized to {_cache}\"\n+ _cache = FileSystemCache(path)\n+\n+def get_executable(xla_computation, compile_options) -> Optional[xla_client.Executable]:\n+ \"\"\"Returns the cached executable if present, or None otherwise.\"\"\"\n+ assert _cache is not None, \"initialize_cache must be called before calling this function.\"\n+ cache_key = get_cache_key(xla_computation, compile_options)\n+ xla_executable_serialized = _cache.get(cache_key)\n+ if not xla_executable_serialized:\n+ return None\n+ backend = jax.lib.xla_bridge.get_backend()\n+ # TODO(skye): xla_computation.get_hlo_module() is the unoptimized HLO but it should\n+ #be optimized\n+ xla_executable_deserialized = backend.deserialize_executable(\n+ xla_executable_serialized,\n+ xla_computation.get_hlo_module(),\n+ compile_options)\n+ return xla_executable_deserialized\n+\n+def put_executable(xla_computation, compile_options, executable: xla_client.Executable):\n+ \"\"\"Adds 'executable' to the cache, possibly evicting older entries.\"\"\"\n+ assert _cache is not None, \"initialize_cache must be called before calling this function.\"\n+ cache_key = get_cache_key(xla_computation, compile_options)\n+ backend = jax.lib.xla_bridge.get_backend()\n+ serialized_executable = backend.serialize_executable(executable)\n+ _cache.put(cache_key, serialized_executable)\ndef get_cache_key(xla_computation, compile_options) -> str:\n\"\"\"Creates a hashed string to use as a key to the compilation cache.\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -19,7 +19,9 @@ import jax\nimport jax.test_util as jtu\nimport numpy as np\nimport random\n+import tempfile\nimport unittest\n+from unittest import SkipTest\nclass CompilationCacheTest(jtu.JaxTestCase):\n@@ -117,6 +119,56 @@ class CompilationCacheTest(jtu.JaxTestCase):\nself.assertNotEqual(cc.get_cache_key(computation1, compile_options),\ncc.get_cache_key(computation2, compile_options))\n+ @unittest.skipIf(jax.lib.version < (0, 1, 69), \"fails with earlier jaxlibs\")\n+ def test_get_no_executable(self):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"serialize executable only works on TPU\")\n+ cc._cache = None\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ computation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ self.assertEqual(cc.get_executable(computation, compile_options), None)\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 69), \"fails with earlier jaxlibs\")\n+ def test_diff_executables(self):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"serialize executable only works on TPU\")\n+ cc._cache = None\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ computation1 = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ computation2 = jax.xla_computation(lambda x, y: x * y)(2, 2)\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ backend = jax.lib.xla_bridge.get_backend()\n+ executable1 = backend.compile(computation1, compile_options)\n+ executable2 = backend.compile(computation2, compile_options)\n+ cc.put_executable(computation1, compile_options, executable1)\n+ cc.put_executable(computation2, compile_options, executable2)\n+ self.assertNotEqual(cc.get_executable(computation1, compile_options),\n+ cc.get_executable(computation2, compile_options))\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 69), \"fails with earlier jaxlibs\")\n+ def test_put_executable(self):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"serialize executable only works on TPU\")\n+ cc._cache = None\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ computation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n+ compile_options = jax.lib.xla_bridge.get_compile_options(\n+ num_replicas=1, num_partitions=1)\n+ backend = jax.lib.xla_bridge.get_backend()\n+ executable = backend.compile(computation, compile_options)\n+ cc.put_executable(computation, compile_options, executable)\n+ deserialized_executable = cc.get_executable(computation, compile_options)\n+ inputs_to_executable = (np.array(1, dtype=np.int32), np.array(2, dtype=np.int32))\n+ expected = jax.lib.xla_client.execute_with_python_values(executable, inputs_to_executable, backend)\n+ actual = jax.lib.xla_client.execute_with_python_values(deserialized_executable, inputs_to_executable, backend)\n+ self.assertEqual(expected, actual)\n+\ndef create_new_debug_options(self, debug_options_obj):\ndebug_options_obj.xla_cpu_enable_fast_math = False\ndebug_options_obj.xla_cpu_fast_math_honor_infs = False\n"
}
] | Python | Apache License 2.0 | google/jax | initialize_cache, get_executable, and put_executable functions |
260,287 | 14.07.2021 11:39:52 | 0 | 1c1ec79edd74e5ceb6e51c4a8c7d42ff7811803b | Clarify the error message for out-of-bounds in_axes in pmap and vmap
Fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -1320,16 +1320,17 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\nreturn batched_fun\ndef _mapped_axis_size(tree, vals, dims, name, *, kws=False):\n- def _get_axis_size(name: str, i:int, shape: Tuple[int, ...], axis: int):\n+ def _get_axis_size(name: str, shape: Tuple[int, ...], axis: int):\ntry:\nreturn shape[axis]\nexcept (IndexError, TypeError) as e:\n- ranks = tree_unflatten(tree, [np.ndim(x) for x, d in zip(vals, dims)])\n- raise ValueError(f\"{name} got arg {i} of rank {len(shape)} but axis to be \"\n- f\"mapped {axis}. The tree of ranks is:\\n{ranks}\") from e\n+ min_rank = axis + 1 if axis >= 0 else -axis\n+ raise ValueError(f\"{name} was requested to map its argument along axis {axis}, \"\n+ f\"which implies that its rank should be at least {min_rank}, \"\n+ f\"but is only {len(shape)} (its shape is {shape})\") from e\n- mapped_axis_sizes = {_get_axis_size(name, i, np.shape(x), d)\n- for i, (x, d) in enumerate(zip(vals, dims))\n+ mapped_axis_sizes = {_get_axis_size(name, np.shape(x), d)\n+ for x, d in zip(vals, dims)\nif d is not None}\ntry:\nsize, = mapped_axis_sizes\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1968,8 +1968,10 @@ class APITest(jtu.JaxTestCase):\nr\"\\(10, \\[2, 2\\]\\)\"):\napi.vmap(h, in_axes=(0, 1))(X, [U, U])\n- with self.assertRaisesRegex(\n- ValueError, \"vmap got arg 0 of rank 0 but axis to be mapped 0\"):\n+ error = (r\"vmap was requested to map its argument along axis 0, which \"\n+ r\"implies that its rank should be at least 1, but is only 0 \"\n+ r\"\\(its shape is \\(\\)\\)\")\n+ with self.assertRaisesRegex(ValueError, error):\n# The mapped inputs cannot be scalars\napi.vmap(lambda x: x)(1.)\n@@ -1978,8 +1980,10 @@ class APITest(jtu.JaxTestCase):\n# If the output is mapped, there must be a non-None in_axes\napi.vmap(lambda x: x, in_axes=None)(jnp.array([1., 2.]))\n- with self.assertRaisesRegex(\n- ValueError, \"vmap got arg 0 of rank 1 but axis to be mapped 1\"):\n+ error = (r\"vmap was requested to map its argument along axis 1, which \"\n+ r\"implies that its rank should be at least 2, but is only 1 \"\n+ r\"\\(its shape is \\(2,\\)\\)\")\n+ with self.assertRaisesRegex(ValueError, error):\napi.vmap(lambda x: x, in_axes=1)(jnp.array([1., 2.]))\n# Error is: TypeError: only integer scalar arrays can be converted to a scalar index\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/batching_test.py",
"new_path": "tests/batching_test.py",
"diff": "@@ -1059,7 +1059,11 @@ class BatchingTest(jtu.JaxTestCase):\nself.assertAllClose(jax.vmap(jnp.sum, in_axes=-1)(x),\njnp.sum(x, axis=(0, 1)))\n- with self.assertRaisesRegex(ValueError, \"vmap got arg 0 of rank 3 but axis to be mapped -4\"):\n+\n+ error = (r\"vmap was requested to map its argument along axis -4, which \"\n+ r\"implies that its rank should be at least 4, but is only 3 \"\n+ r\"\\(its shape is \\(3, 4, 5\\)\\)\")\n+ with self.assertRaisesRegex(ValueError, error):\njax.vmap(jnp.sum, in_axes=-4)(x)\nid = lambda y: y\n"
}
] | Python | Apache License 2.0 | google/jax | Clarify the error message for out-of-bounds in_axes in pmap and vmap
Fixes #5201. |
260,287 | 14.07.2021 06:24:48 | 25,200 | 1049e7205f2cc8a0a3969f8f44ee77eabe19c3d1 | Implement vmap rules for with_sharding_constraint
pjit already supports batching, so there's no need to hold off on that. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/pjit.py",
"new_path": "jax/experimental/pjit.py",
"diff": "@@ -265,6 +265,7 @@ class SpecSync(IntEnum):\nWe use this to make sure we don't show garbage modified values while claiming\nthat the users have specified them like that.\n\"\"\"\n+ OUT_OF_SYNC = 0 # Arbitrary changes, including new axes inserted\nDIM_PERMUTE = 1 # Dimensions permuted, but no new sharding axes\nIN_SYNC = 2 # Entirely in sync\n@@ -291,7 +292,7 @@ class ParsedPartitionSpec:\nif too_short > 0:\nparts += ((),) * too_short\nnew_partitions = tuple_insert(parts, dim, val)\n- new_sync = SpecSync.DIM_PERMUTE if val == () else SpecSync.IN_SYNC\n+ new_sync = SpecSync.DIM_PERMUTE if val == () else SpecSync.OUT_OF_SYNC\nreturn ParsedPartitionSpec(self.unsafe_user_spec, new_partitions, sync=new_sync)\n@classmethod\n@@ -329,6 +330,10 @@ class ParsedPartitionSpec:\ndef __iter__(self):\nreturn iter(self.partitions)\n+ def __repr__(self):\n+ return f\"<partitions={self.partitions} sync={self.sync}>\"\n+\n+\nREPLICATED = ParsedPartitionSpec(None, ())\n@@ -566,20 +571,30 @@ def _sharding_constraint_impl(x, axis_resources, resource_env):\nraise NotImplementedError(\n\"with_sharding_constraint() should only be called inside pjit()\")\n-def _sharding_constraint_translation_rule(c, x_node, axis_resources, resource_env):\n- mesh = resource_env.physical_mesh\n- return xb.set_sharding_proto(c, x_node,\n- get_sharding_proto(c, x_node, axis_resources, mesh))\n-\nsharding_constraint_p = core.Primitive(\"sharding_constraint\")\nsharding_constraint_p.def_impl(_sharding_constraint_impl)\n-sharding_constraint_p.def_abstract_eval(lambda x, **unused: x)\n+sharding_constraint_p.def_abstract_eval(lambda x, **_: x)\nad.deflinear2(sharding_constraint_p,\nlambda ct, _, axis_resources, resource_env: (\nsharding_constraint_p.bind(\nct, axis_resources=axis_resources, resource_env=resource_env),))\n+\n+def _sharding_constraint_translation_rule(c, x_node, axis_resources, resource_env):\n+ mesh = resource_env.physical_mesh\n+ return xb.set_sharding_proto(c, x_node,\n+ get_sharding_proto(c, x_node, axis_resources, mesh))\nxla.translations[sharding_constraint_p] = _sharding_constraint_translation_rule\n+def _sharding_constraint_batcher(vals_in, dims_in, axis_resources, resource_env):\n+ x, = vals_in\n+ d, = dims_in\n+ y = sharding_constraint_p.bind(\n+ x,\n+ axis_resources=axis_resources.insert_axis_partitions(d, ()),\n+ resource_env=resource_env)\n+ return y, d\n+batching.primitive_batchers[sharding_constraint_p] = _sharding_constraint_batcher\n+\ndef _resource_typing_sharding_constraint(avals, params, source_info, named_axis_resources):\naval, = avals\n_check_resources_against_named_axes(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pjit_test.py",
"new_path": "tests/pjit_test.py",
"diff": "@@ -296,6 +296,17 @@ class PJitTest(jtu.BufferDonationTestCase):\nself.assertEqual(z.sharding_spec.sharding, (pxla.NoSharding(), pxla.Chunked([2])))\nself.assertEqual(w.sharding_spec.sharding, (pxla.Chunked([2]),))\n+ @jtu.with_mesh([('x', 2)])\n+ def testVMapShardingConstraint(self):\n+ f = pjit(lambda x: with_sharding_constraint(x, P('x')),\n+ in_axis_resources=P(), out_axis_resources=P('x'))\n+ x = jnp.arange(5*4).reshape((5, 4))\n+ jaxpr = jax.make_jaxpr(jax.vmap(f))(x)\n+ pjit_eqn, = jaxpr.eqns\n+ constraint_eqn, = pjit_eqn.params['jaxpr'].eqns\n+ self.assertEqual(constraint_eqn.params['axis_resources'].partitions, ((), ('x',)))\n+ self.assertEqual(constraint_eqn.params['axis_resources'].sync, SpecSync.DIM_PERMUTE)\n+\n@jtu.with_mesh([('x', 2), ('y', 1)])\ndef testShardingInXMap(self):\nh = pjit(lambda x: x, in_axis_resources=P('x'), out_axis_resources=None)\n"
}
] | Python | Apache License 2.0 | google/jax | Implement vmap rules for with_sharding_constraint
pjit already supports batching, so there's no need to hold off on that.
PiperOrigin-RevId: 384684263 |
260,631 | 14.07.2021 11:25:37 | 25,200 | b9aaff48702bb2e2e6910f5750b771b4eb1212dd | Parse absl flags in compilation_cache_test.py | [
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -23,6 +23,10 @@ import tempfile\nimport unittest\nfrom unittest import SkipTest\n+from jax.config import config\n+config.parse_flags_with_absl()\n+FLAGS = config.FLAGS\n+\nclass CompilationCacheTest(jtu.JaxTestCase):\n@unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\n@@ -123,6 +127,8 @@ class CompilationCacheTest(jtu.JaxTestCase):\ndef test_get_no_executable(self):\nif jtu.device_under_test() != \"tpu\":\nraise SkipTest(\"serialize executable only works on TPU\")\n+ if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n+ raise SkipTest(\"the new TFRT runtime does not support serialization\")\ncc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\n@@ -135,6 +141,8 @@ class CompilationCacheTest(jtu.JaxTestCase):\ndef test_diff_executables(self):\nif jtu.device_under_test() != \"tpu\":\nraise SkipTest(\"serialize executable only works on TPU\")\n+ if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n+ raise SkipTest(\"the new TFRT runtime does not support serialization\")\ncc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\n@@ -154,6 +162,8 @@ class CompilationCacheTest(jtu.JaxTestCase):\ndef test_put_executable(self):\nif jtu.device_under_test() != \"tpu\":\nraise SkipTest(\"serialize executable only works on TPU\")\n+ if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n+ raise SkipTest(\"the new TFRT runtime does not support serialization\")\ncc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\n"
}
] | Python | Apache License 2.0 | google/jax | Parse absl flags in compilation_cache_test.py
PiperOrigin-RevId: 384744462 |
260,287 | 15.07.2021 04:22:08 | 25,200 | 64510bd5b69933cb6bec62f63b9b7ba2f1eff3fc | Add `axis` and `tiled` options to `lax.all_gather`.
This is especially convenient when using JAX as an HLO generator, because the
HLO AllGather defaults to the tiling behavior. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -954,13 +954,7 @@ batching.collective_rules[all_to_all_p] = _all_to_all_batched_collective\ncore.axis_substitution_rules[all_to_all_p] = partial(_subst_all_names_in_param, 'axis_name')\n-def _expand(dim, size, index, x):\n- shape = list(x.shape)\n- shape.insert(dim, size)\n- out = lax.full(shape, lax._const(x, 0))\n- return lax.dynamic_update_index_in_dim(out, x, index, dim)\n-\n-def all_gather(x, axis_name, *, axis_index_groups=None):\n+def all_gather(x, axis_name, *, axis_index_groups=None, axis=0, tiled=False):\n\"\"\"Gather values of x across all replicas.\nIf ``x`` is a pytree then the result is equivalent to mapping this function to\n@@ -976,11 +970,21 @@ def all_gather(x, axis_name, *, axis_index_groups=None):\nan axis of size 4, [[0, 1], [2, 3]] would run all gather over the first\ntwo and last two replicas). Groups must cover all axis indices exactly\nonce, and all groups must be the same size.\n+ axis: a positional axis into which the chunks along ``axis_name`` will be\n+ concatenated.\n+ tiled: when ``False``, the chunks will be stacked into a fresh positional\n+ axis at index ``axis`` in the output. When ``True``, ``axis`` has to\n+ refer to an exising positional dimension and the chunks will be\n+ concatenated into that dimension.\nReturns:\nArray(s) representing the result of an all-gather along the axis\n- ``axis_name``. Shapes are the same as ``x.shape``, but with a leading\n- dimension of the axis_size.\n+ ``axis_name``. Shapes are the same as ``x.shape``, but:\n+\n+ - when ``tiled`` is ``False``, there is a new dimension equal to the\n+ size of axis ``axis_name`` in position ``axis``,\n+ - when ``tiled`` is ``True``, the size of dimension in position ``axis``\n+ is multiplied by the size of axis ``axis_name``.\nFor example, with 4 XLA devices available:\n@@ -1015,22 +1019,35 @@ def all_gather(x, axis_name, *, axis_index_groups=None):\n[ 4 5 6 7]]]\n\"\"\"\naxis_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n- bind = partial(all_gather_p.bind, all_gather_dimension=0,\n+ bind = partial(all_gather_p.bind, all_gather_dimension=axis,\naxis_name=axis_name, axis_index_groups=axis_index_groups,\n- axis_size=axis_size)\n+ axis_size=axis_size, tiled=tiled)\nreturn tree_util.tree_map(bind, x)\n-def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _expand(dim, size, index, tiled, x):\n+ shape = list(x.shape)\n+ if tiled:\n+ tile_size = shape[dim]\n+ shape[dim] *= size\n+ out = lax.full(shape, lax._const(x, 0))\n+ return lax.dynamic_update_slice_in_dim(out, x, index * tile_size, dim)\n+ else:\n+ shape.insert(dim, size)\n+ out = lax.full(shape, lax._const(x, 0))\n+ return lax.dynamic_update_index_in_dim(out, x, index, dim)\n+\n+def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\nindex = _index_in_group(axis_name, axis_index_groups)\n- outs = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index), x)\n+ outs = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index, tiled), x)\nreturn psum(outs, axis_name, axis_index_groups=axis_index_groups)\n-def _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\nraise AssertionError(\"Unexpected call to _all_gather_impl\")\n-def _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, axis_env, platform):\n+def _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled, axis_env, platform):\n# TODO(cjfj): Enable this for TPU also?\nif (platform == 'gpu') and (all_gather_dimension == 0):\n+ if not tiled:\nnew_shape = list(c.get_shape(x).dimensions())\nnew_shape.insert(all_gather_dimension, 1)\nbroadcast_dimensions = [i for i in range(len(new_shape)) if i != all_gather_dimension]\n@@ -1041,19 +1058,25 @@ def _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_\nelse:\nlowering = xla.lower_fun(_all_gather_via_psum, multiple_results=False, parallel=True)\nreturn lowering(c, x, all_gather_dimension=all_gather_dimension, axis_name=axis_name,\n- axis_index_groups=axis_index_groups, axis_size=axis_size, axis_env=axis_env, platform=platform)\n+ axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled,\n+ axis_env=axis_env, platform=platform)\n-def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\nif not isinstance(axis_name, (list, tuple)):\naxis_name = (axis_name,)\nx_aval = raise_to_shaped(x)\nnew_shape = list(x_aval.shape)\n+ if tiled:\n+ new_shape[all_gather_dimension] *= axis_size\n+ else:\nnew_shape.insert(all_gather_dimension, axis_size)\nnew_named_shape = {name: size for name, size in x_aval.named_shape.items()\nif name not in axis_name}\nreturn x_aval.update(shape=new_shape, named_shape=new_named_shape)\n-def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\n+ if tiled:\n+ raise NotImplementedError(\"Please open a feature request!\")\n# TODO(cjfj): Add reduce-scatter op to XLA?\nconcat_axis = 0\nreturn (lax_numpy.sum(all_to_all(\n@@ -1061,7 +1084,9 @@ def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_\nconcat_axis=concat_axis, axis_index_groups=axis_index_groups),\naxis=concat_axis),)\n-def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\n+ if tiled:\n+ raise NotImplementedError(\"Please open a feature request!\")\n(x,), (d,) = vals_in, dims_in\nif d <= all_gather_dimension:\nall_gather_dimension += 1\n@@ -1072,10 +1097,13 @@ def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, ax\nall_gather_dimension=all_gather_dimension,\naxis_name=axis_name,\naxis_index_groups=axis_index_groups,\n- axis_size=axis_size)\n+ axis_size=axis_size,\n+ tiled=tiled)\nreturn result, d\n-def _all_gather_batched_collective(frame, vals_in, dims_in, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+def _all_gather_batched_collective(frame, vals_in, dims_in, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):\n+ if tiled:\n+ raise NotImplementedError(\"Please open a feature request!\")\nassert axis_index_groups is None, \"axis_index_groups not supported in vmap\"\nassert axis_size == frame.size, \"axis size doesn't match\"\nif not isinstance(axis_name, tuple):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -149,6 +149,16 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testGatherTiled(self):\n+ f = pmap(lambda x: lax.all_gather(x, 'i', tiled=True), axis_name='i')\n+\n+ device_count = xla_bridge.device_count()\n+ shape = (device_count, 4)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ expected = np.array([x] * device_count).reshape(device_count, -1)\n+ ans = f(x)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n@ignore_slow_all_to_all_warning()\ndef testTrees(self):\nptranspose = lambda x, axis_name: lax.all_to_all(x, axis_name, 0, 0)\n"
}
] | Python | Apache License 2.0 | google/jax | Add `axis` and `tiled` options to `lax.all_gather`.
This is especially convenient when using JAX as an HLO generator, because the
HLO AllGather defaults to the tiling behavior.
PiperOrigin-RevId: 384897270 |
260,287 | 15.07.2021 13:10:05 | 0 | 478828a21a0f1a6cce200ebb3f2d1970f916dc37 | Add support for reverse-mode AD of xmap | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/maps.py",
"new_path": "jax/experimental/maps.py",
"diff": "@@ -43,7 +43,7 @@ from ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom .._src.util import (safe_map, safe_zip, HashableFunction,\nas_hashable_function, unzip2, distributed_debug_log,\n- tuple_insert, moveaxis)\n+ tuple_insert, moveaxis, split_list, wrap_name)\nfrom .._src.lax.parallel import _axis_index_translation_rule\nfrom .. import lax\n@@ -846,6 +846,44 @@ core.axis_substitution_rules[xmap_p] = _xmap_axis_subst\nad.JVPTrace.process_xmap = ad.JVPTrace.process_call # type: ignore\nad.call_param_updaters[xmap_p] = ad.call_param_updaters[xla.xla_call_p]\n+def _xmap_transpose(params, call_jaxpr, args, cts_in, cts_in_avals, reduce_axes):\n+ all_args, in_tree_def = tree_flatten(((), args, cts_in)) # empty consts\n+ fun = lu.hashable_partial(\n+ lu.wrap_init(ad.backward_pass),\n+ call_jaxpr, reduce_axes + tuple(params['global_axis_sizes'].keys()))\n+ fun, nz_arg_cts = ad.nonzero_outputs(fun)\n+ fun, out_tree = flatten_fun_nokwargs(fun, in_tree_def)\n+ # Preserve axis for primal arguments, skip tangents (represented as undefined primals).\n+ in_axes, out_axes = params['in_axes'], params['out_axes']\n+ new_in_axes = (*(axis for axis, x in zip(in_axes, args) if not ad.is_undefined_primal(x)),\n+ *(axis for axis, x in zip(out_axes, cts_in) if type(x) is not ad.Zero))\n+ # NOTE: This assumes that the output cotangents being zero is a deterministic\n+ # function of which input cotangents were zero.\n+ @as_hashable_function(closure=(in_axes, tuple(type(c) is ad.Zero for c in cts_in)))\n+ def out_axes_thunk():\n+ return tuple(axis for axis, nz in zip(in_axes, nz_arg_cts()) if nz)\n+ new_params = dict(params,\n+ name=wrap_name(params['name'], 'transpose'),\n+ in_axes=new_in_axes,\n+ out_axes_thunk=out_axes_thunk,\n+ donated_invars=(False,) * len(new_in_axes),\n+ spmd_out_axes_thunk=None)\n+ del new_params['out_axes']\n+ del new_params['spmd_out_axes']\n+ out_flat = xmap_p.bind(fun, *all_args, **new_params)\n+ arg_cts = tree_unflatten(out_tree(), out_flat)\n+\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 params['global_axis_sizes'].items()}\n+ def unmap_zero(zero, axes):\n+ return ad.Zero(_insert_aval_axes(zero.aval, axes, local_axis_sizes))\n+ return tuple(unmap_zero(arg_ct, in_axis) if type(arg_ct) is ad.Zero else arg_ct\n+ for arg_ct, in_axis in zip(arg_cts, in_axes))\n+ad.primitive_transposes[xmap_p] = _xmap_transpose\n+\n+\ndef _typecheck_xmap(\n*in_avals, call_jaxpr, name, in_axes, out_axes, donated_invars,\nglobal_axis_sizes, axis_resources, resource_env, backend,\n@@ -917,7 +955,7 @@ pxla.custom_resource_typing_rules[xmap_p] = _resource_typing_xmap\n# This is DynamicJaxprTrace.process_map with some very minor modifications\ndef _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\nfrom jax.interpreters.partial_eval import (\n- trace_to_subjaxpr_dynamic, DynamicJaxprTracer, source_info_util,\n+ trace_to_subjaxpr_dynamic, DynamicJaxprTracer,\nconvert_constvars_jaxpr, new_jaxpr_eqn)\nassert primitive is xmap_p\nin_avals = [t.aval for t in tracers]\n@@ -966,6 +1004,142 @@ def _dynamic_jaxpr_process_xmap(self, primitive, f, tracers, params):\npe.DynamicJaxprTrace.process_xmap = _dynamic_jaxpr_process_xmap # type: ignore\n+@lu.transformation_with_aux\n+def out_local_named_shapes(local_axes, *args, **kwargs):\n+ ans = yield args, kwargs\n+ ans_axes = [frozenset(a.aval.named_shape) & local_axes for a in ans]\n+ yield ans, ans_axes\n+\n+@lu.transformation_with_aux\n+def hide_units(unit_args, *args, **kwargs):\n+ ans = yield restore_units(unit_args, args), kwargs\n+ yield filter_units(ans)\n+\n+def filter_units(vals):\n+ vals_no_units = [v for v in vals if v is not core.unit]\n+ vals_is_unit = [v is core.unit for v in vals]\n+ return vals_no_units, vals_is_unit\n+\n+def restore_units(is_unit, vals):\n+ vals_it = iter(vals)\n+ vals_with_units = [core.unit if u else next(vals_it) for u in is_unit]\n+ try:\n+ next(vals_it)\n+ raise RuntimeError(\"Expected the iterator to be exhausted\")\n+ except StopIteration:\n+ return vals_with_units\n+\n+\n+def _jaxpr_trace_process_xmap(self, primitive, f: lu.WrappedFun, tracers, params):\n+ from jax.interpreters.partial_eval import (\n+ PartialVal, JaxprTracer, _drop_invars, _dce_open_jaxpr,\n+ convert_constvars_jaxpr, new_eqn_recipe)\n+ assert primitive is xmap_p\n+ in_axes = params['in_axes']\n+ donated_invars = params['donated_invars']\n+ global_axis_sizes = params['global_axis_sizes']\n+\n+ in_pvals = [t.pval for t in tracers]\n+ in_pvals = [pval if pval.is_known()\n+ else PartialVal.unknown(_delete_aval_axes(pval[0], axes))\n+ for pval, axes in zip(in_pvals, in_axes)]\n+\n+ const_axes_s = lu.Store()\n+ def app(f, *args):\n+ args_no_units, in_units = filter_units(args)\n+ f, out_units = hide_units(f, tuple(in_units))\n+ f, out_named_shapes = out_local_named_shapes(f, frozenset(global_axis_sizes))\n+ out_axes_thunk = params['out_axes_thunk']\n+ @as_hashable_function(closure=out_axes_thunk)\n+ def new_out_axes_thunk():\n+ out_axes = out_axes_thunk()\n+ axes_units, const_units = split_list(out_units(), [len(out_axes)])\n+ assert not any(const_units)\n+ num_consts = len(const_units)\n+ out_axes_no_units = [a for a, u in zip(out_axes, axes_units) if not u]\n+ const_axes = [\n+ AxisNamePos(zip(sort_named_shape, range(len(sort_named_shape))),\n+ user_repr=f'<internal: {sort_named_shape}>')\n+ for named_shape in out_named_shapes()[-num_consts:]\n+ # We sort here to make the iteration order deterministic\n+ for sort_named_shape in [sorted(named_shape, key=str)]\n+ ]\n+ if not const_axes_s: # NOTE: This can be called multiple times\n+ const_axes_s.store(const_axes)\n+ assert const_axes_s.val == const_axes\n+ return (*out_axes_no_units, *const_axes)\n+ pe_params = dict(\n+ params,\n+ in_axes=tuple(a for a, u in zip(in_axes, in_units) if not u),\n+ donated_invars=tuple(a for a, u in zip(donated_invars, in_units) if not u),\n+ out_axes_thunk=new_out_axes_thunk)\n+ outs_no_units = primitive.bind(f, *args_no_units, **pe_params)\n+ new_out_axes_thunk() # Make sure it is called at least once to compute const_axes\n+ return restore_units(out_units(), outs_no_units)\n+\n+ jaxpr, out_pvals, consts, env_tracers = self.partial_eval(\n+ f, in_pvals, app, instantiate=False)\n+\n+ out_axes = params['out_axes_thunk']()\n+ const_axes = const_axes_s.val\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_pvals = [pval if pval.is_known() else\n+ PartialVal.unknown(_insert_aval_axes(pval[0], axes, local_axis_sizes))\n+ for pval, axes in zip(out_pvals, out_axes)]\n+\n+ with core.extend_axis_env_nd(global_axis_sizes.items()):\n+ # Skip known invars and outvars, and lift constants as regular invars\n+ in_knowns = tuple(t.pval.is_known() for t in it.chain(env_tracers, tracers))\n+ out_unknowns = tuple(not pval.is_known() for pval in out_pvals)\n+ jaxpr = _drop_invars(jaxpr, in_knowns)\n+ jaxpr = _dce_open_jaxpr(jaxpr, out_unknowns, drop_outputs=True)\n+ jaxpr = convert_constvars_jaxpr(jaxpr)\n+\n+ # Known tracers get propagated as if they were constants\n+ known_tracers_out = [self.new_const(pval.get_known()) for pval in out_pvals\n+ if pval.is_known()]\n+\n+ # I'm not 100% if that's correct, but it is an assumption that\n+ # JaxprTrace.process_call already makes.\n+ if any(t.pval.is_known() for t in env_tracers):\n+ raise AssertionError(\"Please open a bug report!\")\n+ # Unknown tracers need to have the jaxpr set up as their recipe\n+ unknown_tracers_in = (*env_tracers, *(t for t in tracers if not t.pval.is_known()))\n+ unknown_tracers_out = [JaxprTracer(self, pval, None) for pval in out_pvals\n+ if not pval.is_known()]\n+ const_tracers = map(self.new_instantiated_const, consts)\n+\n+ # Set up new params\n+ new_in_axes = (*const_axes,\n+ *(None for _ in env_tracers),\n+ *(axis for axis, t in zip(in_axes, tracers)\n+ if not t.pval.is_known()))\n+ new_out_axes = tuple(axis for axis, pval in zip(out_axes, out_pvals)\n+ if not pval.is_known())\n+\n+ assert params['spmd_in_axes'] is None and params['spmd_out_axes_thunk'] is None\n+ new_params = dict(\n+ params,\n+ call_jaxpr=jaxpr,\n+ donated_invars=(*(False for _ in const_tracers),\n+ *(d for d, t in zip(donated_invars, tracers) if not t.pval.is_known())),\n+ in_axes=new_in_axes,\n+ out_axes=new_out_axes,\n+ spmd_out_axes=None)\n+ del new_params['out_axes_thunk']\n+ del new_params['spmd_out_axes_thunk']\n+\n+ eqn = new_eqn_recipe((*const_tracers, *unknown_tracers_in),\n+ unknown_tracers_out,\n+ primitive, new_params, source_info_util.current())\n+ for t in unknown_tracers_out: t.recipe = eqn\n+ return pe._zip_knowns(known_tracers_out, unknown_tracers_out, out_unknowns)\n+pe.JaxprTrace.process_xmap = _jaxpr_trace_process_xmap\n+\n+\ndef _batch_trace_update_spmd_axes(\nspmd_in_axes, spmd_out_axes_thunk,\naxis_name, dims, dims_out_thunk):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xmap_test.py",
"new_path": "tests/xmap_test.py",
"diff": "@@ -515,13 +515,26 @@ class XMapTest(XMapTestCase):\ny = rng.randn(*yshape)\nself.assertAllClose(fm(x, y), fref(x, y))\n- def testJVP(self):\n+ def testAutodiffBroadcast(self):\nf = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\nprecision=lax.Precision.HIGHEST)),\nin_axes=[['i', ...], {}], out_axes=['i', ...])\nx = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100\ny = jnp.arange(20, dtype=jnp.float32).reshape((4, 5)) / 100\njtu.check_grads(f, (x, y), order=2, modes=['fwd'])\n+ jtu.check_grads(f, (x, y), order=1, modes=['rev'])\n+ with self.assertRaises(AssertionError):\n+ # Second order reverse-mode differentiations seems to be broken,\n+ # likely due to the transpose of psum being defined incorrectly.\n+ jtu.check_grads(f, (x, y), order=2, modes=['rev'])\n+\n+ def testAutodiffNoBroadcast(self):\n+ f = xmap(lambda x, y: jnp.cos(lax.dot(x, jnp.sin(y),\n+ precision=lax.Precision.HIGHEST)),\n+ in_axes=[['i', ...], [None, 'i']], out_axes=['i'])\n+ x = jnp.arange(12, dtype=jnp.float32).reshape((3, 4)) / 100\n+ y = jnp.arange(12, dtype=jnp.float32).reshape((4, 3)) / 100\n+ jtu.check_grads(f, (x, y), order=2)\n@jtu.with_and_without_mesh\ndef testNamedShape(self, mesh, axis_resources):\n"
}
] | Python | Apache License 2.0 | google/jax | Add support for reverse-mode AD of xmap |
260,687 | 16.07.2021 02:36:45 | -19,080 | 61949b6f8b78687a1960c17593876cef4d6034b1 | fix small typo in docs/developer.md | [
{
"change_type": "MODIFY",
"old_path": "docs/developer.md",
"new_path": "docs/developer.md",
"diff": "@@ -131,7 +131,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-`ip install -r build/test-requirements.txt`.\n+`pip install -r build/test-requirements.txt`.\nThen, from the repository root directory run:\n```\n"
}
] | Python | Apache License 2.0 | google/jax | fix small typo in docs/developer.md |
260,299 | 16.07.2021 12:24:19 | -7,200 | 6ca775b10aa85ebfe31af1fec3db693f57f48c93 | Add TPU precision details to README gotchas | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -368,6 +368,10 @@ Some standouts:\ndouble-precision](https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#Double-(64bit)-precision)\n(64-bit, e.g. `float64`) one needs to set the `jax_enable_x64` variable at\nstartup (or set the environment variable `JAX_ENABLE_X64=True`).\n+ On TPU, JAX uses 32-bit values by default for everything _except_ internal\n+ temporary variables in 'matmul-like' operations, such as `jax.numpy.dot` and `lax.conv`.\n+ Those ops have a `precision` parameter which can be used to simulate\n+ true 32-bit, with a cost of possibly slower runtime.\n1. Some of NumPy's dtype promotion semantics involving a mix of Python scalars\nand NumPy types aren't preserved, namely `np.add(1, np.array([2],\nnp.float32)).dtype` is `float64` rather than `float32`.\n"
}
] | Python | Apache License 2.0 | google/jax | Add TPU precision details to README gotchas |
260,411 | 16.07.2021 17:23:34 | -10,800 | bd77a61d3170e72c5b8d3279fffacb058457c1dd | [jax2tf] Fix the shape polymorphism for batched while, and random_gamma. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -2634,16 +2634,15 @@ def _batched_cond_while(*args: TfVal, cond_nconsts: int,\nnew_carry: Sequence[TfVal] = _interpret_jaxpr(body_jaxpr, *body_consts,\n*carry,\nextra_name_stack=\"while/body\")\n-\n- def select_one_carry(new_c: TfVal, c: TfVal) -> TfVal:\n+ # We repeat those carries for which the loop termination condition is false\n+ def select_one_carry(new_c: TfVal, c: TfVal, c_aval: core.AbstractValue) -> TfVal:\npred_b_bcast = _broadcast_in_dim(\npred_b,\n- shape=new_c.shape,\n+ shape=c_aval.shape, # a JAX shape\nbroadcast_dimensions=list(range(len(pred_b.shape))))\nreturn tf.where(pred_b_bcast, new_c, c)\n- selected_carry: Sequence[TfVal] = list(\n- map(select_one_carry, new_carry, carry))\n+ selected_carry: Sequence[TfVal] = list(map(select_one_carry, new_carry, carry, body_jaxpr.out_avals))\nnext_pred_b, = _interpret_jaxpr(cond_jaxpr, *cond_consts, *selected_carry,\nextra_name_stack=\"body_pred\")\nreturn (next_pred_b, *selected_carry)\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": "@@ -1046,10 +1046,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[0]),\n# TODO: random_gamma does not work yet.\n- # _make_harness(\"random_gamma\", \"\",\n- # lambda key, a: jax.random.gamma(key, a),\n- # [RandArg((3, 2), np.uint32), RandArg((3, 3), _f32)],\n- # poly_axes=[0, 0]),\n+ _make_harness(\"random_gamma\", \"\",\n+ lambda key, a: jax.random.gamma(key, a),\n+ [RandArg((3, 2), np.uint32), RandArg((3, 3), _f32)],\n+ poly_axes=[0, 0]),\n_make_harness(\"reshape\", \"0\",\nlambda x: x.reshape([x.shape[0], -1]),\n@@ -1328,6 +1328,21 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\ntol = harness.params[\"tol\"]\nself.assertAllClose(res_jax, f_tf(*args), atol=tol, rtol=tol)\n+ def test_vmap_while(self):\n+ def cond_func(x): # x: f32[3]\n+ return jnp.sum(x) >= 0.\n+ def body_func(x): # x: f32[3]\n+ return x - 1.\n+ def f_jax(x):\n+ return lax.while_loop(cond_func, body_func, x)\n+\n+ self.CheckShapePolymorphism(\n+ jax.vmap(f_jax),\n+ input_signature=[tf.TensorSpec((None, 3), dtype=tf.float32)],\n+ polymorphic_shapes=[\"b, ...\"],\n+ expected_output_signature=tf.TensorSpec((None, 3), dtype=tf.float32)\n+ )\n+\ndef test_reshape_error(self):\nwith self.assertRaisesRegex(\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix the shape polymorphism for batched while, and random_gamma. |
260,374 | 08.07.2021 16:11:39 | 0 | 262b10ee5967fc2ae22d90359adcbfa74ab58098 | pmap integration | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -28,7 +28,7 @@ def initialize_cache(path):\ndef get_executable(xla_computation, compile_options) -> Optional[xla_client.Executable]:\n\"\"\"Returns the cached executable if present, or None otherwise.\"\"\"\n- assert _cache is not None, \"initialize_cache must be called before calling this function.\"\n+ assert _cache is not None, \"initialize_cache must be called before you can call get_executable()\"\ncache_key = get_cache_key(xla_computation, compile_options)\nxla_executable_serialized = _cache.get(cache_key)\nif not xla_executable_serialized:\n@@ -44,7 +44,7 @@ def get_executable(xla_computation, compile_options) -> Optional[xla_client.Exec\ndef put_executable(xla_computation, compile_options, executable: xla_client.Executable):\n\"\"\"Adds 'executable' to the cache, possibly evicting older entries.\"\"\"\n- assert _cache is not None, \"initialize_cache must be called before calling this function.\"\n+ assert _cache is not None, \"initialize_cache must be called before you can call put_executable()\"\ncache_key = get_cache_key(xla_computation, compile_options)\nbackend = jax.lib.xla_bridge.get_backend()\nserialized_executable = backend.serialize_executable(executable)\n@@ -123,3 +123,6 @@ def _hash_bool(hash_obj, bool_var):\ndef _hash_string(hash_obj, str_var):\nhash_obj.update(str_var.encode('utf-8').strip())\n+\n+def is_initialized():\n+ return _cache is not None\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -59,6 +59,20 @@ from . import partial_eval as pe\nfrom . import xla\nfrom . import ad\n+def compile_or_get_cached(backend, computation, compile_options):\n+ # Avoid import cycle between jax and jax.experimental\n+ from jax.experimental.compilation_cache import compilation_cache as cc\n+ if cc.is_initialized():\n+ cached_executable = cc.get_executable(computation, compile_options)\n+ if cached_executable is not None:\n+ return cached_executable\n+ else:\n+ compiled = xla.backend_compile(backend, computation, compile_options)\n+ cc.put_executable(computation, compile_options, compiled)\n+ return compiled\n+ else:\n+ return xla.backend_compile(backend, computation, compile_options)\n+\n# Built in Python lists don't support weak refs but subclasses of lists do.\nclass WeakRefList(list):\npass\n@@ -903,7 +917,8 @@ def parallel_callable(fun: lu.WrappedFun,\ninput_indices, input_sharding_specs,\nhandle_outs)\nreturn WeakRefList([execute_fun, None])\n- compiled = xla.backend_compile(backend, built, compile_options)\n+\n+ compiled = compile_or_get_cached(backend, built, compile_options)\nhandle_args = partial(shard_args, compiled.local_devices(), input_indices)\nexecute_fun = partial(execute_replicated, compiled, backend, handle_args, handle_outs)\nfingerprint = getattr(compiled, \"fingerprint\", None)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -16,10 +16,13 @@ from absl.testing import absltest\nimport hashlib\nfrom jax.experimental.compilation_cache import compilation_cache as cc\nimport jax\n+from jax import pmap, lax\nimport jax.test_util as jtu\nimport numpy as np\n+import os\nimport random\nimport tempfile\n+import unittest\nfrom unittest import SkipTest\nfrom jax.config import config\n@@ -28,6 +31,14 @@ FLAGS = config.FLAGS\nclass CompilationCacheTest(jtu.JaxTestCase):\n+ def setUp(self):\n+ super().setUp()\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest(\"serialize executable only works on TPU\")\n+ if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n+ raise SkipTest(\"the new TFRT runtime does not support serialization\")\n+\n+ @unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\ndef test_compile_options(self):\ncompile_options_not_filled = jax.lib.xla_bridge.get_compile_options(\nnum_replicas=1, num_partitions=1)\n@@ -130,10 +141,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\nself.assertEqual(cc.get_executable(computation, compile_options), None)\ndef test_diff_executables(self):\n- if jtu.device_under_test() != \"tpu\":\n- raise SkipTest(\"serialize executable only works on TPU\")\n- if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n- raise SkipTest(\"the new TFRT runtime does not support serialization\")\ncc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\n@@ -150,10 +157,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\ncc.get_executable(computation2, compile_options))\ndef test_put_executable(self):\n- if jtu.device_under_test() != \"tpu\":\n- raise SkipTest(\"serialize executable only works on TPU\")\n- if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n- raise SkipTest(\"the new TFRT runtime does not support serialization\")\ncc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\n@@ -169,6 +172,21 @@ class CompilationCacheTest(jtu.JaxTestCase):\nactual = jax.lib.xla_client.execute_with_python_values(deserialized_executable, inputs_to_executable, backend)\nself.assertEqual(expected, actual)\n+ def test_pmap(self):\n+ cc._cache = None\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n+ x = np.arange(jax.device_count(), dtype=np.int64)\n+ f(x)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 1)\n+ x = np.arange(jax.device_count(), dtype=np.float32)\n+ f(x)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 2)\n+ #TODO: create a test for calling pmap with the same input more than once\n+\ndef create_new_debug_options(self, debug_options_obj):\ndebug_options_obj.xla_cpu_enable_fast_math = False\ndebug_options_obj.xla_cpu_fast_math_honor_infs = False\n"
}
] | Python | Apache License 2.0 | google/jax | pmap integration |
260,411 | 16.07.2021 16:52:15 | -10,800 | 41d46b2a9143a2331802ea5055b63948fe97b451 | [jax2tf] Expand the handling of shape-polymorphic einsum.
einsum supports an API where the arrays are interleaved with list
of indices. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -435,7 +435,8 @@ def _einsum_contract_path(*operands, **kwargs):\n# sizes of operands and intermediate results.\nfake_ops = []\nfor operand in operands:\n- if isinstance(operand, str):\n+ # We replace only array operands\n+ if not hasattr(operand, \"dtype\"):\nfake_ops.append(operand)\nelse:\nshape = np.shape(operand)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"new_path": "jax/experimental/jax2tf/tests/shape_poly_test.py",
"diff": "@@ -982,22 +982,43 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"einsum\", \"0_alt\",\n+ lambda x: jnp.einsum(x, (..., 1), [...]),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+\n_make_harness(\"einsum\", \"1\",\nlambda x, y: jnp.einsum(\"...ij,...jk->...ik\", x, y),\n[RandArg((3, 4, 5), _f32), RandArg((3, 5, 6), _f32)],\npoly_axes=[0, 0]),\n+ _make_harness(\"einsum\", \"1_alt\",\n+ lambda x, y: jnp.einsum(x, [..., 0, 1], y, (..., 1, 2), [..., 0, 2]),\n+ [RandArg((3, 4, 5), _f32), RandArg((3, 5, 6), _f32)],\n+ poly_axes=[0, 0]),\n+\n_make_harness(\"einsum\", \"2\",\nlambda x, y: jnp.einsum(\"...ij,jk->...ik\", x, y),\n[RandArg((3, 4, 5), _f32), RandArg((5, 6), _f32)],\npoly_axes=[0, None]),\n+ _make_harness(\"einsum\", \"2_alt\",\n+ lambda x, y: jnp.einsum(x, [..., 0, 1], y, [1, 2], [..., 0, 2]),\n+ [RandArg((3, 4, 5), _f32), RandArg((5, 6), _f32)],\n+ poly_axes=[0, None]),\n+\n_make_harness(\"einsum\", \"3\",\n# Reduced dimension is polymorphic\nlambda x, y: jnp.einsum(\"ij,jk->ik\", x, y),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n+ _make_harness(\"einsum\", \"3_alt\",\n+ # Reduced dimension is polymorphic\n+ lambda x, y: jnp.einsum(x, [0, 1], y, [1, 2], [0, 2]),\n+ [RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\n+ poly_axes=[1, 0]),\n+\n_make_harness(\"einsum\", \"4\",\n# Reduced dimension is polymorphic, and is 2*b\nlambda x, y: jnp.einsum(\"ij,jk->ik\",\n@@ -1006,6 +1027,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n+ _make_harness(\"einsum\", \"4_alt\",\n+ # Reduced dimension is polymorphic, and is 2*b\n+ lambda x, y: jnp.einsum(jnp.concatenate([x, x], axis=1), [0, 1],\n+ jnp.concatenate([y, y], axis=0), [1, 2],\n+ [0, 2]),\n+ [RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\n+ poly_axes=[1, 0]),\n+\n# TODO(necula): not supported yet\n# _make_harness(\"jnp_getitem\", \"\",\n# lambda a, i: a[i],\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Expand the handling of shape-polymorphic einsum.
einsum supports an API where the arrays are interleaved with list
of indices. |
260,456 | 17.07.2021 08:04:56 | 0 | ee08acd046e6065aacf5a0e94bbdf76000f63400 | update rocblas because of | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/rocblas.cc",
"new_path": "jaxlib/rocblas.cc",
"diff": "@@ -67,7 +67,7 @@ template <>\nif (stream) {\nThrowIfErrorStatus(rocblas_set_stream(handle, stream));\n}\n- return rocBlasHandlePool::Handle(pool, handle);\n+ return rocBlasHandlePool::Handle(pool, handle, stream);\n}\n// Set of types known to Rocsolver.\n"
}
] | Python | Apache License 2.0 | google/jax | update rocblas because of PR-7306 |
260,411 | 18.07.2021 19:35:14 | -10,800 | 117d0d23ab26a5e1585f2027bc90f75393e23fb7 | Attempt to fix RTD build
It seems that the failure is for transformations.md | [
{
"change_type": "MODIFY",
"old_path": "docs/conf.py",
"new_path": "docs/conf.py",
"diff": "@@ -117,6 +117,8 @@ exclude_patterns = [\n'notebooks/*.md',\n'jax-101/*.md',\n'autodidax.md',\n+ # Attempt to fix RTD build failure\n+ 'transformations.md',\n]\n# The name of the Pygments (syntax highlighting) style to use.\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/index.rst",
"new_path": "docs/index.rst",
"diff": "@@ -23,7 +23,6 @@ parallelize, Just-In-Time compile to GPU/TPU, and more.\n:caption: Reference Documentation\nfaq\n- transformations\nasync_dispatch\njaxpr\nnotebooks/convolutions\n"
}
] | Python | Apache License 2.0 | google/jax | Attempt to fix RTD build
It seems that the failure is for transformations.md |
260,411 | 18.07.2021 19:03:59 | -10,800 | 0693c316e4044a6bb425da69e7e79364162b3e59 | [jax2tf] Improved error checking for inconsistent use of a dimension variable
Previously the check was done only for multiple occurrences of a shape
variable in one argument. Now we check across all arguments. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -711,7 +711,7 @@ self.assertEqual(0, f_jax(x0)) # JAX sees that the x.shape[0] == 0\n# jax2tf catches the broken assumption b >= 1 if the converted function is executed\n# eagerly.\n-# Raises: ValueError: PolyShape 'b' has dimension variable 'b' corresponding to 0, for argument shape (0,)\n+# Raises: ValueError: PolyShape ('b',) has dimension variable 'b' corresponding to 0, for argument shapes (TensorShape([0]),)\njax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0))\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption:\n@@ -734,7 +734,7 @@ self.assertEqual(0, f_jax(x45)) # JAX seems that x.shape[0] != x.shape[1]\n# jax2tf catches the broken assumption x.shape[0] == x.shape[1] if the converted\n# function is executed eagerly.\n-# Raises: ValueError: PolyShape 'b, b' has dimension variable 'b' corresponding to multiple values ([4, 5]), for argument shape (4, 5)\n+# Raises: ValueError: PolyShape ('b, b',) has dimension variable 'b' corresponding to multiple values {4, 5}, for argument shapes (TensorShape([4, 5]),)\njax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"])(x45)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Experimental module transforms JAX functions to be executed by TensorFlow.\"\"\"\n+import collections\nfrom functools import partial\nimport contextlib\nimport os\nimport re\nimport string\nimport threading\n-from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union\n+from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union\nimport jax\nfrom jax._src import ad_util\n@@ -588,6 +589,10 @@ def _args_to_avals_and_env(\n\"\"\"\nshapeenv: _ShapeEnv = {}\n+ # Map shape variables to the set of integers they correspond to in the\n+ # actual arguments\n+ shape_var_map: Dict[str, Set[int]] = collections.defaultdict(set)\n+\ndef input_aval(arg: TfVal,\narg_jax_dtype: DType,\npolymorphic_shape: Optional[str]) -> core.AbstractValue:\n@@ -596,23 +601,38 @@ def _args_to_avals_and_env(\naval_shape = shape_poly.parse_spec(polymorphic_shape, arg_shape)\nfor i, d in enumerate(aval_shape):\n+ dim_size = arg_shape[i]\n+ if isinstance(dim_size, tf.compat.v1.Dimension):\n+ dim_size = dim_size.value\nif not shape_poly.is_poly_dim(d):\n- assert d == arg_shape[i]\n+ assert d == dim_size\nelse:\nd_var = d.to_var() # type: ignore\n- if d_var is not None and d_var not in shapeenv:\n+ if d_var is not None:\n+ if d_var not in shapeenv:\n# Even if the shape of `arg` is known, we still use `tf.shape` for\n# safety, because the promise is that we will convert the function\n# to work for any value of the dimension.\nshapeenv[d_var] = tf.shape(arg)[i] # type: ignore[index]\n- else:\n- # TODO: add an assertion tf.shape(arg)[i] == env[d]\n- pass\n-\n+ if dim_size is not None:\n+ shape_var_map[d_var].add(int(dim_size))\nreturn core.ShapedArray(aval_shape, arg_jax_dtype)\navals = tuple(map(input_aval, args, arg_jax_dtypes, polymorphic_shapes)) # type: ignore\n+ arg_shapes = tuple(np.shape(a) for a in args)\n+\n+ for dim_var, dim_var_values in shape_var_map.items():\n+ if len(dim_var_values) != 1:\n+ msg = (f\"PolyShape {tuple(polymorphic_shapes)} has dimension variable '{dim_var}' \"\n+ f\"corresponding to multiple values {set(sorted(dim_var_values))}, for \"\n+ f\"argument shapes {arg_shapes}\")\n+ raise ValueError(msg)\n+ elif list(dim_var_values)[0] <= 0:\n+ msg = (f\"PolyShape {tuple(polymorphic_shapes)} has dimension variable '{dim_var}' \"\n+ f\"corresponding to 0, for argument shapes {arg_shapes}\")\n+ raise ValueError(msg)\n+\nreturn avals, shapeenv\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -559,7 +559,7 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nreturn functools.reduce(op.mul, map(_parse_factor, factors))\nreturn functools.reduce(op.add, map(_parse_term, terms))\n- shape_var_map: Dict[str, Set[int]] = collections.defaultdict(set)\n+\ndef _process_dim(i: int, dim_spec: Union[str, int]):\nif isinstance(dim_spec, str):\ndim_spec = dim_spec.strip()\n@@ -588,24 +588,9 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nf\"for known dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_size\n- # We have a dimension polynomial for a known dimension.\n- dim_var = dim_poly.to_var() # type: ignore\n- if dim_var is not None:\n- shape_var_map[dim_spec].add(dim_size) # type: ignore\nreturn dim_poly\ndims = tuple([_process_dim(i, ds) for i, ds in enumerate(spec_tuple)])\n- for dim_var, dim_var_values in shape_var_map.items():\n- if len(dim_var_values) != 1:\n- msg = (f\"PolyShape '{spec}' has dimension variable '{dim_var}' \"\n- f\"corresponding to multiple values ({sorted(dim_var_values)}), for \"\n- f\"argument shape {arg_shape}\")\n- raise ValueError(msg)\n- elif list(dim_var_values)[0] <= 0:\n- msg = (f\"PolyShape '{spec}' has dimension variable '{dim_var}' \"\n- f\"corresponding to 0, for argument shape {arg_shape}\")\n- raise ValueError(msg)\n-\nreturn dims\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": "@@ -335,7 +335,6 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nreturn tf.Variable(\nnp.ones(initializer_shape, np.float32), dtype=tf.float32, shape=shape)\n-\n# Known shapes for the arguments\ncheck_avals(\nargs=[const((2, 3))],\n@@ -482,19 +481,29 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(a, a)' has dimension variable 'a' corresponding to \"\n- \"multiple values ([2, 3]), for argument shape (2, 3)\"\n+ \"PolyShape ('(a, a)',) has dimension variable 'a' corresponding to multiple values {2, 3}, for argument shapes (TensorShape([2, 3]),)\"\n)):\ncheck_avals(\nargs=[tf_var([2, 3], initializer_shape=(2, 3))],\npolymorphic_shapes=[\"(a, a)\"],\nexpected_avals=None)\n+ # Same error across multiple arguments\n+ with self.assertRaisesRegex(\n+ ValueError,\n+ re.escape(\n+ \"PolyShape ('a, ...', 'a') has dimension variable 'a' corresponding to multiple values {2, 5}\"\n+ )):\n+ check_avals(\n+ args=[tf_var([2, 3], initializer_shape=(2, 3)),\n+ tf_var([5], initializer_shape=[5])],\n+ polymorphic_shapes=[\"a, ...\", \"a\"],\n+ expected_avals=None)\n+\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(a,)' has dimension variable 'a' corresponding to 0, \"\n- \"for argument shape (0,)\"\n+ \"PolyShape ('(a,)',) has dimension variable 'a' corresponding to 0, for argument shapes (TensorShape([0]),)\"\n)):\ncheck_avals(\nargs=[tf_var([0], initializer_shape=(0))],\n@@ -741,7 +750,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# eagerly.\n# Raises: ValueError: PolyShape 'b' has dimension variable 'b' corresponding to 0, for argument shape (0,)\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"PolyShape 'b' has dimension variable 'b' corresponding to 0, for argument shape (0,)\")):\n+ re.escape(\"PolyShape ('b',) has dimension variable 'b' corresponding to 0, for argument shapes (TensorShape([0]),)\")):\njax2tf.convert(f_jax, polymorphic_shapes=[\"b\"])(x0)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption:\n@@ -761,7 +770,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# function is executed eagerly.\n# Raises: ValueError: PolyShape 'b, b' has dimension variable 'b' corresponding to multiple values ([4, 5]), for argument shape (4, 5)\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"PolyShape 'b, b' has dimension variable 'b' corresponding to multiple values ([4, 5]), for argument shape (4, 5)\")):\n+ re.escape(\"PolyShape ('b, b',) has dimension variable 'b' corresponding to multiple values {4, 5}, for argument shapes (TensorShape([4, 5]),)\")):\njax2tf.convert(f_jax, polymorphic_shapes=[\"b, b\"])(x45)\n# However, if we first trace to a TensorFlow graph, we may miss the broken assumption.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improved error checking for inconsistent use of a dimension variable
Previously the check was done only for multiple occurrences of a shape
variable in one argument. Now we check across all arguments. |
260,374 | 19.07.2021 21:53:27 | 0 | 711c3130261f26fcdf570c28dd152f7f54d406c6 | added tearDown() method to test class | [
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -38,6 +38,10 @@ class CompilationCacheTest(jtu.JaxTestCase):\nif jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\nraise SkipTest(\"the new TFRT runtime does not support serialization\")\n+ def tearDown(self):\n+ super().tearDown()\n+ cc._cache = None\n+\n@unittest.skipIf(jax.lib.version < (0, 1, 68), \"fails with earlier jaxlibs\")\ndef test_compile_options(self):\ncompile_options_not_filled = jax.lib.xla_bridge.get_compile_options(\n@@ -128,11 +132,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\ncc.get_cache_key(computation2, compile_options))\ndef test_get_no_executable(self):\n- if jtu.device_under_test() != \"tpu\":\n- raise SkipTest(\"serialize executable only works on TPU\")\n- if jax.lib.xla_bridge.get_backend().runtime_type == \"tfrt\":\n- raise SkipTest(\"the new TFRT runtime does not support serialization\")\n- cc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\ncomputation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n@@ -141,7 +140,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\nself.assertEqual(cc.get_executable(computation, compile_options), None)\ndef test_diff_executables(self):\n- cc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\ncomputation1 = jax.xla_computation(lambda x, y: x + y)(1, 1)\n@@ -157,7 +155,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\ncc.get_executable(computation2, compile_options))\ndef test_put_executable(self):\n- cc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\ncomputation = jax.xla_computation(lambda x, y: x + y)(1, 1)\n@@ -173,7 +170,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\nself.assertEqual(expected, actual)\ndef test_pmap(self):\n- cc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\nf = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n"
}
] | Python | Apache License 2.0 | google/jax | added tearDown() method to test class |
260,374 | 19.07.2021 19:10:16 | 0 | 2eaadd86b6c7249e5ea09b6a23ce7e79fa9d8b7d | jit integration with persistent compilation cache | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -59,20 +59,6 @@ from . import partial_eval as pe\nfrom . import xla\nfrom . import ad\n-def compile_or_get_cached(backend, computation, compile_options):\n- # Avoid import cycle between jax and jax.experimental\n- from jax.experimental.compilation_cache import compilation_cache as cc\n- if cc.is_initialized():\n- cached_executable = cc.get_executable(computation, compile_options)\n- if cached_executable is not None:\n- return cached_executable\n- else:\n- compiled = xla.backend_compile(backend, computation, compile_options)\n- cc.put_executable(computation, compile_options, compiled)\n- return compiled\n- else:\n- return xla.backend_compile(backend, computation, compile_options)\n-\n# Built in Python lists don't support weak refs but subclasses of lists do.\nclass WeakRefList(list):\npass\n@@ -918,7 +904,7 @@ def parallel_callable(fun: lu.WrappedFun,\nhandle_outs)\nreturn WeakRefList([execute_fun, None])\n- compiled = compile_or_get_cached(backend, built, compile_options)\n+ compiled = xla.compile_or_get_cached(backend, built, compile_options)\nhandle_args = partial(shard_args, compiled.local_devices(), input_indices)\nexecute_fun = partial(execute_replicated, compiled, backend, handle_args, handle_outs)\nfingerprint = getattr(compiled, \"fingerprint\", None)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -61,6 +61,20 @@ XlaExecutable = Any # xla_extension.LocalExecutable\n# This flag is set on exit; no logging should be attempted\n_on_exit = False\n+\n+def compile_or_get_cached(backend, computation, compile_options):\n+ # Avoid import cycle between jax and jax.experimental\n+ from jax.experimental.compilation_cache import compilation_cache as cc\n+ if cc.is_initialized():\n+ cached_executable = cc.get_executable(computation, compile_options)\n+ if cached_executable is not None:\n+ return cached_executable\n+ else:\n+ compiled = backend_compile(backend, computation, compile_options)\n+ cc.put_executable(computation, compile_options, compiled)\n+ return compiled\n+ return backend_compile(backend, computation, compile_options)\n+\ndef identity(x): return x\n_scalar_types = dtypes.python_scalar_dtypes.keys()\n@@ -741,7 +755,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nnum_partitions=1,\ndevice_assignment=(device.id,) if device else None)\noptions.parameter_is_tupled_arguments = tuple_args\n- compiled = backend_compile(backend, built, options)\n+ compiled = compile_or_get_cached(backend, built, options)\nif nreps == 1:\nreturn partial(_execute_compiled, compiled, out_avals, result_handlers,\nkept_var_idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "@@ -16,7 +16,7 @@ from absl.testing import absltest\nimport hashlib\nfrom jax.experimental.compilation_cache import compilation_cache as cc\nimport jax\n-from jax import pmap, lax\n+from jax import jit, lax, pmap\nimport jax.test_util as jtu\nimport numpy as np\nimport os\n@@ -187,6 +187,18 @@ class CompilationCacheTest(jtu.JaxTestCase):\nself.assertEqual(files_in_directory, 2)\n#TODO: create a test for calling pmap with the same input more than once\n+ def test_jit(self):\n+ cc._cache = None\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ f = jit(lambda x: x*x)\n+ f(1)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 1)\n+ f(1.0)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 2)\n+\ndef create_new_debug_options(self, debug_options_obj):\ndebug_options_obj.xla_cpu_enable_fast_math = False\ndebug_options_obj.xla_cpu_fast_math_honor_infs = False\n"
}
] | Python | Apache License 2.0 | google/jax | jit integration with persistent compilation cache |
260,374 | 20.07.2021 16:16:21 | 0 | 65c6a6a6fb0b771cf93512fe06c0b2c62f8395b6 | xmap and pjit integration | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/pxla.py",
"new_path": "jax/interpreters/pxla.py",
"diff": "@@ -1569,7 +1569,7 @@ def compile_and_wrap_mesh_hlo(computation: xc.XlaComputation, backend,\nreturn backend.compile_replicated(computation, compile_options,\ninput_indices, local_input_specs,\nhandle_outs)\n- compiled = xla.backend_compile(backend, computation, compile_options)\n+ compiled = xla.compile_or_get_cached(backend, computation, compile_options)\nhandle_args = partial(shard_args, compiled.local_devices(), input_indices)\nreturn partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/compilation_cache_test.py",
"new_path": "tests/compilation_cache_test.py",
"diff": "# limitations under the License.\nfrom absl.testing import absltest\n+from functools import partial\nimport hashlib\n+from jax.experimental import PartitionSpec as P\nfrom jax.experimental.compilation_cache import compilation_cache as cc\n+from jax.experimental.maps import xmap\n+from jax.experimental.pjit import pjit\nimport jax\nfrom jax import jit, lax, pmap\n+from jax._src.util import prod\nimport jax.test_util as jtu\nimport numpy as np\nimport os\n@@ -184,7 +189,6 @@ class CompilationCacheTest(jtu.JaxTestCase):\n#TODO: create a test for calling pmap with the same input more than once\ndef test_jit(self):\n- cc._cache = None\nwith tempfile.TemporaryDirectory() as tmpdir:\ncc.initialize_cache(tmpdir)\nf = jit(lambda x: x*x)\n@@ -195,6 +199,46 @@ class CompilationCacheTest(jtu.JaxTestCase):\nfiles_in_directory = len(os.listdir(tmpdir))\nself.assertEqual(files_in_directory, 2)\n+ @jtu.with_mesh([('x', 2)])\n+ def test_pjit(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ @partial(pjit,\n+ in_axis_resources=(P('x'), P('x')),\n+ out_axis_resources=None)\n+ def f(x, y):\n+ return x + y\n+\n+ shape = (8, 8)\n+ x = np.arange(prod(shape), dtype=np.int64).reshape(shape)\n+ f(x, x + 1)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 1)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ f(x, x + 1)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 2)\n+\n+ @jtu.with_mesh([('x', 2)])\n+ def test_xmap(self):\n+ with tempfile.TemporaryDirectory() as tmpdir:\n+ cc.initialize_cache(tmpdir)\n+ def f(x):\n+ return x * 2\n+ devices = np.array(jax.local_devices()[:2])\n+ if devices.size < 2:\n+ raise SkipTest(\"Test requires 2 devices\")\n+ x = np.arange(8, dtype=np.int64).reshape((2, 2, 2))\n+ xmap(f, in_axes=['a', ...], out_axes=['a', ...],\n+ axis_resources={'a': 'x'})(x)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 1)\n+ x = np.arange(8, dtype=np.float32).reshape((2, 2, 2))\n+ xmap(f, in_axes=['a', ...], out_axes=['a', ...],\n+ axis_resources={'a': 'x'})(x)\n+ files_in_directory = len(os.listdir(tmpdir))\n+ self.assertEqual(files_in_directory, 2)\n+\ndef create_new_debug_options(self, debug_options_obj):\ndebug_options_obj.xla_cpu_enable_fast_math = False\ndebug_options_obj.xla_cpu_fast_math_honor_infs = False\n"
}
] | Python | Apache License 2.0 | google/jax | xmap and pjit integration |
260,424 | 21.07.2021 10:29:46 | -3,600 | 24c9a933d6b00c8690b52c9ee03dc5a5dc435011 | Add shape and dtype of leaked tracer to UnexpectedTracerError. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -445,7 +445,8 @@ def escaped_tracer_error(tracer, detail=None):\npass\nelse:\nmsg += ('\\nThe tracer that caused this error was created on line '\n- f'{source_info_util.summarize(line_info)}.\\n')\n+ f'{source_info_util.summarize(line_info)}. The tracer has'\n+ f' shape {tracer.shape} and dtype {tracer.dtype}.\\n')\nif num_frames > 0:\nmsg += (f'When the tracer was created, the final {num_frames} stack '\n'frames (most recent last) excluding JAX-internal frames were:\\n'\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2292,6 +2292,12 @@ class APITest(jtu.JaxTestCase):\njax.eval_shape(self.helper_save_tracer, 1)\n_ = self._saved_tracer+1\n+ def test_escaped_tracer_shape_dtype(self):\n+ with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ r\"shape \\(4, 3\\) and dtype int32\"):\n+ jax.jit(self.helper_save_tracer)(jnp.ones((4, 3), dtype=jnp.int32))\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"
}
] | Python | Apache License 2.0 | google/jax | Add shape and dtype of leaked tracer to UnexpectedTracerError. |
260,333 | 21.07.2021 14:50:10 | 14,400 | 215e7d618fcec2f0a9d31adb1c13dae4c73c7cf8 | Make jax arrays not pass isinstance checks for hashable. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1311,11 +1311,6 @@ for device_array in [DeviceArray]:\n# clobbered when jax.numpy is imported, but useful in tests\nsetattr(device_array, \"__eq__\", lambda self, other: self._value == other)\n- def __hash__(self):\n- raise TypeError(\"JAX DeviceArray, like numpy.ndarray, is not hashable.\")\n-\n- setattr(device_array, \"__hash__\", __hash__)\n-\n# The following methods are dynamically overridden in lax_numpy.py.\ndef raise_not_implemented():\nraise NotImplementedError\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2077,10 +2077,7 @@ class APITest(jtu.JaxTestCase):\nrep = jnp.ones(()) + 1.\nself.assertIsInstance(rep, jax.interpreters.xla.DeviceArray)\nmsg = \"JAX DeviceArray, like numpy.ndarray, is not hashable.\"\n- with self.assertRaisesRegex(TypeError, msg):\n- hash(rep)\n- with self.assertRaisesRegex(TypeError, msg):\n- hash(rep.device_buffer)\n+ self.assertNotIsInstance(rep, collections.Hashable)\ndef test_grad_without_enough_args_error_message(self):\n# https://github.com/google/jax/issues/1696\n"
}
] | Python | Apache License 2.0 | google/jax | Make jax arrays not pass isinstance checks for hashable. |
260,333 | 21.07.2021 16:12:52 | 14,400 | 00a273d1fe46f2b8fd643377bac72b6c6188eabc | Add assert raises check. | [
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2077,6 +2077,8 @@ class APITest(jtu.JaxTestCase):\nrep = jnp.ones(()) + 1.\nself.assertIsInstance(rep, jax.interpreters.xla.DeviceArray)\nself.assertNotIsInstance(rep, collections.Hashable)\n+ with self.assertRaisesRegex(TypeError, 'unhashable type'):\n+ hash(rep)\ndef test_grad_without_enough_args_error_message(self):\n# https://github.com/google/jax/issues/1696\n"
}
] | Python | Apache License 2.0 | google/jax | Add assert raises check. |
260,333 | 21.07.2021 17:13:40 | 14,400 | 231b8cbc497f99e138766fc2e953b02209bb5b9d | Explicitly set array to be unhashable. | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1308,6 +1308,9 @@ for device_array in [DeviceArray]:\nsetattr(device_array, \"__reduce__\",\npartialmethod(_forward_to_value, op.methodcaller(\"__reduce__\")))\n+ # explicitly set to be unhashable.\n+ setattr(device_array, \"__hash__\", None)\n+\n# clobbered when jax.numpy is imported, but useful in tests\nsetattr(device_array, \"__eq__\", lambda self, other: self._value == other)\n"
}
] | Python | Apache License 2.0 | google/jax | Explicitly set array to be unhashable. |
260,374 | 21.07.2021 22:22:40 | 0 | 86985fd4c18c0e712620d283540ea51f809db69d | add parameter to initalize_cache function and added __init__ file | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/compilation_cache/__init__.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"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -20,11 +20,14 @@ from typing import Optional\n_cache = None\n-def initialize_cache(path):\n- \"\"\"Creates a global cache object. Should only be called once per process.\"\"\"\n+def initialize_cache(path, max_cache_size_bytes=32 * 2**30):\n+ \"\"\"Creates a global cache object. Should only be called once per process.\n+\n+ max_cache_sixe defaults to 32GiB.\n+ \"\"\"\nglobal _cache\nassert _cache == None, f\"The cache path has already been initialized to {_cache}\"\n- _cache = FileSystemCache(path)\n+ _cache = FileSystemCache(path, max_cache_size_bytes)\ndef get_executable(xla_computation, compile_options) -> Optional[xla_client.Executable]:\n\"\"\"Returns the cached executable if present, or None otherwise.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | add parameter to initalize_cache function and added __init__ file |
260,335 | 21.07.2021 21:14:40 | 25,200 | fd5dec7b685afae4ce83ffb663cb1f55ddad9070 | fix xla.lower_fun axis env issue | [
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -1021,6 +1021,7 @@ def lower_fun(fun, multiple_results, parallel=False, with_avals=False, backend=N\nwrapped_fun = lu.wrap_init(fun, params)\nif not multiple_results:\nwrapped_fun = _tuple_output(wrapped_fun)\n+ with core.extend_axis_env_nd(zip(axis_env.names, axis_env.sizes)):\njaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, avals)\nouts = jaxpr_subcomp(c, jaxpr, backend, axis_env, _xla_consts(c, consts), '',\n*xla_args)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -1788,6 +1788,17 @@ class APITest(jtu.JaxTestCase):\ndef test_xla_computation_donate_argnums(self):\napi.xla_computation(lambda x: None, donate_argnums=(0,))(3) # doesn't crash\n+ def test_xla_computation_lower_fun_axis_env(self):\n+ axis_name = 'i'\n+ def fn(x):\n+ y = lax.all_gather(\n+ x, axis_name=axis_name)\n+ return y * lax.axis_index(axis_name).astype(jnp.float32)\n+\n+ input_x = jnp.ones((5,6,4))\n+ axis_env = [(axis_name, api.local_device_count())]\n+ _ = api.xla_computation(fn, axis_env=axis_env, backend='cpu')(input_x)\n+\ndef test_concurrent_device_get_and_put(self):\ndef f(x):\nfor _ in range(100):\n"
}
] | Python | Apache License 2.0 | google/jax | fix xla.lower_fun axis env issue |
260,335 | 22.07.2021 21:09:58 | 25,200 | fa274f3acec948bd7dc8be36c626b0e804a45867 | small tweaks, type annotations | [
{
"change_type": "MODIFY",
"old_path": "docs/autodidax.ipynb",
"new_path": "docs/autodidax.ipynb",
"diff": "\" dynamic_trace = prev_dynamic_trace\\n\",\n\"\\n\",\n\"@lru_cache()\\n\",\n- \"def make_jaxpr(f, *avals_in):\\n\",\n+ \"def make_jaxpr(f: Callable, *avals_in: ShapedArray,\\n\",\n+ \" ) -> Tuple[Jaxpr, List[Any], PyTreeDef]:\\n\",\n\" avals_in, in_tree = tree_flatten(avals_in)\\n\",\n\" f, out_tree = flatten_fun(f, in_tree)\\n\",\n\"\\n\",\n},\n\"outputs\": [],\n\"source\": [\n- \"def partial_eval_flat(f, pvals_in: List[PartialVal]):\\n\",\n+ \"def partial_eval_flat(f: Callable, pvals_in: List[PartialVal]\\n\",\n+ \" ) -> Tuple[Jaxpr, List[PartialVal], List[Any]]:\\n\",\n\" with new_main(PartialEvalTrace) as main:\\n\",\n\" trace = PartialEvalTrace(main)\\n\",\n\" tracers_in = [trace.new_arg(pval) for pval in pvals_in]\\n\",\n\" outs = f(*tracers_in)\\n\",\n\" tracers_out = [full_raise(trace, out) for out in outs]\\n\",\n- \" jaxpr, consts = tracers_to_jaxpr(tracers_in, tracers_out)\\n\",\n\" pvals_out = [t.pval for t in tracers_out]\\n\",\n+ \" unk_tracers_in = [t for t in tracers_in if t.pval.is_unknown]\\n\",\n+ \" unk_tracers_out = [t for t in tracers_out if t.pval.is_unknown]\\n\",\n+ \" jaxpr, consts = tracers_to_jaxpr(unk_tracers_in, unk_tracers_out)\\n\",\n\" return jaxpr, pvals_out, consts\"\n]\n},\n\"class ConstRecipe(NamedTuple):\\n\",\n\" val: Any\\n\",\n\"\\n\",\n- \"class JaxprEqnRecipe:\\n\",\n+ \"class JaxprEqnRecipe(NamedTuple):\\n\",\n\" prim: Primitive\\n\",\n\" tracers_in: List['PartialEvalTracer']\\n\",\n\" params: Dict[str, Any]\\n\",\n\" avals_out: List[ShapedArray]\\n\",\n\" tracer_refs_out: List['ReferenceType[PartialEvalTracer]']\\n\",\n\"\\n\",\n- \" def __init__(self, prim, tracers_in, params, avals_out, tracer_refs_out):\\n\",\n- \" self.prim = prim\\n\",\n- \" self.tracers_in = tracers_in\\n\",\n- \" self.params = params\\n\",\n- \" self.avals_out = avals_out\\n\",\n- \" self.tracer_refs_out = tracer_refs_out\\n\",\n- \"\\n\",\n\"JaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe]\"\n]\n},\n\"source\": [\n\"class PartialEvalTracer(Tracer):\\n\",\n\" pval: PartialVal\\n\",\n- \" recipe: JaxprRecipe\\n\",\n+ \" recipe: Optional[JaxprRecipe]\\n\",\n\"\\n\",\n\" def __init__(self, trace, pval, recipe):\\n\",\n\" self._trace = trace\\n\",\n\" self.pval = pval\\n\",\n\" self.recipe = recipe\\n\",\n\"\\n\",\n- \" @property\\n\",\n- \" def aval(self):\\n\",\n- \" return self.pval.aval\\n\",\n+ \" aval = property(lambda self: self.pval.aval)\\n\",\n\"\\n\",\n\" def full_lower(self):\\n\",\n\" if self.pval.is_known:\\n\",\n\"source\": [\n\"def tracers_to_jaxpr(tracers_in: List[PartialEvalTracer],\\n\",\n\" tracers_out: List[PartialEvalTracer]):\\n\",\n- \" tracers_in = [t for t in tracers_in if t.pval.is_unknown]\\n\",\n- \" tracers_out = [t for t in tracers_out if t.pval.is_unknown]\\n\",\n- \"\\n\",\n\" tracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in}\\n\",\n\" constvar_to_val = {}\\n\",\n\" constid_to_var = {}\\n\",\n\" instantiate: Optional[List[bool]] = None,\\n\",\n\" ) -> Tuple[Jaxpr, Jaxpr, List[bool], int]:\\n\",\n\" env: Dict[Var, bool] = {}\\n\",\n- \" residuals = set()\\n\",\n+ \" residuals: Set[Var] = set()\\n\",\n\"\\n\",\n\" def read(v: Atom) -> bool:\\n\",\n\" return type(v) is Var and env[v]\\n\",\n\" def write(unk: bool, v: Var) -> None:\\n\",\n\" env[v] = unk\\n\",\n\"\\n\",\n- \" def new_res(v: Var) -> Var:\\n\",\n- \" return residuals.add(v) or v\\n\",\n+ \" def new_res(x: Atom) -> Atom:\\n\",\n+ \" if type(x) is Var: residuals.add(x)\\n\",\n+ \" return x\\n\",\n\"\\n\",\n\" eqns1, eqns2 = [], []\\n\",\n\" map(write, in_unknowns, jaxpr.in_binders)\\n\",\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/autodidax.md",
"new_path": "docs/autodidax.md",
"diff": "@@ -1402,7 +1402,8 @@ def new_dynamic(main: MainTrace):\ndynamic_trace = prev_dynamic_trace\n@lru_cache()\n-def make_jaxpr(f, *avals_in):\n+def make_jaxpr(f: Callable, *avals_in: ShapedArray,\n+ ) -> Tuple[Jaxpr, List[Any], PyTreeDef]:\navals_in, in_tree = tree_flatten(avals_in)\nf, out_tree = flatten_fun(f, in_tree)\n@@ -2051,14 +2052,17 @@ return a list of `PartialVal` outputs along with a jaxpr representing the\ndelayed computation:\n```{code-cell}\n-def partial_eval_flat(f, pvals_in: List[PartialVal]):\n+def partial_eval_flat(f: Callable, pvals_in: List[PartialVal]\n+ ) -> Tuple[Jaxpr, List[PartialVal], List[Any]]:\nwith new_main(PartialEvalTrace) as main:\ntrace = PartialEvalTrace(main)\ntracers_in = [trace.new_arg(pval) for pval in pvals_in]\nouts = f(*tracers_in)\ntracers_out = [full_raise(trace, out) for out in outs]\n- jaxpr, consts = tracers_to_jaxpr(tracers_in, tracers_out)\npvals_out = [t.pval for t in tracers_out]\n+ unk_tracers_in = [t for t in tracers_in if t.pval.is_unknown]\n+ unk_tracers_out = [t for t in tracers_out if t.pval.is_unknown]\n+ jaxpr, consts = tracers_to_jaxpr(unk_tracers_in, unk_tracers_out)\nreturn jaxpr, pvals_out, consts\n```\n@@ -2079,36 +2083,27 @@ class LambdaBindingRecipe(NamedTuple):\nclass ConstRecipe(NamedTuple):\nval: Any\n-class JaxprEqnRecipe:\n+class JaxprEqnRecipe(NamedTuple):\nprim: Primitive\ntracers_in: List['PartialEvalTracer']\nparams: Dict[str, Any]\navals_out: List[ShapedArray]\ntracer_refs_out: List['ReferenceType[PartialEvalTracer]']\n- def __init__(self, prim, tracers_in, params, avals_out, tracer_refs_out):\n- self.prim = prim\n- self.tracers_in = tracers_in\n- self.params = params\n- self.avals_out = avals_out\n- self.tracer_refs_out = tracer_refs_out\n-\nJaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe]\n```\n```{code-cell}\nclass PartialEvalTracer(Tracer):\npval: PartialVal\n- recipe: JaxprRecipe\n+ recipe: Optional[JaxprRecipe]\ndef __init__(self, trace, pval, recipe):\nself._trace = trace\nself.pval = pval\nself.recipe = recipe\n- @property\n- def aval(self):\n- return self.pval.aval\n+ aval = property(lambda self: self.pval.aval)\ndef full_lower(self):\nif self.pval.is_known:\n@@ -2176,9 +2171,6 @@ The jaxpr corresponds to a topological sort of the graph.\n```{code-cell}\ndef tracers_to_jaxpr(tracers_in: List[PartialEvalTracer],\ntracers_out: List[PartialEvalTracer]):\n- tracers_in = [t for t in tracers_in if t.pval.is_unknown]\n- tracers_out = [t for t in tracers_out if t.pval.is_unknown]\n-\ntracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in}\nconstvar_to_val = {}\nconstid_to_var = {}\n@@ -2304,7 +2296,7 @@ def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool],\ninstantiate: Optional[List[bool]] = None,\n) -> Tuple[Jaxpr, Jaxpr, List[bool], int]:\nenv: Dict[Var, bool] = {}\n- residuals = set()\n+ residuals: Set[Var] = set()\ndef read(v: Atom) -> bool:\nreturn type(v) is Var and env[v]\n@@ -2312,8 +2304,9 @@ def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool],\ndef write(unk: bool, v: Var) -> None:\nenv[v] = unk\n- def new_res(v: Var) -> Var:\n- return residuals.add(v) or v\n+ def new_res(x: Atom) -> Atom:\n+ if type(x) is Var: residuals.add(x)\n+ return x\neqns1, eqns2 = [], []\nmap(write, in_unknowns, jaxpr.in_binders)\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/autodidax.py",
"new_path": "docs/autodidax.py",
"diff": "@@ -1348,7 +1348,8 @@ def new_dynamic(main: MainTrace):\ndynamic_trace = prev_dynamic_trace\n@lru_cache()\n-def make_jaxpr(f, *avals_in):\n+def make_jaxpr(f: Callable, *avals_in: ShapedArray,\n+ ) -> Tuple[Jaxpr, List[Any], PyTreeDef]:\navals_in, in_tree = tree_flatten(avals_in)\nf, out_tree = flatten_fun(f, in_tree)\n@@ -1966,14 +1967,17 @@ class PartialVal(NamedTuple):\n# return a list of `PartialVal` outputs along with a jaxpr representing the\n# delayed computation:\n-def partial_eval_flat(f, pvals_in: List[PartialVal]):\n+def partial_eval_flat(f: Callable, pvals_in: List[PartialVal]\n+ ) -> Tuple[Jaxpr, List[PartialVal], List[Any]]:\nwith new_main(PartialEvalTrace) as main:\ntrace = PartialEvalTrace(main)\ntracers_in = [trace.new_arg(pval) for pval in pvals_in]\nouts = f(*tracers_in)\ntracers_out = [full_raise(trace, out) for out in outs]\n- jaxpr, consts = tracers_to_jaxpr(tracers_in, tracers_out)\npvals_out = [t.pval for t in tracers_out]\n+ unk_tracers_in = [t for t in tracers_in if t.pval.is_unknown]\n+ unk_tracers_out = [t for t in tracers_out if t.pval.is_unknown]\n+ jaxpr, consts = tracers_to_jaxpr(unk_tracers_in, unk_tracers_out)\nreturn jaxpr, pvals_out, consts\n# Next we need to implement `PartialEvalTrace` and its `PartialEvalTracer`. This\n@@ -1993,20 +1997,13 @@ class LambdaBindingRecipe(NamedTuple):\nclass ConstRecipe(NamedTuple):\nval: Any\n-class JaxprEqnRecipe:\n+class JaxprEqnRecipe(NamedTuple):\nprim: Primitive\ntracers_in: List['PartialEvalTracer']\nparams: Dict[str, Any]\navals_out: List[ShapedArray]\ntracer_refs_out: List['ReferenceType[PartialEvalTracer]']\n- def __init__(self, prim, tracers_in, params, avals_out, tracer_refs_out):\n- self.prim = prim\n- self.tracers_in = tracers_in\n- self.params = params\n- self.avals_out = avals_out\n- self.tracer_refs_out = tracer_refs_out\n-\nJaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe]\n@@ -2014,16 +2011,14 @@ JaxprRecipe = Union[LambdaBindingRecipe, ConstRecipe, JaxprEqnRecipe]\nclass PartialEvalTracer(Tracer):\npval: PartialVal\n- recipe: JaxprRecipe\n+ recipe: Optional[JaxprRecipe]\ndef __init__(self, trace, pval, recipe):\nself._trace = trace\nself.pval = pval\nself.recipe = recipe\n- @property\n- def aval(self):\n- return self.pval.aval\n+ aval = property(lambda self: self.pval.aval)\ndef full_lower(self):\nif self.pval.is_known:\n@@ -2090,9 +2085,6 @@ partial_eval_rules = {}\n# +\ndef tracers_to_jaxpr(tracers_in: List[PartialEvalTracer],\ntracers_out: List[PartialEvalTracer]):\n- tracers_in = [t for t in tracers_in if t.pval.is_unknown]\n- tracers_out = [t for t in tracers_out if t.pval.is_unknown]\n-\ntracer_to_var = {id(t): Var(raise_to_shaped(t.aval)) for t in tracers_in}\nconstvar_to_val = {}\nconstid_to_var = {}\n@@ -2213,7 +2205,7 @@ def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool],\ninstantiate: Optional[List[bool]] = None,\n) -> Tuple[Jaxpr, Jaxpr, List[bool], int]:\nenv: Dict[Var, bool] = {}\n- residuals = set()\n+ residuals: Set[Var] = set()\ndef read(v: Atom) -> bool:\nreturn type(v) is Var and env[v]\n@@ -2221,8 +2213,9 @@ def partial_eval_jaxpr(jaxpr: Jaxpr, in_unknowns: List[bool],\ndef write(unk: bool, v: Var) -> None:\nenv[v] = unk\n- def new_res(v: Var) -> Var:\n- return residuals.add(v) or v\n+ def new_res(x: Atom) -> Atom:\n+ if type(x) is Var: residuals.add(x)\n+ return x\neqns1, eqns2 = [], []\nmap(write, in_unknowns, jaxpr.in_binders)\n"
}
] | Python | Apache License 2.0 | google/jax | small tweaks, type annotations |
260,411 | 23.07.2021 10:59:44 | -10,800 | 24b00e856b20cd74aae8ff499e7cd244373dbff0 | [jax2tf] Adjustments for the polymorphic_shapes specification.
Expanded the polymorphic_shapes specification to detect when
it is a string or PolyShape, and then replicate it for all
arguments.
Some improvements for the error messages for incorrect
polymorphic shapes specification. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -176,7 +176,7 @@ def inside_call_tf():\n@partial(api_util.api_hook, tag=\"jax2tf_convert\")\ndef convert(fun: Callable,\n*,\n- polymorphic_shapes: Optional[Sequence[Any]] = None,\n+ polymorphic_shapes=None,\nwith_gradient=True,\nenable_xla=True\n) -> Callable:\n@@ -192,16 +192,19 @@ def convert(fun: Callable,\n(pytrees).\npolymorphic_shapes: Specifies input shapes to be treated polymorphically\nduring conversion.\n+\n.. warning:: The shape-polymorphic conversion is an experimental feature.\nIt is meant to be sound, but it is known to reject some JAX programs\n- that are shape polymorphic. The details of this feature can change. It\n- should be a Python object with the same pytree structure as, or a prefix\n- of, the tuple of arguments to the function, but with a shape\n- specification corresponding to each argument. The default value is\n- `None`, which is a shortcut for a tuple of `None` one for each argument,\n- denoting that all shapes are monomorphic.\n+ that are shape polymorphic. The details of this feature can change.\n+\n+ It should be `None` (all arguments are monomorphic), a single PolyShape\n+ or string (applies to all arguments), or a tuple/list of the same length\n+ as the function arguments. For each argument the shape specification\n+ should be `None` (monomorphic argument), or a Python object with the\n+ same pytree structure as the argument.\nSee [how optional parameters are matched to\narguments](https://jax.readthedocs.io/en/latest/pytrees.html#applying-optional-parameters-to-pytrees).\n+\nA shape specification for an array argument should be an object\n`PolyShape(dim0, dim1, ..., dimn)`\nwhere each `dim` is a dimension specification: a positive integer denoting\n@@ -210,8 +213,9 @@ def convert(fun: Callable,\nthe special placeholder string \"_\" denoting a monomorphic dimension\nwhose size is given by the actual argument. As a shortcut, an Ellipsis\nsuffix in the list of dimension specifications stands for a list of \"_\"\n- placeholders. For convenience, a shape specification can also be given\n- as a string\n+ placeholders.\n+\n+ For convenience, a shape specification can also be given as a string\nrepresentation, e.g.: \"batch, ...\", \"batch, height, width, _\", possibly\nwith surrounding parentheses: \"(batch, ...)\".\n@@ -268,11 +272,13 @@ def convert(fun: Callable,\nargs_flat = tuple(_apply_name(a, i) for i, a in enumerate(args_flat))\nif polymorphic_shapes is None:\n- polymorphic_shapes_ = (None,) * len(args)\n+ polymorphic_shapes_ = (polymorphic_shapes,) * len(args)\n+ elif isinstance(polymorphic_shapes, (PolyShape, str)):\n+ polymorphic_shapes_ = (polymorphic_shapes,) * len(args) # type: ignore\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 positional argument list \"\n- f\"({len(args)}). Got polymorphic_shapes={polymorphic_shapes}.\")\n+ f\"({len(args)}). Got polymorphic_shapes={repr(polymorphic_shapes)}.\")\nraise TypeError(msg)\npolymorphic_shapes_ = tuple(polymorphic_shapes)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -475,6 +475,11 @@ class PolyShape(tuple):\nSee docstring of :func:`jax2tf.convert`.\n\"\"\"\ndef __new__(cls, *dim_specs):\n+ for i, ds in enumerate(dim_specs):\n+ if not isinstance(ds, (int, str)) and ds != ...:\n+ msg = (f\"Invalid PolyShape element: {repr(ds)}; must be a string \"\n+ \"representing a dimension variable, or an integer, or ...\")\n+ raise ValueError(msg)\nreturn tuple.__new__(PolyShape, dim_specs)\n@@ -507,7 +512,7 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nelse:\nspec_tuple = spec_.split(\",\") # type: ignore\nelse:\n- raise ValueError(f\"PolyShape '{spec}' must be either None, a string, or PolyShape.\")\n+ raise ValueError(f\"PolyShape {repr(spec)} must be either None, a string, or PolyShape.\")\n# Process ...\nspec_tuple = tuple(map(lambda s: ... if isinstance(s, str) and s.strip() == \"...\" else s,\n@@ -515,13 +520,13 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nds_ellipses = tuple(ds for ds in spec_tuple if ds == ...)\nif ds_ellipses:\nif len(ds_ellipses) > 1 or spec_tuple[-1] != ...:\n- raise ValueError(f\"PolyShape '{spec}' can contain Ellipsis only at the end.\")\n+ raise ValueError(f\"PolyShape {repr(spec)} can contain Ellipsis only at the end.\")\nspec_tuple = spec_tuple[0:-1]\nif len(arg_shape) >= len(spec_tuple):\nspec_tuple = spec_tuple + (\"_\",) * (len(arg_shape) - len(spec_tuple))\nif len(arg_shape) != len(spec_tuple):\n- raise ValueError(f\"PolyShape '{spec}' must match the rank of arguments {arg_shape}.\")\n+ raise ValueError(f\"PolyShape {repr(spec)} of rank {len(spec_tuple)} must match the rank {len(arg_shape)} of argument shape {arg_shape}.\")\n# The actual parsing.\n# We actually parse not just dimension variables, but polynomials.\n@@ -533,24 +538,24 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nreturn dim_spec #\ndim_spec = dim_spec.strip()\nif not dim_spec:\n- raise ValueError(f\"PolyShape '{spec}' has invalid syntax (empty dimension {dim_spec}')\")\n+ raise ValueError(f\"PolyShape {repr(spec)} has invalid syntax (empty dimension {dim_spec}')\")\n# Terms are separated by \"+\"\nterms = dim_spec.split(\"+\")\nif not terms:\n- raise ValueError(f\"PolyShape '{spec}' has invalid syntax (empty dimension {dim_spec}')\")\n+ raise ValueError(f\"PolyShape {repr(spec)} has invalid syntax (empty dimension {dim_spec}')\")\ndef _parse_term(term_spec: str) -> DimSize:\nterm_spec = term_spec.strip()\n# Factors are separated by \"*\"\nfactors = term_spec.split(\"*\")\nif not factors:\n- raise ValueError(f\"PolyShape '{spec}' has invalid syntax (unexpected term '{term_spec}')\")\n+ raise ValueError(f\"PolyShape {repr(spec)} has invalid syntax (unexpected term '{term_spec}')\")\ndef _parse_factor(factor_spec: str) -> DimSize:\nfactor_spec = factor_spec.strip()\nif re.match(r\"^-?\\d+$\", factor_spec):\nreturn int(factor_spec)\nm = re.match(r\"^([a-zA-Z]\\w*)(\\^(\\d+))?$\", factor_spec)\nif not m:\n- raise ValueError(f\"PolyShape '{spec}' has invalid syntax (unexpected term '{factor_spec}')\")\n+ raise ValueError(f\"PolyShape {repr(spec)} has invalid syntax (unexpected term '{factor_spec}')\")\nvar = _DimPolynomial.from_var(m.group(1))\nif m.group(3) is None:\nreturn var\n@@ -568,12 +573,12 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\ndim_size = dim_size.value\nif dim_size is None:\nif dim_spec == \"_\":\n- msg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\n+ msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a shape variable \"\nf\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\ndim_poly = _parse_dim(dim_spec)\nif not is_poly_dim(dim_poly):\n- msg = (f\"PolyShape '{spec}' in axis {i} must contain a shape variable \"\n+ msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a shape variable \"\nf\"for unknown dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_poly\n@@ -584,7 +589,7 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\ndim_poly = _parse_dim(dim_spec)\nif not is_poly_dim(dim_poly):\nif dim_poly != dim_size:\n- msg = (f\"PolyShape '{spec}' in axis {i} must contain a constant or '_' \"\n+ msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a constant or '_' \"\nf\"for known dimension in argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_size\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": "@@ -283,8 +283,8 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\nclass ShapePolyTest(tf_test_util.JaxToTfTestCase):\n- def test_simple(self):\n- \"\"\"Test shape polymorphism for a simple case.\"\"\"\n+ def test_simple_unary(self):\n+ \"\"\"Test shape polymorphism for a simple case, unary function.\"\"\"\ndef f_jax(x):\nreturn x + jnp.sin(x)\n@@ -307,6 +307,36 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"h, h\"],\nexpected_output_signature=tf.TensorSpec([None, None]))\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, None])],\n+ polymorphic_shapes=\"h, h\",\n+ expected_output_signature=tf.TensorSpec([None, None]))\n+\n+ def test_simple_binary(self):\n+ \"\"\"Test shape polymorphism for a simple case, binary function.\"\"\"\n+\n+ def f_jax(x, y):\n+ return x + jnp.sin(y)\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([2, 3]), tf.TensorSpec([2, 3])],\n+ polymorphic_shapes=None,\n+ expected_output_signature=tf.TensorSpec([2, 3]))\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([2, None]), tf.TensorSpec([2, 3])],\n+ polymorphic_shapes=\"_, h\",\n+ expected_output_signature=tf.TensorSpec([2, 3]))\n+\n+ self.CheckShapePolymorphism(\n+ f_jax,\n+ input_signature=[tf.TensorSpec([None, None]), tf.TensorSpec([None, None])],\n+ polymorphic_shapes=PS(\"h\", \"h\"),\n+ expected_output_signature=tf.TensorSpec([None, None]))\n+\ndef test_arg_avals(self):\n\"\"\"Test conversion of actual arguments to abstract values.\"\"\"\n@@ -366,6 +396,16 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[PS(\"_\", 3)],\nexpected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+ check_avals(\n+ args=[tf_const((2, 3))],\n+ polymorphic_shapes=[\"...\"],\n+ expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+\n+ check_avals(\n+ args=[tf_const((2, 3))],\n+ polymorphic_shapes=[PS(...)],\n+ expected_avals=(shaped_array(\"2, 3\", [2, 3]),))\n+\n# Partially known shapes for the arguments\ncheck_avals(\nargs=[tf_var([None, 3], initializer_shape=(2, 3))],\n@@ -395,13 +435,20 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nexpected_avals=(shaped_array(\"(b, 3)\", (2, 3)),))\n# Some errors\n- for invalid_syntax in [\")(\", \"2a\", \"a@\", \"a - 2\"]:\n+ for invalid_syntax in [\")(\", \"2a\", \"a@\", \"a - 2\", \"'a'\", \"('a', ...)\"]:\nwith self.assertRaisesRegex(ValueError,\n- re.escape(\"PolyShape '\" + invalid_syntax + \"' has invalid syntax\")):\n+ re.escape(\"has invalid syntax\")):\ncheck_avals(\nargs=[const((2,))], polymorphic_shapes=[invalid_syntax],\nexpected_avals=None)\n+ for invalid_syntax in [5.0, [\"a list\"], (\"a tuple\",), re.compile(\".\")]:\n+ with self.assertRaisesRegex(ValueError,\n+ re.escape(\"Invalid PolyShape element\")):\n+ check_avals(\n+ args=[const((2,))], polymorphic_shapes=[PS([invalid_syntax])],\n+ expected_avals=None)\n+\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\"PolyShape '..., 3' can contain Ellipsis only at the end.\")):\n@@ -413,7 +460,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '2, 3, 4, ...' must match the rank of arguments (2, 3).\")\n+ \"PolyShape '2, 3, 4, ...' of rank 3 must match the rank 2 of argument shape (2, 3).\")\n):\ncheck_avals(\nargs=[const((2, 3))],\n@@ -423,7 +470,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(Ellipsis, 3)' can contain Ellipsis only at the end.\")):\n+ \"PolyShape (Ellipsis, 3) can contain Ellipsis only at the end.\")):\ncheck_avals(\nargs=[const((2, 3))],\npolymorphic_shapes=[PS(..., 3)],\n@@ -432,7 +479,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape 'None' in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\"\n+ \"PolyShape None in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\"\n)):\ncheck_avals(\nargs=[tf_var([2, None], initializer_shape=(2, 3))],\n@@ -441,7 +488,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\n- re.escape(\"PolyShape '()' must match the rank of arguments (2, 3)\")):\n+ re.escape(\"PolyShape '()' of rank 0 must match the rank 2 of argument shape (2, 3)\")):\ncheck_avals(\nargs=[const((2, 3))], polymorphic_shapes=[\"()\"], expected_avals=None)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Adjustments for the polymorphic_shapes specification.
Expanded the polymorphic_shapes specification to detect when
it is a string or PolyShape, and then replicate it for all
arguments.
Some improvements for the error messages for incorrect
polymorphic shapes specification. |
260,411 | 25.07.2021 09:44:40 | -10,800 | f29f5214ab5ff0d6c3e1e34b2b87025ca9f93961 | [jax2tf] Add support for tridiagonal_solve | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -1017,7 +1017,6 @@ tf_not_yet_impl = [\n\"lu_pivots_to_permutation\",\n\"rng_bit_generator\",\n\"xla_pmap\",\n- \"tridiagonal_solve\",\n]\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\n@@ -2889,6 +2888,16 @@ def _linear_solve(*args: TfVal, const_lengths, jaxprs, _in_avals, _out_aval):\ntf_impl_with_avals[lax_control_flow.linear_solve_p] = _linear_solve\n+def _tridiagonal_solve(*args: TfVal, _in_avals, _out_aval, **params):\n+ return _convert_jax_impl(lax_linalg._tridiagonal_solve_jax,\n+ multiple_results=False,\n+ extra_name_stack=\"tridiagonal_solve\")(\n+ *args,\n+ _in_avals=_in_avals,\n+ _out_aval=_out_aval)\n+\n+\n+tf_impl_with_avals[lax_linalg.tridiagonal_solve_p] = _tridiagonal_solve\ndef _custom_jvp_call_jaxpr(*args: TfVal, fun_jaxpr: core.ClosedJaxpr,\njvp_jaxpr_thunk: Callable,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -1088,6 +1088,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ncustom_numeric(dtypes=np.float32, tol=5e-3)\n]\n+ @classmethod\n+ def tridiagonal_solve(cls, harness: primitive_harness.Harness):\n+ return []\ndef custom_numeric(\n*,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -1833,6 +1833,17 @@ def _make_linear_solve_harnesses():\n_make_linear_solve_harnesses()\n+# tridiagonal_solve_p\n+for dtype in [np.float32, np.float64]:\n+ define(\n+ lax.linalg.tridiagonal_solve_p,\n+ f\"shape={jtu.format_shape_dtype_string((3,), dtype)}\",\n+ lax.linalg.tridiagonal_solve,\n+ [ np.array([0.0, 2.0, 3.0], dtype=dtype),\n+ np.ones(3, dtype=dtype),\n+ np.array([1.0, 2.0, 0.0], dtype=dtype),\n+ np.ones([3, 1], dtype=dtype)],\n+ dtype=dtype)\ndef _make_slice_harness(name,\nshape=(3,),\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,9 @@ 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+ #one_containing=\"tridiagonal\"\n+ )\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\ndef test_prim(self, harness: primitive_harness.Harness):\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": "@@ -1301,9 +1301,7 @@ def _add_vmap_primitive_harnesses():\n# We do *= shapes in the batching rule for conv_general_dilated\n\"conv_general_dilated\",\n- # vmap(clamp) fails in JAX\n- \"clamp\",\n-\n+ \"tridiagonal_solve\", # batching not implemented in JAX\n\"iota\", # vmap does not make sense for 0-argument functions\n])\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add support for tridiagonal_solve |
260,411 | 25.07.2021 10:13:13 | -10,800 | 00872d58058f600bb64b3f35f6fed1f36db15682 | [jax2tf] Added test for round trip for custom gradients
Fixes: 7123
The fix is not here, it is in TF. Here we only add the test. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "# limitations under the License.\nfrom absl.testing import absltest\n+import os\nimport jax\nfrom jax import lax\n@@ -153,6 +154,61 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\n# g = tape.gradient(res, xv)\n#self.assertAllClose(g.numpy(), jax.grad(f_jax)(x))\n+ def test_save_grad_integers(self):\n+ # https://github.com/google/jax/issues/7123\n+ # In the end this is a test that does not involve JAX at all\n+ batch_size = 5\n+ state = np.array([1], dtype=np.int32) # Works if float32\n+ params = np.ones((3, 3), dtype=np.float32)\n+\n+ # params: f32[3, 3], state: i32[1]\n+ # returns f32[5, 2] constant, and the state\n+ def tf_predict(params, state):\n+ # state = tf.cast(state, tf.float32)\n+ # Setup a custom-gradient, like jax2tf would\n+ @tf.custom_gradient\n+ def converted_fun_with_custom_gradient(params, state):\n+ res_out = tf.zeros((batch_size, 2), dtype=tf.float32)\n+ state_out = state # tf.zeros((4, 4), np.int32),\n+\n+ return ((res_out, state_out), converted_grad_fn)\n+\n+ def converted_grad_fn(res_out_ct, state_out_ct, variables=None):\n+ # The gradients for params and the state\n+ return tf.zeros(params.shape, dtype=params.dtype), state_out_ct\n+\n+ res, state_out = converted_fun_with_custom_gradient(params, state)\n+ # state_out = tf.cast(state_out, tf.int32)\n+ return res, state_out\n+\n+ # Compute the gradient before saving. This works!\n+ params_v = tf.Variable(params)\n+ with tf.GradientTape() as tape:\n+ preds = tf_predict(params_v, state)[0]\n+ loss = tf.reduce_mean(preds)\n+ g = tape.gradient(loss, params_v)\n+ self.assertAllClose(g.numpy(), np.zeros(params.shape, dtype=params.dtype))\n+\n+ # TF -> SavedModel\n+ model = tf.Module()\n+ model.fn = tf.function(tf_predict, autograph=False)\n+ model.fn.get_concrete_function(\n+ tf.TensorSpec(params.shape, params.dtype),\n+ tf.TensorSpec(state.shape, state.dtype))\n+ save_dir = os.path.join(absltest.get_default_test_tmpdir(), str(id(model)))\n+ options = tf.saved_model.SaveOptions(experimental_custom_gradients=True)\n+ _ = tf.saved_model.save(model, save_dir, options=options)\n+ restored_module = tf.saved_model.load(save_dir)\n+\n+ # It seems that saving and reloading is important\n+ restored_fn = restored_module.fn\n+\n+ # Compute the gradients after saving and restoring. Fails!\n+ with tf.GradientTape() as tape:\n+ preds = restored_fn(params_v, state)[0]\n+ loss = tf.reduce_mean(preds)\n+ g = tape.gradient(loss, params_v)\n+ self.assertAllClose(g.numpy(), np.zeros(params.shape, dtype=params.dtype))\ndef _compare_with_saved_model(self, f_jax, *args):\n# Certain ops are converted to ensure an XLA context, e.g.,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Added test for round trip for custom gradients
Fixes: 7123
The fix is not here, it is in TF. Here we only add the test. |
260,411 | 16.07.2021 08:16:09 | -10,800 | ab050059d15ffb3780e42ac1ff2b13450fe6113d | Ensure that we run the test on the proper TF device | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -280,7 +280,7 @@ def _code_generator_and_avals(\n# TODO(necula): For unoptimized HLO, does it make a difference which device we use?\ntf_device_name = \"/device:CPU:0\"\nwith jax2tf_internal.inside_call_tf():\n- concrete_function_flat_tf = function_flat_tf.get_concrete_function(*args_tf_flat)\n+ concrete_function_flat_tf = function_flat_tf.get_concrete_function(*args_flat_sig_tf)\ncaptured_inputs = []\nif concrete_function_flat_tf.captured_inputs:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -51,7 +51,7 @@ parameterized_jit = parameterized.named_parameters(\nfor with_jit in [True, False])\n-class CallTfTest(jtu.JaxTestCase):\n+class CallTfTest(tf_test_util.JaxToTfTestCase):\ndef setUp(self):\nif tf is None:\n@@ -639,7 +639,7 @@ class CallTfTest(jtu.JaxTestCase):\nprint(jax.make_jaxpr(cos_tf_sin_jax)(x))\nprint(jax.xla_computation(cos_tf_sin_jax)(x).as_hlo_text())\n-class RoundTripToJaxTest(jtu.JaxTestCase):\n+class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\n\"Reloading output of jax2tf into JAX with call_tf\"\ndef setUp(self):\nif tf is None:\n@@ -806,7 +806,7 @@ class RoundTripToJaxTest(jtu.JaxTestCase):\n# The graph tensor has name: args_0:0\n# g = jax.grad(f_rt)(x)\n-class RoundTripToTfTest(jtu.JaxTestCase):\n+class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\n\"Reloading output of call_tf into TF with jax2tf.\"\ndef setUp(self):\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure that we run the test on the proper TF device |
260,411 | 16.07.2021 13:16:21 | -10,800 | 458d66fca34d9fcb31505e1748853559d96cb4eb | Added a suggestion for safer check for captured inputs | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -295,9 +295,9 @@ def _code_generator_and_avals(\nfor inp in concrete_function_flat_tf.captured_inputs:\nif inp.dtype == tf.resource: # A variable; assume the next variable\nassert next_var_idx < len(concrete_function_flat_tf.variables)\n- # TODO(necula): better checking that we are picking the right variable\nvar = concrete_function_flat_tf.variables[next_var_idx]\nnext_var_idx += 1\n+ assert inp is var.handle # For extra safety\ncaptured_inputs.append(var)\nelse:\ncaptured_inputs.append(inp)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -289,7 +289,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(x * 4. + 1, res, check_dtypes=False)\n@parameterized_jit\n- def test_with_tensor_capture(self, with_jit=False):\n+ def test_with_tensor_capture(self, with_jit=True):\nouter_tensor = tf.constant(3., dtype=np.float32)\ndef fun_tf(x):\n@@ -804,6 +804,7 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\n# with tf.init_scope():\n# added = my_constant * 2\n# The graph tensor has name: args_0:0\n+\n# g = jax.grad(f_rt)(x)\nclass RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Added a suggestion for safer check for captured inputs |
260,411 | 25.07.2021 18:09:08 | -10,800 | ea5959cd5ba191b21f51610b468b975737f64d47 | Force the TF compilation to use JAX's default platform | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -277,8 +277,15 @@ def _code_generator_and_avals(\nshape=a.shape,\ndtype=a.dtype) for a in args_flat_sig_tf]\n- # TODO(necula): For unoptimized HLO, does it make a difference which device we use?\n- tf_device_name = \"/device:CPU:0\"\n+ # TODO(necula): We should use the proper device, because in some cases we\n+ # generate different HLO for different devices.\n+ # One example is when the code refers to variables on one device. Or, for\n+ # sharding annotations (only supported on TPU).\n+ # For now we just use the default device, but ideally we should pass the\n+ # intended platform in. The problem is that we want to reuse and cache this\n+ # function across abstract_eval and XLA translation, but for abstract_eval\n+ # we do not know the platform.\n+ tf_device_name = f\"/device:{jax.default_backend().upper()}:0\"\nwith jax2tf_internal.inside_call_tf():\nconcrete_function_flat_tf = function_flat_tf.get_concrete_function(*args_flat_sig_tf)\n"
}
] | Python | Apache License 2.0 | google/jax | Force the TF compilation to use JAX's default platform |
260,411 | 25.07.2021 14:50:54 | -10,800 | 0b697ce23229c050b6c7bfd328a372ce99468b67 | [host_callback] Fix the JVP rule for id_tap(result=...)
The previous rule was leaking ad.Zero. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/host_callback.py",
"new_path": "jax/experimental/host_callback.py",
"diff": "@@ -798,17 +798,24 @@ id_tap_dep_p.multiple_results = False\nid_tap_dep_p.def_impl(lambda r, _: r)\nxla.translations[id_tap_dep_p] = lambda comp, a_res, a_tap: a_res\nid_tap_dep_p.def_abstract_eval(lambda r_a, _: r_a)\n-ad.primitive_jvps[id_tap_dep_p] = (\n- lambda primals, tangents: (\n- id_tap_dep_p.bind(primals[0], primals[1]),\n- id_tap_dep_p.bind(tangents[0], tangents[1])))\n+def _id_tap_dep_jvp_rule(primals, tangents):\n+ tangents_instantiated = tuple(map(_instantiate_zeros, tangents, primals))\n+ return (id_tap_dep_p.bind(primals[0], primals[1]),\n+ id_tap_dep_p.bind(tangents_instantiated[0], tangents_instantiated[1]))\n-def _id_tap_dep_transpose_rule(cts, arg_res, arg_tap):\n- assert ad.is_undefined_primal(arg_res)\n- assert ad.is_undefined_primal(arg_tap)\n- return (_instantiate_zeros(arg_res, cts), ad.Zero(arg_tap.aval))\n+ad.primitive_jvps[id_tap_dep_p] = _id_tap_dep_jvp_rule\n+def _id_tap_dep_transpose_rule(cts, arg_res, arg_tap):\n+ if ad.is_undefined_primal(arg_res):\n+ ct_res = _instantiate_zeros(cts, arg_res)\n+ else:\n+ ct_res = None\n+ if ad.is_undefined_primal(arg_tap):\n+ ct_tap = ad.Zero(arg_tap.aval)\n+ else:\n+ ct_tap = None\n+ return (ct_res, ct_tap)\nad.primitive_transposes[id_tap_dep_p] = _id_tap_dep_transpose_rule\n@@ -1170,36 +1177,37 @@ def _add_transform(params: Dict, name: str, *transform_params) -> Dict:\ndef _aval_is_empty(aval) -> bool:\nreturn np.prod(aval.shape) == 0\n-# TODO(necula): there must be a better way to do this.\n-# The AttributeError is for regular values, the KeyError is for ConcreteArray\n-def _instantiate_zeros(arg, tan):\n- \"\"\"Turn special ad.zero tangents into arrays of 0s for sending to host.\"\"\"\n- # return ad.instantiate_zeros(tan)\n+def _instantiate_zeros(tan, arg):\n+ \"\"\"Turn special ad.zero tangents into arrays of 0s for sending to host.\n+ Args:\n+ tan: the tangent.\n+ arg: the argument for which we need to instantiate the tangent\n+\n+ Returns: tan if is is not ad.Zero, otherwise a 0 array of appropriate type\n+ and shape\n+ \"\"\"\nif type(tan) is not ad.Zero:\nreturn tan\n+ if tan.aval is not core.abstract_unit:\n+ return ad.instantiate_zeros_aval(tan.aval, tan)\n- if tan.aval is core.abstract_unit:\nif ad.is_undefined_primal(arg):\naval = arg.aval\nelse:\naval = core.raise_to_shaped(core.get_aval(arg))\n- else:\n- aval = tan.aval\n- res = ad.instantiate_zeros_aval(aval, tan)\n- return res\n-\n+ return ad.instantiate_zeros_aval(aval, tan)\ndef _outside_call_jvp_rule(primals, tangents, **params):\nassert \"has_token\" not in params\nif not params[\"identity\"]:\nraise NotImplementedError(\"JVP rule is implemented only for id_tap, not for call.\")\n- tangent_instantiated = tuple(map(_instantiate_zeros, primals, tangents))\n+ tangents_instantiated = tuple(map(_instantiate_zeros, tangents, primals))\narg_treedef = params[\"arg_treedef\"]\n# The argument to the jvp tap is a pair of the tapped primals and tangents\njvp_flat_args, jvp_arg_treedef = api.tree_flatten(\n(arg_treedef.unflatten(primals),\n- arg_treedef.unflatten(tangent_instantiated)))\n+ arg_treedef.unflatten(tangents_instantiated)))\nout_all = outside_call_p.bind(\n*jvp_flat_args,\n**dict(_add_transform(params, \"jvp\"),\n@@ -1264,7 +1272,7 @@ def _outside_call_transpose_rule(cts, *args, **params):\nraise NotImplementedError(\"differentiation rules are implemented only for id_tap, not for call.\")\nassert \"has_token\" not in params\nassert len(cts) == len(args)\n- cts_instantiated = tuple(map(_instantiate_zeros, args, cts))\n+ cts_instantiated = tuple(map(_instantiate_zeros, cts, args))\n# The args have been prepared by the id_tap_jvp_rule: tapped_primals, tapped_tangents, rest_primals, rest_tangents\ntransforms = params.get(\"transforms\", ())\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -26,6 +26,7 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\n+from jax import core\nfrom jax._src import api\nfrom jax.config import config\nfrom jax import dtypes\n@@ -1046,6 +1047,82 @@ class HostCallbackTapTest(jtu.JaxTestCase):\n( 2.00\nFalse )\"\"\", testing_stream.output)\n+ def test_tap_grad_float0_result(self):\n+ # https://github.com/google/jax/issues/7340\n+ # x is a Tuple[f32[2], s32[3]]\n+ x = (np.array([.7, .8], dtype=np.float32),\n+ np.array([11, 12, 13], dtype=np.int32))\n+ def f_jax(x):\n+ x = hcb.id_print(x, result=x, output_stream=testing_stream) # result= is important\n+ return (3. * x[0], x[1])\n+\n+ def f_jax_vjp(x):\n+ res, pullback = jax.vjp(f_jax, x)\n+ g, = pullback((np.ones(x[0].shape, dtype=x[0].dtype),\n+ np.zeros(x[1].shape, dtype=dtypes.float0)))\n+ return g\n+\n+ g = f_jax_vjp(x)\n+ self.assertAllClose(np.array([3., 3.], dtype=np.float32), g[0])\n+ self.assertEqual(dtypes.float0, g[1].dtype)\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"\"\"\n+ ( [0.70 0.80]\n+ [11 12 13] )\n+ transforms: ['jvp', 'transpose']\n+ ( [0.00 0.00]\n+ [False False False] )\"\"\", testing_stream.output)\n+\n+ def test_tap_higher_order_grad_float0_result(self):\n+ # https://github.com/google/jax/issues/7340\n+ # x is a Tuple[f32[2], s32[3]]\n+ x = (np.array([.7, .8], dtype=np.float32),\n+ np.array([11, 12, 13], dtype=np.int32))\n+ def f_jax(x):\n+ x = hcb.id_print(x, result=x, output_stream=testing_stream) # result= is important\n+ return (jnp.sin(x[0]), x[1])\n+\n+ def wrap_vjp(f, args, res_f_of_args):\n+ # Given a function \"f\" and \"args\" return the f_vjp and args_vjp\n+ def make_ct(res):\n+ res_dtype = np.result_type(res)\n+ if res_dtype == dtypes.float0:\n+ return res\n+ ct_dtype = core.primal_dtype_to_tangent_dtype(res_dtype)\n+ return np.ones(np.shape(res), dtype=ct_dtype)\n+ cts = tree_util.tree_map(make_ct, res_f_of_args)\n+ def f_vjp(args, cts):\n+ res, pullback = jax.vjp(f, *args)\n+ return pullback(cts)\n+ return (f_vjp, (args, cts))\n+\n+ res = f_jax(x)\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"\"\"\n+ ( [0.70 0.80]\n+ [11 12 13] )\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\n+ # 1st order\n+ f_jax_vjp1, args_vjp1 = wrap_vjp(f_jax, (x,), res)\n+ res_vjp1 = f_jax_vjp1(*args_vjp1)\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"\"\"\n+ ( [0.70 0.80]\n+ [11 12 13] )\n+ transforms: ['jvp', 'transpose']\n+ ( [0.00 0.00]\n+ [False False False] )\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\n+ # 2nd order\n+ f_jax_vjp2, args_vjp2 = wrap_vjp(f_jax_vjp1, args_vjp1, res_vjp1)\n+ res_vjp2 = f_jax_vjp2(*args_vjp2)\n+\n+ # 3rd order\n+ f_jax_vjp3, args_vjp3 = wrap_vjp(f_jax_vjp2, args_vjp2, res_vjp2)\n+ _ = f_jax_vjp3(*args_vjp3)\n+\ndef test_tap_vmap(self):\nvmap_fun1 = api.vmap(fun1)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n"
}
] | Python | Apache License 2.0 | google/jax | [host_callback] Fix the JVP rule for id_tap(result=...)
The previous rule was leaking ad.Zero. |
260,411 | 25.07.2021 20:06:36 | -10,800 | 7638ad04e4d45cada989b97c2d90e9080add9fb2 | Fixed the safety check for call_tf
The previous check was failing on TPUs due to different layout | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -342,17 +342,21 @@ def _code_generator_and_avals(\n# Check that the function does not have compile-time constant inputs that\n# have been inlined in the compiled code.\nxla_comp_parameter_shapes = xla_comp.program_shape().parameter_shapes()\n+ found_parameter_avals = [\n+ core.ShapedArray(found_xla_shape.dimensions(),\n+ found_xla_shape.numpy_dtype())\n+ for found_xla_shape in xla_comp_parameter_shapes\n+ ]\n# Add the captured_inputs to args_flat_sig_tf\nexpected_args_flat_sig_tf = list(args_flat_sig_tf) + list(captured_inputs)\n- expected_parameter_shapes = [\n- xla_client.Shape.array_shape(\n- xla_client.dtype_to_etype(arg_sig.dtype.as_numpy_dtype),\n- arg_sig.shape.as_list()).with_major_to_minor_layout_if_absent()\n+ expected_parameter_avals = [\n+ core.ShapedArray(tuple(arg_sig.shape.as_list()),\n+ arg_sig.dtype.as_numpy_dtype)\nfor arg_sig in expected_args_flat_sig_tf]\n- if xla_comp_parameter_shapes != expected_parameter_shapes:\n+ if found_parameter_avals != expected_parameter_avals:\nmsg = (\"Compiled TensorFlow function has unexpected parameter types \" +\n- f\"{xla_comp_parameter_shapes}, while the expected types are \" +\n- f\"{expected_parameter_shapes}. Perhaps the TensorFlow function \" +\n+ f\"{found_parameter_avals}, while the expected types are \" +\n+ f\"{expected_parameter_avals}. Perhaps the TensorFlow function \" +\n\"has shape-influencing inputs, and thus needs to be recompiled \" +\n\"for each value of some inputs. \" +\n\"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -150,6 +150,10 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nx = np.array([True, False], dtype=np.bool_)\nself.assertAllClose(f_tf_non_compileable(x).numpy(), f_jax(x))\n+ if jtu.device_under_test() == \"tpu\":\n+ # TODO: This works on TPU!!!\n+ self.assertAllClose(f_tf_non_compileable(x).numpy(), jax.jit(f_jax)(x))\n+ else:\nwith self.assertRaisesRegex(ValueError,\nCallTfTest.call_tf_non_compileable):\njax.jit(f_jax)(x)\n@@ -884,6 +888,8 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(np.sin(x), res.numpy())\ndef test_function_dynamic_shape(self):\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TODO: why does this fail on TPU?\")\n# Call a function for which shape inference does not give an output\n# shape.\nx = np.array([-1, 0, 1], dtype=np.int32)\n"
}
] | Python | Apache License 2.0 | google/jax | Fixed the safety check for call_tf
The previous check was failing on TPUs due to different layout |
260,411 | 25.06.2021 08:43:04 | -7,200 | 2749b6352420e2c063ff0900c4e0c9d11909d5da | Ensure zeros from AD are generated on device.
Fixes:
Also fixes type checking in jax2tf, because now we have to be careful
about computations that have result float0 (the broadcast_in_dim used
to compute the zeros). | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/abstract_arrays.py",
"new_path": "jax/_src/abstract_arrays.py",
"diff": "@@ -38,7 +38,8 @@ def make_shaped_array(x):\ndef zeros_like_array(x):\ndtype = dtypes.canonicalize_dtype(dtypes.result_type(x))\n- return zeros_like_shaped_array(ShapedArray(np.shape(x), dtype))\n+ aval = ShapedArray(np.shape(x), dtype)\n+ return ad_util.zeros_like_aval(aval)\narray_types = {np.ndarray, np.bool_,\nnp.int8, np.int16, np.int32, np.int64,\n@@ -51,15 +52,6 @@ for t in array_types:\ncore.pytype_aval_mappings[t] = ConcreteArray\nad_util.jaxval_zeros_likers[t] = zeros_like_array\n-\n-def zeros_like_shaped_array(aval):\n- assert isinstance(aval, ShapedArray)\n- if aval.dtype == dtypes.float0:\n- return np.zeros(aval.shape, dtypes.float0)\n- return np.broadcast_to(np.array(0, aval.dtype), aval.shape)\n-\n-ad_util.aval_zeros_likers[ShapedArray] = zeros_like_shaped_array\n-\ncore.literalable_types.update(array_types)\ndef _zeros_like_python_scalar(t, x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1610,6 +1610,13 @@ def _device_put_raw(x, weak_type=None):\naval = raise_to_shaped(core.get_aval(x), weak_type=weak_type)\nreturn xla.array_result_handler(None, aval)(*xla.device_put(x))\n+def zeros_like_shaped_array(aval):\n+ assert isinstance(aval, ShapedArray)\n+ # The .astype is useful for float0\n+ return broadcast(np.array(0).astype(aval.dtype), aval.shape)\n+\n+ad_util.aval_zeros_likers[ShapedArray] = zeros_like_shaped_array\n+\ndef iota(dtype: DType, size: int) -> Array:\n\"\"\"Wraps XLA's `Iota\n<https://www.tensorflow.org/xla/operation_semantics#iota>`_\n@@ -1672,11 +1679,11 @@ def stop_gradient(x):\n>>> jax.grad(lambda x: x**2)(3.)\nDeviceArray(6., dtype=float32)\n>>> jax.grad(lambda x: jax.lax.stop_gradient(x)**2)(3.)\n- array(0., dtype=float32)\n+ DeviceArray(0., dtype=float32)\n>>> jax.grad(jax.grad(lambda x: x**2))(3.)\nDeviceArray(2., dtype=float32)\n>>> jax.grad(jax.grad(lambda x: jax.lax.stop_gradient(x)**2))(3.)\n- array(0., dtype=float32)\n+ DeviceArray(0., dtype=float32)\n\"\"\"\ndef stop(x):\nif (dtypes.issubdtype(_dtype(x), np.floating) or\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -762,14 +762,19 @@ class TensorFlowTracer(core.Tracer):\nself._aval = aval\nif aval is core.abstract_unit:\nself.val = val\n- elif isinstance(val, (tf.Tensor, tf.Variable)):\n+ return\n+\n+ if isinstance(val, (tf.Tensor, tf.Variable)):\nval_shape = val.shape\n- val_dtype = _to_jax_dtype(val.dtype)\n- aval_dtype = np.dtype(self._aval.dtype) # type: ignore[attr-defined]\nif config.jax_enable_checks:\n- assert aval_dtype == val_dtype, f\"expected {aval_dtype} == {val_dtype}\"\nassert len(self._aval.shape) == len(val_shape), f\"_aval.shape={self._aval.shape} different rank than val_shape={val_shape}\"\n+ # To compare types, we must handle float0 in JAX and x64 in TF\n+ if self._aval.dtype == dtypes.float0:\n+ assert _to_tf_dtype(self._aval.dtype) == val.dtype, f\"expected {self._aval.dtype} == {val.dtype}\"\n+ else:\n+ assert self._aval.dtype == _to_jax_dtype(val.dtype), f\"expected {self._aval.dtype} == {val.dtype}\"\n+\nfor aval_dim, val_dim in zip(\nself._aval.shape, val_shape): # type: ignore[attr-defined]\nif val_dim is None:\n@@ -784,10 +789,8 @@ class TensorFlowTracer(core.Tracer):\ncontinue\nassert aval_int == val_dim, f\"expected {self._aval.shape} == {val_shape}. Found {aval_int} != {val_dim}.\" # type: ignore\n- self.val = val\n- else: # Must be a numeric value\n- self.val = _tfval_to_tensor_jax_dtype(\n- val, self._aval.dtype)[0] # type: ignore[attr-defined]\n+ self.val = _tfval_to_tensor_jax_dtype(val,\n+ self._aval.dtype)[0] # type: ignore[attr-defined]\n@property\ndef aval(self):\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": "@@ -717,7 +717,33 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nres_jax,\njax2tf.convert(f, polymorphic_shapes=[\"(b, h)\", \"h\"])(x, y))\n- def test_saved_model_shape_poly(self):\n+ def test_grad_int_function(self):\n+ # https://github.com/google/jax/issues/7093\n+ def f_jax(xi, yf): # xi is int32 and yf is float32\n+ # Return a triple: (1) float constant, with 0 tangent;\n+ # (2) the integer input; (3) a float dependending on both inputs.\n+ return jnp.zeros(xi.shape, dtype=jnp.float32), xi, xi.astype(np.float32) * 2. * yf\n+\n+ x_shape = (2, 3, 4)\n+ xi = np.arange(np.prod(x_shape), dtype=np.int32).reshape(x_shape)\n+ yf = xi.astype(np.float32)\n+ res, f_vjp = jax.vjp(f_jax, xi, yf)\n+ _ = f_vjp((np.ones(x_shape, dtype=np.float32),\n+ np.zeros(x_shape, dtype=jax.float0),\n+ np.ones(x_shape, dtype=np.float32)))\n+\n+ f_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"b1, b2, 4\", \"b1, b2, 4\"])\n+\n+ xiv = tf.Variable(xi)\n+ yfv = tf.Variable(yf)\n+ with tf.GradientTape() as tape:\n+ res_tf = f_tf(xiv, yfv)\n+\n+ g_tf_xi, g_tf_yf = tape.gradient(res_tf, (xiv, yfv))\n+ self.assertIsNone(g_tf_xi)\n+ self.assertAllClose(2. * xi.astype(np.float32), g_tf_yf)\n+\n+ def test_saved_model(self):\nf_jax = jnp.sin\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\nx = np.array([0.7, 0.8], dtype=np.float32)\n@@ -727,6 +753,31 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ny = np.concatenate([x, x])\nself.assertAllClose(f_jax(y), restored_f(y))\n+ def test_saved_model_int_function(self):\n+ def f_jax(x): # x:[b, 3, 4]\n+ return jnp.reshape(x, (-1,)) # : [b * 12]\n+ f_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\n+ x_shape = (2, 3, 4)\n+ x = np.arange(np.prod(x_shape), dtype=np.int32).reshape(x_shape)\n+\n+ # When saving the model with gradients, we trace the gradient function\n+ # and we used to get an error when creating zeros_like_aval for a\n+ # polymorphic shape\n+ restored_f = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec((None,) + x.shape[1:], x.dtype)])\n+ f_jax_rt = jax2tf.call_tf(restored_f)\n+ res_jax_rt = f_jax_rt(x)\n+ self.assertAllClose(f_jax(x), res_jax_rt)\n+\n+ def test_saved_model_constant_gradient(self):\n+ def f_jax(x): # A function whose gradient is a constant\n+ return 3.\n+\n+ f_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\n+ x = np.array([0.7, 0.8], dtype=np.float32)\n+ restored_f = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\n+ self.assertAllClose(3., restored_f(x))\n+ self.assertAllClose(np.array([0., 0.], dtype=np.float32), jax.grad(f_jax)(x))\n+\ndef test_readme_example(self):\n\"\"\"Some of the examples from the README.\"\"\"\ndef image_mask_jax(images, mask):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/host_callback_test.py",
"new_path": "tests/host_callback_test.py",
"diff": "@@ -935,6 +935,8 @@ class HostCallbackTapTest(jtu.JaxTestCase):\ntransforms=( ) ] b\n_ = mul c 2.00\nd = mul 1.00 2.00\n+ _ = broadcast_in_dim[ broadcast_dimensions=( )\n+ shape=( ) ] 0.00\ne = outside_call[ arg_treedef={treedef}\ncallback=...\nidentity=True\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure zeros from AD are generated on device.
Fixes: #7093
Also fixes type checking in jax2tf, because now we have to be careful
about computations that have result float0 (the broadcast_in_dim used
to compute the zeros). |
260,411 | 25.07.2021 16:07:33 | -10,800 | 4a3e8e99e6b952ec53266ba7d18e25b6918d6c0b | Fix for numpy 1.17.5 | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1612,8 +1612,12 @@ def _device_put_raw(x, weak_type=None):\ndef zeros_like_shaped_array(aval):\nassert isinstance(aval, ShapedArray)\n- # The .astype is useful for float0\n- return broadcast(np.array(0).astype(aval.dtype), aval.shape)\n+ scalar_zero = np.array(0).astype(aval.dtype)\n+ if scalar_zero.dtype != aval.dtype:\n+ # For numpy 1.17.5 we get here for float0. We use an alternate construction.\n+ assert aval.dtype == dtypes.float0\n+ scalar_zero = np.zeros((), dtype=aval.dtype)\n+ return broadcast(scalar_zero, aval.shape)\nad_util.aval_zeros_likers[ShapedArray] = zeros_like_shaped_array\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": "@@ -754,6 +754,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(y), restored_f(y))\ndef test_saved_model_int_function(self):\n+ raise unittest.SkipTest(\"TODO: fix test\")\ndef f_jax(x): # x:[b, 3, 4]\nreturn jnp.reshape(x, (-1,)) # : [b * 12]\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\n@@ -774,7 +775,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\nx = np.array([0.7, 0.8], dtype=np.float32)\n- restored_f = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\nself.assertAllClose(3., restored_f(x))\nself.assertAllClose(np.array([0., 0.], dtype=np.float32), jax.grad(f_jax)(x))\n"
}
] | Python | Apache License 2.0 | google/jax | Fix for numpy 1.17.5 |
260,411 | 26.07.2021 17:48:21 | -10,800 | fd1b13cc04ba50b3b87aea79a22da85405def3e0 | [jax2tf] Improve the error message when forgetting polymorphic_shapes
Also replaced "shape variable" with "dimension variable" in error
message and documentation.
Fixes: | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/README.md",
"new_path": "jax/experimental/jax2tf/README.md",
"diff": "@@ -228,10 +228,10 @@ f_tf.get_concrete_function(tf.TensorSpec([None, 28, 28], tf.float32))\nThe `polymorphic_shapes` parameter, in the form of a sequence of strings corresponding\nto the sequence of positional\n-arguments, introduces one or more shape variables, e.g., `b`, to stand for shape\n+arguments, introduces one or more dimension variables, e.g., `b`, to stand for shape\ndimensions that are assumed to be unknown at JAX tracing time, even if the actual\nparameter value (here `tf.TensorSpec(...)`) happens to have fully known shape.\n-Shape variables are assumed to range\n+Dimension variables are assumed to range\nover all strictly positive integers.\nIn this particular example, we can\nalso abbreviate `polymorphic_shapes=[\"(b, _, _)\"]`,\n@@ -249,7 +249,7 @@ multiple unknown dimensions and there is a relationship between them.\nFor example,\nif the function to be converted is also polymorphic on the size of each\nimage while requiring the images to be square,\n-we would add a shape variable `d` to stand for\n+we would add a dimension variable `d` to stand for\nthe unknown image size:\n```\n@@ -329,7 +329,7 @@ A shape specifier is combined with a `TensorSpec` as follows:\nThe abstract value of the dimension is going to be set to this variable.\nThe corresponding dimension in `TensorSpec` can be `None` or can be a\nconstant.\n- * All occurrences of a shape variable in any dimension\n+ * All occurrences of a dimension variable in any dimension\nfor any argument are assumed to be equal.\nNote that `polymorphic_shapes` controls the shape abstraction used by JAX when tracing\n@@ -429,14 +429,14 @@ values of the dimension variables `b` and `w`:\n```\ndef image_mask_tf(images, mask):\n- b, w, _ = tf.shape(images) # Compute the dynamic values for the shape variables \"b\" and \"w\"\n+ b, w, _ = tf.shape(images) # Compute the dynamic values for the dimension variables \"b\" and \"w\"\nreturn tf.math.multiply(images,\ntf.broadcast_to(tf.reshape(mask, [1, w, w]),\n[b, w, w]))\n```\nTo 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+mapping the dimension variables in the `polymorphic_shapes` specification to TensorFlow expressions\nusing `tf.shape` on the input parameters.\n@@ -498,7 +498,7 @@ jax2tf.convert(lambda x: jnp.reshape(x, (-1, x.shape[0])),\nFinally, certain codes that use shapes in the actual computation may not yet work\nif 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+will have the value of the dimension variable `v`. This case is not yet implemented:\n```\njax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -62,7 +62,7 @@ class _DimMon(dict):\nThe representation is a dictionary mapping var:exponent.\nThe `var` are strings and the exponents are >= 1.\n- The shape variables are assumed to range over integers >= 1.\n+ The dimension variables are assumed to range over integers >= 1.\n\"\"\"\ndef __hash__(self):\nreturn hash(frozenset(self.items()))\n@@ -127,7 +127,7 @@ class _DimMon(dict):\nclass _DimPolynomial(dict):\n\"\"\"Polynomial with integer coefficients for polymorphic shapes.\n- The shape variables are assumed to range over integers >= 1.\n+ The dimension variables are assumed to range over integers >= 1.\nWe overload integer operations, but we do that soundly, raising\n:class:`InconclusiveDimensionOperation` when the result is not\n@@ -599,15 +599,18 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\nif isinstance(dim_size, tf.compat.v1.Dimension):\ndim_size = dim_size.value\nif dim_size is None:\n- if dim_spec == \"_\":\n- msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a shape variable \"\n+ def need_dim_var_msg():\n+ msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a dimension variable \"\nf\"for unknown dimension in argument shape {arg_shape}\")\n- raise ValueError(msg)\n+ if spec is None:\n+ msg += \". Perhaps you forgot to add the polymorphic_shapes= parameter to jax2tf.convert?\"\n+ return msg\n+\n+ if dim_spec == \"_\":\n+ raise ValueError(need_dim_var_msg())\ndim_poly = _parse_dim(dim_spec)\nif not is_poly_dim(dim_poly):\n- msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a shape variable \"\n- f\"for unknown dimension in argument shape {arg_shape}\")\n- raise ValueError(msg)\n+ raise ValueError(need_dim_var_msg())\nreturn dim_poly\nelse: # dim_size is known\ndim_size = int(dim_size)\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": "@@ -337,6 +337,14 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=PS(\"h\", \"h\"),\nexpected_output_signature=tf.TensorSpec([None, None]))\n+ def test_forgot_polymorphic_shapes_error(self):\n+ msg_re = \"PolyShape None in axis .* must contain a dimension variable for unknown dimension in argument shape .*. Perhaps you forgot to add the polymorphic_shapes\"\n+ with self.assertRaisesRegex(ValueError, msg_re):\n+ self.CheckShapePolymorphism(\n+ jnp.sin,\n+ input_signature=[tf.TensorSpec([1, None])],\n+ polymorphic_shapes=None)\n+\ndef test_arg_avals(self):\n\"\"\"Test conversion of actual arguments to abstract values.\"\"\"\n@@ -479,7 +487,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape None in axis 1 must contain a shape variable for unknown dimension in argument shape (2, None)\"\n+ \"PolyShape None in axis 1 must contain a dimension variable for unknown dimension in argument shape (2, None)\"\n)):\ncheck_avals(\nargs=[tf_var([2, None], initializer_shape=(2, 3))],\n@@ -495,7 +503,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(_, _)' in axis 1 must contain a shape variable \"\n+ \"PolyShape '(_, _)' in axis 1 must contain a dimension variable \"\n\"for unknown dimension in argument shape (2, None)\"\n)):\ncheck_avals(\n@@ -517,7 +525,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(2, 3)' in axis 1 must contain a shape variable for \"\n+ \"PolyShape '(2, 3)' in axis 1 must contain a dimension variable for \"\n\"unknown dimension in argument shape (2, None)\"\n)):\ncheck_avals(\n@@ -856,7 +864,7 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual(1, f_tf(x0))\n# Unsoundness: not checking that the actual dimensions denoted by the same\n- # shape variables have equal sizes.\n+ # dimension variables have equal sizes.\ndef f_jax(x):\nreturn 0 if x.shape[0] != x.shape[1] else 1\n@@ -986,7 +994,7 @@ def _make_harness(group_name: str, name: str,\npolymorphic axis), or a tuple of ints (for multiple polymorphic axes).\nFor each argument, we use its `poly_axes` entry to generate the polymorphic_shapes\n- specification, creating shape variables `b0`, `b1, ..., for each of its\n+ specification, creating dimension variables `b0`, `b1, ..., for each of its\npolymorphic axes. This means that separate arguments will share the same\ndimension variable names, in the order in which the axes are listed in\npoly_axes.\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improve the error message when forgetting polymorphic_shapes
Also replaced "shape variable" with "dimension variable" in error
message and documentation.
Fixes: #7213 |
260,439 | 27.07.2021 11:12:51 | 25,200 | e7f03073dd070bb7f619b36c7bae4df7bcb67866 | ReduceScatter translation and abstract eval. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/parallel.py",
"new_path": "jax/_src/lax/parallel.py",
"diff": "@@ -1129,6 +1129,168 @@ batching.primitive_batchers[all_gather_p] = _all_gather_batcher\nbatching.collective_rules[all_gather_p] = _all_gather_batched_collective\ncore.axis_substitution_rules[all_gather_p] = partial(_subst_all_names_in_param, 'axis_name')\n+\n+def _reduce_scatter_via_reducer(x, *, reducer, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled):\n+ index = _index_in_group(axis_name, axis_index_groups)\n+ scatter_dim_input_size = x.shape[scatter_dimension]\n+ if tiled and scatter_dim_input_size % axis_size != 0:\n+ raise ValueError(f\"tiled reduce_scatter operand scatter dimension size \"\n+ f\"{scatter_dim_input_size} must be divisible by \"\n+ f\"shard count {axis_size}\")\n+ elif not tiled and scatter_dim_input_size != axis_size:\n+ raise ValueError(f\"reduce_scatter operand scatter dimension size \"\n+ f\"{scatter_dim_input_size} must match shard count\"\n+ f\"{axis_size}\")\n+ scatter_dim_output_size = scatter_dim_input_size // axis_size\n+\n+ outs = reducer(x, axis_name=axis_name, axis_index_groups=axis_index_groups)\n+ outs = lax.dynamic_slice_in_dim(\n+ outs,\n+ start_index=index * scatter_dim_output_size,\n+ slice_size=scatter_dim_output_size,\n+ axis=scatter_dimension)\n+ if not tiled:\n+ outs = lax.squeeze(outs, [scatter_dimension])\n+ return outs\n+\n+\n+def _reduce_scatter_translation_rule(prim, reducer, c, x, *, scatter_dimension, axis_name,axis_index_groups, axis_size, tiled, axis_env, platform):\n+ # TODO(b/194706412): Enable this for TPU?\n+ if platform == \"gpu\":\n+ scalar = ShapedArray((), c.get_shape(x).numpy_dtype())\n+ computation = xla.primitive_subcomputation(prim, scalar, scalar)\n+ replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\n+ x = xops.ReduceScatter(\n+ x,\n+ computation,\n+ scatter_dimension=scatter_dimension,\n+ shard_count=axis_size,\n+ replica_groups=xc.make_replica_groups(replica_groups))\n+ if not tiled:\n+ new_shape = list(c.get_shape(x).dimensions())\n+ del new_shape[scatter_dimension]\n+ x = xops.Reshape(x, new_shape)\n+ return x\n+ else:\n+ return xla.lower_fun(\n+ _reduce_scatter_via_reducer, multiple_results=False, parallel=True)(\n+ c,\n+ x,\n+ reducer=reducer,\n+ scatter_dimension=scatter_dimension,\n+ axis_name=axis_name,\n+ axis_index_groups=axis_index_groups,\n+ axis_size=axis_size,\n+ tiled=tiled,\n+ axis_env=axis_env,\n+ platform=platform)\n+\n+\n+def _reduce_scatter_abstract_eval(x, *, axis_name, scatter_dimension,\n+ axis_index_groups, axis_size, tiled):\n+ if not isinstance(axis_name, (list, tuple)):\n+ axis_name = (axis_name,)\n+ x_aval = core.raise_to_shaped(x)\n+ new_shape = list(x_aval.shape)\n+ scatter_dim_input_size = x_aval.shape[scatter_dimension]\n+ if tiled:\n+ if scatter_dim_input_size % axis_size != 0:\n+ raise ValueError(f\"tiled reduce_scatter operand scatter dimension size \"\n+ f\"{scatter_dim_input_size} must be divisible by \"\n+ f\"shard_count {axis_size}\")\n+ new_shape[scatter_dimension] = scatter_dim_input_size // axis_size\n+ else:\n+ if scatter_dim_input_size != axis_size:\n+ raise ValueError(f\"reduce_scatter operand scatter dimension size \"\n+ f\"{scatter_dim_input_size} must match shard count \"\n+ f\"{axis_size}\")\n+ del new_shape[scatter_dimension]\n+\n+ new_named_shape = {\n+ name: size\n+ for name, size in x_aval.named_shape.items()\n+ if name not in axis_name\n+ }\n+ return x_aval.update(shape=new_shape, named_shape=new_named_shape)\n+\n+\n+reduce_scatter_p = core.AxisPrimitive(\"reduce_scatter\")\n+reduce_scatter_p.def_abstract_eval(_reduce_scatter_abstract_eval)\n+xla.parallel_translations[reduce_scatter_p] = partial(\n+ _reduce_scatter_translation_rule, lax.add_p, psum)\n+pxla.multi_host_supported_collectives.add(reduce_scatter_p)\n+\n+\n+def psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, tiled=False):\n+ \"\"\"Compute an all-reduce sum over the axis ``axis_name``, and scatter the result.\n+\n+ Args:\n+ x: array(s) with a mapped axis named ``axis_name``.\n+ axis_name: hashable Python object used to name a pmapped axis (see the\n+ :func:`jax.pmap` documentation for more details).\n+ scatter_dimension: a positional axis into which the all reduce result along\n+ ``axis_name`` will be scattered.\n+ axis_index_groups: optional list of lists containing axis indices (e.g. for\n+ an axis of size 4, [[0, 1], [2, 3]] would run reduce-scatter over the\n+ first two and the last two replicas). Groups must cover all axis indices\n+ exactly once, and all groups must be the same size.\n+ tiled: when ``False``, the size of dimension in ``scatter_dimension`` must\n+ match the size of axis ``axis_name`` (or the group size if\n+ ``axis_index_groups`` is given). After scattering the all reduce result\n+ along ``scatter_dimension``, the output is sequeezed by removing\n+ ``scatter_dimension``. When ``True``, the size of dimension in\n+ ``scatter_dimension` must be dividible by the size of axis ``axis_name``\n+ (or the group size if ``axis_index_groups`` is given),\n+ and ``scatter_dimension`` is preserved.\n+\n+ Returns:\n+ Array(s) with the similar shape as ``x``, except the size of dimension in\n+ position``scatter_dimension`` is divided by the size of axis ``axis_name``.\n+\n+ For example, with 4 XLA devices available:\n+\n+ >>> x = np.arange(16).reshape(4,4)\n+ >>> print(x)\n+ [[ 0 1 2 3]\n+ [ 4 5 6 7]\n+ [ 8 9 10 11]\n+ [12 13 14 15]]\n+ >>> y = jax.pmap(lambda x: jax.lax.psum_scatter(x, 'i'), axis_name='i')(x)\n+ >>> print(y)\n+ [24 28 32 36]\n+\n+ if using tiled:\n+\n+ >>> y = jax.pmap(lambda x: jax.lax.psum_scatter(x, 'i', tiled=True), axis_name='i')(x)\n+ >>> print(y)\n+ [[24]\n+ [28]\n+ [32]\n+ [36]]\n+\n+ An example of using axis_index_groups:\n+\n+ >>> def f(x):\n+ ... return jax.lax.psum_scatter(\n+ ... x, 'i', axis_index_groups=[[0, 2], [3, 1]], tiled=True)\n+ >>> y = jax.pmap(f, axis_name='i')(x)\n+ >>> print(y)\n+ [[ 8 10]\n+ [20 22]\n+ [12 14]\n+ [16 18]]\n+ \"\"\"\n+ axis_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n+ bind = partial(\n+ reduce_scatter_p.bind,\n+ axis_name=axis_name,\n+ scatter_dimension=scatter_dimension,\n+ axis_index_groups=axis_index_groups,\n+ axis_size=axis_size,\n+ tiled=tiled)\n+ return tree_util.tree_map(bind, x)\n+\n+\ndef _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\naxis_pos = list(axis_env.names).index(axis_name)\nnreplicas = axis_env.nreps // prod(axis_env.sizes)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -932,6 +932,7 @@ tf_not_yet_impl = [\n\"psum\",\n\"pmax\",\n\"pgather\",\n+ \"reduce_scatter\",\n\"axis_index\",\n\"pdot\",\n\"all_gather\",\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/lax/__init__.py",
"new_path": "jax/lax/__init__.py",
"diff": "@@ -349,6 +349,7 @@ from jax._src.lax.parallel import (\npshuffle,\npsum,\npsum_p,\n+ psum_scatter,\npswapaxes,\npdot,\nxeinsum,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -159,6 +159,54 @@ class PmapTest(jtu.JaxTestCase):\nans = f(x)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def testReduceScatter(self):\n+ f = pmap(lambda x: lax.psum_scatter(x, 'i'), axis_name='i')\n+\n+ device_count = xla_bridge.device_count()\n+ shape = (device_count, device_count)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ expected = np.sum(x, axis=0)\n+ ans = f(x)\n+ for i, actual in enumerate(ans):\n+ self.assertAllClose(actual, expected[i])\n+\n+ def testReduceScatterTiled(self):\n+ f = pmap(lambda x: lax.psum_scatter(x, 'i', tiled=True), axis_name='i')\n+\n+ device_count = xla_bridge.device_count()\n+ shape = (device_count, 4 * device_count)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ expected = np.sum(x, axis=0)\n+ ans = f(x)\n+ scatter_len = len(expected) // device_count\n+ for i, actual in enumerate(ans):\n+ self.assertAllClose(actual,\n+ expected[i * scatter_len:(i + 1) * scatter_len])\n+\n+ def testReduceScatterReplicaGroupsTiled(self):\n+ replicas = xla_bridge.device_count()\n+ if replicas % 2 != 0:\n+ raise SkipTest\n+ axis_index_groups = [[i for i in range(jax.device_count()) if i % 2 == 0],\n+ [i for i in range(jax.device_count()) if i % 2 != 0]]\n+ f = lambda x: lax.psum_scatter(\n+ x, 'i', axis_index_groups=axis_index_groups, tiled=True)\n+ f = pmap(f, axis_name='i')\n+\n+ shape = (replicas, 4 * replicas)\n+ x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n+ ans = f(x)\n+\n+ group_1_result = np.sum(x[0::2,:], axis=0)\n+ group_2_result = np.sum(x[1::2,:], axis=0)\n+ # the result is scattered over (replicas // 2) devices\n+ scatter_len = len(group_1_result) * 2 // replicas\n+\n+ for i, actual in enumerate(ans):\n+ expected = group_1_result if i % 2 == 0 else group_2_result\n+ self.assertAllClose(\n+ actual, expected[i // 2 * scatter_len:(i // 2 + 1) * scatter_len])\n+\n@ignore_slow_all_to_all_warning()\ndef testTrees(self):\nptranspose = lambda x, axis_name: lax.all_to_all(x, axis_name, 0, 0)\n"
}
] | Python | Apache License 2.0 | google/jax | ReduceScatter translation and abstract eval.
PiperOrigin-RevId: 387152857 |
260,424 | 30.06.2021 10:46:37 | -3,600 | 19ee7b22e1d69c9a63211b1c1fc496a974257bdc | Expose UnexpectedTracerError and add docs. | [
{
"change_type": "MODIFY",
"old_path": "docs/errors.rst",
"new_path": "docs/errors.rst",
"diff": "@@ -10,3 +10,4 @@ along with representative examples of how one might fix them.\n.. autoclass:: NonConcreteBooleanIndexError\n.. autoclass:: TracerArrayConversionError\n.. autoclass:: TracerIntegerConversionError\n+.. autoclass:: UnexpectedTracerError\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/custom_derivatives.py",
"new_path": "jax/_src/custom_derivatives.py",
"diff": "@@ -26,6 +26,7 @@ from jax.tree_util import (tree_flatten, tree_unflatten, tree_map,\nfrom jax._src.util import cache, safe_zip, safe_map, split_list\nfrom jax.api_util import flatten_fun_nokwargs, argnums_partial, wrap_hashably\nfrom jax.core import raise_to_shaped\n+from jax.errors import UnexpectedTracerError\nfrom jax._src.ad_util import Zero, zeros_like_aval, stop_gradient_p\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import ad\n@@ -507,7 +508,7 @@ def _check_for_tracers(x):\n\"This behavior recently changed in JAX. \"\n\"See https://github.com/google/jax/blob/main/docs/custom_vjp_update.md \"\n\"for more information.\")\n- raise core.UnexpectedTracerError(msg)\n+ raise UnexpectedTracerError(msg)\n@lu.transformation_with_aux\ndef _flatten_fwd(in_tree, *args):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/errors.py",
"new_path": "jax/_src/errors.py",
"diff": "@@ -432,3 +432,105 @@ class TracerIntegerConversionError(JAXTypeError):\ndef __init__(self, tracer: \"core.Tracer\"):\nsuper().__init__(\nf\"The __index__() method was called on the JAX Tracer object {tracer}\")\n+\n+\n+class UnexpectedTracerError(JAXTypeError):\n+ \"\"\"\n+ This error occurs when you use a JAX value which has leaked out of a function.\n+ What does it mean to leak a value? If you use a JAX transform on a\n+ function which saves a value to an outer scope through a side-effect, this\n+ will leak a `Tracer`. When you then use this leaked value in a different\n+ operation, an `UnexpectedTracerError` will be thrown.\n+ To fix this, you need to return the value out of the transformed function\n+ explictly.\n+\n+ Tracers are created when you transform a function, eg. with `jit`, `pmap`,\n+ `vmap`, `eval_shape`, ... Intermediate values of these transformed values will\n+ be Tracers, and should not escape this function through a side-effect.\n+\n+ Life-cycle of a leaked Tracer\n+ Consider the following example of a transformed function which leaks a value\n+ to an outer scope::\n+\n+ >>> from jax import jit\n+ >>> import jax.numpy as jnp\n+\n+ >>> outs = []\n+ >>> @jit # 1\n+ ... def side_effecting(x):\n+ ... y = x+1 # 3\n+ ... outs.append(y) # 4\n+ >>> x = 1\n+ >>> side_effecting(x) # 2\n+ >>> outs[0]+1 # 5 # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ UnexpectedTracerError: Encountered an unexpected tracer.\n+\n+ In this example we leak a Traced value from an inner transformed scope to an\n+ outer scope. We get an UnexpectedTracerError not when the value is leaked\n+ but later, when the leaked value is used.\n+\n+ This example also demonstrates the life-cycle of a leaked Tracer:\n+\n+ 1. A function is transformed (in this case, jitted)\n+ 2. The transformed function is called (kicking of an abstract trace of the\n+ function and turning `x` into a Tracer)\n+ 3. The Tracer which will be leaked is created (an intermediate value of\n+ a traced function is also a Tracer)\n+ 4. The Tracer is leaked (appended to a list in an outer scope, escaping\n+ the function through a side-channel)\n+ 5. The leaked Tracer is used, and an UnexpectedTracerError is thrown.\n+\n+ The UnexpectedTracerError tries to point to these locations in your code by\n+ including information about each stage. Respectively:\n+\n+ 1. The name of the transformed function (`side_effecting`) and which\n+ transform kicked of the trace (`jit`).\n+ 2. A reconstructed stack-trace of where the Tracer was created, which\n+ includes where the transformed function was called. (`When the Tracer\n+ was created, the final 5 stack frames (most recent last) excluding\n+ JAX-internal frames were...`).\n+ 3. See the reconstructed stack-trace. This will point to the line of code\n+ which created the leaked Tracer.\n+ 4. Currently not included in the error message, because this is difficult\n+ to pin down! We can only tell you what the leaked value looks like\n+ (what shape is has and where it was created) and what boundary it was\n+ leaked over (the name of the transform and the name of the transformed\n+ function).\n+ 5. The actual error stack-trace will point to where the value is used.\n+\n+ The error can be fixed by the returning the value out of the\n+ transformed function::\n+\n+ >>> from jax import jit\n+ >>> import jax.numpy as jnp\n+\n+ >>> outs = []\n+ >>> @jit\n+ ... def not_side_effecting(x):\n+ ... y = x+1\n+ ... return y\n+ >>> x = 1\n+ >>> y = not_side_effecting(x)\n+ >>> outs.append(y)\n+ >>> outs[0]+1 # all good! no longer a leaked value.\n+ DeviceArray(3, dtype=int32)\n+\n+ Leak checker\n+ As discussed in point 2 and 3 above, we show a reconstructed stack-trace\n+ because we only throw an error when the leaked Tracer is used, not when the\n+ Tracer is leaked. We need to know the location where the Tracer was leaked\n+ to fix the error. The leak checker is a debug option you can use to throw an\n+ error as soon as a Tracer is leaked. (To be more exact, it will throw an\n+ error when the transformed function from which the Tracer is leaked returns)\n+\n+ To enable the leak checker you can use the `JAX_CHECK_TRACER_LEAKS`\n+ environment variable or the `with jax.checking_leaks()` context manager.\n+ Note that this util is experimental and may have some false positives. It\n+ works by disabling some JAX caches, so should only be used when debugging\n+ as it will have a negative effect on performance.\n+ \"\"\"\n+\n+ def __init__(self, msg: str):\n+ super().__init__(msg)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -32,7 +32,7 @@ from ._src import dtypes\nfrom ._src import config as jax_config\nfrom ._src.config import FLAGS, config\nfrom .errors import (ConcretizationTypeError, TracerArrayConversionError,\n- TracerIntegerConversionError)\n+ TracerIntegerConversionError, UnexpectedTracerError)\nfrom . import linear_util as lu\nfrom jax._src import source_info_util\n@@ -460,8 +460,6 @@ def escaped_tracer_error(tracer, detail=None):\n'manager.')\nreturn UnexpectedTracerError(msg)\n-class UnexpectedTracerError(Exception): pass\n-\nclass Tracer:\n__array_priority__ = 1000\n__slots__ = ['_trace', '__weakref__', '_line_info']\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/errors.py",
"new_path": "jax/errors.py",
"diff": "@@ -18,4 +18,5 @@ from ._src.errors import (JAXTypeError,\nConcretizationTypeError,\nNonConcreteBooleanIndexError,\nTracerArrayConversionError,\n- TracerIntegerConversionError)\n+ TracerIntegerConversionError,\n+ UnexpectedTracerError)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/loops.py",
"new_path": "jax/experimental/loops.py",
"diff": "@@ -116,6 +116,7 @@ from jax import lax, core\nfrom jax._src.lax import control_flow as lax_control_flow\nfrom jax import tree_util\nfrom jax import numpy as jnp\n+from jax.errors import UnexpectedTracerError\nfrom jax.interpreters import partial_eval as pe\nfrom jax._src.util import safe_map\n@@ -415,7 +416,7 @@ class _BodyTracer(object):\nin_tracers=in_tracers,\nout_tracers=body_out_tracers,\ntrace=self.trace)\n- except core.UnexpectedTracerError as e:\n+ except UnexpectedTracerError as e:\nif \"Tracer not among input tracers\" in str(e):\nraise ValueError(\"Body of cond_range or while_range should not use the \"\n\"index variable returned by iterator.\") from e\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -33,6 +33,7 @@ from jax._src import source_info_util\nfrom jax._src.abstract_arrays import (make_shaped_array, array_types)\nfrom ..core import (ConcreteArray, ShapedArray, AbstractToken,\nLiteral, pp_eqn_compact, raise_to_shaped, abstract_token)\n+from ..errors import UnexpectedTracerError\nfrom jax._src.pprint_util import pp\nfrom .._src.util import (partial, partialmethod, cache, prod, unzip2,\nextend_name_stack, wrap_name, safe_zip, safe_map)\n@@ -682,7 +683,7 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\njaxpr, out_avals, consts = pe.trace_to_jaxpr_final(\nfun, abstract_args, pe.debug_info_final(fun, \"jit\"))\nif any(isinstance(c, core.Tracer) for c in consts):\n- raise core.UnexpectedTracerError(\"Encountered an unexpected tracer.\")\n+ raise UnexpectedTracerError(\"Encountered an unexpected tracer.\")\njaxpr, kept_const_idx, kept_var_idx = _prune_unused_inputs(jaxpr)\nconsts = [c for i, c in enumerate(consts) if i in kept_const_idx]\npruned_arg_specs = (a for i, a in enumerate(arg_specs) if i in kept_var_idx)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -42,6 +42,7 @@ from jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\nfrom jax import core, dtypes, lax\nfrom jax._src import api\nfrom jax.core import Primitive\n+from jax.errors import UnexpectedTracerError\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters.sharded_jit import PartitionSpec as P\n@@ -2193,13 +2194,13 @@ class APITest(jtu.JaxTestCase):\ndef test_escaped_tracers_different_top_level_traces(self):\napi.jit(self.helper_save_tracer)(0.)\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError, \"Encountered an unexpected tracer\"):\n+ UnexpectedTracerError, \"Encountered an unexpected tracer\"):\napi.jit(lambda x: self._saved_tracer)(0.)\ndef test_escaped_tracers_cant_lift_sublevels(self):\napi.jit(self.helper_save_tracer)(0.)\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n+ UnexpectedTracerError,\nre.compile(\n\"Encountered an unexpected tracer\",\nre.DOTALL)):\n@@ -2208,7 +2209,7 @@ class APITest(jtu.JaxTestCase):\ndef test_escaped_tracers_tracer_from_higher_level(self):\napi.grad(self.helper_save_tracer)(0.)\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n+ UnexpectedTracerError,\nre.compile(\n\"Encountered an unexpected tracer.*Tracer from a higher level\",\nre.DOTALL)):\n@@ -2220,7 +2221,7 @@ class APITest(jtu.JaxTestCase):\n# Use the tracer\nreturn x + self._saved_tracer\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n+ UnexpectedTracerError,\nre.compile(\"Encountered an unexpected tracer\",\nre.DOTALL)):\napi.jit(func1)(2.)\n@@ -2230,7 +2231,7 @@ class APITest(jtu.JaxTestCase):\napi.grad(self.helper_save_tracer)(0.)\nreturn x + self._saved_tracer\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n+ UnexpectedTracerError,\nre.compile(\"Encountered an unexpected tracer.*Can't lift\",\nre.DOTALL)):\napi.grad(func1)(2.)\n@@ -2242,7 +2243,7 @@ class APITest(jtu.JaxTestCase):\nreturn x + self._saved_tracer\nwith self.assertRaisesRegex(\n- core.UnexpectedTracerError,\n+ UnexpectedTracerError,\nre.compile(\n\"Encountered an unexpected tracer.*Tracer not among input tracers\",\nre.DOTALL)):\n@@ -2265,7 +2266,7 @@ class APITest(jtu.JaxTestCase):\ndef g():\nlax.scan(f, None, None, length=2)\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ with self.assertRaisesRegex(UnexpectedTracerError,\n\"was created on line\"):\ng()\n@@ -2279,24 +2280,24 @@ class APITest(jtu.JaxTestCase):\nlax.scan(f, None, None, length=2) # leaked a tracer! (of level 1!)\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ with self.assertRaisesRegex(UnexpectedTracerError,\n\"was created on line\"):\n# The following call will try and raise the ones array to the count tracer\n# level, which is no longer live.\njax.jit(jnp.add)(jnp.ones(()), count)\ndef test_escaped_tracer_transform_name(self):\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ with self.assertRaisesRegex(UnexpectedTracerError,\n\"for jit\"):\njax.jit(self.helper_save_tracer)(1)\n_ = self._saved_tracer+1\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ with self.assertRaisesRegex(UnexpectedTracerError,\n\"for pmap\"):\njax.pmap(self.helper_save_tracer)(jnp.ones((1, 2)))\n_ = self._saved_tracer+1\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n+ with self.assertRaisesRegex(UnexpectedTracerError,\n\"for eval_shape\"):\njax.eval_shape(self.helper_save_tracer, 1)\n_ = self._saved_tracer+1\n@@ -3278,7 +3279,7 @@ class RematTest(jtu.JaxTestCase):\napi.remat(g)()\napi.remat(g)()\n- with self.assertRaisesRegex(core.UnexpectedTracerError, \"global state\"):\n+ with self.assertRaisesRegex(UnexpectedTracerError, \"global state\"):\napi.jit(f)()\ndef test_no_cse_widget_on_primals(self):\n@@ -4715,9 +4716,9 @@ class CustomVJPTest(jtu.JaxTestCase):\ndef g(x, y):\nreturn f(x, y)\n- with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n+ with self.assertRaisesRegex(UnexpectedTracerError, \"custom_vjp\"):\n_ = g(2, 3.)\n- with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n+ with self.assertRaisesRegex(UnexpectedTracerError, \"custom_vjp\"):\n_ = api.grad(g, 1)(2., 3.)\ndef test_vmap_axes(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -30,6 +30,7 @@ import numpy.random as npr\nimport jax\nfrom jax._src import api\nfrom jax import core\n+from jax.errors import UnexpectedTracerError\nfrom jax import lax\nfrom jax import random\nfrom jax import test_util as jtu\n@@ -2722,8 +2723,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(deriv(my_pow)(3.0, 1), 1.0, check_dtypes=False)\ndef test_unexpected_tracer_error(self):\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n- \"for while_loop\"):\n+ with self.assertRaisesRegex(UnexpectedTracerError, \"for while_loop\"):\nlst = []\ndef side_effecting_body(val):\nlst.append(val)\n@@ -2731,8 +2731,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nlax.while_loop(lambda x: x < 2, side_effecting_body, 1)\nlst[0] += 1\n- with self.assertRaisesRegex(core.UnexpectedTracerError,\n- \"for scan\"):\n+ with self.assertRaisesRegex(UnexpectedTracerError, \"for scan\"):\nlst = []\ndef side_effecting_scan(carry, val):\nlst.append(val)\n"
}
] | Python | Apache License 2.0 | google/jax | Expose UnexpectedTracerError and add docs. |
260,424 | 28.07.2021 13:02:06 | -3,600 | f966e7ef5ce28fa9b6ce95494d6c2f52f9c66387 | Fix some of the formatting and reword some of the sections. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/errors.py",
"new_path": "jax/_src/errors.py",
"diff": "@@ -440,18 +440,20 @@ class UnexpectedTracerError(JAXTypeError):\nWhat does it mean to leak a value? If you use a JAX transformation on a\nfunction ``f`` that stores, in some scope outside of ``f``, a reference to\nan intermediate value, that value is considered to have been leaked.\n- Leaking values is a side effect.\n+ Leaking values is a side effect. (Read more about avoiding side effects in\n+ `Pure Functions <https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functions>`_)\nJAX detects leaks when you then use the leaked value in another\n- operation later on, at which point it raises `UnexpectedTracerError`.\n+ operation later on, at which point it raises an ``UnexpectedTracerError``.\nTo fix this, avoid side effects: if a function computes a value needed\nin an outer scope, return that value from the transformed function explictly.\n- Specifically, ``Tracer``s are JAX's internal representation of a function's\n- intermediate values during transformations, e.g. within `jit`, `pmap`, `vmap`,\n- etc. Encountering a `Tracer` outside of a transformation implies a leak.\n+ Specifically, a ``Tracer`` is JAX's internal representation of a function's\n+ intermediate values during transformations, e.g. within ``jit``, ``pmap``,\n+ ``vmap``, etc. Encountering a ``Tracer`` outside of a transformation implies a\n+ leak.\n- Life-cycle of a leaked Tracer\n+ Life-cycle of a leaked value\nConsider the following example of a transformed function which leaks a value\nto an outer scope::\n@@ -463,6 +465,7 @@ class UnexpectedTracerError(JAXTypeError):\n... def side_effecting(x):\n... y = x+1 # 3\n... outs.append(y) # 4\n+\n>>> x = 1\n>>> side_effecting(x) # 2\n>>> outs[0]+1 # 5 # doctest: +IGNORE_EXCEPTION_DETAIL\n@@ -471,36 +474,35 @@ class UnexpectedTracerError(JAXTypeError):\nUnexpectedTracerError: Encountered an unexpected tracer.\nIn this example we leak a Traced value from an inner transformed scope to an\n- outer scope. We get an UnexpectedTracerError not when the value is leaked\n- but later, when the leaked value is used.\n+ outer scope. We get an ``UnexpectedTracerError`` when the leaked value is\n+ used, not when the value is leaked.\n- This example also demonstrates the life-cycle of a leaked Tracer:\n+ This example also demonstrates the life-cycle of a leaked value:\n- 1. A function is transformed (in this case, by `jit`)\n+ 1. A function is transformed (in this case, by ``jit``)\n2. The transformed function is called (initiating an abstract trace of the\n- function and turning `x` into a Tracer)\n- 3. The Tracer which will be leaked is created (an intermediate value of\n- a traced function is also a Tracer)\n- 4. The Tracer is leaked (appended to a list in an outer scope, escaping\n+ function and turning ``x`` into a ``Tracer``)\n+ 3. The intermediate value ``y``, which will later be leaked, is created\n+ (an intermediate value of a traced function is also a ``Tracer``)\n+ 4. The value is leaked (appended to a list in an outer scope, escaping\nthe function through a side-channel)\n- 5. The leaked Tracer is used, and an UnexpectedTracerError is raised.\n+ 5. The leaked value is used, and an UnexpectedTracerError is raised.\n- The UnexpectedTracerError tries to point to these locations in your code by\n- including information about each stage. Respectively:\n+ The UnexpectedTracerError message tries to point to these locations in your\n+ code by including information about each stage. Respectively:\n- 1. The name of the transformed function (`side_effecting`) and which\n- transform kicked of the trace (`jit`).\n- 2. A reconstructed stack trace of where the Tracer was created, which\n- includes where the transformed function was called. (`When the Tracer\n- was created, the final 5 stack frames (most recent last) excluding\n- JAX-internal frames were...`).\n+ 1. The name of the transformed function (``side_effecting``) and which\n+ transform kicked of the trace (``jit``).\n+ 2. A reconstructed stack trace of where the leaked Tracer was created,\n+ which includes where the transformed function was called.\n+ (``When the Tracer was created, the final 5 stack frames were...``).\n3. From the reconstructed stack trace, the line of code that created\nthe leaked Tracer.\n- 4. The leak location is not included in the error message. It is difficult\n- to pin down! JAX can only tell you what the leaked value looks like\n- (what shape is has and where it was created) and what boundary it was\n- leaked over (the name of the transformation and the name of the\n- transformed function).\n+ 4. The leak location is not included in the error message because it is\n+ difficult to pin down! JAX can only tell you what the leaked value\n+ looks like (what shape is has and where it was created) and what\n+ boundary it was leaked over (the name of the transformation and the\n+ name of the transformed function).\n5. The current error's stack trace points to where the value is used.\nThe error can be fixed by the returning the value out of the\n@@ -514,6 +516,7 @@ class UnexpectedTracerError(JAXTypeError):\n... def not_side_effecting(x):\n... y = x+1\n... return y\n+\n>>> x = 1\n>>> y = not_side_effecting(x)\n>>> outs.append(y)\n@@ -521,18 +524,44 @@ class UnexpectedTracerError(JAXTypeError):\nDeviceArray(3, dtype=int32)\nLeak checker\n- As discussed in point 2 and 3 above, we show a reconstructed stack-trace\n- because we only raise an error when the leaked Tracer is used, not when the\n- Tracer is leaked. We need to know the location where the Tracer was leaked\n- to fix the error. The leak checker is a debug option you can use to raise an\n- error as soon as a Tracer is leaked. (To be more exact, it will raise an\n- error when the transformed function from which the Tracer is leaked returns)\n-\n- To enable the leak checker you can use the `JAX_CHECK_TRACER_LEAKS`\n- environment variable or the `with jax.checking_leaks()` context manager.\n+ As discussed in point 2 and 3 above, JAX shows a reconstructed stack trace\n+ which points to where the leaked value was created. This is because\n+ JAX only raises an error when the leaked value is used, not when the\n+ value is leaked. This is not the most useful place to raise this error,\n+ because you need to know the location where the Tracer was leaked to fix the\n+ error.\n+\n+ To make this location easier to track down, you can use the leak checker.\n+ When the leak checker is enabled, an error is raised as soon as a ``Tracer``\n+ is leaked. (To be more exact, it will raise an error when the transformed\n+ function from which the ``Tracer`` is leaked returns)\n+\n+ To enable the leak checker you can use the ``JAX_CHECK_TRACER_LEAKS``\n+ environment variable or the ``with jax.checking_leaks()`` context manager.\n+\n+ .. note::\nNote that this tool is experimental and may report false positives. It\n- works by disabling some JAX caches, so should only be used when debugging\n- as it will have a negative effect on performance.\n+ works by disabling some JAX caches, so it will have a negative effect on\n+ performance and should only be used when debugging.\n+\n+ Example usage::\n+\n+ >>> from jax import jit\n+ >>> import jax.numpy as jnp\n+\n+ >>> outs = []\n+ >>> @jit\n+ ... def side_effecting(x):\n+ ... y = x+1\n+ ... outs.append(y)\n+\n+ >>> x = 1\n+ >>> with jax.checking_leaks():\n+ ... y = side_effecting(x) # doctest: +IGNORE_EXCEPTION_DETAIL\n+ Traceback (most recent call last):\n+ ...\n+ Exception: Leaked Trace\n+\n\"\"\"\ndef __init__(self, msg: str):\n"
}
] | Python | Apache License 2.0 | google/jax | Fix some of the formatting and reword some of the sections. |
260,510 | 07.07.2021 11:03:59 | 25,200 | 49f7ac22cce1f421e85d039a075f40b9c861ca09 | change while loop batching fixed point condition | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/control_flow.py",
"new_path": "jax/_src/lax/control_flow.py",
"diff": "@@ -373,7 +373,7 @@ def _pred_bcast_select(c, pred, x, y, x_y_aval: core.AbstractValue):\nelif x_y_aval is core.abstract_token:\nreturn xops.AfterAll(c, [x, y])\nelse:\n- assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)]\n+ assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)], (pred_shape, x_shape, y_shape)\nbcast_pred = xops.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))\nreturn xops.Select(bcast_pred, x, y)\n@@ -383,43 +383,76 @@ def _while_loop_batching_rule(args, dims, axis_name, main_type,\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\norig_batched = [d is not batching.not_mapped for d in dims]\ncconst_bat, bconst_bat, init_bat = split_list(orig_batched, [cond_nconsts, body_nconsts])\n+ cconsts, bconsts, init = split_list(args, [cond_nconsts, body_nconsts])\n+ cconst_dims, bconst_dims, init_dims = split_list(dims, [cond_nconsts, body_nconsts])\n+ carry_bat = init_bat\n# Fixpoint computation of which carry are batched: either\n# batched from init, or the carry out is batched. Each iteration promotes\n- # at least one carry to batched. We need at most len(carry) iterations,\n- # but we need one last iteration to prepare the jaxpr based on the final\n- # carry_bat.\n- carry_bat = init_bat\n+ # at least one carry to batched. We need at most len(carry) iterations to\n+ # reach a fixpoint.\nfor _ in range(1 + len(carry_bat)):\n- batched = bconst_bat + carry_bat\n- body_jaxpr_batched, carry_bat_out = batching.batch_jaxpr(\n- body_jaxpr, size, batched, instantiate=carry_bat,\n+ _, carry_bat_out = batching.batch_jaxpr(\n+ body_jaxpr, size, bconst_bat + carry_bat, instantiate=False,\naxis_name=axis_name, main_type=main_type)\n- cond_jaxpr_batched, (pred_bat,) = batching.batch_jaxpr(\n- cond_jaxpr, size, cconst_bat + carry_bat,\n- instantiate=bool(cond_jaxpr.out_avals[0].shape),\n- axis_name=axis_name, main_type=main_type)\n- carry_bat_out = _map(partial(operator.or_, pred_bat), carry_bat_out)\n- if carry_bat_out == carry_bat:\n+ if carry_bat == carry_bat_out:\nbreak\n- else:\n- carry_bat = _map(operator.or_, carry_bat, carry_bat_out)\n+ carry_bat = safe_map(operator.or_, carry_bat, carry_bat_out)\nelse:\nassert False, \"Fixpoint not reached\"\n- consts, init = split_list(args, [cond_nconsts + body_nconsts])\n- const_dims, init_dims = split_list(dims, [cond_nconsts + body_nconsts])\n- new_consts = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0\n- else x for x, d in zip(consts, const_dims)]\n- new_init = [batching.broadcast(x, size, 0) if now_bat and not was_bat\n- else batching.moveaxis(x, d, 0) if now_bat and d != 0 else x\n- for x, d, was_bat, now_bat in zip(init, init_dims, init_bat, carry_bat)]\n+ # Knowing how the carry is batched now, we can determine if the predicate is\n+ # batched.\n+ _, (pred_bat,) = batching.batch_jaxpr(\n+ cond_jaxpr, size, cconst_bat + carry_bat, instantiate=False,\n+ axis_name=axis_name, main_type=main_type)\n+\n+ if pred_bat:\n+ # If the predicate is batched, we have to batch *all* of the carry\n+ # regardless of if the body needs it.\n+ carry_bat = [True] * len(carry_bat)\n+ carry_dims = [0] * len(carry_bat)\n+ body_jaxpr_batched, _ = batching.batch_jaxpr(\n+ body_jaxpr, size, bconst_bat + carry_bat,\n+ instantiate=True, axis_name=axis_name, main_type=main_type)\n+ cond_jaxpr_batched, _ = batching.batch_jaxpr(\n+ cond_jaxpr, size, cconst_bat + carry_bat, instantiate=True,\n+ axis_name=axis_name, main_type=main_type)\n+ else:\n+ # If the predicate is not batched, we need to make sure that the in axes\n+ # match the out axes in the batched `body_jaxpr`. Otherwise the predicate's\n+ # shape may not be a prefix of the carry shapes. We can do this with\n+ # the `batch_jaxpr_axes` helper method.\n+ cond_rank = len(cond_jaxpr.out_avals[0].shape)\n+ carry_dims = [cond_rank if b else None for b in carry_bat]\n+ body_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ body_jaxpr, size, bconst_dims + carry_dims, carry_dims,\n+ axis_name=axis_name, main_type=main_type)\n+ # Now we need to rebatch the `cond_jaxpr` according to the dims of the\n+ # carry.\n+ cond_jaxpr_batched, _ = batching.batch_jaxpr_axes(\n+ cond_jaxpr, size, cconst_dims + carry_dims, (None,),\n+ axis_name=axis_name, main_type=main_type)\n+\n+\n+ # To prepare the `init` to the `while_p`, we broadcast values if they are\n+ # unbatched and need to have an out axis. If their current batch axis does not\n+ # match the one it needs to be for the translation rule to work, we move it\n+ # into place.\n+ new_init = []\n+ for x, old_axis, new_axis in zip(init, init_dims, carry_dims):\n+ if old_axis is batching.not_mapped and new_axis is not batching.not_mapped:\n+ new_init.append(batching.broadcast(x, size, new_axis))\n+ elif old_axis is batching.not_mapped and new_axis is batching.not_mapped:\n+ new_init.append(x)\n+ else:\n+ assert new_axis is not batching.not_mapped\n+ new_init.append(batching.moveaxis(x, old_axis, new_axis))\n- outs = while_p.bind(*(new_consts + new_init),\n+ outs = while_p.bind(*(cconsts + bconsts + new_init),\ncond_nconsts=cond_nconsts, cond_jaxpr=cond_jaxpr_batched,\nbody_nconsts=body_nconsts, body_jaxpr=body_jaxpr_batched)\n- out_bdims = [0 if b else batching.not_mapped for b in carry_bat]\n- return outs, out_bdims\n+ return outs, carry_dims\ndef _while_loop_jvp(primals, tangents, cond_nconsts, cond_jaxpr, body_nconsts,\nbody_jaxpr):\n@@ -551,7 +584,7 @@ def _while_transpose_error(*_, **kwargs):\n\"lax.while_loop or lax.fori_loop. \"\n\"Try using lax.scan instead.\")\n-while_p = lax.Primitive('while')\n+while_p = core.Primitive('while')\nwhile_p.multiple_results = True\nwhile_p.def_impl(partial(xla.apply_primitive, while_p))\nwhile_p.def_abstract_eval(_while_loop_abstract_eval)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/batching.py",
"new_path": "jax/interpreters/batching.py",
"diff": "@@ -453,17 +453,31 @@ def bdim_at_front(x, bdim, size):\nreturn moveaxis(x, bdim, 0)\n+zero_if_mapped = object()\n+\ndef batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name, main_type):\n+ if instantiate is None:\n+ instantiate = False\n+ if isinstance(instantiate, bool):\n+ instantiate = [instantiate] * len(closed_jaxpr.out_avals)\n+ out_axes = [0 if inst else zero_if_mapped for inst in instantiate]\n+ return batch_jaxpr_axes(\n+ closed_jaxpr, axis_size,\n+ [0 if b else not_mapped for b in in_batched],\n+ out_axes,\n+ axis_name, main_type)\n+\n+def batch_jaxpr_axes(closed_jaxpr, axis_size, in_axes, out_axes, axis_name, main_type):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\n- f, out_batched = batch_subtrace_instantiate(f, instantiate, axis_size)\n- f = batchfun(f, axis_name, axis_size, [0 if b else None for b in in_batched], main_type)\n- avals_in = [core.unmapped_aval(axis_size, 0, aval) if b else aval\n- for aval, b in zip(closed_jaxpr.in_avals, in_batched)]\n+ f, out_batched = batch_subtrace_instantiate(f, axis_size, out_axes)\n+ f = batchfun(f, axis_name, axis_size, in_axes, main_type)\n+ avals_in = [core.unmapped_aval(axis_size, b, aval) if b is not not_mapped\n+ else aval for aval, b in zip(closed_jaxpr.in_avals, in_axes)]\njaxpr_out, _, consts = pe.trace_to_jaxpr_dynamic(f, avals_in)\nreturn core.ClosedJaxpr(jaxpr_out, consts), out_batched()\n@lu.transformation_with_aux\n-def batch_subtrace_instantiate(instantiate, axis_size, main, in_dims, *in_vals):\n+def batch_subtrace_instantiate(axis_size, out_axes, main, in_dims, *in_vals):\n# this is like `batch_subtrace` but we take an extra `instantiate` arg\n# analogue of `jvp_subtrace` in ad.py\ntrace = main.with_cur_sublevel()\n@@ -473,13 +487,12 @@ def batch_subtrace_instantiate(instantiate, axis_size, main, in_dims, *in_vals):\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- if type(instantiate) is bool:\n- instantiate = [instantiate] * len(out_vals)\n- out_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0\n- else broadcast(x, axis_size, 0) if d is not_mapped and inst else x\n- for x, d, inst in zip(out_vals, out_dims, instantiate)]\n- out_batched = [d is not not_mapped or inst\n- for d, inst in zip(out_dims, instantiate)]\n+ out_axes = [(None if od is not_mapped else 0) if out_axis is zero_if_mapped else out_axis\n+ for od, out_axis in zip(out_dims, out_axes)]\n+ out_vals = [moveaxis(x, d, od) if d is not not_mapped\n+ else broadcast(x, axis_size, od) if od is not None else x\n+ for x, d, od in zip(out_vals, out_dims, out_axes)]\n+ out_batched = [od is not None for od in out_axes]\nyield out_vals, out_batched\n@lu.transformation_with_aux\n"
}
] | Python | Apache License 2.0 | google/jax | change while loop batching fixed point condition
Co-authored-by: Sharad Vikram <sharad.vikram@gmail.com>
Co-authored-by: Adam Paszke <apaszke@google.com> |
260,578 | 28.07.2021 15:22:42 | 25,200 | bf28b884b2c54c877d6ae00f29979692e74e21da | Log a warning after 60 secs to remind the user to run code on all hosts for Cloud TPU 1VM | [
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -145,6 +145,22 @@ def _make_tpu_driver_client():\nreturn tpu_driver_client.TpuBackend.create(worker=FLAGS.jax_backend_target)\n+def tpu_client_timer_callback(timer: float):\n+ def _log_warning():\n+ logging.warning('Did you run your code on all the hosts?')\n+\n+ # Will log a warning after `timer` secs.\n+ t = threading.Timer(timer, _log_warning)\n+ t.start()\n+\n+ try:\n+ client = xla_client.make_tpu_client()\n+ finally:\n+ t.cancel()\n+\n+ return client\n+\n+\n# Backends, in increasing order of preference.\n# We have no particular opinion about how \"backends\" relate to \"devices\". For\n# example, there could be multiple backends that provide the same kind of\n@@ -170,7 +186,7 @@ register_backend_factory('tpu_driver', _make_tpu_driver_client,\npriority=100)\nregister_backend_factory('gpu', xla_client.make_gpu_client,\npriority=200)\n-register_backend_factory('tpu', xla_client.make_tpu_client,\n+register_backend_factory('tpu', partial(tpu_client_timer_callback, timer=60.0),\npriority=300)\n_default_backend = None\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/xla_bridge_test.py",
"new_path": "tests/xla_bridge_test.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import sys\n+import time\n+import warnings\nfrom absl.testing import absltest\nfrom jax.lib import xla_bridge as xb\nfrom jax.lib import xla_client as xc\nfrom jax import test_util as jtu\n+mock = absltest.mock\n+\n+\n+def mock_tpu_client():\n+ time.sleep(0.03)\n+ return None\nclass XlaBridgeTest(absltest.TestCase):\n@@ -56,6 +65,12 @@ class XlaBridgeTest(absltest.TestCase):\nwith self.assertRaisesRegex(RuntimeError, \"Unknown backend foo\"):\nxb.local_devices(backend=\"foo\")\n+ @mock.patch('jax.lib.xla_client.make_tpu_client', side_effect=mock_tpu_client)\n+ def test_timer_tpu_warning_1vm(self, _):\n+ with self.assertLogs('absl', level='WARNING') as al:\n+ xb.tpu_client_timer_callback(0.01)\n+ self.assertIn('Did you run your code on all the hosts?', al.output[0])\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | Log a warning after 60 secs to remind the user to run code on all hosts for Cloud TPU 1VM |
260,578 | 28.07.2021 18:28:37 | 25,200 | cdfc2dc8fe5a5351abff18d0d449af3f4fc5abe0 | Use warnings instead of absl.logging.warning | [
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -147,7 +147,7 @@ def _make_tpu_driver_client():\ndef tpu_client_timer_callback(timer: float):\ndef _log_warning():\n- logging.warning('Did you run your code on all the hosts?')\n+ warnings.warn('Did you run your code on all the hosts?')\n# Will log a warning after `timer` secs.\nt = threading.Timer(timer, _log_warning)\n"
}
] | Python | Apache License 2.0 | google/jax | Use warnings instead of absl.logging.warning |
260,578 | 28.07.2021 18:56:22 | 25,200 | ee7759f9939a10663c559ef0c5363f0b60d8f102 | Fix xla_bridge_test.py | [
{
"change_type": "MODIFY",
"old_path": "tests/xla_bridge_test.py",
"new_path": "tests/xla_bridge_test.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+import warnings\nimport time\nfrom absl.testing import absltest\n@@ -65,9 +66,11 @@ class XlaBridgeTest(absltest.TestCase):\n@mock.patch('jax.lib.xla_client.make_tpu_client', side_effect=mock_tpu_client)\ndef test_timer_tpu_warning_1vm(self, _):\n- with self.assertLogs('absl', level='WARNING') as al:\n+ with warnings.catch_warnings(record=True) as w:\n+ warnings.simplefilter('always')\nxb.tpu_client_timer_callback(0.01)\n- self.assertIn('Did you run your code on all the hosts?', al.output[0])\n+ msg = str(w[-1].message)\n+ self.assertIn('Did you run your code on all the hosts?', msg)\nif __name__ == \"__main__\":\n"
}
] | Python | Apache License 2.0 | google/jax | Fix xla_bridge_test.py |
260,578 | 28.07.2021 19:38:58 | 25,200 | 1a994297f1aef7e0bf52d5a1dbafae08f6a44530 | Check for length of warning too | [
{
"change_type": "MODIFY",
"old_path": "tests/xla_bridge_test.py",
"new_path": "tests/xla_bridge_test.py",
"diff": "@@ -70,6 +70,7 @@ class XlaBridgeTest(absltest.TestCase):\nwarnings.simplefilter('always')\nxb.tpu_client_timer_callback(0.01)\nmsg = str(w[-1].message)\n+ self.assertLen(w, 1)\nself.assertIn('Did you run your code on all the hosts?', msg)\n"
}
] | Python | Apache License 2.0 | google/jax | Check for length of warning too |
260,411 | 28.07.2021 19:30:44 | -10,800 | 3d85709e307fec58ec587608ff8525a9f517d63c | [jax2tf] Test code refactoring | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -100,7 +100,7 @@ def call_tf(callable_tf: Callable) -> Callable:\ndef make_tensorspec(a_jax):\na_tf_dtype = jax2tf_internal._to_tf_dtype(a_jax.dtype)\nif any(not core.is_constant_dim(d) for d in a_jax.shape):\n- msg = (\"call_tf cannot be applies to shape-polymorphic arguments. \"\n+ msg = (\"call_tf cannot be applied to shape-polymorphic arguments. \"\nf\"Found argument shape: {a_jax.shape}. \"\n\"See https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#limitations-of-call-tf for a discussion.\")\nraise ValueError(msg)\n@@ -266,7 +266,11 @@ def _code_generator_and_avals(\n# Due to bugs like b/193754660, the compilation may fail. To work around this\n# issue we pass the `code_gen_optional` when in an abstract evaluation context\n- # in which case we fallback on TF shape inference.\n+ # in which case we fallback on TF shape inference. Luckily it seen that\n+ # it is never the case that we are under tf.function, and we call the\n+ # XLA translation rule for call_tf. The latter happens only for jax.jit, but\n+ # jax.jit under a tf.function must be under jax2tf.convert, which unrolls\n+ # the jit.\n# TODO(necula): It seems that we need concrete tensors for get_compiler_ir?\n# We know of one case when TF is sensitive to the values of the tensors that\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -781,6 +781,8 @@ class TensorFlowTrace(core.Trace):\n# This is a bit conservative, doing abstract_eval even in op-by-op execution\n# but we needed it for, e.g., shape_polymorphism where only JAX's\n# abstract evaluation rules can properly track polymorphic shapes.\n+ # Unfortunately under op-by-op execution this is a rare occasion where we\n+ # need abstract evaluation.\nout_aval = primitive.abstract_eval(*args_avals, **params)\nargs_tf: Sequence[TfVal] = [t.val for t in tracers]\ndef invoke_impl() -> TfVal:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -598,11 +598,12 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\n# Call get_compiler_ir in a function context\nx = np.array([2., 3., 4.], dtype=np.float32)\n- # TODO(b/193754660)\n- # def fun_tf_outer(x):\n- # x_const = tf.constant(0, shape=x.shape, dtype=x.dtype)\n- # _ = tf.function(tf.math.sin, jit_compile=True).experimental_get_compiler_ir(x_const)()\n+ def fun_tf_outer(x):\n+ x_const = tf.constant(0, shape=x.shape, dtype=x.dtype)\n+ _ = tf.function(tf.math.sin, jit_compile=True).experimental_get_compiler_ir(x_const)()\n+\n+ # TODO(b/193754660)\n# with self.assertRaisesRegex(\n# TypeError, \"An op outside of the function building code is being passed\"):\n# tf.function(fun_tf_outer)(x)\n@@ -612,13 +613,13 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\n# tf.function(fun_tf_outer, jit_compile=True)(x)\n# Call get_concrete_function in a graph context\n- def fun_tf_outer(x):\n+ def fun_tf_outer_2(x):\n_ = tf.function(tf.math.sin, jit_compile=True).get_concrete_function(tf.TensorSpec(x.shape, x.dtype))\nreturn x\n# Outside of a function context, this works.\n- _ = tf.function(fun_tf_outer)(x)\n- _ = tf.function(fun_tf_outer, jit_compile=True)(x)\n+ _ = tf.function(fun_tf_outer_2)(x)\n+ _ = tf.function(fun_tf_outer_2, jit_compile=True)(x)\ndef test_module_documentation(self):\ndef cos_tf(x):\n@@ -693,17 +694,18 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(f_jax(x), f_jax_rt(x))\ndef test_saved_model_simple(self):\n+ x = np.array([0.7, 0.8], dtype=np.float32)\ndef f_jax(x):\nreturn jnp.sin(x)\n- x = np.array([0.7, 0.8], dtype=np.float32)\n+\nf_tf = jax2tf.convert(f_jax)\n- restored_tf, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec(x.shape, x.dtype)])\n+ restored_tf, _ = tf_test_util.SaveAndLoadFunction(f_tf, input_args=[x])\nrestored_jax = jax2tf.call_tf(restored_tf)\nself.assertAllClose(f_jax(x), restored_jax(x))\ndef test_saved_model_variables(self):\n- x = np.array([0.7, 0.8], dtype=np.float32)\nparam = np.array([1., 2.], dtype=np.float32)\n+ x = np.array([0.7, 0.8], dtype=np.float32)\ndef f_jax(param, x):\nreturn jnp.sin(x) + jnp.cos(param)\n@@ -711,26 +713,27 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f_jax)\n_, restored_model = tf_test_util.SaveAndLoadFunction(\nlambda x: f_tf(param_v, x),\n- [tf.TensorSpec(x.shape, x.dtype)],\n- variables=(param_v,))\n+ input_args=[x],\n+ variables=[param_v])\nrestored_jax = jax2tf.call_tf(restored_model.f)\nself.assertAllClose(f_jax(param, x), restored_jax(x))\nself.assertAllClose(f_jax(param, x), jax.jit(restored_jax)(x))\ndef test_saved_model_shape_poly(self):\ntracing_count = 0\n+ x = np.array([0.7, 0.8], dtype=np.float32)\ndef f_jax(x):\nnonlocal tracing_count\ntracing_count += 1\nreturn jnp.sin(x)\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\n- x = np.array([0.7, 0.8], dtype=np.float32)\nres_jax = f_jax(x)\nself.assertEqual(1, tracing_count)\n# Will trace twice, it seems. Once to get the result signature, and once again\n# for the actual saving.\n- restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(\n+ f_tf, input_signature=[tf.TensorSpec([None], x.dtype)])\nself.assertGreaterEqual(tracing_count, 2)\ntracing_count = 0\nf_jax_rt = jax2tf.call_tf(restored_f)\n@@ -762,7 +765,7 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\ng_tf, _ = tf_test_util.SaveAndLoadFunction(\njax2tf.convert(g, with_gradient=True, polymorphic_shapes=[\"b, ...\"]),\n- [tf.TensorSpec([None], dtype=tf.float32)])\n+ input_signature=[tf.TensorSpec([None], dtype=tf.float32)])\ng_rt = jax2tf.call_tf(g_tf)\nx = np.array([0.7], dtype=np.float32)\nself.assertAllClose(g(x), g_rt(x))\n@@ -775,7 +778,7 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\nx = np.array([0.7, 0.8], dtype=np.float32)\nf_tf, _ = tf_test_util.SaveAndLoadFunction(\njax2tf.convert(f_jax, with_gradient=False),\n- [tf.TensorSpec(x.shape, dtype=x.dtype)])\n+ input_args=[x])\nf_rt = jax2tf.call_tf(f_tf)\nself.assertAllClose(f_jax(x), f_rt(x))\n@@ -789,8 +792,7 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\nx = np.array([0.7, 0.8], dtype=np.float32)\nf_tf, _ = tf_test_util.SaveAndLoadFunction(\n- jax2tf.convert(f_jax, with_gradient=True),\n- [tf.TensorSpec(x.shape, dtype=x.dtype)],\n+ jax2tf.convert(f_jax, with_gradient=True), input_args=[x],\nsave_gradients=False)\nf_rt = jax2tf.call_tf(f_tf)\n@@ -808,8 +810,9 @@ class RoundTripToJaxTest(tf_test_util.JaxToTfTestCase):\n# with tf.init_scope():\n# added = my_constant * 2\n# The graph tensor has name: args_0:0\n+ with self.assertRaisesRegex(TypeError, \"An op outside of the function\"):\n+ _ = jax.grad(f_rt)(x)\n- # g = jax.grad(f_rt)(x)\nclass RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\n\"Reloading output of call_tf into TF with jax2tf.\"\n@@ -842,6 +845,7 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\nwith tf.GradientTape() as tape:\nres = f_tf_outer(xv)\ng_tf = tape.gradient(res, xv)\n+ _, gf = tf_test_util.ComputeTfValueAndGrad(f_tf_outer, (x,))\n# Eager\nexpected_res = np.sin(np.cos(np.sin(np.cos(np.sin(x)))))\nself.assertAllClose(expected_res, f_tf_outer(x).numpy())\n@@ -875,15 +879,14 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\nres = fun_tf_rt(x)\nself.assertAllClose(np.sin(x), res.numpy())\n- # TODO(b/193754660)\n- res = tf.function(fun_tf_rt)(x)\n+ res = tf.function(fun_tf_rt, autograph=False)(x)\nself.assertAllClose(np.sin(x), res.numpy())\n- res = tf.function(fun_tf_rt, jit_compile=True)(x)\n+ res = tf.function(fun_tf_rt, jit_compile=True, autograph=False)(x)\nself.assertAllClose(np.sin(x), res.numpy())\nreloaded_f, _ = tf_test_util.SaveAndLoadFunction(\n- fun_tf_rt, input_signature=[tf.TensorSpec(x.shape, x.dtype)])\n+ fun_tf_rt, input_args=[x])\nres = reloaded_f(x)\nself.assertAllClose(np.sin(x), res.numpy())\n@@ -927,7 +930,7 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"b, ...\"])\nwith self.assertRaisesRegex(\nValueError,\n- \"call_tf cannot be applies to shape-polymorphic arguments\"):\n+ \"call_tf cannot be applied to shape-polymorphic arguments\"):\nfun_tf_rt(x)\nif __name__ == \"__main__\":\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"new_path": "jax/experimental/jax2tf/tests/savedmodel_test.py",
"diff": "@@ -216,8 +216,7 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\n# JAX. We check that this information is preserved through a savedmodel\nf_tf = jax2tf.convert(f_jax)\nres = f_tf(*args)\n- input_signature = list(tf.TensorSpec(a.shape, a.dtype) for a in args)\n- restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, input_signature)\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, input_args=args)\nres_restored = restored_f(*args)\nself.assertAllClose(res, res_restored)\n@@ -265,7 +264,7 @@ class SavedModelTest(tf_test_util.JaxToTfTestCase):\n# Save and restore SavedModel\nrestored_f, _ = tf_test_util.SaveAndLoadFunction(composed_fn,\n- [tf.TensorSpec((2,), dtype=tf.string)])\n+ input_args=[x_str])\nres_tf_restored = restored_f(x_str)\nself.assertAllClose(res_tf_restored.numpy(), res_tf.numpy())\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": "@@ -761,7 +761,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_jax = jnp.sin\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\nx = np.array([0.7, 0.8], dtype=np.float32)\n- restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(\n+ f_tf, input_signature=[tf.TensorSpec([None], x.dtype)])\nself.assertAllClose(f_jax(x), restored_f(x))\n# Ensure that restored_f works at other batch size as well\ny = np.concatenate([x, x])\n@@ -778,7 +779,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\n# When saving the model with gradients, we trace the gradient function\n# and we used to get an error when creating zeros_like_aval for a\n# polymorphic shape\n- restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec((None,) + x.shape[1:], x.dtype)])\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(\n+ f_tf, input_signature=[tf.TensorSpec((None,) + x.shape[1:], x.dtype)])\nf_jax_rt = jax2tf.call_tf(restored_f)\nres_jax_rt = f_jax_rt(x)\nself.assertAllClose(f_jax(x), res_jax_rt)\n@@ -789,7 +791,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nf_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"(b, ...)\"])\nx = np.array([0.7, 0.8], dtype=np.float32)\n- restored_f, _ = tf_test_util.SaveAndLoadFunction(f_tf, [tf.TensorSpec([None], x.dtype)])\n+ restored_f, _ = tf_test_util.SaveAndLoadFunction(\n+ f_tf, input_signature=[tf.TensorSpec([None], x.dtype)])\nself.assertAllClose(3., restored_f(x))\nself.assertAllClose(np.array([0., 0.], dtype=np.float32), jax.grad(f_jax)(x))\n@@ -996,7 +999,8 @@ def _make_harness(group_name: str, name: str,\npoly_axes: Sequence[Optional[Union[int, Sequence[int]]]],\ncheck_result=True,\ntol=None,\n- **params) -> Harness:\n+ enable_and_diable_xla=False,\n+ **params) -> Union[Harness, Sequence[Harness]]:\n\"\"\"The `poly_axes` must correspond to the non-static arguments, and for each\none it must specify which axes are: None, or an int (for the index of the\npolymorphic axis), or a tuple of ints (for multiple polymorphic axes).\n@@ -1012,7 +1016,19 @@ def _make_harness(group_name: str, name: str,\n`check_result` specifies if we want to check that the result of the shape\npolymorphic conversion produces the same result and the JAX function.\n+\n+ enable_and_diable_xla=True means that we generate two harnesses,\n+ one with enable_xla=False.\n\"\"\"\n+ if enable_and_diable_xla:\n+ return [\n+ _make_harness(group_name, name + (\"\" if enable_xla else \"_noxla\"), # type: ignore\n+ func, args, poly_axes=poly_axes,\n+ check_result=check_result, tol=tol, enable_xla=enable_xla,\n+ enable_and_diable_xla=False,\n+ **params)\n+ for enable_xla in [True, False]\n+ ]\npoly_axes_name = f\"poly_axes={repr(poly_axes)}\"\nassert isinstance(poly_axes, Sequence)\n# Make poly_axes: Sequence[Sequence[int]]\n@@ -1036,27 +1052,27 @@ _f32 = np.float32\n# List containing either harnesses, or lists of harnesses\n_POLY_SHAPE_TEST_HARNESSES = [\n- _make_harness(\"jnp_add\", \"\",\n- jnp.add,\n- [RandArg((3, 4), _f32), RandArg((2, 3, 4), _f32)],\n- poly_axes=[0, 1]),\n-\n- _make_harness(\"jnp_broadcast_to\", \"\",\n- lambda x: jnp.broadcast_to(x, [x.shape[0], x.shape[0], 4]),\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0]),\n-\n+ # Reduce the poly dimension\n+ _make_harness(\"argmax\", \"0\",\n+ lambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n+ [RandArg((3, 4, 5), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ # Reduce the non-poly dimension\n+ _make_harness(\"argmax\", \"1\",\n+ lambda op: lax.argmax(op, axis=1, index_dtype=np.int32),\n+ [RandArg((3, 4, 5), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n_make_harness(\"add_transpose\", \"\",\njax.grad(lambda x: jnp.sum(jnp.sum(x, axis=0, keepdims=0) + x)),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"clamp\", \"\",\nlax.clamp,\n[RandArg((3, 4, 5), _f32), RandArg((3, 4, 5), _f32),\nRandArg((3, 4, 5), _f32)],\npoly_axes=[0, 0, 0]),\n-\n_make_harness(\"conv_general_dilated\", \"\",\nlambda lhs, rhs: lax.conv_general_dilated(lhs, rhs,\nwindow_strides=(2, 3),\n@@ -1069,60 +1085,85 @@ _POLY_SHAPE_TEST_HARNESSES = [\nprecision=None),\n[RandArg((7, 3, 9, 10), _f32), RandArg((3, 3, 4, 5), _f32)],\npoly_axes=[0, None]),\n-\n_make_harness(\"cummax\", \"\",\nlambda x: lax_control_flow.cummax(x, axis=1, reverse=False),\n[RandArg((3, 4, 5), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"dot_general\", \"\",\nlambda lhs, rhs: lax.dot_general(lhs, rhs,\ndimension_numbers=(((2,), (1,)), ((0,), (0,)))),\n[RandArg((3, 4, 4), _f32), RandArg((3, 4), _f32)],\npoly_axes=[0, 0]),\n-\n+ _make_harness(\"dynamic_slice\", \"idx=tuple_int\",\n+ # x:shape: (b, 4)\n+ lambda x: lax.dynamic_slice(x, (0, 1), (x.shape[0], 2)),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"dynamic_slice\", \"idx=tuple_arg\",\n+ # x:shape: (b, 4)\n+ lambda x, i0: lax.dynamic_slice(x, (i0, np.int32(1)), (x.shape[0], 2)),\n+ [RandArg((3, 4), _f32), np.array(-2, dtype=np.int32)],\n+ poly_axes=[0, None],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"dynamic_slice\", \"idx=array\",\n+ # x:shape: (b, 4)\n+ lambda x, idx: lax.dynamic_slice(x, idx, (x.shape[0], 2)),\n+ [RandArg((3, 4), _f32), np.array([-2, -1], dtype=np.int32)],\n+ poly_axes=[0, None],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"dynamic_update_slice\", \"idx=tuple_int\",\n+ # x:shape: (b, 4)\n+ lambda x: lax.dynamic_update_slice(x, x, (0, 0)),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"dynamic_update_slice\", \"idx=tuple_arg\",\n+ # x:shape: (b, 4)\n+ lambda x, i0: lax.dynamic_update_slice(x, x, (i0, np.int32(0))),\n+ [RandArg((3, 4), _f32), np.array(-2, dtype=np.int32)],\n+ poly_axes=[0, None],\n+ enable_and_diable_xla=True),\n+ _make_harness(\"dynamic_update_slice\", \"idx=array\",\n+ # x:shape: (b, 4)\n+ lambda x, idx: lax.dynamic_update_slice(x, x, idx),\n+ [RandArg((3, 4), _f32), np.array([-2, -1], dtype=np.int32)],\n+ poly_axes=[0, None],\n+ enable_and_diable_xla=True),\n_make_harness(\"einsum\", \"0\",\nlambda x: jnp.einsum(\"...i->...\", x),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"einsum\", \"0_alt\",\nlambda x: jnp.einsum(x, (..., 1), [...]),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"einsum\", \"1\",\nlambda x, y: jnp.einsum(\"...ij,...jk->...ik\", x, y),\n[RandArg((3, 4, 5), _f32), RandArg((3, 5, 6), _f32)],\npoly_axes=[0, 0]),\n-\n_make_harness(\"einsum\", \"1_alt\",\nlambda x, y: jnp.einsum(x, [..., 0, 1], y, (..., 1, 2), [..., 0, 2]),\n[RandArg((3, 4, 5), _f32), RandArg((3, 5, 6), _f32)],\npoly_axes=[0, 0]),\n-\n_make_harness(\"einsum\", \"2\",\nlambda x, y: jnp.einsum(\"...ij,jk->...ik\", x, y),\n[RandArg((3, 4, 5), _f32), RandArg((5, 6), _f32)],\npoly_axes=[0, None]),\n-\n_make_harness(\"einsum\", \"2_alt\",\nlambda x, y: jnp.einsum(x, [..., 0, 1], y, [1, 2], [..., 0, 2]),\n[RandArg((3, 4, 5), _f32), RandArg((5, 6), _f32)],\npoly_axes=[0, None]),\n-\n_make_harness(\"einsum\", \"3\",\n# Reduced dimension is polymorphic\nlambda x, y: jnp.einsum(\"ij,jk->ik\", x, y),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n-\n_make_harness(\"einsum\", \"3_alt\",\n# Reduced dimension is polymorphic\nlambda x, y: jnp.einsum(x, [0, 1], y, [1, 2], [0, 2]),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n-\n_make_harness(\"einsum\", \"4\",\n# Reduced dimension is polymorphic, and is 2*b\nlambda x, y: jnp.einsum(\"ij,jk->ik\",\n@@ -1130,7 +1171,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\njnp.concatenate([y, y], axis=0)),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n-\n_make_harness(\"einsum\", \"4_alt\",\n# Reduced dimension is polymorphic, and is 2*b\nlambda x, y: jnp.einsum(jnp.concatenate([x, x], axis=1), [0, 1],\n@@ -1138,24 +1178,64 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[0, 2]),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n-\n_make_harness(\"iota\", \"\",\nlambda x: x + lax.iota(_f32, x.shape[0]),\n[RandArg((3,), _f32)],\npoly_axes=[0]),\n-\n+ _make_harness(\"jnp_add\", \"\",\n+ jnp.add,\n+ [RandArg((3, 4), _f32), RandArg((2, 3, 4), _f32)],\n+ poly_axes=[0, 1]),\n+ [\n+ _make_harness(\"jnp_average\",\n+ f\"axis={axis}_weights=None\",\n+ lambda x, axis: jnp.average(x, axis=axis, returned=False, weights=None),\n+ [RandArg((7, 8, 4), _f32), StaticArg(axis)],\n+ poly_axes=[0])\n+ for axis in [None, 0, 1]\n+ ],\n+ [\n+ _make_harness(\"jnp_average\",\n+ f\"axis={axis}_weights=Some\",\n+ lambda x, weights, axis: jnp.average(x, axis=axis, returned=False, weights=weights),\n+ [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), _f32), StaticArg(axis)],\n+ poly_axes=[0, 0])\n+ for axis in [None, 0, 1]\n+ ],\n+ _make_harness(\"jnp_broadcast_to\", \"\",\n+ lambda x: jnp.broadcast_to(x, [x.shape[0], x.shape[0], 4]),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ # operand is non-poly, index is poly\n+ _make_harness(\"jnp_getitem\", \"op=static_idx=poly\",\n+ lambda a, i: a[i],\n+ [RandArg((3, 4), _f32), np.array([2, 2], np.int32)],\n+ poly_axes=[None, 0], enable_and_diable_xla=True),\n+ # operand is poly, index is integer\n+ _make_harness(\"jnp_getitem\", \"op=poly_idx=const\",\n+ lambda a: a[1],\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0], enable_and_diable_xla=True),\n+ # operand is poly, index is dim poly\n+ _make_harness(\"jnp_getitem\", \"op=poly_idx=dim\",\n+ lambda a: a[jax.core.dimension_as_value(a.shape[0] - 2)],\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0], enable_and_diable_xla=True),\n+ # Both the operand and the index are poly\n+ _make_harness(\"jnp_getitem\", \"op=poly_idx=poly\",\n+ lambda a, i: a[i],\n+ [RandArg((3, 4), _f32), np.array([1, 2, 0], np.int32)],\n+ poly_axes=[0, 0], enable_and_diable_xla=True),\n_make_harness(\"jnp_matmul\", \"0\",\njnp.matmul,\n[RandArg((7, 8, 4), _f32), RandArg((7, 4, 5), _f32)],\npoly_axes=[0, 0],\ntol=1e-5),\n-\n_make_harness(\"jnp_matmul\", \"1\",\njnp.matmul,\n[RandArg((7, 8, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[0, None],\ntol=1e-5),\n-\n[\n_make_harness(\"jnp_mean\",\nf\"axis={axis}_keepdims={keepdims}_where=None\",\n@@ -1165,7 +1245,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor keepdims in [False, True]\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n-\n[\n_make_harness(\"jnp_mean\",\nf\"axis={axis}_keepdims={keepdims}_where=Some\",\n@@ -1175,25 +1254,22 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor keepdims in [False, True]\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n-\n- [\n- _make_harness(\"jnp_average\",\n- f\"axis={axis}_weights=None\",\n- lambda x, axis: jnp.average(x, axis=axis, returned=False, weights=None),\n- [RandArg((7, 8, 4), _f32), StaticArg(axis)],\n- poly_axes=[0])\n- for axis in [None, 0, 1]\n- ],\n-\n- [\n- _make_harness(\"jnp_average\",\n- f\"axis={axis}_weights=Some\",\n- lambda x, weights, axis: jnp.average(x, axis=axis, returned=False, weights=weights),\n- [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), _f32), StaticArg(axis)],\n- poly_axes=[0, 0])\n- for axis in [None, 0, 1]\n- ],\n-\n+ _make_harness(\"jnp_ones\", \"\",\n+ lambda x: jnp.ones(x.shape, dtype=_f32),\n+ [RandArg((3, 2, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"jnp_squeeze\", \"axis=None\",\n+ jnp.squeeze,\n+ [RandArg((5,), _f32), StaticArg(())],\n+ poly_axes=[0]),\n+ _make_harness(\"jnp_squeeze\", \"axis=1\",\n+ jnp.squeeze,\n+ [RandArg((4, 1), _f32), StaticArg((1,))],\n+ poly_axes=[0]),\n+ _make_harness(\"jnp_take\", \"\",\n+ lambda a, i: jnp.take(a, i, axis=1),\n+ [RandArg((3, 4, 5), _f32), np.array([1, 2], np.int32)],\n+ poly_axes=[0, None], enable_and_diable_xla=True),\n[\n_make_harness(\"jnp_var\",\nf\"axis={axis}_keepdims={keepdims}_where=None\",\n@@ -1203,7 +1279,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor keepdims in [False, True]\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n-\n[\n_make_harness(\"jnp_var\",\nf\"axis={axis}_keepdims={keepdims}_where=Some\",\n@@ -1213,58 +1288,42 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor keepdims in [False, True]\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n-\n_make_harness(\"jnp_where\", \"\",\njnp.where,\n[RandArg((2,), np.bool_), RandArg((), _f32), RandArg((2,), _f32)],\npoly_axes=[0, None, 0]),\n-\n_make_harness(\"pad\", \"\",\nlax.pad,\n[RandArg((3, 2, 5), _f32), np.float32(5.),\nStaticArg(((0, 0, 0), (0, 0, 0), (1, 1, 1)))],\npoly_axes=[0, None]),\n-\n- _make_harness(\"jnp_ones\", \"\",\n- lambda x: jnp.ones(x.shape, dtype=_f32),\n- [RandArg((3, 2, 4), _f32)],\n- poly_axes=[0]),\n-\n_make_harness(\"random_gamma\", \"\",\nlambda key, a: jax.random.gamma(key, a),\n[RandArg((3, 2), np.uint32), RandArg((3, 3), _f32)],\npoly_axes=[0, 0]),\n-\n+ [\n+ _make_harness(\"reduce\", reduce_op.__name__,\n+ lambda x: reduce_op(x, axis=-1, keepdims=True),\n+ [RandArg((3, 5), _f32)],\n+ poly_axes=[0])\n+ for reduce_op in [jnp.all, jnp.any, jnp.max, jnp.min, jnp.prod, jnp.sum]\n+ ],\n_make_harness(\"reshape\", \"0\",\nlambda x: x.reshape([x.shape[0], -1]),\n[RandArg((3, 2, 3), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"reshape\", \"1\",\nlambda x: x.reshape([x.shape[0], -1]),\n[RandArg((3, 2, 3), _f32)],\npoly_axes=[(0, 1)]),\n-\n_make_harness(\"reshape\", \"2\",\nlambda x: x.reshape([x.shape[0], -1, x.shape[3], x.shape[2]]),\n[RandArg((3, 4, 5, 6, 7), _f32)],\npoly_axes=[(0, 2, 3)]),\n-\n_make_harness(\"reshape\", \"3\",\nlambda x: jnp.reshape(x, [2, -1]),\n[RandArg((3, 4, 5, 6, 7), _f32)],\npoly_axes=[(0, 2)]),\n-\n- _make_harness(\"jnp_squeeze\", \"axis=None\",\n- jnp.squeeze,\n- [RandArg((5,), _f32), StaticArg(())],\n- poly_axes=[0]),\n-\n- _make_harness(\"jnp_squeeze\", \"axis=1\",\n- jnp.squeeze,\n- [RandArg((4, 1), _f32), StaticArg((1,))],\n- poly_axes=[0]),\n-\n_make_harness(\"scatter_add\", \"\",\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True),\n[RandArg((7, 4), _f32),\n@@ -1272,34 +1331,28 @@ _POLY_SHAPE_TEST_HARNESSES = [\nRandArg((7, 2), _f32), # upd\nStaticArg(lax.ScatterDimensionNumbers((0,), (1,), (1,)))],\npoly_axes=[0, None, 0]),\n-\n- _make_harness(\"slice\", \"entire_axis\",\n- lambda x: lax.slice(x, start_indices=(0, 1), limit_indices=(x.shape[0], 3)),\n- [RandArg((7, 3), _f32)],\n- poly_axes=[0]),\n-\n_make_harness(\"select\", \"0\",\n# x.shape = (b, 3)\nlambda x: lax.select(x > 5., x, x),\n[RandArg((7, 3), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"select\", \"1\",\n# x.shape = (b, 3); y.shape = (3,)\njax.vmap(lambda x, y: lax.select(x > 5., x, y), in_axes=[0, None]),\n[RandArg((7, 3), _f32), RandArg((3,), _f32)],\npoly_axes=[0, None]),\n-\n+ _make_harness(\"slice\", \"entire_axis\",\n+ lambda x: lax.slice(x, start_indices=(0, 1), limit_indices=(x.shape[0], 3)),\n+ [RandArg((7, 3), _f32)],\n+ poly_axes=[0]),\n_make_harness(\"squeeze\", \"axis=1_2\",\njnp.squeeze,\n[RandArg((4, 1, 1), _f32), StaticArg((1, 2))],\npoly_axes=[0]),\n-\n_make_harness(\"tile\", \"0\",\nlambda x: jnp.tile(x, (1, 2)),\n[RandArg((4, 3), _f32)],\npoly_axes=[0]),\n-\n_make_harness(\"tile\", \"1\",\n# The repetitions are polys\nlambda x: jnp.tile(x, (1, x.shape[0])),\n@@ -1307,105 +1360,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[0]),\n]\n-\n-for enable_xla in [False, True]:\n- _POLY_SHAPE_TEST_HARNESSES.extend([\n- # Reduce the poly dimension\n- _make_harness(\"argmax\", f\"0_enable_xla={enable_xla}\",\n- lambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n- [RandArg((3, 4, 5), _f32)],\n- poly_axes=[0],\n- enable_xla=enable_xla),\n-\n- # Reduce the non-poly dimension\n- _make_harness(\"argmax\", f\"1_enable_xla={enable_xla}\",\n- lambda op: lax.argmax(op, axis=1, index_dtype=np.int32),\n- [RandArg((3, 4, 5), _f32)],\n- poly_axes=[0],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_slice\", f\"idx=tuple_int_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x: lax.dynamic_slice(x, (0, 1), (x.shape[0], 2)),\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_slice\", f\"idx=tuple_arg_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x, i0: lax.dynamic_slice(x, (i0, np.int32(1)), (x.shape[0], 2)),\n- [RandArg((3, 4), _f32), np.array(-2, dtype=np.int32)],\n- poly_axes=[0, None],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_slice\", f\"idx=array_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x, idx: lax.dynamic_slice(x, idx, (x.shape[0], 2)),\n- [RandArg((3, 4), _f32), np.array([-2, -1], dtype=np.int32)],\n- poly_axes=[0, None],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_update_slice\", f\"idx=tuple_int_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x: lax.dynamic_update_slice(x, x, (0, 0)),\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_update_slice\", f\"idx=tuple_arg_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x, i0: lax.dynamic_update_slice(x, x, (i0, np.int32(0))),\n- [RandArg((3, 4), _f32), np.array(-2, dtype=np.int32)],\n- poly_axes=[0, None],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"dynamic_update_slice\", f\"idx=array_enable_xla={enable_xla}\",\n- # x:shape: (b, 4)\n- lambda x, idx: lax.dynamic_update_slice(x, x, idx),\n- [RandArg((3, 4), _f32), np.array([-2, -1], dtype=np.int32)],\n- poly_axes=[0, None],\n- enable_xla=enable_xla),\n-\n- _make_harness(\"jnp_take\", f\"enable_xla={enable_xla}\",\n- lambda a, i: jnp.take(a, i, axis=1),\n- [RandArg((3, 4, 5), _f32), np.array([1, 2], np.int32)],\n- poly_axes=[0, None], enable_xla=enable_xla),\n-\n- # operand is non-poly, index is poly\n- _make_harness(\"jnp_getitem\", f\"op=static_idx=poly_enable_xla={enable_xla}\",\n- lambda a, i: a[i],\n- [RandArg((3, 4), _f32), np.array([2, 2], np.int32)],\n- poly_axes=[None, 0], enable_xla=enable_xla),\n-\n- # operand is poly, index is integer\n- _make_harness(\"jnp_getitem\", f\"op=poly_idx=const_enable_xla={enable_xla}\",\n- lambda a: a[1],\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0], enable_xla=enable_xla),\n-\n- # operand is poly, index is dim poly\n- _make_harness(\"jnp_getitem\", f\"op=poly_idx=dim_enable_xla={enable_xla}\",\n- lambda a: a[jax.core.dimension_as_value(a.shape[0] - 2)],\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0], enable_xla=enable_xla),\n-\n- # Both the operand and the index are poly\n- _make_harness(\"jnp_getitem\", f\"op=poly_idx=poly_enable_xla={enable_xla}\",\n- lambda a, i: a[i],\n- [RandArg((3, 4), _f32), np.array([1, 2, 0], np.int32)],\n- poly_axes=[0, 0], enable_xla=enable_xla),\n-\n- ])\n-\n-for reduce_op in [jnp.all, jnp.any, jnp.max, jnp.min, jnp.prod, jnp.sum]:\n- _POLY_SHAPE_TEST_HARNESSES.append(\n- _make_harness(\"reduce\", reduce_op.__name__,\n- lambda x: reduce_op(x, axis=-1, keepdims=True),\n- [RandArg((3, 5), _f32)],\n- poly_axes=[0])\n- )\n-\n-\n### We add to the test harnesses some that are obtained from the\n### primitive harnesses by applying vmap to the function and then asserting\n### that we can convert shape polymorphically the result.\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"new_path": "jax/experimental/jax2tf/tests/tf_test_util.py",
"diff": "@@ -85,13 +85,21 @@ def SaveAndLoadModel(model: tf.Module,\nrestored_model = tf.saved_model.load(model_dir)\nreturn restored_model\n-def SaveAndLoadFunction(f_tf: Callable,\n- input_signature: Sequence[tf.TensorSpec],\n+def SaveAndLoadFunction(f_tf: Callable, *,\n+ input_signature: Optional[Sequence[tf.TensorSpec]] = None,\n+ input_args: Optional[Sequence[Any]] = None,\nvariables: Sequence[tf.Variable] = (),\nsave_gradients=True) -> Tuple[Callable, tf.train.Checkpoint]:\n# Roundtrip through saved model on disk. Return the Checkpoint also\n- # for the cases when there are variables.\n+ # for the cases when there are variables. If you don't pass input_signature\n+ # then it is created from the input_args.\nmodel = tf.train.Checkpoint()\n+ if input_signature is None:\n+ assert input_args is not None\n+ input_signature = tf.nest.map_structure(lambda a: tf.TensorSpec(a.shape, a.dtype),\n+ input_args)\n+ else:\n+ assert input_args is None\nmodel.f = tf.function(f_tf,\nautograph=False,\ninput_signature=input_signature)\n@@ -132,9 +140,9 @@ def TransformTfValueAndGrad(tf_f: Callable, tf_args,\nreturn (res_tf, grad)\nreturn wrapped, tf_args\n-\n-def ComputeTfValueAndGrad(tf_f: Callable, tf_args,\n+def ComputeTfValueAndGrad(tf_f: Callable, tf_args: Sequence,\nunconnected_gradients=tf.UnconnectedGradients.ZERO):\n+ assert isinstance(tf_args, Sequence), f\"tf_args must be a tuple: {tf_args}\"\nf1, args1 = TransformTfValueAndGrad(tf_f, tf_args,\nunconnected_gradients=unconnected_gradients)\nreturn f1(*args1)\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Test code refactoring |
260,411 | 29.07.2021 13:16:06 | -10,800 | 881daa5c901c1bbb9600ebd0af5ebe88ccd6e812 | [jax2tf] Handle truediv div for shape polymorphism | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -320,6 +320,19 @@ class _DimPolynomial(dict):\ndef __rfloordiv__(self, other):\nreturn _ensure_poly(other).__floordiv__(self)\n+ def __truediv__(self, divisor: DimSize):\n+ # Used for \"/\"\n+ q, r = self.divmod(divisor)\n+ if r != 0:\n+ raise InconclusiveDimensionOperation(\n+ f\"Dimension polynomial '{self}' is not a multiple of '{divisor}'\")\n+ return q\n+\n+ def __rtruediv__(self, dividend: DimSize):\n+ # Used for \"/\", when dividend is not a _DimPolynomial\n+ raise InconclusiveDimensionOperation(\n+ f\"Division of '{dividend}' by dimension polynomial '{self}' is not supported\")\n+\ndef __mod__(self, divisor: DimSize) -> int:\nreturn self.divmod(divisor)[1]\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": "@@ -245,14 +245,45 @@ class DimPolynomialTest(tf_test_util.JaxToTfTestCase):\n(a, b, None, None),\n(3 * a, 2, None, None),\n(2 * a * b + b * b, a + b, None, None),\n+ (3, a, None, None),\n])\n- def test_poly_divmod(self, dividend, quotient, divisor, remainder):\n+ def test_poly_divmod(self, *, dividend, quotient, divisor, remainder):\nif quotient is None:\nwith self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n\"Dimension polynomial .* is not a multiple of .*\"):\n- dividend.divmod(divisor)\n+ divmod(dividend, divisor)\nelse:\n- self.assertEqual((quotient, remainder), dividend.divmod(divisor))\n+ self.assertEqual((quotient, remainder), divmod(dividend, divisor))\n+\n+ @parameterized.named_parameters(\n+ dict(testcase_name=f\"_D={dividend}_d={divisor}_q={quotient}\",\n+ dividend=dividend, divisor=divisor, quotient=quotient)\n+ for dividend, divisor, quotient in [\n+ (a, 1, a),\n+ (3 * a, 3, a),\n+ (3 * a + 3, 3, a + 1),\n+ (3 * a + 2, 3, None),\n+ (3 * a + 5, 3, None),\n+ (3 * a - 2, 3, None),\n+ (3 * a * a * b + 2 * b * b * a, a * b, 3 * a + 2 * b),\n+ (a * a - b * b, a + b, a - b),\n+ (a, b, None),\n+ (3 * a, 2, None),\n+ (2 * a * b + b * b, a + b, None),\n+ ])\n+ def test_poly_truediv(self, *, dividend, divisor, quotient):\n+ if quotient is None:\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n+ \"Dimension polynomial .* is not a multiple of .*\"):\n+ dividend / divisor\n+ else:\n+ self.assertEqual(quotient, dividend / divisor)\n+\n+ def test_poly_truediv_error(self):\n+ a, = shape_poly.parse_spec(\"a,\", (2,))\n+ with self.assertRaisesRegex(core.InconclusiveDimensionOperation,\n+ \"Division of '3' by dimension polynomial .* is not supported\"):\n+ 3 / a\ndef test_dilate_shape(self):\n\"\"\"0 if d == 0 else 1 + dilation * (d - 1))\"\"\"\n@@ -844,8 +875,9 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"(b1, b2, ...)\"])(np.ones((4, 5, 6)))\nwith self.assertRaisesRegex(\n- TypeError,\n- re.escape(\"unsupported operand type(s) for /: 'TensorFlowTracer' and '_DimPolynomial'\")):\n+ core.InconclusiveDimensionOperation,\n+ re.compile(\"Division of .* by dimension polynomial .* is not supported\",\n+ re.DOTALL)):\njax2tf.convert(lambda x: jnp.sum(x, axis=0) / x.shape[0],\npolymorphic_shapes=[\"(v, _)\"])(np.ones((4, 4)))\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Handle truediv div for shape polymorphism |
260,411 | 29.07.2021 16:07:13 | -10,800 | 0b766b27a4fbb7b3f66504c975bdf0ab8f913e67 | [jax2tf] Improved testing and shape polymorphism support for lax.random. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/random.py",
"new_path": "jax/_src/random.py",
"diff": "@@ -236,7 +236,13 @@ def threefry_2x32(keypair, count):\nmsg = \"threefry_2x32 requires uint32 arguments, got {}\"\nraise TypeError(msg.format([lax.dtype(x) for x in [key1, key2, count]]))\n+ try:\nodd_size = count.size % 2\n+ except core.InconclusiveDimensionOperation as e:\n+ msg = (\"jax.random functions have limited support for shape polymorphism. \"\n+ \"In particular, the product of the known dimensions must be even.\")\n+ raise core.InconclusiveDimensionOperation(msg) from e\n+\nif odd_size:\nx = list(jnp.split(jnp.concatenate([count.ravel(), np.uint32([0])]), 2))\nelse:\n@@ -301,9 +307,16 @@ def _random_bits(key, bit_width, shape):\naxis_index = lax.axis_index(name)\nkey = fold_in(key, axis_index)\nsize = prod(shape.positional)\n- max_count = int(np.ceil(bit_width * size / 32))\n+ # Compute ceil(bit_width * size / 32) in a way that is friendly to shape\n+ # polymorphism\n+ max_count, r = divmod(bit_width * size, 32)\n+ if r > 0:\n+ max_count += 1\n+ if core.is_constant_dim(max_count):\nnblocks, rem = divmod(max_count, jnp.iinfo(np.uint32).max)\n+ else:\n+ nblocks, rem = 0, max_count\nif not nblocks:\nbits = threefry_2x32(key, lax.iota(np.uint32, rem))\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py",
"diff": "@@ -132,7 +132,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n\"dynamic_update_slice\", \"exp\", \"eq\", \"floor\", \"gather\", \"ge\", \"gt\",\n\"imag\",\n\"iota\", \"is_finite\", \"le\", \"lt\", \"log\", \"mul\", \"ne\", \"neg\", \"not\",\n- \"or\", \"pad\", \"population_count\", \"random_split\", \"reduce\",\n+ \"or\", \"pad\", \"population_count\",\n+ \"random_categorical\", \"random_split\", \"random_uniform\", \"random_randint\",\n+ \"reduce\",\n\"reduce_and\", \"reduce_prod\", \"reduce_or\", \"reduce_sum\",\n\"reduce_window_add\", \"reduce_window_mul\", \"reduce_window_min\",\n\"reduce_window_max\",\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -2411,6 +2411,44 @@ for key_i, key in enumerate([\njax.jit(lambda key: jax.random.split(key, 2)), [key],\ndtype=key.dtype)\n+# A few library functions from jax.random\n+for dtype in jtu.dtypes.all_floating:\n+ for shape in ((8,), (5, 4)):\n+ for axis in range(len(shape)):\n+ define(\n+ \"random_categorical\",\n+ f\"shape={jtu.format_shape_dtype_string(shape, dtype)}_axis={axis}\",\n+ jax.random.categorical,\n+ [np.array([42, 43], dtype=np.uint32), RandArg(shape, dtype),\n+ StaticArg(axis)],\n+ dtype=dtype,\n+ axis=axis)\n+\n+for dtype in jtu.dtypes.all_floating:\n+ for shape in ((), (5, 4), (32,)):\n+ define(\n+ \"random_uniform\",\n+ f\"shape={jtu.format_shape_dtype_string(shape, dtype)}\",\n+ jax.random.uniform,\n+ [np.array([42, 43], dtype=np.uint32),\n+ StaticArg(shape), StaticArg(dtype)],\n+ dtype=dtype)\n+\n+for dtype in jtu.dtypes.all_integer:\n+ for shape in ((), (5, 4), (32,)):\n+ maxval = {\n+ np.uint8: 256, # Borderline\n+ }.get(dtype, 5)\n+ define(\n+ \"random_randint\",\n+ f\"shape={jtu.format_shape_dtype_string(shape, dtype)}\",\n+ jax.random.randint,\n+ [np.array([42, 43], dtype=np.uint32),\n+ StaticArg(shape),\n+ StaticArg(-5), # minval\n+ StaticArg(maxval),\n+ StaticArg(dtype)],\n+ dtype=dtype)\ndef _make_clamp_harness(name,\n*,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"new_path": "jax/experimental/jax2tf/tests/primitives_test.py",
"diff": "@@ -100,7 +100,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\n# `one_containing=\"foo\"` to parameterized below.\n@primitive_harness.parameterized(\nprimitive_harness.all_harnesses, include_jax_unimpl=False,\n- #one_containing=\"tridiagonal\"\n+ #one_containing=\"random_uniform_shape=float32[5,4]\"\n)\n@jtu.ignore_warning(\ncategory=UserWarning, message=\"Using reduced precision for gradient.*\")\n@@ -311,6 +311,5 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nvalues = np.array([True, False, True], dtype=np.bool_)\nself.ConvertAndCompare(f_jax, values)\n-\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\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": "@@ -1333,6 +1333,32 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda key, a: jax.random.gamma(key, a),\n[RandArg((3, 2), np.uint32), RandArg((3, 3), _f32)],\npoly_axes=[0, 0]),\n+ # The known dimensions product must be even.\n+ _make_harness(\"random_categorical\", \"axis=0\",\n+ lambda key, a: jax.random.categorical(key, a, axis=0),\n+ [RandArg((2,), np.uint32), RandArg((3, 8), _f32)],\n+ poly_axes=[None, 0]),\n+ _make_harness(\"random_categorical\", \"axis=1\",\n+ lambda key, a: jax.random.categorical(key, a, axis=1),\n+ [RandArg((2,), np.uint32), RandArg((3, 8), _f32)],\n+ poly_axes=[None, 0]),\n+ # Works when the known dimensions are known to be even or odd.\n+ # See the random_uniform_error test also.\n+ _make_harness(\"random_uniform\", \"even_1\",\n+ lambda key, a: jax.random.uniform(key, a.shape, dtype=_f32),\n+ [RandArg((2,), np.uint32), RandArg((3, 4), _f32)],\n+ poly_axes=[None, 0]),\n+ _make_harness(\"random_uniform\", \"even_2\",\n+ lambda key, a: jax.random.uniform(key, (2 * a.shape[0], a.shape[1]),\n+ dtype=_f32),\n+ [RandArg((2,), np.uint32), RandArg((3, 5), _f32)],\n+ poly_axes=[None, 0]),\n+ # TODO(necula): not yet supported, but also unlikely to come up.\n+ # _make_harness(\"random_uniform\", \"odd\",\n+ # lambda key, a: jax.random.uniform(key, (2 * a.shape[0] + 1, a.shape[1]),\n+ # dtype=_f32),\n+ # [RandArg((2,), np.uint32), RandArg((3, 5), _f32)],\n+ # poly_axes=[None, 0]),\n[\n_make_harness(\"reduce\", reduce_op.__name__,\nlambda x: reduce_op(x, axis=-1, keepdims=True),\n@@ -1515,7 +1541,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"dynamic_slice_idx=tuple_arg_enable_xla=False_poly_axes=[0, None]\"\n+ #one_containing=\"uniform_odd_poly_axes=[None, 0]\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n@@ -1656,6 +1682,15 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes=[\"(2, a)\", \"(b, 3)\"],\nexpected_output_signature=tf.TensorSpec([None]))\n+ def test_random_uniform_error(self):\n+ with self.assertRaisesRegex(\n+ core.InconclusiveDimensionOperation,\n+ \"the product of the known dimensions must be even\"):\n+ self.CheckShapePolymorphism(\n+ lambda key, a: jax.random.uniform(key, a.shape, dtype=_f32),\n+ input_signature=[tf.TensorSpec([2], tf.uint32),\n+ tf.TensorSpec([None, 3], tf.float32)],\n+ polymorphic_shapes=[None, \"b, ...\"])\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improved testing and shape polymorphism support for lax.random. |
260,424 | 21.07.2021 13:27:48 | -3,600 | 21907346370320209a26fbf7a4f619bb62978352 | Add tracers to LeakChecker error, and filter out false positives this way.
If we can't find any hanging tracers in the gc.get_referrers chain, is it
really a leak? Probably not! | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -18,6 +18,7 @@ from operator import attrgetter\nfrom contextlib import contextmanager\nfrom collections import namedtuple\nfrom functools import total_ordering\n+import gc\nimport itertools as it\nfrom weakref import ref\nimport threading\n@@ -736,6 +737,17 @@ def reset_trace_state() -> bool:\ndef cur_sublevel() -> Sublevel:\nreturn thread_local_state.trace_state.substack[-1]\n+def maybe_find_leaked_tracers(x: Optional[Union[MainTrace, Sublevel]]):\n+ \"\"\"Find the leaked tracers holding a reference to the MainTrace or SubLevel.\n+\n+ It's possible there's none! eg. there's some cases where JAX itself holds a\n+ reference to `x` inside of a lambda closure, and no tracers were leaked\n+ by the user. In this case an empty list is returned.\n+ \"\"\"\n+ traces = list(filter(lambda x: isinstance(x, Trace), gc.get_referrers(x)))\n+ tracers = list(filter(lambda x: isinstance(x, Tracer), gc.get_referrers(*traces)))\n+ return tracers\n+\n@contextmanager\ndef new_main(trace_type: Type[Trace],\ndynamic: bool = False,\n@@ -761,7 +773,9 @@ def new_main(trace_type: Type[Trace],\nt = ref(main)\ndel main\nif t() is not None:\n- raise Exception(f'Leaked trace {t()}')\n+ leaked_tracers = maybe_find_leaked_tracers(t())\n+ if leaked_tracers:\n+ raise Exception(f'Leaked level {t()}. Leaked tracer(s): {leaked_tracers}.')\n@contextmanager\ndef new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\n@@ -782,7 +796,9 @@ def new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\nt = ref(main)\ndel main\nif t() is not None:\n- raise Exception('Leaked trace {}'.format(t()))\n+ leaked_tracers = maybe_find_leaked_tracers(t())\n+ if leaked_tracers:\n+ raise Exception(f'Leaked level {t()}. Leaked tracer(s): {leaked_tracers}.')\n@contextmanager\ndef eval_context():\n@@ -802,7 +818,9 @@ def new_sublevel() -> Generator[None, None, None]:\nt = ref(sublevel)\ndel sublevel\nif t() is not None:\n- raise Exception(f'Leaked sublevel {t()}.')\n+ leaked_tracers = maybe_find_leaked_tracers(t())\n+ if leaked_tracers:\n+ raise Exception(f'Leaked sublevel {t()}. Leaked tracer(s): {leaked_tracers}.')\ndef full_lower(val):\nif isinstance(val, Tracer):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/api_test.py",
"new_path": "tests/api_test.py",
"diff": "@@ -2596,6 +2596,23 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(Exception, r\"Leaked sublevel\"):\nf(3)\n+ def test_leak_checker_avoids_false_positive_custom_jvp(self):\n+ # see https://github.com/google/jax/issues/5636\n+ with jax.checking_leaks():\n+ @api.custom_jvp\n+ def t(y):\n+ return y\n+\n+ def t_jvp(p, t):\n+ pass\n+\n+ t.defjvp(t_jvp)\n+\n+ @jit\n+ def s(y):\n+ return t(y)\n+ s(3) # doesn't crash\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 | Add tracers to LeakChecker error, and filter out false positives this way.
If we can't find any hanging tracers in the gc.get_referrers chain, is it
really a leak? Probably not! |
260,335 | 29.07.2021 10:34:43 | 25,200 | c31688d2d1632f01491011d7150a527efc2007ff | fix cond-of-pmap bug | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -307,11 +307,13 @@ def extract_call_jaxpr(\nreturn (params[\"call_jaxpr\"], new_params)\n+# TODO(mattjj): replace this approach with a primitive-keyed table of rules\ndef traverse_jaxpr_params(f, params):\n\"\"\"Applies f to each jaxpr parameter and returns a tuple of returned values.\"\"\"\n- return {name: f(param)\n+ return {name: f(p)\nfor name, param in params.items()\n- if type(param) in (Jaxpr, ClosedJaxpr)}\n+ for p in (param if isinstance(param, (tuple, list)) else [param])\n+ if type(p) in (Jaxpr, ClosedJaxpr)}\ndef eval_jaxpr(jaxpr: Jaxpr, consts, *args):\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/pmap_test.py",
"new_path": "tests/pmap_test.py",
"diff": "@@ -1701,6 +1701,17 @@ class PmapTest(jtu.JaxTestCase):\nout_dtype = func(unused_arg).dtype\nself.assertEqual(out_dtype, dtype)\n+ def test_num_replicas_with_switch(self):\n+ # https://github.com/google/jax/issues/7411\n+ def identity(x):\n+ return x\n+\n+ def cond_of_pmap(x):\n+ y = lax.cond(True, jax.pmap(identity), jax.pmap(identity), x)\n+ return y\n+\n+ cond_of_pmap(jnp.zeros((xla_bridge.device_count(), 2)))\n+\nclass VmapOfPmapTest(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | fix cond-of-pmap bug |
260,411 | 30.07.2021 10:52:34 | -10,800 | 64d2e5c107a28d1d4a81c28e9bee3e9371fad9ae | [jax2tf] More cleanup for shape polymorphism testing | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -632,8 +632,8 @@ def parse_spec(spec: Optional[Union[str, PolyShape]],\ndim_poly = _parse_dim(dim_spec)\nif not is_poly_dim(dim_poly):\nif dim_poly != dim_size:\n- msg = (f\"PolyShape {repr(spec)} in axis {i} must contain a constant or '_' \"\n- f\"for known dimension in argument shape {arg_shape}\")\n+ msg = (f\"PolyShape {repr(spec)} in axis {i} must match the \"\n+ f\"known dimension size {dim_size} for argument shape {arg_shape}\")\nraise ValueError(msg)\nreturn dim_size\nreturn dim_poly\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "@@ -621,6 +621,24 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\n_ = tf.function(fun_tf_outer_2)(x)\n_ = tf.function(fun_tf_outer_2, jit_compile=True)(x)\n+ def test_repro_193754660(self):\n+ # Try to reproduce b/193754660. I can't.\n+ # We have to have tf.function(jax2tf.convert(jax2tf.call_tf(f_tf))).\n+ # The get_compiler_ir will indeed fail for f_tf. Then we try to use\n+ # shape inference for f_tf.\n+ # I thought to use a f_tf that uses an op without shape inference, e.g.,\n+ # tfxla.gather. If we wash it through a saved_model I expect that shape\n+ # inference would not work on it. Instead, shape inference works!!!\n+ x = np.array([0, 1, 2, 3, 4, 5], dtype=np.int32)\n+ def f_jax(x):\n+ return x[1]\n+ f_tf = jax2tf.convert(f_jax)\n+ f_tf_rt, _ = tf_test_util.SaveAndLoadFunction(f_tf, input_args=[x])\n+ f_jax2 = jax2tf.call_tf(f_tf_rt)\n+ f_tf2 = jax2tf.convert(f_jax2)\n+ res = tf.function(f_tf2, autograph=False)(x)\n+ self.assertAllClose(res.numpy(), f_jax(x))\n+\ndef test_module_documentation(self):\ndef cos_tf(x):\nreturn tf.math.cos(x)\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": "@@ -544,8 +544,8 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\nwith self.assertRaisesRegex(\nValueError,\nre.escape(\n- \"PolyShape '(2, 13)' in axis 1 must contain a constant or '_' for \"\n- \"known dimension in argument shape (2, 3)\"\n+ \"PolyShape '(2, 13)' in axis 1 must match the known dimension size 3 \"\n+ \"for argument shape (2, 3)\"\n)):\ncheck_avals(\nargs=[const((2, 3))],\n@@ -1030,8 +1030,10 @@ def _make_harness(group_name: str, name: str,\n*,\npoly_axes: Sequence[Optional[Union[int, Sequence[int]]]],\ncheck_result=True,\n+ skip_jax_run=True,\ntol=None,\nenable_and_diable_xla=False,\n+ expect_error=(None, None),\n**params) -> Union[Harness, Sequence[Harness]]:\n\"\"\"The `poly_axes` must correspond to the non-static arguments, and for each\none it must specify which axes are: None, or an int (for the index of the\n@@ -1057,7 +1059,8 @@ def _make_harness(group_name: str, name: str,\n_make_harness(group_name, name + (\"\" if enable_xla else \"_noxla\"), # type: ignore\nfunc, args, poly_axes=poly_axes,\ncheck_result=check_result, tol=tol, enable_xla=enable_xla,\n- enable_and_diable_xla=False,\n+ enable_and_diable_xla=False, skip_jax_run=skip_jax_run,\n+ expect_error=expect_error,\n**params)\nfor enable_xla in [True, False]\n]\n@@ -1074,8 +1077,8 @@ def _make_harness(group_name: str, name: str,\nname,\nfunc, args,\ndtype=np.float32,\n- poly_axes=poly_axes,\n- check_result=check_result,\n+ poly_axes=poly_axes, check_result=check_result,\n+ skip_jax_run=skip_jax_run, expect_error=expect_error,\ntol=tol,\n**params)\n@@ -1084,6 +1087,30 @@ _f32 = np.float32\n# List containing either harnesses, or lists of harnesses\n_POLY_SHAPE_TEST_HARNESSES = [\n+ _make_harness(\"add\", \"\",\n+ jnp.add,\n+ [RandArg((3, 4), _f32), RandArg((2, 3, 4), _f32)],\n+ poly_axes=[0, 1]),\n+ _make_harness(\"add_transpose\", \"\",\n+ jax.grad(lambda x: jnp.sum(jnp.sum(x, axis=0, keepdims=0) + x)),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ [\n+ _make_harness(\"average\",\n+ f\"axis={axis}_weights=None\",\n+ lambda x, axis: jnp.average(x, axis=axis, returned=False, weights=None),\n+ [RandArg((7, 8, 4), _f32), StaticArg(axis)],\n+ poly_axes=[0])\n+ for axis in [None, 0, 1]\n+ ],\n+ [\n+ _make_harness(\"average\",\n+ f\"axis={axis}_weights=Some\",\n+ lambda x, weights, axis: jnp.average(x, axis=axis, returned=False, weights=weights),\n+ [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), _f32), StaticArg(axis)],\n+ poly_axes=[0, 0])\n+ for axis in [None, 0, 1]\n+ ],\n# Reduce the poly dimension\n_make_harness(\"argmax\", \"0\",\nlambda op: lax.argmax(op, axis=0, index_dtype=np.int32),\n@@ -1096,8 +1123,8 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4, 5), _f32)],\npoly_axes=[0],\nenable_and_diable_xla=True),\n- _make_harness(\"add_transpose\", \"\",\n- jax.grad(lambda x: jnp.sum(jnp.sum(x, axis=0, keepdims=0) + x)),\n+ _make_harness(\"broadcast_to\", \"\",\n+ lambda x: jnp.broadcast_to(x, [x.shape[0], x.shape[0], 4]),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n_make_harness(\"clamp\", \"\",\n@@ -1210,66 +1237,59 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[0, 2]),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n- _make_harness(\"iota\", \"\",\n- lambda x: x + lax.iota(_f32, x.shape[0]),\n- [RandArg((3,), _f32)],\n- poly_axes=[0]),\n- _make_harness(\"jnp_add\", \"\",\n- jnp.add,\n- [RandArg((3, 4), _f32), RandArg((2, 3, 4), _f32)],\n- poly_axes=[0, 1]),\n- [\n- _make_harness(\"jnp_average\",\n- f\"axis={axis}_weights=None\",\n- lambda x, axis: jnp.average(x, axis=axis, returned=False, weights=None),\n- [RandArg((7, 8, 4), _f32), StaticArg(axis)],\n- poly_axes=[0])\n- for axis in [None, 0, 1]\n- ],\n- [\n- _make_harness(\"jnp_average\",\n- f\"axis={axis}_weights=Some\",\n- lambda x, weights, axis: jnp.average(x, axis=axis, returned=False, weights=weights),\n- [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), _f32), StaticArg(axis)],\n- poly_axes=[0, 0])\n- for axis in [None, 0, 1]\n- ],\n- _make_harness(\"jnp_broadcast_to\", \"\",\n- lambda x: jnp.broadcast_to(x, [x.shape[0], x.shape[0], 4]),\n- [RandArg((3, 4), _f32)],\n- poly_axes=[0]),\n+ _make_harness(\"einsum\", \"multiple_contractions_error\",\n+ lambda x, y, z: jnp.einsum(\"ab,bc,cd->ad\", x, y, z),\n+ [RandArg((3, 2), _f32), RandArg((2, 3), _f32), RandArg((3, 4), _f32),],\n+ poly_axes=[0, None, None],\n+ expect_error=(ValueError,\n+ \"Shape polymorphism is not yet supported for einsum with more than one contraction\")),\n+ _make_harness(\"einsum\", \"incompatible_contractions_error\",\n+ lambda x, y: jnp.einsum(\"ab,cb->ac\", x, y),\n+ [RandArg((2, 3), _f32), RandArg((2, 3), _f32)],\n+ poly_axes=[1, (0, 1)],\n+ expect_error=(core.InconclusiveDimensionOperation,\n+ \"Dimension polynomial comparison 'b1' == 'b0' is inconclusive\")),\n+\n# operand is non-poly, index is poly\n- _make_harness(\"jnp_getitem\", \"op=static_idx=poly\",\n+ _make_harness(\"getitem\", \"op=static_idx=poly\",\nlambda a, i: a[i],\n[RandArg((3, 4), _f32), np.array([2, 2], np.int32)],\npoly_axes=[None, 0], enable_and_diable_xla=True),\n# operand is poly, index is integer\n- _make_harness(\"jnp_getitem\", \"op=poly_idx=const\",\n+ _make_harness(\"getitem\", \"op=poly_idx=const\",\nlambda a: a[1],\n[RandArg((3, 4), _f32)],\npoly_axes=[0], enable_and_diable_xla=True),\n# operand is poly, index is dim poly\n- _make_harness(\"jnp_getitem\", \"op=poly_idx=dim\",\n+ _make_harness(\"getitem\", \"op=poly_idx=dim\",\nlambda a: a[jax.core.dimension_as_value(a.shape[0] - 2)],\n[RandArg((3, 4), _f32)],\npoly_axes=[0], enable_and_diable_xla=True),\n# Both the operand and the index are poly\n- _make_harness(\"jnp_getitem\", \"op=poly_idx=poly\",\n+ _make_harness(\"getitem\", \"op=poly_idx=poly\",\nlambda a, i: a[i],\n[RandArg((3, 4), _f32), np.array([1, 2, 0], np.int32)],\npoly_axes=[0, 0], enable_and_diable_xla=True),\n- _make_harness(\"jnp_matmul\", \"0\",\n+ _make_harness(\"getitem\", \"op=poly_idx=slice\",\n+ lambda a: a[1],\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0], enable_and_diable_xla=True),\n+ _make_harness(\"iota\", \"\",\n+ lambda x: x + lax.iota(_f32, x.shape[0]),\n+ [RandArg((3,), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"matmul\", \"0\",\njnp.matmul,\n[RandArg((7, 8, 4), _f32), RandArg((7, 4, 5), _f32)],\npoly_axes=[0, 0],\ntol=1e-5),\n- _make_harness(\"jnp_matmul\", \"1\",\n+ _make_harness(\"matmul\", \"1\",\njnp.matmul,\n[RandArg((7, 8, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[0, None],\ntol=1e-5),\n[\n- _make_harness(\"jnp_mean\",\n+ _make_harness(\"mean\",\nf\"axis={axis}_keepdims={keepdims}_where=None\",\nlambda x, axis, keepdims: jnp.mean(x, axis=axis, keepdims=keepdims, where=None),\n[RandArg((7, 8, 4), _f32), StaticArg(axis), StaticArg(keepdims)],\n@@ -1278,7 +1298,7 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n[\n- _make_harness(\"jnp_mean\",\n+ _make_harness(\"mean\",\nf\"axis={axis}_keepdims={keepdims}_where=Some\",\nlambda x, where, axis, keepdims: jnp.mean(x, axis=axis, keepdims=keepdims, where=where),\n[RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), np.bool_), StaticArg(axis), StaticArg(keepdims)],\n@@ -1286,44 +1306,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\nfor keepdims in [False, True]\nfor axis in [None, (0,), (0, 1), (1,)]\n],\n- _make_harness(\"jnp_ones\", \"\",\n+ _make_harness(\"ones\", \"\",\nlambda x: jnp.ones(x.shape, dtype=_f32),\n[RandArg((3, 2, 4), _f32)],\npoly_axes=[0]),\n- _make_harness(\"jnp_squeeze\", \"axis=None\",\n- jnp.squeeze,\n- [RandArg((5,), _f32), StaticArg(())],\n- poly_axes=[0]),\n- _make_harness(\"jnp_squeeze\", \"axis=1\",\n- jnp.squeeze,\n- [RandArg((4, 1), _f32), StaticArg((1,))],\n- poly_axes=[0]),\n- _make_harness(\"jnp_take\", \"\",\n- lambda a, i: jnp.take(a, i, axis=1),\n- [RandArg((3, 4, 5), _f32), np.array([1, 2], np.int32)],\n- poly_axes=[0, None], enable_and_diable_xla=True),\n- [\n- _make_harness(\"jnp_var\",\n- f\"axis={axis}_keepdims={keepdims}_where=None\",\n- lambda x, axis, keepdims: jnp.var(x, axis=axis, keepdims=keepdims, where=None),\n- [RandArg((7, 8, 4), _f32), StaticArg(axis), StaticArg(keepdims)],\n- poly_axes=[0])\n- for keepdims in [False, True]\n- for axis in [None, (0,), (0, 1), (1,)]\n- ],\n- [\n- _make_harness(\"jnp_var\",\n- f\"axis={axis}_keepdims={keepdims}_where=Some\",\n- lambda x, where, axis, keepdims: jnp.var(x, axis=axis, keepdims=keepdims, where=where),\n- [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), np.bool_), StaticArg(axis), StaticArg(keepdims)],\n- poly_axes=[0, 0])\n- for keepdims in [False, True]\n- for axis in [None, (0,), (0, 1), (1,)]\n- ],\n- _make_harness(\"jnp_where\", \"\",\n- jnp.where,\n- [RandArg((2,), np.bool_), RandArg((), _f32), RandArg((2,), _f32)],\n- poly_axes=[0, None, 0]),\n_make_harness(\"pad\", \"\",\nlax.pad,\n[RandArg((3, 2, 5), _f32), np.float32(5.),\n@@ -1343,7 +1329,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((2,), np.uint32), RandArg((3, 8), _f32)],\npoly_axes=[None, 0]),\n# Works when the known dimensions are known to be even or odd.\n- # See the random_uniform_error test also.\n_make_harness(\"random_uniform\", \"even_1\",\nlambda key, a: jax.random.uniform(key, a.shape, dtype=_f32),\n[RandArg((2,), np.uint32), RandArg((3, 4), _f32)],\n@@ -1353,6 +1338,12 @@ _POLY_SHAPE_TEST_HARNESSES = [\ndtype=_f32),\n[RandArg((2,), np.uint32), RandArg((3, 5), _f32)],\npoly_axes=[None, 0]),\n+ _make_harness(\"random_uniform\", \"error_not_even\",\n+ lambda key, a: jax.random.uniform(key, a.shape, dtype=_f32),\n+ [RandArg((2,), np.uint32), RandArg((3, 5), _f32)],\n+ poly_axes=[None, 0],\n+ expect_error=(core.InconclusiveDimensionOperation,\n+ \"the product of the known dimensions must be even\")),\n# TODO(necula): not yet supported, but also unlikely to come up.\n# _make_harness(\"random_uniform\", \"odd\",\n# lambda key, a: jax.random.uniform(key, (2 * a.shape[0] + 1, a.shape[1]),\n@@ -1382,6 +1373,15 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: jnp.reshape(x, [2, -1]),\n[RandArg((3, 4, 5, 6, 7), _f32)],\npoly_axes=[(0, 2)]),\n+ _make_harness(\"reshape\", \"error\",\n+ lambda x: x.reshape([x.shape[0], -1, 3]),\n+ [RandArg((3, 2, 4), _f32)],\n+ poly_axes=[0],\n+ skip_jax_run=True,\n+ expect_error=(core.InconclusiveDimensionOperation,\n+ re.escape(\n+ \"Cannot divide evenly the sizes of shapes (b0, 2, 4) and (b0, -1, 3)\"))),\n+\n_make_harness(\"scatter_add\", \"\",\npartial(lax.scatter_add, indices_are_sorted=False, unique_indices=True),\n[RandArg((7, 4), _f32),\n@@ -1403,10 +1403,32 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: lax.slice(x, start_indices=(0, 1), limit_indices=(x.shape[0], 3)),\n[RandArg((7, 3), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"squeeze\", \"axis=None\",\n+ jnp.squeeze,\n+ [RandArg((5,), _f32), StaticArg(())],\n+ poly_axes=[0]),\n+ _make_harness(\"squeeze\", \"axis=1\",\n+ jnp.squeeze,\n+ [RandArg((4, 1), _f32), StaticArg((1,))],\n+ poly_axes=[0]),\n_make_harness(\"squeeze\", \"axis=1_2\",\njnp.squeeze,\n[RandArg((4, 1, 1), _f32), StaticArg((1, 2))],\npoly_axes=[0]),\n+\n+ _make_harness(\"squeeze\", \"error\",\n+ jnp.squeeze,\n+ [RandArg((3, 33), _f32), StaticArg(-1)],\n+ poly_axes=[(0, 1)],\n+ skip_jax_run=True,\n+ expect_error=(ValueError,\n+ re.escape(\n+ \"cannot select an axis to squeeze out which has size not equal to one, got shape=(b0, b1) and dimensions=(1,)\"))\n+ ),\n+ _make_harness(\"take\", \"\",\n+ lambda a, i: jnp.take(a, i, axis=1),\n+ [RandArg((3, 4, 5), _f32), np.array([1, 2], np.int32)],\n+ poly_axes=[0, None], enable_and_diable_xla=True),\n_make_harness(\"tile\", \"0\",\nlambda x: jnp.tile(x, (1, 2)),\n[RandArg((4, 3), _f32)],\n@@ -1416,6 +1438,28 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: jnp.tile(x, (1, x.shape[0])),\n[RandArg((4, 2), _f32)],\npoly_axes=[0]),\n+ [\n+ _make_harness(\"var\",\n+ f\"axis={axis}_keepdims={keepdims}_where=None\",\n+ lambda x, axis, keepdims: jnp.var(x, axis=axis, keepdims=keepdims, where=None),\n+ [RandArg((7, 8, 4), _f32), StaticArg(axis), StaticArg(keepdims)],\n+ poly_axes=[0])\n+ for keepdims in [False, True]\n+ for axis in [None, (0,), (0, 1), (1,)]\n+ ],\n+ [\n+ _make_harness(\"var\",\n+ f\"axis={axis}_keepdims={keepdims}_where=Some\",\n+ lambda x, where, axis, keepdims: jnp.var(x, axis=axis, keepdims=keepdims, where=where),\n+ [RandArg((7, 8, 4), _f32), RandArg((7, 8, 4), np.bool_), StaticArg(axis), StaticArg(keepdims)],\n+ poly_axes=[0, 0])\n+ for keepdims in [False, True]\n+ for axis in [None, (0,), (0, 1), (1,)]\n+ ],\n+ _make_harness(\"where\", \"\",\n+ jnp.where,\n+ [RandArg((2,), np.bool_), RandArg((), _f32), RandArg((2,), _f32)],\n+ poly_axes=[0, None, 0]),\n]\n### We add to the test harnesses some that are obtained from the\n@@ -1541,7 +1585,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"uniform_odd_poly_axes=[None, 0]\"\n+ #one_containing=\"reshape_error_poly_axes\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n@@ -1573,8 +1617,21 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\npolymorphic_shapes.append(arg_polymorphic_shapes)\ninput_signature.append(arg_tensorspec)\n+ skip_jax_run = harness.params[\"skip_jax_run\"]\n+ if not skip_jax_run:\nres_jax = harness.dyn_fun(*args)\n+\nenable_xla = harness.params.get(\"enable_xla\", True)\n+ expect_error_type, expect_error_regex = harness.params[\"expect_error\"]\n+ if expect_error_type is not None:\n+ with self.assertRaisesRegex(expect_error_type, expect_error_regex):\n+ f_tf = self.CheckShapePolymorphism(\n+ harness.dyn_fun,\n+ input_signature=input_signature,\n+ polymorphic_shapes=polymorphic_shapes,\n+ expected_output_signature=None,\n+ enable_xla=enable_xla)\n+ else:\nf_tf = self.CheckShapePolymorphism(\nharness.dyn_fun,\ninput_signature=input_signature,\n@@ -1582,10 +1639,11 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=None,\nenable_xla=enable_xla)\n- if harness.params[\"check_result\"]:\n+ if not skip_jax_run and expect_error_type is None and harness.params[\"check_result\"]:\ntol = harness.params[\"tol\"]\nself.assertAllClose(res_jax, f_tf(*args), atol=tol, rtol=tol)\n+\ndef test_vmap_while(self):\ndef cond_func(x): # x: f32[3]\nreturn jnp.sum(x) >= 0.\n@@ -1601,18 +1659,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nexpected_output_signature=tf.TensorSpec((None, 3), dtype=tf.float32)\n)\n- def test_reshape_error(self):\n-\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- re.escape(\n- \"Cannot divide evenly the sizes of shapes (batch, 2, 4) and (batch, -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=[PS(\"batch\", ...)],\n- expected_output_signature=tf.TensorSpec([None, 1]))\n-\ndef test_reshape_compiled(self):\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@@ -1646,51 +1692,6 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(res_jax, f_tf(x))\nself.assertFalse(traced) # We are not tracing again\n- def test_squeeze_error(self):\n-\n- with self.assertRaisesRegex(\n- ValueError,\n- re.escape(\"cannot select an axis to squeeze out which has size not equal to one, got shape=(b1, b2) and dimensions=(1,)\")):\n- # Trace with unknown dimension to squeeze\n- self.CheckShapePolymorphism(\n- lambda x: jnp.squeeze(x, axis=1),\n- input_signature=[tf.TensorSpec([None, None])],\n- polymorphic_shapes=[PS(\"b1\", \"b2\")],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- def test_einsum_multiple_contractions_error(self):\n-\n- with self.assertRaisesRegex(\n- ValueError,\n- \"Shape polymorphism is not yet supported for einsum with more than one contraction\"):\n- self.CheckShapePolymorphism(\n- lambda x, y, z: jnp.einsum(\"ab,bc,cd->ad\", x, y, z),\n- input_signature=[tf.TensorSpec([None, 2]),\n- tf.TensorSpec([2, 3]), tf.TensorSpec([3, 4])],\n- polymorphic_shapes=[\"(a, 2)\", \"(2, 3)\", \"(3, 4)\"],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- def test_einsum_incompatible_contractions_error(self):\n-\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- \"Dimension polynomial comparison 'b' == 'a' is inconclusive\"):\n- self.CheckShapePolymorphism(\n- lambda x, y: jnp.einsum(\"ab,bc->ac\", x, y),\n- input_signature=[tf.TensorSpec([2, None]),\n- tf.TensorSpec([None, 3])],\n- polymorphic_shapes=[\"(2, a)\", \"(b, 3)\"],\n- expected_output_signature=tf.TensorSpec([None]))\n-\n- def test_random_uniform_error(self):\n- with self.assertRaisesRegex(\n- core.InconclusiveDimensionOperation,\n- \"the product of the known dimensions must be even\"):\n- self.CheckShapePolymorphism(\n- lambda key, a: jax.random.uniform(key, a.shape, dtype=_f32),\n- input_signature=[tf.TensorSpec([2], tf.uint32),\n- tf.TensorSpec([None, 3], tf.float32)],\n- polymorphic_shapes=[None, \"b, ...\"])\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] More cleanup for shape polymorphism testing |
260,411 | 30.07.2021 13:35:21 | -10,800 | 6aecb3c3c6b52ee61f29e600b4ec4a570ba72555 | [jax2tf] enable multiple round-trips from JAX to TF | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/call_tf.py",
"new_path": "jax/experimental/jax2tf/call_tf.py",
"diff": "@@ -411,6 +411,7 @@ TfVal = jax2tf_internal.TfVal\ndef _jax2tf_call_tf(*args: TfVal,\ncallable_flat_tf: Callable,\n**_) -> TfVal:\n+ with jax2tf_internal.inside_call_tf():\nres_tf_flat = callable_flat_tf(*args)\nreturn res_tf_flat\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/call_tf_test.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for call_tf.\"\"\"\n-\nfrom functools import partial\nfrom typing import Callable, Dict, Tuple\nimport unittest\n@@ -45,12 +44,14 @@ def _maybe_jit(with_jit: bool, func: Callable) -> Callable:\nelse:\nreturn func\n+def _named_test(**kwargs):\n+ return dict(kwargs,\n+ testcase_name = \"_\".join([f\"{k}={kwargs[k]}\" for k in sorted(kwargs.keys())]))\n-parameterized_jit = parameterized.named_parameters(\n- dict(testcase_name=\"_jit\" if with_jit else \"\", with_jit=with_jit)\n+_parameterized_jit = parameterized.named_parameters(\n+ _named_test(with_jit=with_jit)\nfor with_jit in [True, False])\n-\nclass CallTfTest(tf_test_util.JaxToTfTestCase):\ndef setUp(self):\n@@ -61,7 +62,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\n_ = tf.add(1, 1)\nsuper().setUp()\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_scalar_arg(self, with_jit=True):\ndef f_tf(x):\nreturn tf.math.sin(x)\n@@ -69,19 +70,19 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(f_tf))(x)\nself.assertAllClose(jnp.sin(x), res)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_scalar_res(self, with_jit=True):\nx = 3.\nres = _maybe_jit(with_jit, jax2tf.call_tf(lambda x: 4.))(x)\nself.assertAllClose(4., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_numpy_arg(self, with_jit=True):\nx = np.ones((2, 3), dtype=np.float32)\nres = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\nself.assertAllClose(jnp.sin(x), res)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_numpy_res(self, with_jit=False):\nx = np.ones((2, 3))\nres = _maybe_jit(with_jit, jax2tf.call_tf(lambda _: x))(x)\n@@ -96,7 +97,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(x, res)\nself.assertTrue(np.shares_memory(x, res))\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_devicearray_arg(self, with_jit=False):\nx = jnp.ones((2, 3), dtype=np.float32)\nres = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\n@@ -112,7 +113,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(x, res)\nself.assertTrue(np.shares_memory(x, res))\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_eval_pytree(self, with_jit=True):\ndef fun_tf(x: Dict, y: Tuple) -> Tuple:\n@@ -158,7 +159,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nCallTfTest.call_tf_non_compileable):\njax.jit(f_jax)(x)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_control_flow(self, with_jit=True):\ndef times_5_tf(x):\n@@ -199,7 +200,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, fun_jax)(x)\nself.assertAllClose(dtype(2 * x + 3), res)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_bool(self, with_jit=False):\ndef fun_tf(x, y):\n@@ -211,7 +212,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(\nnp.array([True, False, False, False], dtype=np.bool_), res)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_x64_input(self, with_jit=True):\ndef f_tf(x):\nreturn tf.math.sin(x)\n@@ -221,7 +222,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres_jax = jnp.sin(x)\nself.assertAllClose(res_call_tf, res_jax)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_x64_output(self, with_jit=True):\ndef f_tf(x):\nreturn (tf.constant(3., tf.float64), x)\n@@ -234,7 +235,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres_call_tf_jit = jax.jit(jax2tf.call_tf(f_tf))(x)\nself.assertAllClose(res_call_tf_jit, res_jax)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_var_read(self, with_jit=True):\nif jtu.device_under_test() == \"gpu\":\nraise unittest.SkipTest(\"Test fails on GPU\")\n@@ -248,7 +249,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose(x * outer_var_array + 1., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_var_read_x64(self, with_jit=True):\nif jtu.device_under_test() == \"gpu\":\nraise unittest.SkipTest(\"Test fails on GPU\")\n@@ -278,7 +279,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertAllClose(tf_out, jax_out, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_var_write_error(self, with_jit=True):\nif with_jit:\nraise unittest.SkipTest(\"variable writes not yet working\")\n@@ -292,7 +293,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose(x * 4. + 1, res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_tensor_capture(self, with_jit=True):\nouter_tensor = tf.constant(3., dtype=np.float32)\n@@ -303,7 +304,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose(x * 3. + 1., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_tensor_capture_x64(self, with_jit=True):\nouter_tensor = tf.constant(3., dtype=np.float64)\n@@ -314,7 +315,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose(x * 3. * 3.14 + 1., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_value_capture(self, with_jit=True):\nouter_val = np.array(3., dtype=np.float32)\n@@ -325,7 +326,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose(x * 3. + 1., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_with_multiple_capture(self, with_jit=True):\nif jtu.device_under_test() == \"gpu\":\nraise unittest.SkipTest(\"Test fails on GPU\")\n@@ -341,13 +342,13 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nres = _maybe_jit(with_jit, jax2tf.call_tf(fun_tf))(x)\nself.assertAllClose((x * 3. + 4. + 2.) * 3. + 5., res, check_dtypes=False)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_grad(self, with_jit=False):\nx = np.float32(3.)\nres = _maybe_jit(with_jit, jax.grad(jax2tf.call_tf(tf.math.sin)))(x)\nself.assertAllClose(np.cos(x), res)\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_grad_pytree(self, with_jit=False):\ndef fun_tf(x: Dict, y: Tuple) -> Tuple:\n@@ -460,7 +461,7 @@ class CallTfTest(tf_test_util.JaxToTfTestCase):\nself.assertEqual(g_call_tf[0].dtype, dtypes.float0)\nself.assertAllClose(g_jax[1], g_call_tf[1])\n- @parameterized_jit\n+ @_parameterized_jit\ndef test_grad_custom(self, with_jit=False):\n@tf.custom_gradient\n@@ -951,5 +952,55 @@ class RoundTripToTfTest(tf_test_util.JaxToTfTestCase):\n\"call_tf cannot be applied to shape-polymorphic arguments\"):\nfun_tf_rt(x)\n+\n+ @parameterized.named_parameters(\n+ _named_test(f2_function=f2_function, f2_saved_model=f2_saved_model,\n+ f4_function=f4_function, f4_saved_model=f4_saved_model)\n+ for f2_function in [True, False]\n+ for f2_saved_model in [True, False]\n+ for f4_function in [True, False]\n+ for f4_saved_model in [True, False])\n+ def test_several_round_trips(self,\n+ f2_function=False, f2_saved_model=False,\n+ f4_function=False, f4_saved_model=False):\n+ x = np.array(.7, dtype=np.float32)\n+ # f(n)(x) = 2. * x^n\n+ def f(n):\n+ def fn(x):\n+ acc = np.array(2., dtype=x.dtype)\n+ for i in range(n):\n+ acc *= x\n+ return acc\n+ return fn\n+\n+ f2_tf = lambda x: x * jax2tf.convert(f(1))(x)\n+ if f2_function:\n+ f2_tf = tf.function(f2_tf, autograph=False)\n+ if f2_saved_model:\n+ f2_tf, _ = tf_test_util.SaveAndLoadFunction(f2_tf, input_args=[x])\n+\n+ self.assertAllClose(f(2)(x), f2_tf(x).numpy())\n+ _, (g_f2_ft,) = tf_test_util.ComputeTfValueAndGrad(f2_tf, [x])\n+ self.assertAllClose(jax.grad(f(2))(x), g_f2_ft.numpy())\n+\n+ f3_jax = lambda x: x * jax2tf.call_tf(f2_tf)(x)\n+ self.assertAllClose(f(3)(x), f3_jax(x))\n+ self.assertAllClose(f(3)(x), jax.jit(f3_jax)(x))\n+ self.assertAllClose(jax.grad(f(3))(x), jax.grad(f3_jax)(x))\n+\n+ f4_tf = lambda x: x * jax2tf.convert(f3_jax)(x)\n+ self.assertAllClose(f(4)(x), f4_tf(x).numpy())\n+ _, (g_f4_ft,) = tf_test_util.ComputeTfValueAndGrad(f4_tf, [x])\n+ self.assertAllClose(jax.grad(f(4))(x), g_f4_ft.numpy())\n+\n+ if f4_function:\n+ f4_tf = tf.function(f4_tf, autograph=False)\n+ if f4_saved_model:\n+ f4_tf, _ = tf_test_util.SaveAndLoadFunction(f4_tf, input_args=[x])\n+ self.assertAllClose(f(4)(x), f4_tf(x).numpy())\n+ _, (g_f4_ft,) = tf_test_util.ComputeTfValueAndGrad(f4_tf, [x])\n+ self.assertAllClose(jax.grad(f(4))(x), g_f4_ft.numpy())\n+\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] enable multiple round-trips from JAX to TF |
260,374 | 29.07.2021 17:12:15 | 0 | 5383e977d5c577771f9a1dc66aa9a663292647a2 | added debugging logs to compilation cache | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -16,6 +16,7 @@ import hashlib\nimport jax\nfrom jax.experimental.compilation_cache.file_system_cache import FileSystemCache\nfrom jax.lib import xla_client\n+from absl import logging\nfrom typing import Optional\n_cache = None\n@@ -28,6 +29,7 @@ def initialize_cache(path, max_cache_size_bytes=32 * 2**30):\nglobal _cache\nassert _cache == None, f\"The cache path has already been initialized to {_cache}\"\n_cache = FileSystemCache(path, max_cache_size_bytes)\n+ logging.warning(f\"Initialized persistent compilation cache at {path}\")\ndef get_executable(xla_computation, compile_options) -> Optional[xla_client.Executable]:\n\"\"\"Returns the cached executable if present, or None otherwise.\"\"\"\n@@ -67,9 +69,17 @@ def get_cache_key(xla_computation, compile_options) -> str:\n\"\"\"\nhash_obj = hashlib.sha256()\nhash_obj.update(xla_computation.as_serialized_hlo_module_proto())\n+ if logging.vlog_is_on(1):\n+ logging.vlog(1, f\"get_cache_key hash after serializing computation: {hash_obj.digest().hex()}\")\n_hash_compile_options(hash_obj, compile_options)\n+ if logging.vlog_is_on(1):\n+ logging.vlog(1, f\"get_cache_key hash after serializing compile_options: {hash_obj.digest().hex()}\")\nhash_obj.update(bytes(jax.lib.version))\n+ if logging.vlog_is_on(1):\n+ logging.vlog(1, f\"get_cache_key hash after serializing jax_lib version: {hash_obj.digest().hex()}\")\n_hash_platform(hash_obj, jax.lib.xla_bridge.get_backend())\n+ if logging.vlog_is_on(1):\n+ logging.vlog(1, f\"get_cache_key hash after serializing the backend: {hash_obj.digest().hex()}\")\nreturn hash_obj.digest().hex()\ndef _hash_compile_options(hash_obj, compile_options_obj):\n"
}
] | Python | Apache License 2.0 | google/jax | added debugging logs to compilation cache |
260,456 | 30.07.2021 19:17:21 | 0 | b44d35664c94a42f7145b73f27619e21dbc678cf | change skip_on_devices to handle device tags | [
{
"change_type": "MODIFY",
"old_path": "jax/test_util.py",
"new_path": "jax/test_util.py",
"diff": "@@ -423,16 +423,32 @@ def skip_if_unsupported_type(dtype):\nraise unittest.SkipTest(\nf\"Type {dtype.name} not supported on {device_under_test()}\")\n+def is_device_rocm():\n+ return xla_bridge.get_backend().platform_version.startswith('rocm')\n+\n+def is_device_cuda():\n+ return xla_bridge.get_backend().platform_version.startswith('cuda')\n+\n+def _get_device_tags():\n+ \"\"\"returns a set of tags definded for the device under test\"\"\"\n+ if is_device_rocm():\n+ device_tags = set([device_under_test(), \"rocm\"])\n+ elif is_device_cuda():\n+ device_tags = set([device_under_test(), \"cuda\"])\n+ else:\n+ device_tags = set([device_under_test()])\n+ return device_tags\n+\ndef skip_on_devices(*disabled_devices):\n\"\"\"A decorator for test methods to skip the test on certain devices.\"\"\"\ndef skip(test_method):\n@functools.wraps(test_method)\ndef test_method_wrapper(self, *args, **kwargs):\n- device = device_under_test()\n- if device in disabled_devices:\n+ device_tags = _get_device_tags()\n+ if device_tags & set(disabled_devices):\ntest_name = getattr(test_method, '__name__', '[unknown test]')\nraise unittest.SkipTest(\n- f\"{test_name} not supported on {device.upper()}.\")\n+ f\"{test_name} not supported on device with tags {device_tags}.\")\nreturn test_method(self, *args, **kwargs)\nreturn test_method_wrapper\nreturn skip\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/fft_test.py",
"new_path": "tests/fft_test.py",
"diff": "@@ -105,6 +105,7 @@ class FftTest(jtu.JaxTestCase):\nfor shape in [(10,), (10, 10), (9,), (2, 3, 4), (2, 3, 4, 5)]\nfor axes in _get_fftn_test_axes(shape)\nfor s in _get_fftn_test_s(shape, axes)))\n+ @jtu.skip_on_devices(\"rocm\")\ndef testFftn(self, inverse, real, shape, dtype, axes, s):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\n@@ -123,6 +124,7 @@ class FftTest(jtu.JaxTestCase):\ntol = 0.15\njtu.check_grads(jnp_fn, args_maker(), order=2, atol=tol, rtol=tol)\n+ @jtu.skip_on_devices(\"rocm\")\ndef testIrfftTranspose(self):\n# regression test for https://github.com/google/jax/issues/6223\ndef build_matrix(linear_func, size):\n@@ -182,6 +184,7 @@ class FftTest(jtu.JaxTestCase):\nfor shape in [(10,)]\nfor n in [None, 1, 7, 13, 20]\nfor axis in [-1, 0]))\n+ @jtu.skip_on_devices(\"rocm\")\ndef testFft(self, inverse, real, hermitian, shape, dtype, n, axis):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\n@@ -246,6 +249,7 @@ class FftTest(jtu.JaxTestCase):\nfor dtype in (real_dtypes if real and not inverse else all_dtypes)\nfor shape in [(16, 8, 4, 8), (16, 8, 4, 8, 4)]\nfor axes in [(-2, -1), (0, 1), (1, 3), (-1, 2)]))\n+ @jtu.skip_on_devices(\"rocm\")\ndef testFft2(self, inverse, real, shape, dtype, axes):\nrng = jtu.rand_default(self.rng())\nargs_maker = lambda: (rng(shape, dtype),)\n"
}
] | Python | Apache License 2.0 | google/jax | change skip_on_devices to handle device tags |
260,411 | 31.07.2021 10:24:36 | -10,800 | 022d2d6d6e592f60f8821cef47c43802c8d8cbe8 | [jax2tf] Update the limitations
To account for progress on XLA and 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-07-05* (YYYY-MM-DD)\n+*Last generated on: 2021-07-31* (YYYY-MM-DD)\n## Supported data types for primitives\n-We use a set of 2667 test harnesses to test\n-the implementation of 121 numeric JAX primitives.\n+We use a set of 2809 test harnesses to test\n+the implementation of 126 numeric JAX primitives.\nWe consider a JAX primitive supported for a particular data\ntype if it is supported on at least one device type.\nThe following table shows the dtypes at which primitives\n@@ -46,8 +46,8 @@ be updated.\n| add | 16 | inexact, integer | bool |\n| add_any | 14 | inexact, integer | bool |\n| and | 11 | bool, integer | inexact |\n-| argmax | 22 | bool, floating, integer | complex |\n-| argmin | 22 | bool, floating, integer | complex |\n+| argmax | 64 | bool, floating, integer | complex |\n+| argmin | 64 | bool, floating, integer | complex |\n| asin | 6 | inexact | bool, integer |\n| asinh | 6 | inexact | bool, integer |\n| atan | 6 | inexact | bool, integer |\n@@ -56,8 +56,8 @@ be updated.\n| bessel_i0e | 4 | floating | bool, complex, integer |\n| bessel_i1e | 4 | floating | bool, complex, integer |\n| bitcast_convert_type | 41 | all | |\n-| broadcast | 17 | all | |\n| broadcast_in_dim | 19 | all | |\n+| cbrt | 4 | floating | bool, complex, integer |\n| ceil | 4 | floating | bool, complex, integer |\n| cholesky | 30 | inexact | bool, integer |\n| clamp | 20 | all | |\n@@ -115,9 +115,13 @@ be updated.\n| population_count | 8 | integer | bool, inexact |\n| pow | 10 | inexact | bool, integer |\n| qr | 60 | inexact | bool, integer |\n+| random_categorical | 12 | floating | bool, complex, integer |\n| random_gamma | 4 | float32, float64 | bfloat16, bool, complex, float16, integer |\n+| random_randint | 12 | signed | bool, inexact, unsigned |\n| random_split | 5 | uint32 | all |\n+| random_uniform | 12 | floating | bool, complex, integer |\n| real | 2 | complex | bool, floating, integer |\n+| reduce | 33 | all | |\n| reduce_and | 1 | bool | inexact, integer |\n| reduce_max | 15 | all | |\n| reduce_min | 15 | all | |\n@@ -159,6 +163,7 @@ be updated.\n| top_k | 15 | bool, floating, integer | complex |\n| transpose | 17 | all | |\n| triangular_solve | 26 | inexact | bool, integer |\n+| tridiagonal_solve | 2 | float32, float64 | bfloat16, bool, complex, float16, integer |\n| xor | 11 | bool, integer | inexact |\n| zeros_like | 15 | all | |\n@@ -197,8 +202,6 @@ and search for \"limitation\".\n|lu|unimplemented|bfloat16, float16|cpu, gpu, tpu|\n|qr|unimplemented|bfloat16, float16|cpu, gpu|\n|scatter_add|unimplemented|bool|cpu, gpu, tpu|\n-|scatter_max|unimplemented|complex64|tpu|\n-|scatter_min|unimplemented|complex64|tpu|\n|scatter_mul|unimplemented|bool|cpu, gpu, tpu|\n|select_and_scatter_add|works only for 2 or more inactive dimensions|all|tpu|\n|svd|complex not implemented. Works in JAX for CPU and GPU with custom kernels|complex|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-07-05*\n+*Last generated on (YYYY-MM-DD): 2021-07-31*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -64,8 +64,6 @@ More detailed information can be found in the\n| bessel_i0e | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| bessel_i1e | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| cholesky | TF test skipped: Not implemented in JAX: unimplemented | float16 | cpu, gpu | compiled, eager, graph |\n-| cholesky | TF error: function not compilable | complex | cpu, gpu | compiled |\n-| cholesky | TF error: op not defined for dtype | complex | tpu | compiled, graph |\n| clamp | TF test skipped: Not implemented in JAX: unimplemented | bool, complex | cpu, gpu, tpu | compiled, eager, graph |\n| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type not implemented for integers | int16, int32, int8 | gpu | compiled, eager, graph |\n| conv_general_dilated | TF test skipped: Not implemented in JAX: preferred_element_type=c128 not implemented | complex64 | tpu | compiled, eager, graph |\n@@ -74,7 +72,7 @@ More detailed information can be found in the\n| conv_general_dilated | TF error: jax2tf BUG: batch_group_count > 1 not yet converted | all | cpu, gpu, tpu | compiled, eager, graph |\n| digamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| div | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n-| dot_general | TF error: Numeric comparision disabled: Non-deterministic NaN for dot_general with preferred_element_type on GPU (b/189287598) | bfloat16, complex64, float16, float32 | gpu | compiled, eager, graph |\n+| dot_general | TF error: Numeric comparison disabled: Non-deterministic NaN for dot_general with preferred_element_type on GPU (b/189287598) | bfloat16, complex64, float16, float32 | gpu | compiled, eager, graph |\n| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=c128 not implemented | complex64 | tpu | compiled, eager, graph |\n| dot_general | TF test skipped: Not implemented in JAX: preferred_element_type=i64 not implemented | int16, int32, int8 | tpu | compiled, eager, graph |\n| dot_general | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n@@ -83,7 +81,6 @@ 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: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n-| eigh | TF test skipped: TF error: XLA lowering bug | complex | gpu | 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@@ -94,7 +91,6 @@ More detailed information can be found in the\n| integer_pow | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu | graph |\n| lgamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| lu | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n-| lu | TF error: op not defined for dtype | complex64 | tpu | compiled, eager, graph |\n| nextafter | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, 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@@ -104,18 +100,13 @@ More detailed information can be found in the\n| rem | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n| round | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| scatter_add | TF test skipped: Not implemented in JAX: unimplemented | bool | cpu, gpu, tpu | compiled, eager, graph |\n-| scatter_add | TF error: op not defined for dtype | complex64 | tpu | compiled, eager, graph |\n-| scatter_max | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n-| scatter_min | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n| scatter_mul | TF test skipped: Not implemented in JAX: unimplemented | bool | cpu, gpu, tpu | compiled, eager, graph |\n-| scatter_mul | TF error: op not defined for dtype | complex64 | tpu | compiled, eager, graph |\n| select_and_gather_add | TF error: jax2tf unimplemented for 64-bit inputs because the current implementation relies on packing two values into a single value. This can be fixed by using a variadic XlaReduceWindow, when available | float64 | cpu, gpu | compiled, eager, graph |\n| select_and_scatter_add | TF test skipped: Not implemented in JAX: works only for 2 or more inactive dimensions | all | tpu | compiled, eager, graph |\n| svd | TF test skipped: Not implemented in JAX: complex not implemented. Works in JAX for CPU and GPU with custom kernels | complex | tpu | compiled, eager, graph |\n| svd | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n| svd | TF error: function not compilable. Implemented using `tf.linalg.svd` and `tf.linalg.adjoint` | complex | cpu, gpu | compiled |\n| svd | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n-| top_k | TF error: op not defined for dtype | int64, uint64 | cpu, gpu | compiled |\n| triangular_solve | TF test skipped: Not implemented in JAX: unimplemented | float16 | gpu | compiled, eager, graph |\n| triangular_solve | TF error: op not defined for dtype | bfloat16 | cpu, gpu, tpu | compiled, eager, graph |\n| triangular_solve | TF error: op not defined for dtype | float16 | 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": "@@ -254,12 +254,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\njnp.tril(result_jax), result_tf, atol=tol, err_msg=err_msg)\nreturn [\n- # See https://github.com/google/jax/pull/3775#issuecomment-659407824;\n- Jax2TfLimitation(\n- \"function not compilable\",\n- dtypes=[np.complex64, np.complex128],\n- devices=(\"cpu\", \"gpu\"),\n- modes=\"compiled\"),\n# TODO: very high tolerance\ncustom_numeric(\ndtypes=[np.float32, np.complex64],\n@@ -812,7 +806,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nerr_msg=err_msg)\nreturn [\n- missing_tf_kernel(dtypes=[np.complex64], devices=\"tpu\"),\ncustom_numeric(\ndtypes=[np.float32, np.complex64], devices=\"tpu\", tol=0.1),\ncustom_numeric(\n@@ -937,21 +930,11 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef scatter_add(cls, harness):\n- return [\n- missing_tf_kernel(\n- dtypes=[np.complex64],\n- devices=\"tpu\",\n- )\n- ]\n+ return []\n@classmethod\ndef scatter_mul(cls, harness):\n- return [\n- missing_tf_kernel(\n- dtypes=[np.complex64],\n- devices=\"tpu\",\n- ),\n- ]\n+ return []\n@classmethod\ndef select_and_gather_add(cls, harness):\n@@ -1067,10 +1050,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nfirst_arr_jax[~mask_jax], first_arr_tf[~mask_tf], err_msg=err_msg)\nreturn [\n- missing_tf_kernel(\n- dtypes=[np.uint64, np.int64],\n- devices=(\"cpu\", \"gpu\"),\n- modes=\"compiled\"),\ncustom_numeric(\ndtypes=[np.float16, dtypes.bfloat16, np.float32, np.float64],\ncustom_assert=custom_assert,\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"new_path": "jax/experimental/jax2tf/tests/primitive_harness.py",
"diff": "@@ -1211,11 +1211,6 @@ def _make_scatter_harness(name,\nStaticArg(dimension_numbers)\n],\njax_unimplemented=[\n- Limitation(\n- \"unimplemented\",\n- devices=\"tpu\",\n- dtypes=np.complex64,\n- enabled=(f_lax in [lax.scatter_max, lax.scatter_min])),\nLimitation(\n\"unimplemented\",\ndtypes=np.bool_,\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Update the limitations
To account for progress on XLA and TF |
260,578 | 01.08.2021 08:53:12 | 25,200 | 790b8e81871d589504885f9886c6020de1108d86 | Use separate variable names so that we don't get buildifier warnings | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -24,11 +24,14 @@ load(\"//third_party/pocketfft:workspace.bzl\", pocketfft = \"repo\")\npocketfft()\n# Initialize TensorFlow's external dependencies.\n-load(\"@org_tensorflow//tensorflow:workspace3.bzl\", \"workspace\")\n-workspace()\n-load(\"@org_tensorflow//tensorflow:workspace2.bzl\", \"workspace\")\n-workspace()\n-load(\"@org_tensorflow//tensorflow:workspace1.bzl\", \"workspace\")\n-workspace()\n-load(\"@org_tensorflow//tensorflow:workspace0.bzl\", \"workspace\")\n-workspace()\n+load(\"@org_tensorflow//tensorflow:workspace3.bzl\", \"tf_workspace3\")\n+tf_workspace3()\n+\n+load(\"@org_tensorflow//tensorflow:workspace2.bzl\", \"tf_workspace2\")\n+tf_workspace2()\n+\n+load(\"@org_tensorflow//tensorflow:workspace1.bzl\", \"tf_workspace1\")\n+tf_workspace1()\n+\n+load(\"@org_tensorflow//tensorflow:workspace0.bzl\", \"tf_workspace0\")\n+tf_workspace0()\n"
}
] | Python | Apache License 2.0 | google/jax | Use separate variable names so that we don't get buildifier warnings |
260,499 | 30.07.2021 09:33:34 | -3,600 | 69fcc0c20d9508596f506dbb4129d8ef58028e5a | Abstracts into a separate function to evaluation of a single jaxpr equation. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -316,22 +316,8 @@ def traverse_jaxpr_params(f, params):\nif type(p) in (Jaxpr, ClosedJaxpr)}\n-def eval_jaxpr(jaxpr: Jaxpr, consts, *args):\n- def read(v):\n- if type(v) is Literal:\n- return v.val\n- else:\n- return env[v]\n-\n- def write(v, val):\n- env[v] = val\n-\n- env: Dict[Var, Any] = {}\n- write(unitvar, unit)\n- map(write, jaxpr.constvars, consts)\n- map(write, jaxpr.invars, args)\n- for eqn in jaxpr.eqns:\n- in_vals = map(read, eqn.invars)\n+def eval_jaxpr_eqn(eqn, in_vals):\n+ \"\"\"Evaluates the jaxpr equation with the provided input values.\"\"\"\ncall_jaxpr, params = extract_call_jaxpr(eqn.primitive, eqn.params)\nif call_jaxpr:\nsubfuns = [lu.wrap_init(partial(eval_jaxpr, call_jaxpr, ()))]\n@@ -347,7 +333,25 @@ def eval_jaxpr(jaxpr: Jaxpr, consts, *args):\nelse:\nbind_params = params\nwith source_info_util.user_context(eqn.source_info):\n- ans = eqn.primitive.bind(*(subfuns + in_vals), **bind_params)\n+ return eqn.primitive.bind(*(subfuns + in_vals), **bind_params)\n+\n+\n+def eval_jaxpr(jaxpr: Jaxpr, consts, *args):\n+ def read(v):\n+ if type(v) is Literal:\n+ return v.val\n+ else:\n+ return env[v]\n+\n+ def write(v, val):\n+ env[v] = val\n+\n+ env: Dict[Var, Any] = {}\n+ write(unitvar, unit)\n+ map(write, jaxpr.constvars, consts)\n+ map(write, jaxpr.invars, args)\n+ for eqn in jaxpr.eqns:\n+ ans = eval_jaxpr_eqn(eqn, map(read, eqn.invars))\nif eqn.primitive.multiple_results:\nmap(write, eqn.outvars, ans)\nelse:\n"
}
] | Python | Apache License 2.0 | google/jax | Abstracts into a separate function to evaluation of a single jaxpr equation. |
260,578 | 01.08.2021 20:13:02 | 25,200 | ca6465dded5e312d29bf7e7a0ffb855b4e31e2d5 | Add the changes suggested | [
{
"change_type": "MODIFY",
"old_path": "docs/async_dispatch.rst",
"new_path": "docs/async_dispatch.rst",
"diff": "@@ -10,8 +10,8 @@ program:\n>>> import jax.numpy as jnp\n>>> from jax import random\n>>> x = random.uniform(random.PRNGKey(0), (1000, 1000))\n->>> # Printing the result or repr(result) or str(result) will block until the\n->>> # value is ready. That's why the value is present in the output below.\n+>>> # Printing the result (i.e. evaluating `repr(result)` or `str(result)`)\n+>>> # will block until the value is ready.\n>>> jnp.dot(x, x) + 3. # doctest: +SKIP\nDeviceArray([[258.01971436, 249.64862061, 257.13372803, ...,\n236.67948914, 250.68939209, 241.36853027],\n"
}
] | Python | Apache License 2.0 | google/jax | Add the changes suggested |
260,578 | 02.08.2021 18:27:27 | 25,200 | 2f6f78891695be45476a2dd1295421083a3893c8 | Fix the timer->timer_secs typo | [
{
"change_type": "MODIFY",
"old_path": "jax/lib/xla_bridge.py",
"new_path": "jax/lib/xla_bridge.py",
"diff": "@@ -148,9 +148,10 @@ def _make_tpu_driver_client():\ndef tpu_client_timer_callback(timer_secs: float):\ndef _log_warning():\nwarnings.warn(\n- (f'TPU backend initialization is taking more than {timer_secs} seconds. '\n+ f'TPU backend initialization is taking more than {timer_secs} seconds. '\n'Did you run your code on all TPU hosts? '\n- 'See https://jax.readthedocs.io/en/latest/multi_process.html for more information.'))\n+ 'See https://jax.readthedocs.io/en/latest/multi_process.html '\n+ 'for more information.')\n# Will log a warning after `timer_secs`.\nt = threading.Timer(timer_secs, _log_warning)\n@@ -189,8 +190,8 @@ register_backend_factory('tpu_driver', _make_tpu_driver_client,\npriority=100)\nregister_backend_factory('gpu', xla_client.make_gpu_client,\npriority=200)\n-register_backend_factory('tpu', partial(tpu_client_timer_callback, timer=60.0),\n- priority=300)\n+register_backend_factory(\n+ 'tpu', partial(tpu_client_timer_callback, timer_secs=60.0), priority=300)\n_default_backend = None\n_backends = None\n"
}
] | Python | Apache License 2.0 | google/jax | Fix the timer->timer_secs typo |
260,411 | 03.08.2021 09:12:04 | -10,800 | 0c1a37ce33514f24d79bcfdf6d8559bf38b16287 | [jax2tf] Add shape polymorphism support for jnp.eye | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1640,16 +1640,14 @@ def broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n\"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\n- N, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n- bool_eye = eq(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n- broadcasted_iota(np.int32, (N, M), 1))\n+ bool_eye = eq(add(broadcasted_iota(np.int32, shape, 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, shape, 1))\nreturn convert_element_type_p.bind(bool_eye, new_dtype=dtype, weak_type=False)\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n\"\"\"This utility function exists for creating Kronecker delta arrays.\"\"\"\n- shape = tuple(map(int, shape))\naxes = tuple(map(int, axes))\ndtype = dtypes.canonicalize_dtype(dtype)\nbase_shape = tuple(np.take(shape, axes)) # type: ignore[arg-type]\n@@ -1662,11 +1660,10 @@ def _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n\"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\"\"\"\n- N, M = tuple(map(int, shape))\noffset = int(offset)\ndtype = dtypes.canonicalize_dtype(dtype)\n- bool_tri = ge(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n- broadcasted_iota(np.int32, (N, M), 1))\n+ bool_tri = ge(add(broadcasted_iota(np.int32, shape, 0), np.int32(offset)),\n+ broadcasted_iota(np.int32, shape, 1))\nreturn convert_element_type_p.bind(bool_tri, new_dtype=dtype, weak_type=False)\ndef stop_gradient(x):\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/_src/numpy/lax_numpy.py",
"new_path": "jax/_src/numpy/lax_numpy.py",
"diff": "@@ -3176,9 +3176,8 @@ empty = zeros\ndef eye(N, M=None, k=0, dtype=None):\nlax._check_user_dtype_supported(dtype, \"eye\")\ndtype = float_ if dtype is None else dtype\n- N = core.concrete_or_error(operator.index, N, \"'N' argument of jnp.eye()\")\n- M = N if M is None else core.concrete_or_error(\n- operator.index, M, \"'M' argument of jnp.eye()\")\n+ N = core.canonicalize_dim(N, \"'N' argument of jnp.eye()\")\n+ M = N if M is None else core.canonicalize_dim(M, \"'M' argument of jnp.eye()\")\nif N < 0 or M < 0:\nraise ValueError(f\"negative dimensions are not allowed, got {N} and {M}\")\nk = operator.index(k)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1415,29 +1415,42 @@ def _canonicalize_dimension(dim: DimSize) -> DimSize:\nelse:\nreturn operator.index(dim)\n-def canonicalize_shape(shape: Shape) -> Shape:\n+def canonicalize_shape(shape: Shape, context: str=\"\") -> Shape:\n\"\"\"Canonicalizes and checks for errors in a user-provided shape value.\nArgs:\nshape: a Python value that represents a shape.\nReturns:\n- A tuple of integers.\n+ A tuple of canonical dimension values.\n\"\"\"\ntry:\nreturn tuple(map(_canonicalize_dimension, shape))\nexcept TypeError:\npass\n- raise _invalid_shape_error(shape)\n+ raise _invalid_shape_error(shape, context)\n-def _invalid_shape_error(shape: Shape):\n+def canonicalize_dim(d: DimSize, context: str=\"\") -> DimSize:\n+ \"\"\"Canonicalizes and checks for errors in a user-provided shape dimension value.\n+\n+ Args:\n+ f: a Python value that represents a dimension.\n+\n+ Returns:\n+ A canonical dimension value.\n+ \"\"\"\n+ return canonicalize_shape((d,), context)[0]\n+\n+def _invalid_shape_error(shape: Shape, context: str=\"\"):\nmsg = (\"Shapes must be 1D sequences of concrete values of integer type, \"\n- \"got {}.\")\n+ f\"got {shape}.\")\n+ if context:\n+ msg += f\" {context}.\"\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- return TypeError(msg.format(shape))\n+ return TypeError(msg)\n# ------------------- Named 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": "@@ -1163,6 +1163,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: lax_control_flow.cummax(x, axis=1, reverse=False),\n[RandArg((3, 4, 5), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"delta\", \"0\",\n+ lambda x: lax._delta(_f32, x.shape, axes=(0, 1)),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n_make_harness(\"dot_general\", \"\",\nlambda lhs, rhs: lax.dot_general(lhs, rhs,\ndimension_numbers=(((2,), (1,)), ((0,), (0,)))),\n@@ -1264,7 +1268,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\npoly_axes=[1, (0, 1)],\nexpect_error=(core.InconclusiveDimensionOperation,\n\"Dimension polynomial comparison 'b1' == 'b0' is inconclusive\")),\n-\n+ _make_harness(\"eye\", \"N=poly_M=None\",\n+ lambda x: jnp.eye(x.shape[0]),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"eye\", \"N=poly_M=poly\",\n+ lambda x: jnp.eye(x.shape[0], M=x.shape[0] + 2),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n# operand is non-poly, index is poly\n_make_harness(\"getitem\", \"op=static_idx=poly\",\nlambda a, i: a[i],\n@@ -1430,7 +1441,6 @@ _POLY_SHAPE_TEST_HARNESSES = [\njnp.squeeze,\n[RandArg((4, 1, 1), _f32), StaticArg((1, 2))],\npoly_axes=[0]),\n-\n_make_harness(\"squeeze\", \"error\",\njnp.squeeze,\n[RandArg((3, 33), _f32), StaticArg(-1)],\n@@ -1453,6 +1463,14 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: jnp.tile(x, (1, x.shape[0])),\n[RandArg((4, 2), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"tri\", \"N=poly_M=None\",\n+ lambda x: jnp.tri(x.shape[0]),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"tri\", \"N=poly_M=poly\",\n+ lambda x: jnp.tri(x.shape[0], M=x.shape[0] + 2),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n[\n_make_harness(\"var\",\nf\"axis={axis}_keepdims={keepdims}_where=None\",\n@@ -1600,7 +1618,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# to parameterized below.\n@primitive_harness.parameterized(\n_flatten_harnesses(_POLY_SHAPE_TEST_HARNESSES),\n- #one_containing=\"broadcast_in_dim_poly_axes\"\n+ #one_containing=\"delta_0_poly_axes=[0]\"\n)\ndef test_prim(self, harness: Harness):\nargs = harness.dyn_args_maker(self.rng())\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Add shape polymorphism support for jnp.eye |
260,631 | 03.08.2021 09:25:00 | 25,200 | 0d8ef03a939264c2fefeed6b353c979abba02b09 | Added file system cache interface | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "jax/experimental/compilation_cache/cache_interface.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+from abc import ABC, abstractmethod\n+\n+class CacheInterface(ABC):\n+ @abstractmethod\n+ def get(self, key: str):\n+ pass\n+\n+ @abstractmethod\n+ def put(self, key: str, value: bytes):\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/compilation_cache.py",
"new_path": "jax/experimental/compilation_cache/compilation_cache.py",
"diff": "@@ -27,7 +27,7 @@ def initialize_cache(path, max_cache_size_bytes=32 * 2**30):\nmax_cache_sixe defaults to 32GiB.\n\"\"\"\nglobal _cache\n- assert _cache == None, f\"The cache path has already been initialized to {_cache}\"\n+ assert _cache == None, f\"The cache path has already been initialized to {_cache._path}\"\n_cache = FileSystemCache(path, max_cache_size_bytes)\nlogging.warning(f\"Initialized persistent compilation cache at {path}\")\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/compilation_cache/file_system_cache.py",
"new_path": "jax/experimental/compilation_cache/file_system_cache.py",
"diff": "# limitations under the License.\nimport os\n+from jax.experimental.compilation_cache.cache_interface import CacheInterface\nimport tempfile\nfrom typing import Optional\nimport warnings\n-class FileSystemCache:\n+class FileSystemCache(CacheInterface):\ndef __init__(self, path: str, max_cache_size_bytes=32 * 2**30):\n\"\"\"Sets up a cache at 'path'. Cached values may already be present.\"\"\"\n@@ -63,7 +64,6 @@ class FileSystemCache:\nif new_file_size >= self._max_cache_size_bytes:\nreturn False\n- #TODO(colemanliyah): Refactor this section so the whole directory doesn't need to be checked\nwhile new_file_size + self._get_cache_directory_size() > self._max_cache_size_bytes:\nlast_time = float('inf')\nfile_to_delete = None\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/interpreters/xla.py",
"new_path": "jax/interpreters/xla.py",
"diff": "@@ -70,6 +70,7 @@ def compile_or_get_cached(backend, computation, compile_options):\nif cc.is_initialized():\ncached_executable = cc.get_executable(computation, compile_options)\nif cached_executable is not None:\n+ logging.info('Persistent compilation cache hit')\nreturn cached_executable\nelse:\ncompiled = backend_compile(backend, computation, compile_options)\n"
}
] | Python | Apache License 2.0 | google/jax | Added file system cache interface
PiperOrigin-RevId: 388473011 |
260,578 | 03.08.2021 16:36:27 | 25,200 | 70e9708e0abf3a156371e840637029919bf6a1e0 | Fix the tolerance so that the tests will pass on GPU | [
{
"change_type": "MODIFY",
"old_path": "tests/lax_control_flow_test.py",
"new_path": "tests/lax_control_flow_test.py",
"diff": "@@ -1440,7 +1440,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nans = api.linearize(lambda c, as_: scan(f, c, as_), c, as_)[1](c, as_)\nexpected = api.linearize(lambda c, as_: scan_reference(f, c, as_), c, as_)[1](c, as_)\nself.assertAllClose(ans, expected, check_dtypes=False,\n- rtol={np.float64: 1e-14})\n+ rtol={np.float64: 1e-14, np.float32: 1e-4})\n@parameterized.named_parameters(\n{\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/masking_test.py",
"new_path": "tests/masking_test.py",
"diff": "@@ -383,7 +383,8 @@ class MaskingTest(jtu.JaxTestCase):\nexpected = grad(lambda W: rnn_reference(W, xs[:4], y))(W)\n- self.assertAllClose(ans, expected, check_dtypes=False)\n+ self.assertAllClose(ans, expected, check_dtypes=False,\n+ rtol={np.float64: 1e-14, np.float32: 1e-5})\ndef test_ragged_batched_rnn(self):\nn = 3\n"
}
] | Python | Apache License 2.0 | google/jax | Fix the tolerance so that the tests will pass on GPU |
260,411 | 04.08.2021 07:30:12 | -10,800 | f126cabe77c79de79bdaca9c5d7ee39c25e71a4e | [jax2tf] Fix shape polymorphism for broadcast_in_dim_transpose | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -3626,7 +3626,7 @@ def _broadcast_in_dim_shape_rule(operand, *, shape, broadcast_dimensions):\ndef _broadcast_in_dim_transpose_rule(ct, operand, *, shape, broadcast_dimensions):\nshape_in = operand.aval.shape\n- unit_dimensions = tuple(i for i, s in enumerate(shape_in) if s == 1)\n+ unit_dimensions = tuple(i for i, s in enumerate(shape_in) if core.symbolic_equal_dim(s, 1))\nbdims = tuple(np.delete(broadcast_dimensions, unit_dimensions))\naxes = tuple(np.delete(range(len(shape)), bdims))\nreturn [expand_dims(_reduce_sum(ct, axes), unit_dimensions)]\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": "@@ -1142,6 +1142,11 @@ _POLY_SHAPE_TEST_HARNESSES = [\nbroadcast_dimensions=(0, 2, 3)),\n[RandArg((3, 1, 4), _f32)],\npoly_axes=[(0, 2)]),\n+ _make_harness(\"broadcast_in_dim\", \"transpose\",\n+ jax.grad(lambda x: jnp.sum(lax.broadcast_in_dim(x, [2, x.shape[0], 5, x.shape[2], 4],\n+ broadcast_dimensions=(1, 2, 3)))),\n+ [RandArg((3, 1, 4), _f32)],\n+ poly_axes=[(0, 2)]),\n_make_harness(\"clamp\", \"\",\nlax.clamp,\n[RandArg((3, 4, 5), _f32), RandArg((3, 4, 5), _f32),\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Fix shape polymorphism for broadcast_in_dim_transpose |
260,578 | 04.08.2021 08:56:55 | 25,200 | e54efe73edafa32335306d9ee7779b1f82b28757 | Update commit for release | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -7,10 +7,10 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n# and update the sha256 with the result.\nhttp_archive(\nname = \"org_tensorflow\",\n- sha256 = \"77f1b73813553387c25e024cad73dfe3af13a8afc661eac86b40cd32fce63713\",\n- strip_prefix = \"tensorflow-234a51acec19b5728a07915e89eb8f01f4c80b06\",\n+ sha256 = \"7f8c738e967baf3f640769d59d0fbe32960790b856c529d35f046b8c6ebb597a\",\n+ strip_prefix = \"tensorflow-77d8c333405a080c57850c45531dbbf077b2bd0e\",\nurls = [\n- \"https://github.com/tensorflow/tensorflow/archive/234a51acec19b5728a07915e89eb8f01f4c80b06.tar.gz\",\n+ \"https://github.com/tensorflow/tensorflow/archive/77d8c333405a080c57850c45531dbbf077b2bd0e.tar.gz\",\n],\n)\n"
}
] | Python | Apache License 2.0 | google/jax | Update commit for release |
260,318 | 02.08.2021 19:01:13 | -10,800 | 0b1b812e3be92c1731ef84af2e5dbe8fe4ef03c4 | bugfix for sm3 optimizer
Ensure atleast 1d input. Optimizer should work now with scalar data.
fixes | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/optimizers.py",
"new_path": "jax/experimental/optimizers.py",
"diff": "@@ -478,22 +478,24 @@ def sm3(step_size, momentum=0.9):\nreturn x[tuple(idx)]\ndef init(x0):\n+ x_shape = x0.shape\n+ x0 = jnp.atleast_1d(x0)\nvs = [jnp.zeros(sz, dtype=x0.dtype) for sz in x0.shape]\n- return x0, jnp.zeros_like(x0), vs\n+ return x0, jnp.zeros_like(x0), vs, x_shape\ndef update(i, g, state):\n- x, m, vs = state\n+ x, m, vs, x_shape = state\nvs = [broadcast_into(g.ndim, v, i) for i, v in enumerate(vs)]\naccum = functools.reduce(jnp.minimum, vs) + jnp.square(g)\naccum_inv_sqrt = jnp.where(accum > 0, 1. / jnp.sqrt(accum), 0)\nm = (1. - momentum) * (g * accum_inv_sqrt) + momentum * m\nx = x - step_size(i) * m\nvs = [accum.max(splice(range(x.ndim), j, [])) for j in range(x.ndim)]\n- return x, m, vs\n+ return x, m, vs, x_shape\ndef get_params(state):\n- x, _, _ = state\n- return x\n+ x, _, _, x_shape = state\n+ return x.reshape(x_shape)\nreturn init, update, get_params\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/optimizers_test.py",
"new_path": "tests/optimizers_test.py",
"diff": "@@ -138,7 +138,14 @@ class OptimizerTests(jtu.JaxTestCase):\nx0 = (jnp.ones(2), jnp.ones((2, 2)))\nself._CheckOptimizer(optimizers.adagrad, loss, x0, num_iters, step_size)\n- def testSM3(self):\n+ def testSM3Scalar(self):\n+ def loss(x): return x**2\n+ x0 = jnp.array(1.)\n+ num_iters = 100\n+ step_size = 0.1\n+ self._CheckOptimizer(optimizers.sm3, loss, x0, num_iters, step_size)\n+\n+ def testSM3Vector(self):\ndef loss(xs):\nx1, x2 = xs\nreturn jnp.sum(x1 ** 2) + jnp.sum(x2 ** 2)\n"
}
] | Python | Apache License 2.0 | google/jax | bugfix for sm3 optimizer
Ensure atleast 1d input. Optimizer should work now with scalar data.
fixes #7421 |
260,411 | 04.08.2021 09:05:05 | -10,800 | b4e4acd88a57f038829604c9342326a46777ca20 | [jax2tf] Improve support for converting functions with kwargs
The previous conversion for kwargs did not work for AD. | [
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/jax2tf.py",
"new_path": "jax/experimental/jax2tf/jax2tf.py",
"diff": "@@ -36,7 +36,6 @@ from jax._src.lax import fft as lax_fft\nfrom jax._src.lax import lax\nfrom jax._src.lax import linalg as lax_linalg\nimport jax._src.random\n-from jax.api_util import flatten_fun\nfrom jax.experimental import maps\nfrom jax.experimental import pjit\nfrom jax.interpreters import ad\n@@ -254,6 +253,19 @@ def convert(fun: Callable,\nraise ValueError(\"convert must be used outside all JAX transformations.\" +\nf\"Trace state: {core.thread_local_state.trace_state.trace_stack}\")\n+ # We support kwargs by wrapping the function to take only positional arguments.\n+ # This is in part because jax.vjp does not support kwargs.\n+ nr_positional_args = len(args)\n+ kw_names = kwargs.keys()\n+ args = tuple(args) + tuple(kwargs[kw] for kw in kw_names)\n+\n+ def fun_no_kwargs(*args_and_kwargs):\n+ assert len(args_and_kwargs) == nr_positional_args + len(kw_names)\n+ args = args_and_kwargs[:nr_positional_args]\n+ kwargs = {kw: args_and_kwargs[nr_positional_args + i]\n+ for i, kw in enumerate(kw_names)}\n+ return fun(*args, **kwargs)\n+\ndef check_arg(a):\nif not _is_tfval(a):\nmsg = (f\"Argument {a} of type {type(a)} of jax2tf.convert(f) should \"\n@@ -261,9 +273,8 @@ def convert(fun: Callable,\nraise TypeError(msg)\ntree_util.tree_map(check_arg, args)\n- tree_util.tree_map(check_arg, list(kwargs.values()))\n- args_flat, in_tree = tree_util.tree_flatten((args, kwargs))\n+ args_flat, in_tree = tree_util.tree_flatten((args, {}))\n# May need to cast the arguments to have the type assumed by JAX\nargs_and_dtypes_flat = tuple(map(_tfval_to_tensor_jax_dtype, args_flat))\nargs_flat, arg_dtypes_flat = util.unzip2(args_and_dtypes_flat)\n@@ -277,19 +288,16 @@ def convert(fun: Callable,\nelif isinstance(polymorphic_shapes, (PolyShape, str)):\npolymorphic_shapes_ = (polymorphic_shapes,) * len(args) # type: ignore\nelse:\n- if not isinstance(polymorphic_shapes, Sequence) or len(args) != len(polymorphic_shapes):\n+ if not isinstance(polymorphic_shapes, Sequence) or len(polymorphic_shapes) != len(args) - len(kw_names):\nmsg = (\"polymorphic_shapes must be a sequence with the same length as the positional argument list \"\nf\"({len(args)}). Got polymorphic_shapes={repr(polymorphic_shapes)}.\")\nraise TypeError(msg)\n- polymorphic_shapes_ = tuple(polymorphic_shapes)\n+ polymorphic_shapes_ = tuple(polymorphic_shapes) + (None,) * len(kw_names)\n# Expand the polymorphic_shapes to match the argument pytree\npolymorphic_shapes_flat = tuple(api_util.flatten_axes(\"jax2tf.convert polymorphic_shapes\",\nin_tree.children()[0],\npolymorphic_shapes_))\n- # Add kwargs shapes.\n- polymorphic_shapes_flat = polymorphic_shapes_flat + tuple(\n- (None,) * (len(args_flat) - len(polymorphic_shapes_flat)))\n# Construct the abstract values for the flat arguments, possibly based on\n# the input shapes and the polymorphic_shapes if given. May create new shape\n@@ -300,9 +308,9 @@ def convert(fun: Callable,\n# This function may take pytrees of TfVals. We can only set\n# tf.custom_gradient on functions that take a flat argument list.\n- f = lu.wrap_init(fun)\n+ f = lu.wrap_init(fun_no_kwargs)\n# out_tree_thunk() will be the output tree, after running _interpret_fun.\n- flat_fun, out_tree_thunk = flatten_fun(f, in_tree)\n+ flat_fun, out_tree_thunk = api_util.flatten_fun(f, in_tree)\n# out_tree_thunk will be ready after _interpret_fun below.\n# Prepare the grad_fn for tf.custom_gradient.\n@@ -332,8 +340,9 @@ def convert(fun: Callable,\n# pullback may contain captured tracers from the conversion of the\n# main function. Those tracers will confuse the conversion of the\n# pullback. So, we construct the vjp anew and we convert it separately.\n- args_jax, _ = tree_util.tree_unflatten(in_tree, args_flat_jax)\n- _, pullback_jax = jax.vjp(fun, *args_jax)\n+ args_jax, kwargs_jax = tree_util.tree_unflatten(in_tree, args_flat_jax)\n+ assert not kwargs_jax\n+ _, pullback_jax = jax.vjp(fun_no_kwargs, *args_jax)\ndef fix_out_ct(out_ct_jax, out_ct_aval: core.ShapedArray):\n# If the primal function has outputs of integer or bool types, and if we are\n@@ -365,13 +374,13 @@ def convert(fun: Callable,\nreturn in_cts_fixed_flat_jax\n# TODO: enable higher-order gradients\n- # TODO: I think that this does not work with kwargs\nwith tf.name_scope(\"jax2tf_vjp\"):\nin_cts_flat = convert(\nfun_vjp_jax,\nwith_gradient=False,\npolymorphic_shapes=vjp_polymorphic_shapes)(args_flat, out_cts_flat)\n- in_cts, _ = tree_util.tree_unflatten(in_tree, in_cts_flat)\n+ in_cts, kwin_cts = tree_util.tree_unflatten(in_tree, in_cts_flat)\n+ assert not kwin_cts\nreturn in_cts\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py",
"diff": "@@ -745,15 +745,43 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\ntf_fn_array(np.array([3, 4, 5])), np.array([4.5, 10, 17.5],\njnp.bfloat16))\n- def test_kwargs(self):\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_kwargs(self, with_function=True):\n# Re: https://github.com/google/jax/issues/6791\ndef f_jax(*, x):\nreturn jnp.sum(x)\nf_tf = jax2tf.convert(f_jax)\n+ if with_function:\n+ f_tf = tf.function(f_tf)\nself.assertAllClose(\nf_tf(x=np.zeros(3, dtype=np.float32)), # Call with kwargs.\nnp.zeros((), dtype=np.float32))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ dict(testcase_name=f\"function={with_function}\",\n+ with_function=with_function)\n+ for with_function in [False, True]))\n+ def test_grad_kwargs(self, with_function=False):\n+ # Re: https://github.com/google/jax/issues/6791\n+ x = (np.zeros(3, dtype=np.float32),\n+ np.zeros(4, dtype=np.float32))\n+ def f_jax(*, x=(1., 2.)):\n+ return jnp.sum(x[0]) + 2. * jnp.sum(x[1])\n+ f_tf = jax2tf.convert(f_jax)\n+ if with_function:\n+ f_tf = tf.function(f_tf)\n+ xv = tf.nest.map_structure(tf.Variable, x)\n+ with tf.GradientTape() as tape:\n+ res = f_tf(x=xv)\n+ grad_tf = tape.gradient(res, xv)\n+ self.assertAllClose((np.full_like(x[0], fill_value=1.),\n+ np.full_like(x[1], fill_value=2.)),\n+ (grad_tf[0].numpy(), grad_tf[1].numpy()))\n+\n+\ndef test_enable_xla(self):\n# Tests that enable_xla flag is properly scoped to a conversion.\ndef fun(x):\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": "@@ -375,6 +375,18 @@ class ShapePolyTest(tf_test_util.JaxToTfTestCase):\ninput_signature=[tf.TensorSpec([1, None])],\npolymorphic_shapes=None)\n+ def test_kwargs(self):\n+ \"\"\"Test shape polymorphism for a function with kwargs.\"\"\"\n+\n+ x = np.ones(3, dtype=np.float32)\n+ y = np.ones(1, dtype=np.float32)\n+ def f_jax(x, *, y):\n+ return x + jnp.sin(y)\n+\n+ f_tf = jax2tf.convert(f_jax, polymorphic_shapes=[\"b, ...\"])\n+ f_tf(x, y=y)\n+\n+\ndef test_arg_avals(self):\n\"\"\"Test conversion of actual arguments to abstract values.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Improve support for converting functions with kwargs
The previous conversion for kwargs did not work for AD.
Bug: #6791 |
260,578 | 05.08.2021 09:45:39 | 25,200 | 86aaf80dce5f7bec2a34d2d6a187e558ca63cbfa | Use bazel --version | [
{
"change_type": "MODIFY",
"old_path": "build/build.py",
"new_path": "build/build.py",
"diff": "@@ -209,7 +209,7 @@ def get_bazel_path(bazel_path_flag):\ndef check_bazel_version(bazel_path):\ntry:\n- version_output = shell([bazel_path, \"--bazelrc=/dev/null\", \"version\"])\n+ version_output = shell([bazel_path, \"--version\"])\nexcept subprocess.CalledProcessError:\nreturn False\nmatch = re.search(\"Build label: *([0-9\\\\.]+)[^0-9\\\\.]\", version_output)\n"
}
] | Python | Apache License 2.0 | google/jax | Use bazel --version |
260,688 | 06.08.2021 10:54:50 | 25,200 | d6df61c3051e4f5861b8a3d26100147ae17a1046 | Fix the move constructor for Handle | [
{
"change_type": "MODIFY",
"old_path": "jaxlib/handle_pool.h",
"new_path": "jaxlib/handle_pool.h",
"diff": "@@ -47,15 +47,19 @@ class HandlePool {\nHandle(Handle&& other) {\npool_ = other.pool_;\nhandle_ = other.handle_;\n+ stream_ = other.stream_;\nother.pool_ = nullptr;\nother.handle_ = nullptr;\n+ other.stream_ = nullptr;\n}\nHandle& operator=(Handle const&) = delete;\nHandle& operator=(Handle&& other) {\npool_ = other.pool_;\nhandle_ = other.handle_;\n+ stream_ = other.stream_;\nother.pool_ = nullptr;\nother.handle_ = nullptr;\n+ other.stream_ = nullptr;\nreturn *this;\n}\n"
}
] | Python | Apache License 2.0 | google/jax | Fix the move constructor for Handle
PiperOrigin-RevId: 389212536 |
260,424 | 09.08.2021 17:23:05 | -3,600 | ddaef095bbef6571fd4f790e046db2b08bcfb964 | Reword UnexpectedTracerError and add visual dividers. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -440,31 +440,32 @@ class Trace:\ndef escaped_tracer_error(tracer, detail=None):\nnum_frames = FLAGS.jax_tracer_error_num_traceback_frames\n- msg = (\"Encountered an unexpected tracer. Perhaps this tracer escaped \"\n- \"through global state from a previously traced function.\\n\"\n- \"The functions being transformed should not save traced values to \"\n- \"global state.\")\n- if detail:\n- msg += \" Detail: {}.\".format(detail)\n- try:\n- line_info = tracer._line_info\n- except AttributeError:\n- pass\n- else:\n- msg += ('\\nThe tracer that caused this error was created on line '\n- f'{source_info_util.summarize(line_info)}. The tracer has'\n- f' shape {tracer.shape} and dtype {tracer.dtype}.\\n')\n- if num_frames > 0:\n- msg += (f'When the tracer was created, the final {num_frames} stack '\n- 'frames (most recent last) excluding JAX-internal frames were:\\n'\n- f'{source_info_util.summarize(line_info, num_frames=num_frames)}')\n+ msg = ('Encountered an unexpected tracer. A function transformed by JAX '\n+ 'had a side effect, allowing for a reference to an intermediate value '\n+ f'with shape {tracer.shape} and dtype {tracer.dtype} to escape.\\n'\n+ 'JAX transformations require that functions explicitly return their '\n+ 'outputs, and disallow saving intermediate values to global state.')\ndbg = getattr(tracer._trace.main, 'debug_info', None)\nif dbg is not None:\n- msg += ('\\nThe function being traced when the tracer leaked was '\n+ msg += ('\\nThe function being traced when the value leaked was '\nf'{dbg.func_src_info} traced for {dbg.traced_for}.')\n+ line_info = getattr(tracer, '_line_info', None)\n+ if line_info is not None:\n+ divider = '\\n' + '-'*30 + '\\n'\n+ msg += divider\n+ msg += ('The leaked intermediate value was created on line '\n+ f'{source_info_util.summarize(line_info)}. ')\n+ msg += divider\n+ if num_frames > 0:\n+ msg += (f'When the value was created, the final {num_frames} stack '\n+ 'frames (most recent last) excluding JAX-internal frames were:')\n+ msg += divider + source_info_util.summarize(\n+ line_info, num_frames=num_frames) + divider\nmsg += ('\\nTo catch the leak earlier, try setting the environment variable '\n'JAX_CHECK_TRACER_LEAKS or using the `jax.checking_leaks` context '\n'manager.')\n+ if detail:\n+ msg += f'Detail: {detail}'\nreturn UnexpectedTracerError(msg)\nclass Tracer:\n"
}
] | Python | Apache License 2.0 | google/jax | Reword UnexpectedTracerError and add visual dividers. |
260,411 | 10.08.2021 11:50:16 | -10,800 | d597a45499ac5d5694d42c6b1decb5f77c21e182 | [jax2tf] Small fixes for shape polymorphism.
* Fixed a few places where indexing required indices to be integer
constants. Use core._canonicalize_dimension in lieu of casting to integer.
Note that this may break code that passes floating point as indices.
* Relaxed einsum to work for multiple contractions.
* Added tests. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/lax/lax.py",
"new_path": "jax/_src/lax/lax.py",
"diff": "@@ -1947,7 +1947,7 @@ def slice_in_dim(operand: Array, start_index: Optional[int],\ndef index_in_dim(operand: Array, index: int, axis: int = 0,\nkeepdims: bool = True) -> Array:\n\"\"\"Convenience wrapper around slice to perform int indexing.\"\"\"\n- index, axis = int(index), int(axis)\n+ index, axis = _canonicalize_dimension(index), int(axis)\naxis_size = operand.shape[axis]\nwrapped_index = index + axis_size if index < 0 else index\nif not 0 <= wrapped_index < axis_size:\n@@ -1968,7 +1968,7 @@ def dynamic_slice_in_dim(operand: Array, start_index: Array,\naxis = int(axis)\nstart_indices[axis] = start_index\n- slice_sizes[axis] = int(slice_size)\n+ slice_sizes[axis] = _canonicalize_dimension(slice_size)\nreturn dynamic_slice(operand, start_indices, slice_sizes)\n"
},
{
"change_type": "MODIFY",
"old_path": "jax/experimental/jax2tf/shape_poly.py",
"new_path": "jax/experimental/jax2tf/shape_poly.py",
"diff": "@@ -482,10 +482,6 @@ def _einsum_contract_path(*operands, **kwargs):\ncontract_fake_ops, contractions = opt_einsum.contract_path(*fake_ops,\n**kwargs)\n- if len(contractions) > 1:\n- msg = (\"Shape polymorphism is not yet supported for einsum with more than \"\n- f\"one contraction {contractions}\")\n- raise ValueError(msg)\ncontract_operands = []\nfor operand in contract_fake_ops:\nidx = tuple(i for i, fake_op in enumerate(fake_ops) if operand is fake_op)\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": "@@ -1207,6 +1207,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4, 5), _f32), RandArg((3, 4, 5), _f32),\nRandArg((3, 4, 5), _f32)],\npoly_axes=[0, 0, 0]),\n+ _make_harness(\"collapse\", \"\",\n+ lambda x: lax.collapse(x, 1, 4),\n+ [RandArg((3, 4, 5, 6, 7), _f32)],\n+ poly_axes=[(0, 1, 3)]),\n_make_harness(\"conv_general_dilated\", \"\",\nlambda lhs, rhs: lax.conv_general_dilated(lhs, rhs,\nwindow_strides=(2, 3),\n@@ -1250,6 +1254,12 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[RandArg((3, 4), _f32), np.array([-2, -1], dtype=np.int32)],\npoly_axes=[0, None],\nenable_and_diable_xla=True),\n+ _make_harness(\"dynamic_slice_in_dim\", \"idx=0\",\n+ # x:shape: (b, 4)\n+ lambda x: lax.dynamic_slice_in_dim(x, 0, x.shape[0], axis=0),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0],\n+ enable_and_diable_xla=True),\n_make_harness(\"dynamic_update_slice\", \"idx=tuple_int\",\n# x:shape: (b, 4)\nlambda x: lax.dynamic_update_slice(x, x, (0, 0)),\n@@ -1316,12 +1326,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\n[0, 2]),\n[RandArg((3, 4), _f32), RandArg((4, 5), _f32)],\npoly_axes=[1, 0]),\n- _make_harness(\"einsum\", \"multiple_contractions_error\",\n+ _make_harness(\"einsum\", \"multiple_contractions\",\nlambda x, y, z: jnp.einsum(\"ab,bc,cd->ad\", x, y, z),\n[RandArg((3, 2), _f32), RandArg((2, 3), _f32), RandArg((3, 4), _f32),],\n- poly_axes=[0, None, None],\n- expect_error=(ValueError,\n- \"Shape polymorphism is not yet supported for einsum with more than one contraction\")),\n+ poly_axes=[0, None, None]),\n_make_harness(\"einsum\", \"incompatible_contractions_error\",\nlambda x, y: jnp.einsum(\"ab,cb->ac\", x, y),\n[RandArg((2, 3), _f32), RandArg((2, 3), _f32)],\n@@ -1336,6 +1344,10 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: jnp.eye(x.shape[0], M=x.shape[0] + 2),\n[RandArg((3, 4), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"full\", \"\",\n+ lambda x: lax.full((x.shape[0], 2), 3.),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n# operand is non-poly, index is poly\n_make_harness(\"getitem\", \"op=static_idx=poly\",\nlambda a, i: a[i],\n@@ -1360,6 +1372,18 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda a: a[1],\n[RandArg((3, 4), _f32)],\npoly_axes=[0], enable_and_diable_xla=True),\n+ _make_harness(\"index_in_dim\", \"idx=pos\",\n+ lambda x: lax.index_in_dim(x, 0, axis=0, keepdims=False),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"index_in_dim\", \"idx=neg\",\n+ lambda x: lax.index_in_dim(x, -1, axis=0, keepdims=False),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"index_in_dim\", \"idx=last\",\n+ lambda x: lax.index_in_dim(x, x.shape[0] - 1, axis=0, keepdims=False),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n_make_harness(\"iota\", \"\",\nlambda x: x + lax.iota(_f32, x.shape[0]),\n[RandArg((3,), _f32)],\n@@ -1489,6 +1513,18 @@ _POLY_SHAPE_TEST_HARNESSES = [\nlambda x: lax.slice(x, start_indices=(0, 1), limit_indices=(x.shape[0], 3)),\n[RandArg((7, 3), _f32)],\npoly_axes=[0]),\n+ _make_harness(\"slice_in_dim\", \"entire_axis\",\n+ lambda x: lax.slice_in_dim(x, 0, x.shape[0], stride=1, axis=0),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"slice_in_dim\", \"start=neg\",\n+ lambda x: lax.slice_in_dim(x, -1, x.shape[0], stride=1, axis=0),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n+ _make_harness(\"slice_in_dim\", \"limit=neg\",\n+ lambda x: lax.slice_in_dim(x, 0, -1, stride=1, axis=0),\n+ [RandArg((3, 4), _f32)],\n+ poly_axes=[0]),\n_make_harness(\"squeeze\", \"axis=None\",\njnp.squeeze,\n[RandArg((5,), _f32), StaticArg(())],\n"
}
] | Python | Apache License 2.0 | google/jax | [jax2tf] Small fixes for shape polymorphism.
* Fixed a few places where indexing required indices to be integer
constants. Use core._canonicalize_dimension in lieu of casting to integer.
Note that this may break code that passes floating point as indices.
* Relaxed einsum to work for multiple contractions.
* Added tests. |
260,424 | 10.08.2021 18:46:03 | -3,600 | 2f9caf3d642aa584571105a7516b47d9bf8d1789 | Ensure reduce_axes is a tuple. | [
{
"change_type": "MODIFY",
"old_path": "jax/_src/api.py",
"new_path": "jax/_src/api.py",
"diff": "@@ -852,6 +852,7 @@ def value_and_grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n_check_callable(fun)\nargnums = core.concrete_or_error(_ensure_index, argnums)\n+ reduce_axes = _ensure_str_tuple(reduce_axes)\n@wraps(fun, docstr=docstr, argnums=argnums)\n@api_boundary\n@@ -2121,6 +2122,7 @@ def vjp( # type: ignore\n-0.2524413\n\"\"\"\n_check_callable(fun)\n+ reduce_axes = _ensure_str_tuple(reduce_axes)\nreturn _vjp(\nlu.wrap_init(fun), *primals, has_aux=has_aux, reduce_axes=reduce_axes)\n@@ -2198,6 +2200,7 @@ def linear_transpose(fun: Callable, *primals, reduce_axes=()) -> Callable:\n>>> f_transpose(1.0)\n(DeviceArray(0.5, dtype=float32), DeviceArray(-0.5, dtype=float32))\n\"\"\"\n+ reduce_axes = _ensure_str_tuple(reduce_axes)\nprimals_flat, in_tree = tree_flatten(primals)\nflat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\nin_avals = map(shaped_abstractify, primals_flat)\n"
}
] | Python | Apache License 2.0 | google/jax | Ensure reduce_axes is a tuple. |
260,578 | 12.08.2021 11:12:35 | 25,200 | 1f13565b70cff1cf2c6eb81f5fcd2ee6d41286af | Remove opensource CS link since JAX is not indexed | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "| [**Neural net libraries**](#neural-network-libraries)\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**News:** [JAX tops largest-scale MLPerf Training 0.7 benchmarks!](https://cloud.google.com/blog/products/ai-machine-learning/google-breaks-ai-performance-records-in-mlperf-with-worlds-fastest-training-supercomputer)\n"
}
] | Python | Apache License 2.0 | google/jax | Remove opensource CS link since JAX is not indexed |
260,347 | 13.08.2021 14:52:03 | 0 | 6708cd31584f6bd14431ae1020df3de7a1635bb5 | Add dtype to string representation of ConcreteArray.
The string representation of ConcreteArray did not include the data type of the
wrapped value. This makes it harder to spot the reason for errors arising from
inconsistent values (issue This commit adds the data type to the string
representation of ConcreteArray. | [
{
"change_type": "MODIFY",
"old_path": "jax/core.py",
"new_path": "jax/core.py",
"diff": "@@ -1190,7 +1190,7 @@ class ConcreteArray(ShapedArray):\nraise TypeError(self, other)\ndef str_short(self) -> str:\n- return str(self.val)\n+ return f'{self.val}, dtype={self.dtype.name}'\n_bool = _nonzero = partialmethod(_forward_to_value, bool)\n_int = partialmethod(_forward_to_value, int)\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/core_test.py",
"new_path": "tests/core_test.py",
"diff": "@@ -333,6 +333,12 @@ class CoreTest(jtu.JaxTestCase):\nargs_maker = lambda: (core.unit, 1)\nself._CompileAndCheck(f, args_maker)\n+ def test_concrete_array_string_representation(self):\n+ # https://github.com/google/jax/issues/5364\n+ self.assertEqual(\n+ str(core.ConcreteArray(np.array([1], dtype=np.int32))),\n+ 'ConcreteArray([1], dtype=int32)')\n+\nclass JaxprTypeChecks(jtu.JaxTestCase):\n"
}
] | Python | Apache License 2.0 | google/jax | Add dtype to string representation of ConcreteArray.
The string representation of ConcreteArray did not include the data type of the
wrapped value. This makes it harder to spot the reason for errors arising from
inconsistent values (issue #5364). This commit adds the data type to the string
representation of ConcreteArray. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.