slide2vec 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
slide2vec/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.1.0"
@@ -0,0 +1,17 @@
1
+ import pathlib
2
+
3
+ from omegaconf import OmegaConf
4
+
5
+
6
+ def load_config(config_name: str):
7
+ config_filename = config_name + ".yaml"
8
+ return OmegaConf.load(pathlib.Path(__file__).parent.resolve() / config_filename)
9
+
10
+
11
+ default_config = load_config("default")
12
+
13
+
14
+ def load_and_merge_config(config_name: str):
15
+ default_config = OmegaConf.create(default_config)
16
+ loaded_config = load_config(config_name)
17
+ return OmegaConf.merge(default_config, loaded_config)
@@ -0,0 +1,2 @@
1
+ from .dataset import TileDataset
2
+ from .augmentations import RegionUnfolding
@@ -0,0 +1,57 @@
1
+ import torch
2
+ import torchvision.transforms.functional as F
3
+
4
+ from typing import Sequence
5
+ from einops import rearrange
6
+ from torchvision import transforms
7
+
8
+ # Use timm's names
9
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
10
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
11
+
12
+
13
+ def make_normalize_transform(
14
+ mean: Sequence[float] = IMAGENET_DEFAULT_MEAN,
15
+ std: Sequence[float] = IMAGENET_DEFAULT_STD,
16
+ ) -> transforms.Normalize:
17
+ return transforms.Normalize(mean=mean, std=std)
18
+
19
+
20
+ class MaybeToTensor(transforms.ToTensor):
21
+ """
22
+ Convert a PIL Image or ndarray to tensor if it's not already one.
23
+ """
24
+
25
+ def __init__(self):
26
+ super().__init__()
27
+
28
+ def __call__(self, pic):
29
+ """
30
+ Args:
31
+ pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
32
+
33
+ Returns:
34
+ Tensor: Converted image.
35
+ """
36
+ if isinstance(pic, torch.Tensor):
37
+ return pic
38
+ return F.to_tensor(pic)
39
+
40
+ def __repr__(self):
41
+ return f"{self.__class__.__name__}()"
42
+
43
+
44
+ class RegionUnfolding:
45
+ def __init__(self, tile_size):
46
+ self.tile_size = tile_size
47
+
48
+ def __call__(self, x):
49
+ # x = [3, region_size, region_size]
50
+ # unfold into tilees and rearrange
51
+ x = x.unfold(1, self.tile_size, self.tile_size).unfold(
52
+ 2, self.tile_size, self.tile_size
53
+ ) # [3, ntile, region_size, tile_size] -> [3, ntile, ntile, tile_size, tile_size]
54
+ x = rearrange(
55
+ x, "c p1 p2 w h -> (p1 p2) c w h"
56
+ ) # [num_tilees, 3, tile_size, tile_size]
57
+ return x
@@ -0,0 +1,62 @@
1
+ import torch
2
+ import numpy as np
3
+ import wholeslidedata as wsd
4
+
5
+ from PIL import Image
6
+ from pathlib import Path
7
+
8
+
9
+ class TileDataset(torch.utils.data.Dataset):
10
+ def __init__(self, wsi_path, tile_dir, target_spacing, backend, transforms=None):
11
+ self.path = wsi_path
12
+ self.target_spacing = target_spacing
13
+ self.backend = backend
14
+ self.name = wsi_path.stem.replace(" ", "_")
15
+ self.load_coordinates(tile_dir)
16
+ self.transforms = transforms
17
+
18
+ def load_coordinates(self, tile_dir):
19
+ coordinates = np.load(Path(tile_dir, f"{self.name}.npy"), allow_pickle=True)
20
+ self.x = coordinates["x"]
21
+ self.y = coordinates["y"]
22
+ self.coordinates = (np.array([self.x, self.y]).T).astype(int)
23
+ self.scaled_coordinates = self.scale_coordinates()
24
+ self.tile_level = coordinates["tile_level"]
25
+ self.tile_size_resized = coordinates["tile_size_resized"]
26
+ self.resize_factor = coordinates["resize_factor"]
27
+ self.tile_size = (self.tile_size_resized / self.resize_factor).astype(int)
28
+ self.tile_size_lv0 = coordinates["tile_size_lv0"][0]
29
+
30
+ def scale_coordinates(self):
31
+ # coordinates are defined w.r.t. level 0
32
+ # i need to scale them to target_spacing
33
+ wsi = wsd.WholeSlideImage(self.path, backend=self.backend)
34
+ min_spacing = wsi.spacings[0]
35
+ scale = min_spacing / self.target_spacing
36
+ # create a [N, 2] array with x and y coordinates
37
+ scaled_coordinates = (self.coordinates * scale).astype(int)
38
+ return scaled_coordinates
39
+
40
+ def __len__(self):
41
+ return len(self.x)
42
+
43
+ def __getitem__(self, idx):
44
+ wsi = wsd.WholeSlideImage(
45
+ self.path, backend=self.backend
46
+ ) # cannot be defined in __init__ because of multiprocessing
47
+ tile_level = self.tile_level[idx]
48
+ tile_spacing = wsi.spacings[tile_level]
49
+ tile_arr = wsi.get_patch(
50
+ self.x[idx],
51
+ self.y[idx],
52
+ self.tile_size_resized[idx],
53
+ self.tile_size_resized[idx],
54
+ spacing=tile_spacing,
55
+ center=False,
56
+ )
57
+ tile = Image.fromarray(tile_arr).convert("RGB")
58
+ if self.tile_size[idx] != self.tile_size_resized[idx]:
59
+ tile = tile.resize((self.tile_size[idx], self.tile_size[idx]))
60
+ if self.transforms:
61
+ tile = self.transforms(tile)
62
+ return idx, tile
@@ -0,0 +1,344 @@
1
+ import os
2
+ import random
3
+ import re
4
+ import socket
5
+ import datetime
6
+ from typing import Dict, List
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+
11
+ _LOCAL_RANK = -1
12
+ _LOCAL_WORLD_SIZE = -1
13
+
14
+
15
+ def is_enabled() -> bool:
16
+ """
17
+ Returns:
18
+ True if distributed training is enabled
19
+ """
20
+ return dist.is_available() and dist.is_initialized()
21
+
22
+
23
+ def is_enabled_and_multiple_gpus() -> bool:
24
+ """
25
+ Returns:
26
+ True if distributed training is enabled and there are multiple GPUs available.
27
+ """
28
+ return (
29
+ dist.is_available() and dist.is_initialized() and torch.cuda.device_count() > 1
30
+ )
31
+
32
+
33
+ def get_global_size() -> int:
34
+ """
35
+ Returns:
36
+ The number of processes in the process group
37
+ """
38
+ return dist.get_world_size() if is_enabled() else 1
39
+
40
+
41
+ def get_global_rank() -> int:
42
+ """
43
+ Returns:
44
+ The rank of the current process within the global process group.
45
+ """
46
+ return dist.get_rank() if is_enabled() else 0
47
+
48
+
49
+ def get_local_rank() -> int:
50
+ """
51
+ Returns:
52
+ The rank of the current process within the local (per-machine) process group.
53
+ """
54
+ if not is_enabled():
55
+ return 0
56
+ assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE
57
+ return _LOCAL_RANK
58
+
59
+
60
+ def get_local_size() -> int:
61
+ """
62
+ Returns:
63
+ The size of the per-machine process group,
64
+ i.e. the number of processes per machine.
65
+ """
66
+ if not is_enabled():
67
+ return 1
68
+ assert 0 <= _LOCAL_RANK < _LOCAL_WORLD_SIZE
69
+ return _LOCAL_WORLD_SIZE
70
+
71
+
72
+ def is_main_process() -> bool:
73
+ """
74
+ Returns:
75
+ True if the current process is the main one.
76
+ """
77
+ return get_global_rank() == 0
78
+
79
+
80
+ def _restrict_print_to_main_process() -> None:
81
+ """
82
+ This function disables printing when not in the main process
83
+ """
84
+ import builtins as __builtin__
85
+
86
+ builtin_print = __builtin__.print
87
+
88
+ def print(*args, **kwargs):
89
+ force = kwargs.pop("force", False)
90
+ if is_main_process() or force:
91
+ builtin_print(*args, **kwargs)
92
+
93
+ __builtin__.print = print
94
+
95
+
96
+ def _get_master_port(seed: int = 0) -> int:
97
+ MIN_MASTER_PORT, MAX_MASTER_PORT = (20_000, 60_000)
98
+
99
+ master_port_str = os.environ.get("MASTER_PORT")
100
+ if master_port_str is None:
101
+ rng = random.Random(seed)
102
+ return rng.randint(MIN_MASTER_PORT, MAX_MASTER_PORT)
103
+
104
+ return int(master_port_str)
105
+
106
+
107
+ def _get_available_port() -> int:
108
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
109
+ # A "" host address means INADDR_ANY i.e. binding to all interfaces.
110
+ # Note this is not compatible with IPv6.
111
+ s.bind(("", 0))
112
+ port = s.getsockname()[1]
113
+ return port
114
+
115
+
116
+ _TORCH_DISTRIBUTED_ENV_VARS = (
117
+ "MASTER_ADDR",
118
+ "MASTER_PORT",
119
+ "RANK",
120
+ "WORLD_SIZE",
121
+ "LOCAL_RANK",
122
+ "LOCAL_WORLD_SIZE",
123
+ )
124
+
125
+
126
+ def _collect_env_vars() -> Dict[str, str]:
127
+ return {
128
+ env_var: os.environ[env_var]
129
+ for env_var in _TORCH_DISTRIBUTED_ENV_VARS
130
+ if env_var in os.environ
131
+ }
132
+
133
+
134
+ def _is_slurm_job_process() -> bool:
135
+ return "SLURM_JOB_ID" in os.environ
136
+
137
+
138
+ def _parse_slurm_node_list(s: str) -> List[str]:
139
+ nodes = []
140
+ # Extract "hostname", "hostname[1-2,3,4-5]," substrings
141
+ p = re.compile(r"(([^\[]+)(?:\[([^\]]+)\])?),?")
142
+ for m in p.finditer(s):
143
+ prefix, suffixes = s[m.start(2) : m.end(2)], s[m.start(3) : m.end(3)]
144
+ for suffix in suffixes.split(","):
145
+ span = suffix.split("-")
146
+ if len(span) == 1:
147
+ nodes.append(prefix + suffix)
148
+ else:
149
+ width = len(span[0])
150
+ start, end = int(span[0]), int(span[1]) + 1
151
+ nodes.extend([prefix + f"{i:0{width}}" for i in range(start, end)])
152
+ return nodes
153
+
154
+
155
+ def _check_env_variable(key: str, new_value: str):
156
+ # Only check for difference with preset environment variables
157
+ if key in os.environ and os.environ[key] != new_value:
158
+ raise RuntimeError(
159
+ f"Cannot export environment variables as {key} is already set"
160
+ )
161
+
162
+
163
+ class _TorchDistributedEnvironment:
164
+ def __init__(self):
165
+ self.master_addr = "127.0.0.1"
166
+ self.master_port = 0
167
+ self.rank = -1
168
+ self.world_size = -1
169
+ self.local_rank = -1
170
+ self.local_world_size = -1
171
+
172
+ # if _is_slurm_job_process():
173
+ # return self._set_from_slurm_env()
174
+
175
+ env_vars = _collect_env_vars()
176
+ if not env_vars:
177
+ # Environment is not set
178
+ pass
179
+ elif len(env_vars) == len(_TORCH_DISTRIBUTED_ENV_VARS):
180
+ # Environment is fully set
181
+ return self._set_from_preset_env()
182
+ else:
183
+ # Environment is partially set
184
+ collected_env_vars = ", ".join(env_vars.keys())
185
+ raise RuntimeError(f"Partially set environment: {collected_env_vars}")
186
+
187
+ if torch.cuda.device_count() > 0:
188
+ return self._set_from_local()
189
+
190
+ raise RuntimeError("Can't initialize PyTorch distributed environment")
191
+
192
+ # Slurm job created with sbatch, submitit, etc...
193
+ def _set_from_slurm_env(self):
194
+ # logger.info("Initialization from Slurm environment")
195
+ job_id = int(os.environ["SLURM_JOB_ID"])
196
+ node_count = int(os.environ["SLURM_JOB_NUM_NODES"])
197
+ nodes = _parse_slurm_node_list(os.environ["SLURM_JOB_NODELIST"])
198
+ assert len(nodes) == node_count
199
+
200
+ self.master_addr = nodes[0]
201
+ self.master_port = _get_master_port(seed=job_id)
202
+ self.rank = int(os.environ["SLURM_PROCID"])
203
+ self.world_size = int(os.environ["SLURM_NTASKS"])
204
+ assert self.rank < self.world_size
205
+ self.local_rank = int(os.environ["SLURM_LOCALID"])
206
+ self.local_world_size = self.world_size // node_count
207
+ assert self.local_rank < self.local_world_size
208
+
209
+ # Single node job with preset environment (i.e. torchrun)
210
+ def _set_from_preset_env(self):
211
+ # logger.info("Initialization from preset environment")
212
+ self.master_addr = os.environ["MASTER_ADDR"]
213
+ self.master_port = os.environ["MASTER_PORT"]
214
+ self.rank = int(os.environ["RANK"])
215
+ self.world_size = int(os.environ["WORLD_SIZE"])
216
+ assert self.rank < self.world_size
217
+ self.local_rank = int(os.environ["LOCAL_RANK"])
218
+ self.local_world_size = int(os.environ["LOCAL_WORLD_SIZE"])
219
+ assert self.local_rank < self.local_world_size
220
+
221
+ # Single node and GPU job (i.e. local script run)
222
+ def _set_from_local(self):
223
+ # logger.info("Initialization from local")
224
+ self.master_addr = "127.0.0.1"
225
+ self.master_port = _get_available_port()
226
+ self.rank = 0
227
+ self.world_size = 1
228
+ self.local_rank = 0
229
+ self.local_world_size = 1
230
+
231
+ def export(self, *, overwrite: bool) -> "_TorchDistributedEnvironment":
232
+ # See the "Environment variable initialization" section from
233
+ # https://pytorch.org/docs/stable/distributed.html for the complete list of
234
+ # environment variables required for the env:// initialization method.
235
+ env_vars = {
236
+ "MASTER_ADDR": self.master_addr,
237
+ "MASTER_PORT": str(self.master_port),
238
+ "RANK": str(self.rank),
239
+ "WORLD_SIZE": str(self.world_size),
240
+ "LOCAL_RANK": str(self.local_rank),
241
+ "LOCAL_WORLD_SIZE": str(self.local_world_size),
242
+ }
243
+ if not overwrite:
244
+ for k, v in env_vars.items():
245
+ _check_env_variable(k, v)
246
+
247
+ os.environ.update(env_vars)
248
+ return self
249
+
250
+
251
+ def enable(
252
+ *,
253
+ set_cuda_current_device: bool = True,
254
+ overwrite: bool = False,
255
+ allow_nccl_timeout: bool = False,
256
+ ):
257
+ """Enable distributed mode
258
+
259
+ Args:
260
+ set_cuda_current_device: If True, call torch.cuda.set_device() to set the
261
+ current PyTorch CUDA device to the one matching the local rank.
262
+ overwrite: If True, overwrites already set variables. Else fails.
263
+ """
264
+
265
+ global _LOCAL_RANK, _LOCAL_WORLD_SIZE
266
+ if _LOCAL_RANK >= 0 or _LOCAL_WORLD_SIZE >= 0:
267
+ raise RuntimeError("Distributed mode has already been enabled")
268
+ torch_env = _TorchDistributedEnvironment()
269
+ torch_env.export(overwrite=overwrite)
270
+
271
+ if set_cuda_current_device:
272
+ torch.cuda.set_device(torch_env.local_rank)
273
+
274
+ if allow_nccl_timeout:
275
+ # This allows to use torch distributed timeout in a NCCL backend
276
+ key, value = "NCCL_ASYNC_ERROR_HANDLING", "1"
277
+ if not overwrite:
278
+ _check_env_variable(key, value)
279
+ os.environ[key] = value
280
+
281
+ dist.init_process_group(backend="nccl", timeout=datetime.timedelta(days=14))
282
+ dist.barrier()
283
+
284
+ # Finalize setup
285
+ _LOCAL_RANK = torch_env.local_rank
286
+ _LOCAL_WORLD_SIZE = torch_env.local_world_size
287
+ _restrict_print_to_main_process()
288
+
289
+
290
+ def gather_tensor(t: torch.Tensor, dst_rank: int = 0):
291
+ """
292
+ Gather a tensor t from all ranks to dst_rank.
293
+ Returns a list of size world_size on dst_rank, otherwise an empty list on other ranks.
294
+ """
295
+ gather_list = []
296
+ if dist.get_rank() == dst_rank:
297
+ gather_list = [torch.empty_like(t) for _ in range(get_global_size())]
298
+ dist.gather(t, gather_list, dst=dst_rank)
299
+ return gather_list
300
+
301
+
302
+ def gather_features(
303
+ features, indices, device, features_dim, level, scaled_coordinates=None
304
+ ):
305
+ gathered_feature = [
306
+ torch.zeros_like(features, device=device) for _ in range(get_global_size())
307
+ ]
308
+ gathered_indices = [
309
+ torch.zeros_like(indices, device=device) for _ in range(get_global_size())
310
+ ]
311
+ torch.distributed.all_gather(gathered_feature, features)
312
+ torch.distributed.all_gather(gathered_indices, indices)
313
+ # concatenate the gathered features and indices
314
+ wsi_feature = torch.cat(gathered_feature, dim=0)
315
+ tile_indices = torch.cat(gathered_indices, dim=0)
316
+ # handle duplicates
317
+ unique_indices, inverse_indices = torch.unique(
318
+ tile_indices, sorted=False, return_inverse=True
319
+ )
320
+ # create a final tensor to store the features in the correct order
321
+ coordinates = None
322
+ if level == "tile" or level == "slide":
323
+ wsi_feature_ordered = torch.zeros(
324
+ (unique_indices.size(0), features_dim), device=device
325
+ )
326
+ if level == "slide":
327
+ coordinates = torch.zeros(
328
+ (unique_indices.size(0), 2), dtype=torch.int64, device=device
329
+ )
330
+ elif level == "region":
331
+ num_tiles = features.shape[1]
332
+ wsi_feature_ordered = torch.zeros(
333
+ (unique_indices.size(0), num_tiles, features_dim), device=device
334
+ )
335
+ # insert each feature into its correct position based on tile_indices
336
+ for idx in inverse_indices:
337
+ unique_idx = unique_indices[idx]
338
+ wsi_feature_ordered[unique_idx] = wsi_feature[idx]
339
+ if level == "slide":
340
+ assert scaled_coordinates is not None
341
+ coordinates[unique_idx] = torch.tensor(
342
+ scaled_coordinates[idx], device=device
343
+ )
344
+ return wsi_feature_ordered, coordinates