diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 6fbc28a7a..ecf919050 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -26,6 +26,7 @@ New Features - UltraPIPS, a perceptual metric for B-mode ultrasound built on an ultrasound foundation model: :class:`zea.models.ultrapips.UltraPIPS`, or the ``ultrapips`` metric in :mod:`zea.metrics`, used like ``lpips`` (:gh:`649` by :user:`tristan-deep`) - Transparent GIFs from RGBA frames with ``transparent=True`` in :func:`zea.io_lib.save_video` and :func:`zea.io_lib.save_to_gif` (:gh:`663` by :user:`tristan-deep`) - GIFs that play once, with ``loop=None`` in :func:`zea.io_lib.save_to_gif` (:gh:`680` by :user:`wesselvannierop`) +- :func:`zea.func.vmap` accepts nested inputs, dict axes and keyword arguments, like ``jax.vmap``, and can be nested on all backends (:gh:`692` by :user:`wesselvannierop`) - ``zea app`` can serve over HTTPS with ``--ssl-certfile`` and ``--ssl-keyfile`` (:gh:`648` by :user:`Louisvh`) - Frequency-dependent attenuation in the pressure field, with ``attenuation_coef`` in dB/(cm·MHz) in :func:`zea.beamform.pfield.compute_pfield`. It defaults to 0 (lossless) (:gh:`682` by :user:`wesselvannierop`) - :class:`zea.ops.BandPassFilter` and :class:`zea.ops.LowPassFilterIQ` take their ``bandwidth`` from the new :attr:`zea.Parameters.bandwidth`, derived as ``center_frequency * probe_bandwidth_percent / 100`` unless set or ``center_frequency`` varies across transmits (:gh:`644` by :user:`tristan-deep`) @@ -35,6 +36,7 @@ Changed - Streaming ``hf://`` datasets no longer runs into the Hugging Face rate limit, so you can train on many batches with many workers without downloading the data. The API is unchanged; two new environment variables, ``ZEA_MAX_CONCURRENT_REQUESTS`` and ``ZEA_FIND_H5_SHAPES_WORKERS``, tune it (see :doc:`environment`) (:gh:`671` by :user:`tristan-deep`) - Conversion scripts for EchoNet-Dynamic, CAMUS and PICMUS accept the ``.zip`` file itself. EchoNet-Dynamic reproduces the published split by default, and its polar conversion is about 15 times faster (:gh:`676` by :user:`wesselvannierop`) - (Breaking) In ``compute_pfield``, ``alpha`` and ``percentile`` also shape the field when ``norm=False``, the unused ``n_el`` argument is removed, and probes other than linear and phased arrays raise ``NotImplementedError`` (:gh:`657` by :user:`wesselvannierop`) +- (Breaking) :func:`zea.func.vmap` validates axes like ``jax.vmap``, so a list no longer matches a tuple. ``out_axes=None`` only works on the native ``jax.vmap``, and the ``_use_torch_vmap`` argument is removed (:gh:`692` by :user:`wesselvannierop`) - ``Parameters.copy()`` and ``set_transmits`` are much faster (:gh:`656` by :user:`wesselvannierop`) - The default ``probe_bandwidth_percent`` is 100 instead of 200, which also narrows the band used by ``compute_pfield`` (:gh:`644` by :user:`tristan-deep`) diff --git a/tests/test_tensor_ops.py b/tests/test_tensor_ops.py index 213dfe262..73d86b35a 100644 --- a/tests/test_tensor_ops.py +++ b/tests/test_tensor_ops.py @@ -494,11 +494,11 @@ def test_correlate(mode): ["multiply", (0, None), 0, 3, None, False], # batched map ["dummy", (0, None), 0, 3, None, True], # batched map ["dummy", (0, 1), 0, None, 5, True], # chunked map - ["multiple_out", (1, None), (1, None), None, 4, False], # chunked map with multiple outputs + ["multiple_out", (1, 1), (1, 0), None, 4, False], # chunked map with multiple outputs [ "multiple_out", - (1, None), - (1, None), + (1, 1), + (1, 0), None, None, False, @@ -724,7 +724,6 @@ def func(*fn_args): "out_axes_negative_2", "out_axes_per_output", "out_axes_per_output_with_none_output", - "out_axes_none", "out_axes_nested", "out_axes_prefix", "in_axes_1", @@ -781,11 +780,6 @@ def test_vmap_matches_jax(case, vmap_kwargs): (a,), {"out_axes": (1, 0, 0)}, ), - "out_axes_none": ( - lambda a, b: (a, b), - (a, b[0]), - {"in_axes": (0, None), "out_axes": (0, None)}, - ), "out_axes_nested": (lambda a: (a, (a, a + 1)), (a,), {"out_axes": (0, (1, 0))}), "out_axes_prefix": (lambda a: (a, (a, a + 1)), (a,), {"out_axes": (0, 1)}), "in_axes_1": (lambda a: (a, a + 1), (a.T,), {"in_axes": 1}), @@ -853,6 +847,294 @@ def test_vmap_raises_like_jax(case, vmap_kwargs): zea.func.vmap(fun, **axes, **vmap_kwargs)(*[ops.convert_to_tensor(arg) for arg in args]) +# These functions also work on a whole batch. +_VMAP_DEFAULT_AXES_INPUT_CASES = [ + "dict_input", + "tuple_input", + "list_input", + "nested_input", + "none_in_dict_input", + "none_after_nested_input", + "keyword", + "only_keywords", + "nested_keyword", +] +_VMAP_AXES_INPUT_CASES = [ + "dict_in_axes", + "dict_in_axes_unsorted_keys", + "dict_in_axes_unmapped", + "tuple_in_axes", + "int_for_container", + "none_for_container", + "in_axes_list", + "keyword_with_in_axes", + "dict_out_axes", +] + + +@pytest.mark.parametrize( + "case, vmap_kwargs", + [ + (case, kwargs) + for case in _VMAP_DEFAULT_AXES_INPUT_CASES + for kwargs in _VMAP_PATHS + _VMAP_BATCH_PATHS + ] + + [(case, kwargs) for case in _VMAP_AXES_INPUT_CASES for kwargs in _VMAP_PATHS], +) +@backend_equality_check(allow_none=True) +def test_vmap_inputs_match_jax(case, vmap_kwargs): + """`vmap` should accept the same inputs and axes as `jax.vmap`, with the same results.""" + import jax + import keras + from keras import ops + + import zea + + a = np.arange(15, dtype="float32").reshape(5, 3) + b = a + 100 + c = a + 200 + + fun, args, kwargs, axes = { + "dict_input": (lambda d: d["x"] - d["y"], ({"x": a, "y": b},), {}, {}), + "tuple_input": (lambda t: t[0] - t[1], ((a, b),), {}, {}), + "list_input": (lambda t: [t[1], t[0] + 1], ([a, b],), {}, {}), + "nested_input": (lambda d: d["x"][1][0] - d["y"], ({"x": (a, [b]), "y": c},), {}, {}), + "none_in_dict_input": (lambda d: (d["x"], d["y"]), ({"x": a, "y": None},), {}, {}), + "none_after_nested_input": ( + lambda d, n, m, c: (d["x"] - c, n, m), + ({"x": a}, None, None, b), + {}, + {}, + ), + "keyword": (lambda x, y: x - y, (a,), {"y": b}, {}), + "only_keywords": (lambda x, y: x - y, (), {"y": b, "x": a}, {}), + "nested_keyword": (lambda x, y: x - y["z"], (a,), {"y": {"z": b}}, {}), + "dict_in_axes": ( + lambda d: d["x"] - d["y"], + ({"x": a, "y": b.T},), + {}, + {"in_axes": ({"x": 0, "y": 1},)}, + ), + # Leaves are sorted by key, which should not mix up the axes. + "dict_in_axes_unsorted_keys": ( + lambda d: d["z"] - d["a"], + ({"z": a.T, "a": b},), + {}, + {"in_axes": ({"z": 1, "a": 0},)}, + ), + "dict_in_axes_unmapped": ( + lambda d, e: d["x"] - d["y"] + e, + ({"x": a, "y": b[0]}, c[0]), + {}, + {"in_axes": ({"x": 0, "y": None}, None)}, + ), + "tuple_in_axes": ( + lambda t: t[0] - t[1][0], + ((a, (b.T,)),), + {}, + {"in_axes": ((0, (1,)),)}, + ), + "int_for_container": ( + lambda d: d["x"] - d["y"], + ({"x": a.T, "y": b.T},), + {}, + {"in_axes": (1,)}, + ), + "none_for_container": ( + lambda d, e: d["x"] - d["y"] + e, + ({"x": a[0], "y": b[0]}, c), + {}, + {"in_axes": (None, 0)}, + ), + "in_axes_list": (lambda x, y: x - y, (a, b[0]), {}, {"in_axes": [0, None]}), + "keyword_with_in_axes": (lambda x, y: x - y, (a.T,), {"y": b}, {"in_axes": (1,)}), + "dict_out_axes": ( + lambda x: {"y": x, "x": (x + 1, x + 2)}, + (a,), + {}, + {"out_axes": {"y": 1, "x": (0, -1)}}, + ), + }[case] + + def to_tensor(x): + return None if x is None else ops.convert_to_tensor(x) + + expected = jax.vmap(fun, **axes)(*args, **kwargs) + tensor_args, tensor_kwargs = keras.tree.map_structure(to_tensor, (args, kwargs)) + result = zea.func.vmap(fun, **axes, **vmap_kwargs)(*tensor_args, **tensor_kwargs) + result = keras.tree.map_structure( + lambda x: None if x is None else ops.convert_to_numpy(x), result + ) + + assert jax.tree.structure(result) == jax.tree.structure(expected) + jax.tree.map(lambda x, y: np.testing.assert_allclose(x, y), result, expected) + + return jax.tree.leaves(result)[-1] + + +@pytest.mark.parametrize("vmap_kwargs", _VMAP_PATHS) +@backend_equality_check() +def test_vmap_unmapped_numpy_input(vmap_kwargs): + """Unmapped numpy inputs should work with tensors in `fun` on all backends.""" + from keras import ops + + import zea + + a = np.arange(15, dtype="float32").reshape(5, 3) + b = a[0] + 100 + + result = zea.func.vmap(lambda x, y: x - y, in_axes=(0, None), **vmap_kwargs)( + ops.convert_to_tensor(a), b + ) + + result = ops.convert_to_numpy(result) + np.testing.assert_allclose(result, a - b) + return result + + +@pytest.mark.parametrize("vmap_kwargs", _VMAP_PATHS + _VMAP_BATCH_PATHS) +@backend_equality_check(allow_none=True) +def test_vmap_out_axes_none(vmap_kwargs): + """`out_axes=None` needs the native `jax.vmap`, which can check that an output is unmapped.""" + import jax + import keras + from keras import ops + + import zea + + a = np.arange(15, dtype="float32").reshape(5, 3) + b = a[0] + 100 + fun = lambda a, b: (a, b) # noqa: E731 + axes = {"in_axes": (0, None), "out_axes": (0, None)} + args = (ops.convert_to_tensor(a), ops.convert_to_tensor(b)) + + is_native = ( + keras.backend.backend() == "jax" + and not vmap_kwargs.get("disable_jit", False) + and not vmap_kwargs.get("fn_supports_batch", False) + ) + if not is_native: + with pytest.raises(ValueError, match="out_axes=None"): + zea.func.vmap(fun, **axes, **vmap_kwargs) + return None + + expected = jax.vmap(fun, **axes)(a, b) + result = zea.func.vmap(fun, **axes, **vmap_kwargs)(*args) + jax.tree.map(lambda x, y: np.testing.assert_allclose(x, y), result, expected) + with pytest.raises(ValueError): + zea.func.vmap(lambda a: a, out_axes=None, **vmap_kwargs)(args[0]) + return None + + +@pytest.mark.parametrize("vmap_kwargs", _VMAP_PATHS) +@pytest.mark.parametrize( + "case", + [ + "in_axes_too_long", + "in_axes_too_short", + "in_axes_wrong_keys", + "in_axes_missing_keys", + "in_axes_list_for_tuple", + "in_axes_tuple_for_list", + "in_axis_out_of_bounds", + "out_axes_list_for_tuple", + "out_axes_tuple_for_list", + "out_axes_wrong_keys", + "nested_different_lengths", + ], +) +@backend_equality_check(allow_none=True) +def test_vmap_invalid_axes_raise_like_jax(case, vmap_kwargs): + """Axes that do not match the inputs or outputs should raise, as in `jax.vmap`.""" + import jax + import keras + from keras import ops + + import zea + + a = np.arange(15, dtype="float32").reshape(5, 3) + + fun, args, axes = { + "in_axes_too_long": (lambda x: x, (a,), {"in_axes": (0, 0)}), + "in_axes_too_short": (lambda x, y: x, (a, a), {"in_axes": (0,)}), + "in_axes_wrong_keys": (lambda d: d["x"], ({"x": a},), {"in_axes": ({"y": 0},)}), + "in_axes_missing_keys": (lambda d: d["x"], ({"x": a, "y": a},), {"in_axes": ({"x": 0},)}), + "in_axes_list_for_tuple": (lambda t: t[0], ((a, a),), {"in_axes": ([0, 0],)}), + "in_axes_tuple_for_list": (lambda t: t[0], ([a, a],), {"in_axes": ((0, 0),)}), + "in_axis_out_of_bounds": (lambda x: x, (a,), {"in_axes": 5}), + "out_axes_list_for_tuple": (lambda x: (x, x), (a,), {"out_axes": [0, 0]}), + "out_axes_tuple_for_list": (lambda x: [x, x], (a,), {"out_axes": (0, 0)}), + "out_axes_wrong_keys": (lambda x: {"x": x}, (a,), {"out_axes": {"y": 0}}), + "nested_different_lengths": (lambda d: d["x"], ({"x": a, "y": a[:3]},), {}), + }[case] + + with pytest.raises(ValueError): + jax.vmap(fun, **axes)(*args) + tensor_args = keras.tree.map_structure(ops.convert_to_tensor, args) + with pytest.raises(ValueError): + zea.func.vmap(fun, **axes, **vmap_kwargs)(*tensor_args) + + +@pytest.mark.parametrize("chunks", [None, 1]) +def test_vmap_out_axes_none_fn_supports_batch_fast_path(chunks): + """`out_axes=None` should also raise when `fn_supports_batch` would return `fun` as is.""" + import zea + + with pytest.raises(ValueError, match="out_axes=None"): + zea.func.vmap(lambda x: x, out_axes=None, fn_supports_batch=True, chunks=chunks) + + +@pytest.mark.parametrize("inner_kwargs", _VMAP_PATHS) +@pytest.mark.parametrize("outer_kwargs", _VMAP_PATHS) +@backend_equality_check() +def test_vmap_nested(outer_kwargs, inner_kwargs): + """`vmap` can be nested, also with moved axes, unmapped and `None` arguments and outputs.""" + import jax + from keras import ops + + import zea + + a = np.arange(24, dtype="float32").reshape(2, 3, 4) + b = np.arange(4, dtype="float32") + fun = lambda x, y, z: (x * y, None) # noqa: E731 + inner = {"in_axes": (1, 0, None), "out_axes": (-1, 0)} + outer = {"in_axes": (0, None, None)} + + expected = jax.vmap(jax.vmap(fun, **inner), **outer)(a, b, None) + inner_fn = zea.func.vmap(fun, **inner, **inner_kwargs) + result = zea.func.vmap(inner_fn, **outer, **outer_kwargs)( + ops.convert_to_tensor(a), ops.convert_to_tensor(b), None + ) + assert result[1] is None + result = ops.convert_to_numpy(result[0]) + np.testing.assert_allclose(result, expected[0]) + return result + + +@pytest.mark.parametrize( + "axes", + [ + {"in_axes": True}, + {"in_axes": 0.0}, + {"in_axes": np.int64(0)}, + {"in_axes": {"x": 0}}, + {"in_axes": ("a",)}, + {"out_axes": ("a",)}, + {"out_axes": 0.0}, + ], +) +def test_vmap_invalid_axis_types_raise_like_jax(axes): + """Only integers and `None` are valid axes, as in `jax.vmap`.""" + import jax + + import zea + + with pytest.raises(TypeError): + jax.vmap(lambda x: x, **axes) + with pytest.raises(TypeError): + zea.func.vmap(lambda x: x, **axes) + + @backend_equality_check() def test_simple_map_one_input(): """Test the `zea` `simple_map` function against `keras.ops.map`.""" diff --git a/zea/func/tensor.py b/zea/func/tensor.py index 71d64cf3a..a9a0bd5a9 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -370,28 +370,27 @@ def simple_map(function, elements): if keras.backend.backend() == "numpy": def vectorized_map(function, elements): - """Fixes keras.ops.vectorized_map in numpy backend with multiple outputs.""" - if not isinstance(elements, (list, tuple)): - return np.stack([function(x) for x in elements]) - else: - batch_size = elements[0].shape[0] - output_store = [] - for index in range(batch_size): - output_store.append(function([x[index] for x in elements])) - if isinstance(output_store[0], (list, tuple)): - return [np.stack(tensors) for tensors in zip(*output_store)] - else: - return np.stack(output_store) + """Fixes keras.ops.vectorized_map in numpy backend with multiple outputs. + + Only used by `_map`, which passes and returns a tuple of tensors. + """ + outputs = [function([x[i] for x in elements]) for i in range(elements[0].shape[0])] + return [np.stack(tensors) for tensors in zip(*outputs)] else: vectorized_map = ops.vectorized_map -def _find_map_length(args, in_axes) -> int: - """Find the length of the axis to map over, which all mapped arguments should share.""" +def _is_mapped(leaf, axis) -> bool: + """Whether an input leaf is mapped over: `None` leaves and axes are not.""" + return leaf is not None and axis is not None + + +def _find_map_length(leaves, axes) -> int: + """Find the length of the axis to map over, which all mapped leaves should share.""" lengths = [ - ops.shape(arg)[axis] - for arg, axis in zip(args, in_axes) - if axis is not None and arg is not None + ops.shape(leaf)[canonicalize_axis(axis, ops.ndim(leaf))] + for leaf, axis in zip(leaves, axes) + if _is_mapped(leaf, axis) ] if not lengths: raise ValueError("At least one in_axes must be non-None to determine map length.") @@ -403,38 +402,53 @@ def _find_map_length(args, in_axes) -> int: return lengths[0] -def _flatten_out_axes(out_axes, outputs) -> list: - """Get the output axis of each leaf in `outputs`, in the order of `keras.tree.flatten`. +def _flatten_axes(axes, tree, name: str) -> list: + """Get the axis of each leaf in `tree`, in the order of `keras.tree.flatten`. - Like in `jax.vmap`, an int or None applies to all leaves below it. + Like in `jax.vmap`, `axes` should be a prefix of `tree`: an int or None applies to all leaves + below it, and a container should match the type and the length or keys of the one in `tree`. """ - if isinstance(out_axes, int) or out_axes is None: - return [out_axes] * len(keras.tree.flatten(outputs)) - if ( - isinstance(out_axes, (tuple, list)) - and isinstance(outputs, (tuple, list)) - and len(out_axes) == len(outputs) - ): - return [ - leaf_axis - for out_axis, output in zip(out_axes, outputs) - for leaf_axis in _flatten_out_axes(out_axis, output) - ] - raise ValueError(f"out_axes={out_axes} does not match the structure of the function outputs.") + if isinstance(axes, int) or axes is None: + return [axes] * len(keras.tree.flatten(tree)) + if isinstance(axes, dict) and isinstance(tree, dict) and axes.keys() == tree.keys(): + return [leaf for key in sorted(tree) for leaf in _flatten_axes(axes[key], tree[key], name)] + for container in (tuple, list): + if isinstance(axes, container) and isinstance(tree, container) and len(axes) == len(tree): + return [leaf for ax, sub in zip(axes, tree) for leaf in _flatten_axes(ax, sub, name)] + raise ValueError(f"{name}={axes} does not match the structure of the corresponding values.") + + +def _flatten_inputs(args, kwargs, in_axes) -> Tuple[list, list]: + """Get the input leaves and their axes. Like in `jax.vmap`, keywords map over axis 0.""" + if isinstance(in_axes, tuple) and len(in_axes) != len(args): + raise ValueError( + f"in_axes should have an entry per positional argument, got {len(in_axes)} entries " + f"for {len(args)} arguments." + ) + tree = (args, kwargs) + return keras.tree.flatten(tree), _flatten_axes((in_axes, 0), tree, "in_axes") + + +def _check_axes(axes, name: str) -> None: + """Like `jax.vmap`, only accept plain integers and `None` as axes.""" + for axis in keras.tree.flatten(axes): + if axis is not None and type(axis) is not int: + raise TypeError(f"{name} should only contain integers and None, got {axes}.") -def _repeat_int_to_tuple(value, length: int) -> Tuple[Union[int, None], ...]: - """Convert an int or None to a tuple of length `length`.""" - if isinstance(value, int) or value is None: - return (value,) * length - elif isinstance(value, (tuple, list)): - if len(value) != length: - raise ValueError(f"Expected sequence of length {length}, got {len(value)}.") - return tuple(value) - raise ValueError("Value must be an int, None, or a tuple or list.") +def _moveaxis(x, source: int, destination: int): + """`ops.moveaxis` that also works when nested in `torch.vmap`, which has no batching rule for + `aten::moveaxis.int`.""" + ndim = ops.ndim(x) + source, destination = canonicalize_axis(source, ndim), canonicalize_axis(destination, ndim) + if source == destination: + return x + perm = [i for i in range(ndim) if i != source] + perm.insert(destination, source) + return ops.transpose(x, perm) -def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): +def _map(fun, in_axes=0, out_axes=0, map_fn=None): """Mapping function, vectorized by default. For jax, this uses the native vmap implementation. @@ -445,16 +459,11 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): Args: fun: The function to be mapped. - in_axes: The axis or axes to be mapped over in the input. - Can be an integer, a tuple of integers, or None. - If None, the corresponding argument is not mapped over. - Defaults to 0. - out_axes: The axis or axes to be mapped over in the output. - Can be an integer, a tuple of integers, or None. - If None, the corresponding output is not mapped over. + in_axes: The axis or axes to be mapped over in the input, see `zea.func.vmap`. Defaults to 0. + out_axes: The axis or axes to be mapped over in the output, see `zea.func.vmap`. + Only the native jax vmap supports `None`. Defaults to 0. map_fn: The mapping function to use. If None, defaults to `ops.vectorized_map`. - _use_torch_vmap: If True, uses PyTorch's native vmap implementation. Returns: A function that applies `fun` (in a vectorized manner) over the specified axes. @@ -466,95 +475,74 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): return jax.vmap(fun, in_axes=in_axes, out_axes=out_axes) - # Use native vmap for PyTorch backend when map_fn is not provided and _use_torch_vmap is True - if keras.backend.backend() == "torch" and map_fn is None and _use_torch_vmap: - import torch - - return torch.vmap(fun, in_dims=in_axes, out_dims=out_axes) - # Default to keras vectorized_map if map_fn not provided if map_fn is None: map_fn = vectorized_map - def _moveaxes(args, in_axes, out_axes) -> tuple: - """Move axes of the input arguments.""" - args = list(args) - new_args = [] - map_length = _find_map_length(args, in_axes) - for arg, in_axis, out_axis in zip(args, in_axes, out_axes, strict=True): - if arg is None: - # filter out None arguments - continue - if out_axis is None: - new_args.append(ops.take(arg, 0, axis=in_axis)) - elif in_axis is not None: - new_args.append(ops.moveaxis(arg, in_axis, out_axis)) - else: - new_args.append( - ops.repeat(ops.expand_dims(arg, out_axis), map_length, axis=out_axis) - ) - return tuple(new_args) - - def _partial_at(func, idx, value) -> Callable[..., Any]: - """Return a new function with value inserted at index idx in args.""" - - def wrapper(*args, **kwargs): - args = list(args) - args[idx:idx] = [value] - return func(*args, **kwargs) - - return wrapper - - def mapped_wrapper(*args): - _in_axes = _repeat_int_to_tuple(in_axes, len(args)) + def mapped_wrapper(*args, **kwargs): + tree = (args, kwargs) + leaves, leaf_axes = _flatten_inputs(args, kwargs, in_axes) + # Unmapped arrays are passed on as they are, and not all backends can mix them with tensors + leaves = [ + ops.convert_to_tensor(leaf) if isinstance(leaf, (np.ndarray, np.generic)) else leaf + for leaf in leaves + ] + _find_map_length(leaves, leaf_axes) # Checks that the mapped leaves share their length - # Move mapped axes to front - zeros = (0,) * len(args) - none_indexes = [i for i, arg in enumerate(args) if arg is None] - args = _moveaxes(args, _in_axes, zeros) + # `tf.vectorized_map` can not return a captured eager tensor as it is, so wrap the outputs + # in `tf.identity` there + identity_outputs = keras.backend.backend() == "tensorflow" and map_fn is vectorized_map - # Build function with None arguments prefilled. The last wrapper created runs first, - # so wrap in reverse order to insert the None arguments from the lowest index up. - _prefilled_none_fn = fun - for none_idx in reversed(none_indexes): - _prefilled_none_fn = _partial_at(_prefilled_none_fn, none_idx, None) + # Map over the tensors with a mapped axis only, the other leaves are kept as they are + mapped_ids, elements = [], [] + for i, (leaf, axis) in enumerate(zip(leaves, leaf_axes)): + if _is_mapped(leaf, axis): + mapped_ids.append(i) + elements.append(_moveaxis(leaf, axis, 0)) + elements = tuple(elements) # Not all map functions support nested or None outputs, so map over the tensors only is_none = None - def _fun(args): + def _fun(elements): nonlocal is_none - outputs = _prefilled_none_fn(*args) + fn_leaves = list(leaves) + for i, element in zip(mapped_ids, elements): + fn_leaves[i] = element + fn_args, fn_kwargs = keras.tree.pack_sequence_as(tree, fn_leaves) + outputs = fun(*fn_args, **fn_kwargs) is_none = keras.tree.map_structure(lambda output: output is None, outputs) tensors = [output for output in keras.tree.flatten(outputs) if output is not None] + if identity_outputs: + import tensorflow as tf + + tensors = [tf.identity(tensor) for tensor in tensors] # Map functions need at least one output, also when the function only returns None return tuple(tensors) or (ops.zeros(()),) - mapped = keras.tree.flatten(map_fn(_fun, tuple(args))) + mapped = iter(keras.tree.flatten(map_fn(_fun, elements))) - # Move mapped axes back to original position - leaf_is_none = keras.tree.flatten(is_none) - leaf_out_axes = _flatten_out_axes(out_axes, is_none) - _out_axes = [axis for axis, none in zip(leaf_out_axes, leaf_is_none) if not none] - if _out_axes: - mapped = iter(_moveaxes(mapped, (0,) * len(mapped), _out_axes)) - - # Restore the structure of the outputs, with the None outputs in place - leaves = [None if none else next(mapped) for none in leaf_is_none] - return keras.tree.pack_sequence_as(is_none, leaves) + # Restore the structure of the outputs, with the None outputs in place and the mapped + # axes back at their position + new_leaves = [ + None if none else _moveaxis(next(mapped), 0, axis) + for none, axis in zip( + keras.tree.flatten(is_none), _flatten_axes(out_axes, is_none, "out_axes") + ) + ] + return keras.tree.pack_sequence_as(is_none, new_leaves) return mapped_wrapper def vmap( fun: Callable[..., Any], - in_axes: Sequence[int | None] | int = 0, - out_axes: Sequence[int | None] | int = 0, + in_axes: Any = 0, + out_axes: Any = 0, chunks: int | None = None, batch_size: int | None = None, fn_supports_batch: bool = False, disable_jit: bool = False, - _use_torch_vmap: bool = False, ): """`vmap` with batching or chunking support to avoid memory issues. @@ -562,26 +550,31 @@ def vmap( to avoid memory issues with large inputs. Choose the `batch_size` or `chunks` wisely, because it pads the input to make it divisible, and then crop the output back to the original size. - Follows `jax.vmap` for outputs. `fun` can return any number of outputs, also more than it - has inputs, and nested tuples, lists and dicts. `None` outputs stay in place. Unlike `jax.vmap`, - the inputs should be tensors or `None`, so nested inputs are not supported. + Follows `jax.vmap` on all backends. The inputs and outputs of `fun` can be tensors, `None`, or + nested tuples, lists and dicts of those. Keyword arguments are mapped over axis 0. The only + difference is `out_axes=None`, see below. Args: fun: Function to be mapped. - in_axes: Axis or axes to be mapped over in the input. + in_axes: Axis or axes to be mapped over in the input. An integer or `None` applies to all + inputs below it, with `None` meaning that they are not mapped over. Otherwise, a tuple + or list with an entry per positional argument, where each entry can also be a container + that matches the structure of that argument, such as `({"x": 0, "y": None},)`. out_axes: Axis or axes to be mapped over in the output. An integer or `None` applies to - all outputs below it, and a tuple or list should match the structure of the outputs. + all outputs below it, and a tuple, list or dict should match the structure of the + outputs. `None` keeps an output that does not depend on the mapped axis unmapped. It + is only supported by the native `jax.vmap`, which can check that dependency, so it + raises an error on other backends, with `disable_jit` and with `fn_supports_batch`. batch_size: Size of the batch for each step. If `None`, the function will be equivalent to `vmap`. If `1`, will be equivalent to `map`. Mutually exclusive with `chunks`. chunks: Number of chunks to split the input into. If `None` or `1`, the function will be equivalent to `vmap`. Mutually exclusive with `batch_size`. fn_supports_batch: If True, assumes that `fun` can already handle batched inputs. In this case, this function will only handle padding and reshaping for batching. + Unlike in `jax.vmap`, `in_axes` and `out_axes` then do not move any axes: `fun` + should take its batch at `in_axes` and return it at `out_axes` itself. disable_jit: If True, disables JIT compilation for backends that support it. This can be useful for debugging. Will fall back to simple mapping. - _use_torch_vmap: If True, uses PyTorch's native vmap implementation. - Advantage: you can apply `vmap` multiple times without issues. - Disadvantage: does not support None arguments. Returns: A function that applies `fun` in a batched manner over the specified axes. """ @@ -596,56 +589,78 @@ def vmap( if chunks is not None: assert chunks > 0, "chunks must be greater than 0." + # Like in `jax.vmap`, the outer container has an entry per positional argument + if isinstance(in_axes, list): + in_axes = tuple(in_axes) + if not (in_axes is None or type(in_axes) in (int, tuple)): + raise TypeError( + f"in_axes should be an integer, None, or a tuple or list with an entry per " + f"positional argument, got {in_axes}." + ) + _check_axes(in_axes, "in_axes") + _check_axes(out_axes, "out_axes") + + # Other map functions stack all results, so they can not check that an output is really + # unmapped. Without this check, a mapped output would silently be reduced to its first element. + native_jax_vmap = keras.backend.backend() == "jax" and not disable_jit and not fn_supports_batch + if not native_jax_vmap and None in keras.tree.flatten(out_axes): + raise ValueError( + "out_axes=None is only supported by the native `jax.vmap`, so on the jax backend " + "without `disable_jit` and `fn_supports_batch`." + ) + no_chunks_or_batch = batch_size is None and (chunks is None or chunks == 1) if fn_supports_batch and no_chunks_or_batch: return fun - if not fn_supports_batch: - # vmap to support batches - fun = _map( - fun, - in_axes=in_axes, - out_axes=out_axes, - map_fn=None if not disable_jit else simple_map, - _use_torch_vmap=_use_torch_vmap, - ) + # vmap to support batches + vmap_fun = _map( + fun, in_axes=in_axes, out_axes=out_axes, map_fn=None if not disable_jit else simple_map + ) if no_chunks_or_batch: - return fun + return vmap_fun + + batch_fun = fun if fn_supports_batch else vmap_fun # map (sequentially) to support batches/chunks that fit in memory map_fn = ops.map if not disable_jit else simple_map - def batched_fun(*args): - _in_axes = _repeat_int_to_tuple(in_axes, len(args)) - total_length = _find_map_length(args, _in_axes) + def batched_fun(*args, **kwargs): + tree = (args, kwargs) + leaves, leaf_axes = _flatten_inputs(args, kwargs, in_axes) + total_length = _find_map_length(leaves, leaf_axes) if chunks is not None: _batch_size = np.ceil(total_length / chunks).astype(int) else: _batch_size = batch_size - new_args = [] - batch_in_axes = [] - for arg, in_axis in zip(args, _in_axes): - if in_axis is None or arg is None: - new_args.append(arg) - batch_in_axes.append(in_axis) + new_leaves = [] + batch_axes = [] + for leaf, axis in zip(leaves, leaf_axes): + if not _is_mapped(leaf, axis): + new_leaves.append(leaf) + batch_axes.append(axis) continue # Non-negative, because reshaping adds an axis - in_axis = canonicalize_axis(in_axis, ops.ndim(arg)) - padded_arg = pad_array_to_divisible(arg, _batch_size, axis=in_axis) - reshaped_arg = reshape_axis(padded_arg, (-1, _batch_size), axis=in_axis) - new_args.append(reshaped_arg) - batch_in_axes.append(in_axis) + axis = canonicalize_axis(axis, ops.ndim(leaf)) + padded_leaf = pad_array_to_divisible(leaf, _batch_size, axis=axis) + new_leaves.append(reshape_axis(padded_leaf, (-1, _batch_size), axis=axis)) + batch_axes.append(axis) + + new_args, new_kwargs = keras.tree.pack_sequence_as(tree, new_leaves) + batch_in_axes, _ = keras.tree.pack_sequence_as(tree, batch_axes) # The leading axis of each output are the batches - outputs = _map(fun, in_axes=tuple(batch_in_axes), out_axes=0, map_fn=map_fn)(*new_args) + outputs = _map(batch_fun, in_axes=batch_in_axes, out_axes=0, map_fn=map_fn)( + *new_args, **new_kwargs + ) new_outputs = [] leaves = keras.tree.flatten(outputs) - for output, out_axis in zip(leaves, _flatten_out_axes(out_axes, outputs)): + for output, out_axis in zip(leaves, _flatten_axes(out_axes, outputs, "out_axes")): if output is None: new_outputs.append(None) continue @@ -654,7 +669,7 @@ def batched_fun(*args): continue # Put the batches right before the samples in each batch, then merge the two out_axis = canonicalize_axis(out_axis, ops.ndim(output) - 1) - reshaped_output = ops.moveaxis(output, 0, out_axis) + reshaped_output = _moveaxis(output, 0, out_axis) reshaped_output = flatten(reshaped_output, start_dim=out_axis, end_dim=out_axis + 1) cropped_output = ops.take(reshaped_output, ops.arange(total_length), axis=out_axis) new_outputs.append(cropped_output) @@ -1753,9 +1768,9 @@ def apply_along_axis(func1d, axis, arr, *args, **kwargs): axis = canonicalize_axis(axis, num_dims) func = lambda arr: func1d(arr, *args, **kwargs) for i in range(1, num_dims - axis): - func = vmap(func, in_axes=i, out_axes=-1, _use_torch_vmap=True) + func = vmap(func, in_axes=i, out_axes=-1) for i in range(axis): - func = vmap(func, in_axes=0, out_axes=0, _use_torch_vmap=True) + func = vmap(func, in_axes=0, out_axes=0) return func(arr) diff --git a/zea/metrics.py b/zea/metrics.py index ef4944c59..f3487f3f3 100644 --- a/zea/metrics.py +++ b/zea/metrics.py @@ -433,7 +433,7 @@ def _call_metric_fn( return_numpy, device, mapped_batch_size=None, - _use_torch_vmap=True, + torch_vmappable=True, ): num_batch_axes = max(0, ops.ndim(y_true) - 3) @@ -447,11 +447,10 @@ def _call_metric_fn( # disable_jit only when on the torch backend and the metric is not # torch-vmappable (e.g. LPIPS), so that other backends (JAX, etc.) # still benefit from their native vmap / vectorized_map paths. - disable_jit = not _use_torch_vmap and keras.backend.backend() == "torch" + disable_jit = not torch_vmappable and keras.backend.backend() == "torch" metric_fn = tensor.vmap( metric_fn, in_axes=0, - _use_torch_vmap=_use_torch_vmap, disable_jit=disable_jit, batch_size=mapped_batch_size, ) @@ -510,7 +509,7 @@ def __call__( return_numpy, device, mapped_batch_size=mapped_batch_size, - _use_torch_vmap=self.torch_vmappable[name], + torch_vmappable=self.torch_vmappable[name], ) return results diff --git a/zea/ops/pipeline.py b/zea/ops/pipeline.py index b16b63ecd..a7981c539 100644 --- a/zea/ops/pipeline.py +++ b/zea/ops/pipeline.py @@ -1096,7 +1096,7 @@ def __init__( operations: List[Operation], argnames: List[str] | str, in_axes: List[Union[int, None]] | int = 0, - out_axes: List[Union[int, None]] | int = 0, + out_axes: int = 0, chunks: int | None = None, batch_size: int | None = None, **kwargs, @@ -1108,8 +1108,7 @@ def __init__( Can also be a single string if only one argument is mapped over. in_axes (int or list): Axes to map over for each argument. If a single int is provided, it is used for all arguments. - out_axes (int or list): Axes to map over for each output. - If a single int is provided, it is used for all outputs. + out_axes (int): Axis of the output to map over. chunks (int, optional): Number of chunks to split the input data into. If None, no chunking is performed. Mutually exclusive with ``batch_size``. batch_size (int, optional): Size of batches to process at once.