micro_sam.v2.datasets.sampler
1import random 2from typing import Dict, Iterator, List, Optional 3 4import numpy as np 5 6from torch.utils.data import Sampler 7 8from torch_em.data import ConcatDataset 9 10 11class UniBatchSampler(Sampler[List[int]]): 12 """Yields batches where all indices share the same group key. 13 14 Batch sampler that groups indices by an arbitrary key (e.g. source 15 dimensionality, or a ``(ndim, z_slices)`` tuple) and optionally uses 16 a different batch size per group. 17 18 Args: 19 group_per_index: List of length ``len(dataset)`` mapping each global 20 index to its group key (any hashable value). 21 batch_size: Default number of samples per batch (used when no 22 per-group override is provided). 23 batch_size_per_group: Optional dict mapping group keys to their 24 batch size. Groups not present fall back to *batch_size*. 25 shuffle: Whether to shuffle indices within each group and the 26 batch order across groups each epoch. 27 drop_last: Whether to drop the last incomplete batch per group. 28 """ 29 30 def __init__( 31 self, 32 group_per_index: List, 33 batch_size: int = 1, 34 batch_size_per_group: Optional[Dict] = None, 35 shuffle: bool = True, 36 drop_last: bool = False, 37 ): 38 self.group_per_index = group_per_index 39 self.batch_size = batch_size 40 self.batch_size_per_group = batch_size_per_group or {} 41 self.shuffle = shuffle 42 self.drop_last = drop_last 43 44 # Partition indices into groups keyed by group key. 45 self._groups: Dict = {} 46 for idx, key in enumerate(group_per_index): 47 self._groups.setdefault(key, []).append(idx) 48 49 def _get_batch_size(self, group_key) -> int: 50 return self.batch_size_per_group.get(group_key, self.batch_size) 51 52 def __iter__(self) -> Iterator[List[int]]: 53 all_batches: List[List[int]] = [] 54 for group_key, indices in self._groups.items(): 55 bs = self._get_batch_size(group_key) 56 if self.shuffle: 57 indices = indices.copy() 58 random.shuffle(indices) 59 60 for i in range(0, len(indices), bs): 61 batch = indices[i: i + bs] 62 if self.drop_last and len(batch) < bs: 63 continue 64 all_batches.append(batch) 65 66 # Interleave groups rather than emitting all of one group first. 67 if self.shuffle: 68 random.shuffle(all_batches) 69 70 yield from all_batches 71 72 def __len__(self) -> int: 73 total = 0 74 for group_key, indices in self._groups.items(): 75 n = len(indices) 76 bs = self._get_batch_size(group_key) 77 if self.drop_last: 78 total += n // bs 79 else: 80 total += (n + bs - 1) // bs 81 return total 82 83 def set_epoch(self, epoch: int) -> None: 84 """Seed the RNG so shuffling varies across epochs.""" 85 random.seed(epoch) 86 87 88class DistributedUniBatchSampler(Sampler[List[int]]): 89 """Distributed version of UniBatchSampler for DDP training. 90 91 Shards batches **within each group** across ranks, so every rank receives 92 the same proportion of 2D and 3D batches each epoch. This avoids the load 93 imbalance that arises when a globally-shuffled list is interleaved across 94 ranks, because 2D and 3D batches have very different compute costs. 95 96 All ranks use the same shuffle seed (set via :meth:`set_epoch`) so they 97 independently produce identical per-group batch lists, then each takes its 98 own non-overlapping slice. 99 100 Call :meth:`set_epoch` before each epoch so the shuffle seed changes and 101 all ranks stay in sync. 102 103 Args: 104 group_per_index: Same as :class:`UniBatchSampler`. 105 batch_size: Default batch size. 106 batch_size_per_group: Per-group batch size overrides. 107 shuffle: Whether to shuffle batches each epoch. 108 drop_last: Whether to drop the last incomplete batch per group. 109 rank: This process's rank (0-based). 110 world_size: Total number of DDP processes. 111 """ 112 113 def __init__( 114 self, 115 group_per_index: List, 116 batch_size: int = 1, 117 batch_size_per_group: Optional[Dict] = None, 118 shuffle: bool = True, 119 drop_last: bool = False, 120 rank: int = 0, 121 world_size: int = 1, 122 ): 123 self._base = UniBatchSampler( 124 group_per_index, batch_size, batch_size_per_group, shuffle, drop_last 125 ) 126 self.rank = rank 127 self.world_size = world_size 128 129 def _make_evenly_shardable(self, batches: List[List[int]]) -> List[List[int]]: 130 """Drop trailing batches so all ranks receive the same group count.""" 131 n_batches = len(batches) 132 n_batches -= n_batches % self.world_size 133 return batches[:n_batches] 134 135 def set_epoch(self, epoch: int) -> None: 136 """Seed the shuffle for *epoch* - must be called identically on all ranks.""" 137 self._base.set_epoch(epoch) 138 139 def __iter__(self): 140 per_rank_batches: List[List[int]] = [] 141 142 for group_key, indices in self._base._groups.items(): 143 bs = self._base._get_batch_size(group_key) 144 group_indices = list(indices) 145 146 if self._base.shuffle: 147 random.shuffle(group_indices) 148 149 group_batches: List[List[int]] = [] 150 for i in range(0, len(group_indices), bs): 151 batch = group_indices[i:i + bs] 152 if self._base.drop_last and len(batch) < bs: 153 continue 154 group_batches.append(batch) 155 156 group_batches = self._make_evenly_shardable(group_batches) 157 158 # Shard this group's batches across ranks before merging. 159 per_rank_batches.extend(group_batches[self.rank::self.world_size]) 160 161 if self._base.shuffle: 162 random.shuffle(per_rank_batches) 163 164 yield from per_rank_batches 165 166 def __len__(self) -> int: 167 total = 0 168 for group_key, indices in self._base._groups.items(): 169 bs = self._base._get_batch_size(group_key) 170 n = len(indices) 171 n_batches = n // bs if self._base.drop_last else (n + bs - 1) // bs 172 n_batches -= n_batches % self.world_size 173 total += n_batches // self.world_size 174 return total 175 176 177def _build_group_map(concat_dataset: ConcatDataset) -> List: 178 """Build a flat list mapping each global index to its group key. 179 180 The group key is read from ``group_key`` first, falling back to 181 ``source_ndim`` for backward compatibility. 182 183 Args: 184 concat_dataset: A ``ConcatDataset`` whose sub-datasets are 185 ``UniDataWrapper`` instances. 186 187 Returns: 188 List of length ``len(concat_dataset)`` with the group key for each index. 189 """ 190 group_per_index: List = [] 191 for ds in concat_dataset.datasets: 192 key = getattr(ds, "group_key", None) 193 if key is None: 194 key = getattr(ds, "source_ndim", None) 195 if key is None: 196 raise ValueError( 197 f"Dataset {ds} does not have a valid group_key or source_ndim attribute. " 198 "Wrap it with UniDataWrapper(ds, source_ndim=2) or UniDataWrapper(ds, source_ndim=3)." 199 ) 200 group_per_index.extend([key] * len(ds)) 201 return group_per_index 202 203 204class RejectBlankSlices: 205 """Reject a volume crop that holds a constant raw plane, and defer to an inner sampler otherwise. 206 207 A dropped acquisition section reads as a constant plane. Its labels still carry objects, so an 208 instance sampler accepts the crop and the model is asked to segment a plane that holds no signal. 209 fafb, microns-minnie65 and axonem all carry such planes inside the volume, not at its edges. 210 211 Args: 212 sampler: The sampler that decides every crop this one does not reject. 213 """ 214 215 def __init__(self, sampler): 216 self.sampler = sampler 217 218 def __call__(self, x, y) -> bool: 219 """Check the crop. 220 221 Args: 222 x: The raw data, as (z, y, x) or (channel, z, y, x). 223 y: The label data. 224 225 Returns: 226 Whether to accept this crop. 227 """ 228 volume = np.asarray(x) 229 if volume.ndim == 4: 230 volume = volume[0] 231 planes = volume.reshape(volume.shape[0], -1) 232 if bool((planes.min(axis=1) == planes.max(axis=1)).any()): 233 return False 234 return self.sampler(x, y)
12class UniBatchSampler(Sampler[List[int]]): 13 """Yields batches where all indices share the same group key. 14 15 Batch sampler that groups indices by an arbitrary key (e.g. source 16 dimensionality, or a ``(ndim, z_slices)`` tuple) and optionally uses 17 a different batch size per group. 18 19 Args: 20 group_per_index: List of length ``len(dataset)`` mapping each global 21 index to its group key (any hashable value). 22 batch_size: Default number of samples per batch (used when no 23 per-group override is provided). 24 batch_size_per_group: Optional dict mapping group keys to their 25 batch size. Groups not present fall back to *batch_size*. 26 shuffle: Whether to shuffle indices within each group and the 27 batch order across groups each epoch. 28 drop_last: Whether to drop the last incomplete batch per group. 29 """ 30 31 def __init__( 32 self, 33 group_per_index: List, 34 batch_size: int = 1, 35 batch_size_per_group: Optional[Dict] = None, 36 shuffle: bool = True, 37 drop_last: bool = False, 38 ): 39 self.group_per_index = group_per_index 40 self.batch_size = batch_size 41 self.batch_size_per_group = batch_size_per_group or {} 42 self.shuffle = shuffle 43 self.drop_last = drop_last 44 45 # Partition indices into groups keyed by group key. 46 self._groups: Dict = {} 47 for idx, key in enumerate(group_per_index): 48 self._groups.setdefault(key, []).append(idx) 49 50 def _get_batch_size(self, group_key) -> int: 51 return self.batch_size_per_group.get(group_key, self.batch_size) 52 53 def __iter__(self) -> Iterator[List[int]]: 54 all_batches: List[List[int]] = [] 55 for group_key, indices in self._groups.items(): 56 bs = self._get_batch_size(group_key) 57 if self.shuffle: 58 indices = indices.copy() 59 random.shuffle(indices) 60 61 for i in range(0, len(indices), bs): 62 batch = indices[i: i + bs] 63 if self.drop_last and len(batch) < bs: 64 continue 65 all_batches.append(batch) 66 67 # Interleave groups rather than emitting all of one group first. 68 if self.shuffle: 69 random.shuffle(all_batches) 70 71 yield from all_batches 72 73 def __len__(self) -> int: 74 total = 0 75 for group_key, indices in self._groups.items(): 76 n = len(indices) 77 bs = self._get_batch_size(group_key) 78 if self.drop_last: 79 total += n // bs 80 else: 81 total += (n + bs - 1) // bs 82 return total 83 84 def set_epoch(self, epoch: int) -> None: 85 """Seed the RNG so shuffling varies across epochs.""" 86 random.seed(epoch)
Yields batches where all indices share the same group key.
Batch sampler that groups indices by an arbitrary key (e.g. source
dimensionality, or a (ndim, z_slices) tuple) and optionally uses
a different batch size per group.
Arguments:
- group_per_index: List of length
len(dataset)mapping each global index to its group key (any hashable value). - batch_size: Default number of samples per batch (used when no per-group override is provided).
- batch_size_per_group: Optional dict mapping group keys to their batch size. Groups not present fall back to batch_size.
- shuffle: Whether to shuffle indices within each group and the batch order across groups each epoch.
- drop_last: Whether to drop the last incomplete batch per group.
31 def __init__( 32 self, 33 group_per_index: List, 34 batch_size: int = 1, 35 batch_size_per_group: Optional[Dict] = None, 36 shuffle: bool = True, 37 drop_last: bool = False, 38 ): 39 self.group_per_index = group_per_index 40 self.batch_size = batch_size 41 self.batch_size_per_group = batch_size_per_group or {} 42 self.shuffle = shuffle 43 self.drop_last = drop_last 44 45 # Partition indices into groups keyed by group key. 46 self._groups: Dict = {} 47 for idx, key in enumerate(group_per_index): 48 self._groups.setdefault(key, []).append(idx)
89class DistributedUniBatchSampler(Sampler[List[int]]): 90 """Distributed version of UniBatchSampler for DDP training. 91 92 Shards batches **within each group** across ranks, so every rank receives 93 the same proportion of 2D and 3D batches each epoch. This avoids the load 94 imbalance that arises when a globally-shuffled list is interleaved across 95 ranks, because 2D and 3D batches have very different compute costs. 96 97 All ranks use the same shuffle seed (set via :meth:`set_epoch`) so they 98 independently produce identical per-group batch lists, then each takes its 99 own non-overlapping slice. 100 101 Call :meth:`set_epoch` before each epoch so the shuffle seed changes and 102 all ranks stay in sync. 103 104 Args: 105 group_per_index: Same as :class:`UniBatchSampler`. 106 batch_size: Default batch size. 107 batch_size_per_group: Per-group batch size overrides. 108 shuffle: Whether to shuffle batches each epoch. 109 drop_last: Whether to drop the last incomplete batch per group. 110 rank: This process's rank (0-based). 111 world_size: Total number of DDP processes. 112 """ 113 114 def __init__( 115 self, 116 group_per_index: List, 117 batch_size: int = 1, 118 batch_size_per_group: Optional[Dict] = None, 119 shuffle: bool = True, 120 drop_last: bool = False, 121 rank: int = 0, 122 world_size: int = 1, 123 ): 124 self._base = UniBatchSampler( 125 group_per_index, batch_size, batch_size_per_group, shuffle, drop_last 126 ) 127 self.rank = rank 128 self.world_size = world_size 129 130 def _make_evenly_shardable(self, batches: List[List[int]]) -> List[List[int]]: 131 """Drop trailing batches so all ranks receive the same group count.""" 132 n_batches = len(batches) 133 n_batches -= n_batches % self.world_size 134 return batches[:n_batches] 135 136 def set_epoch(self, epoch: int) -> None: 137 """Seed the shuffle for *epoch* - must be called identically on all ranks.""" 138 self._base.set_epoch(epoch) 139 140 def __iter__(self): 141 per_rank_batches: List[List[int]] = [] 142 143 for group_key, indices in self._base._groups.items(): 144 bs = self._base._get_batch_size(group_key) 145 group_indices = list(indices) 146 147 if self._base.shuffle: 148 random.shuffle(group_indices) 149 150 group_batches: List[List[int]] = [] 151 for i in range(0, len(group_indices), bs): 152 batch = group_indices[i:i + bs] 153 if self._base.drop_last and len(batch) < bs: 154 continue 155 group_batches.append(batch) 156 157 group_batches = self._make_evenly_shardable(group_batches) 158 159 # Shard this group's batches across ranks before merging. 160 per_rank_batches.extend(group_batches[self.rank::self.world_size]) 161 162 if self._base.shuffle: 163 random.shuffle(per_rank_batches) 164 165 yield from per_rank_batches 166 167 def __len__(self) -> int: 168 total = 0 169 for group_key, indices in self._base._groups.items(): 170 bs = self._base._get_batch_size(group_key) 171 n = len(indices) 172 n_batches = n // bs if self._base.drop_last else (n + bs - 1) // bs 173 n_batches -= n_batches % self.world_size 174 total += n_batches // self.world_size 175 return total
Distributed version of UniBatchSampler for DDP training.
Shards batches within each group across ranks, so every rank receives the same proportion of 2D and 3D batches each epoch. This avoids the load imbalance that arises when a globally-shuffled list is interleaved across ranks, because 2D and 3D batches have very different compute costs.
All ranks use the same shuffle seed (set via set_epoch()) so they
independently produce identical per-group batch lists, then each takes its
own non-overlapping slice.
Call set_epoch() before each epoch so the shuffle seed changes and
all ranks stay in sync.
Arguments:
- group_per_index: Same as
UniBatchSampler. - batch_size: Default batch size.
- batch_size_per_group: Per-group batch size overrides.
- shuffle: Whether to shuffle batches each epoch.
- drop_last: Whether to drop the last incomplete batch per group.
- rank: This process's rank (0-based).
- world_size: Total number of DDP processes.
114 def __init__( 115 self, 116 group_per_index: List, 117 batch_size: int = 1, 118 batch_size_per_group: Optional[Dict] = None, 119 shuffle: bool = True, 120 drop_last: bool = False, 121 rank: int = 0, 122 world_size: int = 1, 123 ): 124 self._base = UniBatchSampler( 125 group_per_index, batch_size, batch_size_per_group, shuffle, drop_last 126 ) 127 self.rank = rank 128 self.world_size = world_size
205class RejectBlankSlices: 206 """Reject a volume crop that holds a constant raw plane, and defer to an inner sampler otherwise. 207 208 A dropped acquisition section reads as a constant plane. Its labels still carry objects, so an 209 instance sampler accepts the crop and the model is asked to segment a plane that holds no signal. 210 fafb, microns-minnie65 and axonem all carry such planes inside the volume, not at its edges. 211 212 Args: 213 sampler: The sampler that decides every crop this one does not reject. 214 """ 215 216 def __init__(self, sampler): 217 self.sampler = sampler 218 219 def __call__(self, x, y) -> bool: 220 """Check the crop. 221 222 Args: 223 x: The raw data, as (z, y, x) or (channel, z, y, x). 224 y: The label data. 225 226 Returns: 227 Whether to accept this crop. 228 """ 229 volume = np.asarray(x) 230 if volume.ndim == 4: 231 volume = volume[0] 232 planes = volume.reshape(volume.shape[0], -1) 233 if bool((planes.min(axis=1) == planes.max(axis=1)).any()): 234 return False 235 return self.sampler(x, y)
Reject a volume crop that holds a constant raw plane, and defer to an inner sampler otherwise.
A dropped acquisition section reads as a constant plane. Its labels still carry objects, so an instance sampler accepts the crop and the model is asked to segment a plane that holds no signal. fafb, microns-minnie65 and axonem all carry such planes inside the volume, not at its edges.
Arguments:
- sampler: The sampler that decides every crop this one does not reject.