From afbce871a4da5d32d3915a9abf636e6de4f40705 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:16:11 +0000 Subject: [PATCH 1/9] Support nested inputs and match `jax.vmap` axes in `vmap` Flatten inputs and outputs through one helper, so nested tuples, lists and dicts work as inputs on all backends and with batching. `in_axes` and `out_axes` can be containers with dicts, and keyword arguments map over axis 0. This replaces the index bookkeeping for `None` arguments. Add `axis_size`. Validate axes like `jax.vmap`: only plain integers and `None`, in containers that match the type and length or keys of the values. Raise for `out_axes=None` unless it runs on the native `jax.vmap`. Other map functions stack all results and can not check that an output is really unmapped, so a mapped output was silently reduced to its first element. --- docs/source/changelog.rst | 2 + tests/test_tensor_ops.py | 275 +++++++++++++++++++++++++++++++++++-- zea/func/tensor.py | 280 ++++++++++++++++++++++---------------- 3 files changed, 427 insertions(+), 130 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 6fbc28a7a..09fe37beb 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 ``in_axes`` and ``out_axes``, keyword arguments and ``axis_size`` on all backends and with batching, like ``jax.vmap`` (:gh:`PRNUM` 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` raises an error for ``out_axes=None`` unless it runs on the native ``jax.vmap``; other paths silently kept only the first element of a mapped output. Axes are also validated like in ``jax.vmap``: only plain integers and ``None``, in containers that match the inputs or outputs, so a list no longer matches a tuple (:gh:`PRNUM` 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..163d5a883 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,269 @@ 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", + "axis_size", + "axis_size_without_mapped_inputs", +] + + +@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)}}, + ), + "axis_size": (lambda x: x + 1, (a,), {}, {"axis_size": 5}), + "axis_size_without_mapped_inputs": ( + lambda x: x + 1, + (a[0],), + {}, + {"in_axes": None, "axis_size": 5}, + ), + }[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", + "axis_size_mismatch", + "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}}), + "axis_size_mismatch": (lambda x: x, (a,), {"axis_size": 4}), + "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( + "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..485a85bbd 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -386,12 +386,18 @@ def vectorized_map(function, elements): 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.""" - lengths = [ - ops.shape(arg)[axis] - for arg, axis in zip(args, in_axes) - if axis is not None and arg is not None +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, axis_size=None) -> int: + """Find the length of the axis to map over, which all mapped leaves should share.""" + lengths = [] if axis_size is None else [axis_size] + lengths += [ + 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 +409,41 @@ 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 _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 _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 _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, _use_torch_vmap=False, axis_size=None): """Mapping function, vectorized by default. For jax, this uses the native vmap implementation. @@ -445,16 +454,13 @@ 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. + axis_size: The length of the axis to map over. If None, inferred from the inputs. Returns: A function that applies `fun` (in a vectorized manner) over the specified axes. @@ -464,96 +470,86 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): if keras.backend.backend() == "jax" and map_fn is None: import jax - return jax.vmap(fun, in_axes=in_axes, out_axes=out_axes) + return jax.vmap(fun, in_axes=in_axes, out_axes=out_axes, axis_size=axis_size) # 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 + if axis_size is not None: + raise ValueError("axis_size is not supported with _use_torch_vmap=True.") 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)) - - # 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) - - # 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) + 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 + ] + map_length = _find_map_length(leaves, leaf_axes, axis_size) + + # `tf.vectorized_map` can not return a captured eager tensor, so also map over unmapped + # tensors there, by repeating them + repeat_unmapped = keras.backend.backend() == "tensorflow" and map_fn is vectorized_map + + # 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(ops.moveaxis(leaf, axis, 0)) + elif repeat_unmapped and ops.is_tensor(leaf): + mapped_ids.append(i) + elements.append(ops.repeat(ops.expand_dims(leaf, 0), map_length, axis=0)) + elements = tuple(elements) + # Map functions need at least one input, also when only `axis_size` is given + elements = elements or (ops.arange(map_length),) # 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] # 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))) - - # 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)) + mapped = iter(keras.tree.flatten(map_fn(_fun, elements))) - # 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 ops.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, + axis_size: int | None = None, _use_torch_vmap: bool = False, ): """`vmap` with batching or chunking support to avoid memory issues. @@ -562,15 +558,21 @@ 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 @@ -579,6 +581,8 @@ def vmap( In this case, this function will only handle padding and reshaping for batching. disable_jit: If True, disables JIT compilation for backends that support it. This can be useful for debugging. Will fall back to simple mapping. + axis_size: Length of the axis to map over. Only needed when no input is mapped over, + otherwise it should match the length of the mapped inputs. _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. @@ -596,56 +600,90 @@ 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") + 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: + # 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`." + ) + + def _vmap_fun(axis_size=None): # vmap to support batches - fun = _map( + return _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, + axis_size=axis_size, ) if no_chunks_or_batch: - return fun + return _vmap_fun(axis_size) + + 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, axis_size) + + # Only `axis_size` is given, so there are no inputs to split into batches + if not any(_is_mapped(leaf, axis) for leaf, axis in zip(leaves, leaf_axes)): + if fn_supports_batch: + raise ValueError("fn_supports_batch needs at least one mapped input.") + return _vmap_fun(axis_size)(*args, **kwargs) 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 From ff71104a62f74da14d4c24ef49262645b8225f99 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:16:53 +0000 Subject: [PATCH 2/9] Add the pull request number to the `vmap` changelog entries --- docs/source/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 09fe37beb..6e25551c9 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -26,7 +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 ``in_axes`` and ``out_axes``, keyword arguments and ``axis_size`` on all backends and with batching, like ``jax.vmap`` (:gh:`PRNUM` by :user:`wesselvannierop`) +- :func:`zea.func.vmap` accepts nested inputs, dict ``in_axes`` and ``out_axes``, keyword arguments and ``axis_size`` on all backends and with batching, like ``jax.vmap`` (: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`) @@ -36,7 +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` raises an error for ``out_axes=None`` unless it runs on the native ``jax.vmap``; other paths silently kept only the first element of a mapped output. Axes are also validated like in ``jax.vmap``: only plain integers and ``None``, in containers that match the inputs or outputs, so a list no longer matches a tuple (:gh:`PRNUM` by :user:`wesselvannierop`) +- (Breaking) :func:`zea.func.vmap` raises an error for ``out_axes=None`` unless it runs on the native ``jax.vmap``; other paths silently kept only the first element of a mapped output. Axes are also validated like in ``jax.vmap``: only plain integers and ``None``, in containers that match the inputs or outputs, so a list no longer matches a tuple (: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`) From 31809a108d4c8bf1cf9afe285fd69cf3a4b70c68 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:27:22 +0000 Subject: [PATCH 3/9] Compact the `vmap` changelog entries and document the `_use_torch_vmap` limit --- docs/source/changelog.rst | 4 ++-- zea/func/tensor.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 6e25551c9..69d1faf6f 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -26,7 +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 ``in_axes`` and ``out_axes``, keyword arguments and ``axis_size`` on all backends and with batching, like ``jax.vmap`` (:gh:`692` by :user:`wesselvannierop`) +- :func:`zea.func.vmap` accepts nested inputs, dict axes, keyword arguments and ``axis_size``, like ``jax.vmap`` (: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`) @@ -36,7 +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` raises an error for ``out_axes=None`` unless it runs on the native ``jax.vmap``; other paths silently kept only the first element of a mapped output. Axes are also validated like in ``jax.vmap``: only plain integers and ``None``, in containers that match the inputs or outputs, so a list no longer matches a tuple (:gh:`692` 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`` (: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/zea/func/tensor.py b/zea/func/tensor.py index 485a85bbd..32842f925 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -585,7 +585,7 @@ def vmap( otherwise it should match the length of the mapped inputs. _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. + Disadvantage: does not support None arguments or outputs. Returns: A function that applies `fun` in a batched manner over the specified axes. """ From 97e6228b8264a3a18e80e7f6830aaf160d389636 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 9 Nov 2026 09:54:14 +0000 Subject: [PATCH 4/9] small cleanup --- zea/func/tensor.py | 18 ++++++------------ zea/ops/pipeline.py | 5 ++--- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/zea/func/tensor.py b/zea/func/tensor.py index 32842f925..f58c72755 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -370,18 +370,12 @@ 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 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. From 04fee2bafc0a8783243b52feff9280fdb6867d8f Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:59:10 +0000 Subject: [PATCH 5/9] Reject `out_axes=None` before the `fn_supports_batch` fast path in `vmap` --- tests/test_tensor_ops.py | 9 +++++++++ zea/func/tensor.py | 10 +++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/tests/test_tensor_ops.py b/tests/test_tensor_ops.py index 163d5a883..e2f364a47 100644 --- a/tests/test_tensor_ops.py +++ b/tests/test_tensor_ops.py @@ -1086,6 +1086,15 @@ def test_vmap_invalid_axes_raise_like_jax(case, vmap_kwargs): 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( "axes", [ diff --git a/zea/func/tensor.py b/zea/func/tensor.py index f58c72755..b30b6d637 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -605,11 +605,6 @@ def vmap( _check_axes(in_axes, "in_axes") _check_axes(out_axes, "out_axes") - 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 - # 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 @@ -619,6 +614,11 @@ def vmap( "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 + def _vmap_fun(axis_size=None): # vmap to support batches return _map( From 7457f19835edd6b269481f998c75495c8ecf6089 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:00:30 +0000 Subject: [PATCH 6/9] Remove `axis_size` from `vmap`, since zea does not use it It needed extra paths for inputs without a mapped axis, and older supported jax versions do not check it against the mapped inputs. --- docs/source/changelog.rst | 2 +- tests/test_tensor_ops.py | 11 --------- zea/func/tensor.py | 49 +++++++++++++-------------------------- 3 files changed, 17 insertions(+), 45 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index 69d1faf6f..c8366ef34 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -26,7 +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, keyword arguments and ``axis_size``, like ``jax.vmap`` (:gh:`692` by :user:`wesselvannierop`) +- :func:`zea.func.vmap` accepts nested inputs, dict axes and keyword arguments, like ``jax.vmap`` (: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`) diff --git a/tests/test_tensor_ops.py b/tests/test_tensor_ops.py index e2f364a47..c1e93c9fe 100644 --- a/tests/test_tensor_ops.py +++ b/tests/test_tensor_ops.py @@ -869,8 +869,6 @@ def test_vmap_raises_like_jax(case, vmap_kwargs): "in_axes_list", "keyword_with_in_axes", "dict_out_axes", - "axis_size", - "axis_size_without_mapped_inputs", ] @@ -956,13 +954,6 @@ def test_vmap_inputs_match_jax(case, vmap_kwargs): {}, {"out_axes": {"y": 1, "x": (0, -1)}}, ), - "axis_size": (lambda x: x + 1, (a,), {}, {"axis_size": 5}), - "axis_size_without_mapped_inputs": ( - lambda x: x + 1, - (a[0],), - {}, - {"in_axes": None, "axis_size": 5}, - ), }[case] def to_tensor(x): @@ -1049,7 +1040,6 @@ def test_vmap_out_axes_none(vmap_kwargs): "out_axes_list_for_tuple", "out_axes_tuple_for_list", "out_axes_wrong_keys", - "axis_size_mismatch", "nested_different_lengths", ], ) @@ -1075,7 +1065,6 @@ def test_vmap_invalid_axes_raise_like_jax(case, vmap_kwargs): "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}}), - "axis_size_mismatch": (lambda x: x, (a,), {"axis_size": 4}), "nested_different_lengths": (lambda d: d["x"], ({"x": a, "y": a[:3]},), {}), }[case] diff --git a/zea/func/tensor.py b/zea/func/tensor.py index b30b6d637..adfd396a4 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -385,10 +385,9 @@ def _is_mapped(leaf, axis) -> bool: return leaf is not None and axis is not None -def _find_map_length(leaves, axes, axis_size=None) -> int: +def _find_map_length(leaves, axes) -> int: """Find the length of the axis to map over, which all mapped leaves should share.""" - lengths = [] if axis_size is None else [axis_size] - lengths += [ + lengths = [ ops.shape(leaf)[canonicalize_axis(axis, ops.ndim(leaf))] for leaf, axis in zip(leaves, axes) if _is_mapped(leaf, axis) @@ -437,7 +436,7 @@ def _check_axes(axes, name: str) -> None: raise TypeError(f"{name} should only contain integers and None, got {axes}.") -def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False, axis_size=None): +def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): """Mapping function, vectorized by default. For jax, this uses the native vmap implementation. @@ -454,7 +453,6 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False, axis_si 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. - axis_size: The length of the axis to map over. If None, inferred from the inputs. Returns: A function that applies `fun` (in a vectorized manner) over the specified axes. @@ -464,14 +462,12 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False, axis_si if keras.backend.backend() == "jax" and map_fn is None: import jax - return jax.vmap(fun, in_axes=in_axes, out_axes=out_axes, axis_size=axis_size) + 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 - if axis_size is not None: - raise ValueError("axis_size is not supported with _use_torch_vmap=True.") return torch.vmap(fun, in_dims=in_axes, out_dims=out_axes) # Default to keras vectorized_map if map_fn not provided @@ -486,7 +482,7 @@ def mapped_wrapper(*args, **kwargs): ops.convert_to_tensor(leaf) if isinstance(leaf, (np.ndarray, np.generic)) else leaf for leaf in leaves ] - map_length = _find_map_length(leaves, leaf_axes, axis_size) + map_length = _find_map_length(leaves, leaf_axes) # `tf.vectorized_map` can not return a captured eager tensor, so also map over unmapped # tensors there, by repeating them @@ -502,8 +498,6 @@ def mapped_wrapper(*args, **kwargs): mapped_ids.append(i) elements.append(ops.repeat(ops.expand_dims(leaf, 0), map_length, axis=0)) elements = tuple(elements) - # Map functions need at least one input, also when only `axis_size` is given - elements = elements or (ops.arange(map_length),) # Not all map functions support nested or None outputs, so map over the tensors only is_none = None @@ -543,7 +537,6 @@ def vmap( batch_size: int | None = None, fn_supports_batch: bool = False, disable_jit: bool = False, - axis_size: int | None = None, _use_torch_vmap: bool = False, ): """`vmap` with batching or chunking support to avoid memory issues. @@ -575,8 +568,6 @@ def vmap( In this case, this function will only handle padding and reshaping for batching. disable_jit: If True, disables JIT compilation for backends that support it. This can be useful for debugging. Will fall back to simple mapping. - axis_size: Length of the axis to map over. Only needed when no input is mapped over, - otherwise it should match the length of the mapped inputs. _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 or outputs. @@ -619,21 +610,19 @@ def vmap( if fn_supports_batch and no_chunks_or_batch: return fun - def _vmap_fun(axis_size=None): - # vmap to support batches - return _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, - axis_size=axis_size, - ) + # 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, + _use_torch_vmap=_use_torch_vmap, + ) if no_chunks_or_batch: - return _vmap_fun(axis_size) + return vmap_fun - batch_fun = fun if fn_supports_batch else _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 @@ -641,13 +630,7 @@ def _vmap_fun(axis_size=None): 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, axis_size) - - # Only `axis_size` is given, so there are no inputs to split into batches - if not any(_is_mapped(leaf, axis) for leaf, axis in zip(leaves, leaf_axes)): - if fn_supports_batch: - raise ValueError("fn_supports_batch needs at least one mapped input.") - return _vmap_fun(axis_size)(*args, **kwargs) + total_length = _find_map_length(leaves, leaf_axes) if chunks is not None: _batch_size = np.ceil(total_length / chunks).astype(int) From 29b07fa418eb53d6748d841dfaba4282157565fd Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:02:23 +0000 Subject: [PATCH 7/9] Remove `_use_torch_vmap` and support nested `vmap` on torch Nesting failed on torch because `aten::moveaxis.int` has no batching rule in `torch.vmap`, so `vmap` now moves axes with a transpose. The generic path then nests like the native `torch.vmap`, while also supporting `None` inputs and outputs and keyword arguments. Metrics keep `torch_vmappable` to fall back to a loop for LPIPS and UltraPIPS, whose Conv2D can not run in `torch.vmap`. --- docs/source/changelog.rst | 4 ++-- tests/test_tensor_ops.py | 27 ++++++++++++++++++++++++++ zea/func/tensor.py | 41 ++++++++++++++++++--------------------- zea/metrics.py | 7 +++---- 4 files changed, 51 insertions(+), 28 deletions(-) diff --git a/docs/source/changelog.rst b/docs/source/changelog.rst index c8366ef34..ecf919050 100644 --- a/docs/source/changelog.rst +++ b/docs/source/changelog.rst @@ -26,7 +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`` (:gh:`692` 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`) @@ -36,7 +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`` (:gh:`692` 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 c1e93c9fe..73d86b35a 100644 --- a/tests/test_tensor_ops.py +++ b/tests/test_tensor_ops.py @@ -1084,6 +1084,33 @@ def test_vmap_out_axes_none_fn_supports_batch_fast_path(chunks): 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", [ diff --git a/zea/func/tensor.py b/zea/func/tensor.py index adfd396a4..e5b2fa0db 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -436,7 +436,19 @@ def _check_axes(axes, name: str) -> None: raise TypeError(f"{name} should only contain integers and None, got {axes}.") -def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): +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): """Mapping function, vectorized by default. For jax, this uses the native vmap implementation. @@ -452,7 +464,6 @@ def _map(fun, in_axes=0, out_axes=0, map_fn=None, _use_torch_vmap=False): 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. @@ -464,12 +475,6 @@ 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 @@ -493,7 +498,7 @@ def mapped_wrapper(*args, **kwargs): for i, (leaf, axis) in enumerate(zip(leaves, leaf_axes)): if _is_mapped(leaf, axis): mapped_ids.append(i) - elements.append(ops.moveaxis(leaf, axis, 0)) + elements.append(_moveaxis(leaf, axis, 0)) elif repeat_unmapped and ops.is_tensor(leaf): mapped_ids.append(i) elements.append(ops.repeat(ops.expand_dims(leaf, 0), map_length, axis=0)) @@ -519,7 +524,7 @@ def _fun(elements): # 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 ops.moveaxis(next(mapped), 0, axis) + 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") ) @@ -537,7 +542,6 @@ def vmap( 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. @@ -568,9 +572,6 @@ def vmap( In this case, this function will only handle padding and reshaping for batching. 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 or outputs. Returns: A function that applies `fun` in a batched manner over the specified axes. """ @@ -612,11 +613,7 @@ def 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, - _use_torch_vmap=_use_torch_vmap, + fun, in_axes=in_axes, out_axes=out_axes, map_fn=None if not disable_jit else simple_map ) if no_chunks_or_batch: @@ -669,7 +666,7 @@ def batched_fun(*args, **kwargs): 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) @@ -1768,9 +1765,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 From 32c4ea24277eed2c6fbbd9df1140acb4e9a446f2 Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:08:41 +0000 Subject: [PATCH 8/9] Refactor `_map` to handle TensorFlow outputs correctly by wrapping them in `tf.identity` --- zea/func/tensor.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/zea/func/tensor.py b/zea/func/tensor.py index e5b2fa0db..75e279ea8 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -487,11 +487,11 @@ def mapped_wrapper(*args, **kwargs): ops.convert_to_tensor(leaf) if isinstance(leaf, (np.ndarray, np.generic)) else leaf for leaf in leaves ] - map_length = _find_map_length(leaves, leaf_axes) + _find_map_length(leaves, leaf_axes) # Checks that the mapped leaves share their length - # `tf.vectorized_map` can not return a captured eager tensor, so also map over unmapped - # tensors there, by repeating them - repeat_unmapped = keras.backend.backend() == "tensorflow" and map_fn is vectorized_map + # `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 # Map over the tensors with a mapped axis only, the other leaves are kept as they are mapped_ids, elements = [], [] @@ -499,9 +499,6 @@ def mapped_wrapper(*args, **kwargs): if _is_mapped(leaf, axis): mapped_ids.append(i) elements.append(_moveaxis(leaf, axis, 0)) - elif repeat_unmapped and ops.is_tensor(leaf): - mapped_ids.append(i) - elements.append(ops.repeat(ops.expand_dims(leaf, 0), map_length, axis=0)) elements = tuple(elements) # Not all map functions support nested or None outputs, so map over the tensors only @@ -516,6 +513,10 @@ def _fun(elements): 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(()),) From 5dddcda128df6d79503aa0c60a85443dfe71306c Mon Sep 17 00:00:00 2001 From: Wessel van Nierop <40076995+wesselvannierop@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:46:02 +0100 Subject: [PATCH 9/9] Document that `fn_supports_batch` does not move axes in `vmap` --- zea/func/tensor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zea/func/tensor.py b/zea/func/tensor.py index 75e279ea8..a9a0bd5a9 100644 --- a/zea/func/tensor.py +++ b/zea/func/tensor.py @@ -571,6 +571,8 @@ def vmap( 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. Returns: