micro_sam.v2.batched_inference
Batched, pipelined, multi-GPU SAM2 inference: scheduling engine, encoder embeddings, and decoder passes.
1"""Batched, pipelined, multi-GPU SAM2 inference: scheduling engine, encoder embeddings, and decoder passes.""" 2 3import gc 4import os 5import time 6import queue 7import warnings 8import threading 9import contextlib 10from copy import deepcopy 11from dataclasses import dataclass 12from collections import defaultdict 13from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union 14 15import numpy as np 16 17import torch 18 19from micro_sam.util import _create_dataset_without_data 20from .util import UNISAM2_OUTPUT_CHANNELS, Devices, autocast, recommend_batch_size, to_float32 21from .normalization import IMAGE_PREPROCESSING, VIDEO_PREPROCESSING, compute_percentile_bounds, to_image 22 23 24STOP = object() 25 26# Slices sampled to estimate whole-volume normalization statistics, so a lazy volume (dask / zarr / 27# h5py) is never materialized all at once just to compute them. 28NORMALIZATION_SAMPLE_SLICES = 32 29 30 31def _volume_normalization_bounds(input_: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: 32 """Percentile bounds from a sample of z slices spanning the whole volume. 33 34 Every slice or tile the volume is later split into is normalized with these bounds (see 35 `_compute_3d` / `_compute_tiled_3d`), so they all share one normalization instead of each 36 estimating its own from a smaller, biased crop. 37 """ 38 n_slices = int(input_.shape[0]) 39 step = max(1, n_slices // NORMALIZATION_SAMPLE_SLICES) 40 sample = np.stack([np.asarray(input_[z]) for z in range(0, n_slices, step)]) 41 if sample.ndim == 4: 42 bounds = compute_percentile_bounds(sample, axis=(0, 1, 2)) 43 return tuple(bound[0] for bound in bounds) 44 return compute_percentile_bounds(sample) 45 46 47class _PipelineAborted(Exception): 48 """Raised inside workers when another pipeline worker fails.""" 49 50 51class _AtomicCounter: 52 """Lock-guarded counter used to send completion sentinels exactly once.""" 53 54 def __init__(self, value: int) -> None: 55 self.value = value 56 self.lock = threading.Lock() 57 58 def decrement(self) -> int: 59 with self.lock: 60 self.value -= 1 61 return self.value 62 63 64@dataclass 65class _PipelineJob: 66 """A work item moving from the input loader to inference and output writing.""" 67 68 spec: Any 69 data: Any 70 71 72def _normalize_device(device: Union[str, torch.device]) -> torch.device: 73 device = torch.device(device) 74 if device.type == "cuda" and device.index is None and torch.cuda.is_available(): 75 return torch.device("cuda", torch.cuda.current_device()) 76 return device 77 78 79def _model_device(model: torch.nn.Module) -> torch.device: 80 try: 81 return _normalize_device(next(model.parameters()).device) 82 except (AttributeError, StopIteration): 83 return torch.device("cpu") 84 85 86def _all_cuda_devices() -> List[torch.device]: 87 return [torch.device("cuda", index) for index in range(torch.cuda.device_count())] 88 89 90def _resolve_devices(model: torch.nn.Module, devices: Devices = None) -> List[torch.device]: 91 """Resolve the inference devices, using every visible CUDA device by default. 92 93 Only `devices=None` fans out. Anything given explicitly stays on the one device it names, so a bare 94 'cuda' resolves to the current CUDA device and inference never allocates on a GPU the caller did not 95 select. The GUI passes None for its 'auto' entry and lists the visible GPUs individually, so both 96 intents are reachable from it. 97 98 Automatic multi-GPU execution is enabled only when the supplied model already lives on CUDA. 99 This preserves an explicitly CPU- or MPS-loaded model. 100 101 Args: 102 model: The model whose device decides the default. Only used when `devices` is None. 103 devices: A single device to force one device, or a sequence to select an explicit set. 104 By default all visible CUDA devices are used if the model is on CUDA. 105 106 Returns: 107 The resolved devices, in the order they will be assigned to inference workers. 108 109 Raises: 110 ValueError: If no device is given, or if the same device is given more than once. 111 RuntimeError: If a CUDA device is requested but CUDA is unavailable. 112 """ 113 if devices is None: 114 device = _model_device(model) 115 resolved = _all_cuda_devices() if device.type == "cuda" and torch.cuda.device_count() > 1 else [device] 116 elif isinstance(devices, (str, torch.device)): 117 resolved = [_normalize_device(devices)] 118 else: 119 resolved = [_normalize_device(device) for device in devices] 120 121 if len(resolved) == 0: 122 raise ValueError("At least one inference device is required.") 123 if len(set(resolved)) != len(resolved): 124 raise ValueError(f"Inference devices must be unique, got {resolved}.") 125 if any(device.type == "cuda" for device in resolved) and not torch.cuda.is_available(): 126 raise RuntimeError("CUDA inference was requested, but PyTorch CUDA support is unavailable.") 127 return resolved 128 129 130def _prepare_models( 131 model: torch.nn.Module, devices: Sequence[torch.device], 132) -> List[Tuple[torch.nn.Module, torch.device]]: 133 """Create one eval-mode model replica per device, reusing the original where possible. 134 135 Replicas are deep-copied from a CPU copy of the model rather than from the source-device model, 136 so a second full copy is never allocated on the source GPU (which could OOM during setup). This 137 is safe because `_prepare_models` runs only at synchronous pipeline setup, with no concurrent use. 138 139 Args: 140 model: The model to replicate. 141 devices: The devices to place the replicas on (see `_resolve_devices`). 142 143 Returns: 144 One (model, device) pair per device. The pair for the model's own device holds the original 145 model, all others hold a deep copy. Release them with `_release_model_replicas`. 146 """ 147 source_device = _model_device(model) 148 replicas = {} 149 other_devices = [device for device in devices if device != source_device] 150 if other_devices: 151 # Move the original to CPU (in place) so each deepcopy lands in host RAM, then restore it. 152 model.to("cpu") 153 try: 154 for device in other_devices: 155 replicas[device] = deepcopy(model).to(device) 156 finally: 157 model.to(source_device) 158 159 models = [] 160 for device in devices: 161 replica = model if device == source_device else replicas[device] 162 if hasattr(replica, "eval"): 163 replica.eval() 164 models.append((replica, device)) 165 return models 166 167 168def _release_model_replicas(model_devices: List[Tuple[torch.nn.Module, torch.device]]) -> None: 169 """Drop the replicas built by `_prepare_models` and free their GPU memory. 170 171 Clearing the list releases only the per-device copies; the caller's own model stays alive 172 through its other references. 173 174 Args: 175 model_devices: The (model, device) pairs returned by `_prepare_models`. Cleared in place. 176 """ 177 model_devices.clear() 178 gc.collect() 179 if torch.cuda.is_available(): 180 torch.cuda.empty_cache() 181 182 183def _is_oom_error(exc: Exception) -> bool: 184 oom_type = getattr(torch.cuda, "OutOfMemoryError", ()) 185 return isinstance(exc, oom_type) or "out of memory" in str(exc).lower() 186 187 188def _release_probe_memory(device: torch.device) -> None: 189 gc.collect() 190 if device.type == "cuda": 191 with torch.cuda.device(device): 192 torch.cuda.empty_cache() 193 194 195def _release_fragmented_cuda_cache(device: torch.device) -> None: 196 """Release inactive cache when it leaves the logical CUDA device with too little free VRAM.""" 197 if device.type != "cuda": 198 return 199 free_memory, total_memory = torch.cuda.mem_get_info(device) 200 allocated_memory = torch.cuda.memory_allocated(device) 201 inactive_memory = torch.cuda.memory_reserved(device) - allocated_memory 202 if free_memory < 0.25 * total_memory and inactive_memory > 0.25 * total_memory: 203 with torch.cuda.device(device): 204 torch.cuda.empty_cache() 205 206 207def _measure_batch_throughput( 208 model: torch.nn.Module, 209 device: torch.device, 210 batch_size: int, 211 patch_shape: Tuple[int, ...], 212 in_channels: int, 213 prediction_function: Callable[[torch.nn.Module, torch.Tensor], Any], 214 n_repeats: int = 2, 215) -> Optional[float]: 216 """Measure samples per second for one synthetic batch, returning None on CUDA OOM.""" 217 inputs = output = None 218 was_training = model.training 219 model.eval() 220 try: 221 inputs = torch.empty( 222 (batch_size, in_channels, *patch_shape), dtype=torch.float32, device=device, 223 ).normal_() 224 timings = [] 225 for repeat in range(n_repeats + 1): 226 if device.type == "cuda": 227 torch.cuda.synchronize(device) 228 start = time.perf_counter() 229 with torch.no_grad(): 230 output = prediction_function(model, inputs) 231 if device.type == "cuda": 232 torch.cuda.synchronize(device) 233 if repeat > 0: 234 timings.append(time.perf_counter() - start) 235 del output 236 output = None 237 return float(batch_size) / float(np.median(timings)) 238 except Exception as exc: 239 if _is_oom_error(exc): 240 return None 241 raise 242 finally: 243 model.train(was_training) 244 del inputs, output 245 _release_probe_memory(device) 246 247 248def _select_throughput_batch_size( 249 measurements: Sequence[Tuple[int, float]], min_relative_improvement: float = 0.1, 250) -> int: 251 """Prefer the smallest batch unless a larger one improves throughput materially.""" 252 if not measurements: 253 raise ValueError("At least one batch-throughput measurement is required.") 254 selected_batch, selected_throughput = measurements[0] 255 for batch_size, throughput in measurements[1:]: 256 if throughput >= selected_throughput * (1.0 + min_relative_improvement): 257 selected_batch, selected_throughput = batch_size, throughput 258 return int(selected_batch) 259 260 261def _compute_auto_batch_sizes( 262 model_devices: Sequence[Tuple[torch.nn.Module, torch.device]], 263 n_jobs: int, 264 patch_shape: Tuple[int, ...], 265 in_channels: int, 266 prediction_function: Callable[[torch.nn.Module, torch.Tensor], Any], 267) -> List[int]: 268 """Select a throughput-efficient batch size independently on every CUDA device. 269 270 Powers of two are benchmarked from one upwards. A larger batch is selected only when it improves 271 measured throughput by at least 10 percent, and probing stops after two consecutive candidates 272 fail to do so. CPU and MPS retain the conservative batch size of one. 273 274 Args: 275 model_devices: The (model, device) pairs to benchmark (see `_prepare_models`). 276 n_jobs: The total number of jobs; caps the candidates so a batch never exceeds the work. 277 patch_shape: The spatial shape of a single input to the model. 278 in_channels: The number of channels of a single input to the model. 279 prediction_function: Called as `prediction_function(model, inputs)` to run one probe batch. 280 281 Returns: 282 One batch size per entry in `model_devices`. 283 284 Raises: 285 RuntimeError: If a device runs out of memory already at batch size one. 286 """ 287 if n_jobs < 1: 288 return [1] * len(model_devices) 289 290 jobs_per_device = (int(n_jobs) + len(model_devices) - 1) // len(model_devices) 291 upper_bound = min(256, jobs_per_device) 292 batch_sizes = [] 293 for model, device in model_devices: 294 if device.type != "cuda": 295 batch_sizes.append(1) 296 continue 297 298 measurements = [] 299 non_improving_candidates = 0 300 candidate = 1 301 while candidate <= upper_bound: 302 previous_selection = ( 303 _select_throughput_batch_size(measurements) if measurements else None 304 ) 305 throughput = _measure_batch_throughput( 306 model=model, 307 device=device, 308 batch_size=candidate, 309 patch_shape=patch_shape, 310 in_channels=in_channels, 311 prediction_function=prediction_function, 312 ) 313 if throughput is None: 314 break 315 measurements.append((candidate, throughput)) 316 selection = _select_throughput_batch_size(measurements) 317 if previous_selection is not None: 318 if selection == candidate: 319 non_improving_candidates = 0 320 else: 321 non_improving_candidates += 1 322 if non_improving_candidates >= 2: 323 break 324 candidate *= 2 325 326 if not measurements: 327 raise RuntimeError( 328 f"The model does not fit batch size 1 on {device}. Reduce the patch shape or use a smaller model." 329 ) 330 batch_sizes.append(_select_throughput_batch_size(measurements)) 331 return batch_sizes 332 333 334def _safe_get(input_queue: queue.Queue, stop_event: threading.Event, timeout: float = 0.2) -> Any: 335 while not stop_event.is_set(): 336 try: 337 return input_queue.get(timeout=timeout) 338 except queue.Empty: 339 continue 340 raise _PipelineAborted() 341 342 343def _safe_put(output_queue: queue.Queue, item: Any, stop_event: threading.Event, timeout: float = 0.2) -> None: 344 while not stop_event.is_set(): 345 try: 346 output_queue.put(item, timeout=timeout) 347 return 348 except queue.Full: 349 continue 350 raise _PipelineAborted() 351 352 353def _predict_with_oom_backoff( 354 model: torch.nn.Module, 355 items: List[Any], 356 device: torch.device, 357 predict_fn: Callable[[torch.nn.Module, List[Any], torch.device], List[Any]], 358) -> Tuple[List[Any], int]: 359 """Retry an OOMing batch in halves and return the largest size proven safe.""" 360 try: 361 return predict_fn(model, items, device), len(items) 362 except Exception as exc: 363 if not _is_oom_error(exc): 364 raise 365 366 _release_probe_memory(device) 367 if len(items) == 1: 368 return predict_fn(model, items, device), 1 369 split = len(items) // 2 370 warnings.warn( 371 f"Batch size {len(items)} ran out of memory on {device}; retrying with smaller batches.", 372 RuntimeWarning, 373 stacklevel=2, 374 ) 375 left, left_size = _predict_with_oom_backoff(model, items[:split], device, predict_fn) 376 right, right_size = _predict_with_oom_backoff(model, items[split:], device, predict_fn) 377 return left + right, min(left_size, right_size) 378 379 380def _run_batched_pipeline( 381 jobs: Iterable[Any], 382 model_devices: Sequence[Tuple[torch.nn.Module, torch.device]], 383 batch_sizes: Sequence[int], 384 load_fn: Callable[[Any], Any], 385 predict_fn: Callable[[torch.nn.Module, List[Any], torch.device], List[Any]], 386 write_fn: Callable[[Any, Any], None], 387 num_prefetch_workers: int = 4, 388 num_write_workers: int = 2, 389 update_progress: Optional[Callable[[int], None]] = None, 390 progress_increment: Optional[Callable[[Any], int]] = None, 391) -> None: 392 """Run load/preprocess, batched inference, and writing as a bounded threaded pipeline. 393 394 Loading runs on `num_prefetch_workers` threads, inference on one thread per device, and writing 395 on `num_write_workers` threads, so input I/O and output I/O overlap with the model forward pass. 396 The queues between the stages are bounded, so a slow stage throttles the others instead of 397 growing memory. Jobs are written in completion order, not in input order. If any worker raises, 398 the whole pipeline is stopped and the first error is re-raised on the calling thread. 399 400 Args: 401 jobs: The job specifications, e.g. tile ids or slice indices. Passed to `load_fn` and, with 402 the prediction, to `write_fn`. 403 model_devices: The (model, device) pairs to run inference on (see `_prepare_models`). 404 batch_sizes: One batch size per entry in `model_devices` (see `_prepare_encoder_pipeline` for 405 the encoder and `_compute_auto_batch_sizes` for the decoder). 406 load_fn: Called as `load_fn(job)` to read and preprocess one job. 407 predict_fn: Called as `predict_fn(model, items, device)` with the loaded data of one batch. 408 It must return one output per input. Batches that run out of memory are automatically 409 retried in halves, and the device's batch size is reduced accordingly. 410 write_fn: Called as `write_fn(job, prediction)` to store one result. It must be safe to call 411 from multiple threads if `num_write_workers` is larger than one. 412 num_prefetch_workers: The number of threads used to read and preprocess jobs. 413 num_write_workers: The number of threads used to write results. Multiple writers speed up 414 compressed / chunked outputs; keep it at one for outputs that are not thread-safe. 415 update_progress: Optional callback advancing external progress by the given number of steps. 416 It is called on the calling thread, so it is safe to use for Qt / napari progress bars. 417 progress_increment: Optional callback returning the number of steps a job contributes. 418 By default every job counts as one step. 419 420 Raises: 421 ValueError: If the batch sizes do not match the devices, or are not positive. 422 """ 423 jobs = list(jobs) 424 if len(jobs) == 0: 425 return 426 if len(model_devices) != len(batch_sizes): 427 raise ValueError("Expected one batch size for every model/device pair.") 428 if any(int(batch_size) < 1 for batch_size in batch_sizes): 429 raise ValueError(f"Batch sizes must be positive, got {batch_sizes}.") 430 431 num_prefetch_workers = max(1, min(int(num_prefetch_workers), len(jobs))) 432 num_write_workers = max(1, min(int(num_write_workers), len(jobs))) 433 batch_sizes = [int(batch_size) for batch_size in batch_sizes] 434 435 job_queue = queue.Queue() 436 for job in jobs: 437 job_queue.put(job) 438 for _ in range(num_prefetch_workers): 439 job_queue.put(STOP) 440 441 input_queue = queue.Queue(maxsize=max(2 * sum(batch_sizes), 2)) 442 # Sized to hold a full batch from every device: a consumer that cannot hand off all of its 443 # predictions blocks mid-batch and idles the GPU until the writers catch up. 444 output_queue = queue.Queue(maxsize=max(2 * sum(batch_sizes), 2 * num_write_workers, 2)) 445 progress_queue = queue.Queue() 446 stop_event = threading.Event() 447 error_box = [] 448 error_lock = threading.Lock() 449 remaining_producers = _AtomicCounter(num_prefetch_workers) 450 remaining_consumers = _AtomicCounter(len(model_devices)) 451 452 def record_error(exc): 453 with error_lock: 454 if not error_box: 455 error_box.append(exc) 456 stop_event.set() 457 458 def producer(): 459 try: 460 while True: 461 spec = job_queue.get() 462 if spec is STOP or stop_event.is_set(): 463 break 464 _safe_put(input_queue, _PipelineJob(spec, load_fn(spec)), stop_event) 465 except _PipelineAborted: 466 pass 467 except Exception as exc: # noqa 468 record_error(exc) 469 finally: 470 # A timed put: a consumer that fails while the queue is full leaves nobody to drain it, 471 # and a blocking put would then hang this thread (and the join in the outer cleanup). 472 if remaining_producers.decrement() == 0: 473 with contextlib.suppress(_PipelineAborted): 474 for _ in model_devices: 475 _safe_put(input_queue, STOP, stop_event) 476 477 def consumer(worker_id): 478 model, device = model_devices[worker_id] 479 batch_size = batch_sizes[worker_id] 480 try: 481 while True: 482 batch = [] 483 got_stop = False 484 while len(batch) < batch_size: 485 item = _safe_get(input_queue, stop_event) 486 if item is STOP: 487 got_stop = True 488 break 489 batch.append(item) 490 491 if batch: 492 with torch.no_grad(): 493 predictions, safe_batch_size = _predict_with_oom_backoff( 494 model, [item.data for item in batch], device, predict_fn, 495 ) 496 batch_size = min(batch_size, safe_batch_size) 497 if len(predictions) != len(batch): 498 raise RuntimeError( 499 f"The batch predictor returned {len(predictions)} outputs for {len(batch)} inputs." 500 ) 501 for item, prediction in zip(batch, predictions): 502 item.data = prediction 503 _safe_put(output_queue, item, stop_event) 504 505 if got_stop: 506 break 507 except _PipelineAborted: 508 pass 509 except Exception as exc: # noqa 510 record_error(exc) 511 finally: 512 # Timed as well, for the same reason: the writers can already have failed and stopped. 513 if remaining_consumers.decrement() == 0: 514 with contextlib.suppress(_PipelineAborted): 515 for _ in range(num_write_workers): 516 _safe_put(output_queue, STOP, stop_event) 517 518 def writer(): 519 try: 520 while True: 521 item = _safe_get(output_queue, stop_event) 522 if item is STOP: 523 break 524 write_fn(item.spec, item.data) 525 if update_progress is not None: 526 increment = 1 if progress_increment is None else int(progress_increment(item.spec)) 527 progress_queue.put(increment) 528 except _PipelineAborted: 529 pass 530 except Exception as exc: # noqa 531 record_error(exc) 532 533 writer_threads = [ 534 threading.Thread(target=writer, name=f"sam2-writer-{worker_id}") 535 for worker_id in range(num_write_workers) 536 ] 537 consumer_threads = [ 538 threading.Thread(target=consumer, args=(worker_id,), name=f"sam2-consumer-{worker_id}") 539 for worker_id in range(len(model_devices)) 540 ] 541 producer_threads = [ 542 threading.Thread(target=producer, name=f"sam2-producer-{worker_id}") 543 for worker_id in range(num_prefetch_workers) 544 ] 545 threads = [*writer_threads, *consumer_threads, *producer_threads] 546 547 def forward_progress(block): 548 increments = 0 549 try: 550 increments = progress_queue.get(timeout=0.05 if block else 0) 551 except queue.Empty: 552 return 553 while True: 554 try: 555 increments += progress_queue.get_nowait() 556 except queue.Empty: 557 break 558 update_progress(increments) 559 560 try: 561 for thread in threads: 562 thread.start() 563 if update_progress is None: 564 for thread in threads: 565 thread.join() 566 else: 567 # The writer performs I/O off-thread, but UI progress callbacks must run on the calling 568 # thread. Poll completed writes here instead of queuing Qt signals behind this wait. 569 while any(thread.is_alive() for thread in threads): 570 forward_progress(block=True) 571 for thread in threads: 572 thread.join() 573 forward_progress(block=False) 574 finally: 575 stop_event.set() 576 for thread in threads: 577 thread.join() 578 579 if error_box: 580 raise error_box[0] 581 582 583def _clear_group(group) -> None: 584 for key in list(group.keys()): 585 del group[key] 586 587 588def _embedding_cache_complete(features, root) -> bool: 589 return bool(features.attrs.get("complete", "input_size" in root.attrs)) 590 591 592def _prepare_encoder_pipeline( 593 predictor, n_jobs: int, batch_size: Optional[int], devices: Devices, 594) -> Tuple[torch.nn.Module, List[Tuple[torch.nn.Module, torch.device]], List[int]]: 595 # Validated before the replicas are created, so an invalid argument never allocates on a GPU. 596 if batch_size is not None and int(batch_size) < 1: 597 raise ValueError(f"batch_size must be positive or None, got {batch_size}.") 598 599 model = getattr(predictor, "model", predictor) 600 resolved_devices = _resolve_devices(model, devices) 601 model_devices = _prepare_models(model, resolved_devices) 602 try: 603 if batch_size is None: 604 # Read after the replicas are placed, so their weights already count against the free VRAM. 605 model_type = getattr(model, "model_type", None) or getattr(predictor, "model_type", "") 606 # Cap by the share of the work a device receives, not by the total: a consumer fills its 607 # batch before it runs, so a batch as large as all jobs would keep the other devices idle. 608 jobs_per_device = (max(int(n_jobs), 0) + len(model_devices) - 1) // len(model_devices) 609 batch_sizes = [ 610 recommend_batch_size(model_type, device, n_jobs=jobs_per_device) for _, device in model_devices 611 ] 612 else: 613 batch_sizes = [int(batch_size)] * len(model_devices) 614 except Exception: 615 _release_model_replicas(model_devices) 616 raise 617 return model, model_devices, batch_sizes 618 619 620def _forward_image_batch( 621 model: torch.nn.Module, items: List[Dict], device: torch.device, feature_sizes: Sequence, 622) -> List[Dict]: 623 batch = torch.stack([item["tensor"] for item in items]).to(device, non_blocking=True) 624 # The embedding cache is fp32 and numpy has no bfloat16. 625 with autocast(device): 626 backbone_out = to_float32(model.forward_image(batch)) 627 _, vision_feats, _, _ = model._prepare_backbone_features(backbone_out) 628 if model.directly_add_no_mem_embed: 629 vision_feats[-1] = vision_feats[-1] + model.no_mem_embed 630 631 batch_size = len(items) 632 features = [ 633 feat.permute(1, 2, 0).reshape(batch_size, -1, *feat_size) 634 for feat, feat_size in zip(vision_feats[::-1], feature_sizes[::-1]) 635 ][::-1] 636 features = [feature.detach().cpu().numpy() for feature in features] 637 return [ 638 { 639 "features": features[-1][index:index + 1], 640 "high_res_feats": [feature[index:index + 1] for feature in features[:-1]], 641 "original_size": items[index]["original_size"], 642 } 643 for index in range(batch_size) 644 ] 645 646 647def _compute_tiled_2d( 648 input_: np.ndarray, 649 predictor, 650 tile_shape: Tuple[int, int], 651 halo: Tuple[int, int], 652 root, 653 save_path: Optional[Union[str, os.PathLike]], 654 pbar_init: Callable, 655 pbar_update: Callable, 656 batch_size: Optional[int] = None, 657 devices: Devices = None, 658 num_prefetch_workers: int = 4, 659 num_write_workers: int = 2, 660) -> Dict: 661 """Compute 2d tile embeddings with batched encoders and queued input / output I/O. 662 663 Args: 664 input_: The input image, shape (Y, X) or (Y, X, C). 665 predictor: The SAM2 image predictor. 666 tile_shape: The in-plane tile shape. 667 halo: The in-plane tile halo (overlap). 668 root: The zarr container the embeddings are written to (see `micro_sam.util._open_embeddings`). 669 save_path: The path backing `root`, or None for an in-memory container. A complete cache at 670 this path is returned as is instead of being recomputed. 671 pbar_init: Callback to initialize an external progress bar. 672 pbar_update: Callback to update an external progress bar. 673 batch_size: The number of tiles per encoder call. By default it is looked up from the 674 free VRAM of each CUDA device (see `util.recommend_batch_size`). 675 devices: The device or devices to run inference on (see `_resolve_devices`). 676 num_prefetch_workers: The number of threads used to read and preprocess tiles. 677 num_write_workers: The number of threads used to write embedding tiles. 678 679 Returns: 680 The tiled image embeddings. 'features' and 'high_res_feats' are the zarr groups holding the 681 per-tile datasets; 'input_size' and 'original_size' are None because they are stored per tile. 682 """ 683 from bioimage_cpp.utils import Blocking 684 from micro_sam.v2.util import _write_embedding_signature 685 686 features = root.require_group("features") 687 high_res_group = root.require_group("high_res_feats") 688 if save_path is not None and "shape" in features.attrs and _embedding_cache_complete(features, root): 689 return {"features": features, "high_res_feats": high_res_group, "input_size": None, "original_size": None} 690 691 _clear_group(features) 692 _clear_group(high_res_group) 693 694 tiling = Blocking([0, 0], list(input_.shape[:2]), list(tile_shape)) 695 n_tiles = tiling.number_of_blocks 696 features.attrs["shape"] = list(input_.shape[:2]) 697 features.attrs["tile_shape"] = list(tile_shape) 698 features.attrs["halo"] = list(halo) 699 features.attrs["complete"] = False 700 701 pbar_init(n_tiles, "Compute Image Embeddings 2D tiled") 702 model, model_devices, batch_sizes = _prepare_encoder_pipeline(predictor, n_tiles, batch_size, devices) 703 feature_sizes = predictor._bb_feat_sizes 704 705 def load_tile(tile_id): 706 block = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 707 bb = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end)) 708 image = to_image(np.asarray(input_[bb])) 709 return {"tensor": predictor._transforms(image), "original_size": tuple(image.shape[:2])} 710 711 def predict_tiles(this_model, items, device): 712 return _forward_image_batch(this_model, items, device, feature_sizes) 713 714 # Creating a dataset mutates the shared group, so it is serialized. The data (and with it the 715 # compression) is written outside the lock, which is what multiple write workers speed up. 716 creation_lock = threading.Lock() 717 718 def write_tile(tile_id, result): 719 name = str(tile_id) 720 tile_features = result["features"] 721 high_res_feats = result["high_res_feats"] 722 with creation_lock: 723 dataset = _create_dataset_without_data( 724 features, name, shape=tile_features.shape, dtype=tile_features.dtype, chunks=tile_features.shape, 725 ) 726 dataset.attrs["input_size"] = model.image_size 727 dataset.attrs["original_size"] = [list(result["original_size"])] 728 tile_high_res = high_res_group.require_group(name) 729 high_res_datasets = [ 730 _create_dataset_without_data( 731 tile_high_res, str(level), shape=feature.shape, dtype=feature.dtype, chunks=feature.shape, 732 ) for level, feature in enumerate(high_res_feats) 733 ] 734 735 dataset[:] = tile_features 736 for high_res_dataset, feature in zip(high_res_datasets, high_res_feats): 737 high_res_dataset[:] = feature 738 739 try: 740 _run_batched_pipeline( 741 jobs=range(n_tiles), 742 model_devices=model_devices, 743 batch_sizes=batch_sizes, 744 load_fn=load_tile, 745 predict_fn=predict_tiles, 746 write_fn=write_tile, 747 num_prefetch_workers=num_prefetch_workers, 748 num_write_workers=num_write_workers, 749 update_progress=pbar_update, 750 ) 751 finally: 752 _release_model_replicas(model_devices) 753 754 if save_path is not None: 755 _write_embedding_signature( 756 root, input_, predictor, tile_shape=tile_shape, halo=halo, input_size=None, 757 original_size=None, preprocessing=IMAGE_PREPROCESSING, 758 ) 759 features.attrs["complete"] = True 760 return {"features": features, "high_res_feats": high_res_group, "input_size": None, "original_size": None} 761 762 763def _prepare_video_frame(raw: np.ndarray, image_size: int, bounds=None) -> torch.Tensor: 764 from micro_sam.v2.models._video_predictor import _prepare_frame 765 766 return _prepare_frame(np.asarray(raw), image_size, bounds=bounds) 767 768 769def _forward_video_batch(model: torch.nn.Module, items: List[Dict], device: torch.device) -> List[Dict]: 770 batch = torch.stack([item["tensor"] for item in items]).to(device, non_blocking=True) 771 with autocast(device): 772 backbone_out = to_float32(model.forward_image(batch)) 773 774 vision_features = backbone_out["vision_features"].detach().cpu().numpy() 775 # Positional encodings depend only on the input shape, so every batch element is identical. 776 pos_enc = [value[:1].detach().cpu().numpy() for value in backbone_out["vision_pos_enc"]] 777 # The last FPN level is the same tensor as 'vision_features', so it is not copied or stored twice. 778 fpn = [value.detach().cpu().numpy() for value in backbone_out["backbone_fpn"][:-1]] 779 return [ 780 { 781 "features": vision_features[index:index + 1], 782 "pos_enc": pos_enc, 783 "fpn": [value[index:index + 1] for value in fpn], 784 "original_size": items[index]["original_size"], 785 } 786 for index in range(len(items)) 787 ] 788 789 790def _create_feature_dataset(group, name: str, n_slices: int, tensor: np.ndarray): 791 shape = (n_slices,) + tuple(tensor.shape) 792 chunks = (1,) + tuple(tensor.shape) 793 return _create_dataset_without_data(group, name, shape=shape, dtype="float32", chunks=chunks) 794 795 796def _check_pos_enc_shapes(pos_enc: Sequence[np.ndarray], reference: Sequence) -> None: 797 """Verify a slice's positional encodings match the single stored copy. 798 799 Args: 800 pos_enc: The positional encodings of the slice being written, each (1, C, H, W). 801 reference: The stored encodings, either the datasets or the in-memory tensors. 802 803 Raises: 804 RuntimeError: If the number of levels or any (C, H, W) differs from the stored copy. 805 """ 806 expected = [tuple(value.shape[-3:]) for value in reference] 807 actual = [tuple(value.shape[-3:]) for value in pos_enc] 808 if actual != expected: 809 raise RuntimeError( 810 f"The positional encodings differ between slices, got {actual} but stored {expected}. " 811 "A single stored copy is only valid if every frame is encoded at the same resolution." 812 ) 813 814 815def _create_feature_levels(group, n_slices: int, tensors: Sequence[np.ndarray]) -> List: 816 return [ 817 _create_feature_dataset(group, str(level), n_slices, tensor) 818 for level, tensor in enumerate(tensors) 819 ] 820 821 822def _load_feature_levels(group, lazy_loading: bool) -> List: 823 values = [] 824 level = 0 825 while str(level) in group: 826 dataset = group[str(level)] 827 values.append(dataset if lazy_loading else dataset[:]) 828 level += 1 829 return values 830 831 832def _compute_3d( 833 input_: np.ndarray, 834 predictor, 835 root, 836 save_path: Optional[Union[str, os.PathLike]], 837 lazy_loading: bool, 838 pbar_init: Callable, 839 pbar_update: Callable, 840 batch_size: Optional[int] = None, 841 devices: Devices = None, 842 num_prefetch_workers: int = 4, 843 num_write_workers: int = 2, 844 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 845) -> Dict: 846 """Compute volume embeddings by batching slices and overlapping preprocessing and zarr writes. 847 848 Args: 849 input_: The input volume, shape (Z, Y, X). 850 predictor: The SAM2 video predictor. 851 root: The zarr container the embeddings are written to (see `micro_sam.util._open_embeddings`). 852 save_path: The path backing `root`, or None to keep the embeddings in memory. A complete cache 853 at this path is returned as is instead of being recomputed. 854 lazy_loading: Whether to return the zarr datasets instead of materializing the embeddings. 855 Only has an effect if `save_path` is given. 856 pbar_init: Callback to initialize an external progress bar. 857 pbar_update: Callback to update an external progress bar. 858 batch_size: The number of slices per encoder call. By default it is looked up from the 859 free VRAM of each CUDA device (see `util.recommend_batch_size`). 860 devices: The device or devices to run inference on (see `_resolve_devices`). 861 num_prefetch_workers: The number of threads used to read and preprocess slices. 862 num_write_workers: The number of threads used to write embedding slices. 863 norm_bounds: Precomputed (lower, upper) percentile bounds (see `_volume_normalization_bounds`). 864 Computed from `input_` when not given; pass this to share one volume's bounds across a 865 caller's own tiling/blocking of it, e.g. `TiledAutomaticPromptGenerator`'s per-block calls. 866 867 Returns: 868 The volume embeddings, with the per-slice 'features', 'pos_enc' and 'fpn' outputs of the 869 image encoder as well as 'input_size' and 'original_size'. 870 """ 871 from micro_sam.v2.util import _write_embedding_signature 872 873 if save_path is not None and "original_size" in root.attrs: 874 features = root["features"] if lazy_loading else root["features"][:] 875 return { 876 "features": features, 877 "pos_enc": _load_feature_levels(root["pos_enc"], lazy_loading), 878 "fpn": _load_feature_levels(root["fpn"], lazy_loading), 879 "input_size": root.attrs["input_size"], 880 "original_size": root.attrs["original_size"], 881 } 882 883 for key in ("features", "pos_enc", "fpn"): 884 if key in root: 885 del root[key] 886 887 n_slices = int(input_.shape[0]) 888 image_size = int(predictor.image_size) 889 pbar_init(n_slices, "Compute Image Embeddings 3D") 890 model, model_devices, batch_sizes = _prepare_encoder_pipeline(predictor, n_slices, batch_size, devices) 891 892 # Computed once over the whole volume, so every slice normalizes against the same statistics 893 # instead of each one estimating its own percentiles. 894 if norm_bounds is None: 895 norm_bounds = _volume_normalization_bounds(input_) 896 897 if save_path is None: 898 feature_values = [None] * n_slices 899 fpn_values = [None] * n_slices 900 else: 901 feature_values = fpn_values = None 902 # Only one positional encoding is kept, whichever slice is written first; they are all equal. 903 pos_shared = None 904 feature_dataset = None 905 pos_datasets = None 906 fpn_datasets = None 907 908 def load_slice(z): 909 raw = np.asarray(input_[z]) 910 return { 911 "tensor": _prepare_video_frame(raw, image_size, bounds=norm_bounds), 912 "original_size": tuple(int(value) for value in raw.shape[:2]), 913 } 914 915 # The tool creates the datasets from the first result, so only their creation is serialized. The 916 # per-slice writes run in parallel (they go to separate chunks). 917 creation_lock = threading.Lock() 918 919 def write_slice(z, result): 920 nonlocal feature_dataset, pos_datasets, fpn_datasets, pos_shared 921 if save_path is None: 922 with creation_lock: 923 if pos_shared is None: 924 pos_shared = [torch.from_numpy(value) for value in result["pos_enc"]] 925 _check_pos_enc_shapes(result["pos_enc"], pos_shared) 926 feature_values[z] = torch.from_numpy(result["features"]) 927 fpn_values[z] = [torch.from_numpy(value) for value in result["fpn"]] 928 return 929 930 with creation_lock: 931 if feature_dataset is None: 932 feature_dataset = _create_feature_dataset(root, "features", n_slices, result["features"]) 933 # One entry, not one per slice: all slices share the same positional encoding. 934 pos_datasets = _create_feature_levels(root.require_group("pos_enc"), 1, result["pos_enc"]) 935 for dataset, value in zip(pos_datasets, result["pos_enc"]): 936 dataset[0] = value 937 fpn_datasets = _create_feature_levels(root.require_group("fpn"), n_slices, result["fpn"]) 938 _check_pos_enc_shapes(result["pos_enc"], pos_datasets) 939 feature_dataset[z] = result["features"] 940 for dataset, value in zip(fpn_datasets, result["fpn"]): 941 dataset[z] = value 942 943 try: 944 _run_batched_pipeline( 945 jobs=range(n_slices), 946 model_devices=model_devices, 947 batch_sizes=batch_sizes, 948 load_fn=load_slice, 949 predict_fn=_forward_video_batch, 950 write_fn=write_slice, 951 num_prefetch_workers=num_prefetch_workers, 952 num_write_workers=num_write_workers, 953 update_progress=pbar_update, 954 ) 955 finally: 956 _release_model_replicas(model_devices) 957 958 original_size = tuple(int(value) for value in input_.shape[1:3]) 959 if save_path is None: 960 features = torch.cat(feature_values).numpy() 961 n_levels = len(fpn_values[0]) 962 # Shaped like the on-disk layout, (1, 1, C, H, W), so both are read back the same way. 963 pos_enc = [value.unsqueeze(0) for value in pos_shared] 964 fpn = [torch.stack([value[level] for value in fpn_values]) for level in range(n_levels)] 965 else: 966 _write_embedding_signature( 967 root, input_, predictor, tile_shape=None, halo=None, 968 input_size=image_size, original_size=original_size, preprocessing=VIDEO_PREPROCESSING, 969 norm_bounds=norm_bounds, 970 ) 971 features = feature_dataset if lazy_loading else feature_dataset[:] 972 pos_enc = _load_feature_levels(root["pos_enc"], lazy_loading) 973 fpn = _load_feature_levels(root["fpn"], lazy_loading) 974 975 return { 976 "features": features, 977 "pos_enc": pos_enc, 978 "fpn": fpn, 979 "input_size": image_size, 980 "original_size": original_size, 981 } 982 983 984def _compute_tiled_3d( 985 input_: np.ndarray, 986 predictor, 987 tile_shape: Tuple[int, int], 988 halo: Tuple[int, int], 989 root, 990 save_path: Optional[Union[str, os.PathLike]], 991 pbar_init: Callable, 992 pbar_update: Callable, 993 batch_size: Optional[int] = None, 994 devices: Devices = None, 995 num_prefetch_workers: int = 4, 996 num_write_workers: int = 2, 997 norm_bounds: Optional[Tuple[np.ndarray, np.ndarray]] = None, 998) -> Dict: 999 """Compute tile / slice embeddings as one pipelined job stream across all available GPUs. 1000 1001 Every (tile, slice) pair is a separate job, so tiles and slices are batched together instead of 1002 tile column by tile column. This keeps all devices busy even for few tiles or few slices. 1003 1004 Args: 1005 input_: The input volume, shape (Z, Y, X). 1006 predictor: The SAM2 video predictor. 1007 tile_shape: The in-plane tile shape. The volume is not tiled along z. 1008 halo: The in-plane tile halo (overlap). 1009 root: The zarr container the embeddings are written to (see `micro_sam.util._open_embeddings`). 1010 save_path: The path backing `root`, or None for an in-memory container. A complete cache at 1011 this path is returned as is instead of being recomputed. 1012 pbar_init: Callback to initialize an external progress bar. 1013 pbar_update: Callback to update an external progress bar. 1014 batch_size: The number of tile slices per encoder call. By default it is looked up from 1015 the free VRAM of each CUDA device (see `util.recommend_batch_size`). 1016 devices: The device or devices to run inference on (see `_resolve_devices`). 1017 num_prefetch_workers: The number of threads used to read and preprocess tile slices. 1018 num_write_workers: The number of threads used to write embedding tile slices. 1019 norm_bounds: Precomputed (lower, upper) percentile bounds (see `_volume_normalization_bounds`). 1020 Computed from `input_` when not given; pass this to share one volume's bounds across a 1021 caller's own tiling/blocking of it, e.g. `TiledAutomaticPromptGenerator`'s per-block calls. 1022 1023 Returns: 1024 The tiled volume embeddings. 'features', 'pos_enc' and 'fpn' are the zarr groups holding the 1025 per-tile datasets; 'input_size' and 'original_size' are None because they are stored per tile. 1026 """ 1027 from bioimage_cpp.utils import Blocking 1028 from micro_sam.v2.util import _write_embedding_signature 1029 1030 features = root.require_group("features") 1031 pos_enc_group = root.require_group("pos_enc") 1032 fpn_group = root.require_group("fpn") 1033 if save_path is not None and "shape" in features.attrs and _embedding_cache_complete(features, root): 1034 return { 1035 "features": features, 1036 "pos_enc": pos_enc_group, 1037 "fpn": fpn_group, 1038 "input_size": None, 1039 "original_size": None, 1040 } 1041 1042 _clear_group(features) 1043 _clear_group(pos_enc_group) 1044 _clear_group(fpn_group) 1045 1046 tiling = Blocking([0, 0], list(input_.shape[1:3]), list(tile_shape)) 1047 n_tiles = tiling.number_of_blocks 1048 n_slices = int(input_.shape[0]) 1049 image_size = int(predictor.image_size) 1050 jobs = [(tile_id, z) for tile_id in range(n_tiles) for z in range(n_slices)] 1051 1052 features.attrs["shape"] = list(input_.shape[:3]) 1053 features.attrs["tile_shape"] = list(tile_shape) 1054 features.attrs["halo"] = list(halo) 1055 features.attrs["complete"] = False 1056 pbar_init(len(jobs), "Compute Image Embeddings 3D tiled") 1057 1058 tile_bounds = {} 1059 for tile_id in range(n_tiles): 1060 block = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 1061 tile_bounds[tile_id] = tuple(slice(begin, end) for begin, end in zip(block.begin, block.end)) 1062 1063 # Computed once over the whole volume, so every tile normalizes against the same statistics 1064 # instead of each one estimating its own percentiles from its own, smaller crop. 1065 if norm_bounds is None: 1066 norm_bounds = _volume_normalization_bounds(input_) 1067 1068 model, model_devices, batch_sizes = _prepare_encoder_pipeline(predictor, len(jobs), batch_size, devices) 1069 tile_datasets = {} 1070 1071 def load_tile_slice(job): 1072 tile_id, z = job 1073 bb = tile_bounds[tile_id] 1074 raw = np.asarray(input_[z, bb[0], bb[1]]) 1075 return { 1076 "tensor": _prepare_video_frame(raw, image_size, bounds=norm_bounds), 1077 "original_size": tuple(int(value) for value in raw.shape[:2]), 1078 } 1079 1080 # The tool creates a tile's datasets from its first slice, so only their creation is serialized. The 1081 # per-slice writes run in parallel (they go to separate chunks). 1082 creation_lock = threading.Lock() 1083 1084 def write_tile_slice(job, result): 1085 tile_id, z = job 1086 with creation_lock: 1087 if tile_id not in tile_datasets: 1088 name = str(tile_id) 1089 feature_dataset = _create_feature_dataset(features, name, n_slices, result["features"]) 1090 feature_dataset.attrs["input_size"] = image_size 1091 feature_dataset.attrs["original_size"] = list(result["original_size"]) 1092 # One entry per tile rather than one per slice, see `write_slice` in `_compute_3d`. 1093 pos_datasets = _create_feature_levels( 1094 pos_enc_group.require_group(name), 1, result["pos_enc"], 1095 ) 1096 for dataset, value in zip(pos_datasets, result["pos_enc"]): 1097 dataset[0] = value 1098 fpn_datasets = _create_feature_levels( 1099 fpn_group.require_group(name), n_slices, result["fpn"], 1100 ) 1101 tile_datasets[tile_id] = feature_dataset, pos_datasets, fpn_datasets 1102 1103 feature_dataset, pos_datasets, fpn_datasets = tile_datasets[tile_id] 1104 _check_pos_enc_shapes(result["pos_enc"], pos_datasets) 1105 feature_dataset[z] = result["features"] 1106 for dataset, value in zip(fpn_datasets, result["fpn"]): 1107 dataset[z] = value 1108 1109 try: 1110 _run_batched_pipeline( 1111 jobs=jobs, 1112 model_devices=model_devices, 1113 batch_sizes=batch_sizes, 1114 load_fn=load_tile_slice, 1115 predict_fn=_forward_video_batch, 1116 write_fn=write_tile_slice, 1117 num_prefetch_workers=num_prefetch_workers, 1118 num_write_workers=num_write_workers, 1119 update_progress=pbar_update, 1120 ) 1121 finally: 1122 _release_model_replicas(model_devices) 1123 1124 if save_path is not None: 1125 _write_embedding_signature( 1126 root, input_, predictor, tile_shape=tile_shape, halo=halo, input_size=None, 1127 original_size=None, preprocessing=VIDEO_PREPROCESSING, norm_bounds=norm_bounds, 1128 ) 1129 features.attrs["complete"] = True 1130 return { 1131 "features": features, 1132 "pos_enc": pos_enc_group, 1133 "fpn": fpn_group, 1134 "input_size": None, 1135 "original_size": None, 1136 } 1137 1138 1139class _EmptyEncoder(torch.nn.Module): 1140 """Lightweight placeholder used while replicating decoder-only UniSAM2 models.""" 1141 1142 def __init__(self, img_size: int) -> None: 1143 super().__init__() 1144 self.img_size = img_size 1145 1146 def forward(self, x: torch.Tensor): 1147 raise RuntimeError("The decoder-only placeholder must be replaced before inference.") 1148 1149 1150def _normalize_feature_block(block: np.ndarray) -> torch.Tensor: 1151 block = np.asarray(block) 1152 if block.ndim == 5 and block.shape[1] == 1: 1153 block = block[:, 0] 1154 if block.ndim == 3: 1155 block = block[None] 1156 if block.ndim != 4: 1157 raise ValueError(f"Expected a (Z, C, H, W) feature block, got shape {block.shape}.") 1158 return torch.from_numpy(np.asarray(block, dtype="float32")) 1159 1160 1161def _load_job(job: Dict) -> Dict: 1162 source = job["source"] 1163 selection = job.get("selection") 1164 block = np.asarray(source) if selection is None else np.asarray(source[selection]) 1165 return { 1166 "feature": _normalize_feature_block(block), 1167 "original_size": job["original_size"], 1168 } 1169 1170 1171def _predict_jobs(model: torch.nn.Module, items: List[Dict], device: torch.device) -> List[np.ndarray]: 1172 from micro_sam.v2.instance_segmentation import _decode_3d_feature_batch 1173 1174 original_size = items[0]["original_size"] 1175 if any(item["original_size"] != original_size for item in items): 1176 raise RuntimeError("Decoder jobs with different output sizes cannot share a batch.") 1177 features = torch.stack([item["feature"] for item in items]).to(device, non_blocking=True) 1178 output = _decode_3d_feature_batch(model, features, original_size, device) 1179 predictions = [np.array(value) for value in output] 1180 _release_fragmented_cuda_cache(device) 1181 return predictions 1182 1183 1184def _feature_shape(job: Dict) -> Tuple[int, ...]: 1185 source_shape = tuple(job["source"].shape) 1186 selection = job.get("selection") 1187 if selection is None: 1188 shape = source_shape 1189 else: 1190 start = 0 if selection.start is None else selection.start 1191 stop = source_shape[0] if selection.stop is None else selection.stop 1192 shape = (stop - start,) + source_shape[1:] 1193 1194 if len(shape) == 5 and shape[1] == 1: 1195 shape = (shape[0],) + shape[2:] 1196 if len(shape) == 3: 1197 shape = (1,) + shape 1198 if len(shape) != 4: 1199 raise ValueError(f"Expected feature shape (Z, C, H, W), got {shape}.") 1200 return shape 1201 1202 1203@contextlib.contextmanager 1204def _decoder_only(model: torch.nn.Module): 1205 """Replace the model's image encoder for the duration of the block, so only the decoder is run. 1206 1207 The encoder is not needed when decoding precomputed embeddings, and replicating it per device 1208 would waste memory. Restoring it is a context manager (rather than scattered cleanup) so the 1209 caller's model gets its encoder back on every exit path. 1210 """ 1211 encoder = model.encoder 1212 model.encoder = _EmptyEncoder(getattr(encoder, "img_size", 1024)) 1213 try: 1214 yield 1215 finally: 1216 model.encoder = encoder 1217 1218 1219def _prepare_decoder_pipeline( 1220 model: torch.nn.Module, 1221 jobs: List[Dict], 1222 batch_size: Optional[int], 1223 resolved_devices: Sequence[torch.device], 1224) -> Tuple[List[Tuple[torch.nn.Module, torch.device]], List[int]]: 1225 """Replicate the decoder and select its batch size. Must run inside `_decoder_only`.""" 1226 model_devices = _prepare_models(model, resolved_devices) 1227 try: 1228 if batch_size is not None: 1229 if int(batch_size) < 1: 1230 raise ValueError(f"batch_size must be positive or None, got {batch_size}.") 1231 return model_devices, [int(batch_size)] * len(model_devices) 1232 1233 representative = max( 1234 jobs, 1235 key=lambda job: np.prod(_feature_shape(job)) * np.prod(job["original_size"]), 1236 ) 1237 z, channels, height, width = _feature_shape(representative) 1238 original_size = representative["original_size"] 1239 1240 def prediction_function(this_model, inputs): 1241 from micro_sam.v2.instance_segmentation import _decode_3d_feature_batch 1242 1243 features = inputs.permute(0, 2, 1, 3, 4) 1244 return _decode_3d_feature_batch( 1245 this_model, features, original_size, inputs.device, 1246 ) 1247 1248 batch_sizes = _compute_auto_batch_sizes( 1249 model_devices=model_devices, 1250 n_jobs=len(jobs), 1251 patch_shape=(z, height, width), 1252 in_channels=channels, 1253 prediction_function=prediction_function, 1254 ) 1255 except Exception: 1256 _release_model_replicas(model_devices) 1257 raise 1258 return model_devices, batch_sizes 1259 1260 1261def _run_decoder_jobs( 1262 model: torch.nn.Module, 1263 jobs: List[Dict], 1264 write_fn: Callable[[Dict, np.ndarray], None], 1265 batch_size: Optional[int] = None, 1266 devices: Devices = None, 1267 num_prefetch_workers: int = 4, 1268 num_write_workers: int = 2, 1269 update_progress: Optional[Callable[[int], None]] = None, 1270 progress_increment: Optional[Callable[[Dict], int]] = None, 1271) -> None: 1272 if len(jobs) == 0: 1273 return 1274 1275 # Resolved before the encoder is swapped out, so the device is read off the full model. 1276 resolved_devices = _resolve_devices(model, devices) 1277 with _decoder_only(model): 1278 groups = defaultdict(list) 1279 for job in jobs: 1280 groups[(_feature_shape(job), job["original_size"])].append(job) 1281 1282 # Run the largest shape first so later, smaller groups can reuse its allocator blocks. Starting 1283 # with a boundary z-block and growing to the full context fragmented 10 GB MIG allocators. 1284 group_keys = sorted(groups, key=lambda key: np.prod(key[0]) * np.prod(key[1]), reverse=True) 1285 1286 model_devices, batch_sizes = _prepare_decoder_pipeline(model, jobs, batch_size, resolved_devices) 1287 try: 1288 for group_key in group_keys: 1289 group_jobs = groups[group_key] 1290 _run_batched_pipeline( 1291 jobs=group_jobs, 1292 model_devices=model_devices, 1293 batch_sizes=batch_sizes, 1294 load_fn=_load_job, 1295 predict_fn=_predict_jobs, 1296 write_fn=write_fn, 1297 num_prefetch_workers=num_prefetch_workers, 1298 num_write_workers=num_write_workers, 1299 update_progress=update_progress, 1300 progress_increment=progress_increment, 1301 ) 1302 finally: 1303 _release_model_replicas(model_devices) 1304 1305 1306def _resolve_z_blocking(z_block: Optional[int], z_halo: Optional[int]) -> Tuple[int, int]: 1307 """Resolve the z block / halo used to decode a volume, falling back to the defaults.""" 1308 from micro_sam.v2.util import DEFAULT_HALO_Z, DEFAULT_TILE_Z 1309 1310 z_block = DEFAULT_TILE_Z if z_block is None else int(z_block) 1311 z_halo = DEFAULT_HALO_Z if z_halo is None else int(z_halo) 1312 if z_block < 1 or z_halo < 0: 1313 raise ValueError(f"z_block must be positive and z_halo non-negative, got {z_block}, {z_halo}.") 1314 return z_block, z_halo 1315 1316 1317def _decode_volume_embeddings( 1318 model: torch.nn.Module, 1319 image_embeddings: Dict, 1320 z_block: Optional[int] = None, 1321 z_halo: Optional[int] = None, 1322 pbar_init: Optional[Callable] = None, 1323 pbar_update: Optional[Callable] = None, 1324 batch_size: Optional[int] = None, 1325 devices: Devices = None, 1326 num_prefetch_workers: int = 4, 1327 num_write_workers: int = 2, 1328) -> np.ndarray: 1329 """Decode z blocks from non-tiled volume embeddings with queued reads and batched inference. 1330 1331 The volume is decoded in blocks of `z_block` slices, each extended by `z_halo` context slices 1332 that are cropped away again when the block is written. 1333 1334 Args: 1335 model: The UniSAM2 model. Its encoder is bypassed, only the decoder is run. 1336 image_embeddings: The volume embeddings (see `_compute_3d`). 1337 device: Unused, kept for interface compatibility. Use `devices` instead. 1338 z_block: The number of slices decoded per block. By default `micro_sam.v2.util.DEFAULT_TILE_Z`. 1339 z_halo: The number of context slices per block. By default `micro_sam.v2.util.DEFAULT_HALO_Z`. 1340 pbar_init: Callback to initialize an external progress bar. 1341 pbar_update: Callback to update an external progress bar. 1342 batch_size: The number of z blocks per decoder call. By default candidate sizes are 1343 benchmarked and a throughput-efficient value is selected on each CUDA device. 1344 devices: The device or devices to run inference on (see `_resolve_devices`). 1345 num_prefetch_workers: The number of threads used to read embedding blocks. 1346 num_write_workers: The number of threads used to write decoded blocks. 1347 1348 Returns: 1349 The decoder predictions, shape (5, Z, Y, X): foreground, the three distances and the boundary. 1350 1351 Raises: 1352 ValueError: If the features are not 3d, if `z_block` is not positive or `z_halo` is negative. 1353 """ 1354 features = image_embeddings["features"] 1355 n_dims = len(features.shape) 1356 if n_dims not in (4, 5): 1357 raise ValueError( 1358 f"Decoder-from-embeddings (3d) requires features with ndim 4 or 5, got {n_dims}." 1359 ) 1360 1361 n_slices = int(features.shape[0]) 1362 z_block, z_halo = _resolve_z_blocking(z_block, z_halo) 1363 1364 original_size = tuple(int(value) for value in np.asarray(image_embeddings["original_size"]).reshape(-1)[:2]) 1365 output = np.zeros((UNISAM2_OUTPUT_CHANNELS, n_slices, *original_size), dtype="float32") 1366 jobs = [] 1367 for z0 in range(0, n_slices, z_block): 1368 z1 = min(z0 + z_block, n_slices) 1369 c0, c1 = max(0, z0 - z_halo), min(n_slices, z1 + z_halo) 1370 jobs.append({ 1371 "source": features, 1372 "selection": slice(c0, c1), 1373 "original_size": original_size, 1374 "z0": z0, 1375 "z1": z1, 1376 "c0": c0, 1377 }) 1378 1379 if pbar_init is not None: 1380 pbar_init(n_slices, "Automatic segmentation (volume)") 1381 1382 def write_prediction(job, prediction): 1383 inner = job["z0"] - job["c0"] 1384 count = job["z1"] - job["z0"] 1385 output[:, job["z0"]:job["z1"]] = prediction[:, inner:inner + count] 1386 1387 _run_decoder_jobs( 1388 model, jobs, write_prediction, batch_size=batch_size, devices=devices, 1389 num_prefetch_workers=num_prefetch_workers, num_write_workers=num_write_workers, 1390 update_progress=pbar_update, progress_increment=lambda job: job["z1"] - job["z0"], 1391 ) 1392 return output 1393 1394 1395def _tiled_metadata(image_embeddings: Dict, is_3d: bool) -> Tuple: 1396 from bioimage_cpp.utils import Blocking 1397 1398 features = image_embeddings["features"] 1399 shape = tuple(int(value) for value in features.attrs["shape"]) 1400 tile_shape = tuple(int(value) for value in features.attrs["tile_shape"]) 1401 halo = tuple(int(value) for value in features.attrs["halo"]) 1402 spatial_shape = shape[1:] if is_3d else shape 1403 tiling = Blocking([0, 0], list(spatial_shape), list(tile_shape)) 1404 return features, shape, halo, tiling 1405 1406 1407def _decode_tiled_2d_embeddings( 1408 model: torch.nn.Module, 1409 image_embeddings: Dict, 1410 pbar_init: Optional[Callable] = None, 1411 pbar_update: Optional[Callable] = None, 1412 batch_size: Optional[int] = None, 1413 devices: Devices = None, 1414 num_prefetch_workers: int = 4, 1415 num_write_workers: int = 2, 1416) -> np.ndarray: 1417 """Decode and stitch 2d embedding tiles in automatically sized batches. 1418 1419 Args: 1420 model: The UniSAM2 model. Its encoder is bypassed, only the decoder is run. 1421 image_embeddings: The tiled image embeddings (see `_compute_tiled_2d`). 1422 pbar_init: Callback to initialize an external progress bar. 1423 pbar_update: Callback to update an external progress bar. 1424 batch_size: The number of tiles per decoder call. By default candidate sizes are benchmarked 1425 and a throughput-efficient value is selected on each CUDA device. 1426 devices: The device or devices to run inference on (see `_resolve_devices`). 1427 num_prefetch_workers: The number of threads used to read embedding tiles. 1428 num_write_workers: The number of threads used to stitch decoded tiles into the output. 1429 1430 Returns: 1431 The stitched decoder predictions, shape (5, Y, X): foreground, the three distances and the boundary. 1432 """ 1433 features, shape, halo, tiling = _tiled_metadata(image_embeddings, is_3d=False) 1434 output = np.zeros((UNISAM2_OUTPUT_CHANNELS, *shape), dtype="float32") 1435 jobs = [] 1436 for tile_id in range(tiling.number_of_blocks): 1437 tile_features = features[str(tile_id)] 1438 original_size = tuple(int(value) for value in np.asarray(tile_features.attrs["original_size"]).reshape(-1)[:2]) 1439 jobs.append({ 1440 "source": tile_features, 1441 "selection": None, 1442 "original_size": original_size, 1443 "tile_id": tile_id, 1444 }) 1445 1446 if pbar_init is not None: 1447 pbar_init(len(jobs), "Automatic segmentation (tiles)") 1448 1449 def write_prediction(job, prediction): 1450 block = tiling.get_block_with_halo(job["tile_id"], halo=list(halo)) 1451 local = tuple(slice(begin, end) for begin, end in zip( 1452 block.inner_block_local.begin, block.inner_block_local.end, 1453 )) 1454 inner = tuple(slice(begin, end) for begin, end in zip( 1455 block.inner_block.begin, block.inner_block.end, 1456 )) 1457 output[(slice(None),) + inner] = prediction[(slice(None), slice(0, 1)) + local][:, 0] 1458 1459 _run_decoder_jobs( 1460 model, jobs, write_prediction, batch_size=batch_size, devices=devices, 1461 num_prefetch_workers=num_prefetch_workers, num_write_workers=num_write_workers, 1462 update_progress=pbar_update, 1463 ) 1464 return output 1465 1466 1467def _tiled_3d_jobs(features, tiling, n_slices: int, z_block: int, z_halo: int) -> List[Dict]: 1468 jobs = [] 1469 for tile_id in range(tiling.number_of_blocks): 1470 tile_features = features[str(tile_id)] 1471 original_size = tuple(int(value) for value in np.asarray(tile_features.attrs["original_size"]).reshape(-1)[:2]) 1472 for z0 in range(0, n_slices, z_block): 1473 z1 = min(z0 + z_block, n_slices) 1474 c0, c1 = max(0, z0 - z_halo), min(n_slices, z1 + z_halo) 1475 jobs.append({ 1476 "source": tile_features, 1477 "selection": slice(c0, c1), 1478 "original_size": original_size, 1479 "tile_id": tile_id, 1480 "z0": z0, 1481 "z1": z1, 1482 "c0": c0, 1483 }) 1484 return jobs 1485 1486 1487def _decode_tiled_3d_embeddings( 1488 model: torch.nn.Module, 1489 image_embeddings: Dict, 1490 pbar_init: Optional[Callable] = None, 1491 pbar_update: Optional[Callable] = None, 1492 z_block: Optional[int] = None, 1493 z_halo: Optional[int] = None, 1494 batch_size: Optional[int] = None, 1495 devices: Devices = None, 1496 num_prefetch_workers: int = 4, 1497 num_write_workers: int = 2, 1498) -> np.ndarray: 1499 """Batch over both tile columns and z blocks while decoding tiled 3d embeddings. 1500 1501 Args: 1502 model: The UniSAM2 model. Its encoder is bypassed, only the decoder is run. 1503 image_embeddings: The tiled volume embeddings (see `_compute_tiled_3d`). 1504 pbar_init: Callback to initialize an external progress bar. 1505 pbar_update: Callback to update an external progress bar. 1506 z_block: The number of slices decoded per block. By default `micro_sam.v2.util.DEFAULT_TILE_Z`. 1507 z_halo: The number of context slices per block. By default `micro_sam.v2.util.DEFAULT_HALO_Z`. 1508 batch_size: The number of (tile, z block) jobs per decoder call. By default candidate sizes 1509 are benchmarked and a throughput-efficient value is selected on each CUDA device. 1510 devices: The device or devices to run inference on (see `_resolve_devices`). 1511 num_prefetch_workers: The number of threads used to read embedding blocks. 1512 num_write_workers: The number of threads used to stitch decoded blocks into the output. 1513 1514 Returns: 1515 The stitched decoder predictions, shape (5, Z, Y, X): foreground, the three distances and the boundary. 1516 1517 Raises: 1518 ValueError: If `z_block` is not positive or `z_halo` is negative. 1519 """ 1520 features, shape, halo, tiling = _tiled_metadata(image_embeddings, is_3d=True) 1521 n_slices = shape[0] 1522 z_block, z_halo = _resolve_z_blocking(z_block, z_halo) 1523 jobs = _tiled_3d_jobs(features, tiling, n_slices, z_block, z_halo) 1524 output = np.zeros((UNISAM2_OUTPUT_CHANNELS, *shape), dtype="float32") 1525 1526 if pbar_init is not None: 1527 pbar_init(tiling.number_of_blocks * n_slices, "Automatic segmentation (tiles)") 1528 1529 def write_prediction(job, prediction): 1530 block = tiling.get_block_with_halo(job["tile_id"], halo=list(halo)) 1531 local = tuple(slice(begin, end) for begin, end in zip( 1532 block.inner_block_local.begin, block.inner_block_local.end, 1533 )) 1534 inner = tuple(slice(begin, end) for begin, end in zip( 1535 block.inner_block.begin, block.inner_block.end, 1536 )) 1537 z_count = job["z1"] - job["z0"] 1538 local_z = job["z0"] - job["c0"] 1539 prediction = prediction[:, local_z:local_z + z_count] 1540 output[(slice(None), slice(job["z0"], job["z1"])) + inner] = prediction[(slice(None), slice(None)) + local] 1541 1542 _run_decoder_jobs( 1543 model, jobs, write_prediction, batch_size=batch_size, devices=devices, 1544 num_prefetch_workers=num_prefetch_workers, num_write_workers=num_write_workers, 1545 update_progress=pbar_update, progress_increment=lambda job: job["z1"] - job["z0"], 1546 ) 1547 return output 1548 1549 1550def _decode_tiled_3d_slice( 1551 model: torch.nn.Module, 1552 image_embeddings: Dict, 1553 index: int, 1554 pbar_init: Optional[Callable] = None, 1555 pbar_update: Optional[Callable] = None, 1556 batch_size: Optional[int] = None, 1557 devices: Devices = None, 1558 num_prefetch_workers: int = 4, 1559 num_write_workers: int = 2, 1560) -> np.ndarray: 1561 """Decode one volume slice across all embedding tiles in batches. 1562 1563 Used for slice-wise automatic segmentation of a tiled volume, e.g. when only the current slice 1564 is segmented in the annotator. 1565 1566 Args: 1567 model: The UniSAM2 model. Its encoder is bypassed, only the decoder is run. 1568 image_embeddings: The tiled volume embeddings (see `_compute_tiled_3d`). 1569 index: The index of the slice to decode. 1570 pbar_init: Callback to initialize an external progress bar. 1571 pbar_update: Callback to update an external progress bar. 1572 batch_size: The number of tiles per decoder call. By default candidate sizes are benchmarked 1573 and a throughput-efficient value is selected on each CUDA device. 1574 devices: The device or devices to run inference on (see `_resolve_devices`). 1575 num_prefetch_workers: The number of threads used to read embedding tiles. 1576 num_write_workers: The number of threads used to stitch decoded tiles into the output. 1577 1578 Returns: 1579 The stitched decoder predictions for the slice, shape (5, Y, X). 1580 1581 Raises: 1582 ValueError: If `index` is outside the volume. 1583 """ 1584 features, shape, halo, tiling = _tiled_metadata(image_embeddings, is_3d=True) 1585 n_slices = shape[0] 1586 index = int(index) 1587 # A negative index would silently decode from the end, an index past the volume nothing at all. 1588 if not 0 <= index < n_slices: 1589 raise ValueError(f"The slice index must be in [0, {n_slices}), got {index}.") 1590 1591 output = np.zeros((UNISAM2_OUTPUT_CHANNELS, *shape[1:]), dtype="float32") 1592 jobs = [] 1593 for tile_id in range(tiling.number_of_blocks): 1594 tile_features = features[str(tile_id)] 1595 original_size = tuple(int(value) for value in np.asarray(tile_features.attrs["original_size"]).reshape(-1)[:2]) 1596 jobs.append({ 1597 "source": tile_features, 1598 "selection": slice(index, index + 1), 1599 "original_size": original_size, 1600 "tile_id": tile_id, 1601 }) 1602 1603 if pbar_init is not None: 1604 pbar_init(len(jobs), "Automatic segmentation (tiles)") 1605 1606 def write_prediction(job, prediction): 1607 block = tiling.get_block_with_halo(job["tile_id"], halo=list(halo)) 1608 local = tuple(slice(begin, end) for begin, end in zip( 1609 block.inner_block_local.begin, block.inner_block_local.end, 1610 )) 1611 inner = tuple(slice(begin, end) for begin, end in zip( 1612 block.inner_block.begin, block.inner_block.end, 1613 )) 1614 output[(slice(None),) + inner] = prediction[(slice(None), 0) + local] 1615 1616 _run_decoder_jobs( 1617 model, jobs, write_prediction, batch_size=batch_size, devices=devices, 1618 num_prefetch_workers=num_prefetch_workers, num_write_workers=num_write_workers, 1619 update_progress=pbar_update, 1620 ) 1621 return output
STOP =
<object object>
NORMALIZATION_SAMPLE_SLICES =
32