From 4a21b64979888e4455fb9b3fd6f30a00526074c3 Mon Sep 17 00:00:00 2001 From: Sylvester Kaczmarek <16242628+sylvesterkaczmarek@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:27:03 +0000 Subject: [PATCH] Validate block sizes in depth-space transforms --- dm_pix/_src/depth_and_space.py | 16 ++++- .../_src/depth_space_block_validation_test.py | 72 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 dm_pix/_src/depth_space_block_validation_test.py diff --git a/dm_pix/_src/depth_and_space.py b/dm_pix/_src/depth_and_space.py index 79ee416..d74bc5f 100644 --- a/dm_pix/_src/depth_and_space.py +++ b/dm_pix/_src/depth_and_space.py @@ -13,6 +13,8 @@ # limitations under the License. """This module provides functions for rearranging blocks of spatial data.""" +import numbers + import chex import jax import jax.numpy as jnp @@ -20,6 +22,14 @@ # DO NOT REMOVE - Logging lib. +def _validate_block_size(block_size: int) -> None: + """Require a positive integer block size for spatial rearrangements.""" + if (isinstance(block_size, bool) + or not isinstance(block_size, numbers.Integral) + or block_size < 2): + raise ValueError("block_size must be an integer >= 2.") + + def depth_to_space(inputs: chex.Array, block_size: int) -> chex.Array: """Rearranges data from depth into blocks of spatial data. @@ -35,9 +45,10 @@ def depth_to_space(inputs: chex.Array, block_size: int) -> chex.Array: """ # DO NOT REMOVE - Logging usage. + _validate_block_size(block_size) chex.assert_rank(inputs, {3, 4}) if inputs.ndim == 4: # Batched case. - return jax.vmap(depth_to_space, in_axes=(0, None))(inputs, block_size) + return jax.vmap(lambda x: depth_to_space(x, block_size))(inputs) height, width, depth = inputs.shape if depth % (block_size**2) != 0: @@ -71,9 +82,10 @@ def space_to_depth(inputs: chex.Array, block_size: int) -> chex.Array: """ # DO NOT REMOVE - Logging usage. + _validate_block_size(block_size) chex.assert_rank(inputs, {3, 4}) if inputs.ndim == 4: # Batched case. - return jax.vmap(space_to_depth, in_axes=(0, None))(inputs, block_size) + return jax.vmap(lambda x: space_to_depth(x, block_size))(inputs) height, width, depth = inputs.shape if height % block_size != 0: diff --git a/dm_pix/_src/depth_space_block_validation_test.py b/dm_pix/_src/depth_space_block_validation_test.py new file mode 100644 index 0000000..e76c953 --- /dev/null +++ b/dm_pix/_src/depth_space_block_validation_test.py @@ -0,0 +1,72 @@ +# Copyright 2026 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Validate the block size for spatial-to-channel rearrangements.""" + +from absl.testing import absltest +from absl.testing import parameterized +from dm_pix._src import depth_and_space +import jax +import jax.numpy as jnp +import numpy as np + + +class BlockSizeValidationTest(parameterized.TestCase): + + @parameterized.product( + function=(depth_and_space.depth_to_space, depth_and_space.space_to_depth), + block_size=(0, 1, -1, -2, 1.5, True, np.float64(2.0)), + ) + def test_invalid_block_sizes_raise_value_error(self, function, block_size): + image = jnp.arange(64, dtype=jnp.float32).reshape(4, 4, 4) + with self.assertRaisesRegex(ValueError, "block_size.*integer.*>= 2"): + function(image, block_size) + + @parameterized.parameters( + depth_and_space.depth_to_space, depth_and_space.space_to_depth + ) + def test_invalid_block_size_is_rejected_before_batched_vmap(self, function): + batch = jnp.ones((2, 4, 4, 4), dtype=jnp.float32) + with self.assertRaisesRegex(ValueError, "block_size"): + function(batch, 0) + + def test_valid_numpy_integer_block_round_trips(self): + image = jnp.arange(4 * 4 * 3, dtype=jnp.float32).reshape(4, 4, 3) + block_size = np.int64(2) + grouped = depth_and_space.space_to_depth(image, block_size) + restored = depth_and_space.depth_to_space(grouped, block_size) + self.assertEqual(grouped.shape, (2, 2, 12)) + np.testing.assert_array_equal(restored, image) + + def test_empty_batch_retains_batch_axis(self): + batch = jnp.zeros((0, 4, 4, 3), dtype=jnp.float32) + grouped = depth_and_space.space_to_depth(batch, 2) + restored = depth_and_space.depth_to_space(grouped, 2) + self.assertEqual(grouped.shape, (0, 2, 2, 12)) + self.assertEqual(restored.shape, batch.shape) + + def test_batched_roundtrip_is_jittable(self): + images = jnp.arange(2 * 4 * 4 * 3, dtype=jnp.float32).reshape(2, 4, 4, 3) + + @jax.jit + def roundtrip(batch): + packed = depth_and_space.space_to_depth(batch, 2) + return depth_and_space.depth_to_space(packed, 2) + + result = roundtrip(images) + self.assertEqual(result.shape, images.shape) + np.testing.assert_array_equal(result, images) + + +if __name__ == "__main__": + absltest.main()