-
Notifications
You must be signed in to change notification settings - Fork 79
/
test_full.py
3419 lines (2983 loc) · 125 KB
/
test_full.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
from pathlib import Path
import gdown, zipfile, os, csv, random, copy, shutil, yaml, torch, pytest
import SimpleITK as sitk
import numpy as np
import pandas as pd
import logging
from pydicom.data import get_testdata_file
import cv2
from GANDLF.data.ImagesFromDataFrame import ImagesFromDataFrame
from GANDLF.utils import *
from GANDLF.utils import parseTestingCSV, get_tensor_from_image
from GANDLF.data.preprocessing import global_preprocessing_dict
from GANDLF.data.augmentation import global_augs_dict
from GANDLF.data.patch_miner.opm.utils import (
generate_initial_mask,
alpha_rgb_2d_channel_check,
get_nonzero_percent,
get_patch_size_in_microns,
convert_to_tiff,
)
from GANDLF.config_manager import ConfigManager
from GANDLF.parseConfig import parseConfig
from GANDLF.training_manager import TrainingManager
from GANDLF.inference_manager import InferenceManager
from GANDLF.cli import (
main_run,
preprocess_and_save,
patch_extraction,
config_generator,
run_deployment,
recover_config,
post_training_model_optimization,
generate_metrics_dict,
split_data_and_save_csvs,
)
from GANDLF.cli.huggingface_hub_handler import push_to_model_hub, download_from_hub
from GANDLF.schedulers import global_schedulers_dict
from GANDLF.optimizers import global_optimizer_dict
from GANDLF.models import global_models_dict
from GANDLF.data.post_process import (
torch_morphological,
fill_holes,
get_mapped_label,
cca,
)
from GANDLF.anonymize import run_anonymizer
from GANDLF.entrypoints.debug_info import _debug_info
from huggingface_hub import HfApi
device = "cpu"
## global defines
# pre-defined segmentation model types for testing
all_models_segmentation = [
"lightunet",
"lightunet_multilayer",
"unet",
"unet_multilayer",
"deep_resunet",
"fcn",
"uinc",
"msdnet",
"imagenet_unet",
"dynunet",
]
# pre-defined regression/classification model types for testing
all_models_regression = [
"densenet121",
"vgg16",
"resnet18",
"resnet50",
"efficientnetb0",
"imagenet_unet",
]
# pre-defined regression/classification model types for testing
all_models_classification = [
"imagenet_vgg11",
"imagenet_vgg11_bn",
"imagenet_vgg13",
"imagenet_vgg13_bn",
"imagenet_vgg16",
"imagenet_vgg16_bn",
"imagenet_vgg19",
"imagenet_vgg19_bn",
"resnet18",
]
all_clip_modes = ["norm", "value", "agc"]
all_norm_types = ["batch", "instance"]
all_model_type = ["torch", "openvino"]
patch_size = {"2D": [128, 128, 1], "3D": [32, 32, 32]}
testingDir = Path(__file__).parent.absolute().__str__()
baseConfigDir = os.path.join(testingDir, os.pardir, "samples")
inputDir = os.path.join(testingDir, "data")
outputDir = os.path.join(testingDir, "data_output")
Path(outputDir).mkdir(parents=True, exist_ok=True)
gandlfRootDir = Path(__file__).parent.parent.absolute().__str__()
"""
steps to follow to write tests:
[x] download sample data
[x] construct the training csv
[x] for each dir (application type) and sub-dir (image dimension), run training for a single epoch on cpu
[x] separate tests for 2D and 3D segmentation
[x] read default parameters from yaml config
[x] for each type, iterate through all available segmentation model archs
[x] call training manager with default parameters + current segmentation model arch
[ ] for each dir (application type) and sub-dir (image dimension), run inference for a single trained model per testing/validation split for a single subject on cpu
"""
def prerequisites_hook_download_data():
print("00: Downloading the sample data")
urlToDownload = "https://drive.google.com/uc?id=1c4Yrv-jnK6Tk7Ne1HmMTChv-4nYk43NT"
files_check = [
os.path.join(inputDir, "2d_histo_segmentation", "1", "image.tiff"),
os.path.join(inputDir, "2d_rad_segmentation", "001", "image.png"),
os.path.join(inputDir, "3d_rad_segmentation", "001", "image.nii.gz"),
]
# check for missing subjects so that we do not download data again
for file in files_check:
if not os.path.isfile(file):
print("Downloading and extracting sample data")
output = os.path.join(testingDir, "gandlf_unit_test_data.tgz")
gdown.download(urlToDownload, output, quiet=False, verify=True)
with zipfile.ZipFile(output, "r") as zip_ref:
zip_ref.extractall(testingDir)
os.remove(output)
break
sanitize_outputDir()
print("passed")
def prerequisites_constructTrainingCSV():
print("01: Constructing training CSVs")
# delete previous csv files
files = os.listdir(inputDir)
for item in files:
if item.endswith(".csv"):
os.remove(os.path.join(inputDir, item))
for application_data in os.listdir(inputDir):
currentApplicationDir = os.path.join(inputDir, application_data)
if "2d_rad_segmentation" in application_data:
channelsID = "image.png"
labelID = "mask.png"
elif "3d_rad_segmentation" in application_data:
channelsID = "image"
labelID = "mask"
elif "2d_histo_segmentation" in application_data:
channelsID = "image"
labelID = "mask"
# else:
# continue
outputFile = inputDir + "/train_" + application_data + ".csv"
outputFile_rel = inputDir + "/train_" + application_data + "_relative.csv"
# Test with various combinations of relative/absolute paths
# Absolute input/output
writeTrainingCSV(
currentApplicationDir,
channelsID,
labelID,
outputFile,
relativizePathsToOutput=False,
)
writeTrainingCSV(
currentApplicationDir,
channelsID,
labelID,
outputFile_rel,
relativizePathsToOutput=True,
)
# write regression and classification files
application_data_regression = application_data.replace(
"segmentation", "regression"
)
application_data_classification = application_data.replace(
"segmentation", "classification"
)
with open(
inputDir + "/train_" + application_data + ".csv", "r"
) as read_f, open(
inputDir + "/train_" + application_data_regression + ".csv", "w", newline=""
) as write_reg, open(
inputDir + "/train_" + application_data_classification + ".csv",
"w",
newline="",
) as write_class:
csv_reader = csv.reader(read_f)
csv_writer_1 = csv.writer(write_reg)
csv_writer_2 = csv.writer(write_class)
i = 0
for row in csv_reader:
if i == 0:
row.append("ValueToPredict")
csv_writer_2.writerow(row)
# row.append('ValueToPredict_2')
csv_writer_1.writerow(row)
else:
row_regression = copy.deepcopy(row)
row_classification = copy.deepcopy(row)
row_regression.append(str(random.uniform(0, 1)))
# row_regression.append(str(random.uniform(0, 1)))
row_classification.append(str(random.randint(0, 2)))
csv_writer_1.writerow(row_regression)
csv_writer_2.writerow(row_classification)
i += 1
def test_prepare_data_for_ci():
# is used to run pytest session (i.e. to prepare environment, download data etc)
# without any real test execution
# to see what happens, refer to `conftest.py:pytest_sessionstart`
pass
# # these are helper functions to be used in other tests
def sanitize_outputDir():
print("02_1: Sanitizing outputDir")
if os.path.isdir(outputDir):
shutil.rmtree(outputDir) # overwrite previous results
Path(outputDir).mkdir(parents=True, exist_ok=True)
def write_temp_config_path(parameters_to_write):
print("02_2: Creating path for temporary config file")
temp_config_path = os.path.join(outputDir, "config_temp.yaml")
# if found in previous run, discard.
if os.path.exists(temp_config_path):
os.remove(temp_config_path)
if parameters_to_write is not None:
with open(temp_config_path, "w") as file:
yaml.dump(parameters_to_write, file)
return temp_config_path
# these are helper functions to be used in other tests
def test_train_segmentation_rad_2d(device):
print("03: Starting 2D Rad segmentation tests")
# read and parse csv
parameters = parseConfig(
testingDir + "/config_segmentation.yaml", version_check_flag=False
)
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_segmentation.csv"
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
parameters["model"]["class_list"] = [0, 255]
parameters["model"]["amp"] = True
parameters["model"]["num_channels"] = 3
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters["data_preprocessing"]["resize_image"] = [224, 224]
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# read and initialize parameters for specific data dimension
for model in all_models_segmentation:
if model == "imagenet_unet":
# imagenet_unet encoder needs to be toned down for small patch size
parameters["model"]["encoder_name"] = "mit_b0"
parameters["model"]["encoder_depth"] = 3
parameters["model"]["decoder_channels"] = (64, 32, 16)
parameters["model"]["final_layer"] = random.choice(
["sigmoid", "softmax", "logsoftmax", "tanh", "identity"]
)
parameters["model"]["converter_type"] = random.choice(
["acs", "soft", "conv3d"]
)
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_segmentation_sdnet_rad_2d(device):
print("04: Starting 2D Rad segmentation tests")
# read and parse csv
parameters = ConfigManager(
testingDir + "/config_segmentation.yaml", version_check_flag=False
)
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_segmentation.csv"
)
# patch_size is custom for sdnet
parameters["patch_size"] = [224, 224, 1]
parameters["batch_size"] = 2
parameters["model"]["dimension"] = 2
parameters["model"]["class_list"] = [0, 255]
parameters["model"]["num_channels"] = 1
parameters["model"]["architecture"] = "sdnet"
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
sanitize_outputDir()
print("passed")
def test_train_segmentation_rad_3d(device):
print("05: Starting 3D Rad segmentation tests")
# read and parse csv
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_segmentation.yaml", version_check_flag=False
)
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_segmentation.csv"
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
parameters["model"]["class_list"] = [0, 1]
parameters["model"]["final_layer"] = "softmax"
parameters["model"]["amp"] = True
parameters["in_memory"] = True
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
for model in all_models_segmentation:
if model == "imagenet_unet":
# imagenet_unet encoder needs to be toned down for small patch size
parameters["model"]["encoder_name"] = "mit_b0"
with pytest.raises(Exception) as exc_info:
_ = global_models_dict[model](parameters)
print("Exception raised:", exc_info.value)
parameters["model"]["encoder_name"] = "resnet34"
parameters["model"]["encoder_depth"] = 3
parameters["model"]["decoder_channels"] = (64, 32, 16)
parameters["model"]["final_layer"] = random.choice(
["sigmoid", "softmax", "logsoftmax", "tanh", "identity"]
)
parameters["model"]["converter_type"] = random.choice(
["acs", "soft", "conv3d"]
)
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_regression_rad_2d(device):
print("06: Starting 2D Rad regression tests")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_regression.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
parameters["model"]["amp"] = False
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_regression.csv"
)
parameters["model"]["num_channels"] = 3
parameters["model"]["class_list"] = parameters["headers"]["predictionHeaders"]
parameters["scaling_factor"] = 1
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
for model in all_models_regression:
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_regression_rad_2d_imagenet(device):
print("07: Starting 2D Rad regression tests for imagenet models")
# read and initialize parameters for specific data dimension
print("Starting 2D Rad regression tests for imagenet models")
parameters = ConfigManager(
testingDir + "/config_regression.yaml", version_check_flag=False
)
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
parameters["model"]["amp"] = False
parameters["model"]["print_summary"] = False
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_regression.csv"
)
parameters["model"]["num_channels"] = 3
parameters["model"]["class_list"] = parameters["headers"]["predictionHeaders"]
parameters["scaling_factor"] = 1
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
for model in all_models_classification:
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = 1
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_regression_brainage_rad_2d(device):
print("08: Starting brain age tests")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_regression.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
parameters["model"]["amp"] = False
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_regression.csv"
)
parameters["model"]["num_channels"] = 3
parameters["model"]["class_list"] = parameters["headers"]["predictionHeaders"]
parameters["scaling_factor"] = 1
parameters["model"]["architecture"] = "brain_age"
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
# parameters_temp = copy.deepcopy(parameters)
parameters = populate_header_in_parameters(parameters, parameters["headers"])
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
# file_config_temp = write_temp_config_path(parameters_temp)
model_path = os.path.join(outputDir, "brain_age_best.pth.tar")
config_path = os.path.join(outputDir, "parameters.pkl")
optimization_result = post_training_model_optimization(model_path, config_path)
assert optimization_result == False, "Optimization should fail"
sanitize_outputDir()
print("passed")
def test_train_regression_rad_3d(device):
print("09: Starting 3D Rad regression tests")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_regression.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_regression.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters["model"]["class_list"] = parameters["headers"]["predictionHeaders"]
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
for model in all_models_regression:
if "efficientnet" in model:
parameters["patch_size"] = [16, 16, 16]
else:
parameters["patch_size"] = patch_size["3D"]
if model == "imagenet_unet":
parameters["model"]["depth"] = 2
parameters["model"]["decoder_channels"] = [32, 16]
parameters["model"]["encoder_weights"] = "None"
parameters["model"]["converter_type"] = random.choice(
["acs", "soft", "conv3d"]
)
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_classification_rad_2d(device):
print("10: Starting 2D Rad classification tests")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["track_memory_usage"] = True
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_classification.csv"
)
parameters["model"]["num_channels"] = 3
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
for model in all_models_regression:
if model == "imagenet_unet":
parameters["model"]["depth"] = 2
parameters["model"]["decoder_channels"] = [32, 16]
parameters["model"]["encoder_weights"] = "None"
parameters["model"]["converter_type"] = random.choice(
["acs", "soft", "conv3d"]
)
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
# ensure sigmoid and softmax activations are tested for imagenet models
for activation_type in ["sigmoid", "softmax"]:
parameters["model"]["architecture"] = "imagenet_vgg11"
parameters["model"]["final_layer"] = activation_type
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_classification_rad_3d(device):
print("11: Starting 3D Rad classification tests")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_classification.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
# loop through selected models and train for single epoch
for model in all_models_regression:
if "efficientnet" in model:
parameters["patch_size"] = [16, 16, 16]
else:
parameters["patch_size"] = patch_size["3D"]
if model == "imagenet_unet":
parameters["model"]["encoder_name"] = "efficientnet-b0"
parameters["model"]["depth"] = 1
parameters["model"]["decoder_channels"] = [64]
parameters["model"]["final_layer"] = random.choice(
["sigmoid", "softmax", "logsoftmax", "tanh", "identity"]
)
parameters["model"]["converter_type"] = random.choice(
["acs", "soft", "conv3d"]
)
parameters["model"]["architecture"] = model
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
sanitize_outputDir()
print("passed")
def test_train_resume_inference_classification_rad_3d(device):
print("12: Starting 3D Rad classification tests for resume and reset")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_classification.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
model = all_models_regression[0]
parameters["model"]["architecture"] = model
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
## testing resume with parameter updates
parameters["num_epochs"] = 2
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
parameters["model"]["save_at_every_epoch"] = True
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=True,
reset=False,
)
## testing resume without parameter updates
parameters["num_epochs"] = 1
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=False,
)
parameters["output_dir"] = outputDir # this is in inference mode
InferenceManager(
dataframe=training_data,
modelDir=outputDir,
parameters=parameters,
device=device,
)
sanitize_outputDir()
print("passed")
def test_train_inference_optimize_classification_rad_3d(device):
print("13: Starting 3D Rad segmentation tests for optimization")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_classification.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
parameters["model"]["architecture"] = all_models_regression[0]
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
# parameters_temp = copy.deepcopy(parameters)
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
# file_config_temp = write_temp_config_path(parameters_temp)
model_path = os.path.join(outputDir, all_models_regression[0] + "_best.pth.tar")
config_path = os.path.join(outputDir, "parameters.pkl")
optimization_result = post_training_model_optimization(
model_path, config_path, outputDir
)
assert optimization_result == True, "Optimization should pass"
## testing inference
for model_type in all_model_type:
parameters["model"]["type"] = model_type
parameters["output_dir"] = outputDir # this is in inference mode
InferenceManager(
dataframe=training_data,
modelDir=outputDir,
parameters=parameters,
device=device,
)
sanitize_outputDir()
print("passed")
def test_train_inference_optimize_segmentation_rad_2d(device):
print("14: Starting 2D Rad segmentation tests for optimization")
# read and parse csv
parameters = ConfigManager(
testingDir + "/config_segmentation.yaml", version_check_flag=False
)
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_segmentation.csv"
)
parameters["patch_size"] = patch_size["2D"]
parameters["modality"] = "rad"
parameters["model"]["dimension"] = 2
parameters["model"]["class_list"] = [0, 255]
parameters["model"]["amp"] = True
parameters["save_output"] = True
parameters["model"]["num_channels"] = 3
parameters["metrics"] = ["dice"]
parameters["model"]["architecture"] = "resunet"
parameters["model"]["onnx_export"] = True
parameters["model"]["print_summary"] = False
parameters = populate_header_in_parameters(parameters, parameters["headers"])
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
## testing inference
for model_type in all_model_type:
parameters["model"]["type"] = model_type
parameters["output_dir"] = outputDir # this is in inference mode
InferenceManager(
dataframe=training_data,
modelDir=outputDir,
parameters=parameters,
device=device,
)
sanitize_outputDir()
print("passed")
def test_train_inference_classification_with_logits_single_fold_rad_3d(device):
print("15: Starting 3D Rad classification tests for single fold logits inference")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
parameters["model"]["final_layer"] = "logits"
# loop through selected models and train for single epoch
model = all_models_regression[0]
parameters["model"]["architecture"] = model
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
## add stratified splitting
parameters["nested_training"]["stratified"] = True
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_classification.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# duplicate the data to test stratified sampling
training_data_duplicate = training_data._append(training_data)
for _ in range(1):
training_data_duplicate = training_data_duplicate._append(
training_data_duplicate
)
training_data_duplicate.reset_index(drop=True, inplace=True)
# ensure subjects are not duplicated
training_data_duplicate["SubjectID"] = training_data_duplicate.index
# ensure every part of the code is tested
for folds in [2, 1, -5]:
## add stratified folding information
parameters["nested_training"]["testing"] = folds
parameters["nested_training"]["validation"] = folds if folds != 1 else -5
sanitize_outputDir()
TrainingManager(
dataframe=training_data_duplicate,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
## this is to test if inference can run without having ground truth column
training_data.drop("ValueToPredict", axis=1, inplace=True)
training_data.drop("Label", axis=1, inplace=True)
temp_infer_csv = os.path.join(outputDir, "temp_infer_csv.csv")
training_data.to_csv(temp_infer_csv, index=False)
# read and parse csv
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
training_data, parameters["headers"] = parseTrainingCSV(temp_infer_csv)
parameters["output_dir"] = outputDir # this is in inference mode
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
parameters["model"]["final_layer"] = "logits"
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
model = all_models_regression[0]
parameters["model"]["architecture"] = model
parameters["model"]["onnx_export"] = False
InferenceManager(
dataframe=training_data,
modelDir=outputDir,
parameters=parameters,
device=device,
)
sanitize_outputDir()
print("passed")
def test_train_inference_classification_with_logits_multiple_folds_rad_3d(device):
print("16: Starting 3D Rad classification tests for multi-fold logits inference")
# read and initialize parameters for specific data dimension
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["3D"]
parameters["model"]["dimension"] = 3
parameters["model"]["final_layer"] = "logits"
# necessary for n-fold cross-validation inference
parameters["nested_training"]["validation"] = 2
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_3d_rad_classification.csv"
)
parameters["model"]["num_channels"] = len(parameters["headers"]["channelHeaders"])
parameters = populate_header_in_parameters(parameters, parameters["headers"])
# loop through selected models and train for single epoch
model = all_models_regression[0]
parameters["model"]["architecture"] = model
sanitize_outputDir()
TrainingManager(
dataframe=training_data,
outputDir=outputDir,
parameters=parameters,
device=device,
resume=False,
reset=True,
)
parameters["output_dir"] = outputDir # this is in inference mode
InferenceManager(
dataframe=training_data,
modelDir=outputDir + "," + outputDir,
parameters=parameters,
device=device,
)
sanitize_outputDir()
print("passed")
def test_train_scheduler_classification_rad_2d(device):
print("17: Starting 2D Rad segmentation tests for scheduler")
# read and initialize parameters for specific data dimension
# loop through selected models and train for single epoch
for scheduler in global_schedulers_dict:
parameters = ConfigManager(
testingDir + "/config_classification.yaml", version_check_flag=False
)
parameters["modality"] = "rad"
parameters["patch_size"] = patch_size["2D"]
parameters["model"]["dimension"] = 2
# read and parse csv
training_data, parameters["headers"] = parseTrainingCSV(
inputDir + "/train_2d_rad_classification.csv"
)
parameters["model"]["num_channels"] = 3
parameters["model"]["architecture"] = "densenet121"
parameters["model"]["norm_type"] = "instance"
parameters = populate_header_in_parameters(parameters, parameters["headers"])
parameters["model"]["onnx_export"] = False
parameters["model"]["print_summary"] = False
parameters["scheduler"] = {}
parameters["scheduler"]["type"] = scheduler
parameters["nested_training"]["testing"] = -5
parameters["nested_training"]["validation"] = -5
sanitize_outputDir()
## ensure parameters are parsed every single time
file_config_temp = write_temp_config_path(parameters)
parameters = ConfigManager(file_config_temp, version_check_flag=False)
TrainingManager(