-
Notifications
You must be signed in to change notification settings - Fork 739
677 Add hybrid programming example for bundle #678
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
0021a57
[DLMED] add hybrid placeholders
Nic-Ma 3d49380
[DLMED] update doc
Nic-Ma 7a9d0cb
[DLMED] add scripts
Nic-Ma e61ab67
[DLMED] split to 2 examples
Nic-Ma 2abba43
[DLMED] rename to bundle
Nic-Ma 644fa73
[DLMED] update hybrid programming
Nic-Ma f7261b4
[DLMED] update bundles to bundle
Nic-Ma e2a0e46
[DLMED] add README
Nic-Ma c093aac
[DLMED] update according to comments
Nic-Ma da3d3f2
[DLMED] fix format
Nic-Ma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# MONAI bundle | ||
This folder contains the get_started tutorial and concrete training / inference examples for MONAI bundle features. | ||
|
||
### [spleen segmentation](./spleen_segmentation) | ||
A bundle example for volumetric (3D) segmentation of the spleen from CT image. | ||
### [customize component](./custom_component) | ||
Example shows the use cases of bringing customized python components, such as transform, network, and metrics, in a configuration-based workflow. | ||
### [hybrid programming](./hybrid_programming) | ||
Example shows how to parse the config files in your own python program, instantiate necessary components with python program and execute the inference. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# Description | ||
This example mainly shows a typical use case that brings customized python components (such as transform, network, metrics) in a configuration-based workflow. | ||
|
||
Please note that this example depends on the `spleen_segmentation` bundle example and executes via overriding the config file of it. | ||
|
||
## commands example | ||
To run the workflow with customized components, `PYTHONPATH` should be revised to include the path to the customized component: | ||
``` | ||
export PYTHONPATH=$PYTHONPATH:"<path to 'custom_component/scripts'>" | ||
``` | ||
And please make sure the folder `custom_component/scripts` is a valid python module (it has a `__init__.py` file in the folder). | ||
|
||
Override the `train` config with the customized `transform` and execute training: | ||
``` | ||
python -m monai.bundle run training --meta_file <spleen_configs_path>/metadata.json --config_file "['<spleen_configs_path>/train.json','configs/custom_train.json']" --logging_file <spleen_configs_path>/logging.conf | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"train#preprocessing#transforms#6": | ||
{ | ||
"_target_": "scripts.custom_transforms.PrintEnsureTyped", | ||
"keys": ["image", "label"] | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Copyright (c) MONAI Consortium | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. |
32 changes: 32 additions & 0 deletions
32
modules/bundle/custom_component/scripts/custom_transforms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# Copyright (c) MONAI Consortium | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from monai.config import KeysCollection | ||
from monai.transforms import EnsureTyped | ||
|
||
|
||
class PrintEnsureTyped(EnsureTyped): | ||
""" | ||
Extend the `EnsureTyped` transform to print the image shape. | ||
|
||
Args: | ||
keys: keys of the corresponding items to be transformed. | ||
|
||
""" | ||
|
||
def __init__(self, keys: KeysCollection, data_type: str = "tensor") -> None: | ||
super().__init__(keys, data_type=data_type) | ||
|
||
def __call__(self, data): | ||
d = dict(super().__call__(data=data)) | ||
for key in self.key_iterator(d): | ||
print(f"data shape of {key}: {d[key].shape}") | ||
return d |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Description | ||
This example mainly shows a typical use case that parses the config files in your own python program, instantiates necessary components with python program and executes the inference. | ||
|
||
## commands example | ||
|
||
Parse the config files in the python program and execute inference from the python program: | ||
|
||
``` | ||
python -m scripts.inference run --config_file "['configs/data_loading.json','configs/net_inferer.json','configs/post_processing.json']" --ckpt_path <path_to_checkpoint> | ||
``` |
52 changes: 52 additions & 0 deletions
52
modules/bundle/hybrid_programming/configs/data_loading.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
{ | ||
"image_key": "image", | ||
"preprocessing": { | ||
"_target_": "Compose", | ||
"transforms": [ | ||
{ | ||
"_target_": "LoadImaged", | ||
"keys": "@image_key" | ||
}, | ||
{ | ||
"_target_": "EnsureChannelFirstd", | ||
"keys": "@image_key" | ||
}, | ||
{ | ||
"_target_": "Orientationd", | ||
"keys": "@image_key", | ||
"axcodes": "RAS" | ||
}, | ||
{ | ||
"_target_": "Spacingd", | ||
"keys": "@image_key", | ||
"pixdim": [1.5, 1.5, 2.0], | ||
"mode": "bilinear" | ||
}, | ||
{ | ||
"_target_": "ScaleIntensityRanged", | ||
"keys": "@image_key", | ||
"a_min": -57, | ||
"a_max": 164, | ||
"b_min": 0, | ||
"b_max": 1, | ||
"clip": true | ||
}, | ||
{ | ||
"_target_": "EnsureTyped", | ||
"keys": "@image_key" | ||
} | ||
] | ||
}, | ||
"dataset": { | ||
"_target_": "Dataset", | ||
"data": "@input_data", | ||
"transform": "@preprocessing" | ||
}, | ||
"dataloader": { | ||
"_target_": "DataLoader", | ||
"dataset": "@dataset", | ||
"batch_size": 1, | ||
"shuffle": false, | ||
"num_workers": 4 | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
modules/bundle/hybrid_programming/configs/net_inferer.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
{ | ||
"network": { | ||
"_target_": "UNet", | ||
"spatial_dims": 3, | ||
"in_channels": 1, | ||
"out_channels": 2, | ||
"channels": [16, 32, 64, 128, 256], | ||
"strides": [2, 2, 2, 2], | ||
"num_res_units": 2, | ||
"norm": "batch" | ||
}, | ||
"inferer": { | ||
"_target_": "SlidingWindowInferer", | ||
"roi_size": [96, 96, 96], | ||
"sw_batch_size": 4, | ||
"overlap": 0.5 | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
modules/bundle/hybrid_programming/configs/post_processing.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
{ | ||
"pred_key": "pred", | ||
"postprocessing": { | ||
"_target_": "Compose", | ||
"transforms": [ | ||
{ | ||
"_target_": "Activationsd", | ||
"keys": "@pred_key", | ||
"softmax": true | ||
}, | ||
{ | ||
"_target_": "Invertd", | ||
"keys": "@pred_key", | ||
"transform": "@preprocessing", | ||
"orig_keys": "@image_key", | ||
"meta_key_postfix": "meta_dict", | ||
"nearest_interp": false, | ||
"to_tensor": true | ||
}, | ||
{ | ||
"_target_": "AsDiscreted", | ||
"keys": "@pred_key", | ||
"argmax": true | ||
}, | ||
{ | ||
"_target_": "SaveImaged", | ||
"keys": "@pred_key", | ||
"meta_keys": "pred_meta_dict", | ||
"output_dir": "@output_dir" | ||
} | ||
] | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Copyright (c) MONAI Consortium | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# Copyright (c) MONAI Consortium | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from typing import Sequence, Union | ||
import glob | ||
|
||
import torch | ||
from monai.bundle import ConfigParser | ||
from monai.data import decollate_batch | ||
|
||
|
||
def run(config_file: Union[str, Sequence[str]], ckpt_path: str): | ||
parser = ConfigParser() | ||
parser.read_config(config_file) | ||
# edit the config content at runtime for input / output information and lazy instantiation | ||
datalist = list(sorted(glob.glob("/workspace/data/Task09_Spleen/imagesTs/*.nii.gz"))) | ||
input_data = [{f"{parser['image_key']}": i} for i in datalist] | ||
output_dir = "/workspace/data/tutorials/modules/bundle/hybrid_programming/eval" | ||
parser["input_data"] = input_data | ||
parser["output_dir"] = output_dir | ||
parser["inferer"]["roi_size"] = [160, 160, 160] | ||
|
||
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") | ||
# instantialize the components | ||
model = parser.get_parsed_content("network").to(device) | ||
model.load_state_dict(torch.load(ckpt_path)) | ||
|
||
dataloader = parser.get_parsed_content("dataloader") | ||
if len(dataloader) == 0: | ||
raise ValueError("no data found in the dataloader, please ensure the input image paths are accessable.") | ||
inferer = parser.get_parsed_content("inferer") | ||
postprocessing = parser.get_parsed_content("postprocessing") | ||
|
||
model.eval() | ||
with torch.no_grad(): | ||
for d in dataloader: | ||
images = d[parser["image_key"]].to(device) | ||
# define sliding window size and batch size for windows inference | ||
d[parser["pred_key"]] = inferer(inputs=images, network=model) | ||
# decollate the batch data into a list of dictionaries, then execute postprocessing transforms | ||
[postprocessing(i) for i in decollate_batch(d)] | ||
|
||
|
||
if __name__ == "__main__": | ||
from monai.utils import optional_import | ||
|
||
fire, _ = optional_import("fire") | ||
fire.Fire() |
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.