-
Notifications
You must be signed in to change notification settings - Fork 378
Expand file tree
/
Copy pathsegmenter.py
More file actions
2211 lines (1822 loc) · 89.9 KB
/
segmenter.py
File metadata and controls
2211 lines (1822 loc) · 89.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import copy
import csv
import gc
import logging
import multiprocessing as mp
import os
import shutil
import sys
import time
import warnings
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable, Dict, Hashable, List, Mapping, Optional, Sequence, Tuple, Union
import numpy as np
import psutil
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import yaml
from torch.cuda.amp import GradScaler, autocast
from torch.nn.parallel import DistributedDataParallel
from torch.utils.data.distributed import DistributedSampler
from torch.utils.tensorboard import SummaryWriter
from monai.apps.auto3dseg.auto_runner import logger
from monai.apps.auto3dseg.transforms import EnsureSameShaped
from monai.auto3dseg.utils import datafold_read
from monai.bundle.config_parser import ConfigParser
from monai.config import KeysCollection
from monai.data import CacheDataset, DataLoader, Dataset, DistributedSampler, decollate_batch, list_data_collate
from monai.inferers import SlidingWindowInfererAdapt
from monai.losses import DeepSupervisionLoss
from monai.metrics import CumulativeAverage, DiceHelper
from monai.networks.layers.factories import split_args
from monai.optimizers.lr_scheduler import WarmupCosineSchedule
from monai.transforms import (
AsDiscreted,
CastToTyped,
ClassesToIndicesd,
Compose,
ConcatItemsd,
CopyItemsd,
CropForegroundd,
DataStatsd,
DeleteItemsd,
EnsureTyped,
Identityd,
Invertd,
Lambdad,
LoadImaged,
NormalizeIntensityd,
Orientationd,
RandAdjustContrastd,
RandAffined,
RandCropByLabelClassesd,
RandFlipd,
RandGaussianNoised,
RandGaussianSmoothd,
RandHistogramShiftd,
RandIdentity,
RandRotate90d,
RandScaleIntensityd,
RandScaleIntensityFixedMeand,
RandShiftIntensityd,
RandSpatialCropd,
ResampleToMatchd,
SaveImaged,
ScaleIntensityRanged,
Spacingd,
SpatialPadd,
ToDeviced,
)
from monai.transforms.transform import MapTransform
from monai.utils import ImageMetaKey, convert_to_dst_type, optional_import, set_determinism
mlflow, mlflow_is_imported = optional_import("mlflow")
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:2048"
print = logger.debug
tqdm, has_tqdm = optional_import("tqdm", name="tqdm")
if __package__ in (None, ""):
from utils import auto_adjust_network_settings, logger_configure
else:
from .utils import auto_adjust_network_settings, logger_configure
class LabelEmbedClassIndex(MapTransform):
"""
Label embedding according to class_index
"""
def __init__(
self, keys: KeysCollection = "label", allow_missing_keys: bool = False, class_index: Optional[List] = None
) -> None:
"""
Args:
keys: keys of the corresponding items to be compared to the source_key item shape.
allow_missing_keys: do not raise exception if key is missing.
class_index: a list of class indices
"""
super().__init__(keys=keys, allow_missing_keys=allow_missing_keys)
self.class_index = class_index
def label_mapping(self, x: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
return torch.cat([sum([x == i for i in c]) for c in self.class_index], dim=0).to(dtype=dtype)
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> Dict[Hashable, torch.Tensor]:
d = dict(data)
if self.class_index is not None:
for key in self.key_iterator(d):
d[key] = self.label_mapping(d[key])
return d
def schedule_validation_epochs(num_epochs, num_epochs_per_validation=None, fraction=0.16) -> list:
"""
Schedule of epochs to validate (progressively more frequently)
num_epochs - total number of epochs
num_epochs_per_validation - if provided use a linear schedule with this step
init_step
"""
if num_epochs_per_validation is None:
x = (np.sin(np.linspace(0, np.pi / 2, max(10, int(fraction * num_epochs)))) * num_epochs).astype(int)
x = np.cumsum(np.sort(np.diff(np.unique(x)))[::-1])
x[-1] = num_epochs
x = x.tolist()
else:
if num_epochs_per_validation >= num_epochs:
x = [num_epochs_per_validation]
else:
x = list(range(num_epochs_per_validation, num_epochs, num_epochs_per_validation))
if len(x) == 0:
x = [0]
return x
class DataTransformBuilder:
def __init__(
self,
roi_size: list,
image_key: str = "image",
label_key: str = "label",
resample: bool = False,
resample_resolution: Optional[list] = None,
normalize_mode: str = "meanstd",
normalize_params: Optional[dict] = None,
crop_mode: str = "ratio",
crop_params: Optional[dict] = None,
extra_modalities: Optional[dict] = None,
custom_transforms=None,
augment_params: Optional[dict] = None,
debug: bool = False,
rank: int = 0,
class_index=None,
**kwargs,
) -> None:
self.roi_size, self.image_key, self.label_key = roi_size, image_key, label_key
self.resample, self.resample_resolution = resample, resample_resolution
self.normalize_mode = normalize_mode
self.normalize_params = normalize_params if normalize_params is not None else {}
self.crop_mode = crop_mode
self.crop_params = crop_params if crop_params is not None else {}
self.augment_params = augment_params if augment_params is not None else {}
self.extra_modalities = extra_modalities if extra_modalities is not None else {}
self.custom_transforms = custom_transforms if custom_transforms is not None else {}
self.extra_options = kwargs
self.debug = debug
self.rank = rank
self.class_index = class_index
def get_custom(self, name, **kwargs):
tr = []
for t in self.custom_transforms.get(name, []):
if isinstance(t, dict):
t.update(kwargs)
t = ConfigParser(t).get_parsed_content(instantiate=True)
tr.append(t)
return tr
def get_load_transforms(self):
ts = self.get_custom("load_transforms")
if len(ts) > 0:
return ts
keys = [self.image_key, self.label_key] + list(self.extra_modalities)
ts.append(
LoadImaged(keys=keys, ensure_channel_first=True, dtype=None, allow_missing_keys=True, image_only=True)
)
ts.append(EnsureTyped(keys=keys, data_type="tensor", dtype=torch.float, allow_missing_keys=True))
ts.append(
EnsureSameShaped(keys=self.label_key, source_key=self.image_key, allow_missing_keys=True, warn=self.debug)
)
ts.extend(self.get_custom("after_load_transforms"))
return ts
def get_resample_transforms(self, resample_label=True):
ts = self.get_custom("resample_transforms", resample_label=resample_label)
if len(ts) > 0:
return ts
keys = [self.image_key, self.label_key] if resample_label else [self.image_key]
mode = ["bilinear", "nearest"] if resample_label else ["bilinear"]
extra_keys = list(self.extra_modalities)
if self.extra_options.get("orientation_ras", False):
ts.append(Orientationd(keys=keys, axcodes="RAS"))
if self.extra_options.get("crop_foreground", False) and len(extra_keys) == 0:
ts.append(
CropForegroundd(
keys=keys, source_key=self.image_key, allow_missing_keys=True, margin=10, allow_smaller=True
)
)
if self.resample:
if self.resample_resolution is None:
raise ValueError("resample_resolution is not provided")
pixdim = self.resample_resolution
ts.append(
Spacingd(
keys=keys,
pixdim=pixdim,
mode=mode,
dtype=torch.float,
min_pixdim=np.array(pixdim) * 0.75,
max_pixdim=np.array(pixdim) * 1.25,
allow_missing_keys=True,
)
)
if resample_label:
ts.append(
EnsureSameShaped(
keys=self.label_key, source_key=self.image_key, allow_missing_keys=True, warn=self.debug
)
)
for extra_key in extra_keys:
ts.append(ResampleToMatchd(keys=extra_key, key_dst=self.image_key, dtype=np.float32))
ts.extend(self.get_custom("after_resample_transforms", resample_label=resample_label))
return ts
def get_normalize_transforms(self):
ts = self.get_custom("normalize_transforms")
if len(ts) > 0:
return ts
label_dtype = self.normalize_params.get("label_dtype", None)
if label_dtype is not None:
ts.append(CastToTyped(keys=self.label_key, dtype=label_dtype, allow_missing_keys=True))
image_dtype = self.normalize_params.get("image_dtype", None)
if image_dtype is not None:
ts.append(CastToTyped(keys=self.image_key, dtype=image_dtype, allow_missing_keys=True)) # for caching
ts.append(RandIdentity()) # indicate to stop caching after this point
ts.append(CastToTyped(keys=self.image_key, dtype=torch.float, allow_missing_keys=True))
modalities = {self.image_key: self.normalize_mode}
modalities.update(self.extra_modalities)
for key, normalize_mode in modalities.items():
if normalize_mode == "none":
pass
elif normalize_mode in ["range", "ct"]:
intensity_bounds = self.normalize_params.get("intensity_bounds", None)
if intensity_bounds is None:
intensity_bounds = [-250, 250]
warnings.warn(f"intensity_bounds is not specified, assuming {intensity_bounds}")
ts.append(
ScaleIntensityRanged(
keys=key, a_min=intensity_bounds[0], a_max=intensity_bounds[1], b_min=-1, b_max=1, clip=False
)
)
ts.append(Lambdad(keys=key, func=lambda x: torch.sigmoid(x)))
elif normalize_mode in ["meanstd", "mri"]:
ts.append(NormalizeIntensityd(keys=key, nonzero=True, channel_wise=True))
elif normalize_mode in ["meanstdtanh"]:
ts.append(NormalizeIntensityd(keys=key, nonzero=True, channel_wise=True))
ts.append(Lambdad(keys=key, func=lambda x: 3 * torch.tanh(x / 3)))
elif normalize_mode in ["pet"]:
ts.append(Lambdad(keys=key, func=lambda x: torch.sigmoid((x - x.min()) / x.std())))
else:
raise ValueError("Unsupported normalize_mode" + str(self.normalize_mode))
if len(self.extra_modalities) > 0:
ts.append(ConcatItemsd(keys=list(modalities), name=self.image_key)) # concat
ts.append(DeleteItemsd(keys=list(self.extra_modalities))) # release memory
ts.extend(self.get_custom("after_normalize_transforms"))
return ts
def get_crop_transforms(self):
ts = self.get_custom("crop_transforms")
if len(ts) > 0:
return ts
if self.roi_size is None:
raise ValueError("roi_size is not specified")
keys = [self.image_key, self.label_key]
ts = []
ts.append(SpatialPadd(keys=keys, spatial_size=self.roi_size))
if self.crop_mode == "ratio":
output_classes = self.crop_params.get("output_classes", None)
if output_classes is None:
raise ValueError("crop_params option output_classes must be specified")
crop_ratios = self.crop_params.get("crop_ratios", None)
cache_class_indices = self.crop_params.get("cache_class_indices", False)
max_samples_per_class = self.crop_params.get("max_samples_per_class", None)
if max_samples_per_class <= 0:
max_samples_per_class = None
indices_key = None
sigmoid = self.extra_options.get("sigmoid", False)
crop_add_background = self.crop_params.get("crop_add_background", False)
if crop_ratios is None:
crop_classes = output_classes
if sigmoid and crop_add_background and self.class_index is not None and len(self.class_index) > 1:
crop_classes = crop_classes + 1
else:
crop_classes = len(crop_ratios)
if self.debug:
print(
f"Cropping with classes {crop_classes} and crop_add_background {crop_add_background} ratios {crop_ratios}"
)
if cache_class_indices:
ts.append(
ClassesToIndicesd(
keys=self.label_key,
num_classes=crop_classes,
indices_postfix="_cls_indices",
max_samples_per_class=max_samples_per_class,
)
)
indices_key = self.label_key + "_cls_indices"
num_crops_per_image = self.crop_params.get("num_crops_per_image", 1)
# if num_crops_per_image > 1:
# print(f"Cropping with num_crops_per_image {num_crops_per_image}")
ts.append(
RandCropByLabelClassesd(
keys=keys,
label_key=self.label_key,
num_classes=crop_classes,
spatial_size=self.roi_size,
num_samples=num_crops_per_image,
ratios=crop_ratios,
indices_key=indices_key,
warn=False,
)
)
elif self.crop_mode == "rand":
ts.append(RandSpatialCropd(keys=keys, roi_size=self.roi_size, random_size=False))
else:
raise ValueError("Unsupported crop mode" + str(self.crop_mode))
ts.extend(self.get_custom("after_crop_transforms"))
return ts
def get_augment_transforms(self):
ts = self.get_custom("augment_transforms")
if len(ts) > 0:
return ts
if self.roi_size is None:
raise ValueError("roi_size is not specified")
augment_mode = self.augment_params.get("augment_mode", None)
augment_flips = self.augment_params.get("augment_flips", None)
augment_rots = self.augment_params.get("augment_rots", None)
if self.debug:
print(f"Using augment_mode {augment_mode}, augment_flips {augment_flips} augment_rots {augment_rots}")
ts = []
if augment_mode is None or augment_mode == "default":
ts.append(
RandAffined(
keys=[self.image_key, self.label_key],
prob=0.2,
rotate_range=[0.26, 0.26, 0.26],
scale_range=[0.2, 0.2, 0.2],
mode=["bilinear", "nearest"],
spatial_size=self.roi_size,
cache_grid=True,
padding_mode="border",
)
)
ts.append(
RandGaussianSmoothd(
keys=self.image_key, prob=0.2, sigma_x=[0.5, 1.0], sigma_y=[0.5, 1.0], sigma_z=[0.5, 1.0]
)
)
ts.append(RandScaleIntensityd(keys=self.image_key, prob=0.5, factors=0.3))
ts.append(RandShiftIntensityd(keys=self.image_key, prob=0.5, offsets=0.1))
ts.append(RandGaussianNoised(keys=self.image_key, prob=0.2, mean=0.0, std=0.1))
elif augment_mode == "none":
augment_flips = []
augment_rots = []
elif augment_mode == "ct_ax_1":
ts.append(RandHistogramShiftd(keys="image", prob=0.5, num_control_points=16))
ts.append(RandAdjustContrastd(keys="image", prob=0.2, gamma=[0.5, 3.0]))
ts.append(
RandAffined(
keys=[self.image_key, self.label_key],
prob=0.5,
rotate_range=[0, 0, 0.26],
scale_range=[0.35, 0.35, 0],
mode=["bilinear", "nearest"],
spatial_size=self.roi_size,
cache_grid=True,
padding_mode="border",
)
)
elif augment_mode == "mri_1":
ts.append(
RandAffined(
keys=[self.image_key, self.label_key],
prob=0.2,
rotate_range=[0.26, 0.26, 0.26],
scale_range=[0.2, 0.2, 0.2],
mode=["bilinear", "nearest"],
spatial_size=self.roi_size,
cache_grid=True,
padding_mode="border",
)
)
ts.append(RandGaussianNoised(keys=self.image_key, prob=0.2, mean=0.0, std=0.1))
ts.append(
RandGaussianSmoothd(
keys=self.image_key, prob=0.2, sigma_x=[0.5, 1.0], sigma_y=[0.5, 1.0], sigma_z=[0.5, 1.0]
)
)
ts.append(RandScaleIntensityFixedMeand(keys="image", prob=0.2, fixed_mean=True, factors=0.3))
ts.append(
RandAdjustContrastd(keys="image", prob=0.2, gamma=[0.7, 1.5], retain_stats=True, invert_image=False)
)
ts.append(
RandAdjustContrastd(keys="image", prob=0.2, gamma=[0.7, 1.5], retain_stats=True, invert_image=True)
)
else:
raise ValueError("Unsupported augment_mode: " + str(augment_mode))
# default to all flips
if augment_flips is None:
augment_flips = [0, 1, 2]
for sa in augment_flips:
ts.append(RandFlipd(keys=[self.image_key, self.label_key], prob=0.5, spatial_axis=sa))
# default to no rots
if augment_rots is not None:
for sa in augment_rots:
ts.append(RandRotate90d(keys=[self.image_key, self.label_key], prob=0.5, spatial_axes=sa))
ts.extend(self.get_custom("after_augment_transforms"))
return ts
def get_final_transforms(self):
return self.get_custom("final_transforms")
@classmethod
def get_postprocess_transform(
cls,
save_mask=False,
invert=False,
transform=None,
sigmoid=False,
output_path=None,
resample=False,
data_root_dir="",
output_dtype=np.uint8,
save_mask_mode=None,
) -> Compose:
ts = []
if invert and transform is not None:
# if resample:
# ts.append(ToDeviced(keys="pred", device=torch.device("cpu")))
ts.append(Invertd(keys="pred", orig_keys="image", transform=transform, nearest_interp=False))
if save_mask and output_path is not None:
ts.append(CopyItemsd(keys="pred", times=1, names="seg"))
if save_mask_mode == "prob":
output_dtype = np.float32
else:
ts.append(
AsDiscreted(keys="seg", argmax=True) if not sigmoid else AsDiscreted(keys="seg", threshold=0.5)
)
ts.append(
SaveImaged(
keys=["seg"],
output_dir=output_path,
output_postfix="",
data_root_dir=data_root_dir,
output_dtype=output_dtype,
separate_folder=False,
squeeze_end_dims=True,
resample=False,
print_log=False,
)
)
return Compose(ts)
def __call__(self, augment=False, resample_label=False) -> Compose:
ts = []
ts.extend(self.get_load_transforms())
ts.extend(self.get_resample_transforms(resample_label=resample_label))
ts.extend(self.get_normalize_transforms())
if augment:
ts.extend(self.get_crop_transforms())
ts.extend(self.get_augment_transforms())
ts.extend(self.get_final_transforms())
compose_ts = Compose(ts)
return compose_ts
def __repr__(self) -> str:
out: str = f"DataTransformBuilder: with image_key: {self.image_key}, label_key: {self.label_key} \n"
out += f"roi_size {self.roi_size} resample {self.resample} resample_resolution {self.resample_resolution} \n"
out += f"normalize_mode {self.normalize_mode} normalize_params {self.normalize_params} \n"
out += f"crop_mode {self.crop_mode} crop_params {self.crop_params} \n"
out += f"extra_modalities {self.extra_modalities} \n"
for k, trs in self.custom_transforms.items():
out += f"Custom {k} : {str(trs)} \n"
return out
class Segmenter:
def __init__(
self,
config_file: Optional[Union[str, Sequence[str]]] = None,
config_dict: Dict = {},
rank: int = 0,
global_rank: int = 0,
) -> None:
self.rank = rank
self.global_rank = global_rank
self.distributed = dist.is_initialized()
if self.global_rank == 0:
print(f"Segmenter started config_file: {config_file}, config_dict: {config_dict}")
np.set_printoptions(formatter={"float": "{: 0.3f}".format}, suppress=True)
logging.getLogger("torch.nn.parallel.distributed").setLevel(logging.WARNING)
config = self.parse_input_config(config_file=config_file, override=config_dict)
self.config = config
self.config_file = config_file if not isinstance(config_file, (list, tuple)) else config_file[0]
self.override = config_dict
if config["ckpt_path"] is not None and not os.path.exists(config["ckpt_path"]):
os.makedirs(config["ckpt_path"], exist_ok=True)
if config["log_output_file"] is None:
config["log_output_file"] = os.path.join(self.config["ckpt_path"], "training.log")
logger_configure(log_output_file=config["log_output_file"], debug=config["debug"], global_rank=self.global_rank)
if config["fork"] and "fork" in mp.get_all_start_methods():
mp.set_start_method("fork", force=True) # lambda functions fail to pickle without it
else:
warnings.warn(
"Multiprocessing method fork is not available, some non-picklable objects (e.g. lambda ) may fail"
)
if config["cuda"] and torch.cuda.is_available():
self.device = torch.device(self.rank)
if self.distributed and dist.get_backend() == dist.Backend.NCCL:
torch.cuda.set_device(rank)
else:
self.device = torch.device("cpu")
if self.global_rank == 0:
print(yaml.dump(config))
if config["determ"]:
set_determinism(seed=0)
elif torch.cuda.is_available():
torch.backends.cudnn.benchmark = True
if config["notf32"]:
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
print(f"!!!disabling tf32")
if config.get("float32_precision", None) is not None:
torch.set_float32_matmul_precision(config["float32_precision"])
print(f"!!!setting matmul precession {config['float32_precision']}")
# auto adjust network settings
if config["auto_scale_allowed"]:
if config["auto_scale_batch"] or config["auto_scale_roi"] or config["auto_scale_filters"]:
roi_size, _, init_filters, batch_size = auto_adjust_network_settings(
auto_scale_batch=config["auto_scale_batch"],
auto_scale_roi=config["auto_scale_roi"],
auto_scale_filters=config["auto_scale_filters"],
image_size_mm=config["image_size_mm_median"],
spacing=config["resample_resolution"],
anisotropic_scales=config["anisotropic_scales"],
levels=len(config["network"]["blocks_down"]),
output_classes=config["output_classes"],
)
config["roi_size"] = roi_size
if config["auto_scale_batch"]:
config["batch_size"] = batch_size
if config["auto_scale_filters"] and config["pretrained_ckpt_name"] is None:
config["network"]["init_filters"] = init_filters
self.model = self.setup_model(pretrained_ckpt_name=config["pretrained_ckpt_name"])
loss_function = ConfigParser(config["loss"]).get_parsed_content(instantiate=True)
self.loss_function = DeepSupervisionLoss(loss_function)
dice_ignore_empty = config.get("dice_ignore_empty", True)
self.acc_function = DiceHelper(sigmoid=config["sigmoid"], ignore_empty=dice_ignore_empty)
self.grad_scaler = GradScaler(enabled=config["amp"])
if config.get("sliding_inferrer") is not None:
self.sliding_inferrer = ConfigParser(config["sliding_inferrer"]).get_parsed_content()
else:
self.sliding_inferrer = SlidingWindowInfererAdapt(
roi_size=config["roi_size"],
sw_batch_size=1,
overlap=0.625,
mode="gaussian",
cache_roi_weight_map=True,
progress=False,
)
self._data_transform_builder: DataTransformBuilder = None
self.lr_scheduler = None
self.optimizer = None
def get_custom_transforms(self):
config = self.config
# check for custom transforms
custom_transforms = {}
for tr in config.get("custom_data_transforms", []):
must_include_keys = ("key", "path", "transform")
if not all(k in tr for k in must_include_keys):
raise ValueError("custom transform must include " + str(must_include_keys))
if os.path.abspath(tr["path"]) not in sys.path:
sys.path.append(os.path.abspath(tr["path"]))
custom_transforms.setdefault(tr["key"], [])
custom_transforms[tr["key"]].append(tr["transform"])
if len(custom_transforms) > 0 and self.global_rank == 0:
print(f"Using custom transforms {custom_transforms}")
if isinstance(config["class_index"], list) and len(config["class_index"]) > 0:
# custom label embedding, if class_index provided
custom_transforms.setdefault("final_transforms", [])
custom_transforms["final_transforms"].append(
LabelEmbedClassIndex(keys="label", class_index=config["class_index"], allow_missing_keys=True)
)
return custom_transforms
def get_data_transform_builder(self):
if self._data_transform_builder is None:
config = self.config
custom_transforms = self.get_custom_transforms()
self._data_transform_builder = DataTransformBuilder(
roi_size=config["roi_size"],
resample=config["resample"],
resample_resolution=config["resample_resolution"],
normalize_mode=config["normalize_mode"],
normalize_params={
"intensity_bounds": config["intensity_bounds"],
"label_dtype": torch.uint8 if config["input_channels"] < 255 else torch.int16,
"image_dtype": torch.int16 if config.get("cache_image_int16", False) else None,
},
crop_mode=config["crop_mode"],
crop_params={
"output_classes": config["output_classes"],
"input_channels": config["input_channels"],
"crop_ratios": config["crop_ratios"],
"cache_class_indices": config["cache_class_indices"],
"num_crops_per_image": config["num_crops_per_image"],
"max_samples_per_class": config["max_samples_per_class"],
"crop_add_background": config["crop_add_background"],
},
augment_params={
"augment_mode": config.get("augment_mode", None),
"augment_flips": config.get("augment_flips", None),
"augment_rots": config.get("augment_rots", None),
},
extra_modalities=config["extra_modalities"],
custom_transforms=custom_transforms,
crop_foreground=config.get("crop_foreground", True),
sigmoid=config["sigmoid"],
orientation_ras=config.get("orientation_ras", False),
class_index=config["class_index"],
debug=config["debug"],
)
return self._data_transform_builder
def setup_model(self, pretrained_ckpt_name=None):
config = self.config
spatial_dims = config["network"].get("spatial_dims", 3)
norm_name, norm_args = split_args(config["network"].get("norm", ""))
norm_name = norm_name.upper()
if norm_name == "INSTANCE_NVFUSER":
_, has_nvfuser = optional_import("apex.normalization", name="InstanceNorm3dNVFuser")
if has_nvfuser and spatial_dims == 3:
act = config["network"].get("act", "relu")
if isinstance(act, str):
config["network"]["act"] = [act, {"inplace": False}]
else:
norm_name = "INSTANCE"
if len(norm_name) > 0:
config["network"]["norm"] = norm_name if len(norm_args) == 0 else [norm_name, norm_args]
if spatial_dims == 3:
if config.get("anisotropic_scales", False) and "SegResNetDS" in config["network"]["_target_"]:
config["network"]["resolution"] = copy.deepcopy(config["resample_resolution"])
if self.global_rank == 0:
print(f"Using anisotropic scales {config['network']}")
model = ConfigParser(config["network"]).get_parsed_content()
if self.global_rank == 0:
print(str(model))
if pretrained_ckpt_name is not None:
self.checkpoint_load(ckpt=pretrained_ckpt_name, model=model)
model = model.to(self.device)
if spatial_dims == 3:
memory_format = torch.channels_last_3d if config["channels_last"] else torch.preserve_format
model = model.to(memory_format=memory_format)
if self.distributed and not config["infer"]["enabled"]:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = DistributedDataParallel(
module=model, device_ids=[self.rank], output_device=self.rank, find_unused_parameters=False
)
if self.global_rank == 0:
pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Total parameters count: {pytorch_total_params} distributed: {self.distributed}")
return model
def parse_input_config(
self, config_file: Optional[Union[str, Sequence[str]]] = None, override: Dict = {}
) -> Tuple[ConfigParser, Dict]:
config = {}
if config_file is None or override.get("use_ckpt_config", False):
# attempt to load config from model ckpt file
for ckpt_key in ["pretrained_ckpt_name", "validate#ckpt_name", "infer#ckpt_name", "finetune#ckpt_name"]:
ckpt = override.get(ckpt_key, None)
if ckpt and os.path.exists(ckpt):
checkpoint = torch.load(ckpt, map_location="cpu")
config = checkpoint.get("config", {})
if self.global_rank == 0:
print(f"Initializing config from the checkpoint {ckpt}: {yaml.dump(config)}")
if len(config) == 0 and config_file is None:
warnings.warn("No input config_file provided, and no valid checkpoints found")
if config_file is not None and len(config) == 0:
config = ConfigParser.load_config_files(config_file)
config.setdefault("finetune", {"enabled": False, "ckpt_name": None})
config.setdefault(
"validate", {"enabled": False, "ckpt_name": None, "save_mask": False, "output_path": None}
)
config.setdefault("infer", {"enabled": False, "ckpt_name": None})
parser = ConfigParser(config=config)
parser.update(pairs=override)
config = parser.config # just in case
if config.get("data_file_base_dir", None) is None or config.get("data_list_file_path", None) is None:
raise ValueError("CONFIG: data_file_base_dir and data_list_file_path must be provided")
if config.get("bundle_root", None) is None:
config["bundle_root"] = str(Path(__file__).parent.parent)
if "modality" not in config:
if self.global_rank == 0:
warnings.warn("CONFIG: modality is not provided, assuming MRI")
config["modality"] = "mri"
if "normalize_mode" not in config:
config["normalize_mode"] = "range" if config["modality"].lower() == "ct" else "meanstd"
if self.global_rank == 0:
print(f"CONFIG: normalize_mode is not provided, assuming: {config['normalize_mode']}")
# assign defaults
config.setdefault("debug", False)
config.setdefault("loss", None)
config.setdefault("acc", None)
config.setdefault("amp", True)
config.setdefault("cuda", True)
config.setdefault("fold", 0)
config.setdefault("batch_size", 1)
config.setdefault("determ", False)
config.setdefault("quick", False)
config.setdefault("sigmoid", False)
config.setdefault("cache_rate", None)
config.setdefault("cache_class_indices", None)
config.setdefault("crop_add_background", True)
config.setdefault("orientation_ras", False)
config.setdefault("channels_last", True)
config.setdefault("fork", True)
config.setdefault("num_epochs", 300)
config.setdefault("num_warmup_epochs", 3)
config.setdefault("num_epochs_per_validation", None)
config.setdefault("num_epochs_per_saving", 10)
config.setdefault("num_steps_per_image", None)
config.setdefault("num_crops_per_image", 1)
config.setdefault("max_samples_per_class", None)
config.setdefault("calc_val_loss", False)
config.setdefault("validate_final_original_res", False)
config.setdefault("early_stopping_fraction", 0)
config.setdefault("start_epoch", 0)
config.setdefault("ckpt_path", None)
config.setdefault("ckpt_save", True)
config.setdefault("log_output_file", None)
config.setdefault("crop_mode", "ratio")
config.setdefault("crop_ratios", None)
config.setdefault("resample_resolution", [1.0, 1.0, 1.0])
config.setdefault("resample", False)
config.setdefault("roi_size", [128, 128, 128])
config.setdefault("num_workers", 4)
config.setdefault("extra_modalities", {})
config.setdefault("intensity_bounds", [-250, 250])
config.setdefault("stop_on_lowacc", True)
config.setdefault("float32_precision", None)
config.setdefault("notf32", False)
config.setdefault("class_index", None)
config.setdefault("class_names", [])
if not isinstance(config["class_names"], (list, tuple)):
config["class_names"] = []
if len(config["class_names"]) == 0:
n_foreground_classes = int(config["output_classes"])
if not config["sigmoid"]:
n_foreground_classes -= 1
config["class_names"] = ["acc_" + str(i) for i in range(n_foreground_classes)]
pretrained_ckpt_name = config.get("pretrained_ckpt_name", None)
if pretrained_ckpt_name is None:
if config["validate"]["enabled"]:
pretrained_ckpt_name = config["validate"]["ckpt_name"]
elif config["infer"]["enabled"]:
pretrained_ckpt_name = config["infer"]["ckpt_name"]
elif config["finetune"]["enabled"]:
pretrained_ckpt_name = config["finetune"]["ckpt_name"]
config["pretrained_ckpt_name"] = pretrained_ckpt_name
config.setdefault("auto_scale_allowed", False)
config.setdefault("auto_scale_batch", False)
config.setdefault("auto_scale_roi", False)
config.setdefault("auto_scale_filters", False)
if pretrained_ckpt_name is not None:
config["auto_scale_roi"] = False
config["auto_scale_filters"] = False
if config["max_samples_per_class"] is None:
config["max_samples_per_class"] = 10 * config["num_epochs"]
if not torch.cuda.is_available() and config["cuda"]:
print("No cuda is available.! Running on CPU!!!")
config["cuda"] = False
config["amp"] = config["amp"] and config["cuda"]
config["rank"] = self.rank
config["global_rank"] = self.global_rank
# resolve content
for k, v in config.items():
if isinstance(v, dict) and "_target_" in v:
config[k] = parser.get_parsed_content(k, instantiate=False).config
elif "_target_" in str(v):
config[k] = copy.deepcopy(v)
else:
config[k] = parser.get_parsed_content(k)
return config
def config_save_updated(self, save_path=None):
if self.global_rank == 0 and self.config["auto_scale_allowed"]:
# reload input config
config = ConfigParser.load_config_files(self.config_file)
parser = ConfigParser(config=config)
parser.update(pairs=self.override)
config = parser.config
config["batch_size"] = self.config["batch_size"]
config["roi_size"] = self.config["roi_size"]
config["num_crops_per_image"] = self.config["num_crops_per_image"]
if "init_filters" in self.config["network"]:
config["network"]["init_filters"] = self.config["network"]["init_filters"]
if save_path is None:
save_path = self.config_file
print(f"Re-saving main config to {save_path}.")
ConfigParser.export_config_file(config, save_path, fmt="yaml", default_flow_style=None, sort_keys=False)
def config_with_relpath(self, config=None):
if config is None:
config = self.config
config = copy.deepcopy(config)
bundle_root = config["bundle_root"]
def convert_rel_path(conf):
for k, v in conf.items():
if isinstance(v, str) and v.startswith(bundle_root):
conf[k] = f"$@bundle_root + '/{os.path.relpath(v, bundle_root)}'"
convert_rel_path(config)
convert_rel_path(config["finetune"])
convert_rel_path(config["validate"])
convert_rel_path(config["infer"])
config["bundle_root"] = bundle_root
return config
def checkpoint_save(self, ckpt: str, model: torch.nn.Module, **kwargs):
save_time = time.time()
if isinstance(model, torch.nn.parallel.DistributedDataParallel):
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
config = self.config_with_relpath()