From 1c05003b065f9553bd5bca5dd348d034d3790417 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 15:05:14 +0000 Subject: [PATCH 01/18] Add LICENSE Signed-off-by: Walter Hugo Lopez Pinaya --- .../LICENSE | 201 ++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE diff --git a/model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE b/model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + + 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 b3e355718e390a5a262c89924ddd630cac71258d Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 15:14:38 +0000 Subject: [PATCH 02/18] Rename dir and add logging.conf (#188) Signed-off-by: Walter Hugo Lopez Pinaya --- .../LICENSE | 0 .../configs/logging.conf | 21 +++++++++++++++++++ 2 files changed, 21 insertions(+) rename model-zoo/models/{brain_latent_diffusion_model_ukbiobank => brain_latent_diffusion_model}/LICENSE (100%) create mode 100644 model-zoo/models/brain_latent_diffusion_model/configs/logging.conf diff --git a/model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE b/model-zoo/models/brain_latent_diffusion_model/LICENSE similarity index 100% rename from model-zoo/models/brain_latent_diffusion_model_ukbiobank/LICENSE rename to model-zoo/models/brain_latent_diffusion_model/LICENSE diff --git a/model-zoo/models/brain_latent_diffusion_model/configs/logging.conf b/model-zoo/models/brain_latent_diffusion_model/configs/logging.conf new file mode 100644 index 00000000..91c1a21c --- /dev/null +++ b/model-zoo/models/brain_latent_diffusion_model/configs/logging.conf @@ -0,0 +1,21 @@ +[loggers] +keys=root + +[handlers] +keys=consoleHandler + +[formatters] +keys=fullFormatter + +[logger_root] +level=INFO +handlers=consoleHandler + +[handler_consoleHandler] +class=StreamHandler +level=INFO +formatter=fullFormatter +args=(sys.stdout,) + +[formatter_fullFormatter] +format=%(asctime)s - %(name)s - %(levelname)s - %(message)s From 5a44f071be1b1e566ea5f936a33cf3ad43769286 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 19:58:49 +0000 Subject: [PATCH 03/18] [WIP] Add README.md (#188) Signed-off-by: Walter Hugo Lopez Pinaya --- .../LICENSE | 0 .../configs/logging.conf | 0 .../docs/README.md | 65 +++++++++++++++++++ 3 files changed, 65 insertions(+) rename model-zoo/models/{brain_latent_diffusion_model => brain_image_synthesis_latent_diffusion_model}/LICENSE (100%) rename model-zoo/models/{brain_latent_diffusion_model => brain_image_synthesis_latent_diffusion_model}/configs/logging.conf (100%) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md diff --git a/model-zoo/models/brain_latent_diffusion_model/LICENSE b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/LICENSE similarity index 100% rename from model-zoo/models/brain_latent_diffusion_model/LICENSE rename to model-zoo/models/brain_image_synthesis_latent_diffusion_model/LICENSE diff --git a/model-zoo/models/brain_latent_diffusion_model/configs/logging.conf b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/logging.conf similarity index 100% rename from model-zoo/models/brain_latent_diffusion_model/configs/logging.conf rename to model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/logging.conf diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md new file mode 100644 index 00000000..6972c893 --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md @@ -0,0 +1,65 @@ +# Brain Imaging Generation with Latent Diffusion Models + +### **Authors** + +Walter H. L. Pinaya, Petru-Daniel Tudosiu, Jessica Dafflon, Pedro F Da Costa, Virginia Fernandez, Parashkev Nachev, +Sebastien Ourselin, and M. Jorge Cardoso + +### **Tags** +Synthetic data, Latent Diffusion Model, Generative model, Brain Imaging + +## **Model Description** +This model is trained using the Latent Diffusion Model architecture [1] and is used for the synthesis of conditioned 3D +brain MRI data. The model is divided into two parts: a autoencoder with KL-regularisation model that compresses data +into a latent space, and a diffusion model that learns the to generated conditioned synthetic latent representations. This +model is conditioned on age, sex, the volume of ventricular cerebrospinal fluid, and brain volume normalised for head size. + +## **Data** +The model was trained on brain data from 31,740 participants from the UK Biobank [2]. We used high-resolution 3D T1w MRI with voxel size of 1mm3, resulting in volumes with 160 x 224 x 160 voxels + +#### **Preprocessing** +For the image pre-processing, we used UniRes [3] to perform a rigid body registration to a common MNI space. The voxel intensity was normalised to be between [0, 1]. + +## **Performance** +This model achieves the following results on UK Biobank: a FID of 0.0076, a MS-SSIM of 0.6555, and a 4-G-R-SSIM of 0.3883. + +For more details regarding evaluation results, we refer to table 1 of the original paper. + + +## **Additinal Usage Steps** (Optional) +*If your bundle requires steps outside the normal flow of usage, describe those here in bash style commands.* + +Example: + +My first special instruction for training: +``` +$ python -m monai.bundle +``` +My special instruction for inference 2: +``` +$ python -m monai.bundle +``` + + +## **Citation Info** + +``` +@inproceedings{pinaya2022brain, + title={Brain imaging generation with latent diffusion models}, + author={Pinaya, Walter HL and Tudosiu, Petru-Daniel and Dafflon, Jessica and Da Costa, Pedro F and Fernandez, Virginia and Nachev, Parashkev and Ourselin, Sebastien and Cardoso, M Jorge}, + booktitle={MICCAI Workshop on Deep Generative Models}, + pages={117--126}, + year={2022}, + organization={Springer} +} +``` + +## **References** (Optional) + +Example: + +[1] Pinaya, Walter HL, et al. "Brain imaging generation with latent diffusion models." MICCAI Workshop on Deep Generative Models. Springer, Cham, 2022. + +[2] Sudlow, Cathie, et al. "UK biobank: an open access resource for identifying the causes of a wide range of complex diseases of middle and old age." PLoS medicine 12.3 (2015): e1001779. + +[3] Brudfors, Mikael, et al. "MRI super-resolution using multi-channel total variation." Annual Conference on Medical Image Understanding and Analysis. Springer, Cham, 2018. From 04eb652ff5e5696c814848cd6ffe6f44299ff20f Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 20:26:32 +0000 Subject: [PATCH 04/18] Add metadata.json (#188) Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/metadata.json | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json new file mode 100644 index 00000000..6f786fdc --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json @@ -0,0 +1,71 @@ +{ + "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20220324.json", + "version": "1.0.0", + "changelog": { + "1.0.8": "Initial release" + }, + "monai_version": "1.1.0", + "pytorch_version": "1.13.0", + "numpy_version": "1.22.4", + "optional_packages_version": { + "nibabel": "4.0.1" + }, + "task": "Brain image synthesis", + "description": "A generative model for creating high-resolution 3D brain MRI based on UK Biobank", + "authors": "Walter H. L. Pinaya, Petru-Daniel Tudosiu, Jessica Dafflon, Pedro F Da Costa, Virginia Fernandez, Parashkev Nachev, Sebastien Ourselin, and M. Jorge Cardoso", + "copyright": "Copyright (c) MONAI Consortium", + "data_source": "https://www.ukbiobank.ac.uk/", + "data_type": "nibabel", + "image_classes": "T1w head MRI with 1x1x1 mm voxel size", + "eval_metrics": { + "fid": 0.0076, + "msssim": 0.6555, + "4gmsssim": 0.3883 + }, + "intended_use": "This is an example, not to be used for diagnostic purposes", + "references": [ + "Pinaya, Walter HL, et al. \"Brain imaging generation with latent diffusion models.\" MICCAI Workshop on Deep Generative Models. Springer, Cham, 2022." + ], + "network_data_format": { + "inputs": { + "image": { + "type": "tabular", + "num_channels": 1, + "dtype": "float32", + "value_range": [ + 0, + 1 + ], + "is_patch_data": false, + "channel_def": { + "0": "Gender", + "1": "Age", + "2": "Ventricular volume", + "3": "Brain volume" + } + } + }, + "outputs": { + "pred": { + "type": "image", + "format": "magnitude", + "modality": "MR", + "num_channels": 3, + "spatial_shape": [ + "160", + "224", + "160" + ], + "dtype": "float32", + "value_range": [ + 0, + 1 + ], + "is_patch_data": false, + "channel_def": { + "0": "T1w" + } + } + } + } +} From 2553b5d64a4b9720c1fe0e9520811217203863b4 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 20:36:29 +0000 Subject: [PATCH 05/18] Add large_files.yml (#188) Signed-off-by: Walter Hugo Lopez Pinaya --- .../large_files.yml | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml new file mode 100644 index 00000000..e42c7bee --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml @@ -0,0 +1,9 @@ +large_files: + - path: "models/autoencoder.pth" + url: "https://drive.google.com/uc?export=download&id=1iFWJGT-e0ki72nf6lr_BEZfjXvCu7LX4" + hash_val: "" + hash_type: "" + - path: "models/diffusion_model.pth" + url: "https://drive.google.com/uc?export=download&id=17KR_YImtHiWXTu8pNVXO_v4gOntMVBTi" + hash_val: "" + hash_type: "" From 5afd9b2fb6cc4af5b9acf29a6aee6880d394d14e Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Sat, 14 Jan 2023 21:15:41 +0000 Subject: [PATCH 06/18] [WIP] Add inference.json (#188) Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json new file mode 100644 index 00000000..8e572501 --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -0,0 +1,78 @@ +{ + "imports": [ + "$import glob", + "$import os" + ], + "bundle_root": ".", + "output_dir": "$@bundle_root + '/samples'", + "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", + "autoencoder_def": { + "_target_": "generative.networks.nets.AutoencoderKL", + "spatial_dims": 3, + "in_channels": 1, + "out_channels": 1, + "num_channels": 64, + "latent_channels": 3, + "ch_mult": [ + 1, + 2, + 2, + 2 + ], + "num_res_blocks": 2, + "norm_num_groups": 32, + "norm_eps": 1e-06, + "attention_levels": [ + false, + false, + false, + false + ], + "with_encoder_nonlocal_attn": false, + "with_decoder_nonlocal_attn": false + }, + "autoencoder": "$@network_def.to(@device)", + "diffusion_def": { + "_target_": "generative.networks.nets.DiffusionModelUNet", + "spatial_dims": 3, + "in_channels": 7, + "out_channels": 3, + "num_channels": [ + 256, + 512, + 768 + ], + "num_res_blocks": 2, + "attention_levels": [ + false, + true, + true + ], + "norm_num_groups": 32, + "norm_eps": 1e-06, + "resblock_updown": true, + "num_head_channels": [ + 0, + 512, + 768 + ], + "with_conditioning": true, + "transformer_num_layers": 1, + "cross_attention_dim": 4 + }, + "diffusion": "$@diffusion_def.to(@device)", + "evaluator": { + "_target_": "SupervisedEvaluator", + "device": "@device", + "val_data_loader": "@dataloader", + "network": "@network", + "inferer": "@inferer", + "postprocessing": "@postprocessing", + "val_handlers": "@handlers", + "amp": false + }, + "evaluating": [ + "$setattr(torch.backends.cudnn, 'benchmark', True)", + "$@evaluator.run()" + ] +} From 996c31a586dc990164755adbc67fc7fc7b8cbd16 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Tue, 14 Feb 2023 12:07:09 +0000 Subject: [PATCH 07/18] Update model link Signed-off-by: Walter Hugo Lopez Pinaya --- .../large_files.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml index e42c7bee..2083c0d8 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/large_files.yml @@ -1,9 +1,9 @@ large_files: - path: "models/autoencoder.pth" - url: "https://drive.google.com/uc?export=download&id=1iFWJGT-e0ki72nf6lr_BEZfjXvCu7LX4" + url: "https://drive.google.com/uc?export=download&id=1CZHwxHJWybOsDavipD0EorDPOo_mzNeX" hash_val: "" hash_type: "" - path: "models/diffusion_model.pth" - url: "https://drive.google.com/uc?export=download&id=17KR_YImtHiWXTu8pNVXO_v4gOntMVBTi" + url: "https://drive.google.com/uc?export=download&id=1XO-ak93ZuOcGTCpgRtqgIeZq3dG5ExN6" hash_val: "" hash_type: "" From 49ae22a623e604e766ec17b80e0851fad366018d Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Tue, 14 Feb 2023 14:18:44 +0000 Subject: [PATCH 08/18] [WIP] Add inference.json code Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 8e572501..a4222f24 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -11,13 +11,12 @@ "spatial_dims": 3, "in_channels": 1, "out_channels": 1, - "num_channels": 64, "latent_channels": 3, - "ch_mult": [ - 1, - 2, - 2, - 2 + "num_channels": [ + 64, + 128, + 128, + 128 ], "num_res_blocks": 2, "norm_num_groups": 32, @@ -31,7 +30,7 @@ "with_encoder_nonlocal_attn": false, "with_decoder_nonlocal_attn": false }, - "autoencoder": "$@network_def.to(@device)", + "autoencoder": "$@autoencoder_def.to(@device)", "diffusion_def": { "_target_": "generative.networks.nets.DiffusionModelUNet", "spatial_dims": 3, @@ -61,18 +60,17 @@ "cross_attention_dim": 4 }, "diffusion": "$@diffusion_def.to(@device)", - "evaluator": { - "_target_": "SupervisedEvaluator", - "device": "@device", - "val_data_loader": "@dataloader", - "network": "@network", - "inferer": "@inferer", - "postprocessing": "@postprocessing", - "val_handlers": "@handlers", - "amp": false + "scheduler": { + "_target_": "generative.networks.schedulers.DDIMScheduler", + "beta_start": 0.0001, + "beta_end": 0.02, + "beta_schedule": "scaled_linear" + }, + "inferer": { + "_target_": "generative.inferers.LatentDiffusionInferer", + "scheduler": "$@scheduler" }, "evaluating": [ - "$setattr(torch.backends.cudnn, 'benchmark', True)", - "$@evaluator.run()" + "$@inferer.sample()" ] } From 191da3aecb8a0ec886b112ce110adc8bca8a6904 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Tue, 14 Feb 2023 14:24:33 +0000 Subject: [PATCH 09/18] [WIP] Add inference.json code Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index a4222f24..facc628b 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -1,7 +1,8 @@ { "imports": [ "$import glob", - "$import os" + "$import os", + "$import torch" ], "bundle_root": ".", "output_dir": "$@bundle_root + '/samples'", @@ -70,7 +71,9 @@ "_target_": "generative.inferers.LatentDiffusionInferer", "scheduler": "$@scheduler" }, + "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", + "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=1000)", "evaluating": [ - "$@inferer.sample()" + "$@inferer.sample(input_noise=@noise, autoencoder_model=@autoencoder, diffusion_model=@diffusion, scheduler=@scheduler)" ] } From be3f8966a7f26f81709889c237c99e53edacc417 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Tue, 14 Feb 2023 21:49:19 +0000 Subject: [PATCH 10/18] [WIP] Add inference.json code Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index facc628b..36386566 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -71,9 +71,9 @@ "_target_": "generative.inferers.LatentDiffusionInferer", "scheduler": "$@scheduler" }, - "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", - "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=1000)", - "evaluating": [ - "$@inferer.sample(input_noise=@noise, autoencoder_model=@autoencoder, diffusion_model=@diffusion, scheduler=@scheduler)" + "noise": "$torch.randn((1, 7, 20, 28, 20)).to(@device)", + "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=50)", + "sampling": [ + "$@inferer.sample(input_noise=@noise, autoencoder_model=@autoencoder, diffusion_model=@diffusion, scheduler=@scheduler, conditioning=torch.rand((1, 1, 4)).to(@device))" ] } From 6b0522733d3d588b742b0ba69c2c818c8ea860db Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Fri, 17 Feb 2023 21:51:47 +0000 Subject: [PATCH 11/18] Add sampler Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 9 ++-- .../scripts/__init__.py | 0 .../scripts/sampler.py | 42 +++++++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/__init__.py create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 36386566..3aa31aeb 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -71,9 +71,10 @@ "_target_": "generative.inferers.LatentDiffusionInferer", "scheduler": "$@scheduler" }, - "noise": "$torch.randn((1, 7, 20, 28, 20)).to(@device)", + "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=50)", - "sampling": [ - "$@inferer.sample(input_noise=@noise, autoencoder_model=@autoencoder, diffusion_model=@diffusion, scheduler=@scheduler, conditioning=torch.rand((1, 1, 4)).to(@device))" - ] + "sampler": { + "_target_": "scripts.sampler.Sampler" + }, + "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler)" } diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/__init__.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py new file mode 100644 index 00000000..117c5639 --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py @@ -0,0 +1,42 @@ +import torch +from torch.cuda.amp import autocast +from monai.utils import optional_import + +tqdm, has_tqdm = optional_import("tqdm", name="tqdm") + +class Sampler(): + def __init__(self) -> None: + super().__init__() + + @torch.no_grad() + def sampling_fn( + self, + input_noise, + autoencoder_model, + diffusion_model, + scheduler, + ): + if has_tqdm: + progress_bar = tqdm(scheduler.timesteps) + else: + progress_bar = iter(scheduler.timesteps) + + image = input_noise + conditioning = torch.tensor([[1.0, 0.5, 0.1, 0.5]]).to("cuda").unsqueeze(1) + cond_concat = conditioning.squeeze(1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) + cond_concat = cond_concat.expand(list(cond_concat.shape[0:2]) + list(input_noise.shape[2:])) + for t in progress_bar: + with torch.no_grad(): + with autocast(): + model_output = diffusion_model( + torch.cat((image, cond_concat), dim=1), + timesteps=torch.Tensor((t,)).to(input_noise.device).long(), + context=conditioning + ) + image, _ = scheduler.step(model_output, t, image) + + with torch.no_grad(): + with autocast(): + sample = autoencoder_model.decode_stage_2_outputs(image) + + return sample From a73ba3932b0f6266aeed33043c03ca1f80b1ce6d Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Fri, 17 Feb 2023 21:53:29 +0000 Subject: [PATCH 12/18] Reformat Signed-off-by: Walter Hugo Lopez Pinaya --- .../scripts/sampler.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py index 117c5639..20d143c3 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py @@ -1,21 +1,18 @@ +from __future__ import annotations + import torch -from torch.cuda.amp import autocast from monai.utils import optional_import +from torch.cuda.amp import autocast tqdm, has_tqdm = optional_import("tqdm", name="tqdm") -class Sampler(): + +class Sampler: def __init__(self) -> None: super().__init__() @torch.no_grad() - def sampling_fn( - self, - input_noise, - autoencoder_model, - diffusion_model, - scheduler, - ): + def sampling_fn(self, input_noise, autoencoder_model, diffusion_model, scheduler): if has_tqdm: progress_bar = tqdm(scheduler.timesteps) else: @@ -31,7 +28,7 @@ def sampling_fn( model_output = diffusion_model( torch.cat((image, cond_concat), dim=1), timesteps=torch.Tensor((t,)).to(input_noise.device).long(), - context=conditioning + context=conditioning, ) image, _ = scheduler.step(model_output, t, image) From 924bb6b71b99b269f1e06951a4898f3a23aeb4ce Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Fri, 17 Feb 2023 22:29:14 +0000 Subject: [PATCH 13/18] [WIP] Fix metadata.json Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/metadata.json | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json index 6f786fdc..f6ce2973 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json @@ -8,7 +8,8 @@ "pytorch_version": "1.13.0", "numpy_version": "1.22.4", "optional_packages_version": { - "nibabel": "4.0.1" + "nibabel": "4.0.1", + "generative": "0.1.0" }, "task": "Brain image synthesis", "description": "A generative model for creating high-resolution 3D brain MRI based on UK Biobank", @@ -50,11 +51,11 @@ "type": "image", "format": "magnitude", "modality": "MR", - "num_channels": 3, + "num_channels": 1, "spatial_shape": [ - "160", - "224", - "160" + 160, + 224, + 160 ], "dtype": "float32", "value_range": [ From 6a2d2d6e4231991de2f430f30bed2863be5fa976 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Mon, 27 Feb 2023 10:24:50 +0000 Subject: [PATCH 14/18] [WIP] Fix inference.json Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 20 ++++++++++--------- .../scripts/sampler.py | 2 +- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 3aa31aeb..3f4dadaf 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -5,7 +5,8 @@ "$import torch" ], "bundle_root": ".", - "output_dir": "$@bundle_root + '/samples'", + "model_dir": "$@bundle_root + '/models'", + "output_dir": "$@bundle_root + '/output'", "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", "autoencoder_def": { "_target_": "generative.networks.nets.AutoencoderKL", @@ -31,6 +32,8 @@ "with_encoder_nonlocal_attn": false, "with_decoder_nonlocal_attn": false }, + "load_autoencoder_path": "$@model_dir + '/autoencoder.pth'", + "load_autoencoder": "$@autoencoder_def.load_state_dict(torch.load(@load_autoencoder_path))", "autoencoder": "$@autoencoder_def.to(@device)", "diffusion_def": { "_target_": "generative.networks.nets.DiffusionModelUNet", @@ -60,19 +63,18 @@ "transformer_num_layers": 1, "cross_attention_dim": 4 }, + "load_diffusion_path": "$@model_dir + '/diffusion_model.pth'", + "load_diffusion": "$@diffusion_def.load_state_dict(torch.load(@load_diffusion_path))", "diffusion": "$@diffusion_def.to(@device)", "scheduler": { - "_target_": "generative.networks.schedulers.DDIMScheduler", - "beta_start": 0.0001, - "beta_end": 0.02, + "_target_": "generative.networks.schedulers.DDPMScheduler", + "beta_start": 0.0015, + "beta_end": 0.0205, + "num_train_timesteps": 1000, "beta_schedule": "scaled_linear" }, - "inferer": { - "_target_": "generative.inferers.LatentDiffusionInferer", - "scheduler": "$@scheduler" - }, "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", - "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=50)", + "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=1000)", "sampler": { "_target_": "scripts.sampler.Sampler" }, diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py index 20d143c3..f09761a1 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py @@ -19,7 +19,7 @@ def sampling_fn(self, input_noise, autoencoder_model, diffusion_model, scheduler progress_bar = iter(scheduler.timesteps) image = input_noise - conditioning = torch.tensor([[1.0, 0.5, 0.1, 0.5]]).to("cuda").unsqueeze(1) + conditioning = torch.tensor([[1.0, 0.5, 0.5, 0.5]]).to("cuda").unsqueeze(1) cond_concat = conditioning.squeeze(1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) cond_concat = cond_concat.expand(list(cond_concat.shape[0:2]) + list(input_noise.shape[2:])) for t in progress_bar: From 2a04e3abdb27fedc9fd64a706119c5b417c2c335 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Mon, 27 Feb 2023 15:39:00 +0000 Subject: [PATCH 15/18] Fix model inference by remove clipping Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 10 +++++++--- .../scripts/sampler.py | 15 +++++++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 3f4dadaf..58481ab0 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -4,7 +4,8 @@ "$import os", "$import torch" ], - "bundle_root": ".", + "//bundle_root": ".", + "bundle_root": "/media/walter/Storage/Projects/GenerativeModels/model-zoo/models/brain_image_synthesis_latent_diffusion_model/", "model_dir": "$@bundle_root + '/models'", "output_dir": "$@bundle_root + '/output'", "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", @@ -61,7 +62,9 @@ ], "with_conditioning": true, "transformer_num_layers": 1, - "cross_attention_dim": 4 + "cross_attention_dim": 4, + "upcast_attention": true, + "use_flash_attention": false }, "load_diffusion_path": "$@model_dir + '/diffusion_model.pth'", "load_diffusion": "$@diffusion_def.load_state_dict(torch.load(@load_diffusion_path))", @@ -71,7 +74,8 @@ "beta_start": 0.0015, "beta_end": 0.0205, "num_train_timesteps": 1000, - "beta_schedule": "scaled_linear" + "beta_schedule": "scaled_linear", + "clip_sample": false }, "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=1000)", diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py index f09761a1..d621f70f 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py @@ -19,18 +19,17 @@ def sampling_fn(self, input_noise, autoencoder_model, diffusion_model, scheduler progress_bar = iter(scheduler.timesteps) image = input_noise - conditioning = torch.tensor([[1.0, 0.5, 0.5, 0.5]]).to("cuda").unsqueeze(1) + conditioning = torch.tensor([[1.0, 0.1, 0.2, 0.4]]).to("cuda").unsqueeze(1) cond_concat = conditioning.squeeze(1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) cond_concat = cond_concat.expand(list(cond_concat.shape[0:2]) + list(input_noise.shape[2:])) for t in progress_bar: with torch.no_grad(): - with autocast(): - model_output = diffusion_model( - torch.cat((image, cond_concat), dim=1), - timesteps=torch.Tensor((t,)).to(input_noise.device).long(), - context=conditioning, - ) - image, _ = scheduler.step(model_output, t, image) + model_output = diffusion_model( + torch.cat((image, cond_concat), dim=1), + timesteps=torch.Tensor((t,)).to(input_noise.device).long(), + context=conditioning, + ) + image, _ = scheduler.step(model_output, t, image) with torch.no_grad(): with autocast(): From 4b0dbbcd00a50187ce2f6e999201fabebd06f992 Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Mon, 27 Feb 2023 17:33:51 +0000 Subject: [PATCH 16/18] Working sampler Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 31 +++++++++++++------ .../docs/README.md | 18 ++++------- .../scripts/saver.py | 29 +++++++++++++++++ 3 files changed, 57 insertions(+), 21 deletions(-) create mode 100644 model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/saver.py diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 58481ab0..fe207366 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -1,14 +1,20 @@ { "imports": [ - "$import glob", - "$import os", - "$import torch" + "$import torch", + "$from datetime import datetime", + "$from pathlib import Path" ], - "//bundle_root": ".", - "bundle_root": "/media/walter/Storage/Projects/GenerativeModels/model-zoo/models/brain_image_synthesis_latent_diffusion_model/", + "bundle_root": ".", + "out_file": "$datetime.now().strftime('sample_%H%M%S_%d%m%Y')", "model_dir": "$@bundle_root + '/models'", "output_dir": "$@bundle_root + '/output'", + "create_output_dir": "$Path(@output_dir).mkdir(exist_ok=True)", + "gender": 0.0, + "age": 0.1, + "ventricular_vol": 0.2, + "brain_vol": 0.4, "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", + "conditioning": "$torch.tensor([[@gender, @age, @ventricular_vol, @brain_vol]]).to(@device).unsqueeze(1)", "autoencoder_def": { "_target_": "generative.networks.nets.AutoencoderKL", "spatial_dims": 3, @@ -70,7 +76,7 @@ "load_diffusion": "$@diffusion_def.load_state_dict(torch.load(@load_diffusion_path))", "diffusion": "$@diffusion_def.to(@device)", "scheduler": { - "_target_": "generative.networks.schedulers.DDPMScheduler", + "_target_": "generative.networks.schedulers.DDIMScheduler", "beta_start": 0.0015, "beta_end": 0.0205, "num_train_timesteps": 1000, @@ -78,9 +84,16 @@ "clip_sample": false }, "noise": "$torch.randn((1, 3, 20, 28, 20)).to(@device)", - "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=1000)", + "set_timesteps": "$@scheduler.set_timesteps(num_inference_steps=50)", "sampler": { - "_target_": "scripts.sampler.Sampler" + "_target_": "scripts.sampler.Sampler", + "_requires_": "@set_timesteps" }, - "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler)" + "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler)", + "saver": { + "_target_": "scripts.saver.NiftiSaver", + "output_dir": "@output_dir" + }, + "save_nii": "$@saver.save(@sample, @out_file)", + "save": "$torch.save(@sample, @output_dir + '/' + @out_file + '.pt')" } diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md index 6972c893..4fe3ba07 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md @@ -26,20 +26,14 @@ This model achieves the following results on UK Biobank: a FID of 0.0076, a MS-S For more details regarding evaluation results, we refer to table 1 of the original paper. -## **Additinal Usage Steps** (Optional) -*If your bundle requires steps outside the normal flow of usage, describe those here in bash style commands.* - -Example: - -My first special instruction for training: +## **commands example** +Execute sampling: ``` -$ python -m monai.bundle +export PYTHONPATH=$PYTHONPATH:"" +$ python -m monai.bundle run save_nii --config_file configs/inference.json --gender 1.0 --age 0.5 --ventricular_vol 0.5 --brain_vol 0.5 +$ python -m monai.bundle run save_nii --config_file configs/inference.json ``` -My special instruction for inference 2: -``` -$ python -m monai.bundle -``` - +All conditioning are expected to have values between 0 and 1 ## **Citation Info** diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/saver.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/saver.py new file mode 100644 index 00000000..de882df0 --- /dev/null +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/saver.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import nibabel as nib +import numpy as np +import torch + + +class NiftiSaver: + def __init__(self, output_dir: str) -> None: + super().__init__() + self.output_dir = output_dir + self.affine = np.array( + [ + [-1.0, 0.0, 0.0, 96.48149872], + [0.0, 1.0, 0.0, -141.47715759], + [0.0, 0.0, 1.0, -156.55375671], + [0.0, 0.0, 0.0, 1.0], + ] + ) + + def save(self, image_data: torch.Tensor, file_name: str) -> None: + image_data = image_data.cpu().numpy() + image_data = image_data[0, 0, 5:-5, 5:-5, :-15] + image_data = (image_data - image_data.min()) / (image_data.max() - image_data.min()) + image_data = (image_data * 255).astype(np.uint8) + + empty_header = nib.Nifti1Header() + sample_nii = nib.Nifti1Image(image_data, self.affine, empty_header) + nib.save(sample_nii, f"{str(self.output_dir)}/{file_name}.nii.gz") From 025973aad73ab6215a8ec91e7860b79ac602bf0b Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Mon, 27 Feb 2023 18:10:21 +0000 Subject: [PATCH 17/18] Add conditionings Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 8 ++++++-- .../docs/README.md | 3 +-- .../scripts/sampler.py | 11 +++++++++-- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index fe207366..272cfce7 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -5,7 +5,6 @@ "$from pathlib import Path" ], "bundle_root": ".", - "out_file": "$datetime.now().strftime('sample_%H%M%S_%d%m%Y')", "model_dir": "$@bundle_root + '/models'", "output_dir": "$@bundle_root + '/output'", "create_output_dir": "$Path(@output_dir).mkdir(exist_ok=True)", @@ -15,6 +14,7 @@ "brain_vol": 0.4, "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", "conditioning": "$torch.tensor([[@gender, @age, @ventricular_vol, @brain_vol]]).to(@device).unsqueeze(1)", + "out_file": "$datetime.now().strftime('sample_%H%M%S_%d%m%Y') + '_' + str(@gender) + '_' + str(@age) + '_' + str(@ventricular_vol) + '_' + str(@brain_vol)", "autoencoder_def": { "_target_": "generative.networks.nets.AutoencoderKL", "spatial_dims": 3, @@ -77,6 +77,10 @@ "diffusion": "$@diffusion_def.to(@device)", "scheduler": { "_target_": "generative.networks.schedulers.DDIMScheduler", + "_requires_": [ + "@load_diffusion", + "@load_autoencoder" + ], "beta_start": 0.0015, "beta_end": 0.0205, "num_train_timesteps": 1000, @@ -89,7 +93,7 @@ "_target_": "scripts.sampler.Sampler", "_requires_": "@set_timesteps" }, - "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler)", + "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler, @conditioning)", "saver": { "_target_": "scripts.saver.NiftiSaver", "output_dir": "@output_dir" diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md index 4fe3ba07..329fe400 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md @@ -30,8 +30,7 @@ For more details regarding evaluation results, we refer to table 1 of the origin Execute sampling: ``` export PYTHONPATH=$PYTHONPATH:"" -$ python -m monai.bundle run save_nii --config_file configs/inference.json --gender 1.0 --age 0.5 --ventricular_vol 0.5 --brain_vol 0.5 -$ python -m monai.bundle run save_nii --config_file configs/inference.json +$ python -m monai.bundle run save_nii --config_file configs/inference.json --gender 1.0 --age 0.7 --ventricular_vol 0.7 --brain_vol 0.5 ``` All conditioning are expected to have values between 0 and 1 diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py index d621f70f..3058c470 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/scripts/sampler.py @@ -1,6 +1,7 @@ from __future__ import annotations import torch +import torch.nn as nn from monai.utils import optional_import from torch.cuda.amp import autocast @@ -12,14 +13,20 @@ def __init__(self) -> None: super().__init__() @torch.no_grad() - def sampling_fn(self, input_noise, autoencoder_model, diffusion_model, scheduler): + def sampling_fn( + self, + input_noise: torch.Tensor, + autoencoder_model: nn.Module, + diffusion_model: nn.Module, + scheduler: nn.Module, + conditioning: torch.Tensor, + ) -> torch.Tensor: if has_tqdm: progress_bar = tqdm(scheduler.timesteps) else: progress_bar = iter(scheduler.timesteps) image = input_noise - conditioning = torch.tensor([[1.0, 0.1, 0.2, 0.4]]).to("cuda").unsqueeze(1) cond_concat = conditioning.squeeze(1).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) cond_concat = cond_concat.expand(list(cond_concat.shape[0:2]) + list(input_noise.shape[2:])) for t in progress_bar: From cca624228bfbffe204ea08ff6cfb6d5999ba268e Mon Sep 17 00:00:00 2001 From: Walter Hugo Lopez Pinaya Date: Wed, 1 Mar 2023 09:49:38 +0000 Subject: [PATCH 18/18] Address comments Signed-off-by: Walter Hugo Lopez Pinaya --- .../configs/inference.json | 1 + .../configs/metadata.json | 2 +- .../docs/README.md | 12 ++++++------ 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json index 272cfce7..9edac693 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/inference.json @@ -96,6 +96,7 @@ "sample": "$@sampler.sampling_fn(@noise, @autoencoder, @diffusion, @scheduler, @conditioning)", "saver": { "_target_": "scripts.saver.NiftiSaver", + "_requires_": "@create_output_dir", "output_dir": "@output_dir" }, "save_nii": "$@saver.save(@sample, @out_file)", diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json index f6ce2973..4310640e 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/configs/metadata.json @@ -23,7 +23,7 @@ "msssim": 0.6555, "4gmsssim": 0.3883 }, - "intended_use": "This is an example, not to be used for diagnostic purposes", + "intended_use": "This is a research tool/prototype and not to be used clinically", "references": [ "Pinaya, Walter HL, et al. \"Brain imaging generation with latent diffusion models.\" MICCAI Workshop on Deep Generative Models. Springer, Cham, 2022." ], diff --git a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md index 329fe400..8a2dded6 100644 --- a/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md +++ b/model-zoo/models/brain_image_synthesis_latent_diffusion_model/docs/README.md @@ -10,20 +10,20 @@ Synthetic data, Latent Diffusion Model, Generative model, Brain Imaging ## **Model Description** This model is trained using the Latent Diffusion Model architecture [1] and is used for the synthesis of conditioned 3D -brain MRI data. The model is divided into two parts: a autoencoder with KL-regularisation model that compresses data -into a latent space, and a diffusion model that learns the to generated conditioned synthetic latent representations. This +brain MRI data. The model is divided into two parts: an autoencoder with a KL-regularisation model that compresses data +into a latent space and a diffusion model that learns to generate conditioned synthetic latent representations. This model is conditioned on age, sex, the volume of ventricular cerebrospinal fluid, and brain volume normalised for head size. ## **Data** The model was trained on brain data from 31,740 participants from the UK Biobank [2]. We used high-resolution 3D T1w MRI with voxel size of 1mm3, resulting in volumes with 160 x 224 x 160 voxels #### **Preprocessing** -For the image pre-processing, we used UniRes [3] to perform a rigid body registration to a common MNI space. The voxel intensity was normalised to be between [0, 1]. +We used UniRes [3] to perform a rigid body registration to a common MNI space for image pre-processing. The voxel intensity was normalised to be between [0, 1]. ## **Performance** -This model achieves the following results on UK Biobank: a FID of 0.0076, a MS-SSIM of 0.6555, and a 4-G-R-SSIM of 0.3883. +This model achieves the following results on UK Biobank: an FID of 0.0076, an MS-SSIM of 0.6555, and a 4-G-R-SSIM of 0.3883. -For more details regarding evaluation results, we refer to table 1 of the original paper. +Please, check Table 1 of the original paper for more details regarding evaluation results. ## **commands example** @@ -47,7 +47,7 @@ All conditioning are expected to have values between 0 and 1 } ``` -## **References** (Optional) +## **References** Example: