|
| 1 | +import os |
| 2 | +from typing import Dict, Optional, Union |
| 3 | + |
| 4 | +import pooch |
| 5 | +import torch |
| 6 | +from .file_utils import get_cache_dir |
| 7 | + |
| 8 | + |
| 9 | +def _get_default_device(): |
| 10 | + # Check that we're in CI and use the CPU if we are. |
| 11 | + # Otherwise the tests may run out of memory on MAC if MPS is used. |
| 12 | + if os.getenv("GITHUB_ACTIONS") == "true": |
| 13 | + return "cpu" |
| 14 | + # Use cuda enabled gpu if it's available. |
| 15 | + if torch.cuda.is_available(): |
| 16 | + device = "cuda" |
| 17 | + # As second priority use mps. |
| 18 | + # See https://pytorch.org/docs/stable/notes/mps.html for details |
| 19 | + elif torch.backends.mps.is_available() and torch.backends.mps.is_built(): |
| 20 | + device = "mps" |
| 21 | + # Use the CPU as fallback. |
| 22 | + else: |
| 23 | + device = "cpu" |
| 24 | + return device |
| 25 | + |
| 26 | + |
| 27 | +def get_device(device: Optional[Union[str, torch.device]] = None) -> Union[str, torch.device]: |
| 28 | + """Get the torch device. |
| 29 | +
|
| 30 | + If no device is passed the default device for your system is used. |
| 31 | + Else it will be checked if the device you have passed is supported. |
| 32 | +
|
| 33 | + Args: |
| 34 | + device: The input device. |
| 35 | +
|
| 36 | + Returns: |
| 37 | + The device. |
| 38 | + """ |
| 39 | + if device is None or device == "auto": |
| 40 | + device = _get_default_device() |
| 41 | + else: |
| 42 | + device_type = device if isinstance(device, str) else device.type |
| 43 | + if device_type.lower() == "cuda": |
| 44 | + if not torch.cuda.is_available(): |
| 45 | + raise RuntimeError("PyTorch CUDA backend is not available.") |
| 46 | + elif device_type.lower() == "mps": |
| 47 | + if not (torch.backends.mps.is_available() and torch.backends.mps.is_built()): |
| 48 | + raise RuntimeError("PyTorch MPS backend is not available or is not built correctly.") |
| 49 | + elif device_type.lower() == "cpu": |
| 50 | + pass # cpu is always available |
| 51 | + else: |
| 52 | + raise RuntimeError(f"Unsupported device: {device}. Please choose from 'cpu', 'cuda', or 'mps'.") |
| 53 | + return device |
| 54 | + |
| 55 | + |
| 56 | +# FIXME: SGN-lowres seems to be the wrong model and doesn't work well on the sample data. |
| 57 | +def get_model_registry() -> None: |
| 58 | + """Get the model registry for downloading pre-trained CochleaNet models. |
| 59 | + """ |
| 60 | + registry = { |
| 61 | + "SGN": "3058690b49015d6210a8e8414eb341c34189fee660b8fac438f1fdc41bdfff98", |
| 62 | + "IHC": "89afbcca08ed302aa6dfbaba5bf2530fc13339c05a604b6f2551d97cf5f12774", |
| 63 | + "Synapses": "2a42712b056f082b4794f15cf41b15678aab0bec1acc922ff9f0dc76abe6747e", |
| 64 | + "SGN-lowres": "6accba4b4c65158fccf25623dcd0fb3b14203305d033a0d443a307114ec5dd8c", |
| 65 | + "IHC-lowres": "537f1d4afc5a582771b87adeccadfa5635e1defd13636702363992188ef5bdbd", |
| 66 | + } |
| 67 | + urls = { |
| 68 | + "SGN": "https://owncloud.gwdg.de/index.php/s/NZ2vv7hxX1imITG/download", |
| 69 | + "IHC": "https://owncloud.gwdg.de/index.php/s/GBBJkPQFraz1ZzU/download", |
| 70 | + "Synapses": "https://owncloud.gwdg.de/index.php/s/A9W5NmOeBxiyZgY/download", |
| 71 | + "SGN-lowres": "https://owncloud.gwdg.de/index.php/s/8hwZjBVzkuYhHLm/download", |
| 72 | + "IHC-lowres": "https://owncloud.gwdg.de/index.php/s/EhnV4brhpvFbSsy/download", |
| 73 | + } |
| 74 | + cache_dir = get_cache_dir() |
| 75 | + models = pooch.create( |
| 76 | + path=os.path.join(cache_dir, "models"), |
| 77 | + base_url="", |
| 78 | + registry=registry, |
| 79 | + urls=urls, |
| 80 | + ) |
| 81 | + return models |
| 82 | + |
| 83 | + |
| 84 | +def get_model_path(model_type: str) -> str: |
| 85 | + """Get the local path to a pretrained model. |
| 86 | +
|
| 87 | + Args: |
| 88 | + The model type. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + The local path to the model. |
| 92 | + """ |
| 93 | + model_registry = get_model_registry() |
| 94 | + model_path = model_registry.fetch(model_type) |
| 95 | + return model_path |
| 96 | + |
| 97 | + |
| 98 | +def get_model(model_type: str, device: Optional[Union[str, torch.device]] = None) -> torch.nn.Module: |
| 99 | + """Get the model for a specific segmentation type. |
| 100 | +
|
| 101 | + Args: |
| 102 | + model_type: The model for one of the following segmentation or detection tasks: |
| 103 | + 'SGN', 'IHC', 'Synapses', 'SGN-lowres', 'IHC-lowres'. |
| 104 | + device: The device to use. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + The model. |
| 108 | + """ |
| 109 | + if device is None: |
| 110 | + device = get_device(device) |
| 111 | + model_path = get_model_path(model_type) |
| 112 | + model = torch.load(model_path, weights_only=False) |
| 113 | + model.to(device) |
| 114 | + return model |
| 115 | + |
| 116 | + |
| 117 | +def get_default_tiling() -> Dict[str, Dict[str, int]]: |
| 118 | + """Determine the tile shape and halo depending on the available VRAM. |
| 119 | +
|
| 120 | + Returns: |
| 121 | + The default tiling settings for the available computational resources. |
| 122 | + """ |
| 123 | + if torch.cuda.is_available(): |
| 124 | + # The default halo size. |
| 125 | + halo = {"x": 64, "y": 64, "z": 16} |
| 126 | + |
| 127 | + # Determine the GPU RAM and derive a suitable tiling. |
| 128 | + vram = torch.cuda.get_device_properties(0).total_memory / 1e9 |
| 129 | + |
| 130 | + if vram >= 80: |
| 131 | + tile = {"x": 640, "y": 640, "z": 80} |
| 132 | + elif vram >= 40: |
| 133 | + tile = {"x": 512, "y": 512, "z": 64} |
| 134 | + elif vram >= 20: |
| 135 | + tile = {"x": 352, "y": 352, "z": 48} |
| 136 | + elif vram >= 10: |
| 137 | + tile = {"x": 256, "y": 256, "z": 32} |
| 138 | + halo = {"x": 64, "y": 64, "z": 8} # Choose a smaller halo in z. |
| 139 | + else: |
| 140 | + raise NotImplementedError(f"Infererence with a GPU with {vram} GB VRAM is not supported.") |
| 141 | + |
| 142 | + tiling = {"tile": tile, "halo": halo} |
| 143 | + print(f"Determined tile size for CUDA: {tiling}") |
| 144 | + |
| 145 | + elif torch.backends.mps.is_available(): # Check for Apple Silicon (MPS) |
| 146 | + tile = {"x": 256, "y": 256, "z": 16} |
| 147 | + halo = {"x": 16, "y": 16, "z": 4} |
| 148 | + tiling = {"tile": tile, "halo": halo} |
| 149 | + print(f"Determined tile size for MPS: {tiling}") |
| 150 | + |
| 151 | + # I am not sure what is reasonable on a cpu. For now choosing very small tiling. |
| 152 | + # (This will not work well on a CPU in any case.) |
| 153 | + else: |
| 154 | + tiling = { |
| 155 | + "tile": {"x": 96, "y": 96, "z": 16}, |
| 156 | + "halo": {"x": 16, "y": 16, "z": 8}, |
| 157 | + } |
| 158 | + print(f"Determining default tiling for CPU: {tiling}") |
| 159 | + |
| 160 | + return tiling |
0 commit comments