Skip to content
Open
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
11 changes: 3 additions & 8 deletions webknossos/webknossos/cli/convert_zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,9 @@


def _try_open_zarr(path: UPath) -> tensorstore.TensorStore:
try:
return tensorstore.open(
{"driver": "zarr3", "kvstore": {"driver": "file", "path": path}}
).result()
except tensorstore.TensorStoreError:
return tensorstore.open(
{"driver": "zarr", "kvstore": {"driver": "file", "path": path}}
).result()
return tensorstore.open(
{"driver": "zarr3", "kvstore": {"driver": "file", "path": str(path)}}
).result()
Comment on lines +40 to +42

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The previous implementation of _try_open_zarr attempted to open with zarr3 first and then fell back to zarr (v2) if zarr3 failed. The current change removes this fallback, exclusively trying zarr3. If the system is expected to handle older zarr (v2) datasets, this change could lead to TensorStoreError for those files. Please confirm if zarr (v2) support is intentionally being dropped or if a fallback mechanism is still required.



def _zarr_chunk_converter(
Expand Down
37 changes: 32 additions & 5 deletions webknossos/webknossos/dataset/layer/_downsampling_utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import logging
import math
import math #
import warnings
from collections.abc import Callable
from enum import Enum
from itertools import product
from typing import TYPE_CHECKING, Union

import numba
import numpy as np
from scipy.ndimage import zoom

Expand All @@ -32,10 +33,10 @@ class InterpolationModes(Enum):

def determine_downsample_buffer_shape(array_info: ArrayInfo) -> Vec3Int:
# This is the shape of the data in the downsampling target magnification, so the
# data that is read is up to 512³ vx in the source magnification. Using larger
# data that is read is up to 1024³ vx in the source magnification. Using larger
# shapes uses a lot of RAM, especially for segmentation layers which use the mode filter.
# See https://scm.slack.com/archives/CMBMU5684/p1749771929954699 for more context.
return Vec3Int.full(256).pairmin(array_info.shard_shape)
return Vec3Int.full(512).pairmin(array_info.shard_shape)
Comment on lines +36 to +39

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The determine_downsample_buffer_shape function now sets the buffer size to 512^3 vx (from 256^3 vx). While this can improve performance by processing larger blocks, it also significantly increases memory consumption, especially for segmentation layers using the mode filter. Please ensure that this increased memory usage is acceptable for typical operating environments and data sizes.



def determine_upsample_buffer_shape(array_info: ArrayInfo) -> Vec3Int:
Expand Down Expand Up @@ -262,6 +263,32 @@ def _mode(x: np.ndarray) -> np.ndarray:
return sort[tuple(index)]


@numba.jit(nopython=True, nogil=True)
def fast_mode(input_array: np.ndarray) -> np.ndarray:
values = np.zeros(input_array.shape[0], dtype=input_array.dtype)
counter = np.zeros(input_array.shape[0], dtype=np.uint8)
output_array = np.zeros(input_array.shape[1], dtype=input_array.dtype)
for row_index in range(input_array.shape[1]):
values[0] = input_array[0, row_index]
counter[:] = 0
value_offset = 1
for col_index in range(1, input_array.shape[0]):
value = input_array[col_index, row_index]
found_value = False
for i in range(col_index): # iterate one less
if value == values[i]:
counter[i] = counter[i] + 1
found_value = True
break
if not found_value:
values[value_offset] = value
value_offset += 1
mode = values[np.argmax(counter)]
output_array[row_index] = mode

return output_array
Comment on lines +266 to +289

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The fast_mode function, while Numba-jitted, uses nested Python-style loops for finding the mode. For larger arrays, this pattern can still be less efficient than vectorized NumPy operations, even with Numba. Consider if a more idiomatic Numba/NumPy approach, such as using np.unique with return_counts and np.argmax, could offer better performance and readability, especially if the number of unique values is small compared to input_array.shape[0].



def downsample_unpadded_data(
buffer: np.ndarray, target_mag: Mag, interpolation_mode: InterpolationModes
) -> np.ndarray:
Expand All @@ -288,7 +315,7 @@ def downsample_cube(
cube_buffer: np.ndarray, factors: list[int], interpolation_mode: InterpolationModes
) -> np.ndarray:
if interpolation_mode == InterpolationModes.MODE:
return non_linear_filter_3d(cube_buffer, factors, _mode)
return non_linear_filter_3d(cube_buffer, factors, fast_mode)
elif interpolation_mode == InterpolationModes.MEDIAN:
return non_linear_filter_3d(cube_buffer, factors, _median)
elif interpolation_mode == InterpolationModes.NEAREST:
Expand Down Expand Up @@ -318,7 +345,7 @@ def downsample_cube_job(
target_bbox_in_mag = target_view.bounding_box.in_mag(target_view.mag)
shape = (num_channels,) + target_bbox_in_mag.size.to_tuple()
shape_xyz = target_bbox_in_mag.size_xyz
file_buffer = np.zeros(shape, target_view.get_dtype())
file_buffer = np.zeros(shape, target_view.get_dtype(), order="F")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Specifying order="F" (Fortran-contiguous) for np.zeros can be a good optimization if subsequent operations on file_buffer primarily access data column-wise or along the last axis first. However, if the data is mostly accessed row-wise or along the first axis, order="C" (C-contiguous, default) might be more efficient. Please confirm that Fortran-contiguous order aligns with the primary access patterns for file_buffer to ensure optimal performance.


tiles = product(
*(
Expand Down
8 changes: 6 additions & 2 deletions webknossos/webknossos/dataset/layer/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1161,19 +1161,23 @@ def downsample_mag(
# perform downsampling
with get_executor_for_args(None, executor) as executor:
if buffer_shape is None:
buffer_shape = determine_downsample_buffer_shape(prev_mag_view.info)
buffer_shape = determine_downsample_buffer_shape(target_view.info)
func = named_partial(
downsample_cube_job,
mag_factors=mag_factors,
interpolation_mode=parsed_interpolation_mode,
buffer_shape=buffer_shape,
)

target_chunk_shape = Vec3Int([1024, 1024, 512]).pairmax(
target_view.info.shard_shape
)
source_view.for_zipped_chunks(
# this view is restricted to the bounding box specified in the properties
func,
target_view=target_view,
executor=executor,
source_chunk_shape=target_chunk_shape * target_mag.to_np(),
target_chunk_shape=target_chunk_shape * target_mag.to_np(),
Comment on lines +1171 to +1180

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In downsample_mag, both source_chunk_shape and target_chunk_shape are calculated using target_chunk_shape * target_mag.to_np(). This implies that the chunk shapes for both the source and target views are identical, scaled by the target magnification. This might be incorrect. source_chunk_shape should typically be derived from prev_mag_view.info.shard_shape and from_mag, while target_chunk_shape should be derived from target_view.info.shard_shape and target_mag. Using the same scaled chunk shape for both could lead to inefficient or incorrect chunking when reading from the source or writing to the target, especially if from_mag and target_mag are different.

progress_desc=f"Downsampling layer {self.name} from Mag {from_mag} to Mag {target_mag}",
)

Expand Down
Loading