Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
279 changes: 230 additions & 49 deletions stitch_elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -105,17 +108,53 @@ 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:
(x, y) -> flow array
(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)):
Expand Down Expand Up @@ -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)):
Expand Down Expand Up @@ -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,
Expand Down
Loading