From f729e1bf62c0bf662fe3e163f46dd969a301c3aa Mon Sep 17 00:00:00 2001 From: Michal Januszewski Date: Fri, 4 Dec 2026 07:49:42 -0800 Subject: [PATCH] Add batched XY seam flow estimation and max_shift wiring in stitch_elastic. PiperOrigin-RevId: 1036322436 --- stitch_elastic.py | 279 +++++++++++++++++++++++++++++++++++++-------- tests/mesh_test.py | 210 ++++++++++++++++++++++++++++++++++ 2 files changed, 440 insertions(+), 49 deletions(-) diff --git a/stitch_elastic.py b/stitch_elastic.py index 849e146..af4972a 100644 --- a/stitch_elastic.py +++ b/stitch_elastic.py @@ -20,6 +20,7 @@ dimension represents the XY position of the mesh node at (x, y). """ +import collections.abc import enum import functools as ft from typing import Any, Mapping, Sequence, Union @@ -90,13 +91,15 @@ def compute_flow_map3d( patch_size: Vector = (120, 120, 120), stride: Vector = (40, 40, 40), batch_size: int = 16, + max_shift: int | Sequence[int] | None = None, + use_multi_device: bool = False, ) -> tuple[TileFlow, TileOffset]: """Computes fine flow between two horizontally or vertically adjacent 3d tiles. Args: tile_map: maps (x, y) tile coordinates to ndarray-like objects storing - individual tile data; even object should have shape [1, z, y, x] and - allow standard indexing + individual tile data; even object should have shape [1, z, y, x] and allow + standard indexing tile_shape: XYZ shape of an individual 3d tile offset_map: [3, 1, y, x]-shaped array where the vector spanning the first dimension is a coarse XYZ offset between the tiles (x,y) and (x+1,y) or @@ -105,6 +108,11 @@ def compute_flow_map3d( patch_size: ZYX patch size in pixels stride: ZYX stride for the flow map in pixels batch_size: number of flow vectors to estimate simultaneously + max_shift: optional max allowed shift magnitude along each axis (should be + at least stride + max elastic shift to cover stride-aligned overlap + rounding); enables Overlap-Save cross-correlation and multi-seam batching + use_multi_device: whether to shard macro-tiles across all local JAX devices + when max_shift is set Returns: tuple of dictionaries: @@ -112,10 +120,41 @@ def compute_flow_map3d( (x, y) -> xyz offset at which the following tile was positioned (relative to its native position on the grid) before the flow was computed """ - mfc = flow_field.JAXMaskedXCorrWithStatsCalculator() + mfc = flow_field.JAXMaskedXCorrWithStatsCalculator( + max_shift=max_shift, use_multi_device=use_multi_device + ) + eff_batch_size = max(batch_size, 512) if max_shift is not None else batch_size + if max_shift is None or any(p % s != 0 for p, s in zip(patch_size, stride)): + max_buffer_bytes = 0 + else: + max_buffer_bytes = 256 * 1024 * 1024 ret, offsets = {}, {} + keys: list[TileXY] = [] + pres: list[np.ndarray] = [] + posts: list[np.ndarray] = [] + buffered_bytes = 0 grid_yx_shape = offset_map.shape[-2:] - pad_zyx = np.array(patch_size) // 2 // stride + pad_width = [[0, 0]] + [ + [p, p - 1] for p in np.array(patch_size) // 2 // stride + ] + + def _flush() -> None: + nonlocal buffered_bytes + if not keys: + return + flows = mfc.flow_field_batch( + pres, + posts, + patch_size=patch_size, + step=stride, + batch_size=eff_batch_size, + ) + for key, f in zip(keys, flows): + ret[key] = np.pad(f, pad_width, constant_values=np.nan) + keys.clear() + pres.clear() + posts.clear() + buffered_bytes = 0 for y in range(0, grid_yx_shape[0] - axis): for x in range(0, grid_yx_shape[1] - (1 - axis)): @@ -183,49 +222,34 @@ def compute_flow_map3d( post = tile_post[isec_nbor.to_slice4d()].squeeze(axis=0) assert pre.shape == post.shape - - f = mfc.flow_field( - pre, post, patch_size=patch_size, step=stride, batch_size=batch_size - ) - ret[(x, y)] = np.pad( - f, [[0, 0]] + [[p, p - 1] for p in pad_zyx], constant_values=np.nan - ) + pair_bytes = pre.nbytes + post.nbytes + if keys and buffered_bytes + pair_bytes > max_buffer_bytes: + _flush() + keys.append((x, y)) + pres.append(pre) + posts.append(post) + buffered_bytes += pair_bytes + del pre, post + if buffered_bytes >= max_buffer_bytes: + _flush() + + _flush() return ret, offsets -# TODO(mjanusz): Integrate this function with compute_flow_map3d. -def compute_flow_map( +def _extract_2d_seam_pairs( tile_map: Mapping[TileXY, np.ndarray], offset_map: np.ndarray, axis: int, - patch_size: Vector = (120, 120), - stride: Vector = (20, 20), - batch_size: int = 256, -) -> tuple[TileFlow, TileOffset]: - """Computes fine flow between two horizontally or vertically adjacent 2d tiles. - - Args: - tile_map: maps (x, y) tile coordinates to the tile image content - offset_map: [2, y, x]-shaped array where the vector spanning the first - dimension is a coarse XY offset between the tiles (x,y) and (x+1,y) or - (x,y+1) - axis: axis along which to look for the neighboring tile (0:x, 1:y) - patch_size: YX patch size in pixels - stride: YX stride for the flow map in pixels - batch_size: number of flow vectors to estimate simultaneously - - Returns: - tuple of dictionaries: - (x, y) -> flow array - (x, y) -> xy offset with which the flow was computed - """ + stride: tuple[int, int], +) -> tuple[list[TileXY], list[np.ndarray], list[np.ndarray], TileOffset]: + """Extracts stride-aligned 2D overlap strips for horizontal or vertical NNs.""" yx_shape = offset_map.shape[-2:] - mfc = flow_field.JAXMaskedXCorrWithStatsCalculator() - ret, offsets = {}, {} - - pad_y = patch_size[0] // 2 // stride[0] - pad_x = patch_size[1] // 2 // stride[1] + keys: list[TileXY] = [] + pres: list[np.ndarray] = [] + posts: list[np.ndarray] = [] + offsets: TileOffset = {} for y in range(0, yx_shape[0] - axis): for x in range(0, yx_shape[1] - (1 - axis)): @@ -263,25 +287,182 @@ def compute_flow_map( pre = pre[tuple(pre_sel)] post = post[tuple(post_sel)] - f = mfc.flow_field( - pre, post, patch_size=patch_size, step=stride, batch_size=batch_size - ) - # The inverse flow (post, pre) is just -f, so it does not need to be - # computed separately. + keys.append((x, y)) + pres.append(pre) + posts.append(post) + if axis == 0: + offsets[x, y] = (-overlap, ortho_offset) + else: + offsets[x, y] = (ortho_offset, -overlap) + + return keys, pres, posts, offsets + + +def compute_flow_map( + tile_map: Mapping[TileXY, np.ndarray], + offset_map: np.ndarray, + axis: int, + patch_size: Vector = (120, 120), + stride: Vector = (20, 20), + batch_size: int = 256, + max_shift: int | Sequence[int] | None = None, + use_multi_device: bool = False, +) -> tuple[TileFlow, TileOffset]: + """Computes fine flow between two horizontally or vertically adjacent 2d tiles. + + Args: + tile_map: maps (x, y) tile coordinates to the tile image content + offset_map: [2, y, x]-shaped array where the vector spanning the first + dimension is a coarse XY offset between the tiles (x,y) and (x+1,y) or + (x,y+1) + axis: axis along which to look for the neighboring tile (0:x, 1:y) + patch_size: YX patch size in pixels + stride: YX stride for the flow map in pixels + batch_size: number of flow vectors to estimate simultaneously + max_shift: optional max allowed shift magnitude along each axis (should be + at least stride + max elastic shift to cover stride-aligned overlap + rounding); enables Overlap-Save cross-correlation and multi-seam batching + use_multi_device: whether to shard macro-tiles across all local JAX devices + when max_shift is set + + Returns: + tuple of dictionaries: + (x, y) -> flow array + (x, y) -> xy offset with which the flow was computed + """ + mfc = flow_field.JAXMaskedXCorrWithStatsCalculator( + max_shift=max_shift, use_multi_device=use_multi_device + ) + eff_batch_size = ( + max(batch_size, 4096) if max_shift is not None else batch_size + ) + stride_2d = (int(stride[0]), int(stride[1])) + pad_y = patch_size[0] // 2 // stride_2d[0] + pad_x = patch_size[1] // 2 // stride_2d[1] - ret[(x, y)] = np.pad( + keys, pres, posts, offsets = _extract_2d_seam_pairs( + tile_map, offset_map, axis, stride_2d + ) + ret: TileFlow = {} + if keys: + flows = mfc.flow_field_batch( + pres, + posts, + patch_size=patch_size, + step=stride_2d, + batch_size=eff_batch_size, + ) + # The inverse flow (post, pre) is just -f, so it does not need to be + # computed separately. + for key, f in zip(keys, flows): + ret[key] = np.pad( f, [[0, 0], [pad_y, pad_y - 1], [pad_x, pad_x - 1]], constant_values=np.nan, ) - if axis == 0: - offsets[x, y] = (-overlap, ortho_offset) - else: - offsets[x, y] = (ortho_offset, -overlap) return ret, offsets +def compute_flow_maps_xy( + tile_map: Mapping[TileXY, np.ndarray], + cx: np.ndarray, + cy: np.ndarray, + patch_size: Vector = (120, 120), + stride: Vector = (20, 20), + batch_size: int = 256, + max_shift: int | Sequence[int] | None = None, + use_multi_device: bool = False, +) -> tuple[tuple[TileFlow, TileOffset], tuple[TileFlow, TileOffset]]: + """Computes horizontal and vertical 2D seam flows in a single fused wave. + + When patch_size, stride, and max_shift are isotropic, vertical (axis=1) strips + are transposed into the same (ortho, overlap) layout as horizontal (axis=0) + strips and packed into one `flow_field_batch` call, halving XLA compilations + and doubling single-wave device occupancy. + + Args: + tile_map: maps (x, y) tile coordinates to the tile image content + cx: [2, y, x] coarse XY offsets between (x, y) and (x + 1, y) + cy: [2, y, x] coarse XY offsets between (x, y) and (x, y + 1) + patch_size: YX patch size in pixels + stride: YX stride for the flow map in pixels + batch_size: number of flow vectors to estimate simultaneously + max_shift: optional max allowed shift magnitude along each axis + use_multi_device: whether to shard macro-tiles across all local JAX devices + when max_shift is set + + Returns: + ((fine_x, offsets_x), (fine_y, offsets_y)) matching two `compute_flow_map` + calls on axis=0 and axis=1. + """ + stride_2d = (int(stride[0]), int(stride[1])) + patch_2d = (int(patch_size[0]), int(patch_size[1])) + can_fuse_xy = ( + max_shift is not None + and patch_2d[0] == patch_2d[1] + and stride_2d[0] == stride_2d[1] + and ( + not isinstance(max_shift, collections.abc.Sequence) + or (len(max_shift) == 2 and int(max_shift[0]) == int(max_shift[1])) + ) + ) + if not can_fuse_xy: + return ( + compute_flow_map( + tile_map, + cx, + 0, + patch_size=patch_size, + stride=stride, + batch_size=batch_size, + max_shift=max_shift, + use_multi_device=use_multi_device, + ), + compute_flow_map( + tile_map, + cy, + 1, + patch_size=patch_size, + stride=stride, + batch_size=batch_size, + max_shift=max_shift, + use_multi_device=use_multi_device, + ), + ) + + keys_x, pres_x, posts_x, offsets_x = _extract_2d_seam_pairs( + tile_map, cx, 0, stride_2d + ) + keys_y, pres_y, posts_y, offsets_y = _extract_2d_seam_pairs( + tile_map, cy, 1, stride_2d + ) + fine_x: TileFlow = {} + fine_y: TileFlow = {} + pres_all = pres_x + [a.T for a in pres_y] + posts_all = posts_x + [a.T for a in posts_y] + if pres_all: + mfc = flow_field.JAXMaskedXCorrWithStatsCalculator( + max_shift=max_shift, use_multi_device=use_multi_device + ) + flows_all = mfc.flow_field_batch( + pres_all, + posts_all, + patch_size=patch_2d, + step=stride_2d, + batch_size=max(batch_size, 4096), + ) + pad = patch_2d[0] // 2 // stride_2d[0] + pad_width = [[0, 0], [pad, pad - 1], [pad, pad - 1]] + nx = len(keys_x) + for key, f in zip(keys_x, flows_all[:nx]): + fine_x[key] = np.pad(f, pad_width, constant_values=np.nan) + for key, f_t in zip(keys_y, flows_all[nx:]): + f_orig = np.transpose(f_t[[1, 0, 2, 3]], (0, 2, 1)) + fine_y[key] = np.pad(f_orig, pad_width, constant_values=np.nan) + return (fine_x, offsets_x), (fine_y, offsets_y) + + def aggregate_arrays( x_data: TileFlowData, y_data: TileFlowData, diff --git a/tests/mesh_test.py b/tests/mesh_test.py index 0358aa5..4facebb 100644 --- a/tests/mesh_test.py +++ b/tests/mesh_test.py @@ -17,12 +17,14 @@ import dataclasses from unittest import mock +import weakref from absl.testing import absltest import jax import jax.numpy as jnp import numpy as np from sofima import mesh +from sofima import stitch_elastic from sofima import stitch_rigid @@ -819,5 +821,213 @@ def test_stitch_rigid_memory_capped_buckets(self): [(1, 1)] * 7, ) + def test_compute_flow_map_2d_and_3d_max_shift(self): + rng = np.random.default_rng(101) + canvas = rng.integers(30, 225, size=(240, 280), dtype=np.uint8) + tile_map_2d = { + (0, 0): canvas[0:160, 0:160], + (1, 0): canvas[2:162, 78:238], + (0, 1): canvas[77:237, 3:163], + (1, 1): canvas[79:239, 81:241], + } + off_xy = { + 0: np.array([[[-82.0, 0.0], [-82.0, 0.0]], [[2.0, 0.0], [2.0, 0.0]]]), + 1: np.array([[[3.0, 3.0], [0.0, 0.0]], [[-83.0, -83.0], [0.0, 0.0]]]), + } + for axis in (0, 1): + ref_map, ref_off = stitch_elastic.compute_flow_map( + tile_map_2d, + off_xy[axis], + axis=axis, + patch_size=(40, 40), + stride=(20, 20), + ) + got_map, got_off = stitch_elastic.compute_flow_map( + tile_map_2d, + off_xy[axis], + axis=axis, + patch_size=(40, 40), + stride=(20, 20), + max_shift=24, + use_multi_device=True, + ) + self.assertEqual(got_off, ref_off) + for k in ref_map: + np.testing.assert_allclose( + got_map[k][:2], ref_map[k][:2], rtol=1e-3, atol=1e-3, equal_nan=True + ) + + vol3d = rng.integers(30, 225, size=(1, 48, 80, 140), dtype=np.uint8) + + class _TrackableArray(np.ndarray): + pass + + live_refs: list[weakref.ref] = [] + max_live_slabs = 0 + + class _LazyTile3D: + + def __init__(self, data: np.ndarray): + self._data = data + + def __getitem__(self, key): + nonlocal max_live_slabs + live_refs[:] = [r for r in live_refs if r() is not None] + slab = self._data[key].copy().view(_TrackableArray) + live_refs.append(weakref.ref(slab)) + max_live_slabs = max(max_live_slabs, len(live_refs)) + return slab + + tile_map_3d = { + (0, 0): _LazyTile3D(vol3d[:, :, :, :64]), + (1, 0): _LazyTile3D(vol3d[:, :, :, 30:94]), + (2, 0): _LazyTile3D(vol3d[:, :, :, 60:124]), + } + off_3d = np.zeros((3, 1, 1, 3), dtype=np.float32) + off_3d[0, 0, 0, 0] = -34.0 + off_3d[0, 0, 0, 1] = -34.0 + ref_3d_m, ref_3d_o = stitch_elastic.compute_flow_map3d( + tile_map_3d, + tile_shape=(64, 80, 48), + offset_map=off_3d, + axis=0, + patch_size=(16, 16, 16), + stride=(8, 8, 8), + ) + # Without max_shift, compute_flow_map3d should stream one seam pair at a + # time instead of retaining slabs from earlier seams in host RAM. + self.assertLessEqual(max_live_slabs, 2) + got_3d_m, got_3d_o = stitch_elastic.compute_flow_map3d( + tile_map_3d, + tile_shape=(64, 80, 48), + offset_map=off_3d, + axis=0, + patch_size=(16, 16, 16), + stride=(8, 8, 8), + max_shift=12, + ) + self.assertEqual(got_3d_o, ref_3d_o) + for k in ref_3d_m: + np.testing.assert_allclose( + got_3d_m[k][:3], + ref_3d_m[k][:3], + rtol=1e-3, + atol=1e-3, + equal_nan=True, + ) + + def test_compute_flow_maps_xy(self): + rng = np.random.default_rng(123) + canvas = rng.integers(20, 235, size=(260, 260), dtype=np.uint8) + tile_map = { + (0, 0): canvas[0:160, 0:160], + (1, 0): canvas[2:162, 80:240], + (0, 1): canvas[78:238, 3:163], + (1, 1): canvas[80:240, 83:243], + } + cx, cy = stitch_rigid.compute_coarse_offsets( + (2, 2), + tile_map, + overlaps_xy=((75, 85), (75, 85)), + min_range=(10, 0), + min_overlap=50, + filter_size=6, + ) + cx_2d = np.squeeze(cx) + cy_2d = np.squeeze(cy) + + # Exercise fused XY (including NumPy scalar max_shift) and unfused fallbacks + # (anisotropic max_shift and anisotropic patch_size). + for patch_size, max_shift in ( + ((40, 40), np.int64(16)), + ((40, 40), (16, 8)), + ((60, 40), 16), + ): + fx, off_x = stitch_elastic.compute_flow_map( + tile_map, + cx_2d, + 0, + patch_size=patch_size, + stride=(20, 20), + max_shift=max_shift, + ) + fy, off_y = stitch_elastic.compute_flow_map( + tile_map, + cy_2d, + 1, + patch_size=patch_size, + stride=(20, 20), + max_shift=max_shift, + ) + (fx_xy, off_x_xy), (fy_xy, off_y_xy) = ( + stitch_elastic.compute_flow_maps_xy( + tile_map, + cx_2d, + cy_2d, + patch_size=patch_size, + stride=(20, 20), + max_shift=max_shift, + ) + ) + self.assertEqual(off_x_xy, off_x) + self.assertEqual(off_y_xy, off_y) + self.assertEqual(set(fx_xy.keys()), set(fx.keys())) + self.assertEqual(set(fy_xy.keys()), set(fy.keys())) + for k in fx: + np.testing.assert_allclose( + fx_xy[k], fx[k], rtol=1e-5, atol=1e-5, equal_nan=True + ) + for k in fy: + np.testing.assert_allclose( + fy_xy[k], fy[k], rtol=1e-5, atol=1e-5, equal_nan=True + ) + + # Exercise fused single-axis (horizontal-only) non-square tiles. + tile_map_1x2 = { + (0, 0): canvas[0:140, 0:160], + (1, 0): canvas[2:142, 80:240], + } + cx_1x2 = np.array([[[-80.0, 0.0]], [[2.0, 0.0]]]) + cy_1x2 = np.zeros((2, 1, 2), dtype=np.float32) + fx_1, off_x_1 = stitch_elastic.compute_flow_map( + tile_map_1x2, + cx_1x2, + 0, + patch_size=(40, 40), + stride=(20, 20), + max_shift=16, + ) + (fx_1_xy, off_x_1_xy), (fy_1_xy, off_y_1_xy) = ( + stitch_elastic.compute_flow_maps_xy( + tile_map_1x2, + cx_1x2, + cy_1x2, + patch_size=(40, 40), + stride=(20, 20), + max_shift=16, + ) + ) + self.assertEqual(off_x_1_xy, off_x_1) + self.assertEmpty(fy_1_xy) + self.assertEmpty(off_y_1_xy) + self.assertEqual(set(fx_1_xy.keys()), set(fx_1.keys())) + for k in fx_1: + np.testing.assert_allclose( + fx_1_xy[k], fx_1[k], rtol=1e-5, atol=1e-5, equal_nan=True + ) + + # Malformed max_shift length should delegate to flow_field validation + # rather than raising IndexError in ms_iso. + with self.assertRaises(AssertionError): + stitch_elastic.compute_flow_maps_xy( + tile_map_1x2, + cx_1x2, + cy_1x2, + patch_size=(40, 40), + stride=(20, 20), + max_shift=(16,), + ) + + if __name__ == '__main__': absltest.main()