forked from BiaPyX/BiaPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_workflow.py
1687 lines (1449 loc) · 81 KB
/
base_workflow.py
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
import math
import os
import datetime
import time
import json
import torch
import h5py
import zarr
import numpy as np
from tqdm import tqdm
from abc import ABCMeta, abstractmethod
from sklearn.model_selection import StratifiedKFold
import torch.multiprocessing as mp
import torch.distributed as dist
from biapy.models import build_model, build_torchvision_model
from biapy.engine import prepare_optimizer, build_callbacks
from biapy.data.generators import create_train_val_augmentors, create_test_augmentor, check_generator_consistence
from biapy.utils.misc import (get_world_size, get_rank, is_main_process, save_model, time_text, load_model_checkpoint, TensorboardLogger,
to_pytorch_format, to_numpy_format, is_dist_avail_and_initialized, setup_for_distributed, export_model_to_bmz)
from biapy.utils.util import (load_data_from_dir, load_3d_images_from_dir, create_plots, pad_and_reflect, save_tif, check_downsample_division,
read_chunked_data)
from biapy.engine.train_engine import train_one_epoch, evaluate
from biapy.data.data_2D_manipulation import crop_data_with_overlap, merge_data_with_overlap, load_and_prepare_2D_train_data
from biapy.data.data_3D_manipulation import (crop_3D_data_with_overlap, merge_3D_data_with_overlap, load_and_prepare_3D_data,
extract_3D_patch_with_overlap_yield)
from biapy.data.post_processing.post_processing import ensemble8_2d_predictions, ensemble16_3d_predictions, apply_binary_mask
from biapy.engine.metrics import jaccard_index_numpy, voc_calculation
from biapy.data.post_processing import apply_post_processing
class Base_Workflow(metaclass=ABCMeta):
"""
Base workflow class. A new workflow should extend this class.
Parameters
----------
cfg : YACS configuration
Running configuration.
Job_identifier : str
Complete name of the running job.
device : Torch device
Device used.
args : argpase class
Arguments used in BiaPy's call.
"""
def __init__(self, cfg, job_identifier, device, args):
self.cfg = cfg
self.args = args
self.job_identifier = job_identifier
self.device = device
self.original_test_path = None
self.original_test_mask_path = None
self.test_mask_filenames = None
self.cross_val_samples_ids = None
self.post_processing = {}
self.post_processing['per_image'] = False
self.post_processing['all_images'] = False
self.test_filenames = None
self.metrics = []
self.data_norm = None
self.model_prepared = False
self.dtype = np.float32 if not self.cfg.TEST.REDUCE_MEMORY else np.float16
self.dtype_str = "float32" if not self.cfg.TEST.REDUCE_MEMORY else "float16"
self.loss_dtype = torch.float32
# Save paths in case we need them in a future
self.orig_train_path = self.cfg.DATA.TRAIN.PATH
self.orig_train_mask_path = self.cfg.DATA.TRAIN.GT_PATH
self.orig_val_path = self.cfg.DATA.VAL.PATH
self.orig_val_mask_path = self.cfg.DATA.VAL.GT_PATH
self.all_pred = []
self.all_gt = []
self.stats = {}
# Per crop
self.stats['loss_per_crop'] = 0
self.stats['iou_per_crop'] = 0
self.stats['patch_counter'] = 0
# Merging the image
self.stats['iou_per_image'] = 0
self.stats['ov_iou_per_image'] = 0
# Full image
self.stats['loss'] = 0
self.stats['iou'] = 0
self.stats['ov_iou'] = 0
# Post processing
self.stats['iou_post'] = 0
self.stats['ov_iou_post'] = 0
self.world_size = get_world_size()
self.global_rank = get_rank()
if self.cfg.TEST.BY_CHUNKS.ENABLE and self.cfg.PROBLEM.NDIM == '3D':
maxsize = min(10,self.cfg.SYSTEM.NUM_GPUS*10)
self.output_queue = mp.Queue(maxsize=maxsize)
self.input_queue = mp.Queue(maxsize=maxsize)
self.extract_info_queue = mp.Queue()
# Test variables
if self.cfg.TEST.ANALIZE_2D_IMGS_AS_3D_STACK and self.cfg.PROBLEM.NDIM == "2D":
if self.cfg.TEST.POST_PROCESSING.YZ_FILTERING or self.cfg.TEST.POST_PROCESSING.Z_FILTERING:
self.post_processing['all_images'] = True
elif self.cfg.PROBLEM.NDIM == "3D":
if self.cfg.TEST.POST_PROCESSING.YZ_FILTERING or self.cfg.TEST.POST_PROCESSING.Z_FILTERING:
self.post_processing['per_image'] = True
# Define permute shapes to pass from Numpy axis order (Y,X,C) to Pytorch's (C,Y,X)
self.axis_order = (0,3,1,2) if self.cfg.PROBLEM.NDIM == "2D" else (0,4,1,2,3)
self.axis_order_back = (0,2,3,1) if self.cfg.PROBLEM.NDIM == "2D" else (0,2,3,4,1)
# Define metrics
self.define_metrics()
# Load Bioimage model Zoo pretrained model information
self.torchvision_preprocessing = None
if self.cfg.MODEL.SOURCE == "bmz":
import bioimageio.core
import xarray as xr
print("Loading Bioimage Model Zoo pretrained model . . .")
self.bmz_model_resource = bioimageio.core.load_resource_description(self.cfg.MODEL.BMZ.SOURCE_MODEL_DOI)
# Change PATCH_SIZE with the one stored in the RDF
input_image = np.load(self.bmz_model_resource.test_inputs[0])
opts = ["DATA.PATCH_SIZE", input_image.shape[2:]+(input_image.shape[1],)]
print("[BMZ] Changed 'DATA.PATCH_SIZE' from {} to {} as defined in the RDF"
.format(self.cfg.DATA.PATCH_SIZE,opts[1]))
self.cfg.merge_from_list(opts)
@abstractmethod
def define_metrics(self):
"""
This function must define the following variables:
self.metrics : List of functions
Metrics to be calculated during model's training and inference.
self.metric_names : List of str
Names of the metrics calculated.
self.loss : Function
Loss function used during training.
"""
NotImplementedError
@abstractmethod
def metric_calculation(self, output, targets, metric_logger=None):
"""
Execution of the metrics defined in :func:`~define_metrics` function.
Parameters
----------
output : Torch Tensor
Prediction of the model.
targets : Torch Tensor
Ground truth to compare the prediction with.
metric_logger : MetricLogger, optional
Class to be updated with the new metric(s) value(s) calculated.
Returns
-------
value : float
Value of the metric for the given prediction.
"""
NotImplementedError
def prepare_targets(self, targets, batch):
"""
Location to perform any necessary data transformations to ``targets``
before inputting it into the model.
Parameters
----------
targets : Torch Tensor
Ground truth to compare the prediction with.
batch : Torch Tensor
Prediction of the model. Only used in SSL workflow.
Returns
-------
targets : Torch tensor
Resulting targets.
"""
# We do not use 'batch' input but in SSL workflow
return to_pytorch_format(targets, self.axis_order, self.device)
def load_train_data(self):
"""
Load training and validation data.
"""
if self.cfg.TRAIN.ENABLE:
print("##########################")
print("# LOAD TRAINING DATA #")
print("##########################")
if self.cfg.DATA.TRAIN.IN_MEMORY:
val_split = self.cfg.DATA.VAL.SPLIT_TRAIN if self.cfg.DATA.VAL.FROM_TRAIN else 0.
f_name = load_and_prepare_2D_train_data if self.cfg.PROBLEM.NDIM == '2D' else load_and_prepare_3D_data
objs = f_name(self.cfg.DATA.TRAIN.PATH, self.mask_path, cross_val=self.cfg.DATA.VAL.CROSS_VAL,
cross_val_nsplits=self.cfg.DATA.VAL.CROSS_VAL_NFOLD, cross_val_fold=self.cfg.DATA.VAL.CROSS_VAL_FOLD,
val_split=val_split, seed=self.cfg.SYSTEM.SEED, shuffle_val=self.cfg.DATA.VAL.RANDOM,
random_crops_in_DA=self.cfg.DATA.EXTRACT_RANDOM_PATCH, crop_shape=self.cfg.DATA.PATCH_SIZE,
y_upscaling=self.cfg.PROBLEM.SUPER_RESOLUTION.UPSCALING, ov=self.cfg.DATA.TRAIN.OVERLAP,
padding=self.cfg.DATA.TRAIN.PADDING, minimum_foreground_perc=self.cfg.DATA.TRAIN.MINIMUM_FOREGROUND_PER,
reflect_to_complete_shape=self.cfg.DATA.REFLECT_TO_COMPLETE_SHAPE,
convert_to_rgb=self.cfg.DATA.FORCE_RGB)
if self.cfg.DATA.VAL.FROM_TRAIN:
if self.cfg.DATA.VAL.CROSS_VAL:
self.X_train, self.Y_train, self.X_val, self.Y_val, self.train_filenames, self.cross_val_samples_ids = objs
else:
self.X_train, self.Y_train, self.X_val, self.Y_val, self.train_filenames = objs
else:
self.X_train, self.Y_train, self.train_filenames = objs
del objs
else:
self.X_train, self.Y_train = None, None
##################
### VALIDATION ###
##################
if not self.cfg.DATA.VAL.FROM_TRAIN:
if self.cfg.DATA.VAL.IN_MEMORY:
print("1) Loading validation images . . .")
f_name = load_data_from_dir if self.cfg.PROBLEM.NDIM == '2D' else load_3d_images_from_dir
self.X_val, _, _ = f_name(self.cfg.DATA.VAL.PATH, crop=True, crop_shape=self.cfg.DATA.PATCH_SIZE,
overlap=self.cfg.DATA.VAL.OVERLAP, padding=self.cfg.DATA.VAL.PADDING,
reflect_to_complete_shape=self.cfg.DATA.REFLECT_TO_COMPLETE_SHAPE,
convert_to_rgb=self.cfg.DATA.FORCE_RGB)
if self.cfg.PROBLEM.NDIM == '2D':
crop_shape = (self.cfg.DATA.PATCH_SIZE[0]*self.cfg.PROBLEM.SUPER_RESOLUTION.UPSCALING,
self.cfg.DATA.PATCH_SIZE[1]*self.cfg.PROBLEM.SUPER_RESOLUTION.UPSCALING, self.cfg.DATA.PATCH_SIZE[2])
else:
crop_shape = (self.cfg.DATA.PATCH_SIZE[0], self.cfg.DATA.PATCH_SIZE[1]*self.cfg.PROBLEM.SUPER_RESOLUTION.UPSCALING,
self.cfg.DATA.PATCH_SIZE[2]*self.cfg.PROBLEM.SUPER_RESOLUTION.UPSCALING, self.cfg.DATA.PATCH_SIZE[3])
if self.load_Y_val:
self.Y_val, _, _ = f_name(self.cfg.DATA.VAL.GT_PATH, crop=True, crop_shape=crop_shape,
overlap=self.cfg.DATA.VAL.OVERLAP, padding=self.cfg.DATA.VAL.PADDING,
reflect_to_complete_shape=self.cfg.DATA.REFLECT_TO_COMPLETE_SHAPE,
check_channel=False, check_drange=False,
convert_to_rgb=self.cfg.DATA.FORCE_RGB)
else:
self.Y_val = None
if self.Y_val is not None and len(self.X_val) != len(self.Y_val):
raise ValueError("Different number of raw and ground truth items ({} vs {}). "
"Please check the data!".format(len(self.X_val), len(self.Y_val)))
else:
self.X_val, self.Y_val = None, None
def destroy_train_data(self):
"""
Delete training variable to release memory.
"""
print("Releasing memory . . .")
if 'X_train' in locals() or 'X_train' in globals():
del self.X_train
if 'Y_train' in locals() or 'Y_train' in globals():
del self.Y_train
if 'X_val' in locals() or 'X_val' in globals():
del self.X_val
if 'Y_val' in locals() or 'Y_val' in globals():
del self.Y_val
if 'train_generator' in locals() or 'train_generator' in globals():
del self.train_generator
if 'val_generator' in locals() or 'val_generator' in globals():
del self.val_generator
def prepare_train_generators(self):
"""
Build train and val generators.
"""
if self.cfg.TRAIN.ENABLE:
print("##############################")
print("# PREPARE TRAIN GENERATORS #")
print("##############################")
self.train_generator, \
self.val_generator, \
self.data_norm, \
self.num_training_steps_per_epoch = create_train_val_augmentors(self.cfg, self.X_train, self.Y_train,
self.X_val, self.Y_val, self.world_size, self.global_rank, self.args.distributed)
if self.cfg.DATA.CHECK_GENERATORS and self.cfg.PROBLEM.TYPE != 'CLASSIFICATION':
check_generator_consistence(
self.train_generator, self.cfg.PATHS.GEN_CHECKS+"_train", self.cfg.PATHS.GEN_MASK_CHECKS+"_train")
check_generator_consistence(
self.val_generator, self.cfg.PATHS.GEN_CHECKS+"_val", self.cfg.PATHS.GEN_MASK_CHECKS+"_val")
def bmz_model_call(self, in_img, is_train=False):
"""
Call Bioimage model zoo model.
Parameters
----------
in_img : Tensor
Input image to pass through the model.
is_train : bool, optional
Whether if the call is during training or inference.
Returns
-------
prediction : Tensor
Image prediction.
"""
# Convert from Numpy to xarray.DataArray
if self.cfg.PROBLEM.NDIM == '2D':
self.bmz_axes = ('b', 'c', 'y', 'x')
else:
self.bmz_axes = ('b', 'c', 'z', 'y', 'x')
in_img = xr.DataArray(in_img.cpu().numpy(), dims=tuple(self.bmz_axes))
# Apply pre-processing
in_img = dict(zip([ipt.name for ipt in self.model.input_specs], (in_img,)))
self.bmz_computed_measures = {}
self.model.apply_preprocessing(in_img, self.bmz_computed_measures)
# Predict
prediction_tensors = self.model.predict(*list(in_img.values()))
# Apply post-processing
prediction = dict(zip([out.name for out in self.model.output_specs], prediction_tensors))
self.model.apply_postprocessing(prediction, self.bmz_computed_measures)
# Convert back to Tensor
prediction = torch.from_numpy(prediction['output0'].to_numpy())
return prediction
@abstractmethod
def torchvision_model_call(self, in_img, is_train=False):
"""
Call a regular Pytorch model.
Parameters
----------
in_img : Tensor
Input image to pass through the model.
is_train : bool, optional
Whether if the call is during training or inference.
Returns
-------
prediction : Tensor
Image prediction.
"""
raise NotImplementedError
def model_call_func(self, in_img, to_pytorch=True, is_train=False):
"""
Call a regular Pytorch model.
Parameters
----------
in_img : Tensor
Input image to pass through the model.
to_pytorch : bool, optional
Whether if the input image needs to be converted into pytorch format or not.
is_train : bool, optional
Whether if the call is during training or inference.
Returns
-------
prediction : Tensor
Image prediction.
"""
if to_pytorch:
in_img = to_pytorch_format(in_img, self.axis_order, self.device)
if self.cfg.MODEL.SOURCE == "biapy":
p = self.model(in_img)
elif self.cfg.MODEL.SOURCE == "bmz":
p = self.bmz_model_call(in_img, is_train)
elif self.cfg.MODEL.SOURCE == "torchvision":
p = self.torchvision_model_call(in_img, is_train)
return p
def prepare_model(self):
"""
Build the model.
"""
print("###############")
print("# Build model #")
print("###############")
if self.cfg.MODEL.SOURCE == "biapy":
self.model = build_model(self.cfg, self.job_identifier, self.device)
elif self.cfg.MODEL.SOURCE == "torchvision":
self.model, self.torchvision_preprocessing = build_torchvision_model(self.cfg, self.device)
# Bioimage Model Zoo pretrained models
elif self.cfg.MODEL.SOURCE == "bmz":
# Create a bioimage pipeline to create predictions
try:
self.model = bioimageio.core.create_prediction_pipeline(
self.bmz_model_resource, devices=None,
weight_format="torchscript",
)
except Exception as e:
print(f"The error thrown during the BMZ model load was:\n{e}")
raise ValueError("An error ocurred when creating the BMZ model (see above). "
"BiaPy only supports models prepared with Torchscript.")
if self.args.distributed:
raise ValueError("DDP can not be activated when loading a BMZ pretrained model")
self.model_without_ddp = self.model
if self.args.distributed:
self.model = torch.nn.parallel.DistributedDataParallel(self.model, device_ids=[self.args.gpu],
find_unused_parameters=False)
self.model_without_ddp = self.model.module
self.model_prepared = True
def prepare_logging_tool(self):
"""
Prepare looging tool.
"""
print("#######################")
print("# Prepare loggin tool #")
print("#######################")
# To start the logging
now = datetime.datetime.now()
now = now.strftime("%Y_%m_%d_%H_%M_%S")
self.log_file = os.path.join(self.cfg.LOG.LOG_DIR, self.cfg.LOG.LOG_FILE_PREFIX + "_log_"+str(now)+".txt")
if self.global_rank == 0:
os.makedirs(self.cfg.LOG.LOG_DIR, exist_ok=True)
os.makedirs(self.cfg.PATHS.CHECKPOINT, exist_ok=True)
self.log_writer = TensorboardLogger(log_dir=self.cfg.LOG.TENSORBOARD_LOG_DIR)
else:
self.log_writer = None
self.plot_values = {}
self.plot_values['loss'] = []
self.plot_values['val_loss'] = []
for i in range(len(self.metric_names)):
self.plot_values[self.metric_names[i]] = []
self.plot_values['val_'+self.metric_names[i]] = []
def train(self):
"""
Training phase.
"""
self.load_train_data()
self.prepare_model()
self.prepare_train_generators()
self.prepare_logging_tool()
self.early_stopping = build_callbacks(self.cfg)
self.optimizer, self.lr_scheduler, self.loss_scaler = prepare_optimizer(self.cfg, self.model_without_ddp,
len(self.train_generator))
# Load checkpoint if necessary
if self.cfg.MODEL.LOAD_CHECKPOINT:
self.start_epoch = load_model_checkpoint(cfg=self.cfg, jobname=self.job_identifier, model_without_ddp=self.model_without_ddp,
device=self.device, optimizer=self.optimizer, loss_scaler=self.loss_scaler)
else:
self.start_epoch = 0
print("#####################")
print("# TRAIN THE MODEL #")
print("#####################")
print(f"Start training in epoch {self.start_epoch+1} - Total: {self.cfg.TRAIN.EPOCHS}")
start_time = time.time()
val_best_metric = np.zeros(len(self.metric_names), dtype=np.float32)
val_best_loss = np.Inf
for epoch in range(self.start_epoch, self.cfg.TRAIN.EPOCHS):
print("~~~ Epoch {}/{} ~~~\n".format(epoch+1, self.cfg.TRAIN.EPOCHS))
e_start = time.time()
if self.args.distributed:
self.train_generator.sampler.set_epoch(epoch)
if self.log_writer is not None:
self.log_writer.set_step(epoch * self.num_training_steps_per_epoch)
# Train
train_stats = train_one_epoch(self.cfg, model=self.model, model_call_func=self.model_call_func, loss_function=self.loss,
activations=self.apply_model_activations, metric_function=self.metric_calculation, prepare_targets=self.prepare_targets,
data_loader=self.train_generator, optimizer=self.optimizer, device=self.device, loss_scaler=self.loss_scaler, epoch=epoch,
log_writer=self.log_writer, lr_scheduler=self.lr_scheduler, start_steps=epoch * self.num_training_steps_per_epoch)
# Save checkpoint
if self.cfg.MODEL.SAVE_CKPT_FREQ != -1:
if (epoch + 1) % self.cfg.MODEL.SAVE_CKPT_FREQ == 0 or epoch + 1 == self.cfg.TRAIN.EPOCHS and is_main_process():
save_model(cfg=self.cfg, jobname=self.job_identifier, model=self.model, model_without_ddp=self.model_without_ddp,
optimizer=self.optimizer, loss_scaler=self.loss_scaler, epoch=epoch+1)
# Validation
if self.val_generator is not None:
test_stats = evaluate(self.cfg, model=self.model, model_call_func=self.model_call_func, loss_function=self.loss,
activations=self.apply_model_activations, metric_function=self.metric_calculation, prepare_targets=self.prepare_targets,
epoch=epoch, data_loader=self.val_generator, lr_scheduler=self.lr_scheduler)
# Save checkpoint is val loss improved
if test_stats['loss'] < val_best_loss:
f = os.path.join(self.cfg.PATHS.CHECKPOINT,"{}-checkpoint-best.pth".format(self.job_identifier))
print("Val loss improved from {} to {}, saving model to {}".format(val_best_loss, test_stats['loss'], f))
m = " "
for i in range(len(val_best_metric)):
val_best_metric[i] = test_stats[self.metric_names[i]]
m += f"{self.metric_names[i]}: {val_best_metric[i]:.4f} "
val_best_loss = test_stats['loss']
if is_main_process():
save_model(cfg=self.cfg, jobname=self.job_identifier, model=self.model, model_without_ddp=self.model_without_ddp,
optimizer=self.optimizer, loss_scaler=self.loss_scaler, epoch="best")
print(f'[Val] best loss: {val_best_loss:.4f} best '+m)
# Store validation stats
if self.log_writer is not None:
self.log_writer.update(test_loss=test_stats['loss'], head="perf", step=epoch)
for i in range(len(self.metric_names)):
self.log_writer.update(test_iou=test_stats[self.metric_names[i]], head="perf", step=epoch)
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch}
else:
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
'epoch': epoch}
# Write statistics in the logging file
if is_main_process():
# Log epoch stats
if self.log_writer is not None:
self.log_writer.flush()
with open(self.log_file, mode="a", encoding="utf-8") as f:
f.write(json.dumps(log_stats) + "\n")
# Create training plot
self.plot_values['loss'].append(train_stats['loss'])
if self.val_generator is not None:
self.plot_values['val_loss'].append(test_stats['loss'])
for i in range(len(self.metric_names)):
self.plot_values[self.metric_names[i]].append(train_stats[self.metric_names[i]])
if self.val_generator is not None:
self.plot_values['val_'+self.metric_names[i]].append(test_stats[self.metric_names[i]])
if (epoch+1) % self.cfg.LOG.CHART_CREATION_FREQ == 0:
create_plots(self.plot_values, self.metric_names, self.job_identifier, self.cfg.PATHS.CHARTS)
if self.val_generator is not None and self.early_stopping is not None:
self.early_stopping(test_stats['loss'])
if self.early_stopping.early_stop:
print("Early stopping")
break
e_end = time.time()
t_epoch = e_end - e_start
print("[Time] {} {}/{}\n".format(time_text(t_epoch), time_text(e_end - start_time),
time_text((e_end - start_time)+(t_epoch*(self.cfg.TRAIN.EPOCHS-epoch)))))
total_time = time.time() - start_time
self.total_training_time_str = str(datetime.timedelta(seconds=int(total_time)))
print('Training time {}'.format(self.total_training_time_str))
print("Train loss: {}".format(train_stats['loss']))
for i in range(len(self.metric_names)):
print("Train {}: {}".format(self.metric_names[i], train_stats[self.metric_names[i]]))
if self.val_generator is not None:
print("Val loss: {}".format(val_best_loss))
for i in range(len(self.metric_names)):
print("Val {}: {}".format(self.metric_names[i], val_best_metric))
print('Finished Training')
# Export model to BMZ format
if self.cfg.MODEL.BMZ.EXPORT_MODEL.ENABLE:
sample = next(enumerate(self.train_generator))
test_input = sample[1][0][0]
test_output = sample[1][1]
if not isinstance(test_output, int):
test_output = test_output[0]
export_model_to_bmz(self.cfg, self.job_identifier, self.model, test_input, test_output)
self.destroy_train_data()
def load_test_data(self):
"""
Load test data.
"""
if self.cfg.TEST.ENABLE:
print("######################")
print("# LOAD TEST DATA #")
print("######################")
if not self.cfg.DATA.TEST.USE_VAL_AS_TEST:
if self.cfg.DATA.TEST.IN_MEMORY:
print("2) Loading test images . . .")
f_name = load_data_from_dir if self.cfg.PROBLEM.NDIM == '2D' else load_3d_images_from_dir
self.X_test, _, _ = f_name(self.cfg.DATA.TEST.PATH, convert_to_rgb=self.cfg.DATA.FORCE_RGB)
if self.cfg.DATA.TEST.LOAD_GT:
print("3) Loading test masks . . .")
self.Y_test, _, _ = f_name(self.cfg.DATA.TEST.GT_PATH, check_channel=False, check_drange=False)
if len(self.X_test) != len(self.Y_test):
raise ValueError("Different number of raw and ground truth items ({} vs {}). "
"Please check the data!".format(len(self.X_test), len(self.Y_test)))
else:
self.Y_test = None
else:
self.X_test, self.Y_test = None, None
if self.original_test_path is None:
self.test_filenames = sorted(next(os.walk(self.cfg.DATA.TEST.PATH))[2])
else:
self.test_filenames = sorted(next(os.walk(self.original_test_path))[2])
else:
# The test is the validation, and as it is only available when validation is obtained from train and when
# cross validation is enabled, the test set files reside in the train folder
self.test_filenames = sorted(next(os.walk(self.cfg.DATA.TRAIN.PATH))[2])
self.X_test, self.Y_test = None, None
if self.cross_val_samples_ids is None:
# Split the test as it was the validation when train is not enabled
skf = StratifiedKFold(n_splits=self.cfg.DATA.VAL.CROSS_VAL_NFOLD, shuffle=self.cfg.DATA.VAL.RANDOM,
random_state=self.cfg.SYSTEM.SEED)
fold = 1
test_index = None
A = B = np.zeros(len(self.test_filenames))
for _, te_index in skf.split(A, B):
if self.cfg.DATA.VAL.CROSS_VAL_FOLD == fold:
self.cross_val_samples_ids = te_index.copy()
break
fold += 1
if len(self.cross_val_samples_ids) > 5:
print("Fold number {} used for test data. Printing the first 5 ids: {}".format(fold, self.cross_val_samples_ids[:5]))
else:
print("Fold number {}. Indexes used in cross validation: {}".format(fold, self.cross_val_samples_ids))
self.test_filenames = [x for i, x in enumerate(self.test_filenames) if i in self.cross_val_samples_ids]
self.original_test_path = self.orig_train_path
self.original_test_mask_path = self.orig_train_mask_path
def destroy_test_data(self):
"""
Delete test variable to release memory.
"""
print("Releasing memory . . .")
if 'X_test' in locals() or 'X_test' in globals():
del self.self.X_test
if 'Y_test' in locals() or 'Y_test' in globals():
del self.self.Y_test
if 'test_generator' in locals() or 'test_generator' in globals():
del self.test_generator
if '_X' in locals() or '_X' in globals():
del self._X
if '_Y' in locals() or '_Y' in globals():
del self._Y
def prepare_test_generators(self):
"""
Prepare test data generator.
"""
if self.cfg.TEST.ENABLE:
print("############################")
print("# PREPARE TEST GENERATOR #")
print("############################")
self.test_generator, self.data_norm = create_test_augmentor(self.cfg, self.X_test, self.Y_test, self.cross_val_samples_ids)
def apply_model_activations(self, pred, training=False):
"""
Function that apply the last activation (if any) to the model's output.
Parameters
----------
pred : Torch Tensor
Predictions of the model.
training : bool, optional
To advice the function if this is being applied during training of inference. During training,
``CE_Sigmoid`` activations will NOT be applied, as ``torch.nn.BCEWithLogitsLoss`` will apply
``Sigmoid`` automatically in a way that is more stable numerically
(`ref <https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html>`_).
Returns
-------
pred : Torch tensor
Resulting predictions after applying last activation(s).
"""
for key, value in self.activations.items():
# Ignore CE_Sigmoid as torch.nn.BCEWithLogitsLoss will apply Sigmoid automatically in a way
# that is more stable numerically (ref: https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html)
if (training and value not in ["Linear", "CE_Sigmoid"]) or (not training and value != "Linear"):
value = "Sigmoid" if value == "CE_Sigmoid" else value
act = getattr(torch.nn, value)()
if key == ':':
pred = act(pred)
else:
pred[:,int(key),...] = act(pred[:,int(key),...])
return pred
@torch.no_grad()
def test(self):
"""
Test/Inference step.
"""
self.load_test_data()
if not self.model_prepared:
self.prepare_model()
self.prepare_test_generators()
# Switch to evaluation mode
if self.cfg.MODEL.SOURCE != "bmz":
self.model_without_ddp.eval()
# Load checkpoint
if self.cfg.MODEL.LOAD_CHECKPOINT:
self.start_epoch = load_model_checkpoint(cfg=self.cfg, jobname=self.job_identifier, model_without_ddp=self.model_without_ddp,
device=self.device)
if self.start_epoch == -1:
raise ValueError("There was a problem loading the checkpoint. Test phase aborted!")
image_counter = 0
print("###############")
print("# INFERENCE #")
print("###############")
print("Making predictions on test data . . .")
# Reactivate prints to see each rank progress
if self.cfg.TEST.BY_CHUNKS.ENABLE and self.cfg.PROBLEM.NDIM == '3D':
setup_for_distributed(True)
# Process all the images
for i, batch in tqdm(enumerate(self.test_generator), total=len(self.test_generator)):
if self.cfg.DATA.TEST.LOAD_GT and self.cfg.PROBLEM.TYPE not in ["SELF_SUPERVISED"]:
X, X_norm, Y, Y_norm = batch
else:
X, X_norm = batch
Y, Y_norm = None, None
del batch
if self.cfg.TEST.BY_CHUNKS.ENABLE and self.cfg.PROBLEM.NDIM == '3D':
if type(X) is tuple:
self._X = X[0]
if self.cfg.DATA.TEST.LOAD_GT and self.cfg.PROBLEM.TYPE not in ["SELF_SUPERVISED"]:
self._Y = Y[0]
else:
self._Y = None
else:
self._X = X
self._Y = Y if self.cfg.DATA.TEST.LOAD_GT else None
if len(self.test_filenames) == 0:
self.test_filenames = sorted(next(os.walk(self.cfg.DATA.TEST.PATH))[1])
self.processing_filenames = self.test_filenames[i]
if is_main_process():
print("Processing image: {}".format(self.processing_filenames))
# Process each image separately
self.f_numbers = [i]
self.process_sample_by_chunks(self.processing_filenames)
else:
# Process all the images in the batch, sample by sample
l_X = len(X)
for j in tqdm(range(l_X), leave=False):
self.processing_filenames = self.test_filenames[(i*l_X)+j:(i*l_X)+j+1]
if is_main_process():
print("Processing image(s): {}".format(self.processing_filenames))
if self.cfg.PROBLEM.TYPE != 'CLASSIFICATION':
if type(X) is tuple:
self._X = X[j]
if self.cfg.DATA.TEST.LOAD_GT and self.cfg.PROBLEM.TYPE not in ["SELF_SUPERVISED"]:
self._Y = Y[j]
else:
self._Y = None
else:
self._X = np.expand_dims(X[j],0)
if self.cfg.DATA.TEST.LOAD_GT and self.cfg.PROBLEM.TYPE not in ["SELF_SUPERVISED"]:
self._Y = np.expand_dims(Y[j],0)
else:
self._Y = None
else:
self._X = np.expand_dims(X[j], 0)
self._Y = np.expand_dims(Y, 0) if self.cfg.DATA.TEST.LOAD_GT else None
# Process each image separately
self.f_numbers = list(range((i*l_X)+j,(i*l_X)+j+1))
self.process_sample(norm=(X_norm, Y_norm))
image_counter += 1
# Deactivate again the print function
if self.cfg.TEST.BY_CHUNKS.ENABLE and self.cfg.PROBLEM.NDIM == '3D':
setup_for_distributed(is_main_process())
self.destroy_test_data()
if is_main_process():
self.after_all_images()
print("#############")
print("# RESULTS #")
print("#############")
if self.cfg.TRAIN.ENABLE:
print("Epoch number: {}".format(len(self.plot_values['val_loss'])))
print("Train time (s): {}".format(self.total_training_time_str))
print("Train loss: {}".format(np.min(self.plot_values['loss'])))
for i in range(len(self.metric_names)):
if self.metric_names[i] == "IoU":
print("Train Foreground {}: {}".format(self.metric_names[i], np.max(self.plot_values[self.metric_names[i]])))
else:
print("Train {}: {}".format(self.metric_names[i], np.max(self.plot_values[self.metric_names[i]])))
print("Validation loss: {}".format(np.min(self.plot_values['val_loss'])))
for i in range(len(self.metric_names)):
if self.metric_names[i] == "IoU":
print("Validation Foreground {}: {}".format(self.metric_names[i], np.max(self.plot_values['val_'+self.metric_names[i]])))
else:
print("Validation {}: {}".format(self.metric_names[i], np.max(self.plot_values['val_'+self.metric_names[i]])))
self.print_stats(image_counter)
def process_sample_by_chunks(self, filenames):
"""
Function to process a sample in the inference phase. A final H5/Zarr file is created in "TZCYX" or "TZYXC" order
depending on ``TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER`` ('T' is always included).
Parameters
----------
filenames : List of str
Filenames fo the samples to process.
"""
filename, file_extension = os.path.splitext(filenames)
if file_extension not in ['.hdf5', '.h5', ".zarr"]:
print("WARNING: you could have saved more memory by converting input test images into H5 file format (.h5) "
"or Zarr (.zarr) as with 'TEST.BY_CHUNKS.ENABLE' option enabled H5/Zarr files will be processed by chunks")
# Load data
if file_extension in ['.hdf5', '.h5', ".zarr"]:
self._X_file, self._X = read_chunked_data(self._X)
print(f"Loaded image shape is {self._X.shape}")
data_shape = self._X.shape
if self._X.ndim < 3:
raise ValueError("Loaded image need to have at least 3 dimensions: {} (ndim: {})".format(self._X.shape, self._X.ndim))
if 'T' in self.cfg.TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER:
if len(self.cfg.TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER) > len(data_shape):
data_shape = (1,)+data_shape
else:
data_shape = (1,)+data_shape
if len(self.cfg.TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER) != self._X.ndim:
raise ValueError("'TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER' value {} does not match the number of dimensions of the loaded H5/Zarr "
"file {} (ndim: {})".format(self.cfg.TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER, self._X.shape, self._X.ndim))
# Data paths
os.makedirs(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, exist_ok=True)
ext = ".h5" if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5" else ".zarr"
if self.cfg.SYSTEM.NUM_GPUS > 1:
out_data_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+"_part"+str(get_rank())+ext)
out_data_mask_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+"_part"+str(get_rank())+"_mask"+ext)
else:
out_data_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+"_nodiv"+ext)
out_data_mask_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+"_mask"+ext)
out_data_div_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+ext)
in_data = self._X
# Process in charge of processing one predicted patch
output_handle_proc = mp.Process(target=insert_patch_into_dataset, args=(out_data_filename, out_data_mask_filename,
data_shape, self.output_queue, self.extract_info_queue, self.cfg, self.dtype_str, self.dtype,
self.cfg.TEST.BY_CHUNKS.FORMAT, self.cfg.TEST.VERBOSE))
output_handle_proc.daemon=True
output_handle_proc.start()
# Process in charge of loading part of the data
load_data_process = mp.Process(target=extract_patch_from_dataset, args=(in_data, self.cfg, self.input_queue,
self.extract_info_queue, self.cfg.TEST.VERBOSE))
load_data_process.daemon=True
load_data_process.start()
if '_X_file' in locals() and isinstance(self._X_file, h5py.File):
self._X_file.close()
del self._X, in_data
# Lock the thread inferring until no more patches
if self.cfg.TEST.VERBOSE and self.cfg.SYSTEM.NUM_GPUS > 1:
print(f"[Rank {get_rank()} ({os.getpid()})] Doing inference ")
while True:
obj = self.input_queue.get(timeout=60)
if obj == None: break
img, patch_coords = obj
img, _ = self.test_generator.norm_X(img)
if self.cfg.TEST.AUGMENTATION:
p = ensemble16_3d_predictions(img[0], batch_size_value=self.cfg.TRAIN.BATCH_SIZE,
pred_func=(
lambda img_batch_subdiv:
to_numpy_format(
self.apply_model_activations(
self.model_call_func(img_batch_subdiv),
),
self.axis_order_back
)
)
)
else:
with torch.cuda.amp.autocast():
p = self.model_call_func(img)
p = to_numpy_format(self.apply_model_activations(p), self.axis_order_back)
# Create a mask with the overlap. Calculate the exact part of the patch that will be inserted in the
# final H5/Zarr file
p = p[0, self.cfg.DATA.TEST.PADDING[0]:p.shape[1]-self.cfg.DATA.TEST.PADDING[0],
self.cfg.DATA.TEST.PADDING[1]:p.shape[2]-self.cfg.DATA.TEST.PADDING[1],
self.cfg.DATA.TEST.PADDING[2]:p.shape[3]-self.cfg.DATA.TEST.PADDING[2]]
m = np.ones(p.shape, dtype=np.uint8)
# Put the prediction into queue
self.output_queue.put([p, m, patch_coords])
# Get some auxiliar variables
self.stats['patch_counter'] = self.extract_info_queue.get(timeout=60)
if is_main_process():
z_vol_info = self.extract_info_queue.get(timeout=60)
list_of_vols_in_z = self.extract_info_queue.get(timeout=60)
load_data_process.join()
output_handle_proc.join()
# Wait until all threads are done so the main thread can create the full size image
if self.cfg.SYSTEM.NUM_GPUS > 1 :
if self.cfg.TEST.VERBOSE:
print(f"[Rank {get_rank()} ({os.getpid()})] Finish sample inference ")
if is_dist_avail_and_initialized():
dist.barrier()
t_axes = (0,1,3,4,2) if "ZCYX" in self.cfg.TEST.BY_CHUNKS.INPUT_IMG_AXES_ORDER else (0,1,2,3,4)
# Create the final H5/Zarr file that contains all the individual parts
if is_main_process():
if self.cfg.SYSTEM.NUM_GPUS > 1:
# Obtain parts of the data created by all GPUs
if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5":
data_parts_filenames = sorted(next(os.walk(self.cfg.PATHS.RESULT_DIR.PER_IMAGE))[2])
else:
data_parts_filenames = sorted(next(os.walk(self.cfg.PATHS.RESULT_DIR.PER_IMAGE))[1])
parts = []
mask_parts = []
for x in data_parts_filenames:
if filename+"_part" in x and x.endswith(self.cfg.TEST.BY_CHUNKS.FORMAT):
if "_mask" not in x:
parts.append(x)
else:
mask_parts.append(x)
data_parts_filenames = parts
data_parts_mask_filenames = mask_parts
del parts, mask_parts
if max(1,self.cfg.SYSTEM.NUM_GPUS) != len(data_parts_filenames) != len(list_of_vols_in_z):
raise ValueError("Number of data parts is not the same as number of GPUs")
# Compose the large image
for i, data_part_fname in enumerate(data_parts_filenames):
print("Reading {}".format(os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, data_part_fname)))
data_part_file, data_part = read_chunked_data(os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, data_part_fname))
data_mask_part_file, data_mask_part = read_chunked_data(os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, data_parts_mask_filenames[i]))
if 'data' not in locals():
all_data_filename = os.path.join(self.cfg.PATHS.RESULT_DIR.PER_IMAGE, filename+ext)
if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5":
allfile = h5py.File(all_data_filename,'w')
data = allfile.create_dataset("data", data_part.shape, dtype=self.dtype_str, compression="gzip")
else:
allfile = zarr.open_group(all_data_filename, mode="w")
data = allfile.create_dataset("data", shape=data_part.shape, dtype=self.dtype_str, compression="gzip")
for j, k in enumerate(list_of_vols_in_z[i]):
if self.cfg.TEST.VERBOSE:
print(f"Filling {k} [{z_vol_info[k][0]}:{z_vol_info[k][1]}]")
data[:,z_vol_info[k][0]:z_vol_info[k][1]] = \
data_part[:,z_vol_info[k][0]:z_vol_info[k][1]] / data_mask_part[:,z_vol_info[k][0]:z_vol_info[k][1]]
if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5":
allfile.flush()
if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5":
data_part_file.close()
data_mask_part_file.close()
# Save image
if self.cfg.TEST.BY_CHUNKS.SAVE_OUT_TIF and self.cfg.PATHS.RESULT_DIR.PER_IMAGE != "":
save_tif(np.array(data, dtype=self.dtype).transpose(t_axes), self.cfg.PATHS.RESULT_DIR.PER_IMAGE,
[filename+".tif"], verbose=self.cfg.TEST.VERBOSE)
if self.cfg.TEST.BY_CHUNKS.FORMAT == "h5":
allfile.close()
# Just make the division with the overlap
else:
# Load predictions and overlapping mask