Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+10
- README.md-3
- docker_task_1/.envAdded+2
- docker_task_1/260_gt_nnUNetResEncUNetLPlans.jsonAdded+521
- docker_task_1/262_gt_nnUNetResEncUNetLPlans.jsonAdded+356
- docker_task_1/264_gt_nnUNetResEncUNetLPlans.jsonAdded+521
- docker_task_1/DockerfileAdded+43
- docker_task_1/__pycache__/base_algorithm.cpython-312.pycAdded
- docker_task_1/__pycache__/revert_normalisation.cpython-312.pycAdded
- docker_task_1/base_algorithm.pyAdded+205
- docker_task_1/build.shAdded+4
- docker_task_1/dynamic-network-architectures/.gitignoreAdded+113
- docker_task_1/dynamic-network-architectures/LICENCEAdded+201
- docker_task_1/dynamic-network-architectures/README.mdAdded+14
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/PKG-INFOAdded+16
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/SOURCES.txtAdded+27
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/dependency_links.txtAdded+1
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/not-zip-safeAdded+1
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/requires.txtAdded+2
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/top_level.txtAdded+1
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__init__.pyAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__pycache__/__init__.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__pycache__/__init__.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__init__.pyAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/__init__.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/__init__.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/unet.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/unet.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/resnet.pyAdded+236
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/unet.pyAdded+232
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/vgg.pyAdded+85
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__init__.pyAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/__init__.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/__init__.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/helper.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/helper.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/plain_conv_encoder.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/plain_conv_encoder.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/regularization.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/regularization.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual_encoders.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual_encoders.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/simple_conv_blocks.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/simple_conv_blocks.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder.cpython-312.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder_upsample_nearest.cpython-310.pycAdded
- docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder_upsample_nearest.cpython-312.pycAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdocker_task_1/nnsyn/documentation/assets/amos2022_sparseseg10.png filter=lfs diff=lfs merge=lfs -textdocker_task_1/nnsyn/documentation/assets/amos2022_sparseseg10_2d.png filter=lfs diff=lfs merge=lfs -textdocker_task_1/nnsyn/documentation/assets/nnU-Net_overview.png filter=lfs diff=lfs merge=lfs -textdocker_task_1/nnsyn/documentation/assets/regions_vs_labels.png filter=lfs diff=lfs merge=lfs -textdocker_task_1/nnsyn/documentation/assets/scribble_example.png filter=lfs diff=lfs merge=lfs -textdocker_task_2/nnsyn/documentation/assets/amos2022_sparseseg10.png filter=lfs diff=lfs merge=lfs -textdocker_task_2/nnsyn/documentation/assets/amos2022_sparseseg10_2d.png filter=lfs diff=lfs merge=lfs -textdocker_task_2/nnsyn/documentation/assets/nnU-Net_overview.png filter=lfs diff=lfs merge=lfs -textdocker_task_2/nnsyn/documentation/assets/regions_vs_labels.png filter=lfs diff=lfs merge=lfs -textdocker_task_2/nnsyn/documentation/assets/scribble_example.png filter=lfs diff=lfs merge=lfs -text
123---license: apache-2.0---
12TASK_TYPE="mri" # Set to mri (Task 1) or cbct (Task 2)INPUT_FOLDER="/input" # Do not change unless you want to test locally123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521{ "dataset_name": "Dataset261_synthrad2025_task1_CT_AB_pre_v2r_stitched_masked", "plans_name": "nnUNetResEncUNetLPlans", "original_median_spacing_after_transp": [ 3.0, 1.0, 1.0 ], "original_median_shape_after_transp": [ 99, 442, 465 ], "image_reader_writer": "SimpleITKIO", "transpose_forward": [ 0, 1, 2 ], "transpose_backward": [ 0, 1, 2 ], "configurations": { "2d": { "data_identifier": "nnUNetPlans_2d", "preprocessor_name": "DefaultPreprocessor", "batch_size": 13, "patch_size": [ 448, 512 ], "median_image_size_in_voxels": [ 442.0, 465.0 ], "spacing": [ 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 7, "features_per_stage": [ 32, 64, 128, 256, 512, 512, 512 ], "conv_op": "torch.nn.modules.conv.Conv2d", "kernel_sizes": [ [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ] ], "strides": [ [ 1, 1 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm2d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": true }, "3d_lowres": { "data_identifier": "nnUNetResEncUNetLPlans_3d_lowres", "preprocessor_name": "DefaultPreprocessor", "batch_size": 2, "patch_size": [ 64, 192, 192 ], "median_image_size_in_voxels": [ 99, 292, 307 ], "spacing": [ 3.0, 1.512589724855112, 1.512589724855112 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 6, "features_per_stage": [ 32, 64, 128, 256, 320, 320 ], "conv_op": "torch.nn.modules.conv.Conv3d", "kernel_sizes": [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ], "strides": [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 1, 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm3d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": false, "next_stage": "3d_cascade_fullres" }, "3d_fullres": { "data_identifier": "nnUNetPlans_3d_fullres", "preprocessor_name": "DefaultPreprocessor", "batch_size": 2, "patch_size": [ 40, 192, 224 ], "median_image_size_in_voxels": [ 99.0, 442.0, 465.0 ], "spacing": [ 3.0, 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 6, "features_per_stage": [ 32, 64, 128, 256, 320, 320 ], "conv_op": "torch.nn.modules.conv.Conv3d", "kernel_sizes": [ [ 1, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ], "strides": [ [ 1, 1, 1 ], [ 1, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 1, 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm3d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": true }, "3d_cascade_fullres": { "inherits_from": "3d_fullres", "previous_stage": "3d_lowres" } }, "experiment_planner_used": "nnUNetPlannerResEncL", "label_manager": "LabelManager", "foreground_intensity_properties_per_channel": { "0": { "max": 3958.0, "mean": -226.3246612548828, "median": -81.0, "min": -1502.0, "percentile_00_5": -1024.0, "percentile_99_5": 566.0, "std": 396.30517578125 } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356{ "dataset_name": "Dataset263_synthrad2025_task1_CT_HN_pre_v2r_stitched_masked", "plans_name": "nnUNetResEncUNetLPlans", "original_median_spacing_after_transp": [ 3.0, 1.0, 1.0 ], "original_median_shape_after_transp": [ 89, 296, 279 ], "image_reader_writer": "SimpleITKIO", "transpose_forward": [ 0, 1, 2 ], "transpose_backward": [ 0, 1, 2 ], "configurations": { "2d": { "data_identifier": "nnUNetPlans_2d", "preprocessor_name": "DefaultPreprocessor", "batch_size": 30, "patch_size": [ 320, 320 ], "median_image_size_in_voxels": [ 296.0, 279.0 ], "spacing": [ 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 7, "features_per_stage": [ 32, 64, 128, 256, 512, 512, 512 ], "conv_op": "torch.nn.modules.conv.Conv2d", "kernel_sizes": [ [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ] ], "strides": [ [ 1, 1 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm2d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": true }, "3d_fullres": { "data_identifier": "nnUNetPlans_3d_fullres", "preprocessor_name": "DefaultPreprocessor", "batch_size": 2, "patch_size": [ 56, 192, 160 ], "median_image_size_in_voxels": [ 89.0, 296.0, 279.0 ], "spacing": [ 3.0, 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 6, "features_per_stage": [ 32, 64, 128, 256, 320, 320 ], "conv_op": "torch.nn.modules.conv.Conv3d", "kernel_sizes": [ [ 1, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ], "strides": [ [ 1, 1, 1 ], [ 1, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 1, 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm3d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": false } }, "experiment_planner_used": "nnUNetPlannerResEncL", "label_manager": "LabelManager", "foreground_intensity_properties_per_channel": { "0": { "max": 3940.0, "mean": -137.8296356201172, "median": 12.0, "min": -1708.0, "percentile_00_5": -1018.0, "percentile_99_5": 1349.0, "std": 482.0824279785156 } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521{ "dataset_name": "Dataset265_synthrad2025_task1_CT_TH_pre_v2r_stitched_masked", "plans_name": "nnUNetResEncUNetLPlans", "original_median_spacing_after_transp": [ 3.0, 1.0, 1.0 ], "original_median_shape_after_transp": [ 108, 476, 536 ], "image_reader_writer": "SimpleITKIO", "transpose_forward": [ 0, 1, 2 ], "transpose_backward": [ 0, 1, 2 ], "configurations": { "2d": { "data_identifier": "nnUNetPlans_2d", "preprocessor_name": "DefaultPreprocessor", "batch_size": 13, "patch_size": [ 448, 512 ], "median_image_size_in_voxels": [ 476.0, 536.0 ], "spacing": [ 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 7, "features_per_stage": [ 32, 64, 128, 256, 512, 512, 512 ], "conv_op": "torch.nn.modules.conv.Conv2d", "kernel_sizes": [ [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ] ], "strides": [ [ 1, 1 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ], [ 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm2d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": true }, "3d_lowres": { "data_identifier": "nnUNetResEncUNetLPlans_3d_lowres", "preprocessor_name": "DefaultPreprocessor", "batch_size": 2, "patch_size": [ 64, 192, 192 ], "median_image_size_in_voxels": [ 98, 288, 324 ], "spacing": [ 3.278181, 1.652847632271752, 1.652847632271752 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 6, "features_per_stage": [ 32, 64, 128, 256, 320, 320 ], "conv_op": "torch.nn.modules.conv.Conv3d", "kernel_sizes": [ [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ], "strides": [ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 1, 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm3d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": false, "next_stage": "3d_cascade_fullres" }, "3d_fullres": { "data_identifier": "nnUNetPlans_3d_fullres", "preprocessor_name": "DefaultPreprocessor", "batch_size": 2, "patch_size": [ 40, 192, 224 ], "median_image_size_in_voxels": [ 107.5, 476.0, 536.0 ], "spacing": [ 3.0, 1.0, 1.0 ], "normalization_schemes": [ "CTNormalizationClippingSynthrad2025" ], "use_mask_for_norm": [ false ], "resampling_fn_data": "resample_data_or_seg_to_shape", "resampling_fn_seg": "resample_data_or_seg_to_shape", "resampling_fn_data_kwargs": { "is_seg": false, "order": 3, "order_z": 0, "force_separate_z": null }, "resampling_fn_seg_kwargs": { "is_seg": true, "order": 1, "order_z": 0, "force_separate_z": null }, "resampling_fn_probabilities": "resample_data_or_seg_to_shape", "resampling_fn_probabilities_kwargs": { "is_seg": false, "order": 1, "order_z": 0, "force_separate_z": null }, "architecture": { "network_class_name": "dynamic_network_architectures.architectures.unet.ResidualEncoderUNet", "arch_kwargs": { "n_stages": 6, "features_per_stage": [ 32, 64, 128, 256, 320, 320 ], "conv_op": "torch.nn.modules.conv.Conv3d", "kernel_sizes": [ [ 1, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ], [ 3, 3, 3 ] ], "strides": [ [ 1, 1, 1 ], [ 1, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 2, 2, 2 ], [ 1, 2, 2 ] ], "n_blocks_per_stage": [ 1, 3, 4, 6, 6, 6 ], "n_conv_per_stage_decoder": [ 1, 1, 1, 1, 1 ], "conv_bias": true, "norm_op": "torch.nn.modules.instancenorm.InstanceNorm3d", "norm_op_kwargs": { "eps": 1e-05, "affine": true }, "dropout_op": null, "dropout_op_kwargs": null, "nonlin": "torch.nn.LeakyReLU", "nonlin_kwargs": { "inplace": true } }, "_kw_requires_import": [ "conv_op", "norm_op", "dropout_op", "nonlin" ] }, "batch_dice": true }, "3d_cascade_fullres": { "inherits_from": "3d_fullres", "previous_stage": "3d_lowres" } }, "experiment_planner_used": "nnUNetPlannerResEncL", "label_manager": "LabelManager", "foreground_intensity_properties_per_channel": { "0": { "max": 3867.0, "mean": -282.4960632324219, "median": -94.0, "min": -1607.0, "percentile_00_5": -1024.0, "percentile_99_5": 630.0, "std": 427.12237548828125 } }}12345678910111213141516171819202122232425262728293031323334353637383940414243FROM python:3.12-slim# FROM python:3.12ARG task_type
ENV TASK_TYPE=$task_typeENV EXECUTE_IN_DOCKER=1
RUN groupadd -r algorithm && useradd -m --no-log-init -r -g algorithm algorithm
RUN mkdir -p /opt/algorithm /input /output \ && chown algorithm:algorithm /opt/algorithm /input /output
USER algorithm
WORKDIR /opt/algorithm
ENV PATH="/home/algorithm/.local/bin:${PATH}"# ENV nnUNet_preprocessed="/opt/algorithm/nnunet_preprocessed"# ENV nnUNet_results="/opt/algorithm/nnunet_results"# ENV nnUNet_raw="/opt/algorithm/nnunet_raw"# ENV PYTHONPATH="/opt/algorithm/nnUNetv2:$PYTHONPATH"
RUN python -m pip install --user -U pip
COPY --chown=algorithm:algorithm requirements.txt /opt/algorithm/RUN python -m pip install --user -r requirements.txtCOPY --chown=algorithm:algorithm nnsyn /opt/algorithm/nnsynRUN cd /opt/algorithm/nnsyn && python -m pip install --user -e .
COPY --chown=algorithm:algorithm .env /opt/algorithm/COPY --chown=algorithm:algorithm process.py /opt/algorithm/COPY --chown=algorithm:algorithm base_algorithm.py /opt/algorithm/COPY --chown=algorithm:algorithm nnunet_preprocessed/ /opt/algorithm/nnunet_preprocessedCOPY --chown=algorithm:algorithm nnunet_raw/ /opt/algorithm/nnunet_raw# COPY --chown=algorithm:algorithm nnunet_results/ /opt/algorithm/nnunet_resultsCOPY --chown=algorithm:algorithm 260_gt_nnUNetResEncUNetLPlans.json /opt/algorithm/COPY --chown=algorithm:algorithm 262_gt_nnUNetResEncUNetLPlans.json /opt/algorithm/COPY --chown=algorithm:algorithm 264_gt_nnUNetResEncUNetLPlans.json /opt/algorithm/COPY --chown=algorithm:algorithm revert_normalisation.py /opt/algorithm/COPY --chown=algorithm:algorithm dynamic-network-architectures/ /opt/algorithm/dynamic-network-architecturesRUN cd /opt/algorithm/dynamic-network-architectures && python -m pip install --user -e .ENTRYPOINT python -m process $0 $@123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205import jsonimport loggingimport osimport refrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import (Any, Callable, Dict, Iterable, List, Optional, Pattern, Set, Tuple, Union)
import numpy as npimport SimpleITKfrom evalutils.exceptions import FileLoaderErrorfrom evalutils.io import FileLoader, ImageLoader, SimpleITKLoaderfrom evalutils.validators import (UniqueImagesValidator, UniquePathIndicesValidator)from pandas import DataFrame
logger = logging.getLogger(__name__)
# Check if .env file exists and load itif Path(".env").exists(): from dotenv import dotenv_values
config = dotenv_values(".env")
TASK_TYPE = config["TASK_TYPE"] INPUT_FOLDER = config["INPUT_FOLDER"]
print("########## ENVIRONMENT VARIABLES ##########") print(f"TASK_TYPE: {TASK_TYPE}") print(f"INPUT_FOLDER: {INPUT_FOLDER}")else: TASK_TYPE = "mri" INPUT_FOLDER = "/input"
if INPUT_FOLDER == "/input": OUTPUT_FOLDER = "/output"else: OUTPUT_FOLDER = "./output"
DEFAULT_IMAGE_PATH = Path(f"{INPUT_FOLDER}/images/{TASK_TYPE}")DEFAULT_REGION_PATH = Path(f"{INPUT_FOLDER}/region.json")DEFAULT_MASK_PATH = Path(f"{INPUT_FOLDER}/images/body")DEFAULT_OUTPUT_PATH = Path(f"{OUTPUT_FOLDER}/images/synthetic-ct")DEFAULT_OUTPUT_FILE = Path(f"{OUTPUT_FOLDER}/results.json")
class BaseSynthradAlgorithm(ABC): def __init__( self, input_path: Path = DEFAULT_IMAGE_PATH, mask_path: Path = DEFAULT_MASK_PATH, region_path: Path = DEFAULT_REGION_PATH, output_path: Path = DEFAULT_OUTPUT_PATH, output_file: Path = DEFAULT_OUTPUT_FILE, validators: Optional[Dict[str, callable]] = None, file_loader: FileLoader = SimpleITKLoader(), ): """ Parameters ----------
input_path The path in the container where the input images will be loaded from. from. Default: `/input/images/mri/` mask_path The path in the container where the input masks will be loaded from. Default: `/input/images/body/` output_path The path in the container where the output images will be written. Default: `/output/images/synthetic-ct/`
output_file The path to the location where the results will be written. Default: `/output/results.json` file_loader The loaders that will be used to get all files. Default: `evalutils.io.SimpleITKLoader` for `image` and `mask` validators A dictionary containing the validators that will be used on the loaded data per file_loader key. Default: `evalutils.validators.UniqueImagesValidator` for `input_image` """
self._index_keys = ["image", "mask"] self.input_path = input_path self.mask_path = mask_path self.region_path = region_path self.output_path = output_path self.output_file = output_file self._file_loader = file_loader
# TODO: Add validators # self.validators = [ # UniquePathIndicesValidator(), # UniqueImagesValidator(), # ]
self.cases = {} self._case_results = []
def load(self): self.images = self._load_cases( folder=self.input_path, file_loader=self._file_loader )
self.masks = self._load_cases( folder=self.mask_path, file_loader=self._file_loader )
with open(self.region_path, "r") as f: self.region = json.load(f)
def _load_cases( self, folder: Path, file_loader: ImageLoader, ) -> DataFrame: cases = []
for fp in sorted(folder.glob("*")): try: new_cases = file_loader.load(fname=fp) except FileLoaderError: logger.warning(f"Could not load {fp.name} using {file_loader}.") else: cases.extend(new_cases)
if len(cases) == 0: raise FileLoaderError( f"Could not load any files in {folder} with " f"{file_loader}." )
return cases
def validate(self): """TODO: Validates each dataframe for each fileloader separately""" pass
def _validate_data_frame(self, df: DataFrame): "TODO: Validate the dataframe for a specific fileloader" pass
def process_cases(self): self._case_results = []
for idx, case in enumerate(zip(self.images, self.masks)): self._case_results.append(self.process_case(idx=idx, case=case))
def process_case(self, idx: int, case: List[DataFrame]) -> Dict: images, images_file_paths = {}, {}
images["image"], images_file_paths["image"] = self._load_input_image(case[0]) images["mask"], images_file_paths["mask"] = self._load_input_image(case[1])
images["region"] = self.region
# Predict and generate output out = self.predict(input_dict=images)
# Write resulting segmentation to output location out_path = self.output_path / images_file_paths["image"].name if not self.output_path.exists(): self.output_path.mkdir(parents=True, exist_ok=True)
SimpleITK.WriteImage(out, str(out_path), True)
# Write segmentation file path to result.json for this case return { "outputs": [dict(type="metaio_image", filename=str(out_path))], "inputs": [ dict(type="metaio_image", filename=str(fn)) for fn in images_file_paths.values() ] + [dict(type="String", filename=str(self.region_path))], "error_messages": [], }
def _load_input_image(self, image) -> Tuple[SimpleITK.Image, Path]: input_image_file_path = image["path"] input_image_file_loader = self._file_loader
if not isinstance(input_image_file_loader, ImageLoader): raise RuntimeError("The used FileLoader was not of subclass ImageLoader")
# Load the image input_image = input_image_file_loader.load_image(input_image_file_path)
# Check that it is the expected image if input_image_file_loader.hash_image(input_image) != image["hash"]: raise RuntimeError("Image hashes do not match") return input_image, input_image_file_path
@abstractmethod def predict(self, *, input_dict: Dict[str, SimpleITK.Image]) -> SimpleITK.Image: pass
def save(self): with open(str(self.output_file), "w") as f: json.dump(self._case_results, f)
def process(self): self.load() self.validate() self.process_cases() self.save()1234#!/usr/bin/env bashSCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
docker build -t synthrad_algorithm_mri "$SCRIPTPATH"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonenv/build/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/*.egg-info/.installed.cfg*.egg
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*,cover.hypothesis/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.py
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuildertarget/
# IPython Notebook.ipynb_checkpoints
# pyenv.python-version
# celery beat schedule filecelerybeat-schedule
# dotenv.env
# virtualenvvenv/ENV/
# Spyder project settings.spyderproject
# Rope project settings.ropeproject
*.memmap*.zip*.npz*.npy*.jpg*.jpeg.idea*.txt.idea/**.nii.gz*.nii*.tif*.bmp*.pkl*.xml*.pkl*.pdf*.jpg*.jpeg
*.model
cifar_lightning/mlruns*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [2022] [Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany]
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.1234567891011121314# dynamic-network-architectures_translation This repository adapts the dynamic-network-architectures for image-to-image translation tasks. It is based on the original repository found at [MIC-DKFZ/dynamic-network-architectures](https://github.com/MIC-DKFZ/dynamic-network-architectures).
## Changes Made- **UNet Decoder Improvements**: Added upsampling + convolution in the UNet decoder instead of transposed convolution to help prevent checkerboard artifacts, especially when using perceptual loss. cf [this article](https://distill.pub/2016/deconv-checkerboard/). - `Upsample_Trilinear` - `Upsample_Nearest` ## Updates - Added an argument to control the choice of UNet decoder : decoder_type ["standard", "trilinear", "nearest"]
## TODO- Test if `tanh` is necessary after the last convolution in decoder (constrain to [-1 ; 1])12345678910111213141516Metadata-Version: 2.4Name: dynamic_network_architecturesVersion: 0.3.1Summary: noneAuthor: Fabian IsenseeAuthor-email: f.isensee@dkfz.deLicense: privateLicense-File: LICENCERequires-Dist: torch>=1.6.0aRequires-Dist: numpyDynamic: authorDynamic: author-emailDynamic: licenseDynamic: license-fileDynamic: requires-distDynamic: summary123456789101112131415161718192021222324252627LICENCEREADME.mdsetup.pydynamic_network_architectures/__init__.pydynamic_network_architectures.egg-info/PKG-INFOdynamic_network_architectures.egg-info/SOURCES.txtdynamic_network_architectures.egg-info/dependency_links.txtdynamic_network_architectures.egg-info/not-zip-safedynamic_network_architectures.egg-info/requires.txtdynamic_network_architectures.egg-info/top_level.txtdynamic_network_architectures/architectures/__init__.pydynamic_network_architectures/architectures/resnet.pydynamic_network_architectures/architectures/unet.pydynamic_network_architectures/architectures/vgg.pydynamic_network_architectures/building_blocks/__init__.pydynamic_network_architectures/building_blocks/helper.pydynamic_network_architectures/building_blocks/plain_conv_encoder.pydynamic_network_architectures/building_blocks/regularization.pydynamic_network_architectures/building_blocks/residual.pydynamic_network_architectures/building_blocks/residual_encoders.pydynamic_network_architectures/building_blocks/simple_conv_blocks.pydynamic_network_architectures/building_blocks/unet_decoder.pydynamic_network_architectures/building_blocks/unet_decoder_upsample_nearest.pydynamic_network_architectures/building_blocks/unet_decoder_upsample_trilinear.pydynamic_network_architectures/building_blocks/unet_residual_decoder.pydynamic_network_architectures/initialization/__init__.pydynamic_network_architectures/initialization/weight_init.py1
1
12torch>=1.6.0anumpy1dynamic_network_architectures123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236import torchfrom dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoder, BottleneckD, BasicBlockDfrom dynamic_network_architectures.building_blocks.helper import get_matching_pool_op, get_default_network_configfrom dynamic_network_architectures.building_blocks.simple_conv_blocks import ConvDropoutNormReLUfrom torch import nn
_ResNet_CONFIGS = { '18': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (2, 2, 2, 2), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None}, '34': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None}, '50': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 6, 10, 5), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None}, '152': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 13, 55, 4), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None}, '50_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2), 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': True, 'stem_channels': 64}, '152_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 8, 36, 3), 'strides': (1, 2, 2, 2), 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': True, 'stem_channels': 64}, '18_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (2, 2, 2, 2), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False, 'stem_channels': None}, '34_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False, 'stem_channels': None}, '50_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 6, 10, 5), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False, 'stem_channels': None}, '152_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 13, 55, 4), 'strides': (1, 2, 2, 2), 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False, 'stem_channels': None}, '50_cifar_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2), 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': False, 'stem_channels': 64}, '152_cifar_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 8, 36, 3), 'strides': (1, 2, 2, 2), 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': False, 'stem_channels': 64},}
class ResNetD(nn.Module): def __init__(self, n_classes: int, n_input_channel: int = 3, config='18', input_dimension=2, final_layer_dropout=0.0, stochastic_depth_p=0.0, squeeze_excitation=False, squeeze_excitation_rd_ratio=1./16): """ Implements ResNetD (https://arxiv.org/pdf/1812.01187.pdf). Args: n_classes: Number of classes n_input_channel: Number of input channels (e.g. 3 for RGB) config: Configuration of the ResNet input_dimension: Number of dimensions of the data (1, 2 or 3) final_layer_dropout: Probability of dropout before the final classifier stochastic_depth_p: Stochastic Depth probability squeeze_excitation: Whether Squeeze and Excitation should be applied squeeze_excitation_rd_ratio: Squeeze and Excitation Reduction Ratio Returns: ResNet Model """ super().__init__() self.input_channels = n_input_channel self.cfg = _ResNet_CONFIGS[config] self.ops = get_default_network_config(dimension=input_dimension) self.final_layer_dropout_p = final_layer_dropout
if self.cfg['disable_default_stem']: stem_features = self.cfg['stem_channels'] if self.cfg['stem_channels'] is not None else \ self.cfg['features_per_stage'][0] self.stem = self._build_imagenet_stem_D(stem_features) encoder_input_features = stem_features else: encoder_input_features = n_input_channel self.stem = None
self.encoder = ResidualEncoder(encoder_input_features, n_stages=len(self.cfg['features_per_stage']), features_per_stage=self.cfg['features_per_stage'], conv_op=self.ops['conv_op'], kernel_sizes=3, strides=self.cfg['strides'], n_blocks_per_stage=self.cfg['n_blocks_per_stage'], conv_bias=False, norm_op=self.ops['norm_op'], norm_op_kwargs=None, dropout_op=None, dropout_op_kwargs=None, nonlin=nn.ReLU, nonlin_kwargs={'inplace': True}, block=self.cfg['block'], bottleneck_channels=self.cfg['bottleneck_channels'], return_skips=False, disable_default_stem=self.cfg['disable_default_stem'], stem_channels=self.cfg['stem_channels'], stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_reduction_ratio=squeeze_excitation_rd_ratio)
self.gap = get_matching_pool_op(conv_op=self.ops['conv_op'], adaptive=True, pool_type='avg')(1) self.classifier = nn.Linear(self.cfg['features_per_stage'][-1], n_classes, True) self.final_layer_dropout = self.ops['dropout_op'](p=self.final_layer_dropout_p)
def forward(self, x): if self.stem is not None: x = self.stem(x) x = self.encoder(x) x = self.gap(x) x = self.final_layer_dropout(x).squeeze()
return self.classifier(x)
def _build_imagenet_stem_D(self, stem_features): """ https://arxiv.org/pdf/1812.01187.pdf
use 3 3x3(x3) convs instead of one 7x7. Stride is located in first conv.
Fig2 b) describes this :return: """ c1 = ConvDropoutNormReLU(self.ops['conv_op'], self.input_channels, stem_features, 3, 2, False, self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True}) c2 = ConvDropoutNormReLU(self.ops['conv_op'], stem_features, stem_features, 3, 1, False, self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True}) c3 = ConvDropoutNormReLU(self.ops['conv_op'], stem_features, stem_features, 3, 1, False, self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True}) pl = get_matching_pool_op(conv_op=self.ops['conv_op'], adaptive=False, pool_type='max')(2) stem = nn.Sequential(c1, c2, c3, pl) return stem
class ResNet18_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='18_cifar', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet34_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='34_cifar', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet50_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='50_cifar', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet152_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='152_cifar', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet50bn_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='50_cifar_bn', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet152bn_CIFAR(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='152_cifar_bn', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet18(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='18', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet34(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='34', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet50(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='50', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet152(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='152', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet50bn(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='50_bn', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
class ResNet152bn(ResNetD): def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2, final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False, squeeze_excitation_rd_ratio: float = 1./16): super().__init__(n_classes, n_input_channels, config='152_bn', input_dimension=input_dimension, final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p, squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
if __name__ == '__main__': data = torch.rand((1, 3, 224, 224))
model = ResNet50bn(10, 3) import hiddenlayer as hl
g = hl.build_graph(model, data, transforms=None) g.save("network_architecture.pdf") del g
#print(model.compute_conv_feature_map_size((32, 32)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232from typing import Union, Type, List, Tuple
import torchfrom dynamic_network_architectures.building_blocks.helper import convert_conv_op_to_dimfrom dynamic_network_architectures.building_blocks.plain_conv_encoder import PlainConvEncoderfrom dynamic_network_architectures.building_blocks.residual import BasicBlockD, BottleneckDfrom dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoderfrom dynamic_network_architectures.building_blocks.unet_decoder import UNetDecoderfrom dynamic_network_architectures.building_blocks.unet_residual_decoder import UNetResDecoderfrom dynamic_network_architectures.initialization.weight_init import InitWeights_Hefrom dynamic_network_architectures.initialization.weight_init import init_last_bn_before_add_to_0
from dynamic_network_architectures.building_blocks.unet_decoder_upsample_trilinear import UNetDecoder_Upsample_Trilinearfrom dynamic_network_architectures.building_blocks.unet_decoder_upsample_nearest import UNetDecoder_Upsample_Nearest
from torch import nnfrom torch.nn.modules.conv import _ConvNdfrom torch.nn.modules.dropout import _DropoutNd
class PlainConvUNet(nn.Module): def __init__(self, input_channels: int, n_stages: int, features_per_stage: Union[int, List[int], Tuple[int, ...]], conv_op: Type[_ConvNd], kernel_sizes: Union[int, List[int], Tuple[int, ...]], strides: Union[int, List[int], Tuple[int, ...]], n_conv_per_stage: Union[int, List[int], Tuple[int, ...]], num_classes: int, n_conv_per_stage_decoder: Union[int, Tuple[int, ...], List[int]], conv_bias: bool = False, norm_op: Union[None, Type[nn.Module]] = None, norm_op_kwargs: dict = None, dropout_op: Union[None, Type[_DropoutNd]] = None, dropout_op_kwargs: dict = None, nonlin: Union[None, Type[torch.nn.Module]] = None, nonlin_kwargs: dict = None, deep_supervision: bool = False, nonlin_first: bool = False, decoder_type: str="standard" ): """ nonlin_first: if True you get conv -> nonlin -> norm. Else it's conv -> norm -> nonlin """ super().__init__() if isinstance(n_conv_per_stage, int): n_conv_per_stage = [n_conv_per_stage] * n_stages if isinstance(n_conv_per_stage_decoder, int): n_conv_per_stage_decoder = [n_conv_per_stage_decoder] * (n_stages - 1) assert len(n_conv_per_stage) == n_stages, "n_conv_per_stage must have as many entries as we have " \ f"resolution stages. here: {n_stages}. " \ f"n_conv_per_stage: {n_conv_per_stage}" assert len(n_conv_per_stage_decoder) == (n_stages - 1), "n_conv_per_stage_decoder must have one less entries " \ f"as we have resolution stages. here: {n_stages} " \ f"stages, so it should have {n_stages - 1} entries. " \ f"n_conv_per_stage_decoder: {n_conv_per_stage_decoder}" self.encoder = PlainConvEncoder(input_channels, n_stages, features_per_stage, conv_op, kernel_sizes, strides, n_conv_per_stage, conv_bias, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, nonlin, nonlin_kwargs, return_skips=True, nonlin_first=nonlin_first) if decoder_type == "standard": self.decoder = UNetDecoder(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision, nonlin_first=nonlin_first) elif decoder_type == "trilinear": self.decoder = UNetDecoder_Upsample_Trilinear(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision, nonlin_first=nonlin_first) elif decoder_type == "nearest": self.decoder = UNetDecoder_Upsample_Nearest(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision, nonlin_first=nonlin_first) else: raise ValueError(f"Unsupported decoder type: {decoder_type}. Choose from 'standard', 'trilinear', or 'nearest'.") def forward(self, x): skips = self.encoder(x) output = self.decoder(skips) # output = torch.tanh(output) # added tanh for translation. TODO: perform ablation study + add a parameter to control this return output def compute_conv_feature_map_size(self, input_size): assert len(input_size) == convert_conv_op_to_dim(self.encoder.conv_op), "just give the image size without color/feature channels or " \ "batch channel. Do not give input_size=(b, c, x, y(, z)). " \ "Give input_size=(x, y(, z))!" return self.encoder.compute_conv_feature_map_size(input_size) + self.decoder.compute_conv_feature_map_size(input_size)
@staticmethod def initialize(module): InitWeights_He(1e-2)(module)
class ResidualEncoderUNet(nn.Module): def __init__(self, input_channels: int, n_stages: int, features_per_stage: Union[int, List[int], Tuple[int, ...]], conv_op: Type[_ConvNd], kernel_sizes: Union[int, List[int], Tuple[int, ...]], strides: Union[int, List[int], Tuple[int, ...]], n_blocks_per_stage: Union[int, List[int], Tuple[int, ...]], num_classes: int, n_conv_per_stage_decoder: Union[int, Tuple[int, ...], List[int]], conv_bias: bool = False, norm_op: Union[None, Type[nn.Module]] = None, norm_op_kwargs: dict = None, dropout_op: Union[None, Type[_DropoutNd]] = None, dropout_op_kwargs: dict = None, nonlin: Union[None, Type[torch.nn.Module]] = None, nonlin_kwargs: dict = None, deep_supervision: bool = False, block: Union[Type[BasicBlockD], Type[BottleneckD]] = BasicBlockD, bottleneck_channels: Union[int, List[int], Tuple[int, ...]] = None, stem_channels: int = None ): super().__init__() if isinstance(n_blocks_per_stage, int): n_blocks_per_stage = [n_blocks_per_stage] * n_stages if isinstance(n_conv_per_stage_decoder, int): n_conv_per_stage_decoder = [n_conv_per_stage_decoder] * (n_stages - 1) assert len(n_blocks_per_stage) == n_stages, "n_blocks_per_stage must have as many entries as we have " \ f"resolution stages. here: {n_stages}. " \ f"n_blocks_per_stage: {n_blocks_per_stage}" assert len(n_conv_per_stage_decoder) == (n_stages - 1), "n_conv_per_stage_decoder must have one less entries " \ f"as we have resolution stages. here: {n_stages} " \ f"stages, so it should have {n_stages - 1} entries. " \ f"n_conv_per_stage_decoder: {n_conv_per_stage_decoder}" self.encoder = ResidualEncoder(input_channels, n_stages, features_per_stage, conv_op, kernel_sizes, strides, n_blocks_per_stage, conv_bias, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, nonlin, nonlin_kwargs, block, bottleneck_channels, return_skips=True, disable_default_stem=False, stem_channels=stem_channels) self.decoder = UNetDecoder(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision)
def forward(self, x): skips = self.encoder(x) return self.decoder(skips)
def compute_conv_feature_map_size(self, input_size): assert len(input_size) == convert_conv_op_to_dim(self.encoder.conv_op), "just give the image size without color/feature channels or " \ "batch channel. Do not give input_size=(b, c, x, y(, z)). " \ "Give input_size=(x, y(, z))!" return self.encoder.compute_conv_feature_map_size(input_size) + self.decoder.compute_conv_feature_map_size(input_size)
@staticmethod def initialize(module): InitWeights_He(1e-2)(module) init_last_bn_before_add_to_0(module)
class ResidualUNet(nn.Module): def __init__(self, input_channels: int, n_stages: int, features_per_stage: Union[int, List[int], Tuple[int, ...]], conv_op: Type[_ConvNd], kernel_sizes: Union[int, List[int], Tuple[int, ...]], strides: Union[int, List[int], Tuple[int, ...]], n_blocks_per_stage: Union[int, List[int], Tuple[int, ...]], num_classes: int, n_conv_per_stage_decoder: Union[int, Tuple[int, ...], List[int]], conv_bias: bool = False, norm_op: Union[None, Type[nn.Module]] = None, norm_op_kwargs: dict = None, dropout_op: Union[None, Type[_DropoutNd]] = None, dropout_op_kwargs: dict = None, nonlin: Union[None, Type[torch.nn.Module]] = None, nonlin_kwargs: dict = None, deep_supervision: bool = False, block: Union[Type[BasicBlockD], Type[BottleneckD]] = BasicBlockD, bottleneck_channels: Union[int, List[int], Tuple[int, ...]] = None, stem_channels: int = None ): super().__init__() if isinstance(n_blocks_per_stage, int): n_blocks_per_stage = [n_blocks_per_stage] * n_stages if isinstance(n_conv_per_stage_decoder, int): n_conv_per_stage_decoder = [n_conv_per_stage_decoder] * (n_stages - 1) assert len(n_blocks_per_stage) == n_stages, "n_blocks_per_stage must have as many entries as we have " \ f"resolution stages. here: {n_stages}. " \ f"n_blocks_per_stage: {n_blocks_per_stage}" assert len(n_conv_per_stage_decoder) == (n_stages - 1), "n_conv_per_stage_decoder must have one less entries " \ f"as we have resolution stages. here: {n_stages} " \ f"stages, so it should have {n_stages - 1} entries. " \ f"n_conv_per_stage_decoder: {n_conv_per_stage_decoder}" self.encoder = ResidualEncoder(input_channels, n_stages, features_per_stage, conv_op, kernel_sizes, strides, n_blocks_per_stage, conv_bias, norm_op, norm_op_kwargs, dropout_op, dropout_op_kwargs, nonlin, nonlin_kwargs, block, bottleneck_channels, return_skips=True, disable_default_stem=False, stem_channels=stem_channels) self.decoder = UNetResDecoder(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision)
def forward(self, x): skips = self.encoder(x) return self.decoder(skips)
def compute_conv_feature_map_size(self, input_size): assert len(input_size) == convert_conv_op_to_dim(self.encoder.conv_op), "just give the image size without color/feature channels or " \ "batch channel. Do not give input_size=(b, c, x, y(, z)). " \ "Give input_size=(x, y(, z))!" return self.encoder.compute_conv_feature_map_size(input_size) + self.decoder.compute_conv_feature_map_size(input_size)
@staticmethod def initialize(module): InitWeights_He(1e-2)(module) init_last_bn_before_add_to_0(module)
if __name__ == '__main__': data = torch.rand((1, 4, 128, 128, 128))
model = PlainConvUNet(4, 6, (32, 64, 125, 256, 320, 320), nn.Conv3d, 3, (1, 2, 2, 2, 2, 2), (2, 2, 2, 2, 2, 2), 4, (2, 2, 2, 2, 2), False, nn.BatchNorm3d, None, None, None, nn.ReLU, deep_supervision=True)
if False: import hiddenlayer as hl
g = hl.build_graph(model, data, transforms=None) g.save("network_architecture.pdf") del g
print(model.compute_conv_feature_map_size(data.shape[2:]))
data = torch.rand((1, 4, 512, 512))
model = PlainConvUNet(4, 8, (32, 64, 125, 256, 512, 512, 512, 512), nn.Conv2d, 3, (1, 2, 2, 2, 2, 2, 2, 2), (2, 2, 2, 2, 2, 2, 2, 2), 4, (2, 2, 2, 2, 2, 2, 2), False, nn.BatchNorm2d, None, None, None, nn.ReLU, deep_supervision=True)
if False: import hiddenlayer as hl
g = hl.build_graph(model, data, transforms=None) g.save("network_architecture.pdf") del g
print(model.compute_conv_feature_map_size(data.shape[2:]))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import torchfrom torch import nn
from dynamic_network_architectures.building_blocks.plain_conv_encoder import PlainConvEncoderfrom dynamic_network_architectures.building_blocks.helper import get_matching_pool_op, get_default_network_config
_VGG_CONFIGS = { '16': {'features_per_stage': (64, 128, 256, 512, 512, 512), 'n_conv_per_stage': (2, 2, 2, 3, 3, 3), 'strides': (1, 2, 2, 2, 2, 2)}, '19': {'features_per_stage': (64, 128, 256, 512, 512, 512), 'n_conv_per_stage': (2, 2, 3, 3, 4, 4), 'strides': (1, 2, 2, 2, 2, 2)}, '16_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_conv_per_stage': (2, 3, 5, 5), 'strides': (1, 2, 2, 2)}, '19_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_conv_per_stage': (3, 4, 5, 6), 'strides': (1, 2, 2, 2)},}
_VGG_OPS = { 1: {'conv_op': nn.Conv1d, 'norm_op': nn.BatchNorm1d}, 2: {'conv_op': nn.Conv2d, 'norm_op': nn.BatchNorm2d}, 3: {'conv_op': nn.Conv3d, 'norm_op': nn.BatchNorm3d},}
class VGG(nn.Module): def __init__(self, n_classes: int, n_input_channel: int = 3, config='16', input_dimension=2): """ This is not 1:1 VGG because it does not have the bloated fully connected layers at the end. Since these were counted towards the XX layers as well, we increase the number of convolutional layers so that we have the desired number of conv layers in total
We also use batchnorm """ super().__init__() cfg = _VGG_CONFIGS[config] ops = get_default_network_config(dimension=input_dimension) self.encoder = PlainConvEncoder( n_input_channel, n_stages=len(cfg['features_per_stage']), features_per_stage=cfg['features_per_stage'], conv_op=ops['conv_op'], kernel_sizes=3, strides=cfg['strides'], n_conv_per_stage=cfg['n_conv_per_stage'], conv_bias=False, norm_op=ops['norm_op'], norm_op_kwargs=None, dropout_op=None, dropout_op_kwargs=None, nonlin=nn.ReLU, nonlin_kwargs={'inplace': True}, return_skips=False ) self.gap = get_matching_pool_op(conv_op=ops['conv_op'], adaptive=True, pool_type='avg')(1) self.classifier = nn.Linear(cfg['features_per_stage'][-1], n_classes, True)
def forward(self, x): x = self.encoder(x) x = self.gap(x).squeeze() return self.classifier(x)
def compute_conv_feature_map_size(self, input_size): return self.encoder.compute_conv_feature_map_size(input_size)
class VGG16(VGG): def __init__(self, n_classes: int, n_input_channel: int = 3, input_dimension: int = 2): super().__init__(n_classes, n_input_channel, config='16', input_dimension=input_dimension)
class VGG19(VGG): def __init__(self, n_classes: int, n_input_channel: int = 3, input_dimension: int = 2): super().__init__(n_classes, n_input_channel, config='19', input_dimension=input_dimension)
class VGG16_cifar(VGG): def __init__(self, n_classes: int, n_input_channel: int = 3, input_dimension: int = 2): super().__init__(n_classes, n_input_channel, config='16_cifar', input_dimension=input_dimension)
class VGG19_cifar(VGG): def __init__(self, n_classes: int, n_input_channel: int = 3, input_dimension: int = 2): super().__init__(n_classes, n_input_channel, config='19_cifar', input_dimension=input_dimension)
if __name__ == '__main__': data = torch.rand((1, 3, 32, 32))
model = VGG19_cifar(10, 3) import hiddenlayer as hl
g = hl.build_graph(model, data, transforms=None) g.save("network_architecture.pdf") del g
print(model.compute_conv_feature_map_size((32, 32))).gitattributes+10
README.md-3
docker_task_1/.envAdded+2
docker_task_1/260_gt_nnUNetResEncUNetLPlans.jsonAdded+521
docker_task_1/262_gt_nnUNetResEncUNetLPlans.jsonAdded+356
docker_task_1/264_gt_nnUNetResEncUNetLPlans.jsonAdded+521
docker_task_1/DockerfileAdded+43
docker_task_1/__pycache__/base_algorithm.cpython-312.pycAdded
docker_task_1/__pycache__/revert_normalisation.cpython-312.pycAdded
docker_task_1/base_algorithm.pyAdded+205
docker_task_1/build.shAdded+4
docker_task_1/dynamic-network-architectures/.gitignoreAdded+113
docker_task_1/dynamic-network-architectures/LICENCEAdded+201
docker_task_1/dynamic-network-architectures/README.mdAdded+14
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/PKG-INFOAdded+16
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/SOURCES.txtAdded+27
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/dependency_links.txtAdded+1
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/not-zip-safeAdded+1
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/requires.txtAdded+2
docker_task_1/dynamic-network-architectures/dynamic_network_architectures.egg-info/top_level.txtAdded+1
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__init__.pyAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__pycache__/__init__.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/__pycache__/__init__.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__init__.pyAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/__init__.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/__init__.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/unet.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/__pycache__/unet.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/resnet.pyAdded+236
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/unet.pyAdded+232
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/architectures/vgg.pyAdded+85
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__init__.pyAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/__init__.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/__init__.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/helper.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/helper.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/plain_conv_encoder.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/plain_conv_encoder.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/regularization.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/regularization.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual_encoders.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/residual_encoders.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/simple_conv_blocks.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/simple_conv_blocks.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder.cpython-312.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder_upsample_nearest.cpython-310.pycAdded
docker_task_1/dynamic-network-architectures/dynamic_network_architectures/building_blocks/__pycache__/unet_decoder_upsample_nearest.cpython-312.pycAdded