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
21.12.2020 11:01:29
-7,200
beb0e02fb48e9e7663ce8afe964059f82247a5cf
[host_callback] Added support for jax.named_call.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -558,7 +558,7 @@ batching.primitive_batchers[id_tap_p] = _id_tap_batching_rule\ndef _id_tap_masking_rule(operands, operands_logical_shapes, **params):\n- new_params = _add_transform(params, \"mask\", operands_logical_shapes)\n+ new_params = _add_transform(params, \"mask\", tuple(operands_logical_shapes))\nreturn id_tap_p.bind(*operands, **new_params)\n@@ -802,6 +802,17 @@ def _rewrite_eqn(eqn: core.JaxprEqn, eqns: List[core.JaxprEqn],\nout_trees=\"illegal param\"\n),\neqn.source_info))\n+ elif eqn.primitive is core.named_call_p:\n+ call_jaxpr = cast(core.Jaxpr, eqn.params[\"call_jaxpr\"])\n+ eqns.append(\n+ core.new_jaxpr_eqn(\n+ eqn.invars + [input_token_var], eqn.outvars + [output_token_var],\n+ eqn.primitive,\n+ dict(\n+ eqn.params,\n+ call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),\n+ ),\n+ eqn.source_info))\nelse:\nraise NotImplementedError(f\"outfeed rewrite {eqn.primitive}\")\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -1329,28 +1329,16 @@ class HostCallbackTest(jtu.JaxTestCase):\n1.\"\"\", testing_stream.output)\ndef test_mask(self):\n- # TODO(necula)\n- raise SkipTest(\"masking has regressed\")\n+\n@functools.partial(api.mask, in_shapes=['n'], out_shape='')\ndef padded_sum(x):\nreturn jnp.sum(hcb.id_print(x, what=\"x\", output_stream=testing_stream))\nargs = [jnp.arange(4)], dict(n=np.int64(2))\n- assertMultiLineStrippedEqual(self, \"\"\"\n- { lambda c f ; a b.\n- let d = lt c b\n- e = id_tap[ func=_print\n- logical_shapes=[(Traced<ShapedArray(int32[]):JaxprTrace(level=0/0)>,)]\n- transforms=('mask',)\n- what=x ] a\n- g = select d e f\n- h = reduce_sum[ axes=(0,) ] g\n- in (h,) }\"\"\", str(api.make_jaxpr(padded_sum)(*args)))\n-\n_ = padded_sum(*args)\n+ hcb.barrier_wait()\nself.assertMultiLineStrippedEqual(\"\"\"\n- logical_shapes: [(2,)] transforms: ['mask',) what: x\n- [0 1 2 3]\n- \"\"\", testing_stream.output)\n+ transforms: [('mask', {'logical_shapes': ((2,),)})] what: x\n+ [0 1 2 3]\"\"\", testing_stream.output)\ntesting_stream.reset()\ndef test_callback_delay(self):\n@@ -1461,6 +1449,26 @@ class HostCallbackTest(jtu.JaxTestCase):\n10\"\"\"\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ def test_named_call(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"Test requires omnistaging\")\n+ def tap_scalar(init, do_print=False):\n+ @functools.partial(api.named_call, name=\"step\")\n+ def step(acc, step_nr):\n+ acc = acc + step_nr\n+ maybe_print(do_print, step_nr, what=\"step_nr\")\n+ return acc, None\n+\n+ return lax.scan(step, init, np.arange(2))\n+ self.assertAllClose(tap_scalar(3., do_print=False), tap_scalar(3., do_print=True))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ what: step_nr\n+ 0\n+ what: step_nr\n+ 1\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+\nclass OutfeedRewriterTest(jtu.JaxTestCase):\n@@ -1864,6 +1872,32 @@ class OutfeedRewriterTest(jtu.JaxTestCase):\ncond_nconsts=0 ] 0 1 a c\nin (b, d) }\"\"\", loss, [2])\n+ def test_named_call(self):\n+\n+ def tap_scalar(init, do_print=False):\n+ @functools.partial(api.named_call, name=\"step\")\n+ def step(acc, step_nr):\n+ acc = acc + step_nr\n+ maybe_print(do_print, step_nr, what=\"step_nr\")\n+ return acc, None\n+\n+ return lax.scan(step, init, np.arange(2, dtype=np.int32))\n+ self.assertRewrite(\"\"\"\n+ { lambda a ; b d.\n+ let c = scan[ jaxpr={ lambda ; a b.\n+ let c = named_call[ call_jaxpr={ lambda ; a b.\n+ let c = add a b\n+ in (c,) }\n+ name=step ] a b\n+ in (c,) }\n+ length=2\n+ linear=(False, False)\n+ num_carry=1\n+ num_consts=0\n+ reverse=False\n+ unroll=1 ] b a\n+ in (c, d) }\"\"\", tap_scalar, [np.int32(3)])\n+\ndef test_pmap(self):\ndef f(xv):\napi.pmap(lambda x: jnp.sin(hcb.id_print(x, tap_with_device=True)),\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Added support for jax.named_call.
260,472
17.09.2020 18:33:30
-10,800
3796cf33387ec6e804ae3bc9baaefc344a57027b
Covering an execution path on array creation: when an array is created with an unspecified type (None), there was no typechecking that the inferred type is compatible with JAX. The issue has been documented and a test with the use case added.
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -2733,6 +2733,8 @@ def atleast_3d(*arys):\ndef array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nif order is not None and order != \"K\":\nraise NotImplementedError(\"Only implemented for order='K'\")\n+\n+ # check if the given dtype is compatible with JAX\nlax._check_user_dtype_supported(dtype, \"array\")\nweak_type = dtype is None and dtypes.is_weakly_typed(object)\n@@ -2740,9 +2742,12 @@ def array(object, dtype=None, copy=True, order=\"K\", ndmin=0):\nif _can_call_numpy_array(object):\nobject = _np_array(object, dtype=dtype, ndmin=ndmin, copy=False)\n+\nassert type(object) not in dtypes.python_scalar_dtypes\nif type(object) is np.ndarray:\n+ _inferred_dtype = object.dtype and dtypes.canonicalize_dtype(object.dtype)\n+ lax._check_user_dtype_supported(_inferred_dtype, \"array\")\nout = _device_put_raw(object, weak_type=weak_type)\nif dtype: assert _dtype(out) == dtype\nelif isinstance(object, (DeviceArray, core.Tracer)):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -4664,6 +4664,13 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nwith self.assertRaisesRegex(jax.core.ConcretizationTypeError, msg('stop')):\njax.jit(lambda stop: jnp.arange(0, stop))(3)\n+ def testIssue2347(self):\n+ # https://github.com/google/jax/issues/2347\n+ object_list = List[Tuple[jnp.array, float, float, jnp.array, bool]]\n+ self.assertRaises(TypeError, jnp.array, object_list)\n+\n+ np_object_list = np.array(object_list)\n+ self.assertRaises(TypeError, jnp.array, np_object_list)\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" } ]
Python
Apache License 2.0
google/jax
Covering an execution path on array creation: when an array is created with an unspecified type (None), there was no typechecking that the inferred type is compatible with JAX. The issue has been documented and a test with the use case added.
260,335
23.12.2020 11:04:59
28,800
19057260b96185368dda332713b69fd03273a715
remove unchanged file
[ { "change_type": "MODIFY", "old_path": "jax/experimental/loops.py", "new_path": "jax/experimental/loops.py", "diff": "@@ -548,8 +548,7 @@ class _WhileBuilder(_LoopBuilder):\n# Conditional function is not allowed to modify the scope state\nfor ms, init_ms in zip(carried_state_names, args):\nif not (scope._mutable_state[ms] is init_ms):\n- msg = \"Conditional function modifies scope.{} field.\"\n- raise ValueError(msg.format(ms))\n+ raise ValueError(f\"Conditional function modifies scope.{ms} field.\")\nreturn res\ninit_avals = safe_map(_BodyTracer.abstractify, init_vals)\n@@ -559,11 +558,10 @@ class _WhileBuilder(_LoopBuilder):\ntuple(init_avals)))\n# TODO: share these checks with lax_control_flow.while\nif not tree_util.treedef_is_leaf(cond_tree):\n- msg = \"cond_fun must return a boolean scalar, but got pytree {}.\"\n- raise TypeError(msg.format(cond_tree))\n- if cond_jaxpr.out_avals != [core.ShapedArray((), np.bool_)]:\n- msg = \"cond_fun must return a boolean scalar, but got output type(s) {}.\"\n- raise TypeError(msg.format(cond_jaxpr.out_avals))\n+ raise TypeError(f\"cond_fun must return a boolean scalar, but got pytree {cond_tree}.\")\n+ if not safe_map(core.typecompat, cond_jaxpr.out_avals, [core.ShapedArray((), np.bool_)]):\n+ raise TypeError(f\"cond_fun must return a boolean scalar, but got output type(s) \"\n+ f\"{cond_jaxpr.out_avals}.\")\nreturn lax_control_flow.while_p.bind(*itertools.chain(cond_consts,\nbody_const_vals,\n" } ]
Python
Apache License 2.0
google/jax
remove unchanged file
260,335
29.12.2020 11:43:44
28,800
cdc1b0546a3281c2959866576c7a2d2168d7eda1
remove AbstractValue.at_least_vspace default impl
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -800,7 +800,7 @@ class AbstractValue:\n_num_buffers: int = 1 # number of buffers used to represent the value.\ndef at_least_vspace(self):\n- return self\n+ raise NotImplementedError(\"must override\")\ndef __repr__(self):\ntry:\n@@ -822,6 +822,7 @@ bot = Bot()\nclass AbstractUnit(AbstractValue):\n# TODO(jakevdp): make it possible to set zero buffers\n# _num_buffers = 0\n+ def at_least_vspace(self): return self\ndef join(self, other):\nif not skip_checks:\nassert other is abstract_unit, other\n" } ]
Python
Apache License 2.0
google/jax
remove AbstractValue.at_least_vspace default impl
260,411
05.01.2021 09:47:59
-7,200
f2453207310088332b50f82fe573ae99b2c7b12a
Trigger the re-building of documentation
[ { "change_type": "MODIFY", "old_path": "docs/developer.rst", "new_path": "docs/developer.rst", "diff": "@@ -233,7 +233,8 @@ For each automated documentation build you can see the\nIf you want to test the documentation generation on Readthedocs, you can push code to the ``test-docs``\nbranch. That branch is also built automatically, and you can\n-see the generated documentation `here <https://jax.readthedocs.io/en/test-docs/>`_.\n+see the generated documentation `here <https://jax.readthedocs.io/en/test-docs/>`_. If the documentation build\n+fails you may want to `wipe the build environment for test-docs <https://docs.readthedocs.io/en/stable/guides/wipe-environment.html>`_.\nFor a local test, I was able to do it in a fresh directory by replaying the commands\nI saw in the Readthedocs logs::\n" } ]
Python
Apache License 2.0
google/jax
Trigger the re-building of documentation
260,411
06.01.2021 13:36:37
-7,200
aec6192ed90d75fceb59353b7e4e1c8511626b5b
Fix float0 handling
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -875,25 +875,20 @@ def _add_transform(params: Dict, name: str, *transform_params) -> Dict:\n# TODO(necula): there must be a better way to do this.\n# The AttributeError is for regular values, the KeyError is for ConcreteArray\ndef _instantiate_zeros(arg, tan):\n- \"\"\"Turn special ad.zero tangents into arrays of 0s.\"\"\"\n+ \"\"\"Turn special ad.zero tangents into arrays of 0s for sending to host.\"\"\"\n+ # return ad.instantiate_zeros(tan)\nif type(tan) is not ad.Zero:\nreturn tan\n- try:\n+ if tan.aval is core.abstract_unit:\n+ if ad.is_undefined_primal(arg):\naval = arg.aval\n- return ad.instantiate_zeros_aval(aval, tan)\n- except (AttributeError, KeyError):\n- # We get here for regular Python values\n- return ad.zeros_like_jaxval(arg)\n-\n-\n-def _instantiate_zeros_aval(aval, tan):\n- \"\"\"Turn special ad.zero tangents into arrays of 0s.\"\"\"\n- if type(tan) is not ad.Zero:\n- return tan\n-\n- return ad.instantiate_zeros_aval(aval, tan)\n-\n+ else:\n+ aval = 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\ndef _id_tap_jvp_rule(primals, tangents, **params):\ntangent_instantiated = tuple(map(_instantiate_zeros, primals, tangents))\n@@ -1579,7 +1574,7 @@ def barrier_wait(logging_name: Optional[str] = None):\nWaits until all outfeed from computations already running on all devices\nhas been received and processed by the Python callbacks. Raises\n- Callback if there were exceptions while processing the callbacks.\n+ CallbackException if there were exceptions while processing the callbacks.\nThis works by enqueueing a special tap computation to all devices to which\nwe are listening for outfeed. Once all those tap computations are done, we\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -521,7 +521,7 @@ def instantiate_zeros(tangent):\nelse:\nreturn tangent\n-# This function seems similar to instantaite_zeros, but it is sometimes used\n+# This function seems similar to instantiate_zeros, but it is sometimes used\n# to instantiate zero abstract units with a different aval\ndef instantiate_zeros_aval(aval, tangent):\nif type(tangent) is Zero:\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -26,12 +26,14 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nfrom jax import api\n+from jax.config import config\n+from jax import dtypes\n+from jax.experimental import host_callback as hcb\nfrom jax import lax\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\n-from jax.config import config\n-from jax.experimental import host_callback as hcb\nfrom jax.lib import xla_bridge\n+\nimport numpy as np\nconfig.parse_flags_with_absl()\n@@ -201,6 +203,7 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\ntesting_stream.reset()\ntesting_stream.test_method_name = self._testMethodName\nself.old_flags = os.getenv(\"XLA_FLAGS\", \"\")\n+ super().setUp()\ndef tearDown(self) -> None:\nif os.getenv(\"XLA_FLAGS\") != self.old_flags:\n@@ -961,6 +964,37 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n0.00 )\"\"\", testing_stream.output)\ntesting_stream.reset()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"test works only with omnistaging enabled\")\n+ def test_jvp_float0(self):\n+ def f(x, yint):\n+ x, yint = hcb.id_tap(lambda arg, _: arg, (x, yint))\n+ return x * yint\n+\n+ res = api.jvp(f, (2., 3), (0.2, np.zeros((), dtypes.float0)))\n+ self.assertAllClose((6., 0.6), res)\n+\n+ @skipIf(not config.omnistaging_enabled,\n+ \"test works only with omnistaging enabled\")\n+ def test_grad_float0(self):\n+ def func(x, yint):\n+ x, yint = hcb.id_print((x, yint), what=\"pair\", output_stream=testing_stream)\n+ return x * yint\n+\n+ grad_func = api.grad(func)\n+\n+ res_grad = grad_func(jnp.float32(5.), jnp.int32(2))\n+ self.assertAllClose(2., res_grad, check_dtypes=False)\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"\"\"\n+ what: pair\n+ ( 5.00\n+ 2 )\n+ transforms: ['jvp', 'transpose'] what: pair\n+ ( 2.00\n+ False )\"\"\", testing_stream.output)\n+ testing_stream.reset()\n+\ndef test_vmap(self):\nvmap_fun1 = api.vmap(fun1)\nvargs = jnp.array([jnp.float32(4.), jnp.float32(5.)])\n@@ -1077,6 +1111,61 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n[2 2 2 3 4]\"\"\", testing_stream.output)\ntesting_stream.reset()\n+ @skipIf(not config.omnistaging_enabled,\n+ \"test works only with omnistaging enabled\")\n+ def test_composed(self):\n+ def power(x, n):\n+ x, n = hcb.id_print((x, n), output_stream=testing_stream)\n+ return x * x * n * x\n+\n+ def f(x, n):\n+ return x * power(x + 1., n)\n+\n+ x = 3.\n+ print(\"impl = \", f(x, 2.))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ ( 4.\n+ 2. )\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\n+ print(\"jvp = \", api.jvp(lambda x: f(x, 2.), (x,), (1.,)))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ transforms: ['jvp']\n+ ( ( 4.\n+ 2. )\n+ ( 1.\n+ 0. ) )\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\n+ print(\"grad = \", api.grad(f)(x, 2.))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ ( 4.\n+ 2. )\n+ transforms: ['jvp', 'transpose']\n+ ( 288.\n+ 192. )\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\n+ xv = np.array([3., 4.])\n+ print(\"vmap o grad = \", api.vmap(api.grad(f))(xv, np.array([2., 3.])))\n+ hcb.barrier_wait()\n+ expected = \"\"\"\n+ transforms: [('batch', {'batch_dims': (0, 0)})]\n+ ( [4. 5.]\n+ [2. 3.] )\n+ transforms: ['jvp', 'transpose', ('batch', {'batch_dims': (0, 0)})]\n+ ( [288. 900.]\n+ [192. 500.] )\"\"\"\n+ self.assertMultiLineStrippedEqual(expected, testing_stream.output)\n+ testing_stream.reset()\n+\n+\ndef test_pmap(self):\nxv = jnp.arange(api.device_count(), dtype=jnp.int32)\n@@ -1460,8 +1549,8 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n( 3 ) ) )\n( ( [0. 0.1 0.2 0.3 0.4]\n[0. 0.2 0.4 0.6 0.8] )\n- ( ( 0 )\n- ( 0 ) ) ) )\"\"\", testing_stream.output)\n+ ( ( False )\n+ ( False ) ) ) )\"\"\", testing_stream.output)\ntesting_stream.reset()\n# Now with JIT\n@@ -1605,22 +1694,7 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n1\"\"\"\nself.assertMultiLineStrippedEqual(expected, testing_stream.output)\n- @skipIf(not config.omnistaging_enabled,\n- \"test works only with omnistaging enabled\")\n- def test_composed(self):\n- def power(x, n):\n- x, n = hcb.id_print((x, n))\n- return x ** n\n-\n- def f(x, n):\n- return x * power(x + 1., n)\n- x = 3.\n- print(\"impl = \", f(x, 2.))\n- print(\"jvp = \", api.jvp(lambda x: f(x, 2), (x,), (1.,)))\n- print(\"grad = \", api.grad(f)(x, 2.))\n- xv = np.array([3., 4.])\n- print(\"vmap o grad = \", api.vmap(api.grad(f))(xv, np.array([2., 3.])))\nclass HostCallbackCallTest(jtu.JaxTestCase):\n@@ -1629,9 +1703,11 @@ class HostCallbackCallTest(jtu.JaxTestCase):\ndef setUp(self):\ntesting_stream.reset()\ntesting_stream.test_method_name = self._testMethodName\n+ super().setUp()\ndef tearDown(self) -> None:\nhcb.barrier_wait(\"HostCallbackCallTest.tearDown\")\n+ super().tearDown()\ndef call_log_testing_stream(self, func, arg, *, result_shape, name=\"\"):\n\"\"\"Call `func` and log inputs and outputs to the testing stream\"\"\"\n@@ -1909,6 +1985,7 @@ class CallJaxTest(jtu.JaxTestCase):\nif len(api.devices(\"cpu\")) == 1:\nraise SkipTest(\"Test needs at least two devices. On CPU use XLA_FLAGS=--xla_force_host_platform_device_count=2\")\nself.outside_device = api.devices(\"cpu\")[1]\n+ super().setUp()\ndef test_impl(self):\ndef f_jax(x):\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_to_tf_test.py", "new_path": "tests/host_callback_to_tf_test.py", "diff": "@@ -49,7 +49,7 @@ def call_tf_no_ad(tf_fun: Callable, arg, *, result_shape):\ndef tf_to_numpy(t):\n# Turn the Tensor to NumPy array without copying.\n- return np.array(memoryview(t)) if isinstance(t, tf.Tensor) else t\n+ return np.asarray(memoryview(t)) if isinstance(t, tf.Tensor) else t\nreturn hcb.call(lambda arg: tf.nest.map_structure(tf_to_numpy,\ntf_fun(arg)),\n@@ -162,6 +162,7 @@ class CallToTFTest(jtu.JaxTestCase):\ndef setUp(self):\nif tf is None:\nraise unittest.SkipTest(\"Test requires tensorflow\")\n+ super().setUp()\n@parameterized.named_parameters(\ndict(\n" } ]
Python
Apache License 2.0
google/jax
Fix float0 handling
260,411
06.01.2021 15:02:26
-7,200
7468b9df467ce95cde277fbb3ceb9f1f2d0cd612
Turn off flaky test LaxControlFlowTest.test_cond_typecheck_param
[ { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -2457,6 +2457,7 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nlambda: core.check_jaxpr(jaxpr))\ndef test_cond_typecheck_param(self):\n+ raise SkipTest(\"TODO: test is flaky b/176769043\")\ndef new_jaxpr():\njaxpr = api.make_jaxpr(\nlambda x: lax.switch(0, [jnp.sin, jnp.cos], x))(1.).jaxpr\n" } ]
Python
Apache License 2.0
google/jax
Turn off flaky test LaxControlFlowTest.test_cond_typecheck_param
260,613
06.01.2021 14:43:05
0
0e73bb9281c12f832635b2c371ca41ecda33cdb2
inf checker tests
[ { "change_type": "MODIFY", "old_path": "tests/debug_nans_test.py", "new_path": "tests/debug_nans_test.py", "diff": "@@ -77,5 +77,55 @@ class DebugNaNsTest(jtu.JaxTestCase):\nf(1)\n+class DebugInfsTest(jtu.JaxTestCase):\n+\n+ def setUp(self):\n+ self.cfg = config.read(\"jax_debug_infs\")\n+ config.update(\"jax_debug_inf\", True)\n+\n+ def tearDown(self):\n+ config.update(\"jax_debug_infs\", self.cfg)\n+\n+ def testSingleResultPrimitiveNoInf(self):\n+ A = jnp.array([[1., 2.], [2., 3.]])\n+ ans = jnp.tanh(A)\n+ ans.block_until_ready()\n+\n+ def testMultipleResultPrimitiveNoInf(self):\n+ A = jnp.array([[1., 2.], [2., 3.]])\n+ ans, _ = jnp.linalg.eigh(A)\n+ ans.block_until_ready()\n+\n+ def testJitComputationNoInf(self):\n+ A = jnp.array([[1., 2.], [2., 3.]])\n+ ans = jax.jit(jnp.tanh)(A)\n+ ans.block_until_ready()\n+\n+ def testSingleResultPrimitiveInf(self):\n+ A = jnp.array(0.)\n+ with self.assertRaises(FloatingPointError):\n+ ans = 1. / A\n+ ans.block_until_ready()\n+\n+ def testCallDeoptimized(self):\n+ to_test = [jax.api._python_jit]\n+ if version > (0, 1, 56):\n+ to_test.append(jax.api._cpp_jit)\n+\n+ for jit in to_test:\n+\n+ @jit\n+ def f(x):\n+ return jax.lax.cond(\n+ x == 1, lambda _: np.inf, lambda _: 2., operand=None)\n+\n+ # This makes sure, when using the C++ jit, that the Python code has been\n+ # run to compile, and the next call won't go through `cache_miss`.\n+ f(2)\n+ # 'cond' not 'xla_call'\n+ msg = r\"invalid value \\(inf\\) encountered in cond\"\n+ with self.assertRaisesRegex(FloatingPointError, msg):\n+ f(1)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
inf checker tests
260,340
07.01.2021 17:03:39
-32,400
3614d829facd338867617851d7fcac8ecbe8c2c9
Fix typo in jax/_src/random.py
[ { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -658,7 +658,7 @@ def multivariate_normal(key: jnp.ndarray,\nbroadcasting together the batch shapes of ``mean`` and ``cov``.\ndtype: optional, a float dtype for the returned values (default float64 if\njax_enable_x64 is true, otherwise float32).\n- method: optinoal, a method to compute the factor of ``cov``.\n+ method: optional, a method to compute the factor of ``cov``.\nMust be one of 'svd', eigh, and 'cholesky'. Default 'cholesky'.\nReturns:\nA random array with the specified dtype and shape given by\n" } ]
Python
Apache License 2.0
google/jax
Fix typo in jax/_src/random.py Co-authored-by: Matthew Johnson <mattjj@google.com>
260,411
07.01.2021 07:57:59
-7,200
231ea59f757d720b13ffaf9fea58bdcecc917844
[jax2tf] Fix infinite recursion when converting some bfloat16 arrays This fix takes advantage of a new change in TF to share the bfloat16 dtype definition with JAX Fixes: Relates to:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -77,30 +77,12 @@ def _is_tfval(v: TfVal) -> bool:\nreturn False\ndef _safe_convert_to_tensor(val, dtype=None) -> TfVal:\n- \"\"\"Converts val to a Tensor.\n-\n- This method wraps TensorFlow's `convert_to_tensor\n- <https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor>`_ operator with\n- special case handling for when `val` is an instance of `jnp.bfloat16` or has a\n- `jnp.bfloat16` dtype. Because this type is not supported in numpy and different\n- from `tf.bfloat16.as_numpy_dtype`, `tf.convert_to_tensor` runs into trouble when\n- trying to convert it. In such a case, we solve the problem by viewing val as a\n- `ndarray` with a `uint16` dtype, for which conversion is properly defined. Then, we\n- simply bitcast it back to `bfloat16`.\n- \"\"\"\ndtype = dtype if dtype else (val.dtype if hasattr(val, \"dtype\") else None)\n- if (dtype == jnp.bfloat16 or isinstance(val, jnp.bfloat16)):\n- if not isinstance(val, jnp.ndarray):\n- val = np.array(val, jnp.bfloat16)\n-\n- val = tf.bitcast(tf.convert_to_tensor(val.view(jnp.uint16),\n- dtype=to_tf_dtype(jnp.uint16)),\n- type=to_tf_dtype(jnp.bfloat16))\n- else:\nconversion_type = to_tf_dtype(dtype) if dtype else None\n- val = tf.convert_to_tensor(val, dtype=conversion_type)\n+ # We can convert directly, because all dtypes (even bfloat16) are the same\n+ # in JAX and TF.\n+ return tf.convert_to_tensor(val, dtype=conversion_type)\n- return val\n# The implementation rules for primitives. The rule will be called with the\n# arguments (TfVal) and must return TfVal (or a sequence thereof,\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -421,6 +421,26 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\njax2tf.convert(my_test_function)(2)\nself.assertIn(\"my_test_function/foo\", log[0])\n+ def test_bfloat16_constant(self):\n+ # Re: https://github.com/google/jax/issues/3942\n+ def jax_fn_scalar(x):\n+ x = x.astype(jnp.bfloat16)\n+ x *= 2.\n+ return x\n+\n+ def jax_fn_array(x):\n+ x = x.astype(jnp.bfloat16)\n+ x *= np.array([1.5, 2.5, 3.5], jnp.bfloat16)\n+ return x\n+\n+ tf_fn_scalar = jax2tf.convert(jax_fn_scalar)\n+ self.assertAllClose(tf_fn_scalar(1.375).numpy(), jnp.bfloat16(2.750))\n+\n+ tf_fn_array = jax2tf.convert(jax_fn_array)\n+ self.assertAllClose(\n+ tf_fn_array(np.array([3, 4, 5])), np.array([4.5, 10, 17.5],\n+ jnp.bfloat16))\n+\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -65,7 +65,6 @@ from jax import lax\nfrom jax import numpy as jnp\nfrom jax import test_util as jtu\nfrom jax.config import config\n-from jax.experimental import jax2tf\nfrom jax.interpreters import xla\nimport numpy as np\n@@ -288,31 +287,6 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nvalues = np.array([True, False, True], dtype=np.bool_)\nself.ConvertAndCompare(f_jax, values)\n- # test_bfloat16_constant checks that https://github.com/google/jax/issues/3942 is\n- # fixed\n- # TODO(bchetioui): re-enable this test once recursion issues are addressed.\n- @unittest.skipIf(True, \"Infinite recursion after changes in #5085\")\n- def test_bfloat16_constant(self):\n-\n- def jax_fn_scalar(x):\n- x = x.astype(jnp.bfloat16)\n- x *= 2.\n- return x\n-\n- def jax_fn_array(x):\n- x = x.astype(jnp.bfloat16)\n- x *= np.array([1.5, 2.5, 3.5], jnp.bfloat16)\n- return x\n-\n- tf_fn_scalar = jax2tf.convert(jax_fn_scalar)\n- self.assertAllClose(tf_fn_scalar(1.375).numpy(), jnp.bfloat16(2.750))\n-\n- tf_fn_array = jax2tf.convert(jax_fn_array)\n- self.assertAllClose(\n- tf_fn_array(np.array([3, 4, 5])), np.array([4.5, 10, 17.5],\n- jnp.bfloat16))\n-\n-\nif __name__ == \"__main__\":\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix infinite recursion when converting some bfloat16 arrays This fix takes advantage of a new change in TF to share the bfloat16 dtype definition with JAX Fixes: #5106 Relates to: #5108
260,411
07.01.2021 14:54:47
-7,200
274d970644ad55ca782acab4a7cd6b0fa668c138
[jax2tf] Finish the conversion of lax.sort We were blocked until now due to limited support for the XlaSort op. Also removed the patching of the XlaPad output shape; now XlaPad has shape inference.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -126,7 +126,7 @@ for CUDA. One must be mindful to install a version of CUDA that is compatible\nwith both [jaxlib](https://github.com/google/jax/blob/master/README.md#pip-installation) and\n[TensorFlow](https://www.tensorflow.org/install/source#tested_build_configurations).\n-As of today, the tests are run using `tf_nightly==2.5.0-dev20201223`.\n+As of today, the tests are run using `tf_nightly==2.5.0-dev20210107`.\n## Caveats\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\n-*Last generated on (YYYY-MM-DD): 2020-12-31*\n+*Last generated on (YYYY-MM-DD): 2021-01-07*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -151,9 +151,8 @@ More detailed information can be found in the\n| select_and_scatter_add | TF error: op not defined for dtype | uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n| sign | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| sinh | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n-| sort | TF error: TODO: XlaSort does not support more than 2 arrays | all | cpu, gpu, tpu | compiled, eager, graph |\n-| sort | TF error: TODO: XlaSort does not support sorting axis | all | cpu, gpu, tpu | compiled, eager, graph |\n-| sort | TF error: op not defined for dtype | complex | cpu, gpu | eager, graph |\n+| sort | TF error: op not defined for dtype | complex, float64 | cpu, gpu | compiled, eager, graph |\n+| sort | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| sub | TF error: op not defined for dtype | uint64 | cpu, gpu, tpu | 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 |\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "import functools\nimport re\nimport string\n-from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Union\n+from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union\nimport jax\nfrom jax import ad_util, api, api_util, config\n@@ -1405,8 +1405,6 @@ def _pad(operand, padding_value, *, padding_config,\nif not _enable_xla:\nraise _xla_path_disabled_error(\"pad\")\nout = tfxla.pad(operand, padding_value, low, high, interior)\n- # TODO(necula): implement shape inference for XlaPad\n- out.set_shape(_aval_to_tf_shape(_out_aval))\nreturn out\ntf_impl_with_avals[lax.pad_p] = _pad\n@@ -1987,29 +1985,72 @@ def _top_k(operand: TfVal, k: int) -> Tuple[TfVal, TfVal]:\nconversion_dtype = promote_tf_dtype(operand.dtype)\nif conversion_dtype:\n- values, indices = tf.math.top_k(tf.dtypes.cast(operand, conversion_dtype), k=k, sorted=True)\n+ values, indices = tf.math.top_k(tf.dtypes.cast(operand, conversion_dtype),\n+ k=k, sorted=True)\nreturn tf.dtypes.cast(values, operand.dtype), indices\nelse:\nreturn tf.math.top_k(operand, k=k, sorted=True)\ntf_impl[lax.top_k_p] = _top_k\n-def _sort(*operand: TfVal, dimension: int, is_stable: bool, num_keys: int) -> Tuple[TfVal, ...]:\n- if num_keys != 1:\n- raise NotImplementedError(\"TODO: multiple keys\")\n- if len(operand) > 2:\n- raise NotImplementedError(\"TODO: handle > 2 tensors\")\n- if is_stable:\n- raise NotImplementedError(\"TODO: implement stable version of XlaSort\")\n- if dimension == len(operand[0].shape) - 1:\n+\n+def _sort(*operands: TfVal, dimension: int, is_stable: bool,\n+ num_keys: int) -> Tuple[TfVal, ...]:\nif not _enable_xla:\nraise _xla_path_disabled_error(\"sort\")\n- if len(operand) == 2:\n- return tuple(tfxla.key_value_sort(operand[0], operand[1]))\n+ assert 1 <= num_keys <= len(operands)\n+ assert all([operands[0].shape == op.shape for op in operands[1:]])\n+ assert 0 <= dimension < len(\n+ operands[0].shape\n+ ), f\"Invalid {dimension} for ndim {len(operands[0].shape)}\"\n+\n+ # The comparator is a 2N-argument TF function, with arguments [2k] and [2k +1]\n+ # corresponding to two scalars from operand[k].\n+ def lexicographic_comparator_old(*tf_args: TfVal) -> TfVal:\n+ assert len(tf_args) == 2 * len(operands)\n+ # We build a comparison:\n+ # arg[0] < arg[1] or (arg[0] == arg[1] and (arg[2] < arg[3] or ...))\n+ # all the way to arg[2 * num_keys - 2] < arg[2 * num_keys - 1]\n+ inside_comparison = None\n+ for key_idx in range(num_keys - 1, -1, -1):\n+ a = tf_args[2 * key_idx]\n+ b = tf_args[2 * key_idx + 1]\n+ a_lt_b = tf.math.less(a, b)\n+ if inside_comparison is None:\n+ inside_comparison = a_lt_b\nelse:\n- return (tfxla.sort(operand[0]),)\n- else:\n- raise NotImplementedError(\"TODO: implement XlaSort for all axes\")\n+ inside_comparison = tf.math.logical_or(\n+ a_lt_b, tf.math.logical_and(tf.math.equal(a, b), inside_comparison))\n+ return inside_comparison\n+\n+ comparator_spec: List[tf.TensorSpec] = []\n+ comparator_jax_in_avals: List[core.AbstractValue] = []\n+ for op in operands:\n+ o_spec = tf.TensorSpec((), dtype=op.dtype)\n+ comparator_spec.extend([o_spec, o_spec])\n+ o_aval = core.ShapedArray((), to_jax_dtype(op.dtype))\n+ comparator_jax_in_avals.extend([o_aval, o_aval])\n+\n+ # Use the same comparator that JAX uses when compiling to XLA, to get the\n+ # proper NaN/Inf total order, and the lexicographic ordering.\n+ # The comparator is a 2N-argument TF function, with arguments [2k] and [2k +1]\n+ # corresponding to two scalars from operand[k].\n+ def lexicographic_comparator(*tf_args: TfVal) -> TfVal:\n+ return _convert_jax_impl(\n+ lax._sort_lt_comparator, multiple_results=False)(\n+ *tf_args,\n+ _in_avals=comparator_jax_in_avals,\n+ _out_aval=core.ShapedArray((), np.bool_),\n+ num_keys=num_keys)\n+\n+ xla_comparator_computation = (\n+ tf.function(lexicographic_comparator,\n+ autograph=False).get_concrete_function(*comparator_spec))\n+ results = tfxla.variadic_sort(operands, dimension=dimension,\n+ is_stable=is_stable,\n+ comparator=xla_comparator_computation)\n+ return results\n+\ntf_impl[lax.sort_p] = _sort\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -1184,17 +1184,13 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n# I think that this is because TF is running on CPU even for GPU tests?\n\"TODO: TF non-stable multiple-array sort\",\ndevices=\"gpu\",\n- enabled=(len(harness.arg_descriptors) == 4 and not harness.params[\"is_stable\"]),\n+ enabled=(harness.params[\"num_arrays\"] > 1 and not harness.params[\"is_stable\"]),\nexpect_tf_error=False,\nskip_comparison=True),\n- missing_tf_kernel(dtypes=[np.complex64, np.complex128], devices=(\"cpu\", \"gpu\")),\n- Jax2TfLimitation(\n- \"TODO: XlaSort does not support more than 2 arrays\",\n- enabled=harness.params[\"nb_arrays\"] > 2),\n- Jax2TfLimitation(\n- \"TODO: XlaSort does not support sorting axis\",\n- enabled=harness.params[\"dimension\"] !=\n- len(np.shape(harness.arg_descriptors[0])) - 1)\n+ missing_tf_kernel(dtypes=[np.complex64, np.complex128, np.float64],\n+ devices=(\"cpu\", \"gpu\"), also_compiled=True),\n+ missing_tf_kernel(dtypes=[np.bool_],\n+ also_compiled=True),\n]\n@classmethod\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1405,44 +1405,70 @@ def _make_sort_harness(name,\ndtype=np.float32,\ndimension=0,\nis_stable=False,\n- nb_arrays=1):\n+ num_keys=1):\nif operands is None:\n- operands = [RandArg(shape, dtype) for _ in range(nb_arrays)]\n+ operands = [RandArg(shape, dtype)]\ndefine(\nlax.sort_p,\n- f\"{name}_nbarrays={nb_arrays}_shape={jtu.format_shape_dtype_string(operands[0].shape, operands[0].dtype)}_axis={dimension}_isstable={is_stable}\",\n+ f\"{name}_num_arrays={len(operands)}_shape={jtu.format_shape_dtype_string(operands[0].shape, operands[0].dtype)}_axis={dimension}_isstable={is_stable}_num_keys={num_keys}\",\nlambda *args: lax.sort_p.bind(\n- *args[:-2], dimension=args[-2], is_stable=args[-1], num_keys=1),\n- [*operands, StaticArg(dimension),\n- StaticArg(is_stable)],\n+ *args[:-3], dimension=args[-3], is_stable=args[-2], num_keys=args[-1]\n+ ), [\n+ *operands,\n+ StaticArg(dimension),\n+ StaticArg(is_stable),\n+ StaticArg(num_keys)\n+ ],\nshape=operands[0].shape,\ndimension=dimension,\ndtype=operands[0].dtype,\nis_stable=is_stable,\n- nb_arrays=nb_arrays)\n+ num_keys=num_keys,\n+ num_arrays=len(operands))\n+\n+_lax_sort_multiple_array_shape = (100,)\n+# In order to test lexicographic ordering and sorting stability, the first\n+# array contains only integers 0 and 1\n+_lax_sort_multiple_array_first_arg = (\n+ np.random.uniform(0, 2, _lax_sort_multiple_array_shape).astype(np.int32))\n# Validate dtypes\nfor dtype in jtu.dtypes.all:\n_make_sort_harness(\"dtypes\", dtype=dtype)\n# Validate dimensions\n-_make_sort_harness(\"dimensions\", dimension=1)\n+for dimension in [0, 1]:\n+ _make_sort_harness(\"dimensions\", dimension=dimension)\n# Validate stable sort\n_make_sort_harness(\"is_stable\", is_stable=True)\n# Potential edge cases\nfor operands, dimension in [\n- ([np.array([+np.inf, np.nan, -np.nan, -np.inf, 2], dtype=np.float32)], -1)\n+ ([np.array([+np.inf, np.nan, -np.nan, -np.inf, 2], dtype=np.float32)], 0)\n]:\n_make_sort_harness(\"edge_cases\", operands=operands, dimension=dimension)\n-# Validate multiple arrays\n-for nb_arrays, dtype in [\n- (2, np.float32), # equivalent to sort_key_val\n- (2, np.bool_), # unsupported\n- (3, np.float32), # unsupported\n-]:\n- _make_sort_harness(\"multiple_arrays\", nb_arrays=nb_arrays, dtype=dtype)\n+# Validate multiple arrays, num_keys, and is_stable\n+for is_stable in [False, True]:\n+ for operands in (\n+ [\n+ _lax_sort_multiple_array_first_arg,\n+ RandArg(_lax_sort_multiple_array_shape, np.int32)\n+ ],\n+ [\n+ _lax_sort_multiple_array_first_arg,\n+ RandArg(_lax_sort_multiple_array_shape, np.int32),\n+ RandArg(_lax_sort_multiple_array_shape, np.float32)\n+ ],\n+ ):\n+ for num_keys in range(1, len(operands) + 1):\n+ _make_sort_harness(\n+ \"multiple_arrays\",\n+ operands=operands,\n+ num_keys=num_keys,\n+ is_stable=is_stable,\n+ shape=_lax_sort_multiple_array_first_arg.shape,\n+ dtype=_lax_sort_multiple_array_first_arg.dtype)\ndef _make_cholesky_arg(shape, dtype, rng):\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Finish the conversion of lax.sort We were blocked until now due to limited support for the XlaSort op. Also removed the patching of the XlaPad output shape; now XlaPad has shape inference.
260,411
07.01.2021 08:23:17
-7,200
9c8ec132450c95d4ef2e8cc1fbd8b09835e750cf
[jax2tf] Fix/disable tests for non-omnistaging
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -180,7 +180,14 @@ def convert(fun: Callable, *,\ndef converted_fun(*args: TfVal) -> TfVal:\n# TODO: is there a better way to check if we are inside a transformation?\n- if config.omnistaging_enabled and not core.trace_state_clean():\n+ if config.omnistaging_enabled:\n+ if not core.trace_state_clean():\n+ raise ValueError(\"convert must be used outside all JAX transformations.\"\n+ + f\"Trace state: {core.thread_local_state.trace_state}\")\n+ else:\n+ if (core.thread_local_state.trace_state.trace_stack.downward or\n+ core.thread_local_state.trace_state.trace_stack.upward or\n+ core.thread_local_state.trace_state.substack != [core.Sublevel(0)]):\nraise ValueError(\"convert must be used outside all JAX transformations.\"\n+ f\"Trace state: {core.thread_local_state.trace_state}\")\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_test.py", "diff": "@@ -341,6 +341,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nself.TransformConvertAndCompare(f, arg, None)\nself.TransformConvertAndCompare(f, arg, \"grad\")\n+ @jtu.skip_on_flag('jax_omnistaging', False)\ndef test_convert_nullary_func(self):\n# Even nullary functions are converted to TF (as opposed to constant-folded\n# in JAX prior to conversion).\n@@ -350,6 +351,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nf_tf_graph = f_tf.get_concrete_function().graph.as_graph_def()\nself.assertIn('op: \"Sin\"', str(f_tf_graph))\n+ @jtu.skip_on_flag('jax_omnistaging', False)\ndef test_convert_of_nested_independent_jit(self):\ndef func(x):\ndef inner1(y):\n@@ -400,7 +402,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\ndict(testcase_name=f\"_{transform}\", transform=transform)\nfor transform in [\"jit\", \"jvp\", \"grad\", \"vmap\"]))\n- def test_convert_under_transform_error_non_tracer(self, transform=\"jit\"):\n+ def test_convert_under_transform_error_non_tracer(self, transform=\"vmap\"):\ndef outer(y):\nsin_1 = jax2tf.convert(jnp.sin)(1.) # Inner convert takes non-tracer arg\nreturn y + sin_1\n@@ -409,6 +411,7 @@ class Jax2TfTest(tf_test_util.JaxToTfTestCase):\nValueError, \"convert must be used outside all JAX transformations\"):\nself.TransformConvertAndCompare(outer, np.ones((4,)), transform)\n+ @jtu.skip_on_flag('jax_omnistaging', False)\ndef test_name_scope(self):\nlog = []\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Fix/disable tests for non-omnistaging
260,335
05.01.2021 08:14:16
28,800
7a9f8f96eaf3d323f9189c27cf6e36d22d26ec69
make c++ jit sensitive to global omnistaging state fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -259,7 +259,7 @@ def _cpp_jit(\nraise ValueError(\"can't specify both a device and a backend for jit, \"\nf\"got device={device} and backend={backend}.\")\n- def cache_miss(*args, **kwargs):\n+ def cache_miss(_, *args, **kwargs):\n### This first part is basically the same code as in _python_jit.\n# An alternative would be for cache_miss to accept from C++ the arguments\n# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have\n@@ -362,17 +362,20 @@ def _cpp_jit(\n\"\"\"\nreturn config.read(\"jax_disable_jit\")\n+ static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)\ncpp_jitted_f = jax_jit.jit(fun, cache_miss, get_device_info,\nget_jax_enable_x64, get_jax_disable_jit_flag,\n- static_argnums)\n+ static_argnums_)\n# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods\n@wraps(fun)\n@api_boundary\ndef f_jitted(*args, **kwargs):\n+ context = getattr(core.thread_local_state.trace_state.trace_stack,\n+ 'dynamic', None)\n# TODO(jblespiau): Move this to C++.\nif FLAGS.jax_debug_nans and not _jit_is_disabled():\n- device_arrays = cpp_jitted_f(*args, **kwargs)\n+ device_arrays = cpp_jitted_f(context, *args, **kwargs)\ntry:\nxla.check_nans(xla.xla_call_p, [\nda.device_buffer\n@@ -384,9 +387,11 @@ def _cpp_jit(\nassert FLAGS.jax_debug_nans # compiled_fun can only raise in this case\nprint(\"Invalid nan value encountered in the output of a C++-jit \"\n\"function. Calling the de-optimized version.\")\n- return cache_miss(*args, **kwargs)[0] # probably won't return\n- else:\n+ return cache_miss(context, *args, **kwargs)[0] # probably won't return\n+ elif _jit_is_disabled():\nreturn cpp_jitted_f(*args, **kwargs)\n+ else:\n+ return cpp_jitted_f(context, *args, **kwargs)\nf_jitted._cpp_jitted_f = cpp_jitted_f\nreturn f_jitted\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -506,6 +506,22 @@ class CPPJitTest(jtu.JaxTestCase):\nf\"explicit inner-jit backend specification cpu.\"):\nf(1.)\n+ def test_omnistaging(self):\n+ # See https://github.com/google/jax/issues/5206\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ key_list = [None]\n+\n+ def init():\n+ key, subkey = jax.random.split(key_list[0])\n+ key_list[0] = key\n+ return jax.random.normal(subkey, ())\n+\n+ key_list[0] = np.array([2384771982, 3928867769], dtype=np.uint32)\n+ init()\n+ self.jit(init)()\n+ self.assertIsInstance(key_list[0], core.Tracer)\nclass PythonJitTest(CPPJitTest):\n" } ]
Python
Apache License 2.0
google/jax
make c++ jit sensitive to global omnistaging state fixes #5206 Co-authored-by: Jean-Baptiste Lespiau <jblespiau@google.com>
260,335
08.01.2021 12:13:09
28,800
3f85b300c8b2770dd0aef0c78b883b4820f27412
temporary skip test
[ { "change_type": "MODIFY", "old_path": "tests/random_test.py", "new_path": "tests/random_test.py", "diff": "@@ -954,6 +954,7 @@ class LaxRandomTest(jtu.JaxTestCase):\nself._CompileAndCheck(random.PRNGKey, args_maker)\ndef test_prng_errors(self):\n+ raise SkipTest(\"temporary skip while mattjj debugs\") # TODO(mattjj): fix!\nseed = np.iinfo(np.uint64).max\nwith self.assertRaises(OverflowError):\nrandom.PRNGKey(seed)\n" } ]
Python
Apache License 2.0
google/jax
temporary skip test PiperOrigin-RevId: 350812117
260,631
12.01.2021 13:46:52
28,800
47f254d252a0549e8174727e62912c86cd17f9bf
Copybara import of the project: by Chris Jones [JAX] Use XLA AllGather op for GPU (when supported).
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -670,6 +670,10 @@ def _expand(dim, size, index, x):\nout = lax.full(shape, lax._const(x, 0))\nreturn lax.dynamic_update_index_in_dim(out, x, index, dim)\n+def _allgather(x, dim, size, index, axis_name, axis_index_groups=None):\n+ outs = tree_util.tree_map(partial(_expand, dim, size, index), x)\n+ return psum(outs, axis_name, axis_index_groups=axis_index_groups)\n+\ndef all_gather(x, axis_name, *, axis_index_groups=None):\n\"\"\"Gather values of x across all replicas.\n@@ -722,48 +726,17 @@ def all_gather(x, axis_name, *, axis_index_groups=None):\n[[12. 13. 14. 15.]\n[ 4. 5. 6. 7.]]\n\"\"\"\n- axis_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n- # The all_gather primitive doesn't work when omni-staging is disabled.\n- if not config.omnistaging_enabled:\n- return _all_gather_via_psum(x, all_gather_dimension=0, axis_name=axis_name,\n- axis_index_groups=axis_index_groups, axis_size=axis_size)\n- return all_gather_p.bind(x, all_gather_dimension=0, axis_name=axis_name,\n- axis_index_groups=axis_index_groups, axis_size=axis_size)\n-\n-def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n+\nindex = axis_index(axis_name)\nif axis_index_groups is not None:\nindices = np.array(axis_index_groups).flatten()\naxis_index_to_group_index = indices.argsort() % len(axis_index_groups[0])\nindex = lax_numpy.array(axis_index_to_group_index)[index]\n- outs = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index), x)\n- return psum(outs, axis_name, axis_index_groups=axis_index_groups)\n-def _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, axis_env, platform):\n- # TODO(cjfj): Enable this for TPU also?\n- if (platform == 'gpu') and (all_gather_dimension == 0):\n- new_shape = list(c.get_shape(x).dimensions())\n- new_shape.insert(all_gather_dimension, 1)\n- broadcast_dimensions = [i for i in range(len(new_shape)) if i != all_gather_dimension]\n- x = xops.BroadcastInDim(x, new_shape, broadcast_dimensions)\n- replica_groups = _replica_groups(axis_env, axis_name, axis_index_groups)\n- return xops.AllGather(x, all_gather_dimension=all_gather_dimension, shard_count=axis_size,\n- replica_groups=xc.make_replica_groups(replica_groups))\n- else:\n- lowering = xla.lower_fun(_all_gather_via_psum, multiple_results=False, parallel=True)\n- return 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-\n-def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n- x_aval = raise_to_shaped(x)\n- new_shape = list(x_aval.shape)\n- new_shape.insert(all_gather_dimension, axis_size)\n- return ShapedArray(new_shape, x_aval.dtype)\n-\n-all_gather_p = core.Primitive('all_gather')\n-all_gather_p.def_abstract_eval(_all_gather_abstract_eval)\n-xla.parallel_translations[all_gather_p] = _all_gather_translation_rule\n-pxla.multi_host_supported_collectives.add(all_gather_p)\n+ axis_size = psum(1, axis_name, axis_index_groups=axis_index_groups)\n+\n+ return _allgather(x, 0, axis_size, index, axis_name, axis_index_groups)\n+\ndef _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\naxis_pos = list(axis_env.names).index(axis_name)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -828,7 +828,7 @@ tf_not_yet_impl = [\nlax.after_all_p, lax_parallel.all_to_all_p, lax.create_token_p,\nlax.infeed_p, lax.outfeed_p, lax_parallel.pmax_p,\nlax_parallel.pmin_p, lax_parallel.ppermute_p, lax_parallel.psum_p,\n- lax_parallel.axis_index_p, lax_parallel.pdot_p, lax_parallel.all_gather_p,\n+ lax_parallel.axis_index_p, lax_parallel.pdot_p,\npxla.xla_pmap_p,\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- 474fdfcde05b4e5f17cfcb087a832d37c41ddffe by Chris Jones <cjfj@google.com>: [JAX] Use XLA AllGather op for GPU (when supported). PiperOrigin-RevId: 351440599
260,444
11.12.2020 13:29:35
-3,600
f443e19141c3d04a6e2947a0dcde8d23039af786
JVP rule for SVD works now for complex input.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/linalg.py", "new_path": "jax/_src/lax/linalg.py", "diff": "@@ -1171,7 +1171,6 @@ def svd_jvp_rule(primals, tangents, full_matrices, compute_uv):\nraise NotImplementedError(\n\"Singular value decomposition JVP not implemented for full matrices\")\n- k = s.shape[-1]\nUt, V = _H(U), _H(Vt)\ns_dim = s[..., None, :]\ndS = jnp.matmul(jnp.matmul(Ut, dA), V)\n@@ -1180,19 +1179,26 @@ def svd_jvp_rule(primals, tangents, full_matrices, compute_uv):\nif not compute_uv:\nreturn (s,), (ds,)\n- F = 1 / (jnp.square(s_dim) - jnp.square(_T(s_dim)) + jnp.eye(k, dtype=A.dtype))\n- F = F - jnp.eye(k, dtype=A.dtype)\n- dSS = s_dim * dS\n- SdS = _T(s_dim) * dS\n- dU = jnp.matmul(U, F * (dSS + _T(dSS)))\n- dV = jnp.matmul(V, F * (SdS + _T(SdS)))\n+ s_diffs = jnp.square(s_dim) - jnp.square(_T(s_dim))\n+ s_diffs_zeros = jnp.eye(s.shape[-1], dtype=A.dtype) # jnp.ones((), dtype=A.dtype) * (s_diffs == 0.) # is 1. where s_diffs is 0. and is 0. everywhere else\n+ F = 1 / (s_diffs + s_diffs_zeros) - s_diffs_zeros\n+ dSS = s_dim * dS # dS.dot(jnp.diag(s))\n+ SdS = _T(s_dim) * dS # jnp.diag(s).dot(dS)\n+\n+ s_zeros = jnp.ones((), dtype=A.dtype) * (s == 0.)\n+ s_inv = 1 / (s + s_zeros) - s_zeros\n+ s_inv_mat = jnp.vectorize(jnp.diag, signature='(k)->(k,k)')(s_inv)\n+ dUdV_diag = .5 * (dS - _H(dS)) * s_inv_mat\n+ dU = jnp.matmul(U, F * (dSS + _H(dSS)) + dUdV_diag)\n+ dV = jnp.matmul(V, F * (SdS + _H(SdS)))\nm, n = A.shape[-2:]\nif m > n:\ndU = dU + jnp.matmul(jnp.eye(m, dtype=A.dtype) - jnp.matmul(U, Ut), jnp.matmul(dA, V)) / s_dim\nif n > m:\ndV = dV + jnp.matmul(jnp.eye(n, dtype=A.dtype) - jnp.matmul(V, Vt), jnp.matmul(_H(dA), U)) / s_dim\n- return (s, U, Vt), (ds, dU, _T(dV))\n+\n+ return (s, U, Vt), (ds, dU, _H(dV))\ndef _svd_cpu_gpu_translation_rule(gesvd_impl, c, operand, full_matrices, compute_uv):\n" }, { "change_type": "MODIFY", "old_path": "tests/linalg_test.py", "new_path": "tests/linalg_test.py", "diff": "@@ -559,12 +559,35 @@ class NumpyLinalgTest(jtu.JaxTestCase):\nself._CompileAndCheck(partial(jnp.linalg.svd, full_matrices=full_matrices, compute_uv=compute_uv),\nargs_maker)\n- if not (compute_uv and full_matrices):\n+ if not compute_uv:\nsvd = partial(jnp.linalg.svd, full_matrices=full_matrices,\ncompute_uv=compute_uv)\n# TODO(phawkins): these tolerances seem very loose.\n+ if dtype == np.complex128:\n+ jtu.check_jvp(svd, partial(jvp, svd), (a,), rtol=1e-4, atol=1e-4, eps=1e-8)\n+ else:\njtu.check_jvp(svd, partial(jvp, svd), (a,), rtol=5e-2, atol=2e-1)\n+ if jtu.device_under_test() == \"tpu\":\n+ raise unittest.SkipTest(\"TPU matmul does not have enough precision\")\n+ # TODO(frederikwilde): Find the appropriate precision to use for this test on TPUs.\n+\n+ if compute_uv and (not full_matrices):\n+ b, = args_maker()\n+ def f(x):\n+ u, s, v = jnp.linalg.svd(\n+ a + x * b,\n+ full_matrices=full_matrices,\n+ compute_uv=compute_uv)\n+ vdiag = jnp.vectorize(jnp.diag, signature='(k)->(k,k)')\n+ return jnp.matmul(jnp.matmul(u, vdiag(s)), v).real\n+ _, t_out = jvp(f, (1.,), (1.,))\n+ if dtype == np.complex128:\n+ atol = 1e-13\n+ else:\n+ atol = 5e-4\n+ self.assertArraysAllClose(t_out, b.real, atol=atol)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_fullmatrices={}\".format(\njtu.format_shape_dtype_string(shape, dtype), full_matrices),\n" } ]
Python
Apache License 2.0
google/jax
JVP rule for SVD works now for complex input.
260,403
13.01.2021 12:52:28
28,800
2ca247f43ed898e4c9d683c97cedf921d0601362
Fix pdot translation rule. This concerns the direct pdot translation rule, which is not used during spmd lowering.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -828,13 +828,15 @@ batching.primitive_batchers[pdot_p] = _pdot_vmap_batching_rule\ndef _pdot_translation_rule(c, x, y, *, axis_name, pos_contract, pos_batch,\naxis_env, platform):\n- assert axis_name\nlocal_out = lax._dot_general_translation_rule(\nc, x, y, dimension_numbers=[pos_contract, pos_batch], precision=None)\n+ if axis_name:\nout_tup = xla.parallel_translations[psum_p](\nc, local_out, axis_name=axis_name, axis_index_groups=None,\naxis_env=axis_env, platform=platform)\nout, = xla.xla_destructure(c, out_tup)\n+ else:\n+ out = local_out\nreturn out\nxla.parallel_translations[pdot_p] = _pdot_translation_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -283,6 +283,26 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n+ @ignore_xmap_warning()\n+ @with_mesh([('r1', 2)])\n+ def testPdotBatchingShardUncontractedDim(self):\n+ def f(x, y):\n+ return lax.pdot(x, y, 'i')\n+\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(2, 3, 8)\n+ y = rng.randn(2, 8, 5)\n+\n+ f_mapped = xmap(f,\n+ in_axes=[{0: 'j', 2: 'i'}, {0: 'j', 1: 'i'}],\n+ out_axes=['j', ...],\n+ axis_resources={'j': 'r1'})\n+\n+ z = f_mapped(x, y)\n+\n+ self.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n+\n+\nclass XMapErrorTest(jtu.JaxTestCase):\n@ignore_xmap_warning()\n" } ]
Python
Apache License 2.0
google/jax
Fix pdot translation rule. This concerns the direct pdot translation rule, which is not used during spmd lowering.
260,631
13.01.2021 13:02:53
28,800
9c2aed32eff652973cac1b02cc409e91f9fbefbf
Add # pytype: disable=import-error to a couple of import statements to allow cpu=ppc builds (the imported modules aren't currently linked into jaxlib when building for ppc).
[ { "change_type": "MODIFY", "old_path": "jax/lib/__init__.py", "new_path": "jax/lib/__init__.py", "diff": "@@ -59,7 +59,7 @@ else:\njax_jit = xla_client._xla.jax_jit\ntry:\n- from jaxlib import cusolver\n+ from jaxlib import cusolver # pytype: disable=import-error\nexcept ImportError:\ncusolver = None\n@@ -69,7 +69,7 @@ except ImportError:\nrocsolver = None\ntry:\n- from jaxlib import cuda_prng\n+ from jaxlib import cuda_prng # pytype: disable=import-error\nexcept ImportError:\ncuda_prng = None\n" } ]
Python
Apache License 2.0
google/jax
Add # pytype: disable=import-error to a couple of import statements to allow --cpu=ppc builds (the imported modules aren't currently linked into jaxlib when building for ppc). PiperOrigin-RevId: 351648541
260,287
11.01.2021 10:44:00
0
66f3deb97853d2eb20e3ca6ada3bfb99f0fc9fa1
Make xmapped functions with no axis resources callable more than once When no XLA lowering was involved (i.e. when using a purely vectorized schedule), we used to return `f.call_wrapped` as the xmapped function. This obviously didn't end well when someone tried to call it multiple times, which this patch should fix.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -304,7 +304,9 @@ def make_xmap_callable(fun: lu.WrappedFun,\nEXPERIMENTAL_SPMD_LOWERING,\n*in_avals)\nelse:\n- return f.call_wrapped\n+ # We have to trace again, because `f` is a linear function, so we can't just return it.\n+ final_jaxpr, _, final_consts = pe.trace_to_jaxpr_final(f, mapped_in_avals)\n+ return core.jaxpr_as_fun(core.ClosedJaxpr(jaxpr, consts))\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -25,6 +25,7 @@ from absl.testing import absltest\nfrom absl.testing import parameterized\nfrom functools import partial\n+import jaxlib\nimport jax\nimport jax.numpy as jnp\nfrom jax import test_util as jtu\n@@ -65,6 +66,8 @@ def tearDownModule():\n@curry\ndef with_mesh(named_shape, f):\n+ if not named_shape:\n+ return f\ndef new_f(*args, **kwargs):\naxis_names, shape = unzip2(named_shape)\nsize = np.prod(shape)\n@@ -93,6 +96,8 @@ def use_spmd_lowering(f):\nclass XMapTest(jtu.JaxTestCase):\ndef setUp(self):\n+ if jaxlib.__version__.split('.') < ['0', '1', '58']:\n+ raise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n@@ -302,6 +307,28 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n+ for name, mesh, axis_resources in (\n+ ('', (), ()),\n+ ('Mesh', (('x', 2),), (('i', 'x'),))\n+ ))\n+ @ignore_xmap_warning()\n+ def testMultipleCalls(self, mesh, axis_resources):\n+ def f(x, y):\n+ return x * y\n+\n+ @with_mesh(mesh)\n+ def run_test():\n+ f_mapped = xmap(f,\n+ in_axes=(['i', ...], ['j', ...]),\n+ out_axes=['i', 'j', ...],\n+ axis_resources=dict(axis_resources))\n+ x = jnp.arange(10).reshape(2, 5)\n+ for i in range(10):\n+ f_mapped(x, x)\n+ run_test()\n+\nclass XMapErrorTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Make xmapped functions with no axis resources callable more than once When no XLA lowering was involved (i.e. when using a purely vectorized schedule), we used to return `f.call_wrapped` as the xmapped function. This obviously didn't end well when someone tried to call it multiple times, which this patch should fix.
260,411
14.01.2021 14:11:52
-3,600
555a215cfb12f09dc70dce275f250a2557ffc339
[loops] Extend loops with support for pytrees Also improve error checking and error messages.
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -24,8 +24,17 @@ jax 0.2.9 (Unreleased)\nThese are the release notes for JAX.\n+next version\n+-------------\n+* `GitHub commits <https://github.com/google/jax/compare/jax-v0.2.8...jax-v0.2.9>`_.\n+\n+* New features:\n+\n+ * Extend the `jax.experimental.loops` module with support for pytrees. Improved\n+ error checking and error messages.\n+\njax 0.2.8 (January 12 2021)\n-----------------------\n+---------------------------\n* `GitHub commits <https://github.com/google/jax/compare/jax-v0.2.7...jax-v0.2.8>`_.\n* New features:\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/loops.py", "new_path": "jax/experimental/loops.py", "diff": "@@ -27,7 +27,7 @@ For example, in the following code the `for` loop is unrolled during JAX tracing\nif i % 2 == 0:\narr[i] += 1.\n-In order to capture the structured control-flow one has to use the higher-order\n+In order to capture the structured control-flow one can use the higher-order\nJAX operations, which require you to express the body of the loops and\nconditionals as functions, and the array updates using a functional style that\nreturns an updated array, e.g.::\n@@ -42,7 +42,7 @@ returns an updated array, e.g.::\nlambda arr1: arr1)\narr = lax.fori_loop(0, arr.shape[0], loop_body, arr)\n-The default notation quickly gets unreadable with deeper nested loops.\n+This API quickly gets unreadable with deeper nested loops.\nWith the utilities in this module you can write loops and conditionals that\nlook closer to plain Python, as long as you keep the loop-carried state in a\nspecial `loops.scope` object and use `for` loops over special\n@@ -71,7 +71,8 @@ Notes:\n* Only scope data (stored in fields of the scope object) is functionalized.\nAll other state, e.g., in other Python variables, will not be considered as\nbeing part of the loop output. All references to the mutable state should be\n- through the scope: `s.arr`.\n+ through the scope, e.g., `s.arr`.\n+ * The scope fields can be pytrees, and can themselves be mutable data structures.\n* Conceptually, this model is still \"functional\" in the sense that a loop over\na `Scope.range` behaves as a function whose input and output is the scope data.\n* Scopes should be passed down to callees that need to use loop\n@@ -89,6 +90,8 @@ Restrictions:\nstored in fields of the scope object.\n* No new mutable state can be created inside a loop to be functionalized.\nAll mutable state must be created outside all loops and conditionals.\n+ * Once the loop starts all updates to loop state must be with new values of the\n+ same abstract values as the values on loop start.\n* For a `while` loop, the conditional function is not allowed to modify the\nscope state. This is a checked error. Also, for `while` loops the `grad`\ntransformation does not work. An alternative that allows `grad` is a bounded\n@@ -103,13 +106,11 @@ Transformations:\nFor usage example, see tests/loops_test.py.\n\"\"\"\n-\n-import copy\nfrom functools import partial\nimport itertools\nimport numpy as np\nimport traceback\n-from typing import Any, List, cast\n+from typing import Any, Dict, List, cast\nfrom jax import lax, core\nfrom jax._src.lax import control_flow as lax_control_flow\n@@ -134,7 +135,11 @@ class Scope(object):\n\"\"\"\ndef __init__(self):\n- self._mutable_state = {} # state to be functionalized, indexed by name.\n+ # state to be functionalized, indexed by names, can be pytrees\n+ self._mutable_state: Dict[str, Any] = {}\n+ # the pytrees of abstract values; set when the loop starts.\n+ self._mutable_state_aval: Dict[str, core.AbstractValue] = {}\n+\nself._active_ranges = [] # stack of active ranges, last one is the innermost.\nself._count_subtraces = 0 # How many net started subtraces, for error recovery\n@@ -247,12 +252,21 @@ class Scope(object):\nCalled for *all* attribute setting.\n\"\"\"\n- if key in [\"_active_ranges\", \"_mutable_state\", \"_count_subtraces\"]:\n+ if key in [\"_active_ranges\", \"_mutable_state\", \"_mutable_state_aval\", \"_count_subtraces\"]:\nobject.__setattr__(self, key, value)\nelse:\n- if self._active_ranges and key not in self._mutable_state:\n+ if self._active_ranges:\n+ if key not in self._mutable_state:\nraise ValueError(\n\"New mutable state '{}' cannot be created inside a loop.\".format(key))\n+ assert key in self._mutable_state_aval\n+ old_aval = self._mutable_state_aval[key]\n+ flat_values, flat_tree = tree_util.tree_flatten(value)\n+ new_aval = flat_tree.unflatten(safe_map(_BodyTracer.abstractify, flat_values))\n+ if old_aval != new_aval:\n+ msg = (f\"Mutable state '{key}' is updated with new abstract value \"\n+ f\"{new_aval}, which is different from previous one {old_aval}\")\n+ raise TypeError(msg)\nself._mutable_state[key] = value\ndef __enter__(self):\n@@ -319,15 +333,14 @@ class _BodyTracer(object):\ncast(List[Any], traceback.extract_stack()[:-2]))\n# Next are state kept from the start of the first iteration to the end of the iteration.\n- self.carried_state_initial = {}\n+ # List of scope fields carried through the loop\n+ self.carried_state_names: List[str] = None\n+ self.carried_state_initial = {} # Copy of the initial values of state, before loop starts\n# The parameters that were created for state upon entering an arbitrary iteration.\n- self.carried_state_vars = {}\n+ self.carried_state_vars = {} # For each state, the list of Tracer variables introduced\n+ # when starting to trace the loop body.\nself.trace = None\n- # List of scope fields carried through the loop\n- self.carried_state_names = None\n- self.init_tree = None # The PyTreeDef corresponding to carried_state_names\n- self.init_vals = None # The values corresponding to self.init_tree\ndef location(self):\n\"\"\"A multiline string representing the source location of the range.\"\"\"\n@@ -357,20 +370,22 @@ class _BodyTracer(object):\ndef start_tracing_body(self):\n\"\"\"Called upon starting the tracing of the loop body.\"\"\"\n- # Make a copy of the current value of the mutable state\n- self.carried_state_initial = copy.copy(self.scope._mutable_state)\n- # The entire state is carried.\n- self.carried_state_names = sorted(self.scope._mutable_state.keys())\n-\n# TODO: This is the first part of partial_eval.trace_to_subjaxpr. Share.\nself.trace = self.scope.start_subtrace()\n+ # The entire state is carried.\n+ self.carried_state_names = sorted(self.scope._mutable_state.keys())\n+ for key in self.carried_state_names:\n+ init_val = self.scope._mutable_state[key]\n+ flat_init_vals, init_tree = tree_util.tree_flatten(init_val)\n+ flat_init_avals = safe_map(_BodyTracer.abstractify, flat_init_vals)\n+ flat_init_pvals = safe_map(pe.PartialVal.unknown, flat_init_avals)\n+ flat_init_vars = safe_map(self.trace.new_arg, flat_init_pvals)\n+ self.carried_state_vars[key] = flat_init_vars\n# Set the scope._mutable_state to new tracing variables.\n- for key, initial in self.carried_state_initial.items():\n- mt_aval = _BodyTracer.abstractify(initial)\n- mt_pval = pe.PartialVal.unknown(mt_aval)\n- mt_var = self.trace.new_arg(mt_pval)\n- self.carried_state_vars[key] = mt_var\n- self.scope._mutable_state[key] = mt_var\n+ self.scope._mutable_state[key] = init_tree.unflatten(flat_init_vars)\n+ self.scope._mutable_state_aval[key] = init_tree.unflatten(flat_init_avals)\n+ # Make a copy of the initial state by unflattening the flat_init_vals\n+ self.carried_state_initial[key] = init_tree.unflatten(flat_init_vals)\nindex_var_aval = _BodyTracer.abstractify(0)\nindex_var_pval = pe.PartialVal.unknown(index_var_aval)\n@@ -382,15 +397,26 @@ class _BodyTracer(object):\n# for the scope state (carried_state_names) and returns the values for the\n# same state fields after one execution of the body. For some of the ranges,\n# e.g., scope.range, the function will also take the index_var as last parameter.\n- in_tracers = [self.carried_state_vars[ms] for ms in self.carried_state_names]\n+ in_tracers = tuple(itertools.chain(*[self.carried_state_vars[ms] for ms in self.carried_state_names]))\nif self.loop_builder.can_use_index_var():\n- in_tracers += [self._index_var]\n+ in_tracers += (self._index_var,)\n# Make the jaxpr for the body of the loop\n# TODO: See which mutable state was changed in the one iteration.\n# For now, we assume all state changes.\n- body_out_tracers = tuple([self.scope._mutable_state[ms]\n- for ms in self.carried_state_names])\n+ body_out_tracers = []\n+ for key in self.carried_state_names:\n+ new_val = self.scope._mutable_state[key]\n+ flat_new_values, flat_new_tree = tree_util.tree_flatten(new_val)\n+ body_out_tracers.extend(flat_new_values)\n+ assert key in self.scope._mutable_state_aval\n+ old_aval = self.scope._mutable_state_aval[key]\n+ new_aval = flat_new_tree.unflatten(safe_map(_BodyTracer.abstractify, flat_new_values))\n+ if old_aval != new_aval:\n+ msg = (f\"Mutable state '{key}' had at the end of the loop body new abstract value \"\n+ f\"{new_aval}, which is different from initial one {old_aval}\")\n+ raise TypeError(msg)\n+\ntry:\n# If the body actually uses the index variable, and is not allowed to\n# (e.g., cond_range and while_range), then in_tracers will not contain\n@@ -411,6 +437,7 @@ class _BodyTracer(object):\ncarried_init_val = tuple([self.carried_state_initial[ms]\nfor ms in self.carried_state_names])\ncarried_init_vals, carried_tree = tree_util.tree_flatten(carried_init_val)\n+ assert len(carried_init_vals) == len(body_out_tracers)\ncarried_out_vals = self.loop_builder.build_output_vals(\nself.scope, self.carried_state_names, carried_tree,\n@@ -424,7 +451,7 @@ class _BodyTracer(object):\n@staticmethod\ndef abstractify(x):\n- return core.raise_to_shaped(core.get_aval(x))\n+ return core.raise_to_shaped(core.get_aval(x), weak_type=False)\n@staticmethod\ndef trace_to_jaxpr_finalize(in_tracers, out_tracers, trace, instantiate=True):\n" }, { "change_type": "MODIFY", "old_path": "tests/loops_test.py", "new_path": "tests/loops_test.py", "diff": "from absl.testing import absltest\nimport numpy as np\nimport re\n-import unittest\nfrom jax import api, lax, ops\nfrom jax import numpy as jnp\n@@ -111,6 +110,33 @@ class LoopsTest(jtu.JaxTestCase):\ny = jnp.array([[4.], [5.], [6.]], dtype=jnp.float32) # 3x1\nself.assertAllClose(jnp.matmul(x, y), matmul(x, y))\n+ def test_loop_pytree(self):\n+ # The state elements can be pytrees\n+ def accum_even_odd(n):\n+ with loops.Scope() as s:\n+ s.state = dict(even=0., odd=0.) # accumulate even and odd incremenents\n+ s.incr = (1., 10.) # even and odd increment\n+ for i in s.range(n):\n+ for _ in s.cond_range(i % 2 == 0): # Conditionals are also sugared as loops with 0 or 1 iterations\n+ s.state[\"even\"] += s.incr[0]\n+ for _ in s.cond_range(i % 2 != 0): # Conditionals are also sugared as loops with 0 or 1 iterations\n+ s.state[\"odd\"] += s.incr[1]\n+ return s.state\n+\n+ res = accum_even_odd(20)\n+ self.assertAllClose(dict(even=10., odd=100.), res)\n+\n+ def test_loop_mutable(self):\n+ # The state elements can be in nested mutable state\n+ def add_up_to(n):\n+ with loops.Scope() as s:\n+ s.state = [0.]\n+ for i in s.range(n):\n+ s.state[0] += i\n+ return s.state[0]\n+\n+ self.assertAllClose(190., add_up_to(20))\n+\ndef test_reuse_range(self):\n\"\"\"Ranges can be reused, as long as not nested in each other.\"\"\"\ndef f_op():\n@@ -273,8 +299,62 @@ class LoopsTest(jtu.JaxTestCase):\n\"New mutable state 'other_state' cannot be created inside a loop.\"):\nf_op(2.)\n+ def test_error_update_wrong_aval(self):\n+ \"\"\"Cannot update state in the loop with wrong aval.\"\"\"\n+ def f_op():\n+ with loops.Scope() as s:\n+ r1 = s.range(5)\n+ s.out = np.int32(0)\n+ for _ in r1:\n+ s.out += np.float32(1.) # Update with wrong type\n+ return s.out\n+\n+ with self.assertRaisesRegex(TypeError,\n+ \"Mutable state 'out' is updated with new abstract value\"):\n+ f_op()\n+\n+ def test_error_update_wrong_aval_in_mutable(self):\n+ \"\"\"Cannot update state in the loop with wrong aval.\"\"\"\n+ def f_op():\n+ with loops.Scope() as s:\n+ r1 = s.range(5)\n+ s.out = [np.int32(0)]\n+ for _ in r1:\n+ s.out[0] = np.float32(1.) # Update with wrong type, inside mutable state\n+ return s.out\n+\n+ with self.assertRaisesRegex(TypeError,\n+ \"Mutable state 'out' had at the end of the loop body new abstract value\"):\n+ f_op()\n+\n+ def test_update_aval_before_loop(self):\n+ \"\"\"It is Ok to change the aval before the loopl.\"\"\"\n+ def f_op():\n+ with loops.Scope() as s:\n+ r1 = s.range(5)\n+ s.out = np.int32(0)\n+ s.out = np.float32(0)\n+ for _ in r1:\n+ s.out += np.float32(1.)\n+ return s.out\n+\n+ self.assertAllClose(np.float32(5.), f_op())\n+\n+ def test_error_update_wrong_pytree(self):\n+ \"\"\"Cannot update state in the loop with wrong aval.\"\"\"\n+ def f_op():\n+ with loops.Scope() as s:\n+ r1 = s.range(1)\n+ s.out = 0\n+ for _ in r1:\n+ s.out = (s.out, 1) # Update with wrong pytree\n+ return s.out\n+\n+ with self.assertRaisesRegex(TypeError,\n+ \"Mutable state 'out' is updated with new abstract value\"):\n+ f_op()\n+\ndef test_error_range_ends_static(self):\n- raise unittest.SkipTest(\"broken by omnistaging\") # TODO(mattjj,gnecula): update\ndef f_op(start, end, inc):\nwith loops.Scope() as s:\ns.out = 0.\n" } ]
Python
Apache License 2.0
google/jax
[loops] Extend loops with support for pytrees Also improve error checking and error messages.
260,411
14.01.2021 21:35:42
-7,200
042aae732507d0c024240e62071b3b7977c02c2d
[host_callback] Fix bug when id_tap takes no arguments but has a result. Fixes:
[ { "change_type": "MODIFY", "old_path": "jax/experimental/host_callback.py", "new_path": "jax/experimental/host_callback.py", "diff": "@@ -461,9 +461,11 @@ def id_tap(tap_func, arg, *, result=None, tap_with_device=False, **kwargs):\n# Return the results, but add a dependency on the call, to ensure it\n# is kept in the graph.\ncall_flat_results, _ = pytree.flatten(call_res)\n- assert call_flat_results\n+ if call_flat_results:\ncall_flat_results = [id_tap_dep_p.bind(r, call_flat_results[0])\nfor r in flat_results]\n+ else:\n+ call_flat_results = flat_results\nreturn result_treedef.unflatten(call_flat_results)\nelse:\nreturn call_res\n" }, { "change_type": "MODIFY", "old_path": "tests/host_callback_test.py", "new_path": "tests/host_callback_test.py", "diff": "@@ -259,6 +259,33 @@ class HostCallbackIdTapTest(jtu.JaxTestCase):\n9.00 )\"\"\", testing_stream.output)\ntesting_stream.reset()\n+ def test_tap_with_result_no_arg(self):\n+ def tap_func(arg, transforms):\n+ testing_stream.write(f\"called tap_func with {arg}\")\n+\n+ def func2(x):\n+ x1 = hcb.id_tap(tap_func, None, result=x)\n+ return x1\n+\n+ self.assertEqual(3., func2(3.))\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"called tap_func with None\",\n+ testing_stream.output)\n+ testing_stream.reset()\n+\n+ def test_tap_result_unused(self):\n+ def tap_func(arg, transforms):\n+ testing_stream.write(f\"called tap_func with {arg}\")\n+ def func2(x):\n+ hcb.id_tap(tap_func, None)\n+ return x\n+\n+ self.assertEqual(3., func2(3.))\n+ hcb.barrier_wait()\n+ assertMultiLineStrippedEqual(self, \"called tap_func with None\",\n+ testing_stream.output)\n+ testing_stream.reset()\n+\ndef test_tap_with_device(self):\ndef func2(x):\nx1 = hcb.id_print((x * 2., x * 3.), result=x * 4.,\n" } ]
Python
Apache License 2.0
google/jax
[host_callback] Fix bug when id_tap takes no arguments but has a result. Fixes: #5414
260,411
18.09.2020 11:59:20
-10,800
66ad382112ee15dece2317c00cba288785e566bb
[jax2tf] Add support for Add for uint32
[ { "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\n-*Last generated on (YYYY-MM-DD): 2021-01-07*\n+*Last generated on (YYYY-MM-DD): 2021-01-15*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -54,7 +54,7 @@ More detailed information can be found in the\n| acos | TF error: op not defined for dtype | bfloat16, complex64, float16 | cpu, gpu | eager, graph |\n| acosh | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| add | TF error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n-| add | TF error: op not defined for dtype | uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n+| add | TF error: op not defined for dtype | uint16 | cpu, gpu, tpu | compiled, eager, graph |\n| add_any | TF error: op not defined for dtype | uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| asin | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| asin | TF error: op not defined for dtype | complex | 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": "@@ -841,7 +841,11 @@ except AttributeError:\npass\ntf_impl[ad_util.stop_gradient_p] = tf.stop_gradient\ntf_impl[ad_util.zeros_like_p] = tf.zeros_like\n-tf_impl[ad_util.add_jaxvals_p] = tf.math.add\n+\n+def _add(x: TfVal, y: TfVal) -> TfVal:\n+ return tf.raw_ops.AddV2(x=x, y=y)\n+\n+tf_impl[ad_util.add_jaxvals_p] = _add\ntf_impl[xla.device_put_p] = lambda x, device=None: x\ntf_impl[lax.neg_p] = tf.math.negative\n@@ -922,7 +926,7 @@ tf_impl[lax.conj_p] = _conj\ntf_impl[lax.real_p] = tf.math.real\ntf_impl[lax.imag_p] = tf.math.imag\n-tf_impl[lax.add_p] = tf.math.add\n+tf_impl[lax.add_p] = _add\ntf_impl[lax.sub_p] = tf.math.subtract\ntf_impl[lax.mul_p] = tf.math.multiply\n@@ -1453,7 +1457,7 @@ tf_impl[lax.argmin_p] = functools.partial(_argminmax, tf.math.argmin)\ntf_impl[lax.argmax_p] = functools.partial(_argminmax, tf.math.argmax)\n-_add_fn = tf.function(tf.math.add, autograph=False)\n+_add_fn = tf.function(_add, autograph=False)\n_ge_fn = tf.function(tf.math.greater_equal, autograph=False)\ndef _select_and_gather_add(tangents: TfVal,\n@@ -1717,7 +1721,7 @@ def _get_min_identity(tf_dtype):\n# pylint: disable=protected-access\ntf_impl_with_avals[lax.reduce_window_sum_p] = (\n- functools.partial(_specialized_reduce_window, tf.math.add, lambda x: 0,\n+ functools.partial(_specialized_reduce_window, _add, lambda x: 0,\nname=\"reduce_window_sum\"))\ntf_impl_with_avals[lax.reduce_window_min_p] = (\nfunctools.partial(_specialized_reduce_window, tf.math.minimum,\n@@ -1775,18 +1779,10 @@ def _select_and_scatter_add(source, operand, *, select_prim, window_dimensions,\ntf_impl_with_avals[lax.select_and_scatter_add_p] = _select_and_scatter_add\ndef _threefry2x32_jax_impl(*args: TfVal, _in_avals, _out_aval):\n- # We use the random._threefry2x32_lowering, but since add is not implemented\n- # for uint32, we cast to int32 and back.\n- args_cast = tuple([tf.cast(a, tf.int32) for a in args])\n- _in_avals_cast = tuple(core.ShapedArray(in_aval.shape, np.int32)\n- for in_aval in _in_avals)\n- _out_aval_cast = tuple(core.ShapedArray(out_aval.shape, np.int32)\n- for out_aval in _out_aval)\nres = _convert_jax_impl(\nfunctools.partial(jax._src.random._threefry2x32_lowering,\nuse_rolled_loops=False),\n- multiple_results=True)(*args_cast, _in_avals=_in_avals_cast, _out_aval=_out_aval_cast)\n- res = tuple([tf.cast(r, tf.uint32) for r in res])\n+ multiple_results=True)(*args, _in_avals=_in_avals, _out_aval=_out_aval)\nreturn res\ntf_impl_with_avals[jax.random.threefry2x32_p] = _threefry2x32_jax_impl\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -182,7 +182,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef add(cls, harness: primitive_harness.Harness):\nreturn [\n- missing_tf_kernel(dtypes=[np.uint16, np.uint32], also_compiled=True),\n+ missing_tf_kernel(dtypes=[np.uint16], also_compiled=True),\nmissing_tf_kernel(\ndtypes=[np.uint64],\ndevices=(\"cpu\", \"gpu\"),\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add support for Add for uint32
260,411
15.01.2021 14:40:37
-7,200
0e932aeb725145769dced9d183152b2b2d01dcb8
Update debug_nans_test.py Fix typo
[ { "change_type": "MODIFY", "old_path": "tests/debug_nans_test.py", "new_path": "tests/debug_nans_test.py", "diff": "@@ -81,7 +81,7 @@ class DebugInfsTest(jtu.JaxTestCase):\ndef setUp(self):\nself.cfg = config.read(\"jax_debug_infs\")\n- config.update(\"jax_debug_inf\", True)\n+ config.update(\"jax_debug_infs\", True)\ndef tearDown(self):\nconfig.update(\"jax_debug_infs\", self.cfg)\n" } ]
Python
Apache License 2.0
google/jax
Update debug_nans_test.py Fix typo
260,485
17.01.2021 00:35:45
18,000
a47abe06edfdc90384901b5bc6742a688785b46b
Added check for shapes of arguments in jvp, resolves issue
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1720,6 +1720,12 @@ def _jvp(fun: lu.WrappedFun, primals, tangents):\nf\"Got primal dtype {_dtype(p)} and so expected tangent dtype \"\nf\"{core.primal_dtype_to_tangent_dtype(_dtype(p))}, but got \"\nf\"tangent dtype {_dtype(t)} instead.\")\n+ try:\n+ if p.shape != t.shape:\n+ raise ValueError(\"jvp called with inconsistent primal and tangent shapes;\"\n+ f\"Got primal shape {p.shape} and tangent shape as {t.shape}\")\n+ except AttributeError:\n+ pass\nflat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)\nout_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)\nreturn (tree_unflatten(out_tree(), out_primals),\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -947,6 +947,12 @@ class APITest(jtu.JaxTestCase):\nTypeError,\n\"primal and tangent arguments to jax.jvp do not match.\",\nlambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n+ # If primals and tangents are not of the same shape then raise error\n+ self.assertRaisesRegex(\n+ ValueError,\n+ \"jvp called with inconsistent primal and tangent shapes\",\n+ lambda: api.jvp(lambda x: x+1, (np.random.randn(10,),), (np.random.randn(20,),))\n+ )\ndef test_jvp_non_tuple_arguments(self):\ndef f(x, y): return x + y\n" } ]
Python
Apache License 2.0
google/jax
Added check for shapes of arguments in jvp, resolves issue #5226
260,287
11.12.2020 11:57:22
0
166e1296b98f551c9de320b875ae686f73aa8413
Clean up xmap tests Move `pdot` tests to a separate class. Automatically run all regular xmap tests with both the `pmap`-style lowering and `sharded_jit`-style lowering.
[ { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -78,22 +78,8 @@ def with_mesh(named_shape, f):\nreturn f(*args, **kwargs)\nreturn new_f\n-def use_spmd_lowering(f):\n- def new_f(*args, **kwargs):\n- if jtu.device_under_test() != \"tpu\":\n- raise SkipTest\n- jax.experimental.maps.make_xmap_callable.cache_clear()\n- old = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n- jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = True\n- try:\n- return f(*args, **kwargs)\n- finally:\n- jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = old\n- return new_f\n-\nclass XMapTest(jtu.JaxTestCase):\n-\ndef setUp(self):\nif jax.lib.version < (0, 1, 58):\nraise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\n@@ -121,8 +107,6 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(c, a * 2)\nself.assertAllClose(d, b * 4)\n- testBasicSPMD = use_spmd_lowering(testBasic)\n-\n@ignore_xmap_warning()\ndef testBasicCollective(self):\nlocal_devices = list(jax.local_devices())\n@@ -144,8 +128,6 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a * 2).sum(0))\nself.assertAllClose(d, b * 4)\n- testBasicCollectiveSPMD = use_spmd_lowering(testBasicCollective)\n-\n@ignore_xmap_warning()\n@with_mesh([('x', 2), ('y', 2)])\ndef testOneLogicalTwoMeshAxesBasic(self):\n@@ -249,6 +231,53 @@ class XMapTest(jtu.JaxTestCase):\n\"Changing the resource environment.*\"):\nf(x)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n+ for name, mesh, axis_resources in (\n+ ('', (), ()),\n+ ('Mesh', (('x', 2),), (('i', 'x'),))\n+ ))\n+ @ignore_xmap_warning()\n+ def testMultipleCalls(self, mesh, axis_resources):\n+ def f(x, y):\n+ assert x.shape == y.shape == (3, 5)\n+ return jnp.tensordot(x, y, axes=([1], [1]))\n+\n+ @with_mesh(mesh)\n+ def run_test():\n+ f_mapped = xmap(f,\n+ in_axes=(['i', ...], ['j', ...]),\n+ out_axes=['i', 'j', ...],\n+ axis_resources=dict(axis_resources))\n+ x = jnp.arange(30).reshape(2, 3, 5)\n+ expected = jnp.einsum('imk,jnk->ijmn', x, x)\n+ for i in range(10):\n+ self.assertAllClose(f_mapped(x, x), expected)\n+ run_test()\n+\n+\n+class XMapTestSPMD(XMapTest):\n+ \"\"\"Re-executes all tests with the SPMD partitioner enabled\"\"\"\n+\n+ def setUp(self):\n+ super().setUp()\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest\n+ jax.experimental.maps.make_xmap_callable.cache_clear()\n+ self.old_lowering_flag = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = True\n+\n+ def tearDown(self):\n+ jax.experimental.maps.make_xmap_callable.cache_clear()\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = self.old_lowering_flag\n+\n+\n+class PDotTests(jtu.JaxTestCase):\n+\n+ def setUp(self):\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"xmap requires omnistaging\")\n+\n@ignore_xmap_warning()\n@with_mesh([('r1', 2)])\ndef testPdotBasic(self):\n@@ -306,30 +335,6 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n- @parameterized.named_parameters(\n- {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n- for name, mesh, axis_resources in (\n- ('', (), ()),\n- ('Mesh', (('x', 2),), (('i', 'x'),))\n- ))\n- @ignore_xmap_warning()\n- def testMultipleCalls(self, mesh, axis_resources):\n- def f(x, y):\n- assert x.shape == y.shape == (3, 5)\n- return jnp.tensordot(x, y, axes=([1], [1]))\n-\n- @with_mesh(mesh)\n- def run_test():\n- f_mapped = xmap(f,\n- in_axes=(['i', ...], ['j', ...]),\n- out_axes=['i', 'j', ...],\n- axis_resources=dict(axis_resources))\n- x = jnp.arange(30).reshape(2, 3, 5)\n- expected = jnp.einsum('imk,jnk->ijmn', x, x)\n- for i in range(10):\n- self.assertAllClose(f_mapped(x, x), expected)\n- run_test()\n-\nclass XMapErrorTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
Clean up xmap tests Move `pdot` tests to a separate class. Automatically run all regular xmap tests with both the `pmap`-style lowering and `sharded_jit`-style lowering.
260,411
18.01.2021 03:37:55
28,800
6bf634921e12854aead78e7707a05715d19075f2
Copybara import of the project: by George Necula [jax2tf] Update limitations Some bugs were fixed on the TF-side, and we can remove some limitations. COPYBARA_INTEGRATE_REVIEW=https://github.com/google/jax/pull/5449 from gnecula:jax2tf_limit
[ { "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-01-15*\n+*Last generated on (YYYY-MM-DD): 2021-01-18*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -73,7 +73,6 @@ More detailed information can be found in the\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 error: op not defined for dtype | int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n-| conv_general_dilated | TF test skipped: TF error: TODO: TF/LLVM crash | complex | gpu | compiled, eager, graph |\n| conv_general_dilated | TF error: jax2tf BUG: batch_group_count > 1 not yet converted | all | cpu, gpu, tpu | compiled, eager, graph |\n| cosh | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n| cummax | TF error: op not defined for dtype | complex128, uint64 | cpu, gpu | compiled, eager, graph |\n@@ -91,10 +90,9 @@ More detailed information can be found in the\n| dot_general | TF error: op not defined for dtype | int64 | cpu, gpu | compiled |\n| dot_general | TF error: op not defined for dtype | bool, int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\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, gpu, tpu | compiled |\n+| eig | TF error: function not compilable | all | cpu | compiled |\n| eigh | TF error: function not compilable | complex | cpu, gpu, tpu | compiled |\n| erf | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n-| erf_inv | TF test skipped: TF error: TODO: erf_inv bug on TPU: nan vs non-nan | float32 | tpu | compiled, eager, graph |\n| erf_inv | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| erfc | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| fft | TF error: TF function not compileable | complex128, float64 | cpu, gpu | compiled |\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -314,17 +314,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef conv_general_dilated(cls, harness: primitive_harness.Harness):\nreturn [\n- # It is not enough to add an expect_tf_error limitation for this, because\n- # when this test runs with the LLVM debug-mode, it segfaults.\n- # assert.h assertion failed at third_party/llvm/llvm-project/llvm/lib/IR/Instructions.cpp:2471\n- # in void llvm::BinaryOperator::AssertOK(): getType()->isFPOrFPVectorTy() &&\n- # \"Tried to create a floating-point operation on a \" \"non-floating-point type!\"\n- Jax2TfLimitation(\n- \"TODO: TF/LLVM crash\",\n- devices=\"gpu\",\n- dtypes=[np.complex64, np.complex128],\n- skip_tf_run=True,\n- ),\nJax2TfLimitation(\n\"jax2tf BUG: batch_group_count > 1 not yet converted\",\nenabled=(harness.params[\"batch_group_count\"] > 1)),\n@@ -563,7 +552,9 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nresult_tf[1 + compute_left_eigenvectors])\nreturn [\n- Jax2TfLimitation(\"function not compilable\", modes=\"compiled\"),\n+ # Eig does not work in JAX on gpu or tpu\n+ Jax2TfLimitation(\"function not compilable\", modes=\"compiled\",\n+ devices=\"cpu\"),\nJax2TfLimitation(\n\"TF Conversion of eig is not implemented when both compute_left_eigenvectors and compute_right_eigenvectors are set to True\",\nenabled=(compute_left_eigenvectors and compute_right_eigenvectors)),\n@@ -701,11 +692,6 @@ class Jax2TfLimitation(primitive_harness.Limitation):\nrtol=tol)\nreturn [\n- Jax2TfLimitation(\n- \"TODO: erf_inv bug on TPU: nan vs non-nan\",\n- dtypes=np.float32,\n- devices=\"tpu\",\n- skip_tf_run=True),\nmissing_tf_kernel(\ndtypes=[dtypes.bfloat16, np.float16],\ndevices=(\"cpu\", \"gpu\"),\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -61,7 +61,7 @@ import numpy as np\nFLAGS = config.FLAGS\nRng = Any # A random number generator\n-DType = np.dtype\n+DType = Any\nclass RandArg(NamedTuple):\n\"\"\"Descriptor for a randomly generated argument.\n" } ]
Python
Apache License 2.0
google/jax
Copybara import of the project: -- 781492e0120ec915f9fdc83479884908f59d113d by George Necula <gcnecula@gmail.com>: [jax2tf] Update limitations Some bugs were fixed on the TF-side, and we can remove some limitations. COPYBARA_INTEGRATE_REVIEW=https://github.com/google/jax/pull/5449 from gnecula:jax2tf_limit 781492e0120ec915f9fdc83479884908f59d113d PiperOrigin-RevId: 352381535
260,411
18.01.2021 14:41:42
-7,200
6d2b976fab8a57edbd10459a33e4e2970f0ec31b
[jax2tf] Start using jit_compile instead of the deprecated experimental_compile
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_lib.py", "diff": "@@ -89,7 +89,7 @@ def convert_and_save_model(\nenable_xla: whether the jax2tf converter is allowed to use TFXLA ops. If\nFalse, the conversion tries harder to use purely TF ops and raises an\nexception if it is not possible. (default: True)\n- compile_model: use TensorFlow experimental_compiler on the SavedModel. This\n+ compile_model: use TensorFlow jit_compiler on the SavedModel. This\nis needed if the SavedModel will be used for TensorFlow serving.\nsave_model_options: options to pass to savedmodel.save.\n\"\"\"\n@@ -116,7 +116,7 @@ def convert_and_save_model(\nparams)\ntf_graph = tf.function(lambda inputs: tf_fn(param_vars, inputs),\nautograph=False,\n- experimental_compile=compile_model)\n+ jit_compile=compile_model)\nsignatures = {}\n# This signature is needed for TensorFlow Serving use.\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "new_path": "jax/experimental/jax2tf/examples/saved_model_main.py", "diff": "@@ -56,7 +56,7 @@ flags.DEFINE_boolean(\n\"Train and save a new model. Otherwise, use an existing SavedModel.\")\nflags.DEFINE_boolean(\n\"compile_model\", True,\n- \"Enable TensorFlow experimental_compiler for the SavedModel. This is \"\n+ \"Enable TensorFlow jit_compiler for the SavedModel. This is \"\n\"necessary if you want to use the model for TensorFlow serving.\")\nflags.DEFINE_boolean(\"show_model\", True, \"Show details of saved SavedModel.\")\nflags.DEFINE_boolean(\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -1826,7 +1826,7 @@ def _dynamic_slice(operand, *start_indices, slice_sizes):\n# Here we could use tf.slice. Similarly, for lax.gather we can sometimes use\n# tf.gather. But those have different semantics for index-out-of-bounds than\n# JAX (and XLA). We have tried to force compilation, by wrapping into\n- # tf.xla.experimental.compile, or tf.function(experimental_compile=True), but\n+ # tf.xla.experimental.compile, or tf.function(jit_compile=True), but\n# those solutions are brittle because they do not work when nested into an\n# outer compilation (see b/162814494 and b/163006262). They also do not\n# survive well being put in a SavedModel. Hence, we now use TFXLA slicing\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "new_path": "jax/experimental/jax2tf/tests/jax2tf_limitations.py", "diff": "@@ -977,7 +977,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef qr(cls, harness: primitive_harness.Harness):\n# See https://github.com/google/jax/pull/3775#issuecomment-659407824;\n- # # experimental_compile=True breaks for complex types.\n+ # # jit_compile=True breaks for complex types.\n# TODO: see https://github.com/google/jax/pull/3775#issuecomment-659407824.\n# - for now, the performance of the HLO QR implementation called when\n# compiling with TF is expected to have worse performance than the\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": "@@ -476,7 +476,7 @@ class ShapePolyPrimitivesTest(tf_test_util.JaxToTfTestCase):\n# If we get_concrete_function we trace once\nf_tf = tf.function(jax2tf.convert(f_jax, in_shapes=[\"(2 * batch, d)\"]),\nautograph=False,\n- experimental_compile=True).get_concrete_function(tf.TensorSpec([None, None], tf.float32))\n+ jit_compile=True).get_concrete_function(tf.TensorSpec([None, None], tf.float32))\nself.assertTrue(traced)\ntraced = False\nself.assertAllClose(res_jax, f_tf(x))\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": "@@ -61,7 +61,7 @@ def _run_tf_function(func_tf: Callable, *tf_args, mode: str):\nreturn tf.function(\nfunc_tf,\nautograph=False,\n- experimental_compile=True,\n+ jit_compile=True,\ninput_signature=_make_tf_input_signature(*tf_args))(\n*tf_args) # COMPILED\nelse:\n@@ -114,7 +114,7 @@ class JaxToTfTestCase(jtu.JaxTestCase):\nIt compares the result of JAX, TF (\"eager\" mode),\nTF with tf.function (\"graph\" mode), and TF with\n- tf.function(experimental_compile=True) (\"compiled\" mode). In each mode,\n+ tf.function(jit_compile=True) (\"compiled\" mode). In each mode,\neither we expect to encounter a known limitation, or the value should\nmatch the value from the JAX execution.\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Start using jit_compile instead of the deprecated experimental_compile
260,411
18.01.2021 15:19:01
-7,200
d77a9412571ac8ac828981a8774bff9cf8ea0837
[jax2tf] Reflect in the limitations that add is now implemented for uint32 in TF
[ { "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": "@@ -59,7 +59,7 @@ More detailed information can be found in the\n| acosh | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| add | TF error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n| add | TF error: op not defined for dtype | uint16 | cpu, gpu, tpu | compiled, eager, graph |\n-| add_any | TF error: op not defined for dtype | uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n+| add_any | TF error: op not defined for dtype | uint16, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| asin | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| asin | TF error: op not defined for dtype | complex | cpu, gpu, tpu | compiled, eager, graph |\n| asinh | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n@@ -82,7 +82,7 @@ More detailed information can be found in the\n| cumprod | TF error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n| cumprod | TF error: op not defined for dtype | uint32 | cpu, gpu, tpu | compiled, eager, graph |\n| cumsum | TF error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n-| cumsum | TF error: op not defined for dtype | uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n+| cumsum | TF error: op not defined for dtype | uint16 | cpu, gpu, tpu | compiled, eager, graph |\n| cumsum | TF error: op not defined for dtype | complex64 | 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@@ -125,7 +125,7 @@ More detailed information can be found in the\n| reduce_min | TF error: op not defined for dtype | complex128 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_min | TF error: op not defined for dtype | complex64 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_window_add | TF error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n-| reduce_window_add | TF error: op not defined for dtype | uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n+| reduce_window_add | TF error: op not defined for dtype | uint16 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_window_add | TF error: op not defined for dtype | complex64 | tpu | compiled, eager, graph |\n| reduce_window_max | TF error: TF kernel missing, except when the initial_value is the minimum for the dtype | int8, uint16 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_window_max | TF error: op not defined for dtype | complex128, uint64 | cpu, gpu | compiled, eager, graph |\n@@ -141,7 +141,7 @@ More detailed information can be found in the\n| rev | TF error: op not defined for dtype | uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| round | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| rsqrt | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n-| scatter_add | TF error: op not defined for dtype | bool, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n+| scatter_add | TF error: op not defined for dtype | bool, uint16, uint64 | 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 error: op not defined for dtype | bool, complex, int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| scatter_min | TF error: op not defined for dtype | bool, complex, int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n@@ -150,7 +150,7 @@ More detailed information can be found in the\n| select_and_gather_add | TF error: This JAX primitives is not not exposed directly in the JAX API but arises from JVP of `lax.reduce_window` for reducers `lax.max` or `lax.min`. It also arises from second-order VJP of the same. Implemented using XlaReduceWindow | float32 | 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 error: op not defined for dtype | uint64 | cpu, gpu | compiled, eager, graph |\n-| select_and_scatter_add | TF error: op not defined for dtype | uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n+| select_and_scatter_add | TF error: op not defined for dtype | uint16 | cpu, gpu, tpu | compiled, eager, graph |\n| sign | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| sinh | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n| sort | TF error: op not defined for dtype | complex128, float64 | cpu, gpu | compiled, 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": "@@ -192,7 +192,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\n# Also called add_jaxvals\ndef add_any(cls, harness: primitive_harness.Harness):\n- return [missing_tf_kernel(dtypes=[np.uint16, np.uint32, np.uint64])]\n+ return [missing_tf_kernel(dtypes=[np.uint16, np.uint64])]\n@classmethod\ndef asin(cls, harness: primitive_harness.Harness):\n@@ -407,7 +407,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndevices=(\"cpu\", \"gpu\"),\n),\nmissing_tf_kernel(dtypes=[np.complex64], devices=\"tpu\"),\n- missing_tf_kernel(dtypes=[np.uint16, np.uint32]),\n+ missing_tf_kernel(dtypes=[np.uint16]),\ncustom_numeric(dtypes=np.float16, tol=0.1),\ncustom_numeric(dtypes=dtypes.bfloat16, tol=0.5),\n]\n@@ -1012,7 +1012,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndef reduce_window_add(cls, harness):\nassert \"add\" == harness.params[\"computation\"].__name__\nreturn [\n- missing_tf_kernel(dtypes=[np.uint16, np.uint32]),\n+ missing_tf_kernel(dtypes=[np.uint16]),\nmissing_tf_kernel(dtypes=[np.complex64], devices=\"tpu\"),\nmissing_tf_kernel(dtypes=[np.uint64], devices=(\"cpu\", \"gpu\"))\n]\n@@ -1108,7 +1108,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef scatter_add(cls, harness):\nreturn [\n- missing_tf_kernel(dtypes=[np.uint16, np.uint32, np.uint64, np.bool_],),\n+ missing_tf_kernel(dtypes=[np.uint16, np.uint64, np.bool_],),\nmissing_tf_kernel(\ndtypes=[np.complex64],\ndevices=\"tpu\",\n@@ -1167,7 +1167,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef select_and_scatter_add(cls, harness):\nreturn [\n- missing_tf_kernel(dtypes=[np.uint32, np.uint16]),\n+ missing_tf_kernel(dtypes=[np.uint16]),\nmissing_tf_kernel(\ndtypes=[np.uint64],\ndevices=(\"cpu\", \"gpu\"),\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Reflect in the limitations that add is now implemented for uint32 in TF
260,287
18.01.2021 19:40:46
-3,600
c2871807020c64bda6b32accf721efbd8f03ba1a
Update jax/experimental/maps.py
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -305,7 +305,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nEXPERIMENTAL_SPMD_LOWERING,\n*in_avals)\nelse:\n- # We have to trace again, because `f` is a linear function, so we can't just return it.\n+ # We have to trace again, because `f` is an lu.WrappedFun, so we can't just return it.\nfinal_jaxpr, out_avals, final_consts = pe.trace_to_jaxpr_final(f, in_avals)\nreturn core.jaxpr_as_fun(core.ClosedJaxpr(final_jaxpr, final_consts))\n" } ]
Python
Apache License 2.0
google/jax
Update jax/experimental/maps.py Co-authored-by: Matthew Johnson <mattjj@google.com>
260,485
18.01.2021 23:21:33
18,000
bd9ac93b6bce32182d8d039a00039d832778d0a4
Added changes requested
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1720,12 +1720,10 @@ def _jvp(fun: lu.WrappedFun, primals, tangents):\nf\"Got primal dtype {_dtype(p)} and so expected tangent dtype \"\nf\"{core.primal_dtype_to_tangent_dtype(_dtype(p))}, but got \"\nf\"tangent dtype {_dtype(t)} instead.\")\n- try:\n- if p.shape != t.shape:\n+ if np.shape(p) != np.shape(t):\nraise ValueError(\"jvp called with inconsistent primal and tangent shapes;\"\n- f\"Got primal shape {p.shape} and tangent shape as {t.shape}\")\n- except AttributeError:\n- pass\n+ f\"Got primal shape {np.shape(p)} and tangent shape as {np.shape(t)}\")\n+\nflat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)\nout_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)\nreturn (tree_unflatten(out_tree(), out_primals),\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -948,11 +948,11 @@ class APITest(jtu.JaxTestCase):\n\"primal and tangent arguments to jax.jvp do not match.\",\nlambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n# If primals and tangents are not of the same shape then raise error\n- self.assertRaisesRegex(\n- ValueError,\n- \"jvp called with inconsistent primal and tangent shapes\",\n- lambda: api.jvp(lambda x: x+1, (np.random.randn(10,),), (np.random.randn(20,),))\n- )\n+ fun = lambda x: x+1\n+ with self.assertRaisesRegex(ValueError, \"jvp called with inconsistent primal and tangent shapes\"):\n+ api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.array([1.,2.,3.,4.]),))\n+ api.jvp(fun, (jnp.float(10.),), (jnp.array([1.,2.,3.]),))\n+ api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.float(20.),))\ndef test_jvp_non_tuple_arguments(self):\ndef f(x, y): return x + y\n" } ]
Python
Apache License 2.0
google/jax
Added changes requested
260,335
18.01.2021 20:37:12
28,800
47f7cd468031d2177bfc977a188564f8b5deafdd
avoid printing double periods in error messages
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -385,18 +385,18 @@ class Trace:\nreturn self.sublift(val)\nelse:\nraise escaped_tracer_error(\n- val, f\"Can't lift sublevels {val._trace.sublevel} to {sublevel}.\")\n+ val, f\"Can't lift sublevels {val._trace.sublevel} to {sublevel}\")\nelif val._trace.level < level:\nif val._trace.sublevel > sublevel:\nraise escaped_tracer_error(\n- val, f\"Incompatible sublevel: {val._trace}, {(level, sublevel)}.\")\n+ val, f\"Incompatible sublevel: {val._trace}, {(level, sublevel)}\")\nreturn self.lift(val)\nelif val._trace.level > level:\nraise escaped_tracer_error(\n- val, f\"Can't lift level {val} to {self}.\")\n+ val, f\"Can't lift level {val} to {self}\")\nelse: # val._trace.level == self.level:\nraise escaped_tracer_error(\n- val, f\"Different traces at same level: {val}, {self}.\")\n+ val, f\"Different traces at same level: {val}, {self}\")\ndef pure(self, val):\nraise NotImplementedError(\"must override\")\n" } ]
Python
Apache License 2.0
google/jax
avoid printing double periods in error messages
260,485
19.01.2021 09:12:11
18,000
9260f2c7d7bbffe8b97c866042176bc9b1f9e676
regex check for each test case
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1721,7 +1721,7 @@ def _jvp(fun: lu.WrappedFun, primals, tangents):\nf\"{core.primal_dtype_to_tangent_dtype(_dtype(p))}, but got \"\nf\"tangent dtype {_dtype(t)} instead.\")\nif np.shape(p) != np.shape(t):\n- raise ValueError(\"jvp called with inconsistent primal and tangent shapes;\"\n+ raise ValueError(\"jvp called with different primal and tangent shapes;\"\nf\"Got primal shape {np.shape(p)} and tangent shape as {np.shape(t)}\")\nflat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -949,10 +949,15 @@ class APITest(jtu.JaxTestCase):\nlambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n# If primals and tangents are not of the same shape then raise error\nfun = lambda x: x+1\n- with self.assertRaisesRegex(ValueError, \"jvp called with inconsistent primal and tangent shapes\"):\n+ with self.assertRaisesRegex(\n+ ValueError, \"jvp called with different primal and tangent shapes\"):\napi.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.array([1.,2.,3.,4.]),))\n- api.jvp(fun, (jnp.float(10.),), (jnp.array([1.,2.,3.]),))\n- api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.float(20.),))\n+ with self.assertRaisesRegex(\n+ ValueError, \"jvp called with different primal and tangent shapes\"):\n+ api.jvp(fun, (jnp.float32(10.),), (jnp.array([1.,2.,3.]),))\n+ with self.assertRaisesRegex(\n+ ValueError, \"jvp called with different primal and tangent shapes\"):\n+ api.jvp(fun, (jnp.array([1.,2.,3.]),), (jnp.float32(20.),))\ndef test_jvp_non_tuple_arguments(self):\ndef f(x, y): return x + y\n" } ]
Python
Apache License 2.0
google/jax
regex check for each test case
260,335
19.01.2021 19:08:23
28,800
0f704514e30ad8eda67eff543874bc06459f511b
add BatchTrace.process_custom_vjp_call It was an oversight not to include this! Notice we have BatchTrace.process_custom_jvp_call. In fact, we can use the same function! We just needed the simplest possible post-process-call which just peels and packages. fixes
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -259,6 +259,8 @@ class BatchTrace(Trace):\nout_dims = out_dims[-len(out_vals) % len(out_dims):]\nreturn [BatchTracer(self, v, d) for v, d in zip(out_vals, out_dims)]\n+ post_process_custom_vjp_call = post_process_custom_jvp_call\n+\ndef _main_trace_for_axis_names(main_trace: core.MainTrace,\naxis_name: Union[core.AxisName, Tuple[core.AxisName, ...]]\n) -> bool:\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -3866,6 +3866,47 @@ class CustomVJPTest(jtu.JaxTestCase):\nexpected = jnp.cos(3.)\nself.assertAllClose(ans, expected, check_dtypes=False)\n+ def test_closed_over_tracer2(self):\n+ def outer(x):\n+ @api.custom_vjp\n+ def f(y):\n+ return x * y\n+ def f_fwd(y):\n+ return f(y), jnp.cos(y)\n+ def f_rev(cos_y, g):\n+ return (cos_y * g,)\n+ f.defvjp(f_fwd, f_rev)\n+ return f\n+\n+ @api.vmap\n+ def g(x):\n+ return outer(x)(3.)\n+\n+ ans = g(np.arange(3.))\n+ expected = np.arange(3.) * 3\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\n+ def test_closed_over_tracer3(self):\n+ def outer(x):\n+ @api.custom_vjp\n+ def f(y):\n+ return x * y\n+ def f_fwd(y):\n+ return f(y), (x, jnp.cos(y))\n+ def f_rev(res, g):\n+ x, cos_y = res\n+ return (cos_y * g * x,)\n+ f.defvjp(f_fwd, f_rev)\n+ return api.grad(f)\n+\n+ @api.vmap\n+ def g(x):\n+ return outer(x)(3.)\n+\n+ ans = g(np.arange(3.))\n+ expected = np.cos(3.) * np.arange(3.)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\ndef test_nondiff_arg_tracer_error(self):\n# This is similar to the old (now skipped) test_nondiff_arg_tracer, except\n# we're testing for the error message that that usage pattern now raises.\n" } ]
Python
Apache License 2.0
google/jax
add BatchTrace.process_custom_vjp_call It was an oversight not to include this! Notice we have BatchTrace.process_custom_jvp_call. In fact, we can use the same function! We just needed the simplest possible post-process-call which just peels and packages. fixes #5440 Co-authored-by: Roy Frostig <frostig@google.com>
260,485
20.01.2021 21:47:18
18,000
186c97394d30472246409cef57650a4cac64b601
Added test for python scalar
[ { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -958,6 +958,9 @@ class APITest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(\nValueError, \"jvp called with different primal and tangent shapes\"):\napi.jvp(fun, (jnp.array([1.,2.,3.], dtype=jnp.float32),), (jnp.float32(20.),))\n+ with self.assertRaisesRegex(\n+ ValueError, \"jvp called with different primal and tangent shapes\"):\n+ api.jvp(fun, (jnp.array([1.,2.,3.]),), (20.,))\ndef test_jvp_non_tuple_arguments(self):\ndef f(x, y): return x + y\n" } ]
Python
Apache License 2.0
google/jax
Added test for python scalar
260,335
18.01.2021 10:02:24
28,800
c02d8041f46f33c9f96df61b9f9df97a3bc76c0d
add systematic pdot tests, utility functions Run lots of tests with e.g. ``` env JAX_NUM_GENERATED_CASES=1000 python tests/xmap_test.py PDotTests ```
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -352,11 +352,11 @@ def axis_index(axis_name):\nreturn axis_index_p.bind(axis_name=axis_name)\n-def pdot(x, y, axis_name, pos_contract=((), ())):\n+def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ())):\nif not isinstance(axis_name, (list, tuple)):\naxis_name = (axis_name,)\nreturn pdot_p.bind(x, y, axis_name=axis_name,\n- pos_contract=pos_contract, pos_batch=[(), ()])\n+ pos_contract=pos_contract, pos_batch=pos_batch)\n### parallel primitives\n@@ -870,6 +870,7 @@ def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch):\n@pdot_p.def_abstract_eval\ndef _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\n# TODO: avals with names, check inputs are mapped along axis_name, eliminate\n+ if not len(set(axis_name)) == len(axis_name): raise ValueError\nreturn lax.dot_general_p.abstract_eval(\nx, y, dimension_numbers=[pos_contract, pos_batch],\nprecision=None, preferred_element_type=None)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "# flake8: noqa\n+from contextlib import contextmanager\nimport functools\n-import itertools\n+import itertools as it\nimport os\nimport unittest\nfrom itertools import product, permutations\n+from typing import (Tuple, List, NamedTuple, Dict, Generator, Sequence, Set,\n+ Any, Hashable, Iterable, Iterator, Union)\nfrom unittest import SkipTest, skip, skipIf\nimport numpy as np\n@@ -33,7 +36,8 @@ from jax import vmap\nfrom jax import lax\nfrom jax.experimental.maps import Mesh, mesh, xmap\nfrom jax.lib import xla_bridge\n-from jax._src.util import curry, unzip2\n+from jax._src.util import curry, unzip2, split_list, prod\n+from jax._src.lax.lax import DotDimensionNumbers\nfrom jax.interpreters import pxla\nfrom jax.config import config\n@@ -63,20 +67,20 @@ def tearDownModule():\nos.environ[\"XLA_FLAGS\"] = prev_xla_flags\nxla_bridge.get_backend.cache_clear()\n-@curry\n-def with_mesh(named_shape, f):\n- if not named_shape:\n- return f\n- def new_f(*args, **kwargs):\n+MeshSpec = List[Tuple[str, int]]\n+\n+@contextmanager\n+def with_mesh(named_shape: MeshSpec) -> Generator[None, None, None]:\n+ \"\"\"Test utility for setting up meshes given mesh data from `schedules`.\"\"\"\n+ # This is similar to the `with_mesh` function above, but isn't a decorator.\naxis_names, shape = unzip2(named_shape)\n- size = np.prod(shape)\n+ size = prod(shape)\nlocal_devices = list(jax.local_devices())\nif len(local_devices) < size:\nraise SkipTest(f\"Test requires {size} local devices\")\nmesh_devices = np.array(local_devices[:size]).reshape(shape)\nwith mesh(mesh_devices, axis_names):\n- return f(*args, **kwargs)\n- return new_f\n+ yield\nclass XMapTest(jtu.JaxTestCase):\n@@ -338,12 +342,222 @@ class XMapTestSPMD(XMapTest):\njax.experimental.maps.make_xmap_callable.cache_clear()\njax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = self.old_lowering_flag\n+AxisIndices = Tuple[int, ...]\n+MatchedAxisIndices = Tuple[AxisIndices, AxisIndices]\n+AxisNames = Tuple[str, ...]\n+\n+class PdotTestSpec:\n+ # The axis indices stored by a PdotTestSpec are all positional indices\n+ # *before* taking mapping into account.\n+ map_cont: MatchedAxisIndices\n+ pos_cont: MatchedAxisIndices\n+ map_batch: MatchedAxisIndices\n+ pos_batch: MatchedAxisIndices\n+ all_names: AxisNames\n+ contract_names: AxisNames\n+ batch_names: AxisNames\n+\n+ def __init__(self, map_cont, pos_cont, map_batch, pos_batch):\n+ self.map_cont = map_cont\n+ self.pos_cont = pos_cont\n+ self.map_batch = map_batch\n+ self.pos_batch = pos_batch\n+\n+ names = gen_axis_names()\n+ self.contract_names = [next(names) for _ in range(len(map_cont[0]))]\n+ self.batch_names = [next(names) for _ in range(len(map_batch[0]))]\n+ self.all_names = self.contract_names + self.batch_names\n+\n+ @property\n+ def dot_general_dim_nums(self):\n+ lhs_contract = (*self.map_cont[0], *self.pos_cont[0])\n+ rhs_contract = (*self.map_cont[1], *self.pos_cont[1])\n+ lhs_batch = (*self.map_batch[0], *self.pos_batch[0])\n+ rhs_batch = (*self.map_batch[1], *self.pos_batch[1])\n+ return (lhs_contract, rhs_contract), (lhs_batch, rhs_batch)\n+\n+ @property\n+ def pos_contract_after_mapping(self):\n+ lhs = [i - sum(j < i for j in self._lhs_mapped) for i in self.pos_cont[0]]\n+ rhs = [i - sum(j < i for j in self._rhs_mapped) for i in self.pos_cont[1]]\n+ return (lhs, rhs)\n+\n+ @property\n+ def pos_batch_after_mapping(self):\n+ lhs = [i - sum(j < i for j in self._lhs_mapped) for i in self.pos_batch[0]]\n+ rhs = [i - sum(j < i for j in self._rhs_mapped) for i in self.pos_batch[1]]\n+ return (lhs, rhs)\n+\n+ @property\n+ def _lhs_mapped(self):\n+ return {*self.map_cont[0], *self.map_batch[0]}\n+\n+ @property\n+ def _rhs_mapped(self):\n+ return {*self.map_cont[1], *self.map_batch[1]}\n+\n+ @property\n+ def lhs_in_axes(self):\n+ axis_indices = [*self.map_cont[0], *self.map_batch[0]]\n+ return dict(zip(axis_indices, self.all_names))\n+\n+ @property\n+ def rhs_in_axes(self):\n+ axis_indices = [*self.map_cont[1], *self.map_batch[1]]\n+ return dict(zip(axis_indices, self.all_names))\n+\n+def all_pdot_specs(lhs_shape, rhs_shape):\n+ for matching in axis_matchings(lhs_shape, rhs_shape):\n+ for lists in partitions(matching, 4):\n+ yield PdotTestSpec(*map(unzip2, lists))\n+\n+def axis_matchings(lhs_shape, rhs_shape):\n+ def helper(start, exc1, exc2):\n+ yield ()\n+ for i in range(start, len(lhs_shape)):\n+ d1 = lhs_shape[i]\n+ if i not in exc1:\n+ for j, d2 in enumerate(rhs_shape):\n+ if d1 == d2 and j not in exc2:\n+ for matches in helper(i + 1, exc1 | {i}, exc2 | {j}):\n+ yield ((i, j), *matches)\n+ return helper(0, set(), set())\n+\n+def partitions(s, k):\n+ for indices in product(range(k), repeat=len(s)):\n+ outs = [[] for _ in range(k)]\n+ for i, elt in zip(indices, s):\n+ outs[i].append(elt)\n+ yield outs\n+\n+def powerset(s):\n+ s = list(s)\n+ return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))\n+\n+def gen_axis_names():\n+ names = 'ijkl'\n+ for n in it.count(1):\n+ for chars in product(names, repeat=n):\n+ yield ''.join(chars)\n+\n+AxisResources = Dict[str, Union[str, Tuple[str, ...]]]\n+\n+def schedules(sizes: Dict[str, int]\n+ ) -> Generator[Tuple[AxisResources, MeshSpec], None, None]:\n+ \"\"\"Test utility generating xmap parallel schedules from logical names & sizes.\n+\n+ Args:\n+ sizes: dict mapping logical axis name to its corresponding size.\n+\n+ Returns:\n+ A generator producing finitely many values, where each value is a pair in\n+ which the first element is a value suitable for xmap's axis_resources\n+ argument and the second element is a list of pairs with the first element\n+ representing a generated physical mesh axis name and the second element\n+ representing a corresponding generated mesh axis size. The generated mesh\n+ names/sizes can be used to define a physical mesh in tests.\n+\n+ This function doesn't generate schedules which map distinct logical axis names\n+ to the same parallel resource name. It only generates parallel resources; the\n+ rest are implicitly left for vectorization. Parallel resource names are\n+ generated by prepending an 'r', 'r1', or 'r2' to the corresponding logical\n+ name.\n+\n+ Exa,mples:\n+ >>> for sched in schedules({'i': 2, 'j': 4}):\n+ ... print(sched)\n+ ({}, [])\n+ ({'i': 'ri'}, [('ri', 1)])\n+ ({'i': 'ri'}, [('ri', 2)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 1)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 2)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj'}, [('rj', 1)])\n+ ({'j': 'rj'}, [('rj', 2)])\n+ ({'j': 'rj'}, [('rj', 4)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 1)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 2)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 4)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 1)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 2)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 4), ('r2j', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 2)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 4)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 2)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 4), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 4), ('r2j', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 2), ('r2i', 1)])\n+ \"\"\"\n+ def divisors(n: int) -> List[int]:\n+ return [m for m in range(1, n + 1) if not n % m]\n+\n+ def divisors2(n: int) -> Iterator[Tuple[int, int]]:\n+ for k1 in divisors(n):\n+ for k2 in divisors(n // k1):\n+ yield (k1, k2)\n+\n+ # choose a subset of logical axis names to map to parallel resources\n+ for names in powerset(sizes):\n+ # partition that set of logical axis names into two subsets: one subset to\n+ # map to one parallel resource axis and a second subset to map to two\n+ # parallel resource axes.\n+ for names1, names2 in partitions(names, 2):\n+ # to avoid generating too many complex cases, we skip generating cases\n+ # where more than one logical axis name is to be mapped to two parallel\n+ # resource axes. comment out this line to generate more complex tests.\n+ if len(names2) > 1: continue\n+ # make up parallel resource axis names for each logical axis\n+ axis_resources1 = ((name, 'r' + name) for name in names1)\n+ axis_resources2 = ((name, ('r1' + name, 'r2' + name)) for name in names2)\n+ axis_resources = dict(it.chain(axis_resources1, axis_resources2))\n+ # make up sizes for each resource axis, where the size must divide the\n+ # corresponding logical axis\n+ for mesh_sizes1 in product(*(divisors(sizes[n]) for n in names1)):\n+ for mesh_sizes2 in product(*(divisors2(sizes[n]) for n in names2)):\n+ mesh_data1 = (('r' + name, size) for name, size in zip(names1, mesh_sizes1))\n+ mesh_data2 = (pair for name, (size1, size2) in zip(names2, mesh_sizes2)\n+ for pair in [('r1' + name, size1), ('r2' + name, size2)])\n+ mesh_data = list(it.chain(mesh_data1, mesh_data2))\n+ yield axis_resources, mesh_data\n+\n+def schedules_from_pdot_spec(\n+ spec: PdotTestSpec, lhs_shape: Tuple[int], rhs_shape: Tuple[int]\n+ ) -> Generator[Tuple[AxisResources, MeshSpec], None, None]:\n+ logical_sizes = {\n+ name: shape[ax]\n+ for shape, in_axes in [(lhs_shape, spec.lhs_in_axes),\n+ (rhs_shape, spec.rhs_in_axes)]\n+ for ax, name in in_axes.items()}\n+ yield from schedules(logical_sizes)\n+\nclass PDotTests(jtu.JaxTestCase):\ndef setUp(self):\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n+ super().setUp()\n@ignore_xmap_warning()\n@with_mesh([('r1', 2)])\n@@ -402,6 +616,45 @@ class PDotTests(jtu.JaxTestCase):\nself.assertAllClose(z, jnp.einsum('nij,njk->nik', x, y))\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_{next(test_counter)}\",\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"pdot_spec\": pdot_spec,\n+ \"axis_resources\": axis_resources, \"mesh_data\": mesh_data}\n+ for test_counter in [it.count()]\n+ for lhs_shape, rhs_shape in product(\n+ [(2,), (2, 4, 2, 1)],\n+ repeat=2)\n+ for pdot_spec in all_pdot_specs(lhs_shape, rhs_shape)\n+ for axis_resources, mesh_data in schedules_from_pdot_spec(\n+ pdot_spec, lhs_shape, rhs_shape)))\n+ @ignore_xmap_warning()\n+ def testPdotSystematic(self, lhs_shape, rhs_shape, pdot_spec, axis_resources,\n+ mesh_data):\n+ rng = jtu.rand_default(self.rng())\n+ lhs = rng(lhs_shape, np.float32)\n+ rhs = rng(rhs_shape, np.float32)\n+\n+ def pdot_fun(x, y):\n+ # print(f'pdot(x:{x.aval.str_short()}, y:{y.aval.str_short()},\\n'\n+ # f' axis_name={contract_names},\\n'\n+ # f' pos_contract={spec.pos_contract_after_mapping}\\n'\n+ # f' pos_batch={spec.pos_batch_after_mapping})')\n+ return jax.lax.pdot(x, y, axis_name=pdot_spec.contract_names,\n+ pos_batch=pdot_spec.pos_batch_after_mapping,\n+ pos_contract=pdot_spec.pos_contract_after_mapping)\n+\n+ fun = xmap(pdot_fun, in_axes=[pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes],\n+ out_axes=[*pdot_spec.batch_names, ...],\n+ axis_resources=axis_resources)\n+\n+ with with_mesh(mesh_data):\n+ result = fun(lhs, rhs)\n+\n+ expected = lax.dot_general(lhs, rhs, pdot_spec.dot_general_dim_nums)\n+ tol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\n+ self.assertAllClose(result, expected, check_dtypes=False,\n+ atol=tol, rtol=tol)\n+\nclass XMapErrorTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add systematic pdot tests, utility functions Run lots of tests with e.g. ``` env JAX_NUM_GENERATED_CASES=1000 python tests/xmap_test.py PDotTests ```
260,335
21.01.2021 11:09:59
28,800
6d2f8320c39871b66b5c124addff168febd9500d
add xeinsum, an einsum for xmap (& einsum easter egg)
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -16,6 +16,7 @@ Parallelization primitives.\n\"\"\"\nimport collections\n+import string\nimport warnings\nimport numpy as np\n@@ -359,6 +360,128 @@ def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ())):\npos_contract=pos_contract, pos_batch=pos_batch)\n+def xeinsum(spec: str, x, y):\n+ in_spec, out_spec = spec.split('->')\n+ (lhs_subs, lhs_named), (rhs_subs, rhs_named) = XeinsumSpecParser(in_spec).parse_args()\n+ (out_subs, out_named), = XeinsumSpecParser(out_spec).parse_args()\n+ all_named = {*lhs_named, *rhs_named, *out_named}\n+ all_subs = {*lhs_subs, *rhs_subs, *out_subs}\n+ lhs_uniques = set(lhs_subs) - set(rhs_subs)\n+ rhs_uniques = set(rhs_subs) - set(lhs_subs)\n+ if all_subs & all_named:\n+ raise NotImplementedError\n+ if not set(out_named).issubset({*lhs_named, *rhs_named}):\n+ raise ValueError\n+\n+ # if a named axis appears in both inputs and not the output, contract!\n+ named_contract = list(all_named - set(out_named))\n+\n+ # if a subscript appears in both inputs and not the outputs, contract!\n+ subs_contract = all_subs - set(out_subs)\n+\n+ lhs_reduce_axes = [lhs_subs.index(n) for n in lhs_uniques & subs_contract]\n+ if lhs_reduce_axes:\n+ x = lax._reduce_sum(x, lhs_reduce_axes)\n+ for i in sorted(lhs_reduce_axes, reverse=True):\n+ del lhs_subs[i]\n+\n+ rhs_reduce_axes = [rhs_subs.index(n) for n in rhs_uniques & subs_contract]\n+ if rhs_reduce_axes:\n+ y = lax._reduce_sum(y, rhs_reduce_axes)\n+ for i in sorted(rhs_reduce_axes, reverse=True):\n+ del rhs_subs[i]\n+\n+ pos_contract = unzip2((lhs_subs.index(n), rhs_subs.index(n))\n+ for n in subs_contract - (lhs_uniques | rhs_uniques))\n+\n+ # if a subscript apperas in both inputs _and_ the outputs, batch!\n+ subs_batch = all_subs - subs_contract\n+ if subs_batch & (lhs_uniques | rhs_uniques):\n+ raise NotImplementedError\n+\n+ pos_batch = unzip2((lhs_subs.index(n), rhs_subs.index(n))\n+ for n in subs_batch)\n+\n+ return pdot(x, y, axis_name=named_contract,\n+ pos_contract=pos_contract, pos_batch=pos_batch)\n+\n+class XeinsumSpecParser:\n+ spec: str\n+ pos: int\n+\n+ def __init__(self, spec: str):\n+ self.spec = spec\n+ self.pos = 0\n+\n+ @property\n+ def eof(self):\n+ return self.pos == len(self.spec)\n+\n+ @property\n+ def cur(self):\n+ return self.spec[self.pos]\n+\n+ def parse_subscript(self):\n+ if self.cur in string.ascii_lowercase:\n+ out = self.cur\n+ self.pos += 1\n+ return out, True\n+ else:\n+ return None, False\n+\n+ def parse_axis_name(self):\n+ try:\n+ end = self.spec.index('}', self.pos)\n+ except ValueError:\n+ assert False\n+\n+ try:\n+ end = self.spec.index(',', self.pos, end)\n+ except ValueError:\n+ pass\n+\n+ axis_name = self.spec[self.pos:end]\n+ assert axis_name\n+ self.pos = end + 1\n+ return axis_name, self.spec[end] == ','\n+\n+ def maybe_take(self, char: str, on_eof: bool = False):\n+ if self.eof:\n+ return on_eof\n+ if self.cur == char:\n+ self.pos += 1\n+ return True\n+\n+ def parse_arg(self):\n+ subscripts = []\n+ names = []\n+ while not self.eof:\n+ subscript, cont = self.parse_subscript()\n+ if not cont: break\n+ subscripts.append(subscript)\n+ if self.eof:\n+ return False, (subscripts, names)\n+ if self.maybe_take(','):\n+ return True, (subscripts, names)\n+ else:\n+ assert self.maybe_take('{')\n+ while True:\n+ axis_name, cont = self.parse_axis_name()\n+ names.append(axis_name)\n+ if not cont: break\n+ return self.maybe_take(',', False), (subscripts, names)\n+\n+ def parse_args(self):\n+ arg_specs = []\n+ cont = True\n+ while not self.eof:\n+ cont, result = self.parse_arg()\n+ arg_specs.append(result)\n+ if cont:\n+ arg_specs.append(([], []))\n+ return arg_specs\n+\n+\n### parallel primitives\ndef _allreduce_soft_pmap_rule(prim, reducer, vals, mapped, chunk_size,\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3604,9 +3604,15 @@ def tensordot(a, b, axes=2, *, precision=None):\n@_wraps(np.einsum, lax_description=_PRECISION_DOC)\n-def einsum(*operands, out=None, optimize='greedy', precision=None):\n+def einsum(*operands, out=None, optimize='greedy', precision=None,\n+ _use_xeinsum=False):\nif out is not None:\nraise NotImplementedError(\"The 'out' argument to jnp.einsum is not supported.\")\n+\n+ if (_use_xeinsum or isinstance(operands[0], str) and '{' in operands[0] and\n+ len(operands[1:]) == 2):\n+ return lax.xeinsum(*operands)\n+\noptimize = 'greedy' if optimize is True else optimize\n# using einsum_call=True here is an internal api for opt_einsum\noperands, contractions = opt_einsum.contract_path(\n" }, { "change_type": "MODIFY", "old_path": "jax/lax/__init__.py", "new_path": "jax/lax/__init__.py", "diff": "@@ -343,6 +343,7 @@ from jax._src.lax.parallel import (\npsum_p,\npswapaxes,\npdot,\n+ xeinsum,\n)\nfrom jax._src.lax.other import (\nconv_general_dilated_patches\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -654,6 +654,68 @@ class PDotTests(jtu.JaxTestCase):\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\nself.assertAllClose(result, expected, check_dtypes=False,\natol=tol, rtol=tol)\n+ @ignore_xmap_warning()\n+ def test_xeinsum_vector_dot(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3)\n+ y = rng.randn(3)\n+ out = xmap(partial(jnp.einsum, '{i},{i}->'),\n+ in_axes=(['i', ...], ['i', ...]), out_axes=[...])(x, y)\n+ expected = np.einsum('i,i->', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=False)\n+\n+ @ignore_xmap_warning()\n+ def test_xeinsum_outer_product(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3)\n+ y = rng.randn(3)\n+ out = xmap(partial(jnp.einsum, '{i},{j}->{i,j}'),\n+ in_axes=(['i', ...], ['j', ...]), out_axes=['i', 'j', ...])(x, y)\n+ expected = np.einsum('i,j->ij', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=True)\n+\n+ @ignore_xmap_warning()\n+ def test_xeinsum_matmul(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3, 4)\n+ y = rng.randn(4, 5)\n+\n+ out = xmap(partial(jnp.einsum, '{i,j},{j,k}->{i,k}'),\n+ in_axes=(['i', 'j', ...], ['j', 'k', ...]),\n+ out_axes=['i', 'k', ...])(x, y)\n+ expected = np.einsum('ij,jk->ik', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=True)\n+\n+ # order of named axes in the spec doesn't matter!\n+ out = xmap(partial(jnp.einsum, '{i,j},{k,j}->{k,i}'),\n+ in_axes=(['i', 'j', ...], ['j', 'k', ...]),\n+ out_axes=['i', 'k', ...])(x, y)\n+ expected = np.einsum('ij,jk->ik', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=True)\n+\n+ def test_xeinsum_no_named_axes_vector_dot(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3)\n+ y = rng.randn(3)\n+ out = jnp.einsum('i,i->', x, y, _use_xeinsum=True)\n+ expected = np.einsum('i,i->', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=False)\n+\n+ def test_xeinsum_no_named_axes_batch_vector_dot(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3, 2)\n+ y = rng.randn(3, 2)\n+ out = jnp.einsum('ij,ij->i', x, y, _use_xeinsum=True)\n+ expected = np.einsum('ij,ij->i', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=True)\n+\n+ def test_xeinsum_no_named_axes_reduce_sum(self):\n+ rng = np.random.RandomState(0)\n+ x = rng.randn(3)\n+ y = rng.randn()\n+ out = jnp.einsum('i,->', x, y, _use_xeinsum=True)\n+ expected = np.einsum('i,->', x, y)\n+ self.assertAllClose(out, expected, check_dtypes=True)\nclass XMapErrorTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add xeinsum, an einsum for xmap (& einsum easter egg) Co-authored-by: Adam Paszke <apaszke@google.com>
260,335
19.01.2021 18:38:53
28,800
203af4517b157cb98fd7d0a82e36e25b5b6a1bbb
revive the leak checker, as a debug mode
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -108,12 +108,6 @@ def _initial_style_jaxprs_with_common_consts(funs: Sequence[Callable],\ndef _abstractify(x):\nreturn raise_to_shaped(core.get_aval(x))\n-def _disable_jit_impl(prim, interp, *args, **kwargs):\n- if jax.api._jit_is_disabled():\n- return interp(*args, **kwargs)\n- else:\n- return xla.apply_primitive(prim, *args, **kwargs)\n-\ndef _typecheck_param(prim, param, name, msg_required, pred):\nmsg = (f'invalid {prim} param {name} of type {type(param).__name__}, '\nf'{msg_required} required:')\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -21,8 +21,11 @@ from typing import Any, Callable\nimport numpy as np\n+import jax\n+\npartial = functools.partial\n+\ndef safe_zip(*args):\nn = len(args[0])\nfor arg in args[1:]:\n@@ -181,9 +184,23 @@ def split_merge(predicate, xs):\nreturn lhs, rhs, merge\ndef cache(max_size=4096):\n- return functools.lru_cache(maxsize=max_size)\n+ def wrap(f):\n+ cached = functools.lru_cache(maxsize=max_size)(f)\n+\n+ @functools.wraps(f)\n+ def wrapper(*args, **kwargs):\n+ if jax.core.debug_state.check_leaks:\n+ return f(*args, **kwargs)\n+ else:\n+ return cached(*args, **kwargs)\n+\n+ wrapper.cache_clear = cached.cache_clear\n+ wrapper.cache_info = cached.cache_info\n+ return wrapper\n+ return wrap\n+\n-memoize = functools.lru_cache(maxsize=None)\n+memoize: Callable[[Callable], Any] = functools.lru_cache(maxsize=None)\ndef prod(xs):\nout = 1\n" }, { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -170,3 +170,9 @@ flags.DEFINE_integer(\nint_env('JAX_TRACER_ERROR_NUM_TRACEBACK_FRAMES', 5),\nhelp='Set the number of stack frames in JAX tracer error messages.'\n)\n+\n+flags.DEFINE_bool(\n+ 'jax_check_tracer_leaks',\n+ bool_env('JAX_CHECK_TRACER_LEAKS', False),\n+ help='Turn on checking for leaked tracers as soon as a trace completes.'\n+)\n" }, { "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, suppress\nfrom collections import namedtuple\nfrom functools import total_ordering\n+import gc\nimport itertools as it\nfrom weakref import ref\nimport threading\n@@ -41,15 +42,12 @@ from ._src.pprint_util import pp, vcat, PrettyPrint\nfrom ._src import traceback_util\ntraceback_util.register_exclusion(__file__)\n-# TODO(dougalm): compilation cache breaks the leak detector. Consisder solving.\n-check_leaks = False\n-\n-# Disables internal invariant checks\n-skip_checks = not FLAGS.jax_enable_checks # not __debug__ # google doesn't use -O\n+# TODO(mattjj): move this into debug_state\n+skip_checks = not FLAGS.jax_enable_checks\n@contextmanager\ndef skipping_checks():\n- \"\"\"Context manager for temporarily disabling checks.\"\"\"\n+ \"\"\"Context manager for temporarily disabling internal checks.\"\"\"\nglobal skip_checks\nold_value, skip_checks = skip_checks, True\ntry:\n@@ -57,6 +55,20 @@ def skipping_checks():\nfinally:\nskip_checks = old_value\n+@contextmanager\n+def checking_leaks():\n+ \"\"\"Context manager for temporarily enabling tracer leak checks.\"\"\"\n+ old_value, debug_state.check_leaks = debug_state.check_leaks, True\n+ try:\n+ yield\n+ finally:\n+ debug_state.check_leaks = old_value\n+\n+class DebugState(threading.local):\n+ def __init__(self):\n+ self.check_leaks = FLAGS.jax_check_tracer_leaks\n+debug_state = DebugState()\n+\nzip = safe_zip\nmap = safe_map\n@@ -742,16 +754,22 @@ def new_main(trace_type: Type[Trace],\ntry:\nyield main\nfinally:\n- thread_local_state.trace_state.trace_stack.pop()\n+ stack.pop()\nif dynamic:\nstack.dynamic = prev_dynamic\n- if check_leaks:\n+ if debug_state.check_leaks:\nt = ref(main)\ndel main\nif t() is not None:\n- print(thread_local_state.trace_state.trace_stack)\n- raise Exception('Leaked trace {}'.format(t()))\n+ # handle case where gc doesn't see the leak (Python internal error?)\n+ # TODO(mattjj): investigate this issue\n+ refs = gc.get_referrers\n+ if not (len(refs(t())) == 1 and # Trace\n+ len(refs(refs(t())[0])) == 1 and # Tracer\n+ len(refs(refs(refs(t())[0])[0])) == 1 and # Tracers arglist\n+ len(refs(refs(refs(refs(t())[0])[0])[0])) == 0): # nothing...\n+ raise Exception(f'Leaked trace {t()}')\n@contextmanager\ndef new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\n@@ -766,6 +784,12 @@ def new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\nstack.dynamic = prev_dynamic\nstack.stack[0] = prev_base\n+ if debug_state.check_leaks:\n+ t = ref(main)\n+ del main\n+ if t() is not None:\n+ raise Exception('Leaked trace {}'.format(t()))\n+\n@contextmanager\ndef eval_context():\nwith new_base_main(EvalTrace):\n@@ -780,11 +804,12 @@ def new_sublevel() -> Generator[None, None, None]:\nfinally:\nthread_local_state.trace_state.substack.pop()\n- if check_leaks:\n- t = ref(sublevel)\n- del sublevel\n- if t() is not None:\n- raise Exception('Leaked sublevel {}'.format(t()))\n+ # TODO(mattjj): to check sublevel leaks, we need to make Sublevel weakref-able\n+ # if debug_state.check_leaks:\n+ # t = ref(sublevel)\n+ # del sublevel\n+ # if t() is not None:\n+ # raise Exception('Leaked sublevel {}'.format(t()))\ndef maybe_new_sublevel(trace):\n# dynamic traces run the WrappedFun, so we raise the sublevel for them\n@@ -1136,7 +1161,7 @@ class AbstractToken(AbstractValue):\ndef str_short(self): return 'Tok'\ndef at_least_vspace(self): return self\n-abstract_token = AbstractToken()\n+abstract_token: AbstractToken = AbstractToken()\ndef raise_to_shaped(aval: AbstractValue, weak_type=None):\n@@ -1678,7 +1703,7 @@ def omnistaging_disabler() -> None:\nfinally:\nthread_local_state.trace_state.trace_stack.pop(bottom)\n- if check_leaks:\n+ if debug_state.check_leaks:\nt = ref(main)\ndel main\nif t() is not None:\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -899,6 +899,9 @@ def closure_convert(fun, *example_args):\n\"\"\"\nflat_args, in_tree = tree_flatten(example_args)\nin_avals = tuple(map(abstractify, flat_args))\n+ if core.debug_state.check_leaks:\n+ return _closure_convert_for_avals.__wrapped__(fun, in_tree, in_avals)\n+ else:\nreturn _closure_convert_for_avals(fun, in_tree, in_avals)\n@cache()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/ad.py", "new_path": "jax/interpreters/ad.py", "diff": "@@ -487,7 +487,7 @@ def defbilinear_broadcasting(bcast, prim, lhs_rule, rhs_rule):\nrhs_jvp = lambda g, x, y, **kwargs: prim.bind(x, bcast(g, x), **kwargs)\ndefjvp(prim, lhs_jvp, rhs_jvp)\nprimitive_transposes[prim] = partial(bilinear_transpose, lhs_rule, rhs_rule)\n-defbilinear = partial(defbilinear_broadcasting, lambda g, x: g)\n+defbilinear: Callable = partial(defbilinear_broadcasting, lambda g, x: g)\ndef bilinear_transpose(lhs_rule, rhs_rule, cotangent, x, y, **kwargs):\nassert is_undefined_primal(x) ^ is_undefined_primal(y)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -419,10 +419,11 @@ def batched_traceable(size, batched, instantiate, axis_name, *vals):\nwith core.new_main(BatchTrace, axis_name=axis_name) as main:\nwith core.extend_axis_env(axis_name, size, main):\ntrace = main.with_cur_sublevel()\n- ans = yield map(partial(BatchTracer, trace), vals, in_dims), {}\n+ in_tracers = map(partial(BatchTracer, trace), vals, in_dims)\n+ ans = yield in_tracers, {}\nout_tracers = map(trace.full_raise, ans)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- del main, out_tracers\n+ del main, trace, ans, in_tracers, out_tracers\nif type(instantiate) is bool:\ninstantiate = [instantiate] * len(out_vals)\nout_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0\n@@ -432,7 +433,6 @@ def batched_traceable(size, batched, instantiate, axis_name, *vals):\nfor d, inst in zip(out_dims, instantiate)]\nyield out_vals, out_batched\n-\n@lu.transformation_with_aux\ndef batch_custom_jvp_subtrace(main, in_dims, *in_vals):\nsize, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -505,7 +505,7 @@ def trace_to_jaxpr(fun: lu.WrappedFun, pvals: Sequence[PartialVal],\nfun = trace_to_subjaxpr(fun, main, instantiate)\njaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)\nassert not env\n- del main\n+ del main, fun, env\nreturn jaxpr, out_pvals, consts\n@@ -1184,7 +1184,7 @@ def trace_to_jaxpr_dynamic(fun: lu.WrappedFun, in_avals: Sequence[AbstractValue]\nmain.source_info = fun_sourceinfo(fun.f) # type: ignore\nmain.jaxpr_stack = () # type: ignore\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)\n- del main\n+ del main, fun\nreturn jaxpr, out_avals, consts\ndef trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\n@@ -1196,6 +1196,7 @@ def trace_to_subjaxpr_dynamic(fun: lu.WrappedFun, main: core.MainTrace,\nans = fun.call_wrapped(*in_tracers)\nout_tracers = map(trace.full_raise, ans)\njaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)\n+ del fun, main, trace, frame, in_tracers, out_tracers, ans\nreturn jaxpr, out_avals, consts\n@contextlib.contextmanager\n@@ -1213,7 +1214,7 @@ def trace_to_jaxpr_final(fun: lu.WrappedFun, in_avals: Sequence[AbstractValue]):\nmain.source_info = fun_sourceinfo(fun.f) # type: ignore\nmain.jaxpr_stack = () # type: ignore\njaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)\n- del main\n+ del fun, main\nreturn jaxpr, out_avals, consts\ndef partial_eval_to_jaxpr_dynamic(fun: lu.WrappedFun, in_pvals: Sequence[PartialVal]):\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -1438,7 +1438,7 @@ def _remat_translation_rule(c, axis_env, in_nodes,\ndummy_subc = dummy_subc.build(xops.Tuple(dummy_subc, out_nodes))\nreturn xops.Conditional(pred, true_op, remat_subc, false_op, dummy_subc)\n-call_translations[pe.remat_call_p] = _remat_translation_rule\n+call_translations[pe.remat_call_p] = _remat_translation_rule # type: ignore\nad.primitive_transposes[core.named_call_p] = partial(ad.call_transpose,\n" }, { "change_type": "MODIFY", "old_path": "jax/linear_util.py", "new_path": "jax/linear_util.py", "diff": "@@ -63,10 +63,13 @@ data must be immutable, because it will be stored in function memoization tables\n\"\"\"\nimport threading\n+from functools import partial\nfrom typing import Any, Tuple, Callable\nimport weakref\n+from . import core\nfrom ._src.util import curry\n+from .tree_util import tree_map\nfrom ._src import traceback_util\ntraceback_util.register_exclusion(__file__)\n@@ -154,7 +157,7 @@ class WrappedFun(object):\ngen = gen(*(gen_static_args + tuple(args)), **kwargs)\nargs, kwargs = next(gen)\nstack.append((gen, out_store))\n- gen = None\n+ gen = gen_static_args = out_store = None\ntry:\nans = self.f(*args, **dict(self.params, **kwargs))\n@@ -167,7 +170,7 @@ class WrappedFun(object):\nstack.pop()[0].close()\nraise\n- del args\n+ args = kwargs = None\nwhile stack:\ngen, out_store = stack.pop()\nans = gen.send(ans)\n@@ -242,6 +245,9 @@ def cache(call: Callable):\ndef memoized_fun(fun: WrappedFun, *args):\ncache = fun_caches.setdefault(fun.f, {})\n+ if core.debug_state.check_leaks:\n+ key = (_copy_main_traces(fun.transforms), fun.params, args)\n+ else:\nkey = (fun.transforms, fun.params, args)\nresult = cache.get(key, None)\nif result is not None:\n@@ -266,6 +272,13 @@ def cache(call: Callable):\nreturn memoized_fun\n+@partial(partial, tree_map)\n+def _copy_main_traces(x):\n+ if isinstance(x, core.MainTrace):\n+ return core.MainTrace(x.level, x.trace_type, **x.payload)\n+ else:\n+ return x\n+\n@transformation\ndef hashable_partial(x, *args):\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2174,6 +2174,127 @@ class APITest(jtu.JaxTestCase):\n# Should not crash.\nvjp_fun(arr)\n+ def test_leak_checker_catches_a_jit_leak(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ lst = []\n+\n+ @jit\n+ def f(x):\n+ lst.append(x)\n+ return x\n+\n+ with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n+ f(3)\n+\n+ def test_leak_checker_catches_a_pmap_leak(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ lst = []\n+\n+ @api.pmap\n+ def f(x):\n+ lst.append(x)\n+ return x\n+\n+ with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n+ f(np.ones(1))\n+\n+ def test_leak_checker_catches_a_grad_leak(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ lst = []\n+\n+ def f(x):\n+ lst.append(x)\n+ return x\n+\n+ with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n+ api.grad(f)(3.)\n+\n+ def test_leak_checker_avoids_false_positives(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ @jit\n+ def f(x):\n+ return x\n+ f(3) # doesn't crash\n+ api.vmap(f)(np.arange(3)) # doesn't crash\n+ api.grad(f)(3.) # doesn't crash\n+\n+ @api.pmap\n+ def f(x):\n+ return x\n+ f(np.ones(1)) # doesn't crash\n+ api.vmap(f)(np.ones((1, 1))) # doesn't crash\n+\n+ def test_leak_checker_catches_a_scan_leak(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ lst = []\n+\n+ to_scan = lambda c, x: (lst.append(c) or jnp.sin(c), None)\n+\n+ with self.assertRaisesRegex(Exception, r\"Leaked trace\"):\n+ lax.scan(to_scan, 1., np.arange(3.))\n+\n+ def test_leak_checker_avoids_false_positives_scan(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ to_scan = lambda c, x: (jnp.sin(c), None)\n+ lax.scan(to_scan, 1., np.arange(3.)) # doesn't crash\n+\n+ def test_leak_checker_avoids_false_positives_scan_jvp(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ to_scan = lambda c, x: (c, None)\n+\n+ def f(x):\n+ lax.scan(to_scan, x, None, length=1)\n+ api.jvp(f, (3.,), (1.,)) # doesn't crash\n+\n+ def test_leak_checker_avoids_false_positives_scan_vmap(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ with core.checking_leaks():\n+ to_scan = lambda c, _: (1., None)\n+\n+ @api.vmap\n+ def f(x):\n+ print(x)\n+ lax.scan(to_scan, x, None, length=1)\n+ f(np.arange(5.)) # doesn't crash\n+\n+ def test_leak_checker_avoids_false_positives_scan_vmap_2(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ # This test covers an edge case which fails without the extra check in\n+ # core.py, with the comment \"gc doesn't see the leak\".\n+ with core.checking_leaks():\n+ to_scan = lambda c, _: (c, None)\n+\n+ @api.vmap\n+ def f(x):\n+ print(x)\n+ lax.scan(to_scan, x, None, length=1)\n+ f(np.arange(5.)) # doesn't crash\n+\nclass RematTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
revive the leak checker, as a debug mode Co-authored-by: James Bradbury <jekbradbury@google.com>
260,335
21.01.2021 21:29:09
28,800
9787894d94556c4a3b5c878c00be2c178328fa88
refactor batching transform logic, fix leak checks See PR description in for details.
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -41,7 +41,7 @@ from . import lib\nfrom . import linear_util as lu\nfrom . import ad_util\nfrom . import dtypes\n-from .core import eval_jaxpr\n+from .core import eval_jaxpr, checking_leaks\nfrom .api_util import (flatten_fun, apply_flat_fun, flatten_fun_nokwargs,\nflatten_fun_nokwargs2, argnums_partial,\nargnums_partial_except, flatten_axes, donation_vector,\n@@ -1218,11 +1218,11 @@ def vmap(fun: F, in_axes=0, out_axes=0, axis_name=None) -> F:\nf = lu.wrap_init(fun)\nflat_fun, out_tree = flatten_fun(f, in_tree)\nin_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, (in_axes, 0), kws=True)\n- _ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"vmap\", kws=True)\n- out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,\n- lambda: flatten_axes(\"vmap out_axes\", out_tree(),\n- out_axes),\n- axis_name=axis_name)\n+ axis_size = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"vmap\", kws=True)\n+ out_flat = batching.batch(\n+ flat_fun, axis_name, axis_size, in_axes_flat,\n+ lambda: flatten_axes(\"vmap out_axes\", out_tree(), out_axes)\n+ ).call_wrapped(*args_flat)\nreturn tree_unflatten(out_tree(), out_flat)\nreturn batched_fun\n" }, { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -18,7 +18,6 @@ from operator import attrgetter\nfrom contextlib import contextmanager, suppress\nfrom collections import namedtuple\nfrom functools import total_ordering\n-import gc\nimport itertools as it\nfrom weakref import ref\nimport threading\n@@ -472,6 +471,9 @@ def escaped_tracer_error(tracer, detail=None):\nelse:\nmsg += ('\\nThe function being traced when the tracer leaked was '\nf'{fun_source_info}.')\n+ msg += ('\\nTo catch the leak earlier, try setting the environment variable '\n+ 'JAX_CHECK_TRACER_LEAKS or using the `jax.checking_leaks` context '\n+ 'manager.')\nreturn UnexpectedTracerError(msg)\nclass UnexpectedTracerError(Exception): pass\n@@ -762,13 +764,6 @@ def new_main(trace_type: Type[Trace],\nt = ref(main)\ndel main\nif t() is not None:\n- # handle case where gc doesn't see the leak (Python internal error?)\n- # TODO(mattjj): investigate this issue\n- refs = gc.get_referrers\n- if not (len(refs(t())) == 1 and # Trace\n- len(refs(refs(t())[0])) == 1 and # Tracer\n- len(refs(refs(refs(t())[0])[0])) == 1 and # Tracers arglist\n- len(refs(refs(refs(refs(t())[0])[0])[0])) == 0): # nothing...\nraise Exception(f'Leaked trace {t()}')\n@contextmanager\n" }, { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -627,13 +627,14 @@ def _custom_vjp_call_jaxpr_vmap(\nargs, in_dims, axis_name, *, fun_jaxpr: core.ClosedJaxpr,\nfwd_jaxpr_thunk: Callable[[], Tuple[core.Jaxpr, Sequence[Any]]],\nbwd: lu.WrappedFun, out_trees: Callable, num_consts: int):\n- size, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\n+ axis_size, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\nargs = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0\nelse x for x, d in zip(args, in_dims)]\nin_batched = [d is not not_mapped for d in in_dims]\n_, args_batched = split_list(in_batched, [num_consts])\n- batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False, axis_name)\n+ batched_fun_jaxpr, out_batched = batching.batch_jaxpr(\n+ fun_jaxpr, axis_size, in_batched, False, axis_name)\nout_dims1 = [0 if b else not_mapped for b in out_batched]\nout_dims2 = []\n@@ -641,15 +642,14 @@ def _custom_vjp_call_jaxpr_vmap(\ndef batched_fwd_jaxpr_thunk():\nfwd_jaxpr = core.ClosedJaxpr(*fwd_jaxpr_thunk()) # consts can be tracers\nbatched_fwd_jaxpr, out_batched = batching.batch_jaxpr(\n- fwd_jaxpr, size, args_batched, False, axis_name)\n+ fwd_jaxpr, axis_size, args_batched, False, axis_name)\nout_dims2.append([0 if b else not_mapped for b in out_batched])\nreturn batched_fwd_jaxpr.jaxpr, batched_fwd_jaxpr.consts\nfwd_args_batched = [0 if b else not_mapped for b in args_batched]\nfwd_out_dims = lambda: out_dims2[0]\n- # TODO(mattjj,apaszke): Support collectives in custom_vjp?\n- batched_bwd = batching.batch_fun(bwd, fwd_out_dims, fwd_args_batched,\n- axis_name='__unused_axis_name', sum_match=True)\n+ batched_bwd = batching.batch(bwd, axis_name, axis_size, fwd_out_dims,\n+ fwd_args_batched)\nbatched_outs = custom_vjp_call_jaxpr_p.bind(\n*args, fun_jaxpr=batched_fun_jaxpr,\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -28,50 +28,52 @@ from . import partial_eval as pe\nmap = safe_map\n+def batch(fun: lu.WrappedFun, axis_name, axis_size, in_dims, out_dim_dests,\n+ ) -> lu.WrappedFun:\n+ # anlogue of `jvp` in ad.py\n+ fun, out_dims_thunk = batch_subtrace(fun)\n+ return _match_axes(batchfun(fun, axis_name, axis_size, in_dims),\n+ axis_size, out_dims_thunk, out_dim_dests)\n-def batch(fun: lu.WrappedFun, in_vals, in_dims, out_dim_dests, axis_name):\n- # executes a batched version of `fun` following out_dim_dests\n- batched_fun = batch_fun(fun, in_dims, out_dim_dests, axis_name=axis_name)\n- return batched_fun.call_wrapped(*in_vals)\n+@lu.transformation\n+def batchfun(axis_name, axis_size, in_dims, *in_vals):\n+ # analogue of `jvpfun` in ad.py\n+ in_dims = in_dims() if callable(in_dims) else in_dims\n+ in_dims = [canonicalize_axis(ax, np.ndim(x)) if isinstance(ax, int)\n+ and not isinstance(core.get_aval(x), core.AbstractUnit) # non-omnistaging\n+ else ax for x, ax in zip(in_vals, in_dims)]\n+ with core.new_main(BatchTrace, axis_name=axis_name) as main:\n+ with core.extend_axis_env(axis_name, axis_size, main):\n+ out_vals = yield (main, in_dims, *in_vals), {}\n+ del main\n+ yield out_vals\n@lu.transformation_with_aux\n-def batch_subtrace(main, in_dims, *in_vals, **params):\n+def batch_subtrace(main, in_dims, *in_vals):\n+ # analogue of `jvp_subtrace` in ad.py\ntrace = main.with_cur_sublevel()\nin_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\nfor val, dim in zip(in_vals, in_dims)]\n- outs = yield in_tracers, params\n+ outs = yield in_tracers, {}\nout_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\nyield out_vals, out_dims\n-\n-def batch_fun(fun : lu.WrappedFun, in_dims, out_dim_dests, axis_name,\n- sum_match=False):\n- # transformation version of batch, which doesn't call the function\n- fun, out_dims = batch_subtrace(fun)\n- return _batch_fun(fun, axis_name, sum_match, in_dims, out_dims, out_dim_dests)\n-\n@lu.transformation\n-def _batch_fun(axis_name, sum_match, in_dims, out_dims_thunk, out_dim_dests,\n- *in_vals, **params):\n- in_dims = in_dims() if callable(in_dims) else in_dims\n- in_dims = [\n- canonicalize_axis(dim, np.ndim(val)) if isinstance(dim, int) else dim\n- for val, dim in zip(in_vals, in_dims)]\n- axis_size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\n- with core.new_main(BatchTrace, axis_name=axis_name) as main:\n- with core.extend_axis_env(axis_name, axis_size, main):\n- out_vals = yield (main, in_dims,) + in_vals, params\n- del main\n+def _match_axes(axis_size, out_dims_thunk, out_dim_dests, *in_vals):\n+ out_vals = yield in_vals, {}\nout_dim_dests = out_dim_dests() if callable(out_dim_dests) else out_dim_dests\nout_dims = out_dims_thunk()\nfor od, od_dest in zip(out_dims, out_dim_dests):\n- if od is not None and not isinstance(od_dest, int) and not sum_match:\n+ if od is not None and not isinstance(od_dest, int):\nmsg = f\"vmap has mapped output but out_axes is {od_dest}\"\nraise ValueError(msg)\n- out_vals = map(partial(matchaxis, axis_size, sum_match=sum_match),\n- out_dims, out_dim_dests, out_vals)\n- yield out_vals\n+ yield map(partial(matchaxis, axis_size), out_dims, out_dim_dests, out_vals)\n+\n+\n+# These next two functions, `batch_fun2` and `_batch_fun2`, are deprecated; the\n+# former is only called from `custom_transforms`, which itself is deprecated.\n+# TODO(mattjj): delete these along with custom_transforms\ndef batch_fun2(fun: lu.WrappedFun, in_dims):\n# like `batch_fun` but returns output batch dims (so no out_dim_dests)\n@@ -248,11 +250,12 @@ class BatchTrace(Trace):\ndef process_custom_vjp_call(self, prim, fun, fwd, bwd, tracers, *, out_trees):\nin_vals, in_dims = unzip2((t.val, t.batch_dim) for t in tracers)\n+ axis_size, = {x.shape[d] for x, d in zip(in_vals, in_dims)\n+ if d is not not_mapped}\nfun, out_dims1 = batch_subtrace(fun, self.main, in_dims)\nfwd, out_dims2 = batch_subtrace(fwd, self.main, in_dims)\n- # TODO(mattjj,apaszke): support collectives in custom_vjp?\n- bwd = batch_fun(bwd, out_dims2, in_dims,\n- axis_name='__unused_axis_name', sum_match=True)\n+ bwd = batch_custom_vjp_bwd(bwd, self.axis_name, axis_size,\n+ out_dims2, in_dims)\nout_vals = prim.bind(fun, fwd, bwd, *in_vals, out_trees=out_trees)\nfst, out_dims = lu.merge_linear_aux(out_dims1, out_dims2)\nif not fst:\n@@ -271,6 +274,18 @@ def _main_trace_for_axis_names(main_trace: core.MainTrace,\naxis_name = (axis_name,)\nreturn any(main_trace is core.axis_frame(n).main_trace for n in axis_name)\n+def batch_custom_vjp_bwd(bwd, axis_name, axis_size, in_dims, out_dim_dests):\n+ bwd, out_dims_thunk = batch_subtrace(bwd)\n+ return _match_axes_and_sum(batchfun(bwd, axis_name, axis_size, in_dims),\n+ axis_size, out_dims_thunk, out_dim_dests)\n+\n+@lu.transformation\n+def _match_axes_and_sum(axis_size, out_dims_thunk, out_dim_dests, *in_vals):\n+ # this is like _match_axes, but we do reduce-sums as needed\n+ out_vals = yield in_vals, {}\n+ yield map(partial(matchaxis, axis_size, sum_match=True),\n+ out_dims_thunk(), out_dim_dests, out_vals)\n+\n### primitives\n@@ -399,35 +414,30 @@ def bdim_at_front(x, bdim, size):\nreturn moveaxis(x, bdim, 0)\n-def _promote_aval_rank(sz, aval):\n- if aval is core.abstract_unit:\n- return core.abstract_unit\n- else:\n- return ShapedArray((sz,) + aval.shape, aval.dtype)\n-\n-def batch_jaxpr(closed_jaxpr, size, batched, instantiate, axis_name):\n+def batch_jaxpr(closed_jaxpr, axis_size, in_batched, instantiate, axis_name):\nf = lu.wrap_init(core.jaxpr_as_fun(closed_jaxpr))\n- f, batched_out = batched_traceable(f, size, batched, instantiate, axis_name)\n- avals_in = [_promote_aval_rank(size, a) if b else a\n- for a, b in zip(closed_jaxpr.in_avals, batched)]\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])\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)]\njaxpr_out, _, consts = pe.trace_to_jaxpr_dynamic(f, avals_in)\n- return core.ClosedJaxpr(jaxpr_out, consts), batched_out()\n+ return core.ClosedJaxpr(jaxpr_out, consts), out_batched()\n@lu.transformation_with_aux\n-def batched_traceable(size, batched, instantiate, axis_name, *vals):\n- in_dims = [0 if b else None for b in batched]\n- with core.new_main(BatchTrace, axis_name=axis_name) as main:\n- with core.extend_axis_env(axis_name, size, main):\n+def batch_subtrace_instantiate(instantiate, axis_size, 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- in_tracers = map(partial(BatchTracer, trace), vals, in_dims)\n- ans = yield in_tracers, {}\n- out_tracers = map(trace.full_raise, ans)\n+ in_tracers = [BatchTracer(trace, val, dim) if dim is not None else val\n+ for val, dim in zip(in_vals, in_dims)]\n+ outs = yield in_tracers, {}\n+ out_tracers = map(trace.full_raise, outs)\nout_vals, out_dims = unzip2((t.val, t.batch_dim) for t in out_tracers)\n- del main, trace, ans, in_tracers, out_tracers\n+\nif type(instantiate) is bool:\ninstantiate = [instantiate] * len(out_vals)\nout_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0\n- else broadcast(x, size, 0) if d is not_mapped and inst else x\n+ else broadcast(x, axis_size, 0) if d is not_mapped and inst else x\nfor x, d, inst in zip(out_vals, out_dims, instantiate)]\nout_batched = [d is not not_mapped or inst\nfor d, inst in zip(out_dims, instantiate)]\n@@ -464,15 +474,16 @@ def _merge_bdims(x, y):\ndef omnistaging_disabler() -> None:\nglobal batch_jaxpr\n- def batch_jaxpr(jaxpr, size, batched, instantiate, axis_name):\n+ def batch_jaxpr(jaxpr, axis_size, in_batched, instantiate, axis_name):\nf = lu.wrap_init(core.jaxpr_as_fun(jaxpr))\n- f, batched_out = batched_traceable(f, size, batched, instantiate, axis_name)\n- avals_in = [_promote_aval_rank(size, a) if b else a\n- for a, b in zip(jaxpr.in_avals, batched)]\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])\n+ avals_in = [core.unmapped_aval(axis_size, 0, aval) if b else aval\n+ for aval, b in zip(jaxpr.in_avals, in_batched)]\nin_pvals = [pe.PartialVal.unknown(aval) for aval in avals_in]\njaxpr_out, pvals_out, consts_out = pe.trace_to_jaxpr(f, in_pvals, instantiate=True)\navals_out, _ = unzip2(pvals_out)\n- return core.ClosedJaxpr(jaxpr_out, consts_out), batched_out()\n+ return core.ClosedJaxpr(jaxpr_out, consts_out), out_batched()\ncollective_rules: Dict[core.Primitive, Callable] = {}\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1542,10 +1542,7 @@ def vtile(f_flat,\nyield map(untile_axis, outputs_flat, out_axes_flat)\nreturn _map_to_tile(\n- batching.batch_fun(f_flat,\n- in_axes_flat,\n- out_axes_flat,\n- axis_name=axis_name))\n+ batching.batch(f_flat, axis_name, tile_size, in_axes_flat, out_axes_flat))\n_forbidden_primitives = {\n'xla_pmap': 'pmap',\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2276,7 +2276,6 @@ class APITest(jtu.JaxTestCase):\n@api.vmap\ndef f(x):\n- print(x)\nlax.scan(to_scan, x, None, length=1)\nf(np.arange(5.)) # doesn't crash\n@@ -2284,14 +2283,11 @@ class APITest(jtu.JaxTestCase):\nif not config.omnistaging_enabled:\nraise unittest.SkipTest(\"test only works with omnistaging\")\n- # This test covers an edge case which fails without the extra check in\n- # core.py, with the comment \"gc doesn't see the leak\".\nwith core.checking_leaks():\nto_scan = lambda c, _: (c, None)\n@api.vmap\ndef f(x):\n- print(x)\nlax.scan(to_scan, x, None, length=1)\nf(np.arange(5.)) # doesn't crash\n" } ]
Python
Apache License 2.0
google/jax
refactor batching transform logic, fix leak checks See PR description in #5492 for details. Co-authored-by: Peter Hawkins <phawkins@google.com>
260,335
23.01.2021 14:17:22
28,800
a7bfebe4bc1cdeca333675ccdfd19e385dbc864b
improve leak checker flag description
[ { "change_type": "MODIFY", "old_path": "jax/config.py", "new_path": "jax/config.py", "diff": "@@ -174,5 +174,7 @@ flags.DEFINE_integer(\nflags.DEFINE_bool(\n'jax_check_tracer_leaks',\nbool_env('JAX_CHECK_TRACER_LEAKS', False),\n- help='Turn on checking for leaked tracers as soon as a trace completes.'\n+ help=('Turn on checking for leaked tracers as soon as a trace completes. '\n+ 'Enabling leak checking may have performance impacts: some caching '\n+ 'is disabled, and other overheads may be added.'),\n)\n" } ]
Python
Apache License 2.0
google/jax
improve leak checker flag description
260,628
24.01.2021 16:15:31
0
1524b8218907d826c07f33570f3d1cc044e4f0ef
add support for scipy.stats.poisson.cdf
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/stats/poisson.py", "new_path": "jax/_src/scipy/stats/poisson.py", "diff": "@@ -18,7 +18,7 @@ import scipy.stats as osp_stats\nfrom jax import lax\nfrom jax._src.numpy.util import _wraps\nfrom jax._src.numpy import lax_numpy as jnp\n-from jax.scipy.special import xlogy, gammaln\n+from jax.scipy.special import xlogy, gammaln, gammaincc\n@_wraps(osp_stats.poisson.logpmf, update_doc=False)\n@@ -32,3 +32,11 @@ def logpmf(k, mu, loc=0):\n@_wraps(osp_stats.poisson.pmf, update_doc=False)\ndef pmf(k, mu, loc=0):\nreturn jnp.exp(logpmf(k, mu, loc))\n+\n+@_wraps(osp_stats.poisson.cdf, update_doc=False)\n+def cdf(k, mu, loc=0):\n+ k, mu, loc = jnp._promote_args_inexact(\"poisson.logpmf\", k, mu, loc)\n+ zero = jnp._constant_like(k, 0)\n+ x = lax.sub(k, loc)\n+ p = gammaincc(jnp.floor(1 + x), mu)\n+ return jnp.where(lax.lt(x, zero), zero, p)\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/poisson.py", "new_path": "jax/scipy/stats/poisson.py", "diff": "from jax._src.scipy.stats.poisson import (\nlogpmf,\npmf,\n+ cdf\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -78,6 +78,23 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=1e-3)\nself._CompileAndCheck(lax_fun, args_maker)\n+ @genNamedParametersNArgs(3)\n+ def testPoissonCdf(self, shapes, dtypes):\n+ rng = jtu.rand_default(self.rng())\n+ scipy_fun = osp_stats.poisson.cdf\n+ lax_fun = lsp_stats.poisson.cdf\n+\n+ def args_maker():\n+ k, mu, loc = map(rng, shapes, dtypes)\n+ # clipping to ensure that rate parameter is strictly positive\n+ mu = np.clip(np.abs(mu), a_min=0.1, a_max=None)\n+ return [k, mu, loc]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=1e-3)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\n+\n@genNamedParametersNArgs(3)\ndef testBernoulliLogPmf(self, shapes, dtypes):\nrng = jtu.rand_default(self.rng())\n" } ]
Python
Apache License 2.0
google/jax
add support for scipy.stats.poisson.cdf
260,384
25.01.2021 16:52:38
18,000
7865043341c3b67d280004b6828860bc31f6cbdc
Improve batched collective rule for all_gather_p When an all_gather references a vmapped axis, there is a particularly simple way of implementing it: simply "forget" that the axis was mapped, and return the full array. Conveniently, this doesn't require any explicit broadcasting, and makes it possible to use out_axes=None with the results.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -796,14 +796,7 @@ def _all_gather_batched_collective(frame, vals_in, dims_in, all_gather_dimension\nassert axis_name == frame.name, \"batcher called with wrong axis name\"\n(x,), (d,) = vals_in, dims_in\nassert d is not batching.not_mapped\n- if d <= all_gather_dimension:\n- all_gather_dimension += 1\n- else:\n- d += 1\n- out_shape = list(x.shape)\n- out_shape.insert(all_gather_dimension, axis_size)\n- broadcast_dims = [i for i in range(len(out_shape)) if i != all_gather_dimension]\n- return lax.broadcast_in_dim(x, out_shape, broadcast_dims), d\n+ return _moveaxis(d, all_gather_dimension, x), batching.not_mapped\nall_gather_p = core.Primitive('all_gather')\nall_gather_p.def_abstract_eval(_all_gather_abstract_eval)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1170,6 +1170,41 @@ class BatchingTest(jtu.JaxTestCase):\ny = vmap(f)(a=jnp.array([1]), b=jnp.array([2])) # doesn't work\nself.assertAllClose(x, y)\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAllGatherToUnmapped(self):\n+ def f(x):\n+ return lax.all_gather(x, axis_name='i')\n+\n+ x = jnp.arange(15).reshape((3, 5))\n+ # Original mapped axis becomes first axis of unmapped return value.\n+ self.assertAllClose(vmap(f, axis_name='i', in_axes=1, out_axes=None)(x), x.T)\n+\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testBatchedAllGather(self):\n+ def f(x):\n+ return lax.all_gather(x, axis_name='i')\n+\n+ x = jnp.arange(15).reshape((3, 5))\n+ res = vmap(vmap(f, axis_name='i', out_axes=None), axis_name='j')(x)\n+ self.assertAllClose(res, x)\n+\n+ res = vmap(vmap(f, axis_name='j'), axis_name='i', out_axes=None)(x)\n+ self.assertAllClose(res, x.T)\n+\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAllGatherVjp(self):\n+ def f(x):\n+ return lax.all_gather(x, axis_name='i')\n+\n+ rng = np.random.RandomState(1)\n+ x = rng.randn(3, 4)\n+ y_bar = rng.randn(3, 3, 4)\n+\n+ x_bar, = vmap(lambda x, y_bar: vjp(f, x)[1](y_bar), axis_name='i')(x, y_bar)\n+ self.assertAllClose(x_bar, np.sum(y_bar, axis=0))\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Improve batched collective rule for all_gather_p When an all_gather references a vmapped axis, there is a particularly simple way of implementing it: simply "forget" that the axis was mapped, and return the full array. Conveniently, this doesn't require any explicit broadcasting, and makes it possible to use out_axes=None with the results.
260,384
25.01.2021 17:27:39
18,000
c6a1bba308ba363f7dfaba70b42810c3f591c9c9
Add evaluation rule for all_gather. This should only be called when an all_gather runs on arguments that are not batch tracers, for instance when all_gather-ing a constant.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -743,6 +743,13 @@ def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_group\nouts = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index), 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+ # Only called when the argument is not mapped.\n+ out_shape = list(x.shape)\n+ out_shape.insert(all_gather_dimension, axis_size)\n+ broadcast_dims = [i for i in range(len(out_shape)) if i != all_gather_dimension]\n+ return lax.broadcast_in_dim(x, out_shape, broadcast_dims)\n+\ndef _all_gather_translation_rule(c, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, axis_env, platform):\n# TODO(cjfj): Enable this for TPU also?\nif (platform == 'gpu') and (all_gather_dimension == 0):\n@@ -800,6 +807,7 @@ def _all_gather_batched_collective(frame, vals_in, dims_in, all_gather_dimension\nall_gather_p = core.Primitive('all_gather')\nall_gather_p.def_abstract_eval(_all_gather_abstract_eval)\n+all_gather_p.def_impl(_all_gather_impl)\nxla.parallel_translations[all_gather_p] = _all_gather_translation_rule\nad.deflinear2(all_gather_p, _all_gather_transpose_rule)\npxla.multi_host_supported_collectives.add(all_gather_p)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1206,5 +1206,16 @@ class BatchingTest(jtu.JaxTestCase):\nx_bar, = vmap(lambda x, y_bar: vjp(f, x)[1](y_bar), axis_name='i')(x, y_bar)\nself.assertAllClose(x_bar, np.sum(y_bar, axis=0))\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testAllGatherOfConst(self):\n+ def f(x):\n+ return lax.all_gather(jnp.ones_like(x), axis_name='i')\n+\n+ x = jnp.arange(15).reshape((3, 5))\n+ self.assertAllClose(\n+ vmap(f, axis_name='i', in_axes=1, out_axes=None)(x),\n+ jnp.ones(shape=(5, 3), dtype=x.dtype))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Add evaluation rule for all_gather. This should only be called when an all_gather runs on arguments that are not batch tracers, for instance when all_gather-ing a constant.
260,384
25.01.2021 17:47:50
18,000
15b95e3ff5655470d55baafea9907b5be32ae8ca
Use np.shape instead of assuming argument has a shape attr
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -745,7 +745,7 @@ def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_group\ndef _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n# Only called when the argument is not mapped.\n- out_shape = list(x.shape)\n+ out_shape = list(np.shape(x))\nout_shape.insert(all_gather_dimension, axis_size)\nbroadcast_dims = [i for i in range(len(out_shape)) if i != all_gather_dimension]\nreturn lax.broadcast_in_dim(x, out_shape, broadcast_dims)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -1210,12 +1210,14 @@ class BatchingTest(jtu.JaxTestCase):\n\"vmap collectives only supported when omnistaging is enabled\")\ndef testAllGatherOfConst(self):\ndef f(x):\n- return lax.all_gather(jnp.ones_like(x), axis_name='i')\n+ a = lax.all_gather(jnp.ones_like(x), axis_name='i')\n+ b = lax.all_gather(1, axis_name='i')\n+ return a, b\nx = jnp.arange(15).reshape((3, 5))\n- self.assertAllClose(\n- vmap(f, axis_name='i', in_axes=1, out_axes=None)(x),\n- jnp.ones(shape=(5, 3), dtype=x.dtype))\n+ a, b = vmap(f, axis_name='i', in_axes=1, out_axes=None)(x)\n+ self.assertAllClose(a, jnp.ones(shape=(5, 3), dtype=x.dtype))\n+ self.assertAllClose(b, jnp.ones(shape=(5,), dtype=b.dtype))\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Use np.shape instead of assuming argument has a shape attr
260,509
25.01.2021 17:16:29
28,800
9dccf567ce4c2fef45398683a4e05c5a10ec7846
Clarify tracking Clarify tracing a bit and use wording that does not suggest that JAX executed python program.
[ { "change_type": "MODIFY", "old_path": "docs/jaxpr.rst", "new_path": "docs/jaxpr.rst", "diff": "@@ -104,10 +104,11 @@ inline.\nThe ``reduce_sum`` primitive has named parameters ``axes`` and ``input_shape``, in\naddition to the operand ``e``.\n-Note that JAX traces through Python-level control-flow and higher-order functions\n-when it extracts the jaxpr. This means that just because a Python program contains\n-functions and control-flow, the resulting jaxpr does not have\n-to contain control-flow or higher-order features.\n+Note that even though execution of a program that calls into JAX builds a jaxpr,\n+Python-level control-flow and Python-level functions execute normally.\n+This means that just because a Python program contains functions and control-flow,\n+the resulting jaxpr does not have to contain control-flow or higher-order features.\n+\nFor example, when tracing the function ``func3`` JAX will inline the call to\n``inner`` and the conditional ``if second.shape[0] > 4``, and will produce the same\njaxpr as before\n" } ]
Python
Apache License 2.0
google/jax
Clarify tracking Clarify tracing a bit and use wording that does not suggest that JAX executed python program.
260,335
26.01.2021 10:59:22
28,800
737c1624314e74dba800d5632e3c4f0f67990abf
relax test tolerance on tpu
[ { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -684,14 +684,18 @@ class PDotTests(jtu.JaxTestCase):\nin_axes=(['i', 'j', ...], ['j', 'k', ...]),\nout_axes=['i', 'k', ...])(x, y)\nexpected = np.einsum('ij,jk->ik', x, y)\n- self.assertAllClose(out, expected, check_dtypes=True)\n+ tol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\n+ self.assertAllClose(out, expected, check_dtypes=True,\n+ atol=tol, rtol=tol)\n# order of named axes in the spec doesn't matter!\nout = xmap(partial(jnp.einsum, '{i,j},{k,j}->{k,i}'),\nin_axes=(['i', 'j', ...], ['j', 'k', ...]),\nout_axes=['i', 'k', ...])(x, y)\nexpected = np.einsum('ij,jk->ik', x, y)\n- self.assertAllClose(out, expected, check_dtypes=True)\n+ tol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\n+ self.assertAllClose(out, expected, check_dtypes=True,\n+ atol=tol, rtol=tol)\ndef test_xeinsum_no_named_axes_vector_dot(self):\nrng = np.random.RandomState(0)\n" } ]
Python
Apache License 2.0
google/jax
relax test tolerance on tpu
260,510
26.01.2021 12:39:35
28,800
6061b0979a9ff09c664e8a58e59a187ee261b9c1
Allow `jax.custom_gradient` to return vjp with singleton return value
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -22,7 +22,7 @@ from . import core\nfrom . import dtypes\nfrom . import linear_util as lu\nfrom .tree_util import (tree_flatten, tree_unflatten, tree_map, tree_multimap,\n- register_pytree_node_class)\n+ treedef_is_leaf, register_pytree_node_class)\nfrom ._src.util import cache, safe_zip, safe_map, split_list\nfrom .api_util import flatten_fun_nokwargs, argnums_partial, wrap_hashably\nfrom .core import raise_to_shaped\n@@ -818,7 +818,10 @@ def custom_gradient(fun):\ncts_flat, out_tree_ = tree_flatten((cts,))\nif out_tree != out_tree_: raise TypeError(f'{out_tree}\\n!=\\n{out_tree_}')\ncts_out = core.eval_jaxpr(jaxpr, consts, *cts_flat)\n- return tree_unflatten(in_tree, cts_out)\n+ cts_out = tree_unflatten(in_tree, cts_out)\n+ if treedef_is_leaf(in_tree):\n+ cts_out = (cts_out,)\n+ return cts_out\nwrapped_fun.defvjp(fwd, bwd)\nreturn wrapped_fun\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4536,6 +4536,15 @@ class CustomVJPTest(jtu.JaxTestCase):\napi.grad(lambda x: jnp.sum(jnp.sin(x)))(jnp.arange(3.)) * jnp.array([3., 4., 5.]),\ncheck_dtypes=False)\n+ def test_custom_gradient_can_return_singleton_value_in_vjp(self):\n+ @api.custom_gradient\n+ def f(x):\n+ return x ** 2, lambda g: g * x\n+\n+ self.assertAllClose(f(3.), 9., check_dtypes=False)\n+ self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n+ self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n+\ndef test_closure_convert(self):\ndef minimize(objective_fn, x0):\nconverted_fn, aux_args = api.closure_convert(objective_fn, x0)\n" } ]
Python
Apache License 2.0
google/jax
Allow `jax.custom_gradient` to return vjp with singleton return value
260,335
26.01.2021 17:25:22
28,800
ff66c55709e9199e16a388c109987b7be9ed2c81
add axis_env argument to make_jaxpr fixes
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -2000,6 +2000,7 @@ def linear_transpose(fun: Callable, *primals) -> Callable:\ndef make_jaxpr(fun: Callable,\nstatic_argnums: Union[int, Iterable[int]] = (),\n+ axis_env: Optional[Sequence[Tuple[AxisName, int]]] = None,\nreturn_shape: bool = False,\n) -> Callable[..., core.ClosedJaxpr]:\n\"\"\"Creates a function that produces its jaxpr given example args.\n@@ -2009,6 +2010,12 @@ def make_jaxpr(fun: Callable,\narguments and return value should be arrays, scalars, or standard Python\ncontainers (tuple/list/dict) thereof.\nstatic_argnums: See the :py:func:`jax.jit` docstring.\n+ axis_env: Optional, a sequence of pairs where the first element is an axis\n+ name and the second element is a positive integer representing the size of\n+ the mapped axis with that name. This parameter is useful when lowering\n+ functions that involve parallel communication collectives, and it\n+ specifies the axis name/size environment that would be set up by\n+ applications of :py:func:`jax.pmap`.\nreturn_shape: Optional boolean, defaults to ``False``. If ``True``, the\nwrapped function returns a pair where the first element is the ``jaxpr``\nand the second element is a pytree with the same structure as\n@@ -2069,8 +2076,14 @@ def make_jaxpr(fun: Callable,\njaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\nin_avals = [raise_to_shaped(core.get_aval(x)) for x in jax_args]\nif config.omnistaging_enabled:\n+ with ExitStack() as stack:\n+ for axis_name, size in axis_env or []:\n+ stack.enter_context(core.extend_axis_env(axis_name, size, None))\njaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(jaxtree_fun, in_avals)\nelse:\n+ if axis_env:\n+ raise NotImplementedError(\n+ \"axis_env argument to make_jaxpr only supported with omnistaging.\")\nin_pvals = [pe.PartialVal.unknown(a) for a in in_avals]\njaxpr, out_pvals, consts = pe.trace_to_jaxpr(\njaxtree_fun, in_pvals, instantiate=True, stage_out=True) # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -2775,6 +2775,15 @@ class JaxprTest(jtu.JaxTestCase):\napi.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\nself.assertEqual(shape_tree, expected)\n+ def test_make_jaxpr_axis_env(self):\n+ if not config.omnistaging_enabled:\n+ raise unittest.SkipTest(\"test only works with omnistaging\")\n+\n+ def f(x):\n+ return x - lax.psum(x, 'i')\n+ jaxpr = api.make_jaxpr(f, axis_env=[('i', 4)])(2)\n+ self.assertIn('psum', str(jaxpr))\n+\nclass LazyTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add axis_env argument to make_jaxpr fixes #5522
260,335
26.01.2021 17:03:58
28,800
537c3d5c84e33fe1c0ae5592d7b16db6300b658f
add systematic pdot vjp tests
[ { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -650,6 +650,54 @@ class PDotTests(jtu.JaxTestCase):\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\nself.assertAllClose(result, expected, check_dtypes=False,\natol=tol, rtol=tol)\n+\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_{next(test_counter)}\",\n+ \"lhs_shape\": lhs_shape, \"rhs_shape\": rhs_shape, \"pdot_spec\": pdot_spec,\n+ \"axis_resources\": axis_resources, \"mesh_data\": mesh_data}\n+ for test_counter in [it.count()]\n+ for lhs_shape, rhs_shape in product(\n+ [(2,), (2, 4, 2, 1)],\n+ repeat=2)\n+ for pdot_spec in all_pdot_specs(lhs_shape, rhs_shape)\n+ for axis_resources, mesh_data in schedules_from_pdot_spec(\n+ pdot_spec, lhs_shape, rhs_shape)))\n+ @ignore_xmap_warning()\n+ def testPdotVJPSystematic(self, lhs_shape, rhs_shape, pdot_spec,\n+ axis_resources, mesh_data):\n+ rng = jtu.rand_default(self.rng())\n+ lhs = rng(lhs_shape, np.float32)\n+ rhs = rng(rhs_shape, np.float32)\n+\n+ expected_out, ref_vjp = jax.vjp(\n+ lambda x, y: lax.dot_general(x, y, pdot_spec.dot_general_dim_nums),\n+ lhs, rhs)\n+ out_bar = rng(expected_out.shape, np.float32)\n+ expected_lhs, expected_rhs = ref_vjp(out_bar)\n+\n+ def pdot_fun(x, y, out_bar):\n+ pdot = partial(jax.lax.pdot,\n+ axis_name=pdot_spec.contract_names,\n+ pos_batch=pdot_spec.pos_batch_after_mapping,\n+ pos_contract=pdot_spec.pos_contract_after_mapping)\n+ _, pdot_vjp = jax.vjp(pdot, x, y)\n+ return pdot_vjp(out_bar)\n+\n+ fun = xmap(pdot_fun,\n+ in_axes=[pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes,\n+ [*pdot_spec.batch_names, ...]],\n+ out_axes=(pdot_spec.lhs_in_axes, pdot_spec.rhs_in_axes),\n+ axis_resources=axis_resources)\n+\n+ with with_mesh(mesh_data):\n+ lhs_bar, rhs_bar = fun(lhs, rhs, out_bar)\n+\n+ tol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\n+ self.assertAllClose(lhs_bar, expected_lhs, check_dtypes=False,\n+ atol=tol, rtol=tol)\n+ self.assertAllClose(rhs_bar, expected_rhs, check_dtypes=False,\n+ atol=tol, rtol=tol)\n+\n@ignore_xmap_warning()\ndef test_xeinsum_vector_dot(self):\nrng = np.random.RandomState(0)\n" } ]
Python
Apache License 2.0
google/jax
add systematic pdot vjp tests
260,335
26.01.2021 19:38:40
28,800
014f9a86b40787921dc0177ce8650f224cefdca1
implement soft_pmap in terms of xmap
[ { "change_type": "MODIFY", "old_path": "jax/__init__.py", "new_path": "jax/__init__.py", "diff": "@@ -69,7 +69,6 @@ from .api import (\nshapecheck,\nShapedArray,\nShapeDtypeStruct,\n- soft_pmap,\n# TODO(phawkins): hide tree* functions from jax, update callers to use\n# jax.tree_util.\ntreedef_is_leaf,\n@@ -86,6 +85,7 @@ from .api import (\nxla, # TODO(phawkins): update users to avoid this.\nxla_computation,\n)\n+from .experimental.maps import soft_pmap\nfrom .version import __version__\n# These submodules are separate because they are in an import cycle with\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -484,15 +484,6 @@ class XeinsumSpecParser:\n### parallel primitives\n-def _allreduce_soft_pmap_rule(prim, reducer, vals, mapped, chunk_size,\n- *, axis_name, axis_index_groups):\n- if axis_index_groups is not None:\n- raise NotImplementedError(\"soft_pmap does not yet support axis_index_groups\")\n- reduced_vals = [reducer(x, [0]) if m else x for x, m in zip(vals, mapped)]\n- outs = prim.bind(*reduced_vals, axis_name=axis_name,\n- axis_index_groups=axis_index_groups)\n- return outs, (False,) * len(vals)\n-\n# This is only used for collectives that do not include the vmapped axis name,\n# which is why the rule is so simple.\ndef _collective_batcher(prim, args, dims, **params):\n@@ -593,8 +584,6 @@ def _psum_transpose_rule(cts, *args, axis_name, axis_index_groups):\npsum_p = core.Primitive('psum')\npsum_p.multiple_results = True\npsum_p.def_abstract_eval(lambda *args, **params: map(raise_to_shaped, args))\n-pxla.soft_pmap_rules[psum_p] = \\\n- partial(_allreduce_soft_pmap_rule, psum_p, lax._reduce_sum)\nxla.parallel_translations[psum_p] = partial(_allreduce_translation_rule, lax.add_p) # type: ignore\nad.deflinear2(psum_p, _psum_transpose_rule)\npxla.multi_host_supported_collectives.add(psum_p)\n@@ -957,14 +946,8 @@ def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\nunsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\nreturn xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n-def _axis_index_soft_pmap_rule(vals, mapped, chunk_size, *, axis_name):\n- assert not vals and not mapped\n- idx = axis_index(axis_name) # type: ignore\n- return idx * chunk_size + np.arange(chunk_size, dtype=np.int32), True\n-\naxis_index_p = core.Primitive('axis_index')\nxla.parallel_translations[axis_index_p] = _axis_index_translation_rule\n-pxla.soft_pmap_rules[axis_index_p] = _axis_index_soft_pmap_rule # type: ignore\naxis_index_p.def_abstract_eval(\nlambda *args, **params: ShapedArray((), np.int32))\npxla.multi_host_supported_collectives.add(axis_index_p)\n@@ -991,6 +974,7 @@ def _axis_index_bind(*, axis_name):\naxis_index_p.def_custom_bind(_axis_index_bind)\ndef _process_axis_index(self, frame):\n+ assert frame.size is not None\nreturn batching.BatchTracer(self, lax_numpy.arange(frame.size, dtype=np.int32), 0)\nbatching.BatchTrace.process_axis_index = _process_axis_index # type: ignore\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -1577,37 +1577,6 @@ def pmap(\nreturn f_pmapped\n-def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n- ) -> Callable:\n- if not config.omnistaging_enabled:\n- raise NotImplementedError(\"soft_pmap requires omnistaging.\")\n- warn(\"soft_pmap is an experimental feature and probably has bugs!\")\n- _check_callable(fun)\n- axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n-\n- if any(axis != 0 for axis in tree_leaves(in_axes)):\n- raise ValueError(f\"soft_pmap in_axes leaves must be 0 or None, got {in_axes}\")\n-\n- @wraps(fun)\n- @api_boundary\n- def f_pmapped(*args, **kwargs):\n- f = lu.wrap_init(fun)\n- args_flat, in_tree = tree_flatten((args, kwargs))\n- in_axes_flat = flatten_axes(\"soft_pmap in_axes\", in_tree, (in_axes, 0))\n- axis_size = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"soft_pmap\")\n- for arg in args_flat: _check_arg(arg)\n- flat_fun, out_tree = flatten_fun(f, in_tree)\n- # See note about out_axes_thunk in pmap for the explanation of why we choose this key\n- out_axes_thunk = HashableFunction(\n- lambda: tuple(flatten_axes(\"soft_pmap out_axes\", out_tree(), 0)),\n- closure=())\n- outs = pxla.soft_pmap(flat_fun, *args_flat, axis_name=axis_name,\n- axis_size=axis_size, in_axes=tuple(in_axes_flat),\n- out_axes_thunk=out_axes_thunk)\n- return tree_unflatten(out_tree(), outs)\n- return f_pmapped\n-\n-\ndef mask(fun: Callable, in_shapes, out_shape=None) -> Callable:\n_check_callable(fun)\nunique_ids = masking.UniqueIds()\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -26,7 +26,8 @@ from .. import numpy as jnp\nfrom .. import core\nfrom .. import linear_util as lu\nfrom ..api import _check_callable, _check_arg\n-from ..tree_util import tree_flatten, tree_unflatten, all_leaves\n+from ..tree_util import (tree_flatten, tree_unflatten, all_leaves,\n+ _replace_nones, tree_map, tree_leaves)\nfrom ..api_util import flatten_fun_nokwargs, flatten_axes\nfrom ..interpreters import partial_eval as pe\nfrom ..interpreters import pxla\n@@ -839,3 +840,27 @@ def subst_eqn_axis_names(eqn, axis_subst: Dict[AxisName, Tuple[AxisName]]):\naxis_names = (axis_names,)\nnew_axis_names = sum((axis_subst.get(name, (name,)) for name in axis_names), ())\nreturn eqn._replace(params=dict(eqn.params, axis_name=new_axis_names))\n+\n+\n+# -------- soft_pmap --------\n+\n+def soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n+ ) -> Callable:\n+ warn(\"soft_pmap is an experimental feature and probably has bugs!\")\n+ _check_callable(fun)\n+ axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n+\n+ if any(axis != 0 for axis in tree_leaves(in_axes)):\n+ raise ValueError(f\"soft_pmap in_axes leaves must be 0 or None, got {in_axes}\")\n+ proxy = object()\n+ in_axes = _replace_nones(proxy, in_axes)\n+ in_axes = tree_map(lambda i: {i: axis_name} if i is not proxy else {}, in_axes)\n+\n+\n+ @wraps(fun)\n+ def f_pmapped(*args, **kwargs):\n+ mesh_devices = np.array(xb.local_devices())\n+ with mesh(mesh_devices, ['devices']):\n+ return xmap(fun, in_axes=in_axes, out_axes={0: axis_name},\n+ axis_resources={axis_name: 'devices'})(*args, **kwargs)\n+ return f_pmapped\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "# limitations under the License.\nimport numpy as np\n-from typing import Any, Callable, Dict, Optional, Tuple, Union\n+from typing import Any, Callable, Dict, Optional, Tuple, Union, Sequence\nimport jax\nfrom ..config import config\n@@ -28,16 +28,24 @@ from . import partial_eval as pe\nmap = safe_map\n-def batch(fun: lu.WrappedFun, axis_name, axis_size, in_dims, out_dim_dests,\n+BatchDim = Optional[int]\n+BatchDims = Sequence[BatchDim]\n+AxesSpec = Union[Callable[[], BatchDims], BatchDims]\n+\n+def batch(fun: lu.WrappedFun, axis_name: core.AxisName,\n+ axis_size: Optional[int], in_dims: AxesSpec, out_dim_dests: AxesSpec,\n) -> lu.WrappedFun:\n# anlogue of `jvp` in ad.py\n+ # TODO(mattjj,apaszke): change type of axis_size to be int, not Optional[int]\nfun, out_dims_thunk = batch_subtrace(fun)\nreturn _match_axes(batchfun(fun, axis_name, axis_size, in_dims),\n- axis_size, out_dims_thunk, out_dim_dests)\n+ axis_size, in_dims, out_dims_thunk, out_dim_dests)\n@lu.transformation\ndef batchfun(axis_name, axis_size, in_dims, *in_vals):\n# analogue of `jvpfun` in ad.py\n+ if axis_size is None:\n+ axis_size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\nin_dims = in_dims() if callable(in_dims) else in_dims\nin_dims = [canonicalize_axis(ax, np.ndim(x)) if isinstance(ax, int)\nand not isinstance(core.get_aval(x), core.AbstractUnit) # non-omnistaging\n@@ -60,7 +68,9 @@ def batch_subtrace(main, in_dims, *in_vals):\nyield out_vals, out_dims\n@lu.transformation\n-def _match_axes(axis_size, out_dims_thunk, out_dim_dests, *in_vals):\n+def _match_axes(axis_size, in_dims, out_dims_thunk, out_dim_dests, *in_vals):\n+ if axis_size is None:\n+ axis_size, = {x.shape[d] for x, d in zip(in_vals, in_dims) if d is not not_mapped}\nout_vals = yield in_vals, {}\nout_dim_dests = out_dim_dests() if callable(out_dim_dests) else out_dim_dests\nout_dims = out_dims_thunk()\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -45,14 +45,13 @@ from .. import core\nfrom .. import linear_util as lu\nfrom .. import lazy\nfrom ..abstract_arrays import array_types\n-from ..core import ConcreteArray, ShapedArray, Var, Literal\n+from ..core import ConcreteArray, ShapedArray\nfrom .._src.util import (partial, unzip2, unzip3, prod, safe_map, safe_zip,\nextend_name_stack, wrap_name, assert_unreachable,\ntuple_insert, tuple_delete, taggedtuple, curry)\nfrom ..lib import xla_bridge as xb\nfrom ..lib import xla_client as xc\nfrom ..tree_util import tree_flatten, tree_map\n-from .batching import broadcast, not_mapped, moveaxis\nfrom . import batching\nfrom . import partial_eval as pe\nfrom . import xla\n@@ -1563,7 +1562,6 @@ def vtile(f_flat,\n_forbidden_primitives = {\n'xla_pmap': 'pmap',\n- 'soft_pmap': 'soft_pmap',\n'sharded_call': 'sharded_jit',\n}\ndef _sanitize_mesh_jaxpr(jaxpr):\n@@ -1597,166 +1595,6 @@ def mesh_sharding_specs(axis_sizes, axis_names):\nreturn ShardingSpec(sharding, mesh_mapping)\nreturn mk_sharding_spec\n-\n-# ------------------- soft_pmap -------------------\n-\n-def soft_pmap_impl(fun: lu.WrappedFun, *args, axis_name, axis_size, in_axes, out_axes_thunk):\n- abstract_args = unsafe_map(xla.abstractify, args)\n- compiled_fun = _soft_pmap_callable(fun, axis_name, axis_size, in_axes, out_axes_thunk,\n- *abstract_args)\n- return compiled_fun(*args)\n-\n-@lu.cache\n-def _soft_pmap_callable(fun, axis_name, axis_size, in_axes, out_axes_thunk, *avals):\n- mapped_avals = [core.mapped_aval(axis_size, in_axis, aval) if in_axis is not None else aval\n- for in_axis, aval in safe_zip(in_axes, avals)]\n- with core.extend_axis_env(axis_name, axis_size, None): # type: ignore\n- jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, mapped_avals)\n- out_axes = out_axes_thunk()\n- assert all(out_axis == 0 for out_axis in out_axes)\n- jaxpr = xla.apply_outfeed_rewriter(jaxpr)\n-\n- num_devices = xb.local_device_count()\n- chunk_size, ragged = divmod(axis_size, num_devices)\n- if ragged:\n- msg = f\"number of devices {num_devices} must divide axis size {axis_size}\"\n- raise NotImplementedError(msg)\n-\n- jaxpr, _, consts = _soft_pmap_jaxpr(jaxpr, consts, in_axes,\n- axis_name, axis_size, chunk_size)\n- jaxpr_replicas = xla.jaxpr_replicas(jaxpr)\n- if jaxpr_replicas != 1: raise NotImplementedError\n-\n- tuple_args = len(avals) > 100 # pass long arg lists as tuple for TPU\n-\n- c = xb.make_computation_builder(\"soft_pmap_{}\".format(fun.__name__))\n- xla_consts = map(partial(xb.constant, c), consts)\n- chunked_avals = [core.unmapped_aval(chunk_size, in_axis, aval) if in_axis is not None else aval\n- for in_axis, aval in safe_zip(in_axes, mapped_avals)]\n- xla_args, _ = xla._xla_callable_args(c, chunked_avals, tuple_args)\n- axis_env = xla.AxisEnv(num_devices, (axis_name,), (num_devices,))\n- out_nodes = xla.jaxpr_subcomp(c, jaxpr, None, axis_env, xla_consts,\n- 'soft_pmap', *xla_args)\n- built = c.Build(xops.Tuple(c, out_nodes))\n-\n- compile_options = xb.get_compile_options(\n- num_replicas=num_devices, num_partitions=1, device_assignment=None)\n- compile_options.tuple_arguments = tuple_args\n- backend = xb.get_backend(None)\n- compiled = xla.backend_compile(backend, built, compile_options)\n-\n- input_specs = [\n- ShardingSpec(\n- sharding=tuple_insert((_UNSHARDED_INSTANCE,) *\n- (aval.ndim - 1), in_axis, Chunked(num_devices)),\n- mesh_mapping=[ShardedAxis(0)])\n- if in_axis is not None else ShardingSpec(\n- sharding=[_UNSHARDED_INSTANCE] * aval.ndim,\n- mesh_mapping=[Replicated(num_devices)])\n- for aval, in_axis in safe_zip(avals, in_axes)\n- ]\n- input_indices = [spec and spec_to_indices(aval.shape, spec)\n- for aval, spec in safe_zip(avals, input_specs)]\n- handle_args = partial(shard_args, compiled.local_devices(), input_indices)\n- handle_outs = soft_pmap_avals_to_results_handler(num_devices, chunk_size, out_avals)\n-\n- return partial(execute_replicated, compiled, backend, handle_args, handle_outs)\n-\n-def _soft_pmap_jaxpr(jaxpr, consts, in_axes, axis_name, axis_size, chunk_size):\n- assert all(in_axis is None or in_axis == 0 for in_axis in in_axes), in_axes\n- mapped_invars = [in_axis is not None for in_axis in in_axes]\n- fun = partial(_soft_pmap_interp, chunk_size, jaxpr, consts, mapped_invars)\n- in_avals = [core.unmapped_aval(chunk_size, in_axis, v.aval) if in_axis is not None else v.aval\n- for v, in_axis in safe_zip(jaxpr.invars, in_axes)]\n- with core.extend_axis_env(axis_name, axis_size, None):\n- return pe.trace_to_jaxpr_dynamic(lu.wrap_init(fun), in_avals)\n-\n-def _soft_pmap_interp(chunk_size, jaxpr, consts, mapped_invars, *args):\n-\n- env: Dict[Var, Tuple[Any, bool]] = {}\n-\n- def read(atom: Union[Var, Literal]) -> Tuple[Any, bool]:\n- if isinstance(atom, Literal):\n- return (atom.val, False)\n- else:\n- return env[atom]\n-\n- def write(v: Var, val: Any, mapped: bool) -> None:\n- env[v] = (val, mapped)\n-\n- write(core.unitvar, core.unit, False)\n- map(write, jaxpr.constvars, consts, (False,) * len(consts))\n- map(write, jaxpr.invars, args, mapped_invars)\n- for eqn in jaxpr.eqns:\n- in_vals, in_mapped = unzip2(map(read, eqn.invars))\n- if eqn.primitive in xla.parallel_translations:\n- rule = soft_pmap_rules[eqn.primitive]\n- out_vals, out_mapped = rule(in_vals, in_mapped, chunk_size, **eqn.params)\n- if not eqn.primitive.multiple_results:\n- out_vals, out_mapped = [out_vals], [out_mapped]\n- elif isinstance(eqn.primitive, core.CallPrimitive):\n- # we just inline here for convenience\n- call_jaxpr, params = core.extract_call_jaxpr(eqn.primitive, eqn.params)\n- out_vals = _soft_pmap_interp(chunk_size, call_jaxpr, (), in_mapped, *in_vals)\n- out_mapped = [True] * len(out_vals)\n- elif isinstance(eqn.primitive, core.MapPrimitive):\n- raise NotImplementedError # TODO\n- else:\n- if any(in_mapped):\n- rule = batching.get_primitive_batcher(eqn.primitive, None)\n- in_axes = [0 if m else batching.not_mapped for m in in_mapped]\n- out_vals, out_axes = rule(in_vals, in_axes, **eqn.params)\n- if not eqn.primitive.multiple_results:\n- out_vals, out_axes = [out_vals], [out_axes]\n- out_vals = [moveaxis(x, d, 0) if d is not not_mapped and d != 0 else x\n- for x, d in safe_zip(out_vals, out_axes)]\n- out_mapped = [d is not not_mapped for d in out_axes]\n- else:\n- out_vals = eqn.primitive.bind(*in_vals, **eqn.params)\n- if not eqn.primitive.multiple_results:\n- out_vals = [out_vals]\n- out_mapped = [False for _ in out_vals]\n- map(write, eqn.outvars, out_vals, out_mapped)\n-\n- out_vals, out_mapped = unzip2(map(read, jaxpr.outvars))\n- out_vals = [out if mapped else broadcast(out, chunk_size, 0)\n- for out, mapped in safe_zip(out_vals, out_mapped)]\n- return out_vals\n-\n-# TODO(mattjj): dedup w/ with other aval_to_result_handler via ShardingSpec\n-def soft_pmap_avals_to_results_handler(num_devices, chunk_size, out_avals):\n- nouts = len(out_avals)\n- handlers = [soft_pmap_aval_to_result_handler(chunk_size, num_devices, aval)\n- for aval in out_avals]\n- def handler(out_bufs):\n- buffers = [[result_to_populate] * num_devices for _ in range(nouts)]\n- for r, tuple_buf in enumerate(out_bufs):\n- for i, buf in enumerate(tuple_buf):\n- buffers[i][r] = buf\n- assert not any(buf is result_to_populate for bufs in buffers\n- for buf in bufs)\n- return [h(bufs) for h, bufs in safe_zip(handlers, buffers)]\n- return handler\n-\n-def soft_pmap_aval_to_result_handler(chunk_size, num_devices, aval):\n- axis_size = chunk_size * num_devices\n- if aval is core.abstract_unit:\n- return lambda _: core.unit\n- elif isinstance(aval, core.ShapedArray):\n- new_aval = aval.update(shape=(axis_size,) + aval.shape)\n- spec = ShardingSpec(\n- sharding=(Chunked(num_devices),) + (_UNSHARDED_INSTANCE,) * aval.ndim,\n- mesh_mapping=(ShardedAxis(0),))\n- return lambda bufs: ShardedDeviceArray(new_aval, spec, bufs)\n- else:\n- raise TypeError(aval)\n-\n-soft_pmap_p = core.MapPrimitive('soft_pmap')\n-soft_pmap = soft_pmap_p.bind\n-soft_pmap_p.def_impl(soft_pmap_impl)\n-\n-soft_pmap_rules: Dict[core.Primitive, Callable] = {}\n-\n@contextmanager\ndef maybe_extend_axis_env(*args, **kwargs):\nwith core.extend_axis_env(*args, **kwargs):\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -35,7 +35,7 @@ from jax import tree_util\nfrom jax import lax\nfrom jax import random\nfrom jax.core import ShapedArray\n-from jax.api import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\n+from jax import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\nlinearize, device_put)\nfrom jax.lib import xla_bridge\nfrom jax._src.util import prod, safe_map\n@@ -100,9 +100,6 @@ def tearDownModule():\nos.environ[\"XLA_FLAGS\"] = prev_xla_flags\nxla_bridge.get_backend.cache_clear()\n-ignore_soft_pmap_warning = partial(\n- jtu.ignore_warning, message=\"soft_pmap is an experimental.*\")\n-\nignore_jit_of_pmap_warning = partial(\njtu.ignore_warning, message=\".*jit-of-pmap.*\")\n@@ -1239,7 +1236,7 @@ class PmapTest(jtu.JaxTestCase):\nself.assertAllClose(r, arr + 1)\nself.assertEqual(len(r.device_buffers), 6)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapBatchMatmul(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1249,7 +1246,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.einsum('nij,njk->nik', xs, ys)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapBatchMatmulJit(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1259,7 +1256,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.einsum('nij,njk->nik', xs, ys)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapPsumConstant(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1269,7 +1266,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = n * np.ones(n)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapPsum(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1279,7 +1276,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.ones(n) / n\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapAxisIndex(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1289,7 +1286,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = 2 * np.arange(n)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapOfJit(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\nn = 4 * xla_bridge.device_count()\n@@ -1299,7 +1296,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = 3 * np.arange(n)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapNested(self):\nraise SkipTest(\"not implemented\") # TODO(mattjj): re-implement\nn = 4 * xla_bridge.device_count()\n@@ -1314,7 +1311,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.arange(n ** 2).reshape(n, n).T\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testGradOfSoftPmap(self):\nraise SkipTest(\"not implemented\") # TODO(mattjj): re-implement\nn = 4 * xla_bridge.device_count()\n@@ -1327,7 +1324,7 @@ class PmapTest(jtu.JaxTestCase):\nexpected = np.repeat(np.arange(n)[:, None], n, axis=1)\nself.assertAllClose(ans, expected, check_dtypes=False)\n- @ignore_soft_pmap_warning()\n+ @ignore_xmap_warning()\ndef testSoftPmapDevicePersistence(self):\nif not config.omnistaging_enabled: raise SkipTest(\"requires omnistaging\")\ndevice_count = xla_bridge.device_count()\n" } ]
Python
Apache License 2.0
google/jax
implement soft_pmap in terms of xmap
260,411
29.01.2021 10:52:29
-3,600
3fa950fe9e180fcd5753a2f4c285cdd070f8a345
Update jax2tf.py Small fix for merge error.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -195,7 +195,7 @@ def convert(fun: Callable, *,\n+ f\"Trace state: {core.thread_local_state.trace_state}\")\ndef check_arg(a):\n- if not _is_tfvalorunit(a):\n+ if not _is_tfval(a):\nmsg = (f\"Argument {a} of type {type(a)} of jax2tf.convert(f) should \"\n\"be NumPy array, scalar, tf.Variable, or tf.Tensor\")\nraise TypeError(msg)\n" } ]
Python
Apache License 2.0
google/jax
Update jax2tf.py Small fix for merge error.
260,322
05.01.2021 11:21:21
0
28dd00b010d0dc7a2aded1fd1ec8fcc8685cb2af
Adds support for is_leaf in tree_util.tree_map and tree_util.tree_multimap.
[ { "change_type": "MODIFY", "old_path": "jax/tree_util.py", "new_path": "jax/tree_util.py", "diff": "@@ -167,22 +167,28 @@ def register_pytree_node_class(cls):\nregister_pytree_node(cls, op.methodcaller('tree_flatten'), cls.tree_unflatten)\nreturn cls\n-def tree_map(f: Callable[[Any], Any], tree: Any) -> Any:\n+def tree_map(f: Callable[[Any], Any], tree: Any,\n+ is_leaf: Optional[Callable[[Any], bool]] = None) -> Any:\n\"\"\"Maps a function over a pytree to produce a new pytree.\nArgs:\nf: unary function to be applied at each leaf.\ntree: a pytree to be mapped over.\n+ is_leaf: an optionally specified function that will be called at each\n+ flattening step. It should return a boolean, which indicates whether\n+ the flattening should traverse the current object, or if it should be\n+ stopped immediately, with the whole subtree being treated as a leaf.\nReturns:\nA new pytree with the same structure as `tree` but with the value at each\nleaf given by ``f(x)`` where ``x`` is the value at the corresponding leaf in\nthe input ``tree``.\n\"\"\"\n- leaves, treedef = pytree.flatten(tree)\n+ leaves, treedef = tree_flatten(tree, is_leaf)\nreturn treedef.unflatten(map(f, leaves))\n-def tree_multimap(f: Callable[..., Any], tree: Any, *rest: Any) -> Any:\n+def tree_multimap(f: Callable[..., Any], tree: Any, *rest: Any,\n+ is_leaf: Optional[Callable[[Any], bool]] = None) -> Any:\n\"\"\"Maps a multi-input function over pytree args to produce a new pytree.\nArgs:\n@@ -192,6 +198,10 @@ def tree_multimap(f: Callable[..., Any], tree: Any, *rest: Any) -> Any:\npositional argument to ``f``.\n*rest: a tuple of pytrees, each of which has the same structure as tree or\nor has tree as a prefix.\n+ is_leaf: an optionally specified function that will be called at each\n+ flattening step. It should return a boolean, which indicates whether\n+ the flattening should traverse the current object, or if it should be\n+ stopped immediately, with the whole subtree being treated as a leaf.\nReturns:\nA new pytree with the same structure as ``tree`` but with the value at each\n@@ -199,7 +209,7 @@ def tree_multimap(f: Callable[..., Any], tree: Any, *rest: Any) -> Any:\nleaf in ``tree`` and ``xs`` is the tuple of values at corresponding nodes in\n``rest``.\n\"\"\"\n- leaves, treedef = pytree.flatten(tree)\n+ leaves, treedef = tree_flatten(tree, is_leaf)\nall_leaves = [leaves] + [treedef.flatten_up_to(r) for r in rest]\nreturn treedef.unflatten(f(*xs) for xs in zip(*all_leaves))\n" }, { "change_type": "MODIFY", "old_path": "tests/tree_util_tests.py", "new_path": "tests/tree_util_tests.py", "diff": "@@ -194,6 +194,14 @@ class TreeTest(jtu.JaxTestCase):\nself.assertEqual(out, (((1, [3]), (2, None)),\n((3, {\"foo\": \"bar\"}), (4, 7), (5, [5, 6]))))\n+ def testTreeMultimapWithIsLeafArgument(self):\n+ x = ((1, 2), [3, 4, 5])\n+ y = (([3], None), ({\"foo\": \"bar\"}, 7, [5, 6]))\n+ out = tree_util.tree_multimap(lambda *xs: tuple(xs), x, y,\n+ is_leaf=lambda n: isinstance(n, list))\n+ self.assertEqual(out, (((1, [3]), (2, None)),\n+ (([3, 4, 5], ({\"foo\": \"bar\"}, 7, [5, 6])))))\n+\n@skipIf(jax.lib.version < (0, 1, 58), \"test requires Jaxlib >= 0.1.58\")\ndef testFlattenIsLeaf(self):\nx = [(1, 2), (3, 4), (5, 6)]\n" } ]
Python
Apache License 2.0
google/jax
Adds support for is_leaf in tree_util.tree_map and tree_util.tree_multimap.
260,411
29.01.2021 12:48:56
-3,600
3c89de6eed72a678adad3c5d93dc0febd340bb08
[jax2tf] Add the JAX-not-implemented to the jax2tf limitations doc
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "new_path": "jax/experimental/jax2tf/g3doc/jax_primitives_coverage.md", "diff": "@@ -199,10 +199,8 @@ and search for \"limitation\".\n|reduce_window_max|unimplemented in XLA|complex64|tpu|\n|reduce_window_min|unimplemented in XLA|complex64|tpu|\n|reduce_window_mul|unimplemented in XLA|complex64|tpu|\n-|scatter_add|unimplemented|complex64|tpu|\n|scatter_max|unimplemented|complex64|tpu|\n|scatter_min|unimplemented|complex64|tpu|\n-|scatter_mul|unimplemented|complex64|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|svd|unimplemented|bfloat16, float16|cpu, gpu|\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": "@@ -67,27 +67,37 @@ 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| bitcast_convert_type | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, 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 error: op not defined for dtype | int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| conv_general_dilated | TF error: jax2tf BUG: batch_group_count > 1 not yet converted | all | cpu, gpu, tpu | compiled, eager, graph |\n| cosh | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n+| cummax | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n| cummax | TF error: op not defined for dtype | complex128 | cpu, gpu | compiled, eager, graph |\n-| cummax | TF error: op not defined for dtype | complex64 | cpu, gpu, tpu | compiled, eager, graph |\n+| cummax | TF error: op not defined for dtype | complex64 | cpu, gpu | compiled, eager, graph |\n+| cummin | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n| cummin | TF error: op not defined for dtype | complex128, uint64 | cpu, gpu | compiled, eager, graph |\n| cummin | TF error: op not defined for dtype | complex64, int8, uint16, uint32 | cpu, gpu, tpu | compiled, eager, graph |\n+| cumprod | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n| cumsum | TF error: op not defined for dtype | complex64 | 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| div | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| dot_general | TF error: op not defined for dtype | int64 | cpu, gpu | compiled |\n| dot_general | TF error: op not defined for dtype | bool, int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n+| eig | TF test skipped: Not implemented in JAX: only supported on CPU in JAX | all | gpu, tpu | compiled, eager, graph |\n+| eig | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu | compiled, eager, graph |\n| eig | TF error: TF Conversion of eig is not implemented when both compute_left_eigenvectors and compute_right_eigenvectors are set to True | all | cpu, gpu, tpu | compiled, eager, graph |\n| eig | TF error: function not compilable | all | cpu | compiled |\n+| eigh | TF test skipped: Not implemented in JAX: complex eigh not supported | complex | tpu | compiled, eager, graph |\n+| eigh | TF test skipped: Not implemented in JAX: unimplemented | float16 | cpu | compiled, eager, graph |\n+| eigh | TF test skipped: Not implemented in JAX: unimplemented | float16 | gpu | compiled, eager, graph |\n| eigh | TF error: function not compilable | complex | cpu, gpu, tpu | compiled |\n| erf | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| erf_inv | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu | eager, graph |\n| erfc | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n+| fft | TF test skipped: Not implemented in JAX: only 1D FFT is currently supported b/140351181. | all | tpu | compiled, eager, graph |\n| fft | TF error: TF function not compileable | complex128, float64 | cpu, gpu | compiled |\n| ge | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| gt | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n@@ -97,6 +107,7 @@ More detailed information can be found in the\n| le | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, eager, graph |\n| lgamma | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| lt | TF error: op not defined for dtype | bool | cpu, gpu, tpu | compiled, 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| max | TF error: op not defined for dtype | complex128 | cpu, gpu | compiled, eager, graph |\n| max | TF error: op not defined for dtype | int8, uint16, uint32, uint64 | cpu, gpu | eager, graph |\n@@ -106,15 +117,19 @@ More detailed information can be found in the\n| neg | TF error: op not defined for dtype | unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| nextafter | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| population_count | TF error: op not defined for dtype | uint32, uint64 | cpu, gpu | eager, graph |\n+| qr | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu | compiled, eager, graph |\n| qr | TF error: op not defined for dtype | bfloat16 | tpu | compiled, eager, graph |\n| reduce_max | TF error: op not defined for dtype | complex128 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_max | TF error: op not defined for dtype | complex64 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_min | TF error: op not defined for dtype | complex128 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_min | TF error: op not defined for dtype | complex64 | cpu, gpu, tpu | compiled, eager, graph |\n| reduce_window_add | TF error: op not defined for dtype | complex64 | tpu | compiled, eager, graph |\n+| reduce_window_max | TF test skipped: Not implemented in JAX: unimplemented in XLA | complex64 | tpu | compiled, eager, graph |\n| reduce_window_max | TF error: op not defined for dtype | complex128 | cpu, gpu | compiled, eager, graph |\n| reduce_window_max | TF error: op not defined for dtype | bool, complex64 | cpu, gpu, tpu | compiled, eager, graph |\n+| reduce_window_min | TF test skipped: Not implemented in JAX: unimplemented in XLA | complex64 | tpu | compiled, eager, graph |\n| reduce_window_min | TF error: op not defined for dtype | bool, complex, int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n+| reduce_window_mul | TF test skipped: Not implemented in JAX: unimplemented in XLA | complex64 | tpu | compiled, eager, graph |\n| regularized_incomplete_beta | TF error: op not defined for dtype | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| rem | TF error: TF integer division fails if divisor contains 0; JAX returns NaN | integer | cpu, gpu, tpu | compiled, eager, graph |\n| rem | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n@@ -124,18 +139,25 @@ More detailed information can be found in the\n| rsqrt | TF error: op not defined for dtype | bfloat16 | cpu, gpu | eager, graph |\n| scatter_add | TF error: op not defined for dtype | 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_max | TF error: op not defined for dtype | bool, complex | cpu, gpu, tpu | compiled, eager, graph |\n+| scatter_min | TF test skipped: Not implemented in JAX: unimplemented | complex64 | tpu | compiled, eager, graph |\n| scatter_min | TF error: op not defined for dtype | bool, complex, int8, uint16, uint32, uint64 | cpu, gpu, tpu | compiled, eager, graph |\n| scatter_mul | TF error: op not defined for dtype | 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: This JAX primitives is not not exposed directly in the JAX API but arises from JVP of `lax.reduce_window` for reducers `lax.max` or `lax.min`. It also arises from second-order VJP of the same. Implemented using XlaReduceWindow | float32 | 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| sign | TF error: op not defined for dtype | int16, int8, unsigned | cpu, gpu, tpu | compiled, eager, graph |\n| sinh | TF error: op not defined for dtype | float16 | cpu, gpu | eager, graph |\n| sort | TF error: op not defined for dtype | bool | cpu, gpu, 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+| tie_in | TF test skipped: Not implemented in JAX: requires omnistaging to be disabled | all | cpu, gpu, 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": "@@ -344,7 +344,7 @@ class Jax2TfLimitation(primitive_harness.Limitation):\ndtypes=[np.complex128],\ndevices=(\"cpu\", \"gpu\"),\n),\n- missing_tf_kernel(dtypes=[np.complex64]),\n+ missing_tf_kernel(dtypes=[np.complex64], devices=(\"cpu\", \"gpu\")),\ncustom_numeric(dtypes=np.float16, tol=0.1),\ncustom_numeric(dtypes=dtypes.bfloat16, tol=0.5)\n]\n@@ -1054,12 +1054,11 @@ class Jax2TfLimitation(primitive_harness.Limitation):\n@classmethod\ndef scatter_add(cls, harness):\nreturn [\n- missing_tf_kernel(dtypes=[np.bool_],),\n+ missing_tf_kernel(dtypes=[np.bool_]),\nmissing_tf_kernel(\ndtypes=[np.complex64],\ndevices=\"tpu\",\n- ),\n- ]\n+ )]\n@classmethod\ndef scatter_max(cls, harness):\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "new_path": "jax/experimental/jax2tf/tests/jax_primitives_coverage_test.py", "diff": "@@ -99,6 +99,7 @@ class JaxPrimitiveTest(jtu.JaxTestCase):\nfor h in harnesses:\nharness_groups[h.group_name].append(h)\nfor l in h.jax_unimplemented:\n+ if l.enabled:\nunique_limitations[hash(unique_hash(h, l))] = (h, l)\nprimitive_coverage_table = [\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitives_test.py", "new_path": "jax/experimental/jax2tf/tests/primitives_test.py", "diff": "@@ -145,7 +145,7 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\nharnesses = [\nh for h in primitive_harness.all_harnesses\n- if h.filter(h, include_jax_unimpl=False)\n+ if h.filter(h, include_jax_unimpl=True)\n]\nprint(f\"Found {len(harnesses)} test harnesses that work in JAX\")\n@@ -154,6 +154,16 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):\ntuple([np.dtype(d).name for d in l.dtypes]), l.modes)\nunique_limitations: Dict[Any, Tuple[primitive_harness.Harness, Jax2TfLimitation]] = {}\n+ for h in harnesses:\n+ for l in h.jax_unimplemented:\n+ if l.enabled:\n+ # Fake a Jax2TFLimitation from the Limitation\n+ tfl = Jax2TfLimitation(description=\"Not implemented in JAX: \" + l.description,\n+ devices = l.devices,\n+ dtypes = l.dtypes,\n+ expect_tf_error = False,\n+ skip_tf_run = True)\n+ unique_limitations[hash(unique_hash(h, tfl))] = (h, tfl)\nfor h in harnesses:\nfor l in Jax2TfLimitation.limitations_for_harness(h):\nunique_limitations[hash(unique_hash(h, l))] = (h, l)\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Add the JAX-not-implemented to the jax2tf limitations doc
260,411
29.01.2021 15:09:44
-3,600
87122fc81363756e7843ec06fa438852cf16df71
Update jax2tf.py mypy fix
[ { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -203,7 +203,7 @@ def convert(fun: Callable, *,\n# Name input tensors\nargs = tuple(\n- tree_util.tree_map(lambda x, i=i: tf.identity(x, f\"jax2tf_arg_{i}\"), a)\n+ tree_util.tree_map(lambda x, i=i: tf.identity(x, f\"jax2tf_arg_{i}\"), a) # type: ignore\nfor i, a in enumerate(args))\n# This function may take pytrees of TfVals. We can only set\n" } ]
Python
Apache License 2.0
google/jax
Update jax2tf.py mypy fix
260,352
31.01.2021 09:07:55
-39,600
4e48023538ac4939820fc346452211ce211eeec2
update out of date comment in Pmap_Cookbook.ipynb update comment regarding `pmap` not support `in_axes` because it does now.
[ { "change_type": "MODIFY", "old_path": "cloud_tpu_colabs/Pmap_Cookbook.ipynb", "new_path": "cloud_tpu_colabs/Pmap_Cookbook.ipynb", "diff": "\"source\": [\n\"Notice that applying `vmap(f)` to these arguments leads to a `dot_general` to express the batch matrix multiplication in a single primitive, while applying `pmap(f)` instead leads to a primitive that calls replicas of the original `f` in parallel.\\n\",\n\"\\n\",\n- \"There are also important constraints with using `pmap`:\\n\",\n- \"1. `pmap` always maps over the leading axis of all of its arguments (while with `vmap` you can use `in_axes` to specify which axes get mapped),\\n\",\n- \"2. with `pmap` the mapped axis size must be less than or equal to the number of XLA devices available (and for nested `pmap` functions, the product of the mapped axis sizes must be less than or equal to the number of XLA devices).\\n\",\n+ \"There is also an important constraint with using `pmap`, \",\n+ \"with `pmap` the mapped axis size must be less than or equal to the number of XLA devices available (and for nested `pmap` functions, the product of the mapped axis sizes must be less than or equal to the number of XLA devices).\\n\",\n\"\\n\",\n\"You can use the output of a `pmap` function just like any other value:\"\n]\n" } ]
Python
Apache License 2.0
google/jax
update out of date comment in Pmap_Cookbook.ipynb update comment regarding `pmap` not support `in_axes` because it does now.
260,411
31.01.2021 14:58:14
-7,200
a145e3d414e136015d2df23efc5f74e6ec61c90f
Pin numpy to max version 1.19, to avoid errors with 1.20 Will fix the numpy errors separately.
[ { "change_type": "MODIFY", "old_path": "build/test-requirements.txt", "new_path": "build/test-requirements.txt", "diff": "flake8\n+# For now, we pin the numpy version here, because jaxlib 0.1.59 was built with >=1.12\n+numpy>=1.12,<1.20\n# Must be kept in sync with the minimum jaxlib version in jax/lib/__init__.py\njaxlib==0.1.59\nmypy==0.790\n" }, { "change_type": "MODIFY", "old_path": "jaxlib/setup.py", "new_path": "jaxlib/setup.py", "diff": "@@ -36,7 +36,7 @@ setup(\nauthor_email='jax-dev@google.com',\npackages=['jaxlib'],\npython_requires='>=3.6',\n- install_requires=['scipy', 'numpy>=1.12', 'absl-py', 'flatbuffers'],\n+ install_requires=['scipy', 'numpy>=1.12,<1.20', 'absl-py', 'flatbuffers'],\nurl='https://github.com/google/jax',\nlicense='Apache-2.0',\npackage_data={'jaxlib': binary_libs},\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "@@ -29,7 +29,7 @@ setup(\npackage_data={'jax': ['py.typed']},\npython_requires='>=3.6',\ninstall_requires=[\n- 'numpy >=1.12',\n+ 'numpy >=1.12,<1.20',\n'absl-py',\n'opt_einsum',\n],\n" } ]
Python
Apache License 2.0
google/jax
Pin numpy to max version 1.19, to avoid errors with 1.20 Will fix the numpy errors separately.
260,411
31.01.2021 16:23:39
-7,200
580a8f54cf30d858bf20173313ec3f47a5beac56
Update Pmap_Cookbook.ipynb I am doing this mostly to trigger another run of CI; there was a problem with our CI runs and this PR appears to be failing tests.
[ { "change_type": "MODIFY", "old_path": "cloud_tpu_colabs/Pmap_Cookbook.ipynb", "new_path": "cloud_tpu_colabs/Pmap_Cookbook.ipynb", "diff": "\"source\": [\n\"Notice that applying `vmap(f)` to these arguments leads to a `dot_general` to express the batch matrix multiplication in a single primitive, while applying `pmap(f)` instead leads to a primitive that calls replicas of the original `f` in parallel.\\n\",\n\"\\n\",\n- \"There is also an important constraint with using `pmap`, \",\n- \"with `pmap` the mapped axis size must be less than or equal to the number of XLA devices available (and for nested `pmap` functions, the product of the mapped axis sizes must be less than or equal to the number of XLA devices).\\n\",\n+ \"An important constraint with using `pmap` is that \",\n+ \"the mapped axis size must be less than or equal to the number of XLA devices available (and for nested `pmap` functions, the product of the mapped axis sizes must be less than or equal to the number of XLA devices).\\n\",\n\"\\n\",\n\"You can use the output of a `pmap` function just like any other value:\"\n]\n" } ]
Python
Apache License 2.0
google/jax
Update Pmap_Cookbook.ipynb I am doing this mostly to trigger another run of CI; there was a problem with our CI runs and this PR appears to be failing tests.
260,411
31.01.2021 17:10:14
-7,200
cefab2ca5d8c384b13cefac2ff1ffd83dcd54dae
Disable the "with numpy-dispatch" test action. As numpy 1.20 was released recently, and triggers some errors in the GitHub CI, we pin numpy to 1.19. It seems that we still get failures when trying to import numpy-dispatch. We disable it until we figure out the problem.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/ci-build.yaml", "new_path": ".github/workflows/ci-build.yaml", "diff": "@@ -58,14 +58,6 @@ jobs:\nenable-omnistaging: 1\npackage-overrides: \"none\"\nnum_generated_cases: 25\n- - name-prefix: \"with numpy-dispatch\"\n- python-version: 3.9\n- os: ubuntu-latest\n- enable-x64: 1\n- enable-omnistaging: 1\n- # Test experimental NumPy dispatch\n- package-overrides: \"git+https://github.com/seberg/numpy-dispatch.git\"\n- num_generated_cases: 10\n- name-prefix: \"with internal numpy\"\npython-version: 3.6\nos: ubuntu-latest\n" } ]
Python
Apache License 2.0
google/jax
Disable the "with numpy-dispatch" test action. As numpy 1.20 was released recently, and triggers some errors in the GitHub CI, we pin numpy to 1.19. It seems that we still get failures when trying to import numpy-dispatch. We disable it until we figure out the problem.
260,411
29.01.2021 19:55:02
-3,600
617d77e0374123b6dee111a03f6d7649d845ac5c
Improve error message for when backward function in custom_vjp does not return a tuple. Prior to this we got an assertion that `py_cts_in is not iterable`.
[ { "change_type": "MODIFY", "old_path": "jax/custom_derivatives.py", "new_path": "jax/custom_derivatives.py", "diff": "@@ -545,12 +545,14 @@ def _flatten_bwd(in_tree, in_avals, out_trees, *args):\n# corresponding subtree of in_tree and with leaves of a non-pytree sentinel\n# object, to be replaced with Nones in the final returned result.\nzero = object() # non-pytree sentinel to replace Nones in py_cts_in\n- py_cts_in_ = tuple(zero if ct is None else ct for ct in py_cts_in)\ndummy = tree_unflatten(in_tree, [object()] * in_tree.num_leaves)\ncts_in_flat = []\nappend_cts = lambda x, d: cts_in_flat.extend([x] * len(tree_flatten(d)[0]))\ntry:\n- tree_multimap(append_cts, py_cts_in_, dummy)\n+ if not isinstance(py_cts_in, tuple):\n+ raise ValueError\n+ tree_multimap(append_cts,\n+ tuple(zero if ct is None else ct for ct in py_cts_in), dummy)\nexcept ValueError:\n_, in_tree2 = tree_flatten(py_cts_in)\nmsg = (\"Custom VJP rule must produce an output with the same container \"\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -4130,6 +4130,21 @@ class CustomVJPTest(jtu.JaxTestCase):\n),\nlambda: api.grad(f)(2.))\n+ def test_vjp_bwd_returns_non_tuple_error(self):\n+ @api.custom_vjp\n+ def f(x):\n+ return x\n+\n+ def foo_fwd(x):\n+ return x, None\n+\n+ def foo_bwd(_, g):\n+ return 2. * g # Should be a tuple\n+\n+ f.defvjp(foo_fwd, foo_bwd)\n+ with self.assertRaisesRegex(TypeError, \"Custom VJP rule .* must produce a tuple\"):\n+ api.grad(f)(3.)\n+\ndef test_issue2511(self):\narr = jnp.ones((5, 2, 2))\nfoo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)\n" } ]
Python
Apache License 2.0
google/jax
Improve error message for when backward function in custom_vjp does not return a tuple. Prior to this we got an assertion that `py_cts_in is not iterable`.
260,411
31.01.2021 16:58:20
-7,200
f2530010a5a0055ecf021c88f2df1a924c207da4
[jax2tf] Added tests for sharded_jit. These tests are only looking at the HLO sharding annotations.
[ { "change_type": "ADD", "old_path": null, "new_path": "jax/experimental/jax2tf/tests/sharding_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+\"\"\"Tests for the jax2tf conversion of sharded_jit.\"\"\"\n+\n+from absl.testing import absltest\n+from typing import Sequence\n+\n+import re\n+\n+import jax\n+from jax.experimental import jax2tf\n+import jax.numpy as jnp\n+from jax import test_util as jtu\n+import numpy as np\n+from jax.interpreters import sharded_jit\n+from jax.interpreters.sharded_jit import PartitionSpec as P\n+\n+from jax.experimental.jax2tf.tests import tf_test_util\n+\n+import tensorflow as tf # type: ignore[import]\n+\n+from jax.config import config\n+config.parse_flags_with_absl()\n+\n+\n+class ShardedJitHloTest(tf_test_util.JaxToTfTestCase):\n+ \"\"\"Tests that inspect the HLO for the sharding annotations.\n+\n+ These tests can run on any device.\n+ \"\"\"\n+ def _check_sharding_annotations(self, f_jax, args, expected: Sequence[str]):\n+ \"\"\"Check expected patterns in the HLO generated from f_jax and its conversion.\"\"\"\n+ jax_hlo = jax.xla_computation(f_jax)(*args).as_hlo_text()\n+ self.AssertShardingAnnotations(\"JAX\", jax_hlo, expected)\n+\n+ f_tf = jax2tf.convert(f_jax)\n+ tf_hlo = tf.function(f_tf, jit_compile=True).\\\n+ experimental_get_compiler_ir(*args)(stage=\"optimized_hlo\")\n+ self.AssertShardingAnnotations(\"TF\", tf_hlo, expected)\n+\n+\n+ def AssertShardingAnnotations(self, what: str, hlo: str,\n+ expected: Sequence[str]):\n+ \"\"\"\n+ Args:\n+ what: either 'JAX' or 'TF'\n+ hlo: the text for the HLO module\n+ expected: a sequence of regexps that must occur in the hlo text. Each\n+ regexp must match a line, in order.\n+ \"\"\"\n+ next_expected_idx = 0\n+ failure_msg = [f\"Cannot find some expected sharding annotations in HLO from {what}:\"]\n+ for hlo_line in hlo.split(\"\\n\"):\n+ failure_msg.append(hlo_line)\n+ if re.search(expected[next_expected_idx], hlo_line):\n+ failure_msg.append(\n+ f\">>> Found[{next_expected_idx}] {expected[next_expected_idx]}\")\n+ next_expected_idx += 1\n+ if next_expected_idx >= len(expected):\n+ break\n+ else:\n+ failure_msg.append(\n+ f\"!!! Not found[{next_expected_idx}] {expected[next_expected_idx]}\")\n+ raise self.failureException(\"\\n\".join(failure_msg))\n+\n+\n+ def test_in_out(self):\n+ \"\"\"Test input and output sharding annotations.\"\"\"\n+ def jax_func(x, y):\n+ return jnp.dot(x, y)\n+\n+ sharded_jax_func = sharded_jit.sharded_jit(\n+ jax_func, in_parts=(P(1, 2), P(2, 1)), out_parts=P(1, 2))\n+ xshape = (3, 8)\n+ x = np.arange(np.prod(xshape), dtype=np.float32).reshape(xshape)\n+ yshape = (8, 5)\n+ y = np.arange(np.prod(yshape), dtype=np.float32).reshape(yshape)\n+ self._check_sharding_annotations(\n+ sharded_jax_func, [x, y],\n+ [r'f32\\[3,8\\].*sharding={devices=\\[1,2\\]',\n+ r'f32\\[8,5\\].*sharding={devices=\\[2,1\\]',\n+ r'f32\\[3,5\\].*dot.*sharding={devices=\\[1,2\\]'])\n+\n+\n+ def test_with_sharding_constraint(self):\n+ \"\"\"A sharding constraint in the middle.\"\"\"\n+ def jax_func(x, y):\n+ logits1 = jnp.dot(x, y)\n+ return jnp.sin(sharded_jit.with_sharding_constraint(logits1, P(3, 1)))\n+\n+ sharded_jax_func = sharded_jit.sharded_jit(\n+ jax_func, in_parts=(P(1, 2), P(2, 1)), out_parts=P(1, 2))\n+ xshape = (3, 8)\n+ x = np.arange(np.prod(xshape), dtype=np.float32).reshape(xshape)\n+ yshape = (8, 5)\n+ y = np.arange(np.prod(yshape), dtype=np.float32).reshape(yshape)\n+ self._check_sharding_annotations(\n+ sharded_jax_func, [x, y],\n+ [r'f32\\[3,8\\].*sharding={devices=\\[1,2\\]',\n+ r'f32\\[8,5\\].*sharding={devices=\\[2,1\\]',\n+ r'f32\\[3,5\\].*dot.*sharding={devices=\\[3,1\\]',\n+ r'f32\\[3,5\\].*sine.*sharding={devices=\\[1,2\\]'])\n+\n+ def test_replicated(self):\n+ \"\"\"A replicated input and output.\"\"\"\n+ def jax_func(x, y):\n+ return jnp.dot(x, y)\n+\n+ sharded_jax_func = sharded_jit.sharded_jit(\n+ jax_func, in_parts=(P(1, 2), None), out_parts=None)\n+ xshape = (3, 8)\n+ x = np.arange(np.prod(xshape), dtype=np.float32).reshape(xshape)\n+ yshape = (8, 5)\n+ y = np.arange(np.prod(yshape), dtype=np.float32).reshape(yshape)\n+ self._check_sharding_annotations(\n+ sharded_jax_func, [x, y],\n+ [r'f32\\[3,8\\].*sharding={devices=\\[1,2\\]',\n+ r'f32\\[8,5\\].*sharding={replicated}',\n+ r'f32\\[3,5\\].*dot.*sharding={replicated}'])\n+\n+\n+if __name__ == \"__main__\":\n+ absltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
[jax2tf] Added tests for sharded_jit. These tests are only looking at the HLO sharding annotations.
260,287
28.01.2021 18:19:36
0
a7f9b84bf1c858f950ac9c73ab23be88b6feda9c
Implement a trivial ppermute collective batcher Splitting a single-dimensional ppermute into multiple permutations is a hard problem in general, but not when we're splitting a size-1 dimension. More importantly, this is the case that's triggered by any `xmap` of a `ppermute`, so we better have an implementation ready!
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -652,9 +652,16 @@ def _ppermute_transpose_rule(t, x, perm, axis_name):\nreturn [ppermute(t, axis_name=axis_name, perm=inverse_perm)]\ndef _ppermute_batcher(frame, vals_in, dims_in, axis_name, perm):\n- assert len(perm) == frame.size, \"Permutation doesn't match the axis size!\"\n- assert axis_name == frame.name, \"ppermute batcher called with wrong axis name\"\n(v,), (d,) = vals_in, dims_in\n+ if not isinstance(axis_name, (tuple, list)):\n+ axis_name = (axis_name,)\n+ remaining_axes = tuple(axis for axis in axis_name if axis != frame.name)\n+ if frame.size == 1 and remaining_axes:\n+ return ppermute_p.bind(v, perm=perm, axis_name=remaining_axes), d\n+ if remaining_axes:\n+ raise NotImplementedError(\"ppermute batcher only supports a single axis\")\n+ assert axis_name[0] == frame.name, \"ppermute batcher called with a wrong axis!\"\n+ assert len(perm) == frame.size, \"Permutation doesn't match the axis size!\"\nassert d is not batching.not_mapped\nperm_indices = [None] * frame.size\nfor src, dst in perm:\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -112,15 +112,9 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(d, b * 4)\n@ignore_xmap_warning()\n- def testBasicCollective(self):\n- local_devices = list(jax.local_devices())\n- if len(local_devices) < 4:\n- raise SkipTest(\"Test requires at least 4 local devices\")\n- def f(a, b):\n- return lax.psum(a * 2, 'a'), b * 4\n- devices = np.array(local_devices[:4]).reshape((2, 2))\n- with mesh(devices, ('x', 'y')):\n- fm = xmap(f,\n+ @with_mesh([('x', 2), ('y', 2)])\n+ def testCollectiveReduce(self):\n+ fm = xmap(lambda a, b: (lax.psum(a * 2, 'a'), b * 4),\nin_axes=[['a', 'b', ...], {0: 'c'}],\nout_axes=[['b', ...], {0: 'c'}],\naxis_resources={'a': 'x', 'b': 'y', 'c': 'x'})\n@@ -132,6 +126,26 @@ class XMapTest(jtu.JaxTestCase):\nself.assertAllClose(c, (a * 2).sum(0))\nself.assertAllClose(d, b * 4)\n+ @ignore_xmap_warning()\n+ @with_mesh([('x', 2), ('y', 2)])\n+ def testCollectivePermute2D(self):\n+ perm = np.array([3, 1, 2, 0])\n+ x = jnp.arange(4).reshape((2, 2))\n+ result = xmap(lambda x: lax.pshuffle(x, ('i', 'j'), perm),\n+ in_axes=['i', 'j', ...],\n+ out_axes=['i', 'j', ...],\n+ axis_resources={'i': 'x', 'j': 'y'})(x).reshape((-1,))\n+ self.assertAllClose(result, perm)\n+\n+ @ignore_xmap_warning()\n+ def testCollectivePermute1D(self):\n+ perm = np.array([3, 1, 2, 0])\n+ x = jnp.arange(4)\n+ result = xmap(lambda x: lax.pshuffle(x, 'i', perm),\n+ in_axes=['i', ...],\n+ out_axes=['i', ...])(x)\n+ self.assertAllClose(result, perm)\n+\n@ignore_xmap_warning()\n@with_mesh([('x', 2), ('y', 2)])\ndef testOneLogicalTwoMeshAxesBasic(self):\n@@ -323,12 +337,17 @@ class XMapTest(jtu.JaxTestCase):\nclass XMapTestSPMD(XMapTest):\n\"\"\"Re-executes all tests with the SPMD partitioner enabled\"\"\"\n+ skipped_tests = {\n+ \"NestedMesh\", # Nesting xmap calls is not supported in the SPMD lowering yet\n+ \"CollectivePermute2D\" # vmap of multidimensional permute not implemented yet\n+ }\n+\ndef setUp(self):\nsuper().setUp()\nif jtu.device_under_test() != \"tpu\":\nraise SkipTest\n- # Nesting xmap calls is not supported in the SPMD lowering yet\n- if \"NestedMesh\" in self._testMethodName:\n+ for skipped_name in self.skipped_tests:\n+ if skipped_name in self._testMethodName:\nraise SkipTest\njax.experimental.maps.make_xmap_callable.cache_clear()\nself.old_lowering_flag = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n" } ]
Python
Apache License 2.0
google/jax
Implement a trivial ppermute collective batcher Splitting a single-dimensional ppermute into multiple permutations is a hard problem in general, but not when we're splitting a size-1 dimension. More importantly, this is the case that's triggered by any `xmap` of a `ppermute`, so we better have an implementation ready!
260,484
01.02.2021 14:00:44
-10,800
c71a4f5871bef19d2f9b6e4d56c0209217205691
Try to download bazel as the last resort Resolution order of paths to bazel binary is as follows. 1. Use --bazel_path command line option. 2. Search bazel binary in PATH environment variable. 3. Download required bazel release.
[ { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -144,44 +144,49 @@ def download_and_verify_bazel():\nreturn os.path.join(\".\", package.file)\n-def get_bazel_path(bazel_path_flag):\n- \"\"\"Returns the path to a Bazel binary, downloading Bazel if not found.\"\"\"\n- if bazel_path_flag:\n- return bazel_path_flag\n-\n- bazel = download_and_verify_bazel()\n- if bazel:\n- return bazel\n-\n- bazel = which(\"bazel\")\n- if bazel:\n- return bazel\n+def get_bazel_paths(bazel_path_flag):\n+ \"\"\"Yields a sequence of a guess about bazel path. Some of sequence elements\n+ can be None. The resulting iterator is lazy and potentially has a side\n+ effects.\"\"\"\n+ yield bazel_path_flag\n+ yield which(\"bazel\")\n+ yield download_and_verify_bazel()\n+\n+\n+def get_bazel_path(bazel_path_flag, min_version, max_version):\n+ \"\"\"Returns the path to a Bazel binary, downloading Bazel if not found. Also,\n+ it checks Bazel's version is in the range [`min_version`, `max_version`).\n+\n+ NOTE Manual version check is reasonably only for bazel < 2.0.0. Newer bazel\n+ releases performs version check against .bazelversion (see for details\n+ https://blog.bazel.build/2019/12/19/bazel-2.0.html#other-important-changes).\n+ \"\"\"\n+ for path in filter(None, get_bazel_paths(bazel_path_flag)):\n+ if check_bazel_version(path, min_version, max_version):\n+ return path\nprint(\"Cannot find or download bazel. Please install bazel.\")\nsys.exit(-1)\ndef check_bazel_version(bazel_path, min_version, max_version):\n- \"\"\"Checks Bazel's version is in the range [`min_version`, `max_version`).\"\"\"\n+ try:\nversion_output = shell([bazel_path, \"--bazelrc=/dev/null\", \"version\"])\n+ except subprocess.CalledProcessError:\n+ return False\nmatch = re.search(\"Build label: *([0-9\\\\.]+)[^0-9\\\\.]\", version_output)\nif match is None:\n- print(\"Warning: bazel installation is not a release version. Make sure \"\n- \"bazel is at least {}\".format(min_version))\n- return\n+ return False\nversion = match.group(1)\nmin_ints = [int(x) for x in min_version.split(\".\")]\nactual_ints = [int(x) for x in match.group(1).split(\".\")]\nif min_ints > actual_ints:\n- print(\"Outdated bazel revision (>= {} required, found {})\".format(\n- min_version, version))\n- sys.exit(-1)\n+ return False\nif max_version is not None:\nmax_ints = [int(x) for x in max_version.split(\".\")]\nif actual_ints >= max_ints:\n- print(\"Please downgrade your bazel revision to build JAX (>= {} and < {}\"\n- \" required, found {})\".format(min_version, max_version, version))\n- sys.exit(-1)\n+ return False\n+ return True\nBAZELRC_TEMPLATE = \"\"\"\n@@ -432,8 +437,7 @@ def main():\nos.chdir(os.path.dirname(__file__ or args.prog) or '.')\n# Find a working Bazel.\n- bazel_path = get_bazel_path(args.bazel_path)\n- check_bazel_version(bazel_path, min_version=\"2.0.0\", max_version=None)\n+ bazel_path = get_bazel_path(args.bazel_path, min_version=\"2.0.0\", max_version=None)\nprint(\"Bazel binary path: {}\".format(bazel_path))\npython_bin_path = get_python_bin_path(args.python_bin_path)\n" } ]
Python
Apache License 2.0
google/jax
Try to download bazel as the last resort Resolution order of paths to bazel binary is as follows. 1. Use --bazel_path command line option. 2. Search bazel binary in PATH environment variable. 3. Download required bazel release.
260,709
01.02.2021 16:23:21
28,800
2f6ed3cfeaf0e6ebefb763ec7e38c0ae1a132b99
Initialize variables in LAPACK work size queries to prevent false positives in memory sanitizers. Related prior art in SciPy:
[ { "change_type": "MODIFY", "old_path": "jaxlib/lapack.pyx", "new_path": "jaxlib/lapack.pyx", "diff": "@@ -434,9 +434,9 @@ def getrf(c, a):\n# ?geqrf: QR decomposition\ncdef int lapack_sgeqrf_workspace(int m, int n):\n- cdef float work\n+ cdef float work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\nsgeqrf(&m, &n, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work) if info == 0 else -1\n@@ -466,9 +466,9 @@ cdef void lapack_sgeqrf(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_sgeqrf\", <void*>(lapack_sgeqrf))\ncdef int lapack_dgeqrf_workspace(int m, int n):\n- cdef double work\n+ cdef double work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ndgeqrf(&m, &n, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work) if info == 0 else -1\n@@ -498,9 +498,9 @@ cdef void lapack_dgeqrf(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_dgeqrf\", <void*>(lapack_dgeqrf))\ncdef int lapack_cgeqrf_workspace(int m, int n):\n- cdef float complex work\n+ cdef float complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncgeqrf(&m, &n, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work.real) if info == 0 else -1\n@@ -530,9 +530,9 @@ cdef void lapack_cgeqrf(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_cgeqrf\", <void*>(lapack_cgeqrf))\ncdef int lapack_zgeqrf_workspace(int m, int n):\n- cdef double complex work\n+ cdef double complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\nzgeqrf(&m, &n, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work.real) if info == 0 else -1\n@@ -628,9 +628,9 @@ def geqrf(c, a):\n# ?orgqr: product of elementary Householder reflectors:\ncdef int lapack_sorgqr_workspace(int m, int n, int k):\n- cdef float work\n+ cdef float work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\nsorgqr(&m, &n, &k, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work) if info == 0 else -1\n@@ -661,9 +661,9 @@ cdef void lapack_sorgqr(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_sorgqr\", <void*>(lapack_sorgqr))\ncdef int lapack_dorgqr_workspace(int m, int n, int k):\n- cdef double work\n+ cdef double work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ndorgqr(&m, &n, &k, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work) if info == 0 else -1\n@@ -694,9 +694,9 @@ cdef void lapack_dorgqr(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_dorgqr\", <void*>(lapack_dorgqr))\ncdef int lapack_cungqr_workspace(int m, int n, int k):\n- cdef float complex work\n+ cdef float complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncungqr(&m, &n, &k, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work.real) if info == 0 else -1\n@@ -727,9 +727,9 @@ cdef void lapack_cungqr(void* out_tuple, void** data) nogil:\nregister_cpu_custom_call_target(b\"lapack_cungqr\", <void*>(lapack_cungqr))\ncdef int lapack_zungqr_workspace(int m, int n, int k):\n- cdef double complex work\n+ cdef double complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\nzungqr(&m, &n, &k, NULL, &m, NULL, &work, &lwork, &info)\nreturn <int>(work.real) if info == 0 else -1\n@@ -992,9 +992,9 @@ cdef char gesdd_jobz(bool_t job_opt_compute_uv,\ncdef int sgesdd_work_size(int m, int n, bool_t job_opt_compute_uv,\nbool_t job_opt_full_matrices):\n- cdef float work\n+ cdef float work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncdef int ldvt = min(m, n) if job_opt_full_matrices == 0 else n\ncdef char jobz = gesdd_jobz(job_opt_compute_uv, job_opt_full_matrices)\nsgesdd(&jobz, &m, &n, NULL, &m, NULL, NULL, &m, NULL, &ldvt, &work,\n@@ -1044,9 +1044,9 @@ register_cpu_custom_call_target(b\"lapack_sgesdd\", <void*>(lapack_sgesdd))\ncdef int dgesdd_work_size(int m, int n, bool_t job_opt_compute_uv,\nbool_t job_opt_full_matrices):\n- cdef double work\n+ cdef double work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncdef int ldvt = min(m, n) if job_opt_full_matrices == 0 else n\ncdef char jobz = gesdd_jobz(job_opt_compute_uv, job_opt_full_matrices)\ndgesdd(&jobz, &m, &n, NULL, &m, NULL, NULL, &m, NULL, &ldvt, &work,\n@@ -1095,9 +1095,9 @@ register_cpu_custom_call_target(b\"lapack_dgesdd\", <void*>(lapack_dgesdd))\ncdef int cgesdd_work_size(int m, int n, bool_t job_opt_compute_uv,\nbool_t job_opt_full_matrices):\n- cdef float complex work\n+ cdef float complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncdef int ldvt = min(m, n) if job_opt_full_matrices == 0 else n\ncdef char jobz = gesdd_jobz(job_opt_compute_uv, job_opt_full_matrices)\ncgesdd(&jobz, &m, &n, NULL, &m, NULL, NULL, &m, NULL, &ldvt, &work,\n@@ -1148,9 +1148,9 @@ register_cpu_custom_call_target(b\"lapack_cgesdd\", <void*>(lapack_cgesdd))\ncdef int zgesdd_work_size(int m, int n, bool_t job_opt_compute_uv,\nbool_t job_opt_full_matrices):\n- cdef double complex work\n+ cdef double complex work = 0\ncdef int lwork = -1\n- cdef int info\n+ cdef int info = 0\ncdef int ldvt = min(m, n) if job_opt_full_matrices == 0 else n\ncdef char jobz = gesdd_jobz(job_opt_compute_uv, job_opt_full_matrices)\nzgesdd(&jobz, &m, &n, NULL, &m, NULL, NULL, &m, NULL, &ldvt, &work,\n" } ]
Python
Apache License 2.0
google/jax
Initialize variables in LAPACK work size queries to prevent false positives in memory sanitizers. Related prior art in SciPy: https://github.com/scipy/scipy/pull/9054
260,411
02.02.2021 10:31:04
-7,200
ec2301a9ce58101e6374af32abd4c400a35b3914
Update limitations docs
[ { "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-01-29* (YYYY-MM-DD)\n+*Last generated on: 2021-02-02* (YYYY-MM-DD)\n## Supported data types for primitives\n@@ -191,8 +191,7 @@ and search for \"limitation\".\n|eig|only supported on CPU in JAX|all|tpu, gpu|\n|eig|unimplemented|bfloat16, float16|cpu|\n|eigh|complex eigh not supported |complex|tpu|\n-|eigh|unimplemented|float16|cpu|\n-|eigh|unimplemented|float16|gpu|\n+|eigh|unimplemented|bfloat16, float16|cpu, gpu, tpu|\n|fft|only 1D FFT is currently supported b/140351181.|all|tpu|\n|lu|unimplemented|bfloat16, float16|cpu, gpu, tpu|\n|qr|unimplemented|bfloat16, float16|cpu, gpu|\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-01-29*\n+*Last generated on (YYYY-MM-DD): 2021-02-02*\nThis document summarizes known limitations of the jax2tf conversion.\nThere are several kinds of limitations.\n@@ -91,8 +91,7 @@ More detailed information can be found in the\n| eig | TF error: TF Conversion of eig is not implemented when both compute_left_eigenvectors and compute_right_eigenvectors are set to True | all | cpu, gpu, tpu | compiled, eager, graph |\n| eig | TF error: function not compilable | all | cpu | compiled |\n| eigh | TF test skipped: Not implemented in JAX: complex eigh not supported | complex | tpu | compiled, eager, graph |\n-| eigh | TF test skipped: Not implemented in JAX: unimplemented | float16 | cpu | compiled, eager, graph |\n-| eigh | TF test skipped: Not implemented in JAX: unimplemented | float16 | gpu | compiled, eager, graph |\n+| eigh | TF test skipped: Not implemented in JAX: unimplemented | bfloat16, float16 | cpu, gpu, tpu | compiled, eager, graph |\n| eigh | TF error: function not compilable | complex | cpu, gpu, tpu | compiled |\n| 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" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "new_path": "jax/experimental/jax2tf/tests/primitive_harness.py", "diff": "@@ -1659,13 +1659,7 @@ for dtype in jtu.dtypes.all_inexact:\ndevices=\"tpu\",\ndtypes=[np.complex64, np.complex128]),\nLimitation(\n- \"unimplemented\", devices=\"cpu\",\n- dtypes=[np.float16, dtypes.bfloat16]),\n- Limitation(\n- \"unimplemented\", devices=\"gpu\",\n- dtypes=[np.float16, dtypes.bfloat16]),\n- Limitation(\n- \"unimplemented\", devices=\"tpu\",\n+ \"unimplemented\", devices=(\"cpu\", \"gpu\", \"tpu\"),\ndtypes=[np.float16, dtypes.bfloat16]),\n],\nshape=shape,\n" } ]
Python
Apache License 2.0
google/jax
Update limitations docs
260,287
01.02.2021 16:49:46
0
e11c4fffac4c1fe9fad301f6184539e8f7121735
Add support for axis names in jax.scipy.special.logsumexp
[ { "change_type": "MODIFY", "old_path": "jax/_src/scipy/special.py", "new_path": "jax/_src/scipy/special.py", "diff": "@@ -102,26 +102,26 @@ expit.defjvps(lambda g, ans, x: g * ans * (lax._const(ans, 1) - ans))\ndef logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):\nif b is not None:\na, b = jnp.broadcast_arrays(a, b)\n- _, dims = _reduction_dims(a, axis)\n- dimadd = lambda x: lax.expand_dims(x, dims)\n- amax = lax.reduce(a, _constant_like(a, -np.inf), lax.max, dims)\n+ pos_dims, dims = _reduction_dims(a, axis)\n+ amax = jnp.max(a, axis=dims, keepdims=keepdims)\namax = lax.stop_gradient(lax.select(lax.is_finite(amax), amax, lax.full_like(amax, 0)))\n- amax_singletons = dimadd(amax)\n+ amax_with_dims = amax if keepdims else lax.expand_dims(amax, pos_dims)\nif b is None:\n- out = lax.add(lax.log(lax.reduce(lax.exp(lax.sub(a, amax_singletons)),\n- _constant_like(a, 0), lax.add, dims)), amax)\n+ out = lax.add(lax.log(jnp.sum(lax.exp(lax.sub(a, amax_with_dims)),\n+ axis=dims, keepdims=keepdims)),\n+ amax)\nsign = jnp.where(jnp.isnan(out), np.nan, 1.0).astype(out.dtype)\nsign = jnp.where(out == -np.inf, 0.0, sign)\nelse:\n- sumexp = lax.reduce(lax.mul(lax.exp(lax.sub(a, amax_singletons)), b),\n- _constant_like(a, 0), lax.add, dims)\n+ sumexp = jnp.sum(lax.mul(lax.exp(lax.sub(a, amax_with_dims)), b),\n+ axis=dims, keepdims=keepdims)\nsign = lax.stop_gradient(lax.sign(sumexp))\nout = lax.add(lax.log(lax.abs(sumexp)), amax)\nif return_sign:\n- return (dimadd(out), dimadd(sign)) if keepdims else (out, sign)\n+ return (out, sign)\nif b is not None:\nout = jnp.where(sign < 0, np.nan, out)\n- return dimadd(out) if keepdims else out\n+ return out\n@_wraps(osp_special.xlogy)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -31,6 +31,7 @@ from functools import partial\nimport jax\nimport jax.numpy as jnp\n+import jax.scipy as jscipy\nfrom jax import test_util as jtu\nfrom jax import vmap\nfrom jax import lax\n@@ -365,12 +366,12 @@ class NamedNumPyTest(jtu.JaxTestCase):\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n- @parameterized.named_parameters(\n- {\"testcase_name\": f\"{reduction.__name__}_axes={axes}_i={mapped_axis}\",\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": f\"_{reduction.__name__}_axes={axes}_i={mapped_axis}\",\n\"reduction\": reduction, \"axes\": axes, \"mapped_axis\": mapped_axis}\n- for reduction in (jnp.sum, jnp.max, jnp.min)\n+ for reduction in (jnp.sum, jnp.max, jnp.min, jscipy.special.logsumexp)\nfor axes in (0, 'i', (1,), ('i',), (0, 1), (0, 'i'), ('i', 0))\n- for mapped_axis in range(2))\n+ for mapped_axis in range(3)))\n@ignore_xmap_warning()\ndef testReductions(self, reduction, axes, mapped_axis):\naxes_t = axes if isinstance(axes, tuple) else (axes,)\n" } ]
Python
Apache License 2.0
google/jax
Add support for axis names in jax.scipy.special.logsumexp
260,411
02.02.2021 15:47:13
-7,200
d25d37811551f0bb5bf9756f4fdcb7f946928791
Fixes for numpy 1.20 It seems that `np.ndim` and `np.shape` fail in version 1.20 when used on sequences of Tracers. We avoid invoking these functions in places where this may happen.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -662,7 +662,7 @@ def cond(*args, **kwargs):\nreturn _cond(*args, **kwargs)\ndef _cond(pred, true_fun: Callable, false_fun: Callable, operand):\n- if len(np.shape(pred)) != 0:\n+ if not isinstance(pred, Sequence) and len(np.shape(pred)) != 0:\nraise TypeError(\nf\"Pred must be a scalar, got {pred} of shape {np.shape(pred)}.\")\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -131,6 +131,20 @@ ndim = _ndim = np.ndim\nsize = np.size\n_dtype = dtypes.result_type\n+def _ndim_sequence(xs):\n+ \"\"\"A version of np.ndim that works on sequences that may include Tracers.\n+\n+ Prior to version 1.20, np.ndim worked on sequences.\"\"\"\n+ if isinstance(xs, Sequence):\n+ if not xs:\n+ return 1\n+ ndims = set(_ndim_sequence(x) for x in xs)\n+ if len(ndims) > 1:\n+ raise ValueError(f\"ndim called on a ragged sequence with ndims {ndims}\")\n+ return 1 + ndims.pop()\n+ else:\n+ return ndim(xs)\n+\n# At present JAX doesn't have a reason to distinguish between scalars and arrays\n# in its object system. Further, we want JAX scalars to have the same type\n# promotion behaviors as JAX arrays. Rather than introducing a new type of JAX\n@@ -2586,7 +2600,7 @@ the modified array. This is because Jax arrays are immutable.\n(In numpy, \"function\" mode's argument should modify a rank 1 array in-place.)\n\"\"\")\ndef pad(array, pad_width, mode=\"constant\", **kwargs):\n- pad_width = _broadcast_to_pairs(pad_width, ndim(array), \"pad_width\")\n+ pad_width = _broadcast_to_pairs(pad_width, _ndim_sequence(array), \"pad_width\")\nif pad_width and np.array(pad_width).dtype.kind != 'i':\nraise TypeError('`pad_width` must be of integral type.')\n@@ -4587,8 +4601,7 @@ def _expand_bool_indices(idx):\nexcept TypeError:\nabstract_i = None\nif (isinstance(abstract_i, ShapedArray) and issubdtype(abstract_i.dtype, bool_)\n- or isinstance(i, list) and _all(not _shape(e) and issubdtype(_dtype(e), bool_)\n- for e in i)):\n+ or isinstance(i, list) and _all(_is_bool_scalar_like(e) for e in i)):\nif isinstance(i, list):\ni = array(i)\nabstract_i = core.get_aval(i)\n@@ -4613,7 +4626,8 @@ def _is_advanced_int_indexer(idx):\n\"\"\"Returns True if idx should trigger int array indexing, False otherwise.\"\"\"\n# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\nassert isinstance(idx, tuple)\n- if _all(np.ndim(elt) == 0 for elt in idx):\n+ if _all(e is None or e is Ellipsis or isinstance(e, slice)\n+ or _is_int_scalar_like(e) for e in idx):\nreturn False\nreturn _all(e is None or e is Ellipsis or isinstance(e, slice)\nor _is_int_arraylike(e) for e in idx)\n@@ -4624,6 +4638,15 @@ def _is_int_arraylike(x):\nor issubdtype(getattr(x, \"dtype\", None), np.integer)\nor isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))\n+def _is_int_scalar_like(x):\n+ \"\"\"Returns True if x is a scalar integer, False otherwise.\"\"\"\n+ return (isinstance(x, int) and not isinstance(x, bool)\n+ or issubdtype(getattr(x, \"dtype\", None), np.integer) and np.ndim(x) == 0)\n+\n+def _is_bool_scalar_like(x):\n+ \"\"\"Returns True if x is a scalar boolean, False otherwise.\"\"\"\n+ return (isinstance(x, bool)\n+ or issubdtype(getattr(x, \"dtype\", None), np.bool_) and np.ndim(x) == 0)\ndef _canonicalize_tuple_index(arr_ndim, idx):\n\"\"\"Helper to remove Ellipsis and add in the implicit trailing slice(None).\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Fixes for numpy 1.20 It seems that `np.ndim` and `np.shape` fail in version 1.20 when used on sequences of Tracers. We avoid invoking these functions in places where this may happen.
260,287
02.02.2021 14:06:42
0
f812402d373e17711efb926b91d813bc5fab2bf3
Add support for named axes in jax.nn.one_hot
[ { "change_type": "MODIFY", "old_path": "jax/_src/nn/functions.py", "new_path": "jax/_src/nn/functions.py", "diff": "\"\"\"Shared neural network activations and other functions.\"\"\"\n+import operator\nimport numpy as np\nfrom typing import Any, Optional, Tuple, Union\n@@ -22,6 +23,8 @@ from jax import custom_jvp\nfrom jax import dtypes\nfrom jax import lax\nfrom jax import core\n+from jax.core import AxisName\n+from .. import util\nfrom jax.scipy.special import expit\nfrom jax.scipy.special import logsumexp as _logsumexp\nimport jax.numpy as jnp\n@@ -265,7 +268,8 @@ def normalize(x: Array,\nvariance = jnp.mean(jnp.square(x), axis, keepdims=True) - jnp.square(mean)\nreturn (x - mean) * lax.rsqrt(variance + epsilon)\n-def one_hot(x: Array, num_classes: int, *, dtype: Any = jnp.float64) -> Array:\n+def one_hot(x: Array, num_classes: int, *,\n+ dtype: Any = jnp.float64, axis: Union[int, AxisName] = -1) -> Array:\n\"\"\"One-hot encodes the given indicies.\nEach index in the input ``x`` is encoded as a vector of zeros of length\n@@ -293,8 +297,21 @@ def one_hot(x: Array, num_classes: int, *, dtype: Any = jnp.float64) -> Array:\n\"The error arose in jax.nn.one_hot argument `num_classes`.\")\ndtype = dtypes.canonicalize_dtype(dtype)\nx = jnp.asarray(x)\n- lhs = x[..., jnp.newaxis]\n- rhs = lax.broadcast_to_rank(jnp.arange(num_classes, dtype=x.dtype), lhs.ndim)\n+ try:\n+ output_pos_axis = util.canonicalize_axis(axis, x.ndim + 1)\n+ except TypeError:\n+ axis_size = lax.psum(1, axis)\n+ if num_classes != axis_size:\n+ raise ValueError(f\"Expected num_classes to match the size of axis {axis}, \"\n+ f\"but {num_classes} != {axis_size}\") from None\n+ axis_idx = lax.axis_index(axis)\n+ return jnp.asarray(x == axis_idx, dtype=dtype)\n+ axis = operator.index(axis)\n+ lhs = lax.expand_dims(x, (axis,))\n+ rhs_shape = [1] * x.ndim\n+ rhs_shape.insert(output_pos_axis, num_classes)\n+ rhs = lax.broadcast_in_dim(jnp.arange(num_classes, dtype=x.dtype),\n+ rhs_shape, (output_pos_axis,))\nreturn jnp.asarray(lhs == rhs, dtype=dtype)\ndef relu6(x: Array) -> Array:\n" }, { "change_type": "MODIFY", "old_path": "tests/nn_test.py", "new_path": "tests/nn_test.py", "diff": "@@ -166,6 +166,16 @@ class NNFunctionsTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(core.ConcretizationTypeError, msg):\njax.jit(nn.one_hot)(3, 5)\n+ def testOneHotAxis(self):\n+ expected = jnp.array([[0., 1., 0.],\n+ [0., 0., 1.],\n+ [1., 0., 0.]]).T\n+\n+ actual = nn.one_hot(jnp.array([1, 2, 0]), 3, axis=0)\n+ self.assertAllClose(actual, expected)\n+\n+ actual = nn.one_hot(jnp.array([1, 2, 0]), 3, axis=-2)\n+ self.assertAllClose(actual, expected)\nInitializerRecord = collections.namedtuple(\n\"InitializerRecord\",\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -388,6 +388,28 @@ class NamedNumPyTest(jtu.JaxTestCase):\nx = rng.randn(2, 5, 6)\nself.assertAllClose(ref_red(x), xmap_red(x))\n+ @ignore_xmap_warning()\n+ def testOneHot(self):\n+ f = xmap(lambda x: jax.nn.one_hot([1, 2, 0], 3, axis='i'),\n+ in_axes=['i', ...], out_axes=['i', ...])\n+ expected = jnp.array([[0., 1., 0.],\n+ [0., 0., 1.],\n+ [1., 0., 0.]]).T\n+ self.assertAllClose(f(jnp.ones((3,))), expected)\n+\n+ @ignore_xmap_warning()\n+ def testOneHotOutOfBound(self):\n+ f = xmap(lambda x: jax.nn.one_hot([-1, 3], 3, axis='i'),\n+ in_axes=['i', ...], out_axes=['i', ...])\n+ self.assertAllClose(f(jnp.ones((3,))), jnp.zeros((3, 2)))\n+\n+ @ignore_xmap_warning()\n+ def testOneHotAxisSizeMismatch(self):\n+ f = xmap(lambda x: jax.nn.one_hot([-1, 3], 3, axis='i'),\n+ in_axes=['i', ...], out_axes=['i', ...])\n+ with self.assertRaisesRegex(ValueError, \"to match the size of axis i, but 3 != 5\"):\n+ f(jnp.ones((5,)))\n+\nAxisIndices = Tuple[int, ...]\nMatchedAxisIndices = Tuple[AxisIndices, AxisIndices]\n" } ]
Python
Apache License 2.0
google/jax
Add support for named axes in jax.nn.one_hot
260,287
02.02.2021 15:39:23
0
a8b1f5f78fe08e03a953aff6b0a0dc84ab72f768
Add axis_sizes to xmap Right now, all axis sizes have to be inferred from arguments to xmap which is unnecessarily strict. This lets users specify explicit sizes, allowing them to handle e.g. empty dicts that were supposed to contain mapped arguments.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -210,6 +210,8 @@ def _prepare_axes(axes, arg_name):\ndef xmap(fun: Callable,\nin_axes,\nout_axes,\n+ *,\n+ axis_sizes: Dict[AxisName, int] = {},\naxis_resources: Dict[AxisName, Union[ResourceAxisName, Tuple[ResourceAxisName, ...]]] = {},\nbackend: Optional[str] = None):\n\"\"\"Assign a positional signature to a program that uses named array axes.\n@@ -298,6 +300,9 @@ def xmap(fun: Callable,\nas in ``in_axes``. Note that ``out_axes`` can also be a prefix of the return\ncontainer structure, in which case the mapping is repeated for all arrays\nin the collapsed subtree.\n+ axis_sizes: A dict mapping axis names to their sizes. All axes defined by xmap\n+ have to appear either in ``in_axes`` or ``axis_sizes``. Sizes of axes\n+ that appear in ``in_axes`` are inferred from arguments whenever possible.\naxis_resources: A dictionary mapping the axes introduced in this\n:py:func:`xmap` to one or more resource axes. Any array that has in its\nshape an axis with some resources assigned will be partitioned over the\n@@ -374,28 +379,33 @@ def xmap(fun: Callable,\nif isinstance(out_axes, list):\nout_axes = tuple(out_axes)\n+ if in_axes == (): # Allow empty argument lists\n+ in_axes, in_axes_entries = (), []\n+ else:\nin_axes, in_axes_entries = _prepare_axes(in_axes, \"in_axes\")\nout_axes, out_axes_entries = _prepare_axes(out_axes, \"out_axes\")\n+ axis_sizes_names = set(axis_sizes.keys())\nin_axes_names = set(it.chain(*(spec.keys() for spec in in_axes_entries)))\n+ defined_names = axis_sizes_names | in_axes_names\nout_axes_names = set(it.chain(*(spec.keys() for spec in out_axes_entries)))\nnormalized_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]] = \\\n{axis: (resources if isinstance(resources, tuple) else (resources,))\nfor axis, resources in axis_resources.items()}\n- for axis in in_axes_names:\n+ for axis in defined_names:\nnormalized_axis_resources.setdefault(axis, ())\nfrozen_axis_resources = FrozenDict(normalized_axis_resources)\nnecessary_resources = set(it.chain(*frozen_axis_resources.values()))\naxes_with_resources = set(frozen_axis_resources.keys())\n- if axes_with_resources > in_axes_names:\n+ if axes_with_resources > defined_names:\nraise ValueError(f\"All axes that were assigned resources have to appear in \"\n- f\"in_axes, but the following are missing: \"\n- f\"{axes_with_resources - in_axes_names}\")\n- if out_axes_names > in_axes_names:\n+ f\"in_axes or axis_sizes, but the following are missing: \"\n+ f\"{axes_with_resources - defined_names}\")\n+ if out_axes_names > defined_names:\nraise ValueError(f\"All axis names appearing in out_axes must also appear in \"\n- f\"in_axes, but the following are missing: \"\n- f\"{out_axes_names - in_axes_names}\")\n+ f\"in_axes or axis_sizes, but the following are missing: \"\n+ f\"{out_axes_names - defined_names}\")\nfor axis, resources in frozen_axis_resources.items():\nif len(set(resources)) != len(resources):\n@@ -422,13 +432,14 @@ def xmap(fun: Callable,\nout_axes_thunk = HashableFunction(\nlambda: tuple(flatten_axes(\"xmap out_axes\", out_tree(), out_axes)),\nclosure=out_axes)\n- axis_sizes = _get_axis_sizes(args_flat, in_axes_flat)\n+ frozen_axis_sizes = FrozenDict(_get_axis_sizes(args_flat, in_axes_flat, axis_sizes))\n+ assert set(frozen_axis_sizes.keys()) == set(frozen_axis_resources.keys())\nout_flat = xmap_p.bind(\nfun_flat, *args_flat,\nname=getattr(fun, '__name__', '<unnamed function>'),\nin_axes=tuple(in_axes_flat),\nout_axes_thunk=out_axes_thunk,\n- axis_sizes=FrozenDict(axis_sizes),\n+ axis_sizes=frozen_axis_sizes,\naxis_resources=frozen_axis_resources,\nresource_env=resource_env,\nbackend=backend)\n@@ -448,7 +459,7 @@ def make_xmap_callable(fun: lu.WrappedFun,\nin_axes, out_axes_thunk, axis_sizes,\naxis_resources, resource_env, backend,\n*in_avals):\n- plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env)\n+ plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\n# TODO: Making axis substitution final style would allow us to avoid\n# tracing to jaxpr here\n@@ -483,22 +494,31 @@ def make_xmap_callable(fun: lu.WrappedFun,\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n+ resource_env: ResourceEnv\n+ axis_sizes: Dict[AxisName, int]\nphysical_axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]]\naxis_subst: Dict[AxisName, Tuple[ResourceAxisName, ...]]\n@classmethod\n- def from_axis_resources(cls, axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]], resource_env):\n+ def from_axis_resources(cls,\n+ axis_resources: Dict[AxisName, Tuple[ResourceAxisName, ...]],\n+ resource_env: ResourceEnv,\n+ axis_sizes: Dict[AxisName, int]):\n# TODO: Support sequential resources\nphysical_axis_resources = axis_resources # NB: We only support physical resources at the moment\naxis_subst = {name: axes + (fresh_resource_name(name),) for name, axes in axis_resources.items()}\n- return cls(physical_axis_resources, axis_subst)\n+ return cls(resource_env, axis_sizes, physical_axis_resources, axis_subst)\ndef vectorize(self, f: lu.WrappedFun, in_axes, out_axes):\n+ resource_shape = self.resource_env.shape\nfor naxis, raxes in self.axis_subst.items():\n- vaxis = raxes[-1]\n+ paxes, vaxis = raxes[:-1], raxes[-1]\nmap_in_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), in_axes))\nmap_out_axes = tuple(unsafe_map(lambda spec: spec.get(naxis, None), out_axes))\n- f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=None, axis_name=vaxis)\n+ paxes_size = int(np.prod([resource_shape[paxis] for paxis in paxes], dtype=np.int64))\n+ assert self.axis_sizes[naxis] % paxes_size == 0\n+ tile_size = self.axis_sizes[naxis] // paxes_size\n+ f = pxla.vtile(f, map_in_axes, map_out_axes, tile_size=tile_size, axis_name=vaxis)\nreturn f\ndef to_mesh_axes(self, in_axes, out_axes):\n@@ -624,7 +644,7 @@ def _xmap_translation_rule_replica(c, axis_env,\ncall_jaxpr, name,\nin_axes, out_axes, axis_sizes,\naxis_resources, resource_env, backend):\n- plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env)\n+ plan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\nlocal_mesh = resource_env.physical_mesh.local_mesh\nlocal_mesh_shape = local_mesh.shape\n@@ -756,8 +776,10 @@ def _insert_aval_axes(aval, axes: AxisNamePos, axis_sizes):\n# TODO: pmap has some very fancy error messages for this function!\n-def _get_axis_sizes(args_flat: Iterable[Any], in_axes_flat: Iterable[AxisNamePos]):\n- axis_sizes: Dict[AxisName, int] = {}\n+def _get_axis_sizes(args_flat: Iterable[Any],\n+ in_axes_flat: Iterable[AxisNamePos],\n+ axis_sizes: Dict[AxisName, int]):\n+ axis_sizes = dict(axis_sizes)\nfor arg, in_axes in zip(args_flat, in_axes_flat):\nfor name, dim in in_axes.items():\nif name in axis_sizes:\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1534,9 +1534,6 @@ def vtile(f_flat,\nin_axes_flat: Tuple[Optional[int], ...],\nout_axes_flat: Tuple[Optional[int], ...],\ntile_size: Optional[int], axis_name):\n- if tile_size == 1:\n- return f_flat\n-\n@curry\ndef tile_axis(arg, axis: Optional[int], tile_size):\nif axis is None:\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -82,6 +82,8 @@ def with_mesh(named_shape: MeshSpec) -> Generator[None, None, None]:\nwith mesh(mesh_devices, axis_names):\nyield\n+def with_mesh_from_kwargs(f):\n+ return lambda *args, **kwargs: with_mesh(kwargs['mesh'])(f)(*args, **kwargs)\nclass XMapTest(jtu.JaxTestCase):\ndef setUp(self):\n@@ -202,10 +204,9 @@ class XMapTest(jtu.JaxTestCase):\n('OneToOne', (('x', 2), ('y', 2)), (('a', 'y'), ('b', 'x'))),\n('Multiple', (('x', 2), ('y', 2), ('z', 2)), (('a', 'y'), ('b', ('x', 'z')))),\n))\n+ @with_mesh_from_kwargs\n@ignore_xmap_warning()\ndef testNestedMesh(self, mesh, axis_resources):\n- @with_mesh(mesh)\n- def run_test():\n@partial(xmap, in_axes={1: 'a'}, out_axes=({0: 'a'}, {}),\naxis_resources=dict([axis_resources[0]]))\ndef f(x):\n@@ -224,7 +225,6 @@ class XMapTest(jtu.JaxTestCase):\n(pxla.Chunked(2), pxla.NoSharding(), pxla.NoSharding()))\nself.assertEqual(y[0].sharding_spec.mesh_mapping,\n(pxla.Replicated(2), pxla.ShardedAxis(0)) + (pxla.Replicated(2),) * (len(mesh) - 2))\n- run_test()\n@parameterized.named_parameters(\n{\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n@@ -232,14 +232,13 @@ class XMapTest(jtu.JaxTestCase):\n('', (), ()),\n('Mesh', (('x', 2),), (('i', 'x'),))\n))\n+ @with_mesh_from_kwargs\n@ignore_xmap_warning()\ndef testMultipleCalls(self, mesh, axis_resources):\ndef f(x, y):\nassert x.shape == y.shape == (3, 5)\nreturn jnp.tensordot(x, y, axes=([1], [1]))\n- @with_mesh(mesh)\n- def run_test():\nf_mapped = xmap(f,\nin_axes=(['i', ...], ['j', ...]),\nout_axes=['i', 'j', ...],\n@@ -248,7 +247,21 @@ class XMapTest(jtu.JaxTestCase):\nexpected = jnp.einsum('imk,jnk->ijmn', x, x)\nfor i in range(10):\nself.assertAllClose(f_mapped(x, x), expected)\n- run_test()\n+\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n+ for name, mesh, axis_resources in (\n+ ('', (), ()),\n+ ('Mesh', (('x', 2),), (('i', 'x'),))\n+ ))\n+ @with_mesh_from_kwargs\n+ @ignore_xmap_warning()\n+ def testAxisSizes(self, mesh, axis_resources):\n+ result = xmap(lambda: lax.axis_index('i'),\n+ in_axes=(), out_axes=['i', ...],\n+ axis_sizes={'i': 6},\n+ axis_resources=dict(axis_resources))()\n+ self.assertAllClose(result, jnp.arange(6, dtype=result.dtype))\ndef VmapOfXmapCases():\nxmap_in_axes = ([{}] +\n" } ]
Python
Apache License 2.0
google/jax
Add axis_sizes to xmap Right now, all axis sizes have to be inferred from arguments to xmap which is unnecessarily strict. This lets users specify explicit sizes, allowing them to handle e.g. empty dicts that were supposed to contain mapped arguments.
260,411
03.02.2021 11:06:18
-7,200
d3186b195f814c124ecc05deb0cefbe2c6a0aef8
Tightened the API of some jax.numpy functions Do not accept tuples and lists in lieu of array arguments
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -22,6 +22,10 @@ jax 0.2.10 (Unreleased)\n* :func:`jax.numpy.i0` no longer accepts complex numbers. Previously the\nfunction computed the absolute value of complex arguments. This change was\nmade to match the semantics of NumPy 1.20.0.\n+ * Several `jax.numpy` functions no longer accept tuples or lists in place\n+ of array arguments: :func:`jax.numpy.pad`, :func`jax.numpy.ravel`,\n+ :func:`jax.numpy.repeat`.\n+ In general, `jax.numpy` functions should be used with scalars or array arguments.\njaxlib 0.1.60 (Unreleased)\n--------------------------\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -662,9 +662,11 @@ def cond(*args, **kwargs):\nreturn _cond(*args, **kwargs)\ndef _cond(pred, true_fun: Callable, false_fun: Callable, operand):\n- if not isinstance(pred, Sequence) and len(np.shape(pred)) != 0:\n+ if isinstance(pred, Sequence) or np.ndim(pred) != 0:\nraise TypeError(\n- f\"Pred must be a scalar, got {pred} of shape {np.shape(pred)}.\")\n+ f\"Pred must be a scalar, got {pred} of \" +\n+ (f\"type {type(pred)}\" if isinstance(pred, Sequence)\n+ else f\"shape {np.shape(pred)}.\"))\ntry:\npred_dtype = dtypes.result_type(pred)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -131,20 +131,6 @@ ndim = _ndim = np.ndim\nsize = np.size\n_dtype = dtypes.result_type\n-def _ndim_sequence(xs):\n- \"\"\"A version of np.ndim that works on sequences that may include Tracers.\n-\n- Prior to version 1.20, np.ndim worked on sequences.\"\"\"\n- if isinstance(xs, Sequence):\n- if not xs:\n- return 1\n- ndims = set(_ndim_sequence(x) for x in xs)\n- if len(ndims) > 1:\n- raise ValueError(f\"ndim called on a ragged sequence with ndims {ndims}\")\n- return 1 + ndims.pop()\n- else:\n- return ndim(xs)\n-\n# At present JAX doesn't have a reason to distinguish between scalars and arrays\n# in its object system. Further, we want JAX scalars to have the same type\n# promotion behaviors as JAX arrays. Rather than introducing a new type of JAX\n@@ -1266,6 +1252,7 @@ def isrealobj(x):\n@_wraps(np.reshape)\ndef reshape(a, newshape, order=\"C\"):\n+ _check_arraylike(\"reshape\", a)\ntry:\nreturn a.reshape(newshape, order=order) # forward to method for ndarrays\nexcept AttributeError:\n@@ -1301,6 +1288,7 @@ def _reshape(a, *args, order=\"C\"):\n@_wraps(np.ravel)\ndef ravel(a, order=\"C\"):\n+ _check_arraylike(\"ravel\", a)\nif order == \"K\":\nraise NotImplementedError(\"Ravel not implemented for order='K'.\")\nreturn reshape(a, (size(a),), order)\n@@ -1349,7 +1337,7 @@ and out-of-bounds indices are clipped.\n@_wraps(np.unravel_index, lax_description=_UNRAVEL_INDEX_DOC)\ndef unravel_index(indices, shape):\nindices = asarray(indices)\n- sizes = pad(shape, (0, 1), constant_values=1)\n+ sizes = array(tuple(shape) + (1,))\ncumulative_sizes = cumprod(sizes[::-1])[::-1]\ntotal_size = cumulative_sizes[0]\n# Clip so raveling and unraveling an oob index will not change the behavior\n@@ -2600,7 +2588,8 @@ the modified array. This is because Jax arrays are immutable.\n(In numpy, \"function\" mode's argument should modify a rank 1 array in-place.)\n\"\"\")\ndef pad(array, pad_width, mode=\"constant\", **kwargs):\n- pad_width = _broadcast_to_pairs(pad_width, _ndim_sequence(array), \"pad_width\")\n+ _check_arraylike(\"pad\", array)\n+ pad_width = _broadcast_to_pairs(pad_width, ndim(array), \"pad_width\")\nif pad_width and np.array(pad_width).dtype.kind != 'i':\nraise TypeError('`pad_width` must be of integral type.')\n@@ -3183,6 +3172,7 @@ will be repeated.\n@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)\ndef repeat(a, repeats, axis: Optional[int] = None, *, total_repeat_length=None):\n_check_arraylike(\"repeat\", a)\n+ _check_arraylike(\"repeat\", repeats)\nif axis is None:\na = ravel(a)\n@@ -4601,7 +4591,7 @@ def _expand_bool_indices(idx):\nexcept TypeError:\nabstract_i = None\nif (isinstance(abstract_i, ShapedArray) and issubdtype(abstract_i.dtype, bool_)\n- or isinstance(i, list) and _all(_is_bool_scalar_like(e) for e in i)):\n+ or isinstance(i, list) and _all(_is_scalar(e) and issubdtype(_dtype(e), np.bool_) for e in i)):\nif isinstance(i, list):\ni = array(i)\nabstract_i = core.get_aval(i)\n@@ -4627,7 +4617,7 @@ def _is_advanced_int_indexer(idx):\n# https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\nassert isinstance(idx, tuple)\nif _all(e is None or e is Ellipsis or isinstance(e, slice)\n- or _is_int_scalar_like(e) for e in idx):\n+ or _is_scalar(e) and issubdtype(_dtype(e), np.integer) for e in idx):\nreturn False\nreturn _all(e is None or e is Ellipsis or isinstance(e, slice)\nor _is_int_arraylike(e) for e in idx)\n@@ -4638,15 +4628,9 @@ def _is_int_arraylike(x):\nor issubdtype(getattr(x, \"dtype\", None), np.integer)\nor isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))\n-def _is_int_scalar_like(x):\n- \"\"\"Returns True if x is a scalar integer, False otherwise.\"\"\"\n- return (isinstance(x, int) and not isinstance(x, bool)\n- or issubdtype(getattr(x, \"dtype\", None), np.integer) and np.ndim(x) == 0)\n-\n-def _is_bool_scalar_like(x):\n- \"\"\"Returns True if x is a scalar boolean, False otherwise.\"\"\"\n- return (isinstance(x, bool)\n- or issubdtype(getattr(x, \"dtype\", None), np.bool_) and np.ndim(x) == 0)\n+def _is_scalar(x):\n+ \"\"\"Checks if a Python or NumPy scalar.\"\"\"\n+ return np.isscalar(x) or (isinstance(x, ndarray) and np.ndim(x) == 0)\ndef _canonicalize_tuple_index(arr_ndim, idx):\n\"\"\"Helper to remove Ellipsis and add in the implicit trailing slice(None).\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1494,7 +1494,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\n'wrap': {},\n'empty': {}\n}\n- arr = [1, 2, 3]\n+ arr = jnp.array([1, 2, 3])\npad_width = 1\nfor mode in modes.keys():\n@@ -1550,7 +1550,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker)\ndef testPadWithNumpyPadWidth(self):\n- a = [1, 2, 3, 4, 5]\n+ a = jnp.array([1, 2, 3, 4, 5])\nf = jax.jit(\npartial(\njnp.pad,\n@@ -1944,7 +1944,7 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nelse:\nargs_maker = lambda: [m]\n- for repeats in [2, [1,3,2,1,1,2], [1,3,0,1,1,2], [2], jnp.array([1,3,2,1,1,2]), jnp.array([2])]:\n+ for repeats in [2, jnp.array([1,3,0,1,1,2]), jnp.array([1,3,2,1,1,2]), jnp.array([2])]:\ntest_single(m, args_maker, repeats, axis=None)\ntest_single(m, args_maker, repeats, axis=0)\n@@ -1954,10 +1954,10 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nelse:\nargs_maker = lambda: [m_rect]\n- for repeats in [2, [2,1], [2], jnp.array([2,1]), jnp.array([2])]:\n+ for repeats in [2, jnp.array([2,1]), jnp.array([2])]:\ntest_single(m_rect, args_maker, repeats, axis=0)\n- for repeats in [2, [1,3,2], [2], jnp.array([1,3,2]), jnp.array([2])]:\n+ for repeats in [2, jnp.array([1,3,2]), jnp.array([2])]:\ntest_single(m_rect, args_maker, repeats, axis=1)\ndef testIssue2330(self):\n" } ]
Python
Apache License 2.0
google/jax
Tightened the API of some jax.numpy functions Do not accept tuples and lists in lieu of array arguments
260,615
03.02.2021 15:09:21
18,000
48864a665b231e5e3994c06089c934ce6cb2dbe1
Add logdf and pdf for chisquare distribution Add tests Lint with flake8 fails. Should pass now newline at end of file for flake8 docs and changes remove whitespace in changeloc
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -11,6 +11,7 @@ jax 0.2.10 (Unreleased)\n-----------------------\n* `GitHub commits <https://github.com/google/jax/compare/jax-v0.2.9...master>`__.\n* New features:\n+ * :func:`jax.scipy.stats.chi2` is now available as a distribution with logpdf and pdf methods.\n* Bug fixes:\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -139,6 +139,17 @@ jax.scipy.stats.cauchy\nlogpdf\npdf\n+jax.scipy.stats.chi2\n+~~~~~~~~~~~~~~~~~~~~~~\n+.. automodule:: jax.scipy.stats.chi2\n+\n+.. autosummary::\n+ :toctree: _autosummary\n+\n+ logpdf\n+ pdf\n+\n+\njax.scipy.stats.dirichlet\n~~~~~~~~~~~~~~~~~~~~~~~~~\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/scipy/stats/chi2.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+\n+import scipy.stats as osp_stats\n+\n+from jax import lax\n+from jax._src.numpy.util import _wraps\n+from jax._src.numpy.lax_numpy import _promote_args_inexact, _constant_like, where, inf\n+\n+\n+@_wraps(osp_stats.chi2.logpdf, update_doc=False)\n+def logpdf(x, df, loc=0, scale=1):\n+ x, df, loc, scale = _promote_args_inexact(\"chi2.logpdf\", x, df, loc, scale)\n+ one = _constant_like(x, 1)\n+ two = _constant_like(x, 2)\n+ y = lax.div(lax.sub(x, loc), scale)\n+ df_on_two = lax.div(df, two)\n+\n+ kernel = lax.sub(lax.mul(lax.sub(df_on_two, one), lax.log(y)), lax.div(y,two))\n+\n+ nrml_cnst = lax.neg(lax.add(lax.lgamma(df_on_two),lax.div(lax.mul(lax.log(two), df),two)))\n+\n+ log_probs = lax.add(lax.sub(nrml_cnst, lax.log(scale)), kernel)\n+ return where(lax.lt(x, loc), -inf, log_probs)\n+\n+@_wraps(osp_stats.chi2.pdf, update_doc=False)\n+def pdf(x, df, loc=0, scale=1):\n+ return lax.exp(logpdf(x, df, loc, scale))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/__init__.py", "new_path": "jax/scipy/stats/__init__.py", "diff": "@@ -28,3 +28,4 @@ from . import pareto\nfrom . import poisson\nfrom . import t\nfrom . import uniform\n+from . import chi2\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/scipy/stats/chi2.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+# flake8: noqa: F401\n+\n+from jax._src.scipy.stats.chi2 import (\n+ logpdf,\n+ pdf,\n+)\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -406,6 +406,20 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=1e-4)\nself._CompileAndCheck(lax_fun, args_maker)\n+ @genNamedParametersNArgs(4)\n+ def testChi2LogPdf(self, shapes, dtypes):\n+ rng = jtu.rand_positive(self.rng())\n+ scipy_fun = osp_stats.chi2.logpdf\n+ lax_fun = lsp_stats.chi2.logpdf\n+\n+ def args_maker():\n+ x, df, loc, scale = map(rng, shapes, dtypes)\n+ return [x, df, loc, scale]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=5e-4)\n+ self._CompileAndCheck(lax_fun, args_maker)\n+\ndef testIssue972(self):\nself.assertAllClose(\nnp.ones((4,), np.float32),\n" } ]
Python
Apache License 2.0
google/jax
Add logdf and pdf for chisquare distribution Add tests Lint with flake8 fails. Should pass now newline at end of file for flake8 docs and changes remove whitespace in changeloc
260,287
04.02.2021 12:45:20
0
76e8deb06416ae4088d16044c31ec69777c289ff
Throw in `jax.random.bernoulli` for good measure Because it's useful in implementing dropout over named axes.
[ { "change_type": "MODIFY", "old_path": "jax/_src/random.py", "new_path": "jax/_src/random.py", "diff": "@@ -774,7 +774,7 @@ def _truncated_normal(key, lower, upper, shape, dtype) -> jnp.ndarray:\ndef bernoulli(key: jnp.ndarray,\np: jnp.ndarray = np.float32(0.5),\n- shape: Optional[Sequence[int]] = None) -> jnp.ndarray:\n+ shape: Optional[Union[Sequence[int], NamedShape]] = None) -> jnp.ndarray:\n\"\"\"Sample Bernoulli random values with given shape and mean.\nArgs:\n@@ -791,7 +791,7 @@ def bernoulli(key: jnp.ndarray,\n\"\"\"\ndtype = dtypes.canonicalize_dtype(lax.dtype(p))\nif shape is not None:\n- shape = core.canonicalize_shape(shape)\n+ shape = core.as_named_shape(shape)\nif not jnp.issubdtype(dtype, np.floating):\nmsg = \"bernoulli probability `p` must have a floating dtype, got {}.\"\nraise TypeError(msg.format(dtype))\n@@ -801,6 +801,7 @@ def bernoulli(key: jnp.ndarray,\n@partial(jit, static_argnums=(2,))\ndef _bernoulli(key, p, shape) -> jnp.ndarray:\nif shape is None:\n+ # TODO: Use the named part of `p` as well\nshape = np.shape(p)\nelse:\n_check_shape(\"bernoulli\", shape, np.shape(p))\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -416,6 +416,7 @@ class NamedRandomTest(jtu.JaxTestCase):\nfor name, sample in [\n(\"Uniform\", jax.random.uniform),\n(\"Normal\", jax.random.normal),\n+ (\"Bernoulli\", partial(jax.random.bernoulli, p=0.5)),\n(\"TruncatedNormal\", partial(jax.random.truncated_normal, lower=-2, upper=2)),\n])\n@ignore_xmap_warning()\n@@ -426,7 +427,7 @@ class NamedRandomTest(jtu.JaxTestCase):\nreplicated = sample((3,), 4)\nself.assertTrue((replicated[:,[0]] == replicated).all())\nsharded = sample(NamedShape(3, i=4), 4)\n- self.assertFalse((sharded[:,[0]] == sharded[:,1:]).any())\n+ self.assertFalse((sharded[:,[0]] == sharded[:,1:]).all(1).any())\nerror = \"The shape of axis i was specified as 4, but it really is 5\"\nwith self.assertRaisesRegex(ValueError, error):\nsample(NamedShape(3, i=4), 5)\n" } ]
Python
Apache License 2.0
google/jax
Throw in `jax.random.bernoulli` for good measure Because it's useful in implementing dropout over named axes.
260,424
04.02.2021 13:55:36
0
bea17e573df56ab02e2a2f4dcc22c842b5d6acc4
Fix a _check_arraylike error. Before, if `repeats` was the the non-array arg the error would display the wrong arg position (position 0 -> position 1)
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3178,8 +3178,7 @@ will be repeated.\n@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)\ndef repeat(a, repeats, axis: Optional[int] = None, *, total_repeat_length=None):\n- _check_arraylike(\"repeat\", a)\n- _check_arraylike(\"repeat\", repeats)\n+ _check_arraylike(\"repeat\", a, repeats)\nif axis is None:\na = ravel(a)\n" } ]
Python
Apache License 2.0
google/jax
Fix a _check_arraylike error. Before, if `repeats` was the the non-array arg the error would display the wrong arg position (position 0 -> position 1)
260,287
05.02.2021 10:52:54
0
a7d616e3d40824caeab07ff39757a43cb6f75aca
Fix a bug in xmap mesh slicing code The previous version didn't adjust the axes indices after slicing the devices array, leading to out-of-bounds errors when doing the transpose.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1371,12 +1371,12 @@ class Mesh:\nreturn Mesh(self.devices[subcube_indices], self.axis_names)\ndef __getitem__(self, new_axes):\n- indices = [0] * len(self.axis_names)\naxis_pos = {name: i for i, name in enumerate(self.axis_names)}\n- for axis in new_axes:\n- indices[axis_pos[axis]] = slice(None)\n- new_devices = self.devices[tuple(indices)]\n- new_devices = new_devices.transpose(tuple(axis_pos[axis] for axis in new_axes))\n+ new_devices = self.devices.transpose(tuple(axis_pos[axis] for axis in new_axes) +\n+ tuple(axis_pos[axis] for axis in self.axis_names\n+ if axis not in new_axes))\n+ new_devices = new_devices[(slice(None),) * len(new_axes) +\n+ (0,) * (len(self.axis_names) - len(new_axes))]\nreturn Mesh(new_devices, new_axes)\n@property\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -184,6 +184,14 @@ class XMapTest(jtu.JaxTestCase):\npxla.ShardingSpec((pxla.NoSharding(), pxla.Chunked((2, 2))),\n(pxla.ShardedAxis(1), pxla.ShardedAxis(0))))\n+ @ignore_xmap_warning()\n+ @with_mesh([('x', 2), ('y', 2)])\n+ def testSkipFirstMeshDim(self):\n+ def run(axis_resources):\n+ return xmap(lambda x: x * 2, in_axes=['i', ...], out_axes=['i', ...],\n+ axis_resources=axis_resources)(jnp.ones((4,)))\n+ self.assertAllClose(run({'i': 'x'}), run({'i': 'y'}))\n+\n@ignore_xmap_warning()\n@with_mesh([('x', 2)])\ndef testCompilationCache(self):\n" } ]
Python
Apache License 2.0
google/jax
Fix a bug in xmap mesh slicing code The previous version didn't adjust the axes indices after slicing the devices array, leading to out-of-bounds errors when doing the transpose.
260,287
05.02.2021 10:50:51
0
1194115e821f08d07a8b50d3409ff3ea1d950380
Make sure that samplers with names don't depend on axis resources
[ { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -69,6 +69,8 @@ def tearDownModule():\nos.environ[\"XLA_FLAGS\"] = prev_xla_flags\nxla_bridge.get_backend.cache_clear()\n+# -------------------- Mesh parametrization helpers --------------------\n+\nMeshSpec = List[Tuple[str, int]]\n@contextmanager\n@@ -87,6 +89,124 @@ def with_mesh(named_shape: MeshSpec) -> Generator[None, None, None]:\ndef with_mesh_from_kwargs(f):\nreturn lambda *args, **kwargs: with_mesh(kwargs['mesh'])(f)(*args, **kwargs)\n+\n+# -------------------- Itertools helpers --------------------\n+\n+def partitions(s, k):\n+ for indices in product(range(k), repeat=len(s)):\n+ outs = [[] for _ in range(k)]\n+ for i, elt in zip(indices, s):\n+ outs[i].append(elt)\n+ yield outs\n+\n+def powerset(s):\n+ s = list(s)\n+ return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))\n+\n+# -------------------- Axis resources generation --------------------\n+\n+AxisResources = Dict[str, Union[str, Tuple[str, ...]]]\n+\n+def schedules(sizes: Dict[str, int]\n+ ) -> Generator[Tuple[AxisResources, MeshSpec], None, None]:\n+ \"\"\"Test utility generating xmap parallel schedules from logical names & sizes.\n+\n+ Args:\n+ sizes: dict mapping logical axis name to its corresponding size.\n+\n+ Returns:\n+ A generator producing finitely many values, where each value is a pair in\n+ which the first element is a value suitable for xmap's axis_resources\n+ argument and the second element is a list of pairs with the first element\n+ representing a generated physical mesh axis name and the second element\n+ representing a corresponding generated mesh axis size. The generated mesh\n+ names/sizes can be used to define a physical mesh in tests.\n+\n+ This function doesn't generate schedules which map distinct logical axis names\n+ to the same parallel resource name. It only generates parallel resources; the\n+ rest are implicitly left for vectorization. Parallel resource names are\n+ generated by prepending an 'r', 'r1', or 'r2' to the corresponding logical\n+ name.\n+\n+ Examples:\n+ >>> for sched in schedules({'i': 2, 'j': 4}):\n+ ... print(sched)\n+ ({}, [])\n+ ({'i': 'ri'}, [('ri', 1)])\n+ ({'i': 'ri'}, [('ri', 2)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 1)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 2)])\n+ ({'i': ('r1i', 'r2i')}, [('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj'}, [('rj', 1)])\n+ ({'j': 'rj'}, [('rj', 2)])\n+ ({'j': 'rj'}, [('rj', 4)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 1)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 2)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 4)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 1)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 2)])\n+ ({'j': ('r1j', 'r2j')}, [('r1j', 4), ('r2j', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 2)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 4)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 1)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 2)])\n+ ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 4), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 4)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 1)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 2)])\n+ ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 4), ('r2j', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 2), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 1)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 2)])\n+ ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 2), ('r2i', 1)])\n+ \"\"\"\n+ def divisors(n: int) -> List[int]:\n+ return [m for m in range(1, n + 1) if not n % m]\n+\n+ def divisors2(n: int) -> Iterator[Tuple[int, int]]:\n+ for k1 in divisors(n):\n+ for k2 in divisors(n // k1):\n+ yield (k1, k2)\n+\n+ # choose a subset of logical axis names to map to parallel resources\n+ for names in powerset(sizes):\n+ # partition that set of logical axis names into two subsets: one subset to\n+ # map to one parallel resource axis and a second subset to map to two\n+ # parallel resource axes.\n+ for names1, names2 in partitions(names, 2):\n+ # to avoid generating too many complex cases, we skip generating cases\n+ # where more than one logical axis name is to be mapped to two parallel\n+ # resource axes. comment out this line to generate more complex tests.\n+ if len(names2) > 1: continue\n+ # make up parallel resource axis names for each logical axis\n+ axis_resources1 = ((name, 'r' + name) for name in names1)\n+ axis_resources2 = ((name, ('r1' + name, 'r2' + name)) for name in names2)\n+ axis_resources = dict(it.chain(axis_resources1, axis_resources2))\n+ # make up sizes for each resource axis, where the size must divide the\n+ # corresponding logical axis\n+ for mesh_sizes1 in product(*(divisors(sizes[n]) for n in names1)):\n+ for mesh_sizes2 in product(*(divisors2(sizes[n]) for n in names2)):\n+ mesh_data1 = (('r' + name, size) for name, size in zip(names1, mesh_sizes1))\n+ mesh_data2 = (pair for name, (size1, size2) in zip(names2, mesh_sizes2)\n+ for pair in [('r1' + name, size1), ('r2' + name, size2)])\n+ mesh_data = list(it.chain(mesh_data1, mesh_data2))\n+ yield axis_resources, mesh_data\n+\n+\nclass XMapTest(jtu.JaxTestCase):\ndef setUp(self):\nif jax.lib.version < (0, 1, 58):\n@@ -411,16 +531,26 @@ class NamedRandomTest(jtu.JaxTestCase):\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n- @parameterized.named_parameters(\n- {\"testcase_name\": name, \"distr_sample\": sample}\n+ @curry\n+ def parameterize_by_sampler(extra, f, subset):\n+ if extra is None:\n+ extra = [(\"\", {})]\n+ else:\n+ extra = list(extra)\n+ subset_fn = jtu.cases_from_list if subset else lambda x: x\n+ return parameterized.named_parameters(subset_fn(\n+ {\"testcase_name\": name + extra_name, \"distr_sample\": sample, **extra_kwargs}\nfor name, sample in [\n(\"Uniform\", jax.random.uniform),\n(\"Normal\", jax.random.normal),\n(\"Bernoulli\", partial(jax.random.bernoulli, p=0.5)),\n(\"TruncatedNormal\", partial(jax.random.truncated_normal, lower=-2, upper=2)),\n- ])\n+ ]\n+ for extra_name, extra_kwargs in extra))(f)\n+\n+ @parameterize_by_sampler(None, subset=False)\n@ignore_xmap_warning()\n- def testSample(self, distr_sample):\n+ def testSamplerSharding(self, distr_sample):\ndef sample(shape, map_size):\nreturn xmap(lambda: distr_sample(jax.random.PRNGKey(0), shape=shape),\nin_axes=(), out_axes=[None, 'i', ...], axis_sizes={'i': map_size})()\n@@ -432,6 +562,19 @@ class NamedRandomTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, error):\nsample(NamedShape(3, i=4), 5)\n+ @parameterize_by_sampler(\n+ ((f\"_mesh={mesh}_resources={sorted(axis_resources.items())}\",\n+ {\"axis_resources\": tuple(axis_resources.items()), \"mesh\": tuple(mesh)})\n+ for axis_resources, mesh in schedules({'i': 4, 'j': 6})), subset=True)\n+ @with_mesh_from_kwargs\n+ @ignore_xmap_warning()\n+ def testSamplerResourceIndependence(self, distr_sample, axis_resources, mesh):\n+ def sample(axis_resources):\n+ return xmap(lambda: distr_sample(jax.random.PRNGKey(0), shape=NamedShape(3, i=4, j=6)),\n+ in_axes=(), out_axes=['i', 'j', ...], axis_sizes={'i': 4, 'j': 6},\n+ axis_resources=axis_resources)()\n+ self.assertAllClose(sample({}), sample(dict(axis_resources)))\n+\nclass NamedNNTest(jtu.JaxTestCase):\ndef setUp(self):\n@@ -577,123 +720,12 @@ def axis_matchings(lhs_shape, rhs_shape):\nyield ((i, j), *matches)\nreturn helper(0, set(), set())\n-def partitions(s, k):\n- for indices in product(range(k), repeat=len(s)):\n- outs = [[] for _ in range(k)]\n- for i, elt in zip(indices, s):\n- outs[i].append(elt)\n- yield outs\n-\n-def powerset(s):\n- s = list(s)\n- return it.chain.from_iterable(it.combinations(s, r) for r in range(len(s)+1))\n-\ndef gen_axis_names():\nnames = 'ijkl'\nfor n in it.count(1):\nfor chars in product(names, repeat=n):\nyield ''.join(chars)\n-AxisResources = Dict[str, Union[str, Tuple[str, ...]]]\n-\n-def schedules(sizes: Dict[str, int]\n- ) -> Generator[Tuple[AxisResources, MeshSpec], None, None]:\n- \"\"\"Test utility generating xmap parallel schedules from logical names & sizes.\n-\n- Args:\n- sizes: dict mapping logical axis name to its corresponding size.\n-\n- Returns:\n- A generator producing finitely many values, where each value is a pair in\n- which the first element is a value suitable for xmap's axis_resources\n- argument and the second element is a list of pairs with the first element\n- representing a generated physical mesh axis name and the second element\n- representing a corresponding generated mesh axis size. The generated mesh\n- names/sizes can be used to define a physical mesh in tests.\n-\n- This function doesn't generate schedules which map distinct logical axis names\n- to the same parallel resource name. It only generates parallel resources; the\n- rest are implicitly left for vectorization. Parallel resource names are\n- generated by prepending an 'r', 'r1', or 'r2' to the corresponding logical\n- name.\n-\n- Exa,mples:\n- >>> for sched in schedules({'i': 2, 'j': 4}):\n- ... print(sched)\n- ({}, [])\n- ({'i': 'ri'}, [('ri', 1)])\n- ({'i': 'ri'}, [('ri', 2)])\n- ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 1)])\n- ({'i': ('r1i', 'r2i')}, [('r1i', 1), ('r2i', 2)])\n- ({'i': ('r1i', 'r2i')}, [('r1i', 2), ('r2i', 1)])\n- ({'j': 'rj'}, [('rj', 1)])\n- ({'j': 'rj'}, [('rj', 2)])\n- ({'j': 'rj'}, [('rj', 4)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 1)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 2)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 1), ('r2j', 4)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 1)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 2), ('r2j', 2)])\n- ({'j': ('r1j', 'r2j')}, [('r1j', 4), ('r2j', 1)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 1)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 2)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 1), ('rj', 4)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 1)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 2)])\n- ({'i': 'ri', 'j': 'rj'}, [('ri', 2), ('rj', 4)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 1)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 2)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 1), ('r2j', 4)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 1)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 2), ('r2j', 2)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 1), ('r1j', 4), ('r2j', 1)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 1)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 2)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 1), ('r2j', 4)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 1)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 2), ('r2j', 2)])\n- ({'i': 'ri', 'j': ('r1j', 'r2j')}, [('ri', 2), ('r1j', 4), ('r2j', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 1), ('r2i', 2)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 1), ('r1i', 2), ('r2i', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 1), ('r2i', 2)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 2), ('r1i', 2), ('r2i', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 1)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 1), ('r2i', 2)])\n- ({'j': 'rj', 'i': ('r1i', 'r2i')}, [('rj', 4), ('r1i', 2), ('r2i', 1)])\n- \"\"\"\n- def divisors(n: int) -> List[int]:\n- return [m for m in range(1, n + 1) if not n % m]\n-\n- def divisors2(n: int) -> Iterator[Tuple[int, int]]:\n- for k1 in divisors(n):\n- for k2 in divisors(n // k1):\n- yield (k1, k2)\n-\n- # choose a subset of logical axis names to map to parallel resources\n- for names in powerset(sizes):\n- # partition that set of logical axis names into two subsets: one subset to\n- # map to one parallel resource axis and a second subset to map to two\n- # parallel resource axes.\n- for names1, names2 in partitions(names, 2):\n- # to avoid generating too many complex cases, we skip generating cases\n- # where more than one logical axis name is to be mapped to two parallel\n- # resource axes. comment out this line to generate more complex tests.\n- if len(names2) > 1: continue\n- # make up parallel resource axis names for each logical axis\n- axis_resources1 = ((name, 'r' + name) for name in names1)\n- axis_resources2 = ((name, ('r1' + name, 'r2' + name)) for name in names2)\n- axis_resources = dict(it.chain(axis_resources1, axis_resources2))\n- # make up sizes for each resource axis, where the size must divide the\n- # corresponding logical axis\n- for mesh_sizes1 in product(*(divisors(sizes[n]) for n in names1)):\n- for mesh_sizes2 in product(*(divisors2(sizes[n]) for n in names2)):\n- mesh_data1 = (('r' + name, size) for name, size in zip(names1, mesh_sizes1))\n- mesh_data2 = (pair for name, (size1, size2) in zip(names2, mesh_sizes2)\n- for pair in [('r1' + name, size1), ('r2' + name, size2)])\n- mesh_data = list(it.chain(mesh_data1, mesh_data2))\n- yield axis_resources, mesh_data\ndef schedules_from_pdot_spec(\nspec: PdotTestSpec, lhs_shape: Tuple[int], rhs_shape: Tuple[int]\n" } ]
Python
Apache License 2.0
google/jax
Make sure that samplers with names don't depend on axis resources
260,287
04.02.2021 14:01:56
0
1361ae1247091e404e723e2fcc71a2dfffc8bd5d
Add positional axis handling to the psum transpose rule I must have forgotten to do that in one of the previous patches and apparently we didn't have any tests for it (at least in the `vmap` case)!
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -650,10 +650,20 @@ def _notuple_allreduce_translation_rule(prim, c, *args, named_axes, axis_env,\nreturn xops.Tuple(c, outs)\ndef _psum_transpose_rule(cts, *args, axes, axis_index_groups):\n- if any(isinstance(axis, int) for axis in axes):\n- raise NotImplementedError\n+ named_axes, pos_axes = axes_partition = [], []\n+ for axis in axes:\n+ axes_partition[isinstance(axis, int)].append(axis)\n+\n+ def broadcast_positional(ct, arg):\n+ assert ad.is_undefined_primal(arg)\n+ if type(ct) is ad.Zero: return ad.Zero(arg.aval)\n+ return lax._reduce_sum_transpose_rule(ct, arg, axes=pos_axes)[0]\n+ cts = map(broadcast_positional, cts, args)\n+\n+ # We treat psum as psum + pbroadcast, which is why the transpose reduces\n+ # over the named axes again (unlike for positional axes).\nnonzero_out_cts, treedef = tree_util.tree_flatten(cts)\n- nonzero_in_cts = psum_p.bind(*nonzero_out_cts, axes=axes,\n+ nonzero_in_cts = psum_p.bind(*nonzero_out_cts, axes=named_axes,\naxis_index_groups=axis_index_groups)\nreturn tree_util.tree_unflatten(treedef, nonzero_in_cts)\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -978,7 +978,7 @@ class BatchingTest(jtu.JaxTestCase):\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\ndef testCommAssocCollective(self, collective, bulk_op, vmap_names, collective_names):\n- x = jnp.arange(3 * 4 * 5).reshape((3, 4, 5))\n+ x = jnp.arange(3 * 4 * 5, dtype=jnp.float32).reshape((3, 4, 5))\n# To test relative permutations of the order in which the axis names appear\n# in the primitive call versus the order the vmaps are applied, we always\n@@ -989,6 +989,9 @@ class BatchingTest(jtu.JaxTestCase):\nf = vmap(f, axis_name=axis_name)\nself.assertAllClose(f(x), x - bulk_op(x, axis=tuple(range(len(vmap_names)))))\n+ if collective is lax.psum:\n+ jtu.check_grads(f, (x,), 2, eps=1)\n+\n@skipIf(not jax.config.omnistaging_enabled,\n\"vmap collectives only supported when omnistaging is enabled\")\ndef testPPermute(self):\n" } ]
Python
Apache License 2.0
google/jax
Add positional axis handling to the psum transpose rule I must have forgotten to do that in one of the previous patches and apparently we didn't have any tests for it (at least in the `vmap` case)!
260,287
04.02.2021 15:45:23
0
45dc712e779557a24a354c34574dede95f034741
Don't require ellipsis at the end of each list axis spec in xmap Skipping the ellipsis will make xmap assert that your inputs are of ranks matching the length of the list.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -170,12 +170,18 @@ def fresh_resource_name(tag=None):\n# This is really a Dict[AxisName, int], but we don't define a\n# pytree instance for it, so that it is treated as a leaf.\nclass AxisNamePos(FrozenDict):\n- user_repr: Any\n+ user_repr: str\n+ expected_rank: Optional[int] = None\ndef __init__(self, *args, user_repr, **kwargs):\nsuper().__init__(*args, **kwargs)\nself.user_repr = user_repr\n+class AxisNamePosWithRank(AxisNamePos):\n+ def __init__(self, *args, expected_rank, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ self.expected_rank = expected_rank\n+\n# str(...) == 'Ellipsis' which is really annoying\nclass DotDotDotRepr:\n@@ -188,16 +194,23 @@ def _parse_entry(arg_name, entry):\nresult = AxisNamePos(((name, axis) for axis, name in entry.items()),\nuser_repr=str(entry))\nnum_mapped_dims = len(entry)\n- # Non-empty lists or tuples that terminate with an ellipsis\n- elif isinstance(entry, (tuple, list)) and entry and entry[-1] == ...:\n- result = AxisNamePos(((name, axis) for axis, name in enumerate(entry[:-1])\n+ # Non-empty lists or tuples that optionally terminate with an ellipsis\n+ elif isinstance(entry, (tuple, list)):\n+ if entry and entry[-1] == ...:\n+ constr = AxisNamePos\n+ entry = entry[:-1]\n+ user_repr = str(entry + [DotDotDotRepr()])\n+ else:\n+ constr = partial(AxisNamePosWithRank, expected_rank=len(entry))\n+ user_repr = str(entry)\n+ result = constr(((name, axis) for axis, name in enumerate(entry)\nif name is not None),\n- user_repr=str(entry[:-1] + [DotDotDotRepr()]))\n- num_mapped_dims = sum(name is not None for name in entry[:-1])\n+ user_repr=user_repr)\n+ num_mapped_dims = sum(name is not None for name in entry)\nelse:\nraise TypeError(f\"\"\"\\\nValue mapping specification in xmap {arg_name} pytree can be either:\n-- lists of axis names, ending with ellipsis (...)\n+- lists of axis names (possibly ending with the ellipsis object: ...)\n- dictionaries that map axis names to positional axes (integers)\nbut got: {entry}\"\"\")\nif len(result) != num_mapped_dims:\n@@ -432,6 +445,10 @@ def xmap(fun: Callable,\nraise ValueError(f\"Resource assignment of a single axis must be a tuple of \"\nf\"distinct resources, but specified {resources} for axis {axis}\")\n+ # A little performance optimization to avoid iterating over all args unnecessarily\n+ has_input_rank_assertions = any(spec.expected_rank is not None for spec in in_axes_entries)\n+ has_output_rank_assertions = any(spec.expected_rank is not None for spec in out_axes_entries)\n+\n@wraps(fun)\ndef fun_mapped(*args):\n# Putting this outside of fun_mapped would make resources lexically scoped\n@@ -459,6 +476,12 @@ def xmap(fun: Callable,\nf\"You've probably passed in empty containers in place of arguments that had \"\nf\"those axes in their in_axes. Provide the sizes of missing axes explicitly \"\nf\"via axis_sizes to fix this error.\")\n+ if has_input_rank_assertions:\n+ for arg, spec in zip(args_flat, in_axes_flat):\n+ if spec.expected_rank is not None and spec.expected_rank != arg.ndim:\n+ raise ValueError(f\"xmap argument has an in_axes specification of {spec.user_repr}, \"\n+ f\"which asserts that it should be of rank {spec.expected_rank}, \"\n+ f\"but the argument has rank {arg.ndim} (and shape {arg.shape})\")\nout_flat = xmap_p.bind(\nfun_flat, *args_flat,\nname=getattr(fun, '__name__', '<unnamed function>'),\n@@ -468,6 +491,12 @@ def xmap(fun: Callable,\naxis_resources=frozen_axis_resources,\nresource_env=resource_env,\nbackend=backend)\n+ if has_output_rank_assertions:\n+ for out, spec in zip(out_flat, out_axes_thunk()):\n+ if spec.expected_rank is not None and spec.expected_rank != out.ndim:\n+ raise ValueError(f\"xmap output has an out_axes specification of {spec.user_repr}, \"\n+ f\"which asserts that it should be of rank {spec.expected_rank}, \"\n+ f\"but the output has rank {out.ndim} (and shape {out.shape})\")\nreturn tree_unflatten(out_tree(), out_flat)\nreturn fun_mapped\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -890,7 +890,7 @@ class PDotTests(jtu.JaxTestCase):\nx = rng.randn(3)\ny = rng.randn(3)\nout = xmap(partial(jnp.einsum, '{i},{i}->'),\n- in_axes=(['i', ...], ['i', ...]), out_axes=[...])(x, y)\n+ in_axes=(['i'], ['i']), out_axes=[])(x, y)\nexpected = np.einsum('i,i->', x, y)\nself.assertAllClose(out, expected, check_dtypes=False)\n@@ -900,7 +900,7 @@ class PDotTests(jtu.JaxTestCase):\nx = rng.randn(3)\ny = rng.randn(3)\nout = xmap(partial(jnp.einsum, '{i},{j}->{i,j}'),\n- in_axes=(['i', ...], ['j', ...]), out_axes=['i', 'j', ...])(x, y)\n+ in_axes=(['i'], ['j']), out_axes=['i', 'j'])(x, y)\nexpected = np.einsum('i,j->ij', x, y)\nself.assertAllClose(out, expected, check_dtypes=True)\n@@ -911,8 +911,8 @@ class PDotTests(jtu.JaxTestCase):\ny = rng.randn(4, 5)\nout = xmap(partial(jnp.einsum, '{i,j},{j,k}->{i,k}'),\n- in_axes=(['i', 'j', ...], ['j', 'k', ...]),\n- out_axes=['i', 'k', ...])(x, y)\n+ in_axes=(['i', 'j'], ['j', 'k']),\n+ out_axes=['i', 'k'])(x, y)\nexpected = np.einsum('ij,jk->ik', x, y)\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\nself.assertAllClose(out, expected, check_dtypes=True,\n@@ -920,8 +920,8 @@ class PDotTests(jtu.JaxTestCase):\n# order of named axes in the spec doesn't matter!\nout = xmap(partial(jnp.einsum, '{i,j},{k,j}->{k,i}'),\n- in_axes=(['i', 'j', ...], ['j', 'k', ...]),\n- out_axes=['i', 'k', ...])(x, y)\n+ in_axes=(['i', 'j'], ['j', 'k']),\n+ out_axes=['i', 'k'])(x, y)\nexpected = np.einsum('ij,jk->ik', x, y)\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\nself.assertAllClose(out, expected, check_dtypes=True,\n@@ -1031,6 +1031,20 @@ class XMapErrorTest(jtu.JaxTestCase):\nwith self.assertRaisesRegex(ValueError, \"xmap doesn't support negative axes in out_axes\"):\nxmap(lambda x: x, in_axes={0: 'i'}, out_axes={-1: 'i'})(jnp.ones((5,)))\n+ @ignore_xmap_warning()\n+ def testListAxesRankAssertion(self):\n+ error = (r\"xmap argument has an in_axes specification of \\['i', None\\], which \"\n+ r\"asserts that it should be of rank 2, but the argument has rank 1 \"\n+ r\"\\(and shape \\(5,\\)\\)\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x: x, in_axes=['i', None], out_axes=['i', None])(jnp.ones((5,)))\n+ error = (r\"xmap output has an out_axes specification of \\['i', None\\], which \"\n+ r\"asserts that it should be of rank 2, but the output has rank 3 \"\n+ r\"\\(and shape \\(5, 2, 2\\)\\)\")\n+ with self.assertRaisesRegex(ValueError, error):\n+ xmap(lambda x: x.reshape((2, 2)),\n+ in_axes=['i', None], out_axes=['i', None])(jnp.ones((5, 4)))\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Don't require ellipsis at the end of each list axis spec in xmap Skipping the ellipsis will make xmap assert that your inputs are of ranks matching the length of the list.
260,287
05.02.2021 17:12:23
0
6ada0b02a81eb5d237644d8d46a69fa235e3e77c
Hotfix for psum transpose The previous patch has been causing some failures in the `is_undefined_primal` assertion in `broadcast_position`, but it looks like in all of those cases there are no positional axes, so this should fix them. More debugging underway, but I wanted to make sure they're unblocked.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -654,6 +654,7 @@ def _psum_transpose_rule(cts, *args, axes, axis_index_groups):\nfor axis in axes:\naxes_partition[isinstance(axis, int)].append(axis)\n+ if pos_axes:\ndef broadcast_positional(ct, arg):\nassert ad.is_undefined_primal(arg)\nif type(ct) is ad.Zero: return ad.Zero(arg.aval)\n" } ]
Python
Apache License 2.0
google/jax
Hotfix for psum transpose The previous patch has been causing some failures in the `is_undefined_primal` assertion in `broadcast_position`, but it looks like in all of those cases there are no positional axes, so this should fix them. More debugging underway, but I wanted to make sure they're unblocked.
260,615
05.02.2021 15:13:09
18,000
a3ad787402ced1a85864783395410c94c4584964
Add betabinomial logpmf/pmf and tests Squash all changes to single commit. Add betabinom Add tests for betabinom. nan where undefefined squash
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.rst", "new_path": "docs/CHANGELOG.rst", "diff": "@@ -12,6 +12,7 @@ jax 0.2.10 (Unreleased)\n* `GitHub commits <https://github.com/google/jax/compare/jax-v0.2.9...master>`__.\n* New features:\n* :func:`jax.scipy.stats.chi2` is now available as a distribution with logpdf and pdf methods.\n+ * :func:`jax.scipy.stats.betabinom` is now available as a distribution with logpmf and pmf methods.\n* Bug fixes:\n" }, { "change_type": "MODIFY", "old_path": "docs/jax.scipy.rst", "new_path": "docs/jax.scipy.rst", "diff": "@@ -129,6 +129,16 @@ jax.scipy.stats.beta\nlogpdf\npdf\n+jax.scipy.stats.betabinom\n+~~~~~~~~~~~~~~~~~~~~\n+.. automodule:: jax.scipy.stats.betabinom\n+\n+.. autosummary::\n+ :toctree: _autosummary\n+\n+ logpmf\n+ pmf\n+\njax.scipy.stats.cauchy\n~~~~~~~~~~~~~~~~~~~~~~\n.. automodule:: jax.scipy.stats.cauchy\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/_src/scipy/stats/betabinom.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+\n+import scipy.stats as osp_stats\n+\n+from jax import lax\n+from jax._src.numpy.util import _wraps\n+from jax._src.numpy.lax_numpy import _promote_args_inexact, _constant_like, where, inf, logical_or, nan\n+from jax._src.scipy.special import betaln\n+\n+\n+@_wraps(osp_stats.betabinom.logpmf, update_doc=False)\n+def logpmf(k, n, a, b, loc=0):\n+ k, n, a, b, loc = _promote_args_inexact(\"betabinom.logpmf\", k, n, a, b, loc)\n+ y = lax.sub(lax.floor(k), loc)\n+ one = _constant_like(y, 1)\n+ zero = _constant_like(y, 0)\n+ combiln = lax.neg(lax.add(lax.log1p(n), betaln(lax.add(lax.sub(n,y), one), lax.add(y,one))))\n+ beta_lns = lax.sub(betaln(lax.add(y,a), lax.add(lax.sub(n,y),b)), betaln(a,b))\n+ log_probs = lax.add(combiln, beta_lns)\n+ y_cond = logical_or(lax.lt(y, lax.neg(loc)), lax.gt(y, lax.sub(n, loc)))\n+ log_probs = where(y_cond, -inf, log_probs)\n+ n_a_b_cond = logical_or(logical_or(lax.lt(n, one), lax.lt(a, zero)), lax.lt(b, zero))\n+ return where(n_a_b_cond, nan, log_probs)\n+\n+@_wraps(osp_stats.betabinom.pmf, update_doc=False)\n+def pmf(k, n, a, b, loc=0):\n+ return lax.exp(logpmf(k, n, a, b, loc))\n" }, { "change_type": "MODIFY", "old_path": "jax/scipy/stats/__init__.py", "new_path": "jax/scipy/stats/__init__.py", "diff": "@@ -29,3 +29,4 @@ from . import poisson\nfrom . import t\nfrom . import uniform\nfrom . import chi2\n+from . import betabinom\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "jax/scipy/stats/betabinom.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+# flake8: noqa: F401\n+\n+from jax._src.scipy.stats.betabinom import (\n+ logpmf,\n+ pmf,\n+)\n" }, { "change_type": "MODIFY", "old_path": "tests/scipy_stats_test.py", "new_path": "tests/scipy_stats_test.py", "diff": "@@ -420,6 +420,25 @@ class LaxBackedScipyStatsTests(jtu.JaxTestCase):\ntol=5e-4)\nself._CompileAndCheck(lax_fun, args_maker)\n+ @genNamedParametersNArgs(5)\n+ def testBetaBinomLogPmf(self, shapes, dtypes):\n+ rng = jtu.rand_positive(self.rng())\n+ scipy_fun = osp_stats.betabinom.logpmf\n+ lax_fun = lsp_stats.betabinom.logpmf\n+\n+ def args_maker():\n+ k, n, a, b, loc = map(rng, shapes, dtypes)\n+ k = np.floor(k)\n+ n = np.ceil(n)\n+ a = np.clip(a, a_min = 0.1, a_max = None)\n+ b = np.clip(a, a_min = 0.1, a_max = None)\n+ loc = np.floor(loc)\n+ return [k, n, a, b, loc]\n+\n+ self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker, check_dtypes=False,\n+ tol=5e-4)\n+ self._CompileAndCheck(lax_fun, args_maker, rtol=1e-5, atol=1e-5)\n+\ndef testIssue972(self):\nself.assertAllClose(\nnp.ones((4,), np.float32),\n" } ]
Python
Apache License 2.0
google/jax
Add betabinomial logpmf/pmf and tests Squash all changes to single commit. Add betabinom Add tests for betabinom. nan where undefefined squash
260,335
05.02.2021 16:25:23
28,800
bb4d46c25b93e0bf5ded8b64e3929b8ceeba938a
make vmap-of-cond preserve nan safety Thanks to John Jumper and Jonas Adler!
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/control_flow.py", "new_path": "jax/_src/lax/control_flow.py", "diff": "@@ -754,47 +754,58 @@ def _select_tree(indices, branch_vals):\nassert len(branch_vals) > 0\nif len(branch_vals) == 1:\nreturn branch_vals[0]\n- mid = len(branch_vals) // 2\n- mid = np.array(mid, dtypes.canonicalize_dtype(lax.dtype(indices)))\n- return lax.select(lax.lt(indices, mid),\n+ mid = lax._const(indices, len(branch_vals) // 2)\n+ return _bcast_select(lax.lt(indices, mid),\n_select_tree(indices, branch_vals[:mid]),\n_select_tree(indices - mid, branch_vals[mid:]))\n-def _cond_index_bcast_and_select_tree(indices, branch_vals):\n- if all(core.get_aval(x) is core.abstract_unit for x in branch_vals):\n- return branch_vals[0]\n- else:\n- bcast_indices = lax.broadcast_in_dim(\n- indices, np.shape(branch_vals[0]), list(range(np.ndim(indices))))\n- return _select_tree(bcast_indices, branch_vals)\n+def _bcast_select(pred, on_true, on_false):\n+ if np.ndim(pred) != np.ndim(on_true):\n+ idx = list(range(np.ndim(pred)))\n+ pred = lax.broadcast_in_dim(pred, np.shape(on_true), idx)\n+ return lax.select(pred, on_true, on_false)\ndef _cond_batching_rule(args, dims, axis_name, branches, linear):\n- # TODO: maybe avoid moving arg axes to front if we're promoting to select?\nsize, = {x.shape[d] for x, d in zip(args, dims) if d is not batching.not_mapped}\n- args = [batching.moveaxis(x, d, 0) if d is not batching.not_mapped and d != 0\n- else x for x, d in zip(args, dims)]\n- orig_bat = [d is not batching.not_mapped for d in dims]\n- del dims\nindex, *ops = args\n- index_bat, *bat = orig_bat\n+ index_dim, *op_dims = dims\n+\n+ if index_dim is not batching.not_mapped:\n+ # Convert to a lax.select. While we could get away with not broadcasting\n+ # some operands yet, because all outputs must be broadcast together anyway\n+ # for the select we broadcast the input operands for simplicity and leave\n+ # optimizations to XLA.\n+ # TODO(mattjj,frostig): assumes branches are side-effect-free, revise!\n+ index, *ops = [batching.bdim_at_front(x, d, size) for x, d in zip(args, dims)]\n+\n+ branches_batched = [\n+ batching.batch_jaxpr(jaxpr, size, [True] * len(ops), True, axis_name)[0]\n+ for jaxpr in branches]\n+\n+ branch_outs = []\n+ for i, jaxpr in enumerate(branches_batched):\n+ # Perform a select on the inputs for safety of reverse-mode autodiff; see\n+ # https://github.com/google/jax/issues/1052\n+ ops_ = [_bcast_select(lax.eq(index, lax._const(index, i)),\n+ x, lax.stop_gradient(x))\n+ if x is not core.unit else x for x in ops]\n+ branch_outs.append(core.jaxpr_as_fun(jaxpr)(*ops_))\n+ out = [_select_tree(index, outs) if outs[0] is not core.unit else outs[0]\n+ for outs in zip(*branch_outs)]\n+ return out, [0] * len(branch_outs[0])\n+ else:\n+ ops_bat = [d is not batching.not_mapped for d in op_dims]\n+ ops = [batching.moveaxis(x, d, 0) if b else x\n+ for b, x, d in zip(ops_bat, ops, op_dims)]\n- branches_out_bat = [batching.batch_jaxpr(jaxpr, size, bat, False, axis_name)[1]\n+ branches_out_bat = [\n+ batching.batch_jaxpr(jaxpr, size, ops_bat, False, axis_name)[1]\nfor jaxpr in branches]\nout_bat = [any(bat) for bat in zip(*branches_out_bat)]\n-\n- branches_batched = tuple(batching.batch_jaxpr(jaxpr, size, bat, out_bat, axis_name)[0]\n+ branches_batched = tuple(\n+ batching.batch_jaxpr(jaxpr, size, ops_bat, out_bat, axis_name)[0]\nfor jaxpr in branches)\n- if index_bat:\n- branch_outs = []\n- for jaxpr in branches_batched:\n- out = core.jaxpr_as_fun(jaxpr)(*ops)\n- out = [batching.broadcast(x, size, 0) if not b else x\n- for x, b in zip(out, out_bat)]\n- branch_outs.append(out)\n- return [_cond_index_bcast_and_select_tree(index, outs)\n- for outs in zip(*branch_outs)], [0] * len(branch_outs[0])\n- else:\nout_dims = [0 if b else batching.not_mapped for b in out_bat]\nout = cond_p.bind(\nindex, *ops, branches=branches_batched, linear=linear)\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_control_flow_test.py", "new_path": "tests/lax_control_flow_test.py", "diff": "@@ -982,6 +982,16 @@ class LaxControlFlowTest(jtu.JaxTestCase):\nself.assertAllClose(ans, expected, check_dtypes=False)\njtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"])\n+ @skipIf(not config.omnistaging_enabled, \"test only works with omnistaging\")\n+ def testCondGradVmapNan(self):\n+ eps = 1e-3\n+\n+ def safe1(x):\n+ return lax.cond(x < eps, lambda _: eps, lambda _: jnp.sqrt(x), ())\n+\n+ out = api.grad(lambda x: api.vmap(safe1)(x).sum())(np.zeros(10))\n+ self.assertFalse(np.isnan(out).any())\n+\ndef testSwitchGrad(self):\nbranches = [lambda x: 3. * x,\nlambda x: jnp.sin(x),\n" } ]
Python
Apache License 2.0
google/jax
make vmap-of-cond preserve nan safety Thanks to John Jumper and Jonas Adler!
260,719
06.02.2021 22:05:06
-19,080
108d078c5f55507330873f6310a1c205f01dcc59
add support for union1d add union1d in jax.numpy which closely follows numpy implementaion
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -362,6 +362,7 @@ Not every function in NumPy is implemented; contributions are welcome!\nuint64\nuint8\nunique\n+ union1d\nunpackbits\nunravel_index\nunsignedinteger\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1515,6 +1515,16 @@ def setdiff1d(ar1, ar2, assume_unique=False):\nidx = in1d(ar1, ar2, invert=True)\nreturn ar1[idx]\n+\n+@_wraps(np.union1d)\n+def union1d(ar1, ar2):\n+ ar1 = core.concrete_or_error(asarray, ar1, \"The error arose in union1d()\")\n+ ar2 = core.concrete_or_error(asarray, ar2, \"The error arose in union1d()\")\n+\n+ conc = concatenate((ar1, ar2), axis=None)\n+ return unique(conc)\n+\n+\n@partial(jit, static_argnums=2)\ndef _intersect1d_sorted_mask(ar1, ar2, return_indices=False):\n\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/__init__.py", "new_path": "jax/numpy/__init__.py", "diff": "@@ -60,7 +60,7 @@ from jax._src.numpy.lax_numpy import (\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- unpackbits, unravel_index, unsignedinteger, unwrap, vander, var, vdot, vsplit,\n+ union1d, unpackbits, unravel_index, unsignedinteger, unwrap, vander, var, vdot, vsplit,\nvstack, where, zeros, zeros_like, _NOT_IMPLEMENTED)\nfrom jax._src.numpy.polynomial import roots\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1162,6 +1162,23 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nargs_maker = lambda: [rng(shape1, dtype1), rng(shape2, dtype2)]\nself._CheckAgainstNumpy(np.setdiff1d, jnp.setdiff1d, args_maker)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_{}_{}\".format(\n+ jtu.format_shape_dtype_string(shape1, dtype1),\n+ jtu.format_shape_dtype_string(shape2, dtype2)),\n+ \"shape1\": shape1, \"shape2\": shape2, \"dtype1\": dtype1, \"dtype2\": dtype2}\n+ for dtype1 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for dtype2 in [s for s in default_dtypes if s != jnp.bfloat16]\n+ for shape1 in nonempty_nonscalar_array_shapes\n+ for shape2 in nonempty_nonscalar_array_shapes))\n+ def testUnion1d(self, shape1, shape2, dtype1, dtype2):\n+ rng = jtu.rand_default(self.rng())\n+ args_maker = lambda: [rng(shape1, dtype1), rng(shape2, dtype2)]\n+ def np_fun(arg1, arg2):\n+ dtype = jnp.promote_types(arg1.dtype, arg2.dtype)\n+ return np.union1d(arg1, arg2).astype(dtype)\n+ self._CheckAgainstNumpy(np_fun, jnp.union1d, args_maker)\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_{}_{}_assume_unique={}_return_indices={}\".format(\njtu.format_shape_dtype_string(shape1, dtype1),\n" } ]
Python
Apache License 2.0
google/jax
add support for union1d add union1d in jax.numpy which closely follows numpy implementaion
260,287
04.02.2021 14:53:38
0
0b7febea390932c7d9e728037c5e91dc188f5381
Add argument donation for xmap Also, pass the body to XLA JIT when no parallel resources are used. There is no reason to not do that given that we already require users to pay the price of making their code jittable.
[ { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -28,7 +28,8 @@ from .. import linear_util as lu\nfrom ..api import _check_callable, _check_arg\nfrom ..tree_util import (tree_flatten, tree_unflatten, all_leaves,\n_replace_nones, tree_map, tree_leaves)\n-from ..api_util import flatten_fun_nokwargs, flatten_axes\n+from ..api_util import (flatten_fun_nokwargs, flatten_axes, _ensure_index_tuple,\n+ donation_vector)\nfrom ..interpreters import partial_eval as pe\nfrom ..interpreters import pxla\nfrom ..interpreters import xla\n@@ -112,6 +113,9 @@ class ResourceEnv:\ndef __hash__(self):\nreturn hash(self.physical_mesh)\n+ def __repr__(self):\n+ return f\"ResourceEnv({self.physical_mesh!r})\"\n+\nthread_resources = threading.local()\nthread_resources.env = ResourceEnv(Mesh(np.empty((), dtype=object), ()))\n@@ -243,6 +247,7 @@ def xmap(fun: Callable,\n*,\naxis_sizes: Dict[AxisName, int] = {},\naxis_resources: Dict[AxisName, Union[ResourceAxisName, Tuple[ResourceAxisName, ...]]] = {},\n+ donate_argnums: Union[int, Sequence[int]] = (),\nbackend: Optional[str] = None):\n\"\"\"Assign a positional signature to a program that uses named array axes.\n@@ -445,6 +450,8 @@ def xmap(fun: Callable,\nraise ValueError(f\"Resource assignment of a single axis must be a tuple of \"\nf\"distinct resources, but specified {resources} for axis {axis}\")\n+ donate_argnums = _ensure_index_tuple(donate_argnums)\n+\n# A little performance optimization to avoid iterating over all args unnecessarily\nhas_input_rank_assertions = any(spec.expected_rank is not None for spec in in_axes_entries)\nhas_output_rank_assertions = any(spec.expected_rank is not None for spec in out_axes_entries)\n@@ -463,6 +470,10 @@ def xmap(fun: Callable,\nargs_flat, in_tree = tree_flatten(args)\nfor arg in args_flat: _check_arg(arg)\nfun_flat, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n+ if donate_argnums:\n+ donated_invars = donation_vector(donate_argnums, args, ())\n+ else:\n+ donated_invars = (False,) * len(args_flat)\n# TODO: Check that:\n# - two axes mapped to the same resource never coincide (even inside f)\nin_axes_flat = flatten_axes(\"xmap in_axes\", in_tree, in_axes)\n@@ -487,6 +498,7 @@ def xmap(fun: Callable,\nname=getattr(fun, '__name__', '<unnamed function>'),\nin_axes=tuple(in_axes_flat),\nout_axes_thunk=out_axes_thunk,\n+ donated_invars=donated_invars,\naxis_sizes=frozen_axis_sizes,\naxis_resources=frozen_axis_resources,\nresource_env=resource_env,\n@@ -501,17 +513,17 @@ def xmap(fun: Callable,\nreturn fun_mapped\n-def xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes_thunk, axis_sizes,\n- axis_resources, resource_env, backend):\n+def xmap_impl(fun: lu.WrappedFun, *args, name, in_axes, out_axes_thunk, donated_invars,\n+ axis_sizes, axis_resources, resource_env, backend):\nin_avals = [core.raise_to_shaped(core.get_aval(arg)) for arg in args]\n- return make_xmap_callable(fun, name, in_axes, out_axes_thunk, axis_sizes,\n+ return make_xmap_callable(fun, name, in_axes, out_axes_thunk, donated_invars, axis_sizes,\naxis_resources, resource_env, backend, *in_avals)(*args)\n@lu.cache\ndef make_xmap_callable(fun: lu.WrappedFun,\nname,\n- in_axes, out_axes_thunk, axis_sizes,\n- axis_resources, resource_env, backend,\n+ in_axes, out_axes_thunk, donated_invars,\n+ axis_sizes, axis_resources, resource_env, backend,\n*in_avals):\nplan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\n@@ -539,12 +551,12 @@ def make_xmap_callable(fun: lu.WrappedFun,\nsubmesh,\nmesh_in_axes,\nmesh_out_axes,\n+ donated_invars,\nEXPERIMENTAL_SPMD_LOWERING,\n*in_avals)\nelse:\n- # We have to trace again, because `f` is an lu.WrappedFun, so we can't just return it.\n- final_jaxpr, out_avals, final_consts = pe.trace_to_jaxpr_final(f, in_avals)\n- return core.jaxpr_as_fun(core.ClosedJaxpr(final_jaxpr, final_consts))\n+ return xla._xla_callable(f, None, backend, name, donated_invars,\n+ *((a, None) for a in in_avals))\nclass EvaluationPlan(NamedTuple):\n\"\"\"Encapsulates preprocessing common to top-level xmap invocations and its translation rule.\"\"\"\n@@ -700,8 +712,8 @@ xla.call_translations[xmap_p] = _xmap_translation_rule\ndef _xmap_translation_rule_replica(c, axis_env,\nin_nodes, name_stack, *,\ncall_jaxpr, name,\n- in_axes, out_axes, axis_sizes,\n- axis_resources, resource_env, backend):\n+ in_axes, out_axes, donated_invars,\n+ axis_sizes, axis_resources, resource_env, backend):\nplan = EvaluationPlan.from_axis_resources(axis_resources, resource_env, axis_sizes)\nlocal_mesh = resource_env.physical_mesh.local_mesh\n@@ -806,8 +818,8 @@ def _xla_untile(c, axis_env, x, out_axes, axis_sizes, backend):\ndef _xmap_translation_rule_spmd(c, axis_env,\nin_nodes, name_stack, *,\ncall_jaxpr, name,\n- in_axes, out_axes, axis_sizes,\n- axis_resources, resource_env, backend):\n+ in_axes, out_axes, donated_invars,\n+ axis_sizes, axis_resources, resource_env, backend):\n# TODO(apaszke): This is quite difficult to implement given the current lowering\n# in mesh_tiled_callable. There, we vmap the mapped axes, but we\n# have no idea which positional axes they end up being in this\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -1325,6 +1325,8 @@ class Mesh:\n# TODO: This is pretty expensive to compute. Cache this on the mesh object?\n@property\ndef local_mesh(self):\n+ if not self.devices.ndim:\n+ return self\nhost_id = xb.host_id()\nis_local_device = np.vectorize(lambda d: d.host_id == host_id, otypes=[bool])(self.devices)\nsubcube_indices = []\n@@ -1358,6 +1360,10 @@ class Mesh:\ndef device_ids(self):\nreturn np.vectorize(lambda d: d.id, otypes=[int])(self.devices)\n+ def __repr__(self):\n+ return f\"Mesh({self.devices!r}, {self.axis_names!r})\"\n+\n+\ndef tile_aval_nd(axis_sizes, in_axes: ArrayMapping, aval):\nif aval is core.abstract_unit:\nreturn aval\n@@ -1383,6 +1389,7 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\nmesh: Mesh,\nin_axes: Sequence[ArrayMapping],\nout_axes: Sequence[ArrayMapping],\n+ donated_invars: Sequence[bool],\nspmd_lowering,\n*local_in_untiled_avals):\nassert config.omnistaging_enabled\n@@ -1429,7 +1436,6 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\n# 3. Build up the HLO\nc = xb.make_computation_builder(f\"xmap_{fun.__name__}\")\nxla_consts = map(partial(xb.constant, c), consts)\n- donated_invars = (False,) * len(in_jaxpr_avals) # TODO(apaszke): support donation\ntuple_args = len(in_jaxpr_avals) > 100 # pass long arg lists as tuple for TPU\nin_partitions: Optional[List]\nif spmd_lowering:\n@@ -1465,9 +1471,9 @@ def mesh_tiled_callable(fun: lu.WrappedFun,\nout_tuple = xb.with_sharding_proto(c, out_partitions_t, xops.Tuple, c, out_nodes)\nelse:\nout_tuple = xops.Tuple(c, out_nodes)\n- # TODO(apaszke): Does that work with SPMD sharding?\nif backend.platform in (\"gpu\", \"tpu\"):\n- donated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\n+ xla.set_up_aliases(c, xla_args, out_tuple, donated_invars, tuple_args)\n+ # TODO: Warn about unused donations?\nbuilt = c.Build(out_tuple)\n# 4. Compile the HLO\n" }, { "change_type": "MODIFY", "old_path": "jax/test_util.py", "new_path": "jax/test_util.py", "diff": "@@ -922,6 +922,18 @@ class JaxTestCase(parameterized.TestCase):\ncanonicalize_dtypes=canonicalize_dtypes)\n+class BufferDonationTestCase(JaxTestCase):\n+ assertDeleted = lambda self, x: self._assertDeleted(x, True)\n+ assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n+\n+ def _assertDeleted(self, x, deleted):\n+ if hasattr(x, \"device_buffer\"):\n+ self.assertEqual(x.device_buffer.is_deleted(), deleted)\n+ else:\n+ for buffer in x.device_buffers:\n+ self.assertEqual(buffer.is_deleted(), deleted)\n+\n+\n@contextmanager\ndef ignore_warning(**kw):\nwith warnings.catch_warnings():\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -50,7 +50,7 @@ config.parse_flags_with_absl()\nFLAGS = config.FLAGS\n-class CPPJitTest(jtu.JaxTestCase):\n+class CPPJitTest(jtu.BufferDonationTestCase):\n\"\"\"Shared tests between the Python and the C++ jax,jit implementations.\nBecause the Python implementation supports more features, we need to have the\n@@ -208,15 +208,6 @@ class CPPJitTest(jtu.JaxTestCase):\nself.assertEqual(f(list(range(500))), sum(range(500)))\n# Jit and Donate arguments\n- assertDeleted = lambda self, x: self._assertDeleted(x, True)\n- assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n-\n- def _assertDeleted(self, x, deleted):\n- if hasattr(x, \"device_buffer\"):\n- self.assertEqual(x.device_buffer.is_deleted(), deleted)\n- else:\n- for buffer in x.device_buffers:\n- self.assertEqual(buffer.is_deleted(), deleted)\ndef test_jit_donate_argnums_warning_raised(self):\nx = jnp.array([1.0, 2.0], jnp.float32)\n@@ -4934,7 +4925,7 @@ class DeprecatedCustomTransformsTest(jtu.JaxTestCase):\nprint(gf(a, b)) # doesn't crash\n-class BufferDonationTest(jtu.JaxTestCase):\n+class BufferDonationTest(jtu.BufferDonationTestCase):\n@jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\ndef test_pmap_donate_argnums_invalidates_input(self):\n@@ -4955,16 +4946,6 @@ class BufferDonationTest(jtu.JaxTestCase):\npmap_fun(a) # doesn't crash\n- assertDeleted = lambda self, x: self._assertDeleted(x, True)\n- assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n-\n- def _assertDeleted(self, x, deleted):\n- if hasattr(x, \"device_buffer\"):\n- self.assertEqual(x.device_buffer.is_deleted(), deleted)\n- else:\n- for buffer in x.device_buffers:\n- self.assertEqual(buffer.is_deleted(), deleted)\n-\nclass NamedCallTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -207,7 +207,7 @@ def schedules(sizes: Dict[str, int]\nyield axis_resources, mesh_data\n-class XMapTest(jtu.JaxTestCase):\n+class XMapTest(jtu.BufferDonationTestCase):\ndef setUp(self):\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n@@ -376,6 +376,31 @@ class XMapTest(jtu.JaxTestCase):\nfor i in range(10):\nself.assertAllClose(f_mapped(x, x), expected)\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n+ for name, mesh, axis_resources in (\n+ ('', (), ()),\n+ ('Mesh', (('x', 2),), (('i', 'x'),))\n+ ))\n+ @with_mesh_from_kwargs\n+ @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n+ @ignore_xmap_warning()\n+ def testBufferDonation(self, mesh, axis_resources):\n+ shard = lambda x: x\n+ if axis_resources:\n+ shard = xmap(lambda x: x, in_axes=['i', ...], out_axes=['i', ...],\n+ axis_resources=dict(axis_resources))\n+ f = xmap(lambda x, y: x + y * 4,\n+ in_axes=['i', ...], out_axes=['i', ...],\n+ axis_resources=dict(axis_resources),\n+ donate_argnums=0)\n+ # The multiplications below disable some optimizations that prevent reuse\n+ x = shard(jnp.zeros((2, 5)) * 4)\n+ y = shard(jnp.ones((2, 5)) * 2)\n+ f(x, y)\n+ self.assertNotDeleted(y)\n+ self.assertDeleted(x)\n+\n@parameterized.named_parameters(\n{\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\nfor name, mesh, axis_resources in (\n@@ -480,6 +505,7 @@ class XMapTestSPMD(XMapTest):\nskipped_tests = {\n\"NestedMesh\", # Nesting xmap calls is not supported in the SPMD lowering yet\n+ \"NestedMap\", # Same as above\n\"CollectivePermute2D\" # vmap of multidimensional permute not implemented yet\n}\n" } ]
Python
Apache License 2.0
google/jax
Add argument donation for xmap Also, pass the body to XLA JIT when no parallel resources are used. There is no reason to not do that given that we already require users to pay the price of making their code jittable.
260,287
08.02.2021 12:18:33
0
692e31c92401aaf65c546612db32f11a483ab0ea
Small cleanup of xmap tests
[ { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -89,6 +89,14 @@ def with_mesh(named_shape: MeshSpec) -> Generator[None, None, None]:\ndef with_mesh_from_kwargs(f):\nreturn lambda *args, **kwargs: with_mesh(kwargs['mesh'])(f)(*args, **kwargs)\n+def with_and_without_mesh(f):\n+ return parameterized.named_parameters(\n+ {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n+ for name, mesh, axis_resources in (\n+ ('', (), ()),\n+ ('Mesh', (('x', 2),), (('i', 'x'),))\n+ ))(with_mesh_from_kwargs(f))\n+\n# -------------------- Itertools helpers --------------------\n@@ -207,10 +215,31 @@ def schedules(sizes: Dict[str, int]\nyield axis_resources, mesh_data\n-class XMapTest(jtu.BufferDonationTestCase):\n+class XMapTestCase(jtu.BufferDonationTestCase):\ndef setUp(self):\n+ if jax.lib.version < (0, 1, 58):\n+ raise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\nif not config.omnistaging_enabled:\nraise SkipTest(\"xmap requires omnistaging\")\n+ super().setUp()\n+\n+\n+# A mixin that enables SPMD lowering tests\n+class SPMDTestMixin:\n+ def setUp(self):\n+ if jtu.device_under_test() != \"tpu\":\n+ raise SkipTest\n+ super().setUp()\n+ jax.experimental.maps.make_xmap_callable.cache_clear()\n+ self.old_lowering_flag = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = True\n+\n+ def tearDown(self):\n+ jax.experimental.maps.make_xmap_callable.cache_clear()\n+ jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = self.old_lowering_flag\n+\n+\n+class XMapTest(XMapTestCase):\n@ignore_xmap_warning()\ndef testBasic(self):\n@@ -354,13 +383,7 @@ class XMapTest(jtu.BufferDonationTestCase):\nself.assertEqual(y[0].sharding_spec.mesh_mapping,\n(pxla.Replicated(2), pxla.ShardedAxis(0)) + (pxla.Replicated(2),) * (len(mesh) - 2))\n- @parameterized.named_parameters(\n- {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n- for name, mesh, axis_resources in (\n- ('', (), ()),\n- ('Mesh', (('x', 2),), (('i', 'x'),))\n- ))\n- @with_mesh_from_kwargs\n+ @with_and_without_mesh\n@ignore_xmap_warning()\ndef testMultipleCalls(self, mesh, axis_resources):\ndef f(x, y):\n@@ -376,13 +399,7 @@ class XMapTest(jtu.BufferDonationTestCase):\nfor i in range(10):\nself.assertAllClose(f_mapped(x, x), expected)\n- @parameterized.named_parameters(\n- {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n- for name, mesh, axis_resources in (\n- ('', (), ()),\n- ('Mesh', (('x', 2),), (('i', 'x'),))\n- ))\n- @with_mesh_from_kwargs\n+ @with_and_without_mesh\n@jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n@ignore_xmap_warning()\ndef testBufferDonation(self, mesh, axis_resources):\n@@ -401,13 +418,7 @@ class XMapTest(jtu.BufferDonationTestCase):\nself.assertNotDeleted(y)\nself.assertDeleted(x)\n- @parameterized.named_parameters(\n- {\"testcase_name\": name, \"mesh\": mesh, \"axis_resources\": axis_resources}\n- for name, mesh, axis_resources in (\n- ('', (), ()),\n- ('Mesh', (('x', 2),), (('i', 'x'),))\n- ))\n- @with_mesh_from_kwargs\n+ @with_and_without_mesh\n@ignore_xmap_warning()\ndef testAxisSizes(self, mesh, axis_resources):\nresult = xmap(lambda: lax.axis_index('i'),\n@@ -500,8 +511,8 @@ class XMapTest(jtu.BufferDonationTestCase):\nself.assertAllClose(fm(x, y), fref(x, y))\n-class XMapTestSPMD(XMapTest):\n- \"\"\"Re-executes all tests with the SPMD partitioner enabled\"\"\"\n+class XMapTestSPMD(SPMDTestMixin, XMapTest):\n+ \"\"\"Re-executes all basic tests with the SPMD partitioner enabled\"\"\"\nskipped_tests = {\n\"NestedMesh\", # Nesting xmap calls is not supported in the SPMD lowering yet\n@@ -510,25 +521,13 @@ class XMapTestSPMD(XMapTest):\n}\ndef setUp(self):\n- super().setUp()\n- if jtu.device_under_test() != \"tpu\":\n- raise SkipTest\nfor skipped_name in self.skipped_tests:\nif skipped_name in self._testMethodName:\nraise SkipTest\n- jax.experimental.maps.make_xmap_callable.cache_clear()\n- self.old_lowering_flag = jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING\n- jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = True\n-\n- def tearDown(self):\n- jax.experimental.maps.make_xmap_callable.cache_clear()\n- jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING = self.old_lowering_flag\n+ super().setUp()\n-class NamedNumPyTest(jtu.JaxTestCase):\n- def setUp(self):\n- if not config.omnistaging_enabled:\n- raise SkipTest(\"xmap requires omnistaging\")\n+class NamedNumPyTest(XMapTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": f\"_{reduction.__name__}_axes={axes}_i={mapped_axis}\",\n@@ -554,12 +553,7 @@ class NamedNumPyTest(jtu.JaxTestCase):\nself.assertAllClose(ref_red(x), xmap_red(x))\n-class NamedRandomTest(jtu.JaxTestCase):\n- def setUp(self):\n- if jax.lib.version < (0, 1, 58):\n- raise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\n- if not config.omnistaging_enabled:\n- raise SkipTest(\"xmap requires omnistaging\")\n+class NamedRandomTest(XMapTestCase):\n@curry\ndef parameterize_by_sampler(extra, f, subset):\n@@ -606,12 +600,7 @@ class NamedRandomTest(jtu.JaxTestCase):\nself.assertAllClose(sample({}), sample(dict(axis_resources)))\n-class NamedNNTest(jtu.JaxTestCase):\n- def setUp(self):\n- if jax.lib.version < (0, 1, 58):\n- raise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\n- if not config.omnistaging_enabled:\n- raise SkipTest(\"xmap requires omnistaging\")\n+class NamedNNTest(XMapTestCase):\n@ignore_xmap_warning()\ndef testOneHot(self):\n@@ -768,12 +757,7 @@ def schedules_from_pdot_spec(\nyield from schedules(logical_sizes)\n-class PDotTests(jtu.JaxTestCase):\n-\n- def setUp(self):\n- if not config.omnistaging_enabled:\n- raise SkipTest(\"xmap requires omnistaging\")\n- super().setUp()\n+class PDotTests(XMapTestCase):\n@ignore_xmap_warning()\n@with_mesh([('r1', 2)])\n" } ]
Python
Apache License 2.0
google/jax
Small cleanup of xmap tests
260,287
05.02.2021 11:34:32
0
6965e8bbe3f2f2682fe0b3966ae5b85487256e0c
Add support for named axes in jnp.mean and jnp.std
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -26,6 +26,7 @@ rules for the underlying :code:`lax` primitives.\nimport builtins\nimport collections\n+import collections.abc\nimport operator\nimport os\nimport types\n@@ -50,7 +51,7 @@ from jax import lax\nfrom jax._src.lax.lax import _device_put_raw\nfrom jax import ops\nfrom jax._src.util import (partial, unzip2, prod as _prod, subvals, safe_zip,\n- canonicalize_axis as _canonicalize_axis)\n+ canonicalize_axis as _canonicalize_axis, maybe_named_axis)\nfrom jax.tree_util import tree_leaves, tree_flatten, tree_map\nFLAGS = flags.FLAGS\n@@ -1915,10 +1916,7 @@ def _reduction(a, name, np_fun, op, init_val, has_identity=True,\nreturn lax.convert_element_type(result, dtype or result_dtype)\ndef _canonicalize_axis_allow_named(x, rank):\n- try:\n- return _canonicalize_axis(x, rank)\n- except TypeError:\n- return x\n+ return maybe_named_axis(x, lambda i: _canonicalize_axis(i, rank), lambda name: name)\ndef _reduction_dims(a, axis):\nif axis is None:\n@@ -1995,6 +1993,15 @@ amax = max\nalltrue = all\nsometrue = any\n+def _axis_size(a, axis):\n+ if not isinstance(axis, collections.abc.Sequence):\n+ axis = (axis,)\n+ size = 1\n+ a_shape = shape(a)\n+ for a in axis:\n+ size *= maybe_named_axis(a, lambda i: a_shape[i], lambda name: lax.psum(1, name))\n+ return size\n+\n@_wraps(np.mean)\ndef mean(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\nout=None, keepdims=False):\n@@ -2006,7 +2013,7 @@ def mean(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\nif axis is None:\nnormalizer = size(a)\nelse:\n- normalizer = np.prod(np.take(shape(a), axis)) # type: ignore\n+ normalizer = _axis_size(a, axis)\nif dtype is None:\nif issubdtype(_dtype(a), bool_) or issubdtype(_dtype(a), integer):\ndtype = float_\n@@ -2087,7 +2094,7 @@ def var(a, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype=None,\nif axis is None:\nnormalizer = size(a)\nelse:\n- normalizer = np.prod(np.take(shape(a), axis)) # type: ignore\n+ normalizer = _axis_size(a, axis)\nnormalizer = normalizer - ddof\nresult = sum(centered, axis, keepdims=keepdims)\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -371,3 +371,11 @@ class HashableFunction:\ndef as_hashable_function(closure):\nreturn lambda f: HashableFunction(f, closure)\n+\n+def maybe_named_axis(axis, if_pos, if_named):\n+ try:\n+ pos = operator.index(axis)\n+ named = False\n+ except TypeError:\n+ named = True\n+ return if_named(axis) if named else if_pos(pos)\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -533,7 +533,8 @@ class NamedNumPyTest(jtu.JaxTestCase):\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": f\"_{reduction.__name__}_axes={axes}_i={mapped_axis}\",\n\"reduction\": reduction, \"axes\": axes, \"mapped_axis\": mapped_axis}\n- for reduction in (jnp.sum, jnp.max, jnp.min, jscipy.special.logsumexp)\n+ for reduction in (jnp.sum, jnp.max, jnp.min, jnp.mean, jnp.var, jnp.std,\n+ jscipy.special.logsumexp)\nfor axes in (0, 'i', (1,), ('i',), (0, 1), (0, 'i'), ('i', 0))\nfor mapped_axis in range(3)))\n@ignore_xmap_warning()\n" } ]
Python
Apache License 2.0
google/jax
Add support for named axes in jnp.mean and jnp.std
260,287
08.02.2021 20:09:33
0
b19dd8758198e51c85b31c0c0d11ca674c30b391
Add a pgather primitive, making it possible to index into mapped axes
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -18,6 +18,7 @@ Parallelization primitives.\nimport collections\nimport string\nimport warnings\n+from typing import Union\nimport numpy as np\n@@ -26,13 +27,13 @@ from jax import dtypes\nfrom jax import tree_util\nfrom jax._src import source_info_util\nfrom . import lax\n-from jax.core import ShapedArray, raise_to_shaped\n+from jax.core import ShapedArray, AxisName, raise_to_shaped\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import batching\nfrom jax.interpreters import partial_eval as pe\n-from jax._src.util import partial, unzip2, prod, canonicalize_axis, safe_map\n+from jax._src.util import partial, unzip2, prod, canonicalize_axis, safe_map, moveaxis\nfrom jax.lib import xla_client as xc\nfrom jax.lib import xla_bridge as xb\nfrom jax.config import config\n@@ -490,6 +491,14 @@ class XeinsumSpecParser:\nreturn arg_specs\n+def pgather(src, idx, axes: Union[int, AxisName]):\n+ \"\"\"Uses the last positional axis of idx to index into src's axes.\"\"\"\n+ if not isinstance(axes, (tuple, list)):\n+ axes = (axes,)\n+ # TODO: Canonicalize exes!\n+ return pgather_p.bind(src, idx, axes=tuple(axes))\n+\n+\n### parallel primitives\ndef _subst_all_names_in_param(\n@@ -530,8 +539,6 @@ def _reduction_with_positional_batcher(prim, vals_in, dims_in, axis_index_groups\nassert all(v is not None for v in vals_out)\nreturn vals_out\n-# This is only used for collectives that do not include the vmapped axis name,\n-# which is why the rule is so simple.\ndef _reduction_batcher(prim, vals_in, dims_in, *, axes, axis_index_groups):\nif not any(isinstance(axis, int) for axis in axes):\nreturn prim.bind(*vals_in, axes=axes, axis_index_groups=axis_index_groups), dims_in\n@@ -1164,6 +1171,84 @@ ad.defbilinear(pdot_p, _pdot_transpose_lhs, _pdot_transpose_rhs)\npxla.multi_host_supported_collectives.add(pdot_p)\n+def _pgather_impl(src, idx, *, axes):\n+ assert all(isinstance(axis, int) for axis in axes)\n+ src_axes_front = moveaxis(src, axes, range(len(axes)))\n+ non_axes_shape = src_axes_front.shape[len(axes):]\n+ src_one_axis_front = src_axes_front.reshape((-1,) + non_axes_shape)\n+ slice_sizes = (1,) + non_axes_shape\n+ idx = lax.reshape(idx, idx.shape + (1,))\n+ offset_dims = tuple(range(idx.ndim - 1, idx.ndim + src_one_axis_front.ndim - 2))\n+ dnums = lax.GatherDimensionNumbers(\n+ offset_dims=offset_dims,\n+ collapsed_slice_dims=(0,),\n+ start_index_map=(0,))\n+ return lax.gather(src_one_axis_front, idx, dimension_numbers=dnums,\n+ slice_sizes=tuple(slice_sizes))\n+\n+def _pgather_abstract_eval(src, idx, *, axes):\n+ # TODO: Avals with names rule: remove all axes from src, insert those from idx\n+ # The order is important, because it is ok to re-insert one of the deleted axes!\n+ shape = list(src.shape)\n+ for axis in sorted((a for a in axes if isinstance(a, int)), reverse=True):\n+ del shape[axis]\n+ shape = idx.shape + tuple(shape)\n+ return ShapedArray(shape, src.dtype)\n+\n+def _pgather_parallel_translation(c, src, idx, *, axes, axis_env, platform):\n+ if any(not isinstance(axis, int) for axis in axes):\n+ raise NotImplementedError(\"pgather only supported in the SPMD lowering.\"\n+ \"Please open a feature request!\")\n+ return xla.lower_fun(_pgather_impl, multiple_results=False)(c, src, idx, axes=axes)\n+\n+def _pgather_batcher(vals_in, dims_in, *, axes):\n+ src, idx = vals_in\n+ dsrc, didx = dims_in\n+ if didx is not batching.not_mapped and dsrc is not batching.not_mapped:\n+ # NB: We could just go forward with it and take the diagonal along the\n+ # two axes we get in the output, but that would be quite inefficient\n+ raise NotImplementedError(\"Please open a feature request!\")\n+ elif didx is not batching.not_mapped:\n+ return pgather_p.bind(src, idx, axes=axes), didx\n+ elif dsrc is not batching.not_mapped:\n+ src_last_batched = moveaxis(src, dsrc, -1)\n+ result = pgather_p.bind(src_last_batched, idx, axes=axes)\n+ return result, result.ndim - 1\n+ else:\n+ assert False # This shouldn't get called anyway\n+\n+def _pgather_collective_batcher(frame, vals_in, dims_in, *, axes):\n+ src, idx = vals_in\n+ dsrc, didx = dims_in\n+ if dsrc is batching.not_mapped:\n+ raise ValueError(\"pgather axis {frame.name} is missing from the indexed value\")\n+ if didx is not batching.not_mapped:\n+ # NOTE: This is allowed and the output would be mapped along this axis!\n+ raise NotImplementedError(\"Please open a feature request!\")\n+ # Now source is mapped, idx is not\n+ new_axes = tuple(dsrc if axis == frame.name else\n+ axis + (dsrc <= axis) if isinstance(axis, int) else\n+ axis\n+ for axis in axes)\n+ # The result is not mapped, because we eliminate all axes, and those include\n+ # the batched axis.\n+ if all(isinstance(axis, int) for axis in axes):\n+ # We rewrite a purely positional pgather as a gather, because that one\n+ # is more fully featured (e.g. supports AD).\n+ return _pgather_impl(src, idx, axes=new_axes), batching.not_mapped\n+ else:\n+ return pgather_p.bind(src, idx, axes=new_axes), batching.not_mapped\n+\n+pgather_p = core.Primitive('pgather')\n+pgather_p.def_impl(_pgather_impl)\n+pgather_p.def_abstract_eval(_pgather_abstract_eval)\n+xla.parallel_translations[pgather_p] = _pgather_parallel_translation\n+# TODO: Transpose? That requires adding pscatter...\n+batching.primitive_batchers[pgather_p] = _pgather_batcher\n+batching.collective_rules[pgather_p] = _pgather_collective_batcher\n+core.axis_substitution_rules[pgather_p] = partial(_subst_all_names_in_param, 'axes')\n+\n+\n@config.register_omnistaging_disabler\ndef omnistaging_disabler() -> None:\nglobal axis_index\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/util.py", "new_path": "jax/_src/util.py", "diff": "@@ -284,10 +284,15 @@ def canonicalize_axis(axis, num_dims) -> int:\ndef moveaxis(x, src, dst):\nif src == dst:\nreturn x\n- src = canonicalize_axis(src, x.ndim)\n- dst = canonicalize_axis(dst, x.ndim)\n- perm = [i for i in range(np.ndim(x)) if i != src]\n- perm.insert(dst, src)\n+ if isinstance(src, int):\n+ src = (src,)\n+ if isinstance(dst, int):\n+ dst = (dst,)\n+ src = [canonicalize_axis(a, x.ndim) for a in src]\n+ dst = [canonicalize_axis(a, x.ndim) for a in dst]\n+ perm = [i for i in range(np.ndim(x)) if i not in src]\n+ for d, s in sorted(zip(dst, src)):\n+ perm.insert(d, s)\nreturn x.transpose(perm)\ndef ceil_of_ratio(x, y):\n@@ -320,6 +325,10 @@ def tuple_delete(t, idx):\nassert 0 <= idx < len(t), (idx, len(t))\nreturn t[:idx] + t[idx + 1:]\n+def tuple_replace(t, idx, val):\n+ assert 0 <= idx < len(t), (idx, len(t))\n+ return t[:idx] + (val,) + t[idx:]\n+\n# TODO(mattjj): replace with dataclass when Python 2 support is removed\ndef taggedtuple(name, fields) -> Callable[..., Any]:\n\"\"\"Lightweight version of namedtuple where equality depends on the type.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/jax2tf.py", "new_path": "jax/experimental/jax2tf/jax2tf.py", "diff": "@@ -838,7 +838,7 @@ tf_not_yet_impl = [\n# Not high priority?\n\"after_all\", \"all_to_all\", \"create_token\",\n\"infeed\", \"outfeed\", \"pmax_p\",\n- \"pmin\", \"ppermute\", \"psum\", \"pmax\",\n+ \"pmin\", \"ppermute\", \"psum\", \"pmax\", \"pgather\",\n\"axis_index\", \"pdot\", \"all_gather\",\n\"xla_pmap\",\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -40,6 +40,7 @@ from jax.experimental.maps import Mesh, mesh, xmap\nfrom jax.lib import xla_bridge\nfrom jax._src.util import curry, unzip2, split_list, prod\nfrom jax._src.lax.lax import DotDimensionNumbers\n+from jax._src.lax.parallel import pgather\nfrom jax.interpreters import pxla\nfrom jax.config import config\n@@ -658,6 +659,40 @@ class NamedNNTest(XMapTestCase):\natol=1e-4, rtol=2e-2)\n+class NewPrimitiveTest(XMapTestCase):\n+ def setUp(self):\n+ if jax.lib.version < (0, 1, 58):\n+ raise SkipTest(\"xmap requires jaxlib version >= 0.1.58\")\n+ if not config.omnistaging_enabled:\n+ raise SkipTest(\"xmap requires omnistaging\")\n+\n+ def testGatherPositional(self):\n+ x = jnp.arange(27).reshape((9, 3))\n+ idx = jnp.array([1, 2, 1, 0]).reshape((2, 2))\n+ self.assertAllClose(pgather(x, idx, 0), x[idx.ravel()].reshape((2, 2, 3)))\n+\n+ x_explode = x.reshape((3, 3, 3))\n+ self.assertAllClose(pgather(x, idx, 0), pgather(x_explode, idx, (0, 1)))\n+\n+ @with_and_without_mesh\n+ @ignore_xmap_warning()\n+ def testGather(self, mesh, axis_resources):\n+ if axis_resources and not jax.experimental.maps.EXPERIMENTAL_SPMD_LOWERING:\n+ raise SkipTest(\"pgather over mesh axes without SPMD lowering not implemented\")\n+ x = jnp.arange(12, dtype=np.float32).reshape((4, 3))\n+ y = jnp.arange(35).reshape((5, 7)) % 3\n+ f = xmap(lambda src, idx: pgather(src, idx, 'j'),\n+ in_axes=(['i', 'j'], ['k', 'm']),\n+ out_axes=['i', 'k', 'm'],\n+ axis_resources=dict(axis_resources))\n+ f_ref = lambda x, y: x[:, y.reshape((-1,))].reshape((4, 5, 7))\n+ self.assertAllClose(f(x, y), f_ref(x, y))\n+\n+\n+class NewPrimitiveTestSPMD(SPMDTestMixin, NewPrimitiveTest):\n+ pass\n+\n+\nAxisIndices = Tuple[int, ...]\nMatchedAxisIndices = Tuple[AxisIndices, AxisIndices]\nAxisNames = Tuple[str, ...]\n" } ]
Python
Apache License 2.0
google/jax
Add a pgather primitive, making it possible to index into mapped axes
260,335
09.02.2021 11:19:09
28,800
7394048782ed574f2fc6c21ff7d1aec683cb5f1e
make jax.eval_shape duck typing more robust
[ { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -2318,8 +2318,14 @@ def eval_shape(fun: Callable, *args, **kwargs):\n>>> print(out.dtype)\nfloat32\n\"\"\"\n+ def dtype(x):\n+ try:\n+ return dtypes.result_type(x)\n+ except ValueError:\n+ return dtypes.result_type(getattr(x, 'dtype'))\n+\ndef abstractify(x):\n- return ShapedArray(np.shape(x), dtypes.result_type(x))\n+ return ShapedArray(np.shape(x), dtype(x))\nargs_flat, in_tree = tree_flatten((args, kwargs))\nwrapped_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\nout = pe.abstract_eval_fun(wrapped_fun.call_wrapped,\n" }, { "change_type": "MODIFY", "old_path": "jax/dtypes.py", "new_path": "jax/dtypes.py", "diff": "@@ -324,7 +324,9 @@ def dtype(x):\ndef result_type(*args):\n\"\"\"Convenience function to apply Numpy argument dtype promotion.\"\"\"\n# TODO(jakevdp): propagate weak_type to the result.\n- if len(args) < 2:\n+ if len(args) == 0:\n+ raise ValueError(\"at least one array or dtype is required\")\n+ if len(args) == 1:\nreturn canonicalize_dtype(dtype(args[0]))\n# TODO(jakevdp): propagate weak_type to the result when necessary.\nreturn canonicalize_dtype(_least_upper_bound(*{_jax_type(arg) for arg in args}))\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1222,6 +1222,17 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(out_shape.shape, (3, 5))\n+ def test_eval_shape_duck_typing2(self):\n+ # https://github.com/google/jax/issues/5683\n+ class EasyDict(dict):\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+ self.__dict__ = self\n+\n+ x = EasyDict(shape=(3,), dtype=np.dtype('float32'))\n+ out_shape = api.eval_shape(lambda x: x, x) # doesn't crash\n+ self.assertEqual(out_shape.shape, (3,))\n+\ndef test_issue_871(self):\nT = jnp.array([[1., 2.], [3., 4.], [5., 6.]])\nx = jnp.array([1, 2, 3])\n" } ]
Python
Apache License 2.0
google/jax
make jax.eval_shape duck typing more robust
260,335
08.02.2021 20:24:19
28,800
ffb3873e5aaf759a984eb54b6c0adc7b53884a50
add pargmax, pargmin wrappers
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -180,6 +180,23 @@ def pmin(x, axis_name, *, axis_index_groups=None):\naxis_index_groups=axis_index_groups)\nreturn tree_util.tree_unflatten(treedef, out_flat)\n+# TODO(mattjj): add a pargmin_p, or add named axis support to lax.argmin_p\n+def pargmin(x, axis_name):\n+ if isinstance(axis_name, (tuple, list)):\n+ raise TypeError(f\"pargmin only accepts a single axis, got {axis_name}\")\n+ return _axis_index_of_val(x, pmin(x, axis_name), axis_name)\n+\n+# TODO(mattjj): add a pargmax_p, or add named axis support to lax.argmax_p\n+def pargmax(x, axis_name):\n+ if isinstance(axis_name, (tuple, list)):\n+ raise TypeError(f\"pargmin only accepts a single axis, got {axis_name}\")\n+ return _axis_index_of_val(x, pmax(x, axis_name), axis_name)\n+\n+def _axis_index_of_val(x, val, axis_name):\n+ idx = axis_index(axis_name)\n+ validx = lax_numpy.where(val == x, idx, dtypes.iinfo(dtypes.dtype(idx)).max)\n+ return pmin(validx, axis_name)\n+\ndef _validate_axis_index_groups(axis_index_groups):\nif axis_index_groups is None:\nreturn\n" }, { "change_type": "MODIFY", "old_path": "tests/batching_test.py", "new_path": "tests/batching_test.py", "diff": "@@ -24,6 +24,7 @@ import jax.numpy as jnp\nfrom jax.interpreters import batching\nfrom jax import test_util as jtu\nfrom jax import lax\n+from jax._src.lax import parallel\nfrom jax import random\nfrom jax.api import jit, grad, jvp, vjp, make_jaxpr, jacfwd, jacrev, hessian\nfrom jax.api import vmap\n@@ -1222,5 +1223,27 @@ class BatchingTest(jtu.JaxTestCase):\nself.assertAllClose(a, jnp.ones(shape=(5, 3), dtype=x.dtype))\nself.assertAllClose(b, jnp.ones(shape=(5,), dtype=b.dtype))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_shape={}_axis={}_collective={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ axis, collective.__name__.replace(\" \", \"\")),\n+ \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n+ \"collective\": collective, \"bulk_op\": bulk_op}\n+ for collective, bulk_op in [(parallel.pargmax, jnp.argmax),\n+ (parallel.pargmin, jnp.argmin)]\n+ for dtype in [np.float32, np.int32]\n+ for shape in [(7,), (5, 8)]\n+ for axis in range(len(shape))\n+ )\n+ @skipIf(not jax.config.omnistaging_enabled,\n+ \"vmap collectives only supported when omnistaging is enabled\")\n+ def testArgAllReduce(self, shape, dtype, axis, collective, bulk_op):\n+ rng = jtu.rand_default(self.rng())\n+ x = rng(shape, dtype)\n+ ans = vmap(lambda x: collective(x, 'i'), in_axes=axis, out_axes=None,\n+ axis_name='i')(x)\n+ expected = bulk_op(x, axis=axis)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" }, { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -33,6 +33,7 @@ import jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax import lax\n+from jax._src.lax import parallel\nfrom jax import random\nfrom jax.core import ShapedArray\nfrom jax import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\n@@ -1653,6 +1654,29 @@ class PmapTest(jtu.JaxTestCase):\nz = pmap(f, axis_name='i', out_axes=None)(x, y)\nself.assertAllClose(z, jnp.dot(x.T, y))\n+ @parameterized.named_parameters(\n+ {\"testcase_name\": \"_shape={}_axis={}_collective={}\".format(\n+ jtu.format_shape_dtype_string(shape, dtype),\n+ axis, collective.__name__.replace(\" \", \"\")),\n+ \"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n+ \"collective\": collective, \"bulk_op\": bulk_op}\n+ for collective, bulk_op in [(parallel.pargmax, jnp.argmax),\n+ (parallel.pargmin, jnp.argmin)]\n+ for dtype in [np.float32, np.int32]\n+ for shape in [(4,), (4, 2)]\n+ for axis in range(len(shape))\n+ )\n+ def testArgAllReduce(self, shape, dtype, axis, collective, bulk_op):\n+ if not config.omnistaging_enabled:\n+ self.skipTest(\"test requires omnistaging\")\n+\n+ rng = jtu.rand_default(self.rng())\n+ x = rng(shape, dtype)\n+ ans = pmap(lambda x: collective(x, 'i'), in_axes=axis, out_axes=None,\n+ axis_name='i')(x)\n+ expected = bulk_op(x, axis=axis)\n+ self.assertAllClose(ans, expected, check_dtypes=False)\n+\nclass VmapOfPmapTest(jtu.JaxTestCase):\n" } ]
Python
Apache License 2.0
google/jax
add pargmax, pargmin wrappers
260,287
09.02.2021 17:01:26
0
926b2ad03f65736cc52a409b26cc7dbe7117b23a
Minor fixes for xmap docstring, xeinsum parser The regression loss example from the xmap docstring was broken and the xeinsum parser didn't accept empty parens while it should.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -451,8 +451,8 @@ class XeinsumSpecParser:\naxis_name = self.spec[self.pos:end]\nassert axis_name\n- self.pos = end + 1\n- return axis_name, self.spec[end] == ','\n+ self.pos = end\n+ return axis_name\ndef maybe_take(self, char: str, on_eof: bool = False):\nif self.eof:\n@@ -474,10 +474,15 @@ class XeinsumSpecParser:\nreturn True, (subscripts, names)\nelse:\nassert self.maybe_take('{')\n- while True:\n- axis_name, cont = self.parse_axis_name()\n+ first = True\n+ while not self.maybe_take('}'):\n+ if not first:\n+ assert self.maybe_take(',')\n+ first = False\n+ if self.eof:\n+ raise ValueError(\"Unterminated named axis brace\")\n+ axis_name = self.parse_axis_name()\nnames.append(axis_name)\n- if not cont: break\nreturn self.maybe_take(',', False), (subscripts, names)\ndef parse_args(self):\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -1994,7 +1994,7 @@ alltrue = all\nsometrue = any\ndef _axis_size(a, axis):\n- if not isinstance(axis, collections.abc.Sequence):\n+ if not isinstance(axis, (tuple, list)):\naxis = (axis,)\nsize = 1\na_shape = shape(a)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/maps.py", "new_path": "jax/experimental/maps.py", "diff": "@@ -367,15 +367,15 @@ def xmap(fun: Callable,\nwhile named axes are just a convenient way to achieve batching. While this\nmight seem like a silly example at first, it might turn out to be useful in\npractice, since with conjuction with ``axis_resources`` this makes it possible\n- to implement a distributed matrix-multiplication in just a few lines of code:\n+ to implement a distributed matrix-multiplication in just a few lines of code::\n- >>> devices = np.array(jax.devices())[:4].reshape((2, 2))\n- >>> with mesh(devices, ('x', 'y')): # declare a 2D mesh with axes 'x' and 'y'\n- ... distributed_out = xmap(\n- ... jnp.vdot,\n- ... in_axes=({0: 'left', 1: 'right'}),\n- ... out_axes=['left', 'right', ...],\n- ... axis_resources={'left': 'x', 'right': 'y'})(x, x.T)\n+ devices = np.array(jax.devices())[:4].reshape((2, 2))\n+ with mesh(devices, ('x', 'y')): # declare a 2D mesh with axes 'x' and 'y'\n+ distributed_out = xmap(\n+ jnp.vdot,\n+ in_axes=({0: 'left'}, {1: 'right'}),\n+ out_axes=['left', 'right', ...],\n+ axis_resources={'left': 'x', 'right': 'y'})(x, x.T)\nStill, the above examples are quite simple. After all, the xmapped\ncomputation was a simple NumPy function that didn't use the axis names at all!\n@@ -384,8 +384,9 @@ def xmap(fun: Callable,\ndef regression_loss(x, y, w, b):\n# Contract over in_features. Batch and out_features are present in\n# both inputs and output, so they don't need to be mentioned\n- y_pred = jnp.einsum('{in_features},{in_features}->{}') + b\n- return jnp.mean((y - y_pred) ** 2, axis='batch')\n+ y_pred = jnp.einsum('{in_features},{in_features}->{}', x, w) + b\n+ error = jnp.sum((y - y_pred) ** 2, axis='out_features')\n+ return jnp.mean(error, axis='batch')\nxmap(regression_loss,\nin_axes=(['batch', 'in_features', ...],\n" }, { "change_type": "MODIFY", "old_path": "tests/xmap_test.py", "new_path": "tests/xmap_test.py", "diff": "@@ -964,22 +964,19 @@ class PDotTests(XMapTestCase):\nx = rng.randn(3, 4)\ny = rng.randn(4, 5)\n- out = xmap(partial(jnp.einsum, '{i,j},{j,k}->{i,k}'),\n- in_axes=(['i', 'j'], ['j', 'k']),\n- out_axes=['i', 'k'])(x, y)\n- expected = np.einsum('ij,jk->ik', x, y)\n- tol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\n- self.assertAllClose(out, expected, check_dtypes=True,\n- atol=tol, rtol=tol)\n-\n- # order of named axes in the spec doesn't matter!\n- out = xmap(partial(jnp.einsum, '{i,j},{k,j}->{k,i}'),\n+ def check(spec):\n+ out = xmap(partial(jnp.einsum, spec),\nin_axes=(['i', 'j'], ['j', 'k']),\nout_axes=['i', 'k'])(x, y)\nexpected = np.einsum('ij,jk->ik', x, y)\ntol = 1e-1 if jtu.device_under_test() == \"tpu\" else None\nself.assertAllClose(out, expected, check_dtypes=True,\natol=tol, rtol=tol)\n+ check('{i,j},{j,k}->{i,k}')\n+ check('{i,j},{k,j}->{k,i}') # order of named axes in the spec doesn't matter!\n+ check('{j},{k,j}->{k}')\n+ check('{i,j},{j}->{i}')\n+ check('{j},{j}->{}')\ndef test_xeinsum_no_named_axes_vector_dot(self):\nrng = np.random.RandomState(0)\n" } ]
Python
Apache License 2.0
google/jax
Minor fixes for xmap docstring, xeinsum parser The regression loss example from the xmap docstring was broken and the xeinsum parser didn't accept empty parens while it should.
260,335
11.02.2021 08:30:37
28,800
e47c933fd328a012a5bb4cdecaf15f6a0b360346
fix/skip test failures
[ { "change_type": "MODIFY", "old_path": "tests/pmap_test.py", "new_path": "tests/pmap_test.py", "diff": "@@ -1660,15 +1660,23 @@ class PmapTest(jtu.JaxTestCase):\naxis, collective.__name__.replace(\" \", \"\")),\n\"shape\": shape, \"dtype\": dtype, \"axis\": axis,\n\"collective\": collective, \"bulk_op\": bulk_op}\n- for collective, bulk_op in [(parallel.pargmax, jnp.argmax),\n- (parallel.pargmin, jnp.argmin)]\n+ for collective, bulk_op in [\n+ (parallel.pargmax, jnp.argmax),\n+ (parallel.pargmin, jnp.argmin)\n+ ]\nfor dtype in [np.float32, np.int32]\n- for shape in [(4,), (4, 2)]\n+ for shape in [(4,), (2, 2), (2, 4), (4, 2)]\nfor axis in range(len(shape))\n)\ndef testArgAllReduce(self, shape, dtype, axis, collective, bulk_op):\nif not config.omnistaging_enabled:\nself.skipTest(\"test requires omnistaging\")\n+ if xla_bridge.device_count() < shape[axis]:\n+ raise SkipTest(f\"test requires at least {shape[axis]} devices\")\n+ if (jtu.device_under_test() == 'cpu' and\n+ np.issubdtype(dtype, np.floating) and\n+ len(shape) > 1):\n+ raise SkipTest(\"skipped on cpu due to strange failures\") # TODO(mattjj)\nrng = jtu.rand_default(self.rng())\nx = rng(shape, dtype)\n" } ]
Python
Apache License 2.0
google/jax
fix/skip test failures
260,335
12.02.2021 10:30:46
28,800
268493bae899008e87d819377be50a23e91d4e71
specialize standard_primitive back to single-out
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1996,43 +1996,53 @@ def _argnum_weak_type(*argnums):\nreturn lambda *args, **_: all(args[i].weak_type for i in argnums)\ndef standard_primitive(shape_rule, dtype_rule, name, translation_rule=None,\n- multiple_results=False, weak_type_rule=None):\n- weak_type_rule = weak_type_rule or partial(_standard_weak_type_rule, name)\n+ weak_type_rule=None):\n+ weak_type_rule = weak_type_rule or _standard_weak_type_rule\nprim = Primitive(name)\n- prim.multiple_results = multiple_results\nprim.def_impl(partial(xla.apply_primitive, prim))\nprim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule, weak_type_rule))\nxla.translations[prim] = translation_rule or partial(standard_translate, name)\nreturn prim\n-def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule, *args, **kwargs):\n- assert all(isinstance(arg, UnshapedArray) for arg in args), args\n- weak_types = weak_type_rule(*args, **kwargs)\n- least_specialized = _max(\n- map(type, args), key=operator.attrgetter('array_abstraction_level'))\n+def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule, *avals, **kwargs):\n+ assert all(isinstance(aval, UnshapedArray) for aval in avals), avals\n+ assert not prim.multiple_results\n+ weak_type = weak_type_rule(*avals, **kwargs)\n+ least_specialized = _max(map(type, avals),\n+ key=operator.attrgetter('array_abstraction_level'))\nif least_specialized is ConcreteArray:\n- out_vals = prim.impl(*[x.val for x in args], **kwargs)\n- if not prim.multiple_results:\n- out_vals, weak_types = [out_vals], [weak_types]\n- out_avals = [ConcreteArray(v, weak_type=weak_type)\n- for v, weak_type in safe_zip(out_vals, weak_types)]\n+ return ConcreteArray(prim.impl(*[x.val for x in avals], **kwargs),\n+ weak_type=weak_type)\nelif least_specialized is ShapedArray:\n- shapes, dtypes = shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs)\n- if not prim.multiple_results:\n- shapes, dtypes, weak_types = [shapes], [dtypes], [weak_types]\n- out_avals = [ShapedArray(shape, dtype, weak_type=weak_type)\n- for shape, dtype, weak_type in safe_zip(shapes, dtypes, weak_types)]\n+ return ShapedArray(shape_rule(*avals, **kwargs), dtype_rule(*avals, **kwargs),\n+ weak_type=weak_type)\nelif least_specialized is UnshapedArray:\n- dtypes = dtype_rule(*args, **kwargs)\n- if not prim.multiple_results:\n- dtypes, weak_types = [dtypes], [weak_types]\n- out_avals = [UnshapedArray(dtype, weak_type=weak_type)\n- for dtype, weak_type in safe_zip(dtypes, weak_types)]\n+ return UnshapedArray(dtype_rule(*avals, **kwargs), weak_type=weak_type)\nelse:\n- raise TypeError(args, least_specialized)\n- if not prim.multiple_results:\n- return out_avals[0]\n- return out_avals\n+ raise TypeError(avals, least_specialized)\n+\n+def standard_multi_result_abstract_eval(\n+ prim, shape_rule, dtype_rule, weak_type_rule, *avals, **kwargs):\n+ assert prim.multiple_results\n+ assert all(isinstance(aval, UnshapedArray) for aval in avals), avals\n+ least_specialized = _max(map(type, avals),\n+ key=operator.attrgetter('array_abstraction_level'))\n+ weak_types = weak_type_rule(*avals, **kwargs)\n+ if least_specialized is ConcreteArray:\n+ out_vals = prim.impl(*[x.val for x in avals], **kwargs)\n+ return [ConcreteArray(val, weak_type=weak_type)\n+ for val, weak_type in safe_zip(out_vals, weak_types)]\n+ elif least_specialized is ShapedArray:\n+ out_shapes = shape_rule(*avals, **kwargs)\n+ out_dtypes = dtype_rule(*avals, **kwargs)\n+ return [ShapedArray(s, d, weak_type=weak_type)\n+ for s, d, weak_type in safe_zip(out_shapes, out_dtypes, weak_types)]\n+ elif least_specialized is UnshapedArray:\n+ out_dtypes = dtype_rule(*avals, **kwargs)\n+ return [UnshapedArray(dtype, weak_type=weak_type)\n+ for dtype, weak_type in safe_zip(out_dtypes, weak_types)]\n+ else:\n+ raise TypeError(avals, least_specialized)\ndef standard_translate(name, c, *args, **kwargs):\n@@ -2097,7 +2107,7 @@ def _broadcasting_shape_rule(name, *avals):\nraise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\nreturn result_shape\n-def _standard_weak_type_rule(name, *avals, **kwargs):\n+def _standard_weak_type_rule(*avals, **kwargs):\nreturn all(aval.weak_type for aval in avals)\ndef _naryop_weak_type_rule(name, *avals, **kwargs):\n@@ -4933,30 +4943,27 @@ batching.primitive_batchers[scatter_p] = (\npartial(_scatter_batching_rule, scatter))\n-def _reduce_shape_rule(*args, computation, jaxpr, consts, dimensions):\n- operand_args, init_value_args = split_list(args, [len(args) // 2])\n- if any(arg.shape != () for arg in init_value_args):\n- init_value_shapes = [a.shape for a in init_value_args]\n- raise ValueError(f'Found non-scalar init_value: {init_value_shapes}')\n- return [\n- tuple(np.delete(op_arg.shape, dimensions))\n- for op_arg in operand_args\n- ]\n-\n-\n-def _reduce_dtype_rule(*args, computation, jaxpr, consts, dimensions):\n- operand_args, init_value_args = split_list(args, [len(args) // 2])\n- operand_dtypes = [dtypes.canonicalize_dtype(op.dtype) for op in operand_args]\n- init_value_dtypes = [dtypes.canonicalize_dtype(init.dtype) for init in init_value_args]\n- if operand_dtypes != init_value_dtypes:\n- raise TypeError(f\"operand dtypes should match corresponding initial value dtypes; got \"\n- f\"operands={operand_args} and initial_values={init_value_args}\")\n+def _reduce_shape_rule(*avals, computation, jaxpr, consts, dimensions):\n+ operand_avals, init_val_avals = split_list(avals, [len(avals) // 2])\n+ if any(arg.shape != () for arg in init_val_avals):\n+ init_val_shapes = [a.shape for a in init_val_avals]\n+ raise ValueError(f'reduce found non-scalar initial value: {init_val_shapes}')\n+ return [tuple(np.delete(op.shape, dimensions)) for op in operand_avals]\n+\n+def _reduce_dtype_rule(*avals, computation, jaxpr, consts, dimensions):\n+ operand_avals, init_val_avals = split_list(avals, [len(avals) // 2])\n+ operand_dtypes = [dtypes.canonicalize_dtype(op.dtype) for op in operand_avals]\n+ init_val_dtypes = [dtypes.canonicalize_dtype(init.dtype) for init in init_val_avals]\n+ if operand_dtypes != init_val_dtypes:\n+ raise TypeError(\n+ \"reduce operand dtypes should match corresponding initial value dtypes, \"\n+ f\"got operands={operand_avals} and initial_values={init_val_avals}\")\nreturn operand_dtypes\n-def _reduce_weak_type_rule(*args, computation, jaxpr, consts, dimensions):\n- operand_args, init_value_args = split_list(args, [len(args) // 2])\n- return [op.weak_type and init_value.weak_type\n- for op, init_value in safe_zip(operand_args, init_value_args)]\n+def _reduce_weak_type_rule(*avals, computation, jaxpr, consts, dimensions):\n+ operand_avals, init_val_avals = split_list(avals, [len(avals) // 2])\n+ return [op.weak_type and init_val.weak_type\n+ for op, init_val in safe_zip(operand_avals, init_val_avals)]\ndef _reduce_translation_rule(c, *values, computation, jaxpr,\nconsts, dimensions):\n@@ -4969,7 +4976,6 @@ def _reduce_translation_rule(c, *values, computation, jaxpr,\nxla_computation = _reduction_computation(c, jaxpr, consts, init_values, singleton=False)\nreturn xops.Reduce(c, operands, init_values, xla_computation, dimensions)\n-\ndef _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr,\nconsts, dimensions):\nnum_operands = len(batched_args) // 2\n@@ -4992,7 +4998,6 @@ def _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr,\nelse:\nraise NotImplementedError # loop and stack\n-\ndef _reduction_computation(c, jaxpr, consts, init_values, singleton=True):\nif singleton:\ninit_values = [init_values]\n@@ -5022,9 +5027,13 @@ def _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\nbind = prim_bind if input_shape is None else partial(prim_bind, input_shape=padded_shape)\nreturn bind(masked_val, axes=axes)\n-reduce_p = standard_primitive(_reduce_shape_rule, _reduce_dtype_rule,\n- 'reduce', translation_rule=_reduce_translation_rule,\n- multiple_results=True, weak_type_rule=_reduce_weak_type_rule)\n+reduce_p = core.Primitive('reduce')\n+reduce_p.multiple_results = True\n+reduce_p.def_impl(partial(xla.apply_primitive, reduce_p))\n+reduce_p.def_abstract_eval(\n+ partial(standard_multi_result_abstract_eval, reduce_p, _reduce_shape_rule,\n+ _reduce_dtype_rule, _reduce_weak_type_rule))\n+xla.translations[reduce_p] = _reduce_translation_rule\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2272,7 +2272,8 @@ class LaxTest(jtu.JaxTestCase):\noperands = {'x': np.ones(5)}\nbad_init_values = {'x': np.ones(5)}\n- with self.assertRaisesRegex(ValueError, 'Found non-scalar init_value'):\n+ with self.assertRaisesRegex(ValueError,\n+ 'reduce found non-scalar initial value'):\nlax.reduce(operands, bad_init_values,\nlambda x, y: dict(x=x['x'] + y['x']), [0])\n" } ]
Python
Apache License 2.0
google/jax
specialize standard_primitive back to single-out
260,411
05.02.2021 12:04:25
-7,200
fd2b9b4759816eb0bdd4218f48039269cf9645a8
[call_tf] Add support for DLPack to avoid copying arrays in eager mode
[ { "change_type": "MODIFY", "old_path": "docs/CHANGELOG.md", "new_path": "docs/CHANGELOG.md", "diff": "@@ -13,6 +13,9 @@ PLEASE REMEMBER TO CHANGE THE '..master' WITH AN ACTUAL TAG in GITHUB LINK.\n* New features:\n* {func}`jax.scipy.stats.chi2` is now available as a distribution with logpdf and pdf methods.\n* {func}`jax.scipy.stats.betabinom` is now available as a distribution with logpmf and pmf methods.\n+ * Added {func}`jax.experimental.jax2tf.call_tf` to call TensorFlow functions\n+ from JAX ([#5627](https://github.com/google/jax/pull/5627)\n+ and [README](https://github.com/google/jax/blob/master/jax/experimental/jax2tf/README.md#calling-tensorflow-functions-from-jax)).\n* Bug fixes:\n* Breaking changes:\n* JAX's promotion rules were adjusted to make promotion more consistent and\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/dlpack.py", "new_path": "jax/_src/dlpack.py", "diff": "# limitations under the License.\nfrom jax import core\n+from jax import numpy as jnp\nfrom jax import lazy\nfrom jax.interpreters import xla\nfrom jax.lib import xla_client\nfrom jax.lib import xla_bridge\n+SUPPORTED_DTYPES = set([jnp.int8, jnp.int16, jnp.int32, jnp.int64,\n+ jnp.uint8, jnp.uint16, jnp.uint32, jnp.uint64,\n+ jnp.float16, jnp.bfloat16, jnp.float32, jnp.float64])\n+\n+\ndef to_dlpack(x: xla.DeviceArrayProtocol, take_ownership: bool = False):\n\"\"\"Returns a DLPack tensor that encapsulates a DeviceArray `x`.\n" }, { "change_type": "MODIFY", "old_path": "jax/dlpack.py", "new_path": "jax/dlpack.py", "diff": "# limitations under the License.\n# flake8: noqa: F401\n-from jax._src.dlpack import (to_dlpack, from_dlpack)\n+from jax._src.dlpack import (to_dlpack, from_dlpack, SUPPORTED_DTYPES)\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/README.md", "new_path": "jax/experimental/jax2tf/README.md", "diff": "@@ -237,8 +237,9 @@ before conversion. (This is a hypothesis, we have not verified it extensively.)\nThe experimental function ```call_tf``` allows JAX to call\nTensorFlow functions. These functions can be called anywhere in a JAX\n-computation, including in ``jax.jit``, ``jax.pmap``, ``jax.xmap``,\n-or inside JAX's control-flow primitives.\n+computation, including in staging contexts ``jax.jit``, ``jax.pmap``, ``jax.xmap``,\n+or inside JAX's control-flow primitives. In non-staging contexts,\n+the TensorFlow function is called in eager mode.\nFor now, only reverse-mode autodiff is supported for these functions\n(no forward-mode autodiff, nor ``vmap``).\n@@ -314,6 +315,11 @@ the ``a_inference_cos_tf_68__``HLO function that was compiled by TF from ``cos_t\nJAX XLA computation.\n* The TF custom gradients are respected, since it is TF that generates the\ngradient computation.\n+ * In op-by-op mode, when we call TensorFlow in eager mode, we use\n+ DLPack to try to avoid copying the data. This works for CPU (for\n+ DeviceArray data or for np.ndarray that are aligned on 16-byte\n+ boundaries) and on GPU (for DeviceArray).\n+ The zero-copy does not yet work on TPU.\n* ``call_tf`` works best with pure TF functions that do not capture\n``tf.Variable``s or tensors from the environment, and all such\ncontext is passed explicitly through arguments, and if variables\n" }, { "change_type": "MODIFY", "old_path": "jax/experimental/jax2tf/call_tf.py", "new_path": "jax/experimental/jax2tf/call_tf.py", "diff": "@@ -27,11 +27,13 @@ from typing import Callable\nimport jax\nfrom jax import core\n+from jax import dlpack\nfrom jax import dtypes\nfrom jax import numpy as jnp\nfrom jax import tree_util\nfrom jax._src import util\nfrom jax.interpreters import xla\n+from jax.lib import xla_bridge\nfrom jax.lib import xla_client\nimport numpy as np\n@@ -39,6 +41,10 @@ import tensorflow as tf # type: ignore[import]\nxops = xla_client._xla.ops # type: ignore\n+# The platforms for which to use DLPack to avoid copying (only works on GPU\n+# and CPU at the moment, and only for DeviceArray). For CPU we don't need\n+# DLPack, if we are careful.\n+_DLPACK_PLATFORMS = (\"gpu\",)\ndef call_tf(func_tf: Callable) -> Callable:\n\"\"\"Calls a TensorFlow function from JAX, with support for reverse autodiff.\n@@ -147,13 +153,36 @@ 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, args_treedef, func_tf, **_):\n- # TODO(necula): does this copy to the host?\n- args_tf_flat = [tf.constant(np.asarray(a)) for a in args]\n+def _call_tf_impl(*args_jax_flat, args_treedef, func_tf, **_):\n+ # On GPU we use dlpack to avoid copies of data to the host.\n+ def _arg_jax_to_tf(arg_jax):\n+ if (isinstance(arg_jax, xla.DeviceArray) and\n+ arg_jax.device_buffer.client.platform in _DLPACK_PLATFORMS and\n+ arg_jax.dtype in dlpack.SUPPORTED_DTYPES):\n+ arg_dlpack = jax.dlpack.to_dlpack(arg_jax, take_ownership=False)\n+ return tf.experimental.dlpack.from_dlpack(arg_dlpack)\n+ # The following avoids copies to the host on CPU, always for DeviceArray\n+ # and even for ndarray if they are sufficiently aligned.\n+ # TODO(necula): on TPU this copies to the host!\n+ return tf.constant(np.asarray(arg_jax))\n+\n+ args_tf_flat = tuple(map(_arg_jax_to_tf, args_jax_flat))\nres_tf = func_tf(*args_treedef.unflatten(args_tf_flat))\n+ res_tf_flat, _ = tree_util.tree_flatten(res_tf)\n# TODO(necula): check the result for tree and aval\n- # TODO(necula): does this copy to the host?\n- return [jnp.asarray(np.asarray(r)) for r in tree_util.tree_flatten(res_tf)[0]]\n+\n+ def _res_tf_to_jax(res_tf):\n+ if isinstance(res_tf, tf.Tensor) and res_tf.dtype in dlpack.SUPPORTED_DTYPES:\n+ res_tf_platform = tf.DeviceSpec.from_string(res_tf.backing_device).device_type\n+ res_jax_platform = res_tf_platform.lower()\n+ if res_jax_platform in _DLPACK_PLATFORMS:\n+ res_dlpack = tf.experimental.dlpack.to_dlpack(res_tf)\n+ return jax.dlpack.from_dlpack(\n+ res_dlpack, backend=xla_bridge.get_backend(res_jax_platform))\n+\n+ return jnp.asarray(np.asarray(res_tf))\n+\n+ return list(map(_res_tf_to_jax, res_tf_flat))\ncall_tf_p.def_impl(_call_tf_impl)\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": "@@ -53,14 +53,59 @@ class CallTfTest(jtu.JaxTestCase):\ndef setUp(self):\nif tf is None:\nraise unittest.SkipTest(\"Test requires tensorflow\")\n+ # TODO(b/171320191): this line works around a missing context initialization\n+ # bug in TensorFlow.\n+ _ = tf.add(1, 1)\nsuper().setUp()\n@parameterized_jit\n- def test_eval(self, with_jit=True):\n- x = jnp.float32(3.)\n+ def test_eval_scalar_arg(self, with_jit=False):\n+ x = 3.\n+ res = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\n+ self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+\n+ @parameterized_jit\n+ def test_eval_scalar_res(self, with_jit=False):\n+ x = 3.\n+ res = _maybe_jit(with_jit, jax2tf.call_tf(lambda x: 4.))(x)\n+ self.assertAllClose(4., res, check_dtypes=False)\n+ @parameterized_jit\n+ def test_eval_numpy_arg(self, with_jit=False):\n+ x = np.ones((2, 3), dtype=np.float32)\n+ res = _maybe_jit(with_jit, jax2tf.call_tf(tf.math.sin))(x)\n+ self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+\n+ @parameterized_jit\n+ def test_eval_numpy_res(self, with_jit=False):\n+ x = np.ones((2, 3), dtype=np.float32)\n+ res = _maybe_jit(with_jit, jax2tf.call_tf(lambda _: x))(x)\n+ self.assertAllClose(x, res, check_dtypes=False)\n+\n+ def test_eval_numpy_no_copy(self):\n+ if jtu.device_under_test() != \"cpu\":\n+ raise unittest.SkipTest(\"no_copy test works only on CPU\")\n+ # For ndarray, zero-copy only works for sufficiently-aligned arrays.\n+ x = np.ones((16, 16), dtype=np.float32)\n+ res = jax2tf.call_tf(lambda x: x)(x)\n+ self.assertAllClose(x, res)\n+ self.assertTrue(np.shares_memory(x, res))\n+\n+ @parameterized_jit\n+ def test_eval_devicearray_arg(self, with_jit=False):\n+ x = 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)\n+ self.assertAllClose(jnp.sin(x), res, check_dtypes=False)\n+\n+ def test_eval_devicearray_no_copy(self):\n+ if jtu.device_under_test() != \"cpu\":\n+ # TODO(necula): add tests for GPU and TPU\n+ raise 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+ res = jax2tf.call_tf(lambda x: x)(x)\n+ self.assertAllClose(x, res)\n+ self.assertTrue(np.shares_memory(x, res))\n@parameterized_jit\ndef test_eval_pytree(self, with_jit=True):\n" }, { "change_type": "MODIFY", "old_path": "tests/array_interoperability_test.py", "new_path": "tests/array_interoperability_test.py", "diff": "@@ -45,9 +45,7 @@ except:\ntf = None\n-dlpack_dtypes = [jnp.int8, jnp.int16, jnp.int32, jnp.int64,\n- jnp.uint8, jnp.uint16, jnp.uint32, jnp.uint64,\n- jnp.float16, jnp.float32, jnp.float64]\n+dlpack_dtypes = jax.dlpack.SUPPORTED_DTYPES\ntorch_dtypes = [jnp.int8, jnp.int16, jnp.int32, jnp.int64,\njnp.uint8, jnp.float16, jnp.float32, jnp.float64]\n" } ]
Python
Apache License 2.0
google/jax
[call_tf] Add support for DLPack to avoid copying arrays in eager mode
260,484
13.02.2021 16:32:21
-10,800
96193cef122212b27ed797c6f8d8714778cc051d
Simplify bazel version check
[ { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -145,7 +145,7 @@ def download_and_verify_bazel():\ndef get_bazel_paths(bazel_path_flag):\n- \"\"\"Yields a sequence of a guess about bazel path. Some of sequence elements\n+ \"\"\"Yields a sequence of guesses about bazel path. Some of sequence elements\ncan be None. The resulting iterator is lazy and potentially has a side\neffects.\"\"\"\nyield bazel_path_flag\n@@ -153,23 +153,23 @@ def get_bazel_paths(bazel_path_flag):\nyield download_and_verify_bazel()\n-def get_bazel_path(bazel_path_flag, min_version, max_version):\n+def get_bazel_path(bazel_path_flag):\n\"\"\"Returns the path to a Bazel binary, downloading Bazel if not found. Also,\n- it checks Bazel's version is in the range [`min_version`, `max_version`).\n+ it checks Bazel's version at lease newer than 2.0.0.\nNOTE Manual version check is reasonably only for bazel < 2.0.0. Newer bazel\nreleases performs version check against .bazelversion (see for details\nhttps://blog.bazel.build/2019/12/19/bazel-2.0.html#other-important-changes).\n\"\"\"\nfor path in filter(None, get_bazel_paths(bazel_path_flag)):\n- if check_bazel_version(path, min_version, max_version):\n+ if check_bazel_version(path):\nreturn path\nprint(\"Cannot find or download bazel. Please install bazel.\")\nsys.exit(-1)\n-def check_bazel_version(bazel_path, min_version, max_version):\n+def check_bazel_version(bazel_path):\ntry:\nversion_output = shell([bazel_path, \"--bazelrc=/dev/null\", \"version\"])\nexcept subprocess.CalledProcessError:\n@@ -177,14 +177,8 @@ def check_bazel_version(bazel_path, min_version, max_version):\nmatch = re.search(\"Build label: *([0-9\\\\.]+)[^0-9\\\\.]\", version_output)\nif match is None:\nreturn False\n- version = match.group(1)\n- min_ints = [int(x) for x in min_version.split(\".\")]\nactual_ints = [int(x) for x in match.group(1).split(\".\")]\n- if min_ints > actual_ints:\n- return False\n- if max_version is not None:\n- max_ints = [int(x) for x in max_version.split(\".\")]\n- if actual_ints >= max_ints:\n+ if (2, 0, 0) > actual_ints:\nreturn False\nreturn True\n@@ -437,7 +431,7 @@ def main():\nos.chdir(os.path.dirname(__file__ or args.prog) or '.')\n# Find a working Bazel.\n- bazel_path = get_bazel_path(args.bazel_path, min_version=\"2.0.0\", max_version=None)\n+ bazel_path = get_bazel_path(args.bazel_path)\nprint(\"Bazel binary path: {}\".format(bazel_path))\npython_bin_path = get_python_bin_path(args.python_bin_path)\n" } ]
Python
Apache License 2.0
google/jax
Simplify bazel version check
260,411
13.02.2021 15:47:42
-7,200
25dbe9748730b42fff82fe6b23604e7afc18128a
Update gpu_memory_allocation.rst Discovered that the link did not work anymore
[ { "change_type": "MODIFY", "old_path": "docs/gpu_memory_allocation.rst", "new_path": "docs/gpu_memory_allocation.rst", "diff": "@@ -54,7 +54,7 @@ Common causes of OOM failures\nin TF1, which should be set in a :code:`tf.ConfigProto` passed to\n:code:`tf.Session`. See\n`Using GPUs: Limiting GPU memory growth\n- <https://www.tensorflow.org/beta/guide/using_gpu#limiting_gpu_memory_growth>`_\n+ <https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth>`_\nfor TF2).\n**Running JAX on the display GPU.**\n" } ]
Python
Apache License 2.0
google/jax
Update gpu_memory_allocation.rst Discovered that the link did not work anymore
260,335
13.02.2021 08:19:31
28,800
671fe938bd8d5087889a7971161a6290ee24fe12
make map/unmap aval functions extensible Also, use them in batching.py. This change is needed for the dynamic shapes prototype in since we add new types that can be mapped over.
[ { "change_type": "MODIFY", "old_path": "jax/core.py", "new_path": "jax/core.py", "diff": "@@ -1425,6 +1425,38 @@ named_call_p.def_impl(call_impl)\n# ------------------- Map -------------------\n+def mapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n+ handler, _ = aval_mapping_handlers.get(type(aval), (None, None))\n+ if handler is not None:\n+ return handler(size, axis, aval)\n+ else:\n+ raise TypeError(f\"no mapping handler for {aval} of type {type(aval)}\")\n+\n+def unmapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n+ _, handler = aval_mapping_handlers.get(type(aval), (None, None))\n+ if handler is not None:\n+ return handler(size, axis, aval)\n+ else:\n+ raise TypeError(f\"no unmapping handler for {aval} of type {type(aval)}\")\n+\n+def _map_unit(size: int, axis: int, aval: AbstractUnit) -> AbstractUnit:\n+ return aval\n+\n+def _map_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\n+ assert aval.shape[axis] == size\n+ return ShapedArray(tuple_delete(aval.shape, axis), aval.dtype)\n+\n+def _unmap_shaped_array(size: int, axis: int, aval: ShapedArray) -> ShapedArray:\n+ return ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype)\n+\n+AvalMapHandlerPair = Tuple[Callable, Callable]\n+aval_mapping_handlers: Dict[Type, AvalMapHandlerPair] = {\n+ AbstractUnit: (_map_unit, _map_unit),\n+ ShapedArray: (_map_shaped_array, _unmap_shaped_array),\n+ ConcreteArray: (_map_shaped_array, _unmap_shaped_array),\n+}\n+\n+\nclass MapPrimitive(Primitive):\nmultiple_results = True\nmap_primitive = True\n@@ -1516,24 +1548,6 @@ axis_substitution_rules: Dict[Primitive, Callable[[ParamDict, AxisSubst], ParamD\n# ------------------- Jaxpr checking -------------------\n-def mapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n- if aval is abstract_unit:\n- return aval\n- elif isinstance(aval, ShapedArray):\n- # might be raising abstraction level from Concrete here\n- assert aval.shape[axis] == size\n- return ShapedArray(tuple_delete(aval.shape, axis), aval.dtype)\n- else:\n- raise TypeError(f\"Mapped operand {aval}\")\n-\n-def unmapped_aval(size: int, axis: int, aval: AbstractValue) -> AbstractValue:\n- if aval is abstract_unit:\n- return aval\n- elif isinstance(aval, ShapedArray):\n- return ShapedArray(tuple_insert(aval.shape, axis, size), aval.dtype)\n- else:\n- raise TypeError(f\"Mapped output {aval}\")\n-\ndef typecheck(aval: AbstractValue, x) -> bool:\nreturn typecompat(aval, get_aval(x))\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/batching.py", "new_path": "jax/interpreters/batching.py", "diff": "@@ -18,7 +18,7 @@ from typing import Any, Callable, Dict, Optional, Tuple, Union, Sequence, Iterab\nimport jax\nfrom ..config import config\nfrom .. import core\n-from ..core import ShapedArray, raise_to_shaped, Trace, Tracer\n+from ..core import raise_to_shaped, Trace, Tracer\nfrom ..ad_util import add_jaxvals, add_jaxvals_p, zeros_like_jaxval, zeros_like_p\nfrom .. import linear_util as lu\nfrom .._src.util import (unzip2, partial, safe_map, wrap_name, split_list,\n@@ -116,17 +116,10 @@ class BatchTracer(Tracer):\n@property\ndef aval(self):\naval = raise_to_shaped(core.get_aval(self.val))\n- if self.batch_dim is not_mapped:\n- return aval\n- else:\n- if aval is core.abstract_unit:\n+ if self.batch_dim is not_mapped or aval is core.abstract_unit:\nreturn aval\n- elif type(aval) is ShapedArray:\n- assert 0 <= self.batch_dim < aval.ndim\n- new_shape = tuple(np.delete(aval.shape, self.batch_dim))\n- return aval.update(shape=new_shape)\nelse:\n- raise TypeError(aval)\n+ return core.mapped_aval(aval.shape[self.batch_dim], self.batch_dim, aval)\ndef full_lower(self):\nif self.batch_dim is not_mapped:\n" } ]
Python
Apache License 2.0
google/jax
make map/unmap aval functions extensible Also, use them in batching.py. This change is needed for the dynamic shapes prototype in #5717, since we add new types that can be mapped over.
260,335
17.02.2021 07:31:38
28,800
9b18135b6e0f33766b278f95e001f002c394c2e1
Rollback of due to internal breakage.
[ { "change_type": "MODIFY", "old_path": "jax/_src/lax/lax.py", "new_path": "jax/_src/lax/lax.py", "diff": "@@ -1996,19 +1996,15 @@ def _argnum_weak_type(*argnums):\nreturn lambda *args, **_: all(args[i].weak_type for i in argnums)\ndef standard_primitive(shape_rule, dtype_rule, name, translation_rule=None,\n- weak_type_rule=None, named_shape_rule=None):\n+ weak_type_rule=None):\nweak_type_rule = weak_type_rule or _standard_weak_type_rule\n- named_shape_rule = named_shape_rule or standard_named_shape_rule\nprim = Primitive(name)\nprim.def_impl(partial(xla.apply_primitive, prim))\n- prim.def_abstract_eval(\n- partial(standard_abstract_eval, prim, shape_rule, dtype_rule,\n- weak_type_rule, named_shape_rule))\n+ prim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule, weak_type_rule))\nxla.translations[prim] = translation_rule or partial(standard_translate, name)\nreturn prim\n-def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule,\n- named_shape_rule, *avals, **kwargs):\n+def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule, *avals, **kwargs):\nassert all(isinstance(aval, UnshapedArray) for aval in avals), avals\nassert not prim.multiple_results\nweak_type = weak_type_rule(*avals, **kwargs)\n@@ -2019,16 +2015,14 @@ def standard_abstract_eval(prim, shape_rule, dtype_rule, weak_type_rule,\nweak_type=weak_type)\nelif least_specialized is ShapedArray:\nreturn ShapedArray(shape_rule(*avals, **kwargs), dtype_rule(*avals, **kwargs),\n- weak_type=weak_type,\n- named_shape=named_shape_rule(*avals, **kwargs))\n+ weak_type=weak_type)\nelif least_specialized is UnshapedArray:\nreturn UnshapedArray(dtype_rule(*avals, **kwargs), weak_type=weak_type)\nelse:\nraise TypeError(avals, least_specialized)\ndef standard_multi_result_abstract_eval(\n- prim, shape_rule, dtype_rule, weak_type_rule,\n- named_shape_rule, *avals, **kwargs):\n+ prim, shape_rule, dtype_rule, weak_type_rule, *avals, **kwargs):\nassert prim.multiple_results\nassert all(isinstance(aval, UnshapedArray) for aval in avals), avals\nleast_specialized = _max(map(type, avals),\n@@ -2041,10 +2035,8 @@ def standard_multi_result_abstract_eval(\nelif least_specialized is ShapedArray:\nout_shapes = shape_rule(*avals, **kwargs)\nout_dtypes = dtype_rule(*avals, **kwargs)\n- out_named_shapes = named_shape_rule(*avals, **kwargs)\n- return [ShapedArray(s, d, weak_type=weak_type, named_shape=named_shape)\n- for s, d, weak_type, named_shape\n- in safe_zip(out_shapes, out_dtypes, weak_types, out_named_shapes)]\n+ return [ShapedArray(s, d, weak_type=weak_type)\n+ for s, d, weak_type in safe_zip(out_shapes, out_dtypes, weak_types)]\nelif least_specialized is UnshapedArray:\nout_dtypes = dtype_rule(*avals, **kwargs)\nreturn [UnshapedArray(dtype, weak_type=weak_type)\n@@ -2052,13 +2044,11 @@ def standard_multi_result_abstract_eval(\nelse:\nraise TypeError(avals, least_specialized)\n+\ndef standard_translate(name, c, *args, **kwargs):\nxla_opname = ''.join(term.capitalize() for term in name.split('_'))\nreturn getattr(xops, xla_opname)(*args, **kwargs)\n-def standard_named_shape_rule(*avals, **kwargs):\n- return core.join_named_shapes(*(a.named_shape for a in avals))\n-\ndef unop_dtype_rule(result_dtype, accepted_dtypes, name, aval, **kwargs):\nif not any(dtypes.issubdtype(aval.dtype, t) for t in accepted_dtypes):\n@@ -4988,19 +4978,15 @@ def _reduce_translation_rule(c, *values, computation, jaxpr,\ndef _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr,\nconsts, dimensions):\n- # TODO(mattjj,frostig): use batch_jaxpr, delete computation (assumes poly??)\nnum_operands = len(batched_args) // 2\noperands, init_values = split_list(batched_args, [num_operands])\noperand_bdims, init_value_bdims = split_list(batch_dims, [num_operands])\n- if all(init_value_bdim is batching.not_mapped\n- for init_value_bdim in init_value_bdims):\n+ if all(init_value_bdim is None for init_value_bdim in init_value_bdims):\n# Assume all batch dims are the same for each of the operands\n+ assert all(operand_bdim is not None for operand_bdim in operand_bdims)\n+ assert all(operand_bdim == operand_bdims[0] for operand_bdim in operand_bdims)\n# TODO(sharadmv): handle the case when batch dims are different across\n# operands or when some are unbatched\n- if not all(operand_bdim is not batching.not_mapped for operand_bdim in operand_bdims):\n- raise NotImplementedError\n- if not all(operand_bdim == operand_bdims[0] for operand_bdim in operand_bdims):\n- raise NotImplementedError\noperand_bdim = operand_bdims[0]\nnew_dimensions = [d + bool(d >= operand_bdim) for d in dimensions]\nnew_operand_bdim = operand_bdim - int(np.sum(np.less(dimensions, operand_bdim)))\n@@ -5041,26 +5027,12 @@ def _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\nbind = prim_bind if input_shape is None else partial(prim_bind, input_shape=padded_shape)\nreturn bind(masked_val, axes=axes)\n-def _reduce_named_shape_rule(*avals, computation, jaxpr, consts, dimensions):\n- # TODO(mattjj,frostig): see the TODOs noting limitations/assumptions in\n- # _reduce_batching_rule. We're making the same assumptions here for now.\n- num_operands = len(avals) // 2\n- operand_avals, init_avals = split_list(avals, [num_operands])\n- if any(a.named_shape for a in init_avals):\n- raise NotImplementedError\n- named_shapes = [a.named_shape for a in operand_avals]\n- if not all(named_shapes[0] == named_shape for named_shape in named_shapes):\n- raise NotImplementedError\n- return named_shapes\n-\n-\nreduce_p = core.Primitive('reduce')\nreduce_p.multiple_results = True\nreduce_p.def_impl(partial(xla.apply_primitive, reduce_p))\nreduce_p.def_abstract_eval(\npartial(standard_multi_result_abstract_eval, reduce_p, _reduce_shape_rule,\n- _reduce_dtype_rule, _reduce_weak_type_rule,\n- _reduce_named_shape_rule))\n+ _reduce_dtype_rule, _reduce_weak_type_rule))\nxla.translations[reduce_p] = _reduce_translation_rule\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/lax/parallel.py", "new_path": "jax/_src/lax/parallel.py", "diff": "@@ -602,18 +602,10 @@ def _allreduce_impl(pos_reducer, *args, axes, axis_index_groups):\nreturn [pos_reducer(arg, axes) for arg in args]\ndef _allreduce_abstract_eval(*args, axes, axis_index_groups):\n- # TODO(frostig,mattjj,jekbradbury): maybe check aval names here\npos_axes = tuple(axis for axis in axes if isinstance(axis, int))\n- named_shapes = [arg.named_shape for arg in args]\n- if axis_index_groups is None:\n- named_axes = set(axis for axis in axes if not isinstance(axis, int))\n- named_shapes = [{name: size for name, size in arg.named_shape.items()\n- if name not in named_axes} for arg in args]\n- else:\n- assert len(pos_axes) == 0\nreturn [ShapedArray(lax._reduce_op_shape_rule(raise_to_shaped(arg), axes=pos_axes),\n- arg.dtype, named_shape=named_shape)\n- for arg, named_shape in zip(args, named_shapes)]\n+ arg.dtype)\n+ for arg in args]\ndef _allreduce_translation_rule(prim, pos_prim, c, *args, axes, axis_index_groups,\naxis_env, platform):\n@@ -1039,9 +1031,7 @@ def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_\nx_aval = raise_to_shaped(x)\nnew_shape = list(x_aval.shape)\nnew_shape.insert(all_gather_dimension, axis_size)\n- new_named_shape = {name: size for name, size in x_aval.named_shape.items()\n- if name != axis_name}\n- return x_aval.update(shape=new_shape, named_shape=new_named_shape)\n+ return x_aval.update(shape=new_shape)\ndef _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size):\n# TODO(cjfj): Add reduce-scatter op to XLA?\n@@ -1096,13 +1086,10 @@ def _axis_index_translation_rule(c, *, axis_name, axis_env, platform):\nunsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\nreturn xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n-def _axis_index_abstract_eval(*, axis_name):\n- frame = core.axis_frame(axis_name)\n- return ShapedArray((), np.int32, named_shape={axis_name: frame.size})\n-\naxis_index_p = core.Primitive('axis_index')\nxla.parallel_translations[axis_index_p] = _axis_index_translation_rule\n-axis_index_p.def_abstract_eval(_axis_index_abstract_eval)\n+axis_index_p.def_abstract_eval(\n+ lambda *args, **params: ShapedArray((), np.int32))\npxla.multi_host_supported_collectives.add(axis_index_p)\ncore.axis_substitution_rules[axis_index_p] = partial(_subst_all_names_in_param, 'axis_name')\n@@ -1143,15 +1130,11 @@ def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch):\n@pdot_p.def_abstract_eval\ndef _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch):\n- # TODO(frostig,mattjj,jekbradbury): check inputs have given axis names?\n+ # TODO: avals with names, check inputs are mapped along axis_name, eliminate\nif not len(set(axis_name)) == len(axis_name): raise ValueError\n- pos_aval = lax.dot_general_p.abstract_eval(\n+ return lax.dot_general_p.abstract_eval(\nx, y, dimension_numbers=[pos_contract, pos_batch],\nprecision=None, preferred_element_type=None)\n- named_shape = {name: size\n- for aval in (x, y) for name, size in aval.named_shape.items()\n- if name not in axis_name}\n- return pos_aval.update(named_shape=named_shape)\ndef _pdot_vmap_collective_rule(frame, vals_in, dims_in, *, axis_name,\npos_contract, pos_batch):\n@@ -1303,8 +1286,7 @@ def omnistaging_disabler() -> None:\nnreps = dynamic_axis_env.nreps\ntrace = frame.pmap_trace\n- out_aval = _axis_index_abstract_eval(\n- nreps=nreps, sizes=sizes, axis_name=axis_name)\n+ out_aval = ShapedArray((), np.int32)\nout_tracer = pe.JaxprTracer(trace, pe.PartialVal.unknown(out_aval), None)\neqn = pe.new_eqn_recipe([], [out_tracer], axis_index_p,\ndict(nreps=nreps, sizes=sizes, axis_name=axis_name),\n@@ -1319,9 +1301,7 @@ def omnistaging_disabler() -> None:\nunsigned_index = xops.Rem(xops.Div(xops.ReplicaId(c), div), mod)\nreturn xops.ConvertElementType(unsigned_index, xb.dtype_to_etype(np.int32))\n- def _axis_index_abstract_eval(*, nreps, sizes, axis_name):\n- return ShapedArray((), np.int32, named_shape={axis_name: sizes[-1]})\n-\naxis_index_p.def_custom_bind(_axis_index_bind)\n- axis_index_p.def_abstract_eval(_axis_index_abstract_eval)\n+ axis_index_p.def_abstract_eval(\n+ lambda *args, **params: ShapedArray((), np.int32))\nxla.translations[axis_index_p] = _axis_index_translation_rule\n" }, { "change_type": "MODIFY", "old_path": "jax/api.py", "new_path": "jax/api.py", "diff": "@@ -2226,11 +2226,10 @@ def _valid_jaxtype(arg):\nclass ShapeDtypeStruct:\n- __slots__ = [\"shape\", \"dtype\", \"named_shape\"]\n- def __init__(self, shape, dtype, named_shape={}):\n+ __slots__ = [\"shape\", \"dtype\"]\n+ def __init__(self, shape, dtype):\nself.shape = shape\nself.dtype = np.dtype(dtype)\n- self.named_shape = named_shape\nsize = property(lambda self: prod(self.shape))\nndim = property(lambda self: len(self.shape))\n@@ -2242,8 +2241,7 @@ class ShapeDtypeStruct:\nraise TypeError(\"len() of unsized object\") from e # same as numpy error\ndef __repr__(self):\n- ns = f\", named_shape={self.named_shape}\" if self.named_shape else \"\"\n- return f\"{type(self).__name__}(shape={self.shape}, dtype={self.dtype.name}{ns})\"\n+ return f\"{type(self).__name__}(shape={self.shape}, dtype={self.dtype.name})\"\n__str__ = __repr__\n@@ -2251,11 +2249,10 @@ class ShapeDtypeStruct:\nif not isinstance(other, ShapeDtypeStruct):\nreturn False\nelse:\n- return (other.shape, other.dtype, other.named_shape) == (\n- self.shape, self.dtype, self.named_shape)\n+ return (other.shape, other.dtype) == (self.shape, self.dtype)\ndef __hash__(self):\n- return hash((self.shape, self.dtype, self.named_shape))\n+ return hash((self.shape, self.dtype))\ndef eval_shape(fun: Callable, *args, **kwargs):\n\"\"\"Compute the shape/dtype of ``fun`` without any FLOPs.\n@@ -2321,7 +2318,7 @@ def eval_shape(fun: Callable, *args, **kwargs):\nwrapped_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\nout = pe.abstract_eval_fun(wrapped_fun.call_wrapped,\n*map(shaped_abstractify, args_flat))\n- out = [ShapeDtypeStruct(x.shape, x.dtype, x.named_shape) for x in out]\n+ out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]\nreturn tree_unflatten(out_tree(), out)\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/partial_eval.py", "new_path": "jax/interpreters/partial_eval.py", "diff": "@@ -1113,10 +1113,6 @@ class DynamicJaxprTrace(core.Trace):\nconstvars = map(self.getvar, map(self.instantiate_const, consts))\noutvars = map(self.makevar, out_tracers)\nnew_in_axes = (None,) * len(consts) + params['in_axes']\n- # extending the axis env here is necessary for type checking that may happen\n- # in convert_constvars_jaxpr\n- # TODO(mattjj): remove the need for extend_axis_env here\n- with core.extend_axis_env(axis_name, axis_size, None): # type: ignore\nnew_params = dict(params, in_axes=new_in_axes, out_axes=out_axes,\ncall_jaxpr=convert_constvars_jaxpr(jaxpr))\ndel new_params['out_axes_thunk']\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -1233,24 +1233,6 @@ class APITest(jtu.JaxTestCase):\nout_shape = api.eval_shape(lambda x: x, x) # doesn't crash\nself.assertEqual(out_shape.shape, (3,))\n- def test_eval_shape_names(self):\n- def fun(x, y):\n- return lax.psum(x, 'i') + y\n-\n- class MyArgArray(object):\n- def __init__(self, shape, dtype, named_shape):\n- self.shape = shape\n- self.dtype = dtype\n- self.named_shape = named_shape\n-\n- x = MyArgArray((3, 2), jnp.float32, {'i': 10})\n- y = MyArgArray((3, 2), jnp.float32, {'j': 5})\n- with core.extend_axis_env('i', 10, None):\n- with core.extend_axis_env('j', 5, None):\n- out_shape = api.eval_shape(fun, x, y)\n-\n- self.assertEqual(out_shape.named_shape, {'j': 5})\n-\ndef test_issue_871(self):\nT = jnp.array([[1., 2.], [3., 4.], [5., 6.]])\nx = jnp.array([1, 2, 3])\n@@ -2841,19 +2823,6 @@ class JaxprTest(jtu.JaxTestCase):\njaxpr = api.make_jaxpr(f, axis_env=[('i', 4)])(2)\nself.assertIn('psum', str(jaxpr))\n- def test_make_jaxpr_named(self):\n- if not config.omnistaging_enabled:\n- raise unittest.SkipTest(\"test only works with omnistaging\")\n-\n- def f(x):\n- return x - lax.psum(x, 'i')\n-\n- x = types.SimpleNamespace(\n- shape=(2, 3), dtype=jnp.float32, named_shape={'i': 10})\n- jaxpr = api.make_jaxpr(f, axis_env=[('i', 10)])(x)\n- named_shapes = [v.aval.named_shape for v in jaxpr.jaxpr.eqns[1].invars]\n- self.assertEqual(named_shapes, [{'i': 10}, {}])\n-\nclass LazyTest(jtu.JaxTestCase):\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_test.py", "new_path": "tests/lax_test.py", "diff": "@@ -2453,28 +2453,5 @@ class LazyConstantTest(jtu.JaxTestCase):\nout = lax.cumsum(x)\nself.assertArraysEqual(out, x)\n-\n-class LaxNamedShapeTest(jtu.JaxTestCase):\n-\n- def test_abstract_eval(self):\n- aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10})\n- out = lax.sin_p.abstract_eval(aval1)\n- self.assertEqual(out, aval1)\n-\n- aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10})\n- aval2 = core.ShapedArray((2, 3), np.float32, False, {'j': 5})\n- expected = core.ShapedArray((2, 3), np.float32, False, {'i': 10, 'j': 5})\n- out = lax.add_p.abstract_eval(aval1, aval2)\n- self.assertEqual(out, expected)\n-\n- def test_abstract_eval_collective(self):\n- if not config.omnistaging_enabled:\n- raise SkipTest(\"test requires omnistaging\")\n- with core.extend_axis_env('i', 10, None):\n- aval1 = core.ShapedArray((2, 3), np.float32, False, {'i': 10, 'j': 5})\n- expected = core.ShapedArray((2, 3), np.float32, False, {'j': 5})\n- out, = lax.psum_p.abstract_eval(aval1, axes=('i',), axis_index_groups=None)\n- self.assertEqual(out, expected)\n-\nif __name__ == '__main__':\nabsltest.main(testLoader=jtu.JaxTestLoader())\n" } ]
Python
Apache License 2.0
google/jax
Rollback of #5702 due to internal breakage. PiperOrigin-RevId: 357943850
260,628
18.02.2021 11:08:41
18,000
4c202ad22209f44eed360f585fbfbfe51abaf42b
implement np.polyint
[ { "change_type": "MODIFY", "old_path": "docs/jax.numpy.rst", "new_path": "docs/jax.numpy.rst", "diff": "@@ -283,6 +283,7 @@ Not every function in NumPy is implemented; contributions are welcome!\npiecewise\npolyadd\npolyder\n+ polyint\npolymul\npolysub\npolyval\n" }, { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -3479,6 +3479,26 @@ def polyadd(a1, a2):\nreturn a2.at[-a1.shape[0]:].add(a1)\n+@_wraps(np.polyint)\n+def polyint(p, m=1, k=None):\n+ m = core.concrete_or_error(operator.index, m, \"'m' argument of jnp.polyint\")\n+ p = asarray(p)\n+ if m < 0:\n+ raise ValueError(\"Order of integral must be positive (see polyder)\")\n+ if k is None:\n+ k = zeros(m)\n+ k = atleast_1d(k)\n+ if len(k) == 1:\n+ k = full((m,), k[0])\n+ if len(k) != m or k.ndim > 1:\n+ raise ValueError(\"k must be a scalar or a rank-1 array of length 1 or m.\")\n+ if m == 0:\n+ return p\n+ else:\n+ coeff = maximum(1, arange(len(p) + m, 0, -1) - 1 - arange(m)[:, newaxis]).prod(0)\n+ return true_divide(concatenate((p, k)), coeff)\n+\n+\n@_wraps(np.polyder)\ndef polyder(p, m=1):\nm = core.concrete_or_error(operator.index, m, \"'m' argument of jnp.polyder\")\n" }, { "change_type": "MODIFY", "old_path": "jax/numpy/__init__.py", "new_path": "jax/numpy/__init__.py", "diff": "@@ -51,7 +51,7 @@ from jax._src.numpy.lax_numpy import (\nnanmax, nanmean, nanmin, nanprod, nanstd, nansum, nanvar, ndarray, ndim,\nnegative, newaxis, nextafter, nonzero, not_equal, number, numpy_version,\nobject_, ones, ones_like, operator_name, outer, packbits, pad, percentile,\n- pi, piecewise, polyadd, polyder, polymul, polysub, polyval, positive, power,\n+ pi, piecewise, polyadd, polyder, polyint, polymul, polysub, polyval, positive, power,\nprod, product, promote_types, ptp, quantile,\nrad2deg, radians, ravel, ravel_multi_index, real, reciprocal, remainder, repeat, reshape,\nresult_type, right_shift, rint, roll, rollaxis, rot90, round, row_stack,\n" }, { "change_type": "MODIFY", "old_path": "tests/lax_numpy_test.py", "new_path": "tests/lax_numpy_test.py", "diff": "@@ -1674,6 +1674,25 @@ class LaxBackedNumpyTests(jtu.JaxTestCase):\nself._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+ @parameterized.named_parameters(jtu.cases_from_list(\n+ {\"testcase_name\": \"_shape={}_order={}_k={}\".format(\n+ jtu.format_shape_dtype_string(a_shape, dtype),\n+ order, k),\n+ \"dtype\": dtype, \"a_shape\": a_shape, \"order\" : order, \"k\": k}\n+ for dtype in default_dtypes\n+ for a_shape in one_dim_array_shapes\n+ for order in range(5)\n+ for k in [np.arange(order, dtype=dtype), np.zeros(1, dtype), np.ones(1, dtype), None]\n+))\n+ def testPolyInt(self, a_shape, order, k, dtype):\n+ rng = jtu.rand_default(self.rng())\n+ np_fun = lambda arg1: np.polyint(arg1, m=order, k=k)\n+ jnp_fun = lambda arg1: jnp.polyint(arg1, m=order, k=k)\n+ args_maker = lambda: [rng(a_shape, dtype)]\n+ self._CheckAgainstNumpy(np_fun, jnp_fun, args_maker, check_dtypes=False)\n+ self._CompileAndCheck(jnp_fun, args_maker, check_dtypes=True)\n+\n+\n@parameterized.named_parameters(jtu.cases_from_list(\n{\"testcase_name\": \"_shape={}_order={}\".format(\njtu.format_shape_dtype_string(a_shape, dtype),\n" } ]
Python
Apache License 2.0
google/jax
implement np.polyint (#70)
260,335
18.02.2021 09:46:16
28,800
5a97eab2a0e3a4437a0f6cb0209f0de3c335c6a3
improve error messages for grad(..., has_aux=True) fixes
[ { "change_type": "MODIFY", "old_path": "jax/api_util.py", "new_path": "jax/api_util.py", "diff": "@@ -75,7 +75,11 @@ def apply_flat_fun_nokwargs(fun, io_tree, py_args):\n@lu.transformation_with_aux\ndef flatten_fun_nokwargs2(in_tree, *args_flat):\npy_args = tree_unflatten(in_tree, args_flat)\n- ans, aux = yield py_args, {}\n+ pair = yield py_args, {}\n+ if not isinstance(pair, (list, tuple)) or len(pair) != 2:\n+ raise TypeError(\"expected function with aux output to return a two-element \"\n+ f\"tuple, but got type {type(pair)} with value {repr(pair)}\")\n+ ans, aux = pair\nans_flat, ans_tree = tree_flatten(ans)\naux_flat, aux_tree = tree_flatten(aux)\nyield (ans_flat, aux_flat), (ans_tree, aux_tree)\n" }, { "change_type": "MODIFY", "old_path": "tests/api_test.py", "new_path": "tests/api_test.py", "diff": "@@ -876,6 +876,16 @@ class APITest(jtu.JaxTestCase):\nself.assertAllClose(g, grad(lambda x: x**3)(3.))\nself.assertAllClose(aux, [9.], check_dtypes=False)\n+ def test_grad_and_aux_error(self):\n+ with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n+ grad(lambda x: (1, 2, 3), has_aux=True)(1.)\n+\n+ with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n+ grad(lambda x: x, has_aux=True)(1.)\n+\n+ with self.assertRaisesRegex(TypeError, \"two-element tuple\"):\n+ grad(lambda x: (x,), has_aux=True)(1.)\n+\ndef test_grad_and_aux_nested(self):\ndef f(x):\ng, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n@@ -2319,6 +2329,7 @@ class APITest(jtu.JaxTestCase):\nself.assertEqual(f(x), f(a))\n+\nclass RematTest(jtu.JaxTestCase):\ndef test_remat_basic(self):\n" } ]
Python
Apache License 2.0
google/jax
improve error messages for grad(..., has_aux=True) fixes #5776
260,518
19.02.2021 12:37:04
28,800
80a8204fdb90ca5201d9501a6ffe62051293f060
Update thinking_in_jax.ipynb Fix typo in notebook url.
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/thinking_in_jax.ipynb", "new_path": "docs/notebooks/thinking_in_jax.ipynb", "diff": "\"source\": [\n\"# How to Think in JAX\\n\",\n\"\\n\",\n- \"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/jax/blob/master/docs/notebooks/thinking_ind_jax.ipynb)\\n\",\n+ \"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/jax/blob/master/docs/notebooks/thinking_in_jax.ipynb)\\n\",\n\"\\n\",\n\"JAX provides a simple and powerful API for writing accelerated numerical code, but working effectively in JAX sometimes requires extra consideration. This document is meant to help build a ground-up understanding of how JAX operates, so that you can use it more effectively.\"\n]\n" } ]
Python
Apache License 2.0
google/jax
Update thinking_in_jax.ipynb Fix typo in notebook url.
260,712
19.02.2021 12:57:57
28,800
77905ef5fd72615d2fcbc7ef7eedc37988e03f80
Update build.py with Cloud TPU support Update build.py to have Cloud TPU support by default. b/180656002
[ { "change_type": "MODIFY", "old_path": "build/build.py", "new_path": "build/build.py", "diff": "@@ -271,6 +271,9 @@ build:short_logs --output_filter=DONT_MATCH_ANYTHING\n# Workaround for gcc 10+ warnings related to upb.\n# See https://github.com/tensorflow/tensorflow/issues/39467\nbuild:linux --copt=-Wno-stringop-truncation\n+\n+# Build with Cloud TPU support.\n+build --define=with_tpu_support=true\n\"\"\"\n" } ]
Python
Apache License 2.0
google/jax
Update build.py with Cloud TPU support Update build.py to have Cloud TPU support by default. b/180656002
260,518
19.02.2021 21:59:47
28,800
bb5ae556adb60398db532578b142e9d5c44d094a
Update thinking_in_jax.md
[ { "change_type": "MODIFY", "old_path": "docs/notebooks/thinking_in_jax.md", "new_path": "docs/notebooks/thinking_in_jax.md", "diff": "@@ -33,7 +33,7 @@ ipython.showtraceback = minimal_traceback\n# How to Think in JAX\n-[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/jax/blob/master/docs/notebooks/thinking_ind_jax.ipynb)\n+[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.sandbox.google.com/github/google/jax/blob/master/docs/notebooks/thinking_in_jax.ipynb)\nJAX provides a simple and powerful API for writing accelerated numerical code, but working effectively in JAX sometimes requires extra consideration. This document is meant to help build a ground-up understanding of how JAX operates, so that you can use it more effectively.\n" } ]
Python
Apache License 2.0
google/jax
Update thinking_in_jax.md
260,346
20.02.2021 18:18:32
-3,600
074abba6822a890e53a426b9b77b1fac37cb6a8a
Fix error message string interpolation
[ { "change_type": "MODIFY", "old_path": "jax/_src/numpy/lax_numpy.py", "new_path": "jax/_src/numpy/lax_numpy.py", "diff": "@@ -2568,7 +2568,7 @@ def _broadcast_to_pairs(nvals, nd, name):\nreturn tuple((nvals.flat[0], nvals.flat[0]) for i in range(nd))\nelse:\nraise ValueError(f\"{name} given unexpected structure: {nvals}. \"\n- \"See docstring for valid {name} formats.\")\n+ f\"See docstring for valid {name} formats.\")\n@partial(jit, static_argnums=(1, 2, 4, 5, 6))\n" } ]
Python
Apache License 2.0
google/jax
Fix error message string interpolation
260,346
20.02.2021 20:06:47
-3,600
5fc1730eec3c7fd734461bdf391c3fcda253e427
Also print function ID in compile reason logs.
[ { "change_type": "MODIFY", "old_path": "jax/interpreters/pxla.py", "new_path": "jax/interpreters/pxla.py", "diff": "@@ -777,8 +777,8 @@ def parallel_callable(fun: lu.WrappedFun,\nlog_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\nlogging.log(log_priority,\n- f\"Compiling {fun.__name__} for {num_global_shards} devices with \"\n- f\"args {avals}. (num_replicas={num_global_replicas} \"\n+ f\"Compiling {fun.__name__} ({id(fun)}) for {num_global_shards} \"\n+ f\"devices with args {avals}. (num_replicas={num_global_replicas}\"\nf\" num_partitions={num_partitions})\")\naxis_env = xla.AxisEnv(num_global_replicas, (axis_name,), (global_axis_size,))\n@@ -1365,7 +1365,7 @@ def mesh_callable(fun: lu.WrappedFun,\nlog_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\nlogging.log(log_priority,\n- f\"Compiling {fun.__name__} for {tuple(global_axis_sizes.items())} \"\n+ f\"Compiling {fun.__name__} ({id(fun)}) for {tuple(global_axis_sizes.items())} \"\nf\"mesh with args {local_in_untiled_avals}. Argument mapping: {in_axes}.\")\n# 1. Trace to jaxpr and preprocess/verify it\n" }, { "change_type": "MODIFY", "old_path": "jax/interpreters/xla.py", "new_path": "jax/interpreters/xla.py", "diff": "@@ -687,7 +687,8 @@ def _xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *ar\nif not _on_exit:\nlog_priority = logging.WARNING if FLAGS.jax_log_compiles else logging.DEBUG\n- logging.log(log_priority, \"Compiling %s for args %s.\", fun.__name__, abstract_args)\n+ logging.log(log_priority, \"Compiling %s (%s) for args %s.\",\n+ fun.__name__, id(fun), abstract_args)\nif nreps > 1:\nwarn(f\"The jitted function {fun.__name__} includes a pmap. Using \"\n" } ]
Python
Apache License 2.0
google/jax
Also print function ID in compile reason logs.