micro_sam.v2.datasets.wrapper

Wrapper for ensuring all inputs are in a 3d pyramid structure for training UniSAM2.

  1"""Wrapper for ensuring all inputs are in a 3d pyramid structure for training UniSAM2.
  2"""
  3
  4import torch
  5import numpy as np
  6
  7
  8def _leaves(ds):
  9    """The leaf datasets below (possibly nested) torch-em ConcatDatasets."""
 10    datasets = getattr(ds, "datasets", None)
 11    if datasets is None:
 12        return [ds]
 13    return [leaf for child in datasets for leaf in _leaves(child)]
 14
 15
 16class UniDataWrapper(torch.utils.data.Dataset):
 17    def __init__(self, ds, source_ndim=None, group_key=None, max_samples=None):
 18        self.ds = ds
 19        self.ndim = 3
 20        # Optional cap on the number of samples drawn (e.g. to shrink the validation set).
 21        self.max_samples = max_samples
 22
 23        # torch-em spreads 'n_samples' over the per-file datasets; when there are more files than samples the
 24        # surplus files get length 0 and an index can never reach them. Then every sample draws a random file
 25        # instead, so all files are seen over the epochs (the file datasets sample a random patch regardless
 26        # of the index they are given).
 27        self.leaves = _leaves(ds)
 28        self.random_leaf = len(self.leaves) > 1 and any(len(leaf) == 0 for leaf in self.leaves)
 29        self.max_resample = 10
 30
 31        # Track the source dimensionality for batching (2D vs 3D grouping).
 32        if source_ndim is not None:
 33            self.source_ndim = source_ndim
 34        elif hasattr(ds, "ndim"):
 35            self.source_ndim = ds.ndim
 36        else:
 37            self.source_ndim = None
 38
 39        # Group key for the batch sampler (defaults to source_ndim for backward compat).
 40        # Use a finer-grained key (e.g. (3, z_slices)) when batches must match on more than just ndim.
 41        self.group_key = group_key if group_key is not None else self.source_ndim
 42
 43    def __len__(self):
 44        n = len(self.ds)
 45        return min(n, self.max_samples) if self.max_samples is not None else n
 46
 47    def _to_czyx(self, t):
 48        t = t if torch.is_tensor(t) else torch.as_tensor(t)
 49
 50        if t.ndim == 2:  # (Y, X)
 51            t = t.unsqueeze(0).unsqueeze(1)  # converts to (1, 1, Y, X)
 52        elif t.ndim == 3:
 53            if self.source_ndim == 3:  # (Z, Y, X)
 54                t = t.unsqueeze(0)  # converts to (1, Z, Y, X)
 55            else:  # (C, Y, X) - 2D data, any number of channels
 56                t = t.unsqueeze(1)  # converts to (C, 1, Y, X)
 57        elif t.ndim == 4:  # assumes (C, Z, Y, X) and life goes on.
 58            pass
 59        else:
 60            raise ValueError(f"Unsupported ndim {t.ndim}")
 61        return t
 62
 63    def _draw(self, i):
 64        if self.random_leaf:
 65            return self.leaves[np.random.randint(len(self.leaves))][0]
 66        return self.ds[i]
 67
 68    def __getitem__(self, i):
 69        # A file whose labels never satisfy the sampler (e.g. an image with two cells under a three-instance
 70        # sampler) raises once its attempts are used up. Draw from another file instead of failing the epoch.
 71        for attempt in range(self.max_resample):
 72            try:
 73                raw, label = self._draw(i)
 74                break
 75            except RuntimeError as e:
 76                if "Could not sample a valid batch" not in str(e) or attempt == self.max_resample - 1:
 77                    raise
 78                i = np.random.randint(len(self.ds))
 79        raw = self._to_czyx(raw).to(torch.float32)
 80        label = self._to_czyx(label).to(torch.float32)
 81
 82        # Diagnostic: warn when the instance channel (ch 0) of joint labels is all-zero.
 83        # Drills through nested ConcatDatasets to find the actual raw/label file path.
 84        if label.shape[0] >= 5 and label[0].max() == 0:
 85            import warnings
 86
 87            def _find_leaf(ds, idx):
 88                offsets = getattr(ds, "ds_offsets", None)
 89                datasets = getattr(ds, "datasets", None)
 90                if offsets is None or datasets is None:
 91                    return ds, idx
 92                ds_idx = int(np.searchsorted(offsets, idx, side="right"))
 93                offset = offsets[ds_idx - 1] if ds_idx > 0 else 0
 94                return _find_leaf(datasets[ds_idx], idx - offset)
 95
 96            leaf_ds, leaf_idx = _find_leaf(self.ds, i)
 97            raw_path = getattr(leaf_ds, "raw_path", "unknown")
 98            label_path = getattr(leaf_ds, "label_path", "unknown")
 99            ch1_vals = label[1].unique().tolist()  # foreground channel for comparison
100            warnings.warn(
101                f"UniDataWrapper: instance channel all-zero at index {i} "
102                f"(leaf_idx={leaf_idx}, raw={raw_path}, label={label_path}, "
103                f"label.shape={tuple(label.shape)}, ch1_unique={ch1_vals}, group_key={self.group_key})",
104                stacklevel=2,
105            )
106
107        # Encoder patch_embed expects 3 input channels - triplicate any single-channel input.
108        if raw.shape[0] == 1:
109            raw = torch.cat([raw] * 3, dim=0)
110
111        return raw, label
class UniDataWrapper(typing.Generic[+_T_co]):
 17class UniDataWrapper(torch.utils.data.Dataset):
 18    def __init__(self, ds, source_ndim=None, group_key=None, max_samples=None):
 19        self.ds = ds
 20        self.ndim = 3
 21        # Optional cap on the number of samples drawn (e.g. to shrink the validation set).
 22        self.max_samples = max_samples
 23
 24        # torch-em spreads 'n_samples' over the per-file datasets; when there are more files than samples the
 25        # surplus files get length 0 and an index can never reach them. Then every sample draws a random file
 26        # instead, so all files are seen over the epochs (the file datasets sample a random patch regardless
 27        # of the index they are given).
 28        self.leaves = _leaves(ds)
 29        self.random_leaf = len(self.leaves) > 1 and any(len(leaf) == 0 for leaf in self.leaves)
 30        self.max_resample = 10
 31
 32        # Track the source dimensionality for batching (2D vs 3D grouping).
 33        if source_ndim is not None:
 34            self.source_ndim = source_ndim
 35        elif hasattr(ds, "ndim"):
 36            self.source_ndim = ds.ndim
 37        else:
 38            self.source_ndim = None
 39
 40        # Group key for the batch sampler (defaults to source_ndim for backward compat).
 41        # Use a finer-grained key (e.g. (3, z_slices)) when batches must match on more than just ndim.
 42        self.group_key = group_key if group_key is not None else self.source_ndim
 43
 44    def __len__(self):
 45        n = len(self.ds)
 46        return min(n, self.max_samples) if self.max_samples is not None else n
 47
 48    def _to_czyx(self, t):
 49        t = t if torch.is_tensor(t) else torch.as_tensor(t)
 50
 51        if t.ndim == 2:  # (Y, X)
 52            t = t.unsqueeze(0).unsqueeze(1)  # converts to (1, 1, Y, X)
 53        elif t.ndim == 3:
 54            if self.source_ndim == 3:  # (Z, Y, X)
 55                t = t.unsqueeze(0)  # converts to (1, Z, Y, X)
 56            else:  # (C, Y, X) - 2D data, any number of channels
 57                t = t.unsqueeze(1)  # converts to (C, 1, Y, X)
 58        elif t.ndim == 4:  # assumes (C, Z, Y, X) and life goes on.
 59            pass
 60        else:
 61            raise ValueError(f"Unsupported ndim {t.ndim}")
 62        return t
 63
 64    def _draw(self, i):
 65        if self.random_leaf:
 66            return self.leaves[np.random.randint(len(self.leaves))][0]
 67        return self.ds[i]
 68
 69    def __getitem__(self, i):
 70        # A file whose labels never satisfy the sampler (e.g. an image with two cells under a three-instance
 71        # sampler) raises once its attempts are used up. Draw from another file instead of failing the epoch.
 72        for attempt in range(self.max_resample):
 73            try:
 74                raw, label = self._draw(i)
 75                break
 76            except RuntimeError as e:
 77                if "Could not sample a valid batch" not in str(e) or attempt == self.max_resample - 1:
 78                    raise
 79                i = np.random.randint(len(self.ds))
 80        raw = self._to_czyx(raw).to(torch.float32)
 81        label = self._to_czyx(label).to(torch.float32)
 82
 83        # Diagnostic: warn when the instance channel (ch 0) of joint labels is all-zero.
 84        # Drills through nested ConcatDatasets to find the actual raw/label file path.
 85        if label.shape[0] >= 5 and label[0].max() == 0:
 86            import warnings
 87
 88            def _find_leaf(ds, idx):
 89                offsets = getattr(ds, "ds_offsets", None)
 90                datasets = getattr(ds, "datasets", None)
 91                if offsets is None or datasets is None:
 92                    return ds, idx
 93                ds_idx = int(np.searchsorted(offsets, idx, side="right"))
 94                offset = offsets[ds_idx - 1] if ds_idx > 0 else 0
 95                return _find_leaf(datasets[ds_idx], idx - offset)
 96
 97            leaf_ds, leaf_idx = _find_leaf(self.ds, i)
 98            raw_path = getattr(leaf_ds, "raw_path", "unknown")
 99            label_path = getattr(leaf_ds, "label_path", "unknown")
100            ch1_vals = label[1].unique().tolist()  # foreground channel for comparison
101            warnings.warn(
102                f"UniDataWrapper: instance channel all-zero at index {i} "
103                f"(leaf_idx={leaf_idx}, raw={raw_path}, label={label_path}, "
104                f"label.shape={tuple(label.shape)}, ch1_unique={ch1_vals}, group_key={self.group_key})",
105                stacklevel=2,
106            )
107
108        # Encoder patch_embed expects 3 input channels - triplicate any single-channel input.
109        if raw.shape[0] == 1:
110            raw = torch.cat([raw] * 3, dim=0)
111
112        return raw, label

An abstract class representing a Dataset.

All datasets that represent a map from keys to data samples should subclass it. All subclasses should overwrite __getitem__(), supporting fetching a data sample for a given key. Subclasses could also optionally overwrite __len__(), which is expected to return the size of the dataset by many ~torch.utils.data.Sampler implementations and the default options of ~torch.utils.data.DataLoader. Subclasses could also optionally implement __getitems__(), for speedup batched samples loading. This method accepts list of indices of samples of batch and returns list of samples.

sampler that yields integral indices. To make it work with a map-style dataset with non-integral indices/keys, a custom sampler must be provided.

UniDataWrapper(ds, source_ndim=None, group_key=None, max_samples=None)
18    def __init__(self, ds, source_ndim=None, group_key=None, max_samples=None):
19        self.ds = ds
20        self.ndim = 3
21        # Optional cap on the number of samples drawn (e.g. to shrink the validation set).
22        self.max_samples = max_samples
23
24        # torch-em spreads 'n_samples' over the per-file datasets; when there are more files than samples the
25        # surplus files get length 0 and an index can never reach them. Then every sample draws a random file
26        # instead, so all files are seen over the epochs (the file datasets sample a random patch regardless
27        # of the index they are given).
28        self.leaves = _leaves(ds)
29        self.random_leaf = len(self.leaves) > 1 and any(len(leaf) == 0 for leaf in self.leaves)
30        self.max_resample = 10
31
32        # Track the source dimensionality for batching (2D vs 3D grouping).
33        if source_ndim is not None:
34            self.source_ndim = source_ndim
35        elif hasattr(ds, "ndim"):
36            self.source_ndim = ds.ndim
37        else:
38            self.source_ndim = None
39
40        # Group key for the batch sampler (defaults to source_ndim for backward compat).
41        # Use a finer-grained key (e.g. (3, z_slices)) when batches must match on more than just ndim.
42        self.group_key = group_key if group_key is not None else self.source_ndim
ds
ndim
max_samples
leaves
random_leaf
max_resample
group_key