Skip to content
Merged
2 changes: 2 additions & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand All @@ -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`)

Expand Down
300 changes: 291 additions & 9 deletions tests/test_tensor_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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}),
Expand Down Expand Up @@ -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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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`."""
Expand Down
Loading
Loading