yufanh-nv commited on
Commit
8696833
·
verified ·
1 Parent(s): f20a892

initial copy of MONAI VISTA3D-HF

Browse files
LICENSE ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Code License
2
+
3
+ This license applies to all files except the model weights in the directory.
4
+
5
+ Apache License
6
+ Version 2.0, January 2004
7
+ http://www.apache.org/licenses/
8
+
9
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10
+
11
+ 1. Definitions.
12
+
13
+ "License" shall mean the terms and conditions for use, reproduction,
14
+ and distribution as defined by Sections 1 through 9 of this document.
15
+
16
+ "Licensor" shall mean the copyright owner or entity authorized by
17
+ the copyright owner that is granting the License.
18
+
19
+ "Legal Entity" shall mean the union of the acting entity and all
20
+ other entities that control, are controlled by, or are under common
21
+ control with that entity. For the purposes of this definition,
22
+ "control" means (i) the power, direct or indirect, to cause the
23
+ direction or management of such entity, whether by contract or
24
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
25
+ outstanding shares, or (iii) beneficial ownership of such entity.
26
+
27
+ "You" (or "Your") shall mean an individual or Legal Entity
28
+ exercising permissions granted by this License.
29
+
30
+ "Source" form shall mean the preferred form for making modifications,
31
+ including but not limited to software source code, documentation
32
+ source, and configuration files.
33
+
34
+ "Object" form shall mean any form resulting from mechanical
35
+ transformation or translation of a Source form, including but
36
+ not limited to compiled object code, generated documentation,
37
+ and conversions to other media types.
38
+
39
+ "Work" shall mean the work of authorship, whether in Source or
40
+ Object form, made available under the License, as indicated by a
41
+ copyright notice that is included in or attached to the work
42
+ (an example is provided in the Appendix below).
43
+
44
+ "Derivative Works" shall mean any work, whether in Source or Object
45
+ form, that is based on (or derived from) the Work and for which the
46
+ editorial revisions, annotations, elaborations, or other modifications
47
+ represent, as a whole, an original work of authorship. For the purposes
48
+ of this License, Derivative Works shall not include works that remain
49
+ separable from, or merely link (or bind by name) to the interfaces of,
50
+ the Work and Derivative Works thereof.
51
+
52
+ "Contribution" shall mean any work of authorship, including
53
+ the original version of the Work and any modifications or additions
54
+ to that Work or Derivative Works thereof, that is intentionally
55
+ submitted to Licensor for inclusion in the Work by the copyright owner
56
+ or by an individual or Legal Entity authorized to submit on behalf of
57
+ the copyright owner. For the purposes of this definition, "submitted"
58
+ means any form of electronic, verbal, or written communication sent
59
+ to the Licensor or its representatives, including but not limited to
60
+ communication on electronic mailing lists, source code control systems,
61
+ and issue tracking systems that are managed by, or on behalf of, the
62
+ Licensor for the purpose of discussing and improving the Work, but
63
+ excluding communication that is conspicuously marked or otherwise
64
+ designated in writing by the copyright owner as "Not a Contribution."
65
+
66
+ "Contributor" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ 2. Grant of Copyright License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ copyright license to reproduce, prepare Derivative Works of,
74
+ publicly display, publicly perform, sublicense, and distribute the
75
+ Work and such Derivative Works in Source or Object form.
76
+
77
+ 3. Grant of Patent License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ (except as stated in this section) patent license to make, have made,
81
+ use, offer to sell, sell, import, and otherwise transfer the Work,
82
+ where such license applies only to those patent claims licensable
83
+ by such Contributor that are necessarily infringed by their
84
+ Contribution(s) alone or by combination of their Contribution(s)
85
+ with the Work to which such Contribution(s) was submitted. If You
86
+ institute patent litigation against any entity (including a
87
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
88
+ or a Contribution incorporated within the Work constitutes direct
89
+ or contributory patent infringement, then any patent licenses
90
+ granted to You under this License for that Work shall terminate
91
+ as of the date such litigation is filed.
92
+
93
+ 4. Redistribution. You may reproduce and distribute copies of the
94
+ Work or Derivative Works thereof in any medium, with or without
95
+ modifications, and in Source or Object form, provided that You
96
+ meet the following conditions:
97
+
98
+ (a) You must give any other recipients of the Work or
99
+ Derivative Works a copy of this License; and
100
+
101
+ (b) You must cause any modified files to carry prominent notices
102
+ stating that You changed the files; and
103
+
104
+ (c) You must retain, in the Source form of any Derivative Works
105
+ that You distribute, all copyright, patent, trademark, and
106
+ attribution notices from the Source form of the Work,
107
+ excluding those notices that do not pertain to any part of
108
+ the Derivative Works; and
109
+
110
+ (d) If the Work includes a "NOTICE" text file as part of its
111
+ distribution, then any Derivative Works that You distribute must
112
+ include a readable copy of the attribution notices contained
113
+ within such NOTICE file, excluding those notices that do not
114
+ pertain to any part of the Derivative Works, in at least one
115
+ of the following places: within a NOTICE text file distributed
116
+ as part of the Derivative Works; within the Source form or
117
+ documentation, if provided along with the Derivative Works; or,
118
+ within a display generated by the Derivative Works, if and
119
+ wherever such third-party notices normally appear. The contents
120
+ of the NOTICE file are for informational purposes only and
121
+ do not modify the License. You may add Your own attribution
122
+ notices within Derivative Works that You distribute, alongside
123
+ or as an addendum to the NOTICE text from the Work, provided
124
+ that such additional attribution notices cannot be construed
125
+ as modifying the License.
126
+
127
+ You may add Your own copyright statement to Your modifications and
128
+ may provide additional or different license terms and conditions
129
+ for use, reproduction, or distribution of Your modifications, or
130
+ for any such Derivative Works as a whole, provided Your use,
131
+ reproduction, and distribution of the Work otherwise complies with
132
+ the conditions stated in this License.
133
+
134
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
135
+ any Contribution intentionally submitted for inclusion in the Work
136
+ by You to the Licensor shall be under the terms and conditions of
137
+ this License, without any additional terms or conditions.
138
+ Notwithstanding the above, nothing herein shall supersede or modify
139
+ the terms of any separate license agreement you may have executed
140
+ with Licensor regarding such Contributions.
141
+
142
+ 6. Trademarks. This License does not grant permission to use the trade
143
+ names, trademarks, service marks, or product names of the Licensor,
144
+ except as required for reasonable and customary use in describing the
145
+ origin of the Work and reproducing the content of the NOTICE file.
146
+
147
+ 7. Disclaimer of Warranty. Unless required by applicable law or
148
+ agreed to in writing, Licensor provides the Work (and each
149
+ Contributor provides its Contributions) on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151
+ implied, including, without limitation, any warranties or conditions
152
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153
+ PARTICULAR PURPOSE. You are solely responsible for determining the
154
+ appropriateness of using or redistributing the Work and assume any
155
+ risks associated with Your exercise of permissions under this License.
156
+
157
+ 8. Limitation of Liability. In no event and under no legal theory,
158
+ whether in tort (including negligence), contract, or otherwise,
159
+ unless required by applicable law (such as deliberate and grossly
160
+ negligent acts) or agreed to in writing, shall any Contributor be
161
+ liable to You for damages, including any direct, indirect, special,
162
+ incidental, or consequential damages of any character arising as a
163
+ result of this License or out of the use or inability to use the
164
+ Work (including but not limited to damages for loss of goodwill,
165
+ work stoppage, computer failure or malfunction, or any and all
166
+ other commercial damages or losses), even if such Contributor
167
+ has been advised of the possibility of such damages.
168
+
169
+ 9. Accepting Warranty or Additional Liability. While redistributing
170
+ the Work or Derivative Works thereof, You may choose to offer,
171
+ and charge a fee for, acceptance of support, warranty, indemnity,
172
+ or other liability obligations and/or rights consistent with this
173
+ License. However, in accepting such obligations, You may act only
174
+ on Your own behalf and on Your sole responsibility, not on behalf
175
+ of any other Contributor, and only if You agree to indemnify,
176
+ defend, and hold each Contributor harmless for any liability
177
+ incurred by, or claims asserted against, such Contributor by reason
178
+ of your accepting any such warranty or additional liability.
179
+
180
+ END OF TERMS AND CONDITIONS
181
+
182
+ APPENDIX: How to apply the Apache License to your work.
183
+
184
+ To apply the Apache License to your work, attach the following
185
+ boilerplate notice, with the fields enclosed by brackets "[]"
186
+ replaced with your own identifying information. (Don't include
187
+ the brackets!) The text should be enclosed in the appropriate
188
+ comment syntax for the file format. We also recommend that a
189
+ file or class name and description of purpose be included on the
190
+ same "printed page" as the copyright notice for easier
191
+ identification within third-party archives.
192
+
193
+ Copyright [yyyy] [name of copyright owner]
194
+
195
+ Licensed under the Apache License, Version 2.0 (the "License");
196
+ you may not use this file except in compliance with the License.
197
+ You may obtain a copy of the License at
198
+
199
+ http://www.apache.org/licenses/LICENSE-2.0
200
+
201
+ Unless required by applicable law or agreed to in writing, software
202
+ distributed under the License is distributed on an "AS IS" BASIS,
203
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
+ See the License for the specific language governing permissions and
205
+ limitations under the License.
206
+
207
+ ------------------------------------------------------------------------------
208
+
209
+ Model Weights License
210
+
211
+ This license applies to model weights in the directory.
212
+
213
+ NVIDIA License
214
+
215
+ 1. Definitions
216
+
217
+ “Licensor” means any person or entity that distributes its Work.
218
+ “Work” means (a) the original work of authorship made available under this license, which may include software, documentation, or other files, and (b) any additions to or derivative works thereof that are made available under this license.
219
+ The terms “reproduce,” “reproduction,” “derivative works,” and “distribution” have the meaning as provided under U.S. copyright law; provided, however, that 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.
220
+ Works are “made available” under this license by including in or with the Work either (a) a copyright notice referencing the applicability of this license to the Work, or (b) a copy of this license.
221
+
222
+ 2. License Grant
223
+
224
+ 2.1 Copyright Grant. Subject to the terms and conditions of this license, each Licensor grants to you a perpetual, worldwide, non-exclusive, royalty-free, copyright license to use, reproduce, prepare derivative works of, publicly display, publicly perform, sublicense and distribute its Work and any resulting derivative works in any form.
225
+
226
+ 3. Limitations
227
+
228
+ 3.1 Redistribution. You may reproduce or distribute the Work only if (a) you do so under this license, (b) you include a complete copy of this license with your distribution, and (c) you retain without modification any copyright, patent, trademark, or attribution notices that are present in the Work.
229
+
230
+ 3.2 Derivative Works. You may specify that additional or different terms apply to the use, reproduction, and distribution of your derivative works of the Work (“Your Terms”) only if (a) Your Terms provide that the use limitation in Section 3.3 applies to your derivative works, and (b) you identify the specific derivative works that are subject to Your Terms. Notwithstanding Your Terms, this license (including the redistribution requirements in Section 3.1) will continue to apply to the Work itself.
231
+
232
+ 3.3 Use Limitation. The Work and any derivative works thereof only may be used or intended for use non-commercially. Notwithstanding the foregoing, NVIDIA Corporation and its affiliates may use the Work and any derivative works commercially. As used herein, “non-commercially” means for research or evaluation purposes only.
233
+
234
+ 3.4 Patent Claims. If you bring or threaten to bring a patent claim against any Licensor (including any claim, cross-claim or counterclaim in a lawsuit) to enforce any patents that you allege are infringed by any Work, then your rights under this license from such Licensor (including the grant in Section 2.1) will terminate immediately.
235
+
236
+ 3.5 Trademarks. This license does not grant any rights to use any Licensor’s or its affiliates’ names, logos, or trademarks, except as necessary to reproduce the notices described in this license.
237
+
238
+ 3.6 Termination. If you violate any term of this license, then your rights under this license (including the grant in Section 2.1) will terminate immediately.
239
+
240
+ 4. Disclaimer of Warranty.
241
+
242
+ THE WORK IS PROVIDED “AS IS” WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF
243
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER THIS LICENSE.
244
+
245
+ 5. Limitation of Liability.
246
+
247
+ EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK (INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
README.md ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Overview
2
+
3
+ ## Description:
4
+ NV-Segment-CT (the same content but a new name for [MONAI VISTA3D Huggingface model](https://huggingface.co/MONAI/VISTA3D-HF)) is a specialized interactive foundation model for 3D medical imaging. It excels in providing accurate and adaptable segmentation analysis across anatomies and modalities. Utilizing a multi-head architecture, VISTA-3D adapts to varying conditions and anatomical areas, helping guide users' annotation workflow. This model is a copy of the
5
+ This model is a hugging face refactored version of the [MONAI VISTA3D](https://github.com/Project-MONAI/model-zoo/tree/dev/models/vista3d) bundle. A pipeline with transformer library interfaces is provided by this model. For more details about the original model, please visit the [MONAI model zoo](https://github.com/Project-MONAI/model-zoo).
6
+
7
+ This model is for research purposes and not for clinical usage.
8
+
9
+
10
+ Core to VISTA-3D are three workflows:
11
+
12
+ - **Segment everything**: Enables whole body exploration, crucial for understanding complex diseases affecting multiple organs and for holistic treatment planning.
13
+ - **Segment using class**: Provides detailed sectional views based on specific classes, essential for targeted disease analysis or organ mapping, such as tumor identification in critical organs.
14
+ - **Segment point prompts**: Enhances segmentation precision through user-directed, click-based selection. This interactive approach accelerates the creation of accurate ground-truth data, essential in medical imaging analysis.
15
+
16
+ ## Run pipeline:
17
+ For running the pipeline, VISTA3d requires at least one prompt for segmentation. It supports label prompt, which is the index of the class for automatic segmentation. It also supports point-click prompts for binary interactive segmentation. Users can provide both prompts at the same time.
18
+
19
+ Here is a code snippet to showcase how to execute inference with this model.
20
+ ```python
21
+ import os
22
+ import tempfile
23
+
24
+ import torch
25
+ from hugging_face_pipeline import HuggingFacePipelineHelper
26
+
27
+
28
+ FILE_PATH = os.path.dirname(__file__)
29
+ with tempfile.TemporaryDirectory() as tmp_dir:
30
+ output_dir = os.path.join(tmp_dir, "output_dir")
31
+ pipeline_helper = HuggingFacePipelineHelper("vista3d")
32
+ pipeline = pipeline_helper.init_pipeline(
33
+ os.path.join(FILE_PATH, "vista3d_pretrained_model"),
34
+ device=torch.device("cuda:0"),
35
+ )
36
+ inputs = [
37
+ {
38
+ "image": "/data/Task09_Spleen/imagesTs/spleen_1.nii.gz",
39
+ "label_prompt": [3],
40
+ },
41
+ {
42
+ "image": "/data/Task09_Spleen/imagesTs/spleen_11.nii.gz",
43
+ "label_prompt": [3],
44
+ },
45
+ ]
46
+ pipeline(inputs, output_dir=output_dir)
47
+
48
+ ```
49
+ The inputs defines the image to segment and the prompt for segmentation.
50
+ ```python
51
+ inputs = {'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'label_prompt':[1]}
52
+ inputs = {'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'points':[[138,245,18], [271,343,27]], 'point_labels':[1,0]}
53
+ ```
54
+ - The inputs must include the key `image` which contain the absolute path to the nii image file, and includes prompt keys of `label_prompt`, `points` and `point_labels`.
55
+ - The `label_prompt` is a list of length `B`, which can perform `B` foreground objects segmentation, e.g. `[2,3,4,5]`. If `B>1`, Point prompts must NOT be provided.
56
+ - The `points` is of shape `[N, 3]` like `[[x1,y1,z1],[x2,y2,z2],...[xN,yN,zN]]`, representing `N` point coordinates **IN THE ORIGINAL IMAGE SPACE** of a single foreground object. `point_labels` is a list of length [N] like [1,1,0,-1,...], which
57
+ matches the `points`. 0 means background, 1 means foreground, -1 means ignoring this point. `points` and `point_labels` must pe provided together and match length.
58
+ - **B must be 1 if label_prompt and points are provided together**. The inferer only supports SINGLE OBJECT point click segmentatation.
59
+ - If no prompt is provided, the model will use `everything_labels` to segment 117 classes:
60
+
61
+ ```Python
62
+ list(set([i+1 for i in range(132)]) - set([2,16,18,20,21,23,24,25,26,27,128,129,130,131,132]))
63
+ ```
64
+
65
+ - The `points` together with `label_prompts` for "Kidney", "Lung", "Bone" (class index [2, 20, 21]) are not allowed since those prompts will be divided into sub-categories (e.g. left kidney and right kidney). Use `points` for the sub-categories as defined in the `inference.json`.
66
+ - To specify a new class for zero-shot segmentation, set the `label_prompt` to a value between 133 and 254. Ensure that `points` and `point_labels` are also provided; otherwise, the inference result will be a tensor of zeros.
67
+
68
+
69
+
70
+
71
+ ## Model Architecture:
72
+ **Architecture Type:** Transformer <br>
73
+ **Network Architecture:** SAM-like<br>
74
+
75
+ ## Input:
76
+ **Input Type(s):** Computed Tomography (CT) Image<br>
77
+ **Input Format(s):** (Neuroimaging Informatics Technology Initiative) NIfTI <br>
78
+ **Input Parameters:** Three-Dimensional (3D) <br>
79
+ **Other Properties Related to Input:** Array of Class/Point Information
80
+
81
+ ## Output:
82
+ **Output Type(s):** Image <br>
83
+ **Output Format:** NIfTI <br>
84
+ **Output Parameters:** 3D <br>
85
+
86
+ ## Software Integration:
87
+ **Runtime Engine(s):**
88
+ MONAI Core v.1.3 <br>
89
+
90
+ **Supported Hardware Microarchitecture Compatibility:** <br>
91
+ * Ampere <br>
92
+ * Hopper <br>
93
+
94
+ **[Preferred/Supported] Operating System(s):** <br>
95
+ * Linux <br>
96
+
97
+ ## Model Version(s):
98
+ Internal ONLY
99
+ 0.1.9 <br>
100
+ Version changelog: https://gitlab-master.nvidia.com/dlmed/vista3d_bundle/-/blob/main/configs/metadata.json
101
+
102
+ # Training & Evaluation:
103
+ ## Training Dataset:
104
+ Internal ONLY
105
+ 15 Datasets
106
+ Name, JIRA/SWIPAT, Commercial, and # of Data Tracked
107
+ "VISTA" Sheet: https://docs.google.com/spreadsheets/d/14frhzELquSF_-tF7yGFDBHmSdnp-9-5pmbONQx8iQWk/edit?usp=sharing
108
+
109
+ ## Evaluation Dataset:
110
+ Internal ONLY
111
+ 15 Datasets
112
+ Name, JIRA/SWIPAT, Commercial, and # of Data Tracked
113
+ "VISTA" Sheet: https://docs.google.com/spreadsheets/d/14frhzELquSF_-tF7yGFDBHmSdnp-9-5pmbONQx8iQWk/edit?usp=sharing
114
+ https://docs.google.com/spreadsheets/d/1hmv-O-f6tdgndsRnoqCgcunR2uQ9IySDhZWmjsXwgbM/edit?usp=sharing
115
+
116
+ ** Data Collection Method by dataset <br>
117
+ * [Hybrid: Human, Automatic/Sensors] <br>
118
+
119
+ ** Labeling Method by dataset <br>
120
+ * [Hybrid: Human, Automatic/Sensors] <br>
121
+
122
+ **Properties:** Custom internal and public dataset of organs from multiple scanner types. <br>
123
+
124
+
125
+ ## Evaluation Dataset:
126
+
127
+ ** Data Collection Method by dataset <br>
128
+ * [Hybrid: Human, Automatic/Sensors] <br>
129
+
130
+ ** Labeling Method by dataset <br>
131
+ * [Hybrid: Human, Automatic/Sensors] <br>
132
+
133
+ **Properties:** Custom internal and public dataset of organs from multiple scanner types. <br>
134
+
135
+
136
+ ## Inference:
137
+ **Engine:** Triton <br>
138
+ **Test Hardware:**
139
+ A100<br>
140
+ H100<br>
141
+ L40<br>
142
+
143
+ ## Ethical Considerations:
144
+ NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal model team to ensure this model meets requirements for the relevant industry and use case and addresses unforeseen product misuse. For more detailed information on ethical considerations for this model, please see the Model Card++ Explainability, Bias, Safety & Security, and Privacy Subcards [Insert Link to Model Card++ here] Please report security vulnerabilities or NVIDIA AI Concerns [here](https://www.nvidia.com/en-us/support/submit-security-vulnerability/).
145
+
146
+ ## Additional Information:
147
+ The current list of classes available within VISTA-3D:
148
+
149
+ "0": "background",
150
+ "1": "liver",
151
+ "2": "kidney",
152
+ "3": "spleen",
153
+ "4": "pancreas",
154
+ "5": "right kidney",
155
+ "6": "aorta",
156
+ "7": "inferior vena cava",
157
+ "8": "right adrenal gland",
158
+ "9": "left adrenal gland",
159
+ "10": "gallbladder",
160
+ "11": "esophagus",
161
+ "12": "stomach",
162
+ "13": "duodenum",
163
+ "14": "left kidney",
164
+ "15": "bladder",
165
+ "16": "prostate or uterus",
166
+ "17": "portal vein and splenic vein",
167
+ "18": "rectum",
168
+ "19": "small bowel",
169
+ "20": "lung",
170
+ "21": "bone",
171
+ "22": "brain",
172
+ "23": "lung tumor",
173
+ "24": "pancreatic tumor",
174
+ "25": "hepatic vessel",
175
+ "26": "hepatic tumor",
176
+ "27": "colon cancer primaries",
177
+ "28": "left lung upper lobe",
178
+ "29": "left lung lower lobe",
179
+ "30": "right lung upper lobe",
180
+ "31": "right lung middle lobe",
181
+ "32": "right lung lower lobe",
182
+ "33": "vertebrae L5",
183
+ "34": "vertebrae L4",
184
+ "35": "vertebrae L3",
185
+ "36": "vertebrae L2",
186
+ "37": "vertebrae L1",
187
+ "38": "vertebrae T12",
188
+ "39": "vertebrae T11",
189
+ "40": "vertebrae T10",
190
+ "41": "vertebrae T9",
191
+ "42": "vertebrae T8",
192
+ "43": "vertebrae T7",
193
+ "44": "vertebrae T6",
194
+ "45": "vertebrae T5",
195
+ "46": "vertebrae T4",
196
+ "47": "vertebrae T3",
197
+ "48": "vertebrae T2",
198
+ "49": "vertebrae T1",
199
+ "50": "vertebrae C7",
200
+ "51": "vertebrae C6",
201
+ "52": "vertebrae C5",
202
+ "53": "vertebrae C4",
203
+ "54": "vertebrae C3",
204
+ "55": "vertebrae C2",
205
+ "56": "vertebrae C1",
206
+ "57": "trachea",
207
+ "58": "left iliac artery",
208
+ "59": "right iliac artery",
209
+ "60": "left iliac vena",
210
+ "61": "right iliac vena",
211
+ "62": "colon",
212
+ "63": "left rib 1",
213
+ "64": "left rib 2",
214
+ "65": "left rib 3",
215
+ "66": "left rib 4",
216
+ "67": "left rib 5",
217
+ "68": "left rib 6",
218
+ "69": "left rib 7",
219
+ "70": "left rib 8",
220
+ "71": "left rib 9",
221
+ "72": "left rib 10",
222
+ "73": "left rib 11",
223
+ "74": "left rib 12",
224
+ "75": "right rib 1",
225
+ "76": "right rib 2",
226
+ "77": "right rib 3",
227
+ "78": "right rib 4",
228
+ "79": "right rib 5",
229
+ "80": "right rib 6",
230
+ "81": "right rib 7",
231
+ "82": "right rib 8",
232
+ "83": "right rib 9",
233
+ "84": "right rib 10",
234
+ "85": "right rib 11",
235
+ "86": "right rib 12",
236
+ "87": "left humerus",
237
+ "88": "right humerus",
238
+ "89": "left scapula",
239
+ "90": "right scapula",
240
+ "91": "left clavicula",
241
+ "92": "right clavicula",
242
+ "93": "left femur",
243
+ "94": "right femur",
244
+ "95": "left hip",
245
+ "96": "right hip",
246
+ "97": "sacrum",
247
+ "98": "left gluteus maximus",
248
+ "99": "right gluteus maximus",
249
+ "100": "left gluteus medius",
250
+ "101": "right gluteus medius",
251
+ "102": "left gluteus minimus",
252
+ "103": "right gluteus minimus",
253
+ "104": "left autochthon",
254
+ "105": "right autochthon",
255
+ "106": "left iliopsoas",
256
+ "107": "right iliopsoas",
257
+ "108": "left atrial appendage",
258
+ "109": "brachiocephalic trunk",
259
+ "110": "left brachiocephalic vein",
260
+ "111": "right brachiocephalic vein",
261
+ "112": "left common carotid artery",
262
+ "113": "right common carotid artery",
263
+ "114": "costal cartilages",
264
+ "115": "heart",
265
+ "116": "left kidney cyst",
266
+ "117": "right kidney cyst",
267
+ "118": "prostate",
268
+ "119": "pulmonary vein",
269
+ "120": "skull",
270
+ "121": "spinal cord",
271
+ "122": "sternum",
272
+ "123": "left subclavian artery",
273
+ "124": "right subclavian artery",
274
+ "125": "superior vena cava",
275
+ "126": "thyroid gland",
276
+ "127": "vertebrae S1",
277
+ "128": "bone lesion",
278
+ "129": "kidney mass",
279
+ "130": "liver tumor",
280
+ "131": "vertebrae L6",
281
+ "132": "airway"
282
+
283
+ # License
284
+
285
+ ## Code License
286
+
287
+ This project includes code licensed under the Apache License 2.0.
288
+ You may obtain a copy of the License at
289
+
290
+ http://www.apache.org/licenses/LICENSE-2.0
291
+
292
+ ## Model Weights License
293
+
294
+ The model weights included in this project are licensed under the NCLS v1 License.
295
+
296
+ Both licenses' full texts have been combined into a single `LICENSE` file. Please refer to this `LICENSE` file for more details about the terms and conditions of both licenses.
297
+
298
+ # References
299
+ - Antonelli, M., Reinke, A., Bakas, S. et al. The Medical Segmentation Decathlon. Nat Commun 13, 4128 (2022). https://doi.org/10.1038/s41467-022-30695-9
300
+
301
+ - He, Yufan, et al. VISTA3D: A unified segmentation foundation model for 3D medical imaging. CVPR 2025. https://arxiv.org/abs/2406.05285
__init__.py ADDED
File without changes
data_license.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Third Party Licenses
2
+ -----------------------------------------------------------------------
3
+
4
+ /*********************************************************************/
5
+ i. Medical Segmentation Decathlon
6
+ http://medicaldecathlon.com/
hugging_face_pipeline.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from vista3d_config import VISTA3DConfig
3
+ from vista3d_model import VISTA3DModel, register_my_model
4
+ from vista3d_pipeline import VISTA3DPipeline, register_simple_pipeline
5
+
6
+
7
+ class HuggingFacePipelineHelper:
8
+
9
+ def __init__(self, pipeline_name: str = "vista3d"):
10
+ self.pipeline_name = pipeline_name
11
+
12
+ def __model_register(self):
13
+ register_my_model()
14
+
15
+ def __pipeline_register(self):
16
+ register_simple_pipeline()
17
+
18
+ def get_pipeline(self):
19
+ self.__model_register()
20
+ self.__pipeline_register()
21
+ return pipeline(self.pipeline_name)
22
+
23
+ def _update_config(self, config, config_dict):
24
+ if config_dict:
25
+ for key in config_dict:
26
+ if hasattr(config, key) and getattr(config, key) != config_dict[key]:
27
+ setattr(config, key, config_dict[key])
28
+ return config
29
+
30
+ def init_pipeline(self, pretrained_model_name_or_path: str, **kwargs):
31
+ config = VISTA3DConfig()
32
+ config_dict = kwargs.pop("config_dict", None)
33
+ self._update_config(config, config_dict)
34
+ model = VISTA3DModel(config)
35
+ model = model.from_pretrained(
36
+ pretrained_model_name_or_path=pretrained_model_name_or_path
37
+ )
38
+ return VISTA3DPipeline(model, **kwargs)
metadata.json ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json",
3
+ "version": "0.0.1",
4
+ "changelog": {
5
+ "0.0.1": "initial copy of MONAI VISTA3D-HF"
6
+ },
7
+ "monai_version": "1.4.0",
8
+ "pytorch_version": "2.4.0",
9
+ "numpy_version": "1.24.4",
10
+ "required_packages_version": {
11
+ "matplotlib": "3.9.1",
12
+ "einops": "0.7.0",
13
+ "scikit-image": "0.23.2",
14
+ "nibabel": "5.2.1",
15
+ "pytorch-ignite": "0.4.11",
16
+ "cucim-cu12": "24.6.0",
17
+ "mlflow": "2.17.2"
18
+ },
19
+ "supported_apps": {
20
+ "vista3d-nim": ""
21
+ },
22
+ "name": "VISTA3D",
23
+ "task": "Decathlon Spleen segmentation",
24
+ "description": "VISTA3D bundle",
25
+ "authors": "MONAI team",
26
+ "copyright": "Copyright (c) MONAI Consortium",
27
+ "data_source": "Task09_Spleen.tar from http://medicaldecathlon.com/",
28
+ "data_type": "nibabel",
29
+ "image_classes": "1 channel data, intensity scaled to [0, 1]",
30
+ "label_classes": "single channel data",
31
+ "pred_classes": "2 channels OneHot data",
32
+ "intended_use": "This is an example, not to be used for diagnostic purposes",
33
+ "references": [],
34
+ "network_data_format": {
35
+ "inputs": {
36
+ "image": {
37
+ "type": "image",
38
+ "format": "hounsfield",
39
+ "modality": "CT",
40
+ "num_channels": 1,
41
+ "spatial_shape": [
42
+ 128,
43
+ 128,
44
+ 128
45
+ ],
46
+ "dtype": "float32",
47
+ "value_range": [
48
+ 0,
49
+ 1
50
+ ],
51
+ "is_patch_data": true,
52
+ "channel_def": {
53
+ "0": "image"
54
+ }
55
+ }
56
+ },
57
+ "outputs": {
58
+ "pred": {
59
+ "type": "image",
60
+ "format": "segmentation",
61
+ "num_channels": 1,
62
+ "spatial_shape": [
63
+ 128,
64
+ 128,
65
+ 128
66
+ ],
67
+ "dtype": "float32",
68
+ "value_range": [
69
+ 0,
70
+ 1
71
+ ],
72
+ "is_patch_data": true,
73
+ "channel_def": {
74
+ "0": "background",
75
+ "1": "liver",
76
+ "2": "kidney",
77
+ "3": "spleen",
78
+ "4": "pancreas",
79
+ "5": "right kidney",
80
+ "6": "aorta",
81
+ "7": "inferior vena cava",
82
+ "8": "right adrenal gland",
83
+ "9": "left adrenal gland",
84
+ "10": "gallbladder",
85
+ "11": "esophagus",
86
+ "12": "stomach",
87
+ "13": "duodenum",
88
+ "14": "left kidney",
89
+ "15": "bladder",
90
+ "16": "prostate or uterus",
91
+ "17": "portal vein and splenic vein",
92
+ "18": "rectum",
93
+ "19": "small bowel",
94
+ "20": "lung",
95
+ "21": "bone",
96
+ "22": "brain",
97
+ "23": "lung tumor",
98
+ "24": "pancreatic tumor",
99
+ "25": "hepatic vessel",
100
+ "26": "hepatic tumor",
101
+ "27": "colon cancer primaries",
102
+ "28": "left lung upper lobe",
103
+ "29": "left lung lower lobe",
104
+ "30": "right lung upper lobe",
105
+ "31": "right lung middle lobe",
106
+ "32": "right lung lower lobe",
107
+ "33": "vertebrae L5",
108
+ "34": "vertebrae L4",
109
+ "35": "vertebrae L3",
110
+ "36": "vertebrae L2",
111
+ "37": "vertebrae L1",
112
+ "38": "vertebrae T12",
113
+ "39": "vertebrae T11",
114
+ "40": "vertebrae T10",
115
+ "41": "vertebrae T9",
116
+ "42": "vertebrae T8",
117
+ "43": "vertebrae T7",
118
+ "44": "vertebrae T6",
119
+ "45": "vertebrae T5",
120
+ "46": "vertebrae T4",
121
+ "47": "vertebrae T3",
122
+ "48": "vertebrae T2",
123
+ "49": "vertebrae T1",
124
+ "50": "vertebrae C7",
125
+ "51": "vertebrae C6",
126
+ "52": "vertebrae C5",
127
+ "53": "vertebrae C4",
128
+ "54": "vertebrae C3",
129
+ "55": "vertebrae C2",
130
+ "56": "vertebrae C1",
131
+ "57": "trachea",
132
+ "58": "left iliac artery",
133
+ "59": "right iliac artery",
134
+ "60": "left iliac vena",
135
+ "61": "right iliac vena",
136
+ "62": "colon",
137
+ "63": "left rib 1",
138
+ "64": "left rib 2",
139
+ "65": "left rib 3",
140
+ "66": "left rib 4",
141
+ "67": "left rib 5",
142
+ "68": "left rib 6",
143
+ "69": "left rib 7",
144
+ "70": "left rib 8",
145
+ "71": "left rib 9",
146
+ "72": "left rib 10",
147
+ "73": "left rib 11",
148
+ "74": "left rib 12",
149
+ "75": "right rib 1",
150
+ "76": "right rib 2",
151
+ "77": "right rib 3",
152
+ "78": "right rib 4",
153
+ "79": "right rib 5",
154
+ "80": "right rib 6",
155
+ "81": "right rib 7",
156
+ "82": "right rib 8",
157
+ "83": "right rib 9",
158
+ "84": "right rib 10",
159
+ "85": "right rib 11",
160
+ "86": "right rib 12",
161
+ "87": "left humerus",
162
+ "88": "right humerus",
163
+ "89": "left scapula",
164
+ "90": "right scapula",
165
+ "91": "left clavicula",
166
+ "92": "right clavicula",
167
+ "93": "left femur",
168
+ "94": "right femur",
169
+ "95": "left hip",
170
+ "96": "right hip",
171
+ "97": "sacrum",
172
+ "98": "left gluteus maximus",
173
+ "99": "right gluteus maximus",
174
+ "100": "left gluteus medius",
175
+ "101": "right gluteus medius",
176
+ "102": "left gluteus minimus",
177
+ "103": "right gluteus minimus",
178
+ "104": "left autochthon",
179
+ "105": "right autochthon",
180
+ "106": "left iliopsoas",
181
+ "107": "right iliopsoas",
182
+ "108": "left atrial appendage",
183
+ "109": "brachiocephalic trunk",
184
+ "110": "left brachiocephalic vein",
185
+ "111": "right brachiocephalic vein",
186
+ "112": "left common carotid artery",
187
+ "113": "right common carotid artery",
188
+ "114": "costal cartilages",
189
+ "115": "heart",
190
+ "116": "left kidney cyst",
191
+ "117": "right kidney cyst",
192
+ "118": "prostate",
193
+ "119": "pulmonary vein",
194
+ "120": "skull",
195
+ "121": "spinal cord",
196
+ "122": "sternum",
197
+ "123": "left subclavian artery",
198
+ "124": "right subclavian artery",
199
+ "125": "superior vena cava",
200
+ "126": "thyroid gland",
201
+ "127": "vertebrae S1",
202
+ "128": "bone lesion",
203
+ "129": "kidney mass",
204
+ "130": "liver tumor",
205
+ "131": "vertebrae L6",
206
+ "132": "airway"
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
scripts/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ # from .evaluator import EnsembleEvaluator, Evaluator, SupervisedEvaluator
13
+ # from .multi_gpu_supervised_trainer import create_multigpu_supervised_evaluator, create_multigpu_supervised_trainer
14
+
15
+ from .early_stop_score_function import score_function
scripts/early_stop_score_function.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import torch.distributed as dist
5
+
6
+
7
+ def score_function(engine):
8
+ val_metric = engine.state.metrics["val_mean_dice"]
9
+ if dist.is_initialized():
10
+ device = torch.device("cuda:" + os.environ["LOCAL_RANK"])
11
+ val_metric = torch.tensor([val_metric]).to(device)
12
+ dist.all_reduce(val_metric, op=dist.ReduceOp.SUM)
13
+ val_metric /= dist.get_world_size()
14
+ return val_metric.item()
15
+ return val_metric
scripts/evaluator.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
15
+
16
+ import numpy as np
17
+ import torch
18
+ from monai.engines.evaluator import SupervisedEvaluator
19
+ from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch
20
+ from monai.inferers import Inferer, SimpleInferer
21
+ from monai.transforms import Transform, reset_ops_id
22
+ from monai.utils import ForwardMode, IgniteInfo, RankFilter, min_version, optional_import
23
+ from monai.utils.enums import CommonKeys as Keys
24
+ from torch.utils.data import DataLoader
25
+
26
+ rearrange, _ = optional_import("einops", name="rearrange")
27
+
28
+ if TYPE_CHECKING:
29
+ from ignite.engine import Engine, EventEnum
30
+ from ignite.metrics import Metric
31
+ else:
32
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
33
+ Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric")
34
+ EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum")
35
+
36
+ __all__ = ["Vista3dEvaluator"]
37
+
38
+
39
+ class Vista3dEvaluator(SupervisedEvaluator):
40
+ """
41
+ Supervised detection evaluation method with image and label, inherits from ``SupervisedEvaluator`` and ``Workflow``.
42
+ Args:
43
+ device: an object representing the device on which to run.
44
+ val_data_loader: Ignite engine use data_loader to run, must be Iterable, typically be torch.DataLoader.
45
+ network: detector to evaluate in the evaluator, should be regular PyTorch `torch.nn.Module`.
46
+ epoch_length: number of iterations for one epoch, default to `len(val_data_loader)`.
47
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
48
+ with respect to the host. For other cases, this argument has no effect.
49
+ prepare_batch: function to parse expected data (usually `image`, `label` and other network args)
50
+ from `engine.state.batch` for every iteration, for more details please refer to:
51
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
52
+ iteration_update: the callable function for every iteration, expect to accept `engine`
53
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
54
+ if not provided, use `self._iteration()` instead. for more details please refer to:
55
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
56
+ inferer: inference method that execute model forward on input data, like: SlidingWindow, etc.
57
+ postprocessing: execute additional transformation for the model output data.
58
+ Typically, several Tensor based transforms composed by `Compose`.
59
+ key_val_metric: compute metric when every iteration completed, and save average value to
60
+ engine.state.metrics when epoch completed. key_val_metric is the main metric to compare and save the
61
+ checkpoint into files.
62
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
63
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
64
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
65
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
66
+ val_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
67
+ CheckpointHandler, StatsHandler, etc.
68
+ amp: whether to enable auto-mixed-precision evaluation, default is False.
69
+ mode: model forward mode during evaluation, should be 'eval' or 'train',
70
+ which maps to `model.eval()` or `model.train()`, default to 'eval'.
71
+ event_names: additional custom ignite events that will register to the engine.
72
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
73
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
74
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
75
+ #ignite.engine.engine.Engine.register_events.
76
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
77
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
78
+ default to `True`.
79
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
80
+ `device`, `non_blocking`.
81
+ amp_kwargs: dict of the args for `torch.amp.autocast()` API, for more details:
82
+ https://pytorch.org/docs/stable/amp.html#torch.amp.autocast.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ device: torch.device,
88
+ val_data_loader: Iterable | DataLoader,
89
+ network: torch.nn.Module,
90
+ epoch_length: int | None = None,
91
+ non_blocking: bool = False,
92
+ prepare_batch: Callable = default_prepare_batch,
93
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
94
+ inferer: Inferer | None = None,
95
+ postprocessing: Transform | None = None,
96
+ key_val_metric: dict[str, Metric] | None = None,
97
+ additional_metrics: dict[str, Metric] | None = None,
98
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
99
+ val_handlers: Sequence | None = None,
100
+ amp: bool = False,
101
+ mode: ForwardMode | str = ForwardMode.EVAL,
102
+ event_names: list[str | EventEnum | type[EventEnum]] | None = None,
103
+ event_to_attr: dict | None = None,
104
+ decollate: bool = True,
105
+ to_kwargs: dict | None = None,
106
+ amp_kwargs: dict | None = None,
107
+ hyper_kwargs: dict | None = None,
108
+ ) -> None:
109
+ super().__init__(
110
+ device=device,
111
+ val_data_loader=val_data_loader,
112
+ network=network,
113
+ epoch_length=epoch_length,
114
+ non_blocking=non_blocking,
115
+ prepare_batch=prepare_batch,
116
+ iteration_update=iteration_update,
117
+ postprocessing=postprocessing,
118
+ key_val_metric=key_val_metric,
119
+ additional_metrics=additional_metrics,
120
+ metric_cmp_fn=metric_cmp_fn,
121
+ val_handlers=val_handlers,
122
+ amp=amp,
123
+ mode=mode,
124
+ event_names=event_names,
125
+ event_to_attr=event_to_attr,
126
+ decollate=decollate,
127
+ to_kwargs=to_kwargs,
128
+ amp_kwargs=amp_kwargs,
129
+ )
130
+
131
+ self.network = network
132
+ self.device = device
133
+ self.inferer = SimpleInferer() if inferer is None else inferer
134
+ self.hyper_kwargs = hyper_kwargs
135
+ self.logger.addFilter(RankFilter())
136
+
137
+ def transform_points(self, point, affine):
138
+ """transform point to the coordinates of the transformed image
139
+ point: numpy array [bs, N, 3]
140
+ """
141
+ bs, n = point.shape[:2]
142
+ point = np.concatenate((point, np.ones((bs, n, 1))), axis=-1)
143
+ point = rearrange(point, "b n d -> d (b n)")
144
+ point = affine @ point
145
+ point = rearrange(point, "d (b n)-> b n d", b=bs)[:, :, :3]
146
+ return point
147
+
148
+ def check_prompts_format(self, label_prompt, points, point_labels):
149
+ """check the format of user prompts
150
+ label_prompt: [1,2,3,4,...,B] List of tensors
151
+ points: [[[x,y,z], [x,y,z], ...]] List of coordinates of a single object
152
+ point_labels: [[1,1,0,...]] List of scalar that matches number of points
153
+ """
154
+ # check prompt is given
155
+ if label_prompt is None and points is None:
156
+ everything_labels = self.hyper_kwargs.get("everything_labels", None)
157
+ if everything_labels is not None:
158
+ label_prompt = [torch.tensor(_) for _ in everything_labels]
159
+ return label_prompt, points, point_labels
160
+ else:
161
+ raise ValueError("Prompt must be given for inference.")
162
+ # check label_prompt
163
+ if label_prompt is not None:
164
+ if isinstance(label_prompt, list):
165
+ if not np.all([len(_) == 1 for _ in label_prompt]):
166
+ raise ValueError("Label prompt must be a list of single scalar, [1,2,3,4,...,].")
167
+ if not np.all([(x < 255).item() for x in label_prompt]):
168
+ raise ValueError("Current bundle only supports label prompt smaller than 255.")
169
+ if points is None:
170
+ supported_list = list({i + 1 for i in range(132)} - {16, 18, 129, 130, 131})
171
+ if not np.all([x in supported_list for x in label_prompt]):
172
+ raise ValueError("Undefined label prompt detected. Provide point prompts for zero-shot.")
173
+ else:
174
+ raise ValueError("Label prompt must be a list, [1,2,3,4,...,].")
175
+ # check points
176
+ if points is not None:
177
+ if point_labels is None:
178
+ raise ValueError("Point labels must be given if points are given.")
179
+ if not np.all([len(_) == 3 for _ in points]):
180
+ raise ValueError("Points must be three dimensional (x,y,z) in the shape of [[x,y,z],...,[x,y,z]].")
181
+ if len(points) != len(point_labels):
182
+ raise ValueError("Points must match point labels.")
183
+ if not np.all([_ in [-1, 0, 1, 2, 3] for _ in point_labels]):
184
+ raise ValueError("Point labels can only be -1,0,1 and 2,3 for special flags.")
185
+ if label_prompt is not None and points is not None:
186
+ if len(label_prompt) != 1:
187
+ raise ValueError("Label prompt can only be a single object if provided with point prompts.")
188
+ # check point_labels
189
+ if point_labels is not None:
190
+ if points is None:
191
+ raise ValueError("Points must be given if point labels are given.")
192
+ return label_prompt, points, point_labels
193
+
194
+ def _iteration(self, engine: SupervisedEvaluator, batchdata: dict[str, torch.Tensor]) -> dict:
195
+ """
196
+ callback function for the Supervised Evaluation processing logic of 1 iteration in Ignite Engine.
197
+ Return below items in a dictionary:
198
+ - IMAGE: image Tensor data for model input, already moved to device.
199
+ - LABEL: label Tensor data corresponding to the image, already moved to device.
200
+ - PRED: prediction result of model.
201
+
202
+ Args:
203
+ engine: `SupervisedEvaluator` to execute operation for an iteration.
204
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
205
+
206
+ Raises:
207
+ ValueError: When ``batchdata`` is None.
208
+
209
+ """
210
+ if batchdata is None:
211
+ raise ValueError("Must provide batch data for current iteration.")
212
+ label_set = engine.hyper_kwargs.get("label_set", None)
213
+ # this validation label set should be consistent with 'labels.unique()', used to generate fg/bg points
214
+ val_label_set = engine.hyper_kwargs.get("val_label_set", label_set)
215
+ # If user provide prompts in the inference, input image must contain original affine.
216
+ # the point coordinates are from the original_affine space, while image here is after preprocess transforms.
217
+ if engine.hyper_kwargs["user_prompt"]:
218
+ inputs, label_prompt, points, point_labels = (
219
+ batchdata["image"],
220
+ batchdata.get("label_prompt", None),
221
+ batchdata.get("points", None),
222
+ batchdata.get("point_labels", None),
223
+ )
224
+ labels = None
225
+ label_prompt, points, point_labels = self.check_prompts_format(label_prompt, points, point_labels)
226
+ inputs = inputs.to(engine.device)
227
+ # For N foreground object, label_prompt is [1, N], but the batch number 1 needs to be removed. Convert to [N, 1]
228
+ label_prompt = (
229
+ torch.as_tensor([label_prompt]).to(inputs.device)[0].unsqueeze(-1) if label_prompt is not None else None
230
+ )
231
+ # For points, the size can only be [1, K, 3], where K is the number of points for this single foreground object.
232
+ if points is not None:
233
+ points = torch.as_tensor([points])
234
+ points = self.transform_points(
235
+ points, np.linalg.inv(inputs.affine[0]) @ inputs.meta["original_affine"][0].numpy()
236
+ )
237
+ points = torch.from_numpy(points).to(inputs.device)
238
+ point_labels = torch.as_tensor([point_labels]).to(inputs.device) if point_labels is not None else None
239
+
240
+ # If validation with ground truth label available.
241
+ else:
242
+ inputs, labels = engine.prepare_batch(
243
+ batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs
244
+ )
245
+ # create label prompt, this should be consistent with the label prompt used for training.
246
+ if label_set is None:
247
+ output_classes = engine.hyper_kwargs["output_classes"]
248
+ label_set = np.arange(output_classes).tolist()
249
+ label_prompt = torch.tensor(label_set).to(engine.state.device).unsqueeze(-1)
250
+ # point prompt is generated withing vista3d, provide empty points
251
+ points = torch.zeros(label_prompt.shape[0], 1, 3).to(inputs.device)
252
+ point_labels = -1 + torch.zeros(label_prompt.shape[0], 1).to(inputs.device)
253
+ # validation for either auto or point.
254
+ if engine.hyper_kwargs.get("val_head", "auto") == "auto":
255
+ # automatic only validation
256
+ # remove val_label_set, vista3d will not sample points from gt labels.
257
+ val_label_set = None
258
+ else:
259
+ # point only validation
260
+ label_prompt = None
261
+
262
+ # put iteration outputs into engine.state
263
+ engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: labels}
264
+ # execute forward computation
265
+ with engine.mode(engine.network):
266
+ if engine.amp:
267
+ with torch.amp.autocast("cuda", **engine.amp_kwargs):
268
+ engine.state.output[Keys.PRED] = engine.inferer(
269
+ inputs=inputs,
270
+ network=engine.network,
271
+ point_coords=points,
272
+ point_labels=point_labels,
273
+ class_vector=label_prompt,
274
+ labels=labels,
275
+ label_set=val_label_set,
276
+ )
277
+ else:
278
+ engine.state.output[Keys.PRED] = engine.inferer(
279
+ inputs=inputs,
280
+ network=engine.network,
281
+ point_coords=points,
282
+ point_labels=point_labels,
283
+ class_vector=label_prompt,
284
+ labels=labels,
285
+ label_set=val_label_set,
286
+ )
287
+ inputs = reset_ops_id(inputs)
288
+ # Add dim 0 for decollate batch
289
+ engine.state.output["label_prompt"] = label_prompt.unsqueeze(0) if label_prompt is not None else None
290
+ engine.state.output["points"] = points.unsqueeze(0) if points is not None else None
291
+ engine.state.output["point_labels"] = point_labels.unsqueeze(0) if point_labels is not None else None
292
+ engine.fire_event(IterationEvents.FORWARD_COMPLETED)
293
+ engine.fire_event(IterationEvents.MODEL_COMPLETED)
294
+ if torch.cuda.is_available():
295
+ torch.cuda.empty_cache()
296
+
297
+ return engine.state.output
scripts/inferer.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ import copy
13
+ from typing import List, Union
14
+
15
+ import torch
16
+ from monai.apps.vista3d.inferer import point_based_window_inferer
17
+ from monai.inferers import Inferer, SlidingWindowInfererAdapt
18
+ from torch import Tensor
19
+
20
+
21
+ class Vista3dInferer(Inferer):
22
+ """
23
+ Vista3D Inferer
24
+
25
+ Args:
26
+ roi_size: the sliding window patch size.
27
+ overlap: sliding window overlap ratio.
28
+ """
29
+
30
+ def __init__(self, roi_size, overlap, use_point_window=False, sw_batch_size=1) -> None:
31
+ Inferer.__init__(self)
32
+ self.roi_size = roi_size
33
+ self.overlap = overlap
34
+ self.sw_batch_size = sw_batch_size
35
+ self.use_point_window = use_point_window
36
+
37
+ def __call__(
38
+ self,
39
+ inputs: Union[List[Tensor], Tensor],
40
+ network,
41
+ point_coords,
42
+ point_labels,
43
+ class_vector,
44
+ labels=None,
45
+ label_set=None,
46
+ prev_mask=None,
47
+ ):
48
+ """
49
+ Unified callable function API of Inferers.
50
+ Notice: The point_based_window_inferer currently only supports SINGLE OBJECT INFERENCE with B=1.
51
+ It only used in interactive segmentation.
52
+
53
+ Args:
54
+ inputs: input tensor images.
55
+ network: vista3d model.
56
+ point_coords: point click coordinates. [B, N, 3].
57
+ point_labels: point click labels (0 for negative, 1 for positive) [B, N].
58
+ class_vector: class vector of length B.
59
+ labels: groundtruth labels. Used for sampling validation points.
60
+ label_set: [0,1,2,3,...,output_classes].
61
+ prev_mask: [1, B, H, W, D], THE VALUE IS BEFORE SIGMOID!
62
+
63
+ """
64
+ prompt_class = copy.deepcopy(class_vector)
65
+ if class_vector is not None and (point_labels is not None and torch.any(point_labels != -1)):
66
+ # Only when user perform zero-shot interactive during inference. Remove the class vector
67
+ # and keep the prompt_class to inform the model about the zero-shot. During finetuning,
68
+ # a novel class > last_supported is possible and should be taken care of.
69
+ # This check should be moved to evaluator and prompt_class should be added as input to the inferer.
70
+ if hasattr(network, "point_head"):
71
+ point_head = network.point_head
72
+ elif hasattr(network, "module") and hasattr(network.module, "point_head"):
73
+ point_head = network.module.point_head
74
+ else:
75
+ raise AttributeError("Network does not have attribute 'point_head'.")
76
+
77
+ if torch.any(class_vector > point_head.last_supported):
78
+ class_vector = None
79
+ val_outputs = None
80
+ torch.cuda.empty_cache()
81
+ if self.use_point_window and point_coords is not None:
82
+ if isinstance(inputs, list):
83
+ device = inputs[0].device
84
+ else:
85
+ device = inputs.device
86
+ val_outputs = point_based_window_inferer(
87
+ inputs=inputs,
88
+ roi_size=self.roi_size,
89
+ sw_batch_size=self.sw_batch_size,
90
+ transpose=True,
91
+ with_coord=True,
92
+ predictor=network,
93
+ mode="gaussian",
94
+ sw_device=device,
95
+ device=device,
96
+ overlap=self.overlap,
97
+ point_coords=point_coords,
98
+ point_labels=point_labels,
99
+ class_vector=class_vector,
100
+ prompt_class=prompt_class,
101
+ prev_mask=prev_mask,
102
+ labels=labels,
103
+ label_set=label_set,
104
+ )
105
+ else:
106
+ val_outputs = SlidingWindowInfererAdapt(
107
+ roi_size=self.roi_size, sw_batch_size=self.sw_batch_size, with_coord=True, padding_mode="replicate"
108
+ )(
109
+ inputs,
110
+ network,
111
+ transpose=True,
112
+ point_coords=point_coords,
113
+ point_labels=point_labels,
114
+ class_vector=class_vector,
115
+ prompt_class=prompt_class,
116
+ prev_mask=prev_mask,
117
+ labels=labels,
118
+ label_set=label_set,
119
+ )
120
+ return val_outputs
scripts/trainer.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) MONAI Consortium
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ # http://www.apache.org/licenses/LICENSE-2.0
6
+ # Unless required by applicable law or agreed to in writing, software
7
+ # distributed under the License is distributed on an "AS IS" BASIS,
8
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
+ # See the License for the specific language governing permissions and
10
+ # limitations under the License.
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Sequence
15
+
16
+ import numpy as np
17
+ import torch
18
+ from monai.apps.vista3d.sampler import sample_prompt_pairs
19
+ from monai.engines.trainer import Trainer
20
+ from monai.engines.utils import IterationEvents, default_metric_cmp_fn, default_prepare_batch
21
+ from monai.inferers import Inferer, SimpleInferer
22
+ from monai.transforms import Transform
23
+ from monai.utils import IgniteInfo, RankFilter, min_version, optional_import
24
+ from monai.utils.enums import CommonKeys as Keys
25
+ from torch.optim.optimizer import Optimizer
26
+ from torch.utils.data import DataLoader
27
+
28
+ if TYPE_CHECKING:
29
+ from ignite.engine import Engine, EventEnum
30
+ from ignite.metrics import Metric
31
+ else:
32
+ Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine")
33
+ Metric, _ = optional_import("ignite.metrics", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Metric")
34
+ EventEnum, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "EventEnum")
35
+
36
+ __all__ = ["Vista3dTrainer"]
37
+
38
+
39
+ class Vista3dTrainer(Trainer):
40
+ """
41
+ Supervised detection training method with image and label, inherits from ``Trainer`` and ``Workflow``.
42
+ Args:
43
+ device: an object representing the device on which to run.
44
+ max_epochs: the total epoch number for trainer to run.
45
+ train_data_loader: Ignite engine use data_loader to run, must be Iterable or torch.DataLoader.
46
+ detector: detector to train in the trainer, should be regular PyTorch `torch.nn.Module`.
47
+ optimizer: the optimizer associated to the detector, should be regular PyTorch optimizer from `torch.optim`
48
+ or its subclass.
49
+ epoch_length: number of iterations for one epoch, default to `len(train_data_loader)`.
50
+ non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
51
+ with respect to the host. For other cases, this argument has no effect.
52
+ prepare_batch: function to parse expected data (usually `image`,`box`, `label` and other detector args)
53
+ from `engine.state.batch` for every iteration, for more details please refer to:
54
+ https://pytorch.org/ignite/generated/ignite.engine.create_supervised_trainer.html.
55
+ iteration_update: the callable function for every iteration, expect to accept `engine`
56
+ and `engine.state.batch` as inputs, return data will be stored in `engine.state.output`.
57
+ if not provided, use `self._iteration()` instead. for more details please refer to:
58
+ https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html.
59
+ inferer: inference method that execute model forward on input data, like: SlidingWindow, etc.
60
+ postprocessing: execute additional transformation for the model output data.
61
+ Typically, several Tensor based transforms composed by `Compose`.
62
+ key_train_metric: compute metric when every iteration completed, and save average value to
63
+ engine.state.metrics when epoch completlabel_set = np.arange(output_classes).tolist().
64
+ key_train_metric is the main metric to compare and save the checkpoint into files.
65
+ additional_metrics: more Ignite metrics that also attach to Ignite Engine.
66
+ metric_cmp_fn: function to compare current key metric with previous best key metric value,
67
+ it must accept 2 args (current_metric, previous_best) and return a bool result: if `True`, will update
68
+ `best_metric` and `best_metric_epoch` with current metric and epoch, default to `greater than`.
69
+ train_handlers: every handler is a set of Ignite Event-Handlers, must have `attach` function, like:
70
+ CheckpointHandler, StatsHandler, etc.
71
+ amp: whether to enable auto-mixed-precision training, default is False.
72
+ event_names: additional custom ignite events that will register to the engine.
73
+ new events can be a list of str or `ignite.engine.events.EventEnum`.
74
+ event_to_attr: a dictionary to map an event to a state attribute, then add to `engine.state`.
75
+ for more details, check: https://pytorch.org/ignite/generated/ignite.engine.engine.Engine.html
76
+ #ignite.engine.engine.Engine.register_events.
77
+ decollate: whether to decollate the batch-first data to a list of data after model computation,
78
+ recommend `decollate=True` when `postprocessing` uses components from `monai.transforms`.
79
+ default to `True`.
80
+ optim_set_to_none: when calling `optimizer.zero_grad()`, instead of setting to zero, set the grads to None.
81
+ more details: https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html.
82
+ to_kwargs: dict of other args for `prepare_batch` API when converting the input data, except for
83
+ `device`, `non_blocking`.
84
+ amp_kwargs: dict of the args for `torch.amp.autocast()` API, for more details:
85
+ https://pytorch.org/docs/stable/amp.html#torch.amp.autocast.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ device: torch.device,
91
+ max_epochs: int,
92
+ train_data_loader: Iterable | DataLoader,
93
+ network: torch.nn.Module,
94
+ optimizer: Optimizer,
95
+ loss_function: Callable,
96
+ epoch_length: int | None = None,
97
+ non_blocking: bool = False,
98
+ prepare_batch: Callable = default_prepare_batch,
99
+ iteration_update: Callable[[Engine, Any], Any] | None = None,
100
+ inferer: Inferer | None = None,
101
+ postprocessing: Transform | None = None,
102
+ key_train_metric: dict[str, Metric] | None = None,
103
+ additional_metrics: dict[str, Metric] | None = None,
104
+ metric_cmp_fn: Callable = default_metric_cmp_fn,
105
+ train_handlers: Sequence | None = None,
106
+ amp: bool = False,
107
+ event_names: list[str | EventEnum] | None = None,
108
+ event_to_attr: dict | None = None,
109
+ decollate: bool = True,
110
+ optim_set_to_none: bool = False,
111
+ to_kwargs: dict | None = None,
112
+ amp_kwargs: dict | None = None,
113
+ hyper_kwargs: dict | None = None,
114
+ ) -> None:
115
+ super().__init__(
116
+ device=device,
117
+ max_epochs=max_epochs,
118
+ data_loader=train_data_loader,
119
+ epoch_length=epoch_length,
120
+ non_blocking=non_blocking,
121
+ prepare_batch=prepare_batch,
122
+ iteration_update=iteration_update,
123
+ postprocessing=postprocessing,
124
+ key_metric=key_train_metric,
125
+ additional_metrics=additional_metrics,
126
+ metric_cmp_fn=metric_cmp_fn,
127
+ handlers=train_handlers,
128
+ amp=amp,
129
+ event_names=event_names,
130
+ event_to_attr=event_to_attr,
131
+ decollate=decollate,
132
+ to_kwargs=to_kwargs,
133
+ amp_kwargs=amp_kwargs,
134
+ )
135
+
136
+ self.network = network
137
+ self.optimizer = optimizer
138
+ self.loss_function = loss_function
139
+ self.inferer = SimpleInferer() if inferer is None else inferer
140
+ self.optim_set_to_none = optim_set_to_none
141
+ self.hyper_kwargs = hyper_kwargs
142
+ self.logger.addFilter(RankFilter())
143
+
144
+ def _iteration(self, engine, batchdata: dict[str, torch.Tensor]):
145
+ """
146
+ Callback function for the Supervised Training processing logic of 1 iteration in Ignite Engine.
147
+ Return below items in a dictionary:
148
+ - IMAGE: image Tensor data for model input, already moved to device.
149
+ Args:
150
+ engine: `Vista3DTrainer` to execute operation for an iteration.
151
+ batchdata: input data for this iteration, usually can be dictionary or tuple of Tensor data.
152
+ Raises:
153
+ ValueError: When ``batchdata`` is None.
154
+ """
155
+
156
+ if batchdata is None:
157
+ raise ValueError("Must provide batch data for current iteration.")
158
+
159
+ inputs, labels = engine.prepare_batch(batchdata, engine.state.device, engine.non_blocking, **engine.to_kwargs)
160
+ engine.state.output = {Keys.IMAGE: inputs, Keys.LABEL: labels}
161
+
162
+ label_set = engine.hyper_kwargs["label_set"]
163
+ output_classes = engine.hyper_kwargs["output_classes"]
164
+ if label_set is None:
165
+ label_set = np.arange(output_classes).tolist()
166
+ label_prompt, point, point_label, prompt_class = sample_prompt_pairs(
167
+ labels,
168
+ label_set,
169
+ image_size=engine.hyper_kwargs["patch_size"],
170
+ max_point=engine.hyper_kwargs["max_point"],
171
+ max_prompt=engine.hyper_kwargs["max_prompt"],
172
+ max_backprompt=engine.hyper_kwargs["max_backprompt"],
173
+ max_foreprompt=engine.hyper_kwargs["max_foreprompt"],
174
+ drop_label_prob=engine.hyper_kwargs["drop_label_prob"],
175
+ drop_point_prob=engine.hyper_kwargs["drop_point_prob"],
176
+ include_background=not engine.hyper_kwargs["exclude_background"],
177
+ )
178
+
179
+ def _compute_pred_loss():
180
+ outputs = engine.network(
181
+ input_images=inputs, point_coords=point, point_labels=point_label, class_vector=label_prompt
182
+ )
183
+ # engine.state.output[Keys.PRED] = outputs
184
+ engine.fire_event(IterationEvents.FORWARD_COMPLETED)
185
+ loss, loss_n = torch.tensor(0.0, device=engine.state.device), torch.tensor(0.0, device=engine.state.device)
186
+ for id in range(len(prompt_class)):
187
+ loss += engine.loss_function(outputs[[id]].float(), labels == prompt_class[id])
188
+ loss_n += 1.0
189
+ loss /= max(loss_n, 1.0)
190
+ engine.state.output[Keys.LOSS] = loss
191
+ outputs = None
192
+ torch.cuda.empty_cache()
193
+ engine.fire_event(IterationEvents.LOSS_COMPLETED)
194
+
195
+ engine.network.train()
196
+ engine.optimizer.zero_grad(set_to_none=engine.optim_set_to_none)
197
+
198
+ if engine.amp and engine.scaler is not None:
199
+ with torch.amp.autocast("cuda", **engine.amp_kwargs):
200
+ _compute_pred_loss()
201
+ engine.scaler.scale(engine.state.output[Keys.LOSS]).backward()
202
+ engine.fire_event(IterationEvents.BACKWARD_COMPLETED)
203
+ engine.scaler.step(engine.optimizer)
204
+ engine.scaler.update()
205
+ else:
206
+ _compute_pred_loss()
207
+ engine.state.output[Keys.LOSS].backward()
208
+ engine.fire_event(IterationEvents.BACKWARD_COMPLETED)
209
+ engine.optimizer.step()
210
+ engine.fire_event(IterationEvents.MODEL_COMPLETED)
211
+ return engine.state.output
vista3d_config.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class VISTA3DConfig(PretrainedConfig):
5
+ """Configuration class for vista3d"""
6
+
7
+ model_type = "VISTA3D"
8
+
9
+ def __init__(self, encoder_embed_dim: int = 48, input_channels: int = 1, **kwargs):
10
+ """
11
+ Set the hyperparameters for the VISTA3D model.
12
+
13
+ Parameters:
14
+ input_channels: channel of input images.
15
+ encoder_embed_dim: the encoder_embed_dim of the VISTA3D model.
16
+ """
17
+ self.input_channels = input_channels
18
+ self.encoder_embed_dim = encoder_embed_dim
19
+ super().__init__(**kwargs)
vista3d_model.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import monai.networks.nets
4
+ import torch
5
+ from transformers import AutoConfig, AutoModel, PreTrainedModel
6
+ from vista3d_config import VISTA3DConfig
7
+
8
+
9
+ class VISTA3DModel(PreTrainedModel):
10
+ """VISTA3D model for hugging face"""
11
+
12
+ config_class = VISTA3DConfig
13
+
14
+ def __init__(self, config):
15
+ super().__init__(config)
16
+ if config.model_type == "VISTA3D":
17
+ self.network = monai.networks.nets.vista3d132(
18
+ encoder_embed_dim=config.encoder_embed_dim,
19
+ in_channels=config.input_channels,
20
+ )
21
+
22
+ def forward(self, input):
23
+ return self.network(input)
24
+
25
+
26
+ def register_my_model():
27
+ """Utility function to register VISTA3D model so that it can be instantiate by the AutoModel function."""
28
+ AutoConfig.register("VISTA3D", VISTA3DConfig)
29
+ AutoModel.register(VISTA3DConfig, VISTA3DModel)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ FILE_PATH = os.path.dirname(__file__)
34
+ MODEL_WEIGHT_PATH = os.path.join(FILE_PATH, "models/model.pt")
35
+ MODEL_PATH = os.path.join(FILE_PATH, "vista3d_pretrained_model")
36
+ config = VISTA3DConfig()
37
+ hugging_face_model = VISTA3DModel(config)
38
+ hugging_face_model.network.load_state_dict(torch.load(MODEL_WEIGHT_PATH))
39
+ hugging_face_model.save_pretrained(MODEL_PATH)
vista3d_pipeline.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import logging
4
+ import os
5
+ import pathlib
6
+ from typing import Sequence
7
+
8
+ import numpy as np
9
+ import torch
10
+ from monai.apps.vista3d.transforms import VistaPostTransformd, VistaPreTransformd
11
+ from monai.data.utils import decollate_batch, list_data_collate
12
+ from monai.networks.utils import eval_mode, train_mode
13
+ from monai.transforms import (
14
+ CastToTyped,
15
+ Compose,
16
+ CropForegroundd,
17
+ EnsureChannelFirstd,
18
+ EnsureTyped,
19
+ Invertd,
20
+ Lambdad,
21
+ LoadImaged,
22
+ Orientationd,
23
+ SaveImaged,
24
+ ScaleIntensityRanged,
25
+ Spacingd,
26
+ reset_ops_id,
27
+ )
28
+ from monai.utils import ForwardMode, optional_import, set_determinism
29
+ from monai.utils.enums import CommonKeys as Keys
30
+ from monai.utils.module import look_up_option
31
+ from scripts.inferer import Vista3dInferer
32
+ from transformers import AutoModel, Pipeline
33
+ from transformers.pipelines import PIPELINE_REGISTRY
34
+
35
+ rearrange, _ = optional_import("einops", name="rearrange")
36
+
37
+ FILE_PATH = os.path.dirname(__file__)
38
+
39
+
40
+ logging.basicConfig(
41
+ level=logging.INFO,
42
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
43
+ datefmt="%Y-%m-%d %H:%M:%S",
44
+ )
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ class VISTA3DPipeline(Pipeline):
49
+ """Define the VISTA3D pipeline."""
50
+
51
+ PREPROCESSING_EXTRA_ARGS = [
52
+ "image_key",
53
+ "resample_spacing",
54
+ "metadata_path",
55
+ "load_image",
56
+ ]
57
+ INFERENCE_EXTRA_ARGS = [
58
+ "mode",
59
+ "amp",
60
+ "hyper_kwargs",
61
+ "roi_size",
62
+ "overlap",
63
+ "sw_batch_size",
64
+ "use_point_window",
65
+ ]
66
+ POSTPROCESSING_EXTRA_ARGS = [
67
+ "pred_key",
68
+ "image_key",
69
+ "output_dir",
70
+ "output_ext",
71
+ "output_postfix",
72
+ "separate_folder",
73
+ "save_output",
74
+ ]
75
+ EVERYTHING_LABEL = list(
76
+ set([i + 1 for i in range(132)])
77
+ - set([2, 16, 18, 20, 21, 23, 24, 25, 26, 27, 128, 129, 130, 131, 132])
78
+ )
79
+
80
+ def __init__(self, model, **kwargs):
81
+ super().__init__(model, **kwargs)
82
+ self.preprocessing_transforms = self._init_preprocessing_transforms(
83
+ **self._preprocess_params
84
+ )
85
+ self.inferer = self._init_inferer(**self._forward_params)
86
+ self.postprocessing_transforms = self._init_postprocessing_transforms(
87
+ **self._postprocess_params
88
+ )
89
+
90
+ def _init_inferer(
91
+ self,
92
+ roi_size: Sequence = (128, 128, 128),
93
+ overlap: float = 0.3,
94
+ sw_batch_size: int = 1,
95
+ use_point_window: bool = True,
96
+ ):
97
+ return Vista3dInferer(
98
+ roi_size=roi_size,
99
+ overlap=overlap,
100
+ use_point_window=use_point_window,
101
+ sw_batch_size=sw_batch_size,
102
+ )
103
+
104
+ def _init_preprocessing_transforms(
105
+ self,
106
+ image_key: str = "image",
107
+ resample_spacing: Sequence = (1.5, 1.5, 1.5),
108
+ metadata_path: str = os.path.join(FILE_PATH, "metadata.json"),
109
+ load_image: bool = True,
110
+ ):
111
+ device = self.device
112
+ subclass = {
113
+ "2": [14, 5],
114
+ "20": [28, 29, 30, 31, 32],
115
+ "21": list(range(33, 57)) + list(range(63, 98)) + [114, 120, 122],
116
+ }
117
+ metadata = json.loads(pathlib.Path(metadata_path).read_text())
118
+ labels_dict = metadata["network_data_format"]["outputs"]["pred"]["channel_def"]
119
+ preprocessing_list = [
120
+ LoadImaged(keys=image_key, image_only=True),
121
+ EnsureChannelFirstd(keys=image_key),
122
+ EnsureTyped(keys=image_key, device=device, track_meta=True),
123
+ Spacingd(keys=image_key, pixdim=resample_spacing, mode="bilinear"),
124
+ CropForegroundd(
125
+ keys=image_key, allow_smaller=True, margin=10, source_key=image_key
126
+ ),
127
+ VistaPreTransformd(
128
+ keys=image_key, subclass=subclass, labels_dict=labels_dict
129
+ ),
130
+ ScaleIntensityRanged(
131
+ keys=image_key,
132
+ a_min=-963.8247715525971,
133
+ a_max=1053.678477684517,
134
+ b_min=0,
135
+ b_max=1,
136
+ clip=True,
137
+ ),
138
+ Orientationd(keys=image_key, axcodes="RAS"),
139
+ CastToTyped(keys=image_key, dtype=torch.float32),
140
+ ]
141
+ if not load_image:
142
+ preprocessing_list.pop(0)
143
+
144
+ preprocessing_transforms = Compose(preprocessing_list)
145
+ return preprocessing_transforms
146
+
147
+ def _init_postprocessing_transforms(
148
+ self,
149
+ pred_key: str = "pred",
150
+ image_key: str = "image",
151
+ output_dir: str = "output_directory",
152
+ output_ext: str = ".nii.gz",
153
+ output_dtype: torch.dtype = torch.float32,
154
+ output_postfix: str = "seg",
155
+ separate_folder: bool = True,
156
+ save_output: bool = True,
157
+ ):
158
+ transforms = [
159
+ VistaPostTransformd(keys=pred_key),
160
+ Invertd(
161
+ keys=pred_key,
162
+ transform=copy.deepcopy(self.preprocessing_transforms),
163
+ orig_keys=image_key,
164
+ nearest_interp=True,
165
+ to_tensor=True,
166
+ ),
167
+ Lambdad(keys=pred_key, func=lambda x: torch.nan_to_num(x, nan=255)),
168
+ ]
169
+ if save_output:
170
+ transforms.append(
171
+ SaveImaged(
172
+ keys=pred_key,
173
+ resample=False,
174
+ output_dir=output_dir,
175
+ output_ext=output_ext,
176
+ output_dtype=output_dtype,
177
+ output_postfix=output_postfix,
178
+ separate_folder=separate_folder,
179
+ ),
180
+ )
181
+ postprocessing_transforms = Compose(transforms=transforms)
182
+ return postprocessing_transforms
183
+
184
+ def _sanitize_parameters(self, **kwargs):
185
+ """
186
+ _sanitize_parameters exists to allow users to pass any parameters whenever they wish,
187
+ be it at initialization time pipeline(...., maybe_arg=4) or at call time pipe = pipeline(...); output = pipe(...., maybe_arg=4).
188
+ The returns of _sanitize_parameters are the 3 dicts of kwargs that will be passed directly to preprocess, _forward and postprocess.
189
+ Don't fill anything if the caller didn't call with any extra parameter. That allows to keep the default arguments in the function
190
+ definition which is always more “natural”."""
191
+
192
+ vista3d_preprocessing_kwargs = {}
193
+ vista3d_infer_kwargs = {}
194
+ vista3d_postprocessing_kwargs = {}
195
+ for key in self.INFERENCE_EXTRA_ARGS:
196
+ if key in kwargs:
197
+ vista3d_infer_kwargs[key] = kwargs[key]
198
+
199
+ for key in self.PREPROCESSING_EXTRA_ARGS:
200
+ if key in kwargs:
201
+ vista3d_preprocessing_kwargs[key] = kwargs[key]
202
+
203
+ for key in self.POSTPROCESSING_EXTRA_ARGS:
204
+ if key in kwargs:
205
+ vista3d_postprocessing_kwargs[key] = kwargs[key]
206
+
207
+ return (
208
+ vista3d_preprocessing_kwargs,
209
+ vista3d_infer_kwargs,
210
+ vista3d_postprocessing_kwargs,
211
+ )
212
+
213
+ def check_prompts_format(self, label_prompt, points, point_labels):
214
+ """check the format of user prompts
215
+ label_prompt: [1,2,3,4,...,B] List of tensors
216
+ points: [[[x,y,z], [x,y,z], ...]] List of coordinates of a single object
217
+ point_labels: [[1,1,0,...]] List of scalar that matches number of points
218
+ """
219
+ # check prompt is given
220
+ if label_prompt is None and points is None:
221
+ everything_labels = self.hyper_kwargs.get("everything_labels", None)
222
+ if everything_labels is not None:
223
+ label_prompt = [torch.tensor(_) for _ in everything_labels]
224
+ return label_prompt, points, point_labels
225
+ else:
226
+ raise ValueError("Prompt must be given for inference.")
227
+ # check label_prompt
228
+ if label_prompt is not None:
229
+ if isinstance(label_prompt, list):
230
+ if not np.all([len(_) == 1 for _ in label_prompt]):
231
+ raise ValueError(
232
+ "Label prompt must be a list of single scalar, [1,2,3,4,...,]."
233
+ )
234
+ if isinstance(label_prompt[0], list):
235
+ for prompt in label_prompt:
236
+ if not np.all([(x < 255).item() for x in prompt]):
237
+ raise ValueError(
238
+ "Current bundle only supports label prompt smaller than 255."
239
+ )
240
+ else:
241
+ if not np.all([(x < 255).item() for x in label_prompt]):
242
+ raise ValueError(
243
+ "Current bundle only supports label prompt smaller than 255."
244
+ )
245
+ if points is None:
246
+ supported_list = list(
247
+ {i + 1 for i in range(132)} - {16, 18, 129, 130, 131}
248
+ )
249
+ if isinstance(label_prompt[0], list):
250
+ for prompt in label_prompt:
251
+ if not np.all([(x < 255).item() for x in prompt]):
252
+ raise ValueError(
253
+ "Current bundle only supports label prompt smaller than 255."
254
+ )
255
+ else:
256
+ if not np.all([x in supported_list for x in label_prompt]):
257
+ raise ValueError(
258
+ "Undefined label prompt detected. Provide point prompts for zero-shot."
259
+ )
260
+ else:
261
+ raise ValueError("Label prompt must be a list, [1,2,3,4,...,].")
262
+ # check points
263
+ if points is not None:
264
+ if point_labels is None:
265
+ raise ValueError("Point labels must be given if points are given.")
266
+ if not np.all([len(_) == 3 for _ in points]):
267
+ raise ValueError(
268
+ "Points must be three dimensional (x,y,z) in the shape of [[x,y,z],...,[x,y,z]]."
269
+ )
270
+ if len(points) != len(point_labels):
271
+ raise ValueError("Points must match point labels.")
272
+ if not np.all([_ in [-1, 0, 1, 2, 3] for _ in point_labels]):
273
+ raise ValueError(
274
+ "Point labels can only be -1,0,1 and 2,3 for special flags."
275
+ )
276
+ if label_prompt is not None and points is not None:
277
+ if len(label_prompt) != 1:
278
+ raise ValueError(
279
+ "Label prompt can only be a single object if provided with point prompts."
280
+ )
281
+ # check point_labels
282
+ if point_labels is not None:
283
+ if points is None:
284
+ raise ValueError("Points must be given if point labels are given.")
285
+ return label_prompt, points, point_labels
286
+
287
+ def transform_points(self, point, affine):
288
+ """transform point to the coordinates of the transformed image
289
+ point: numpy array [bs, N, 3]
290
+ """
291
+ bs, n = point.shape[:2]
292
+ point = np.concatenate((point, np.ones((bs, n, 1))), axis=-1)
293
+ point = rearrange(point, "b n d -> d (b n)")
294
+ point = affine @ point
295
+ point = rearrange(point, "d (b n)-> b n d", b=bs)[:, :, :3]
296
+ return point
297
+
298
+ def preprocess(
299
+ self,
300
+ inputs,
301
+ **kwargs,
302
+ ):
303
+ for key, value in kwargs.items():
304
+ if key in self._preprocess_params and value != self._preprocess_params[key]:
305
+ logging.warning(
306
+ f"Please set the parameter {key} during initialization."
307
+ )
308
+
309
+ if key not in self.PREPROCESSING_EXTRA_ARGS:
310
+ logging.warning(f"Cannot set parameter {key} for preprocessing.")
311
+ inputs = self.preprocessing_transforms(inputs)
312
+ inputs = list_data_collate([inputs])
313
+ return inputs
314
+
315
+ def _forward(
316
+ self,
317
+ inputs,
318
+ mode: str = ForwardMode.EVAL,
319
+ amp: bool = True,
320
+ hyper_kwargs: dict = {"user_prompt": 1, "everything_labels": 1},
321
+ ):
322
+ set_determinism(seed=123)
323
+
324
+ if inputs is None:
325
+ raise ValueError("Must provide input data for inference.")
326
+ self.hyper_kwargs = hyper_kwargs
327
+
328
+ label_set = hyper_kwargs.get("label_set", None)
329
+ # this validation label set should be consistent with 'labels.unique()', used to generate fg/bg points
330
+ val_label_set = hyper_kwargs.get("val_label_set", label_set)
331
+ # If user provide prompts in the inference, input image must contain original affine.
332
+ # the point coordinates are from the original_affine space, while image here is after preprocess transforms.
333
+ if hyper_kwargs["user_prompt"]:
334
+ inputs, label_prompt, points, point_labels = (
335
+ inputs["image"],
336
+ inputs.get("label_prompt", None),
337
+ inputs.get("points", None),
338
+ inputs.get("point_labels", None),
339
+ )
340
+ labels = None
341
+ label_prompt, points, point_labels = self.check_prompts_format(
342
+ label_prompt, points, point_labels
343
+ )
344
+ inputs = inputs.to(self.device)
345
+ # For N foreground object, label_prompt is [1, N], but the batch number 1 needs to be removed. Convert to [N, 1]
346
+ label_prompt = (
347
+ torch.as_tensor([label_prompt]).to(inputs.device)[0].unsqueeze(-1)
348
+ if label_prompt is not None
349
+ else None
350
+ )
351
+ # For points, the size can only be [1, K, 3], where K is the number of points for this single foreground object.
352
+ if points is not None:
353
+ points = torch.as_tensor([points])
354
+ points = self.transform_points(
355
+ points,
356
+ np.linalg.inv(inputs.affine[0])
357
+ @ inputs.meta["original_affine"][0].numpy(),
358
+ )
359
+ points = torch.from_numpy(points).to(inputs.device)
360
+ point_labels = (
361
+ torch.as_tensor([point_labels]).to(inputs.device)
362
+ if point_labels is not None
363
+ else None
364
+ )
365
+
366
+ # If validation with ground truth label available.
367
+ else:
368
+ # TODO add these as attribute.
369
+ inputs, labels = inputs["image"], inputs["label"]
370
+ # create label prompt, this should be consistent with the label prompt used for training.
371
+ if label_set is None:
372
+ output_classes = hyper_kwargs.get("output_classes", None)
373
+ label_set = np.arange(output_classes).tolist()
374
+ label_prompt = torch.tensor(label_set).to(self.device).unsqueeze(-1)
375
+ # point prompt is generated withing vista3d, provide empty points
376
+ points = torch.zeros(label_prompt.shape[0], 1, 3).to(inputs.device)
377
+ point_labels = -1 + torch.zeros(label_prompt.shape[0], 1).to(inputs.device)
378
+ # validation for either auto or point.
379
+ if hyper_kwargs.get("val_head", "auto") == "auto":
380
+ # automatic only validation
381
+ # remove val_label_set, vista3d will not sample points from gt labels.
382
+ val_label_set = None
383
+ else:
384
+ # point only validation
385
+ label_prompt = None
386
+
387
+ # put iteration outputs into outputs TODO need to align with the customized inputs
388
+ outputs = {Keys.IMAGE: inputs, Keys.LABEL: labels}
389
+ mode = look_up_option(mode, ForwardMode)
390
+ if mode == ForwardMode.EVAL:
391
+ mode = eval_mode
392
+ elif mode == ForwardMode.TRAIN:
393
+ mode = train_mode
394
+ else:
395
+ raise ValueError(f"unsupported mode: {mode}, should be 'eval' or 'train'.")
396
+
397
+ # execute forward computation
398
+ self.model.network.to(self.device)
399
+ with mode(self.model):
400
+ if amp:
401
+ with torch.autocast("cuda"):
402
+ outputs[Keys.PRED] = self.inferer(
403
+ inputs=inputs,
404
+ network=self.model.network,
405
+ point_coords=points,
406
+ point_labels=point_labels,
407
+ class_vector=label_prompt,
408
+ labels=labels,
409
+ label_set=val_label_set,
410
+ )
411
+ else:
412
+ outputs[Keys.PRED] = self.inferer(
413
+ inputs=inputs,
414
+ network=self.model.network,
415
+ point_coords=points,
416
+ point_labels=point_labels,
417
+ class_vector=label_prompt,
418
+ labels=labels,
419
+ label_set=val_label_set,
420
+ )
421
+ inputs = reset_ops_id(inputs)
422
+ # Add dim 0 for decollate batch
423
+ outputs["label_prompt"] = (
424
+ label_prompt.unsqueeze(0) if label_prompt is not None else None
425
+ )
426
+ outputs["points"] = points.unsqueeze(0) if points is not None else None
427
+ outputs["point_labels"] = (
428
+ point_labels.unsqueeze(0) if point_labels is not None else None
429
+ )
430
+ if torch.cuda.is_available():
431
+ torch.cuda.empty_cache()
432
+
433
+ return outputs
434
+
435
+ def postprocess(self, outputs, **kwargs):
436
+ outputs[Keys.IMAGE] = outputs[Keys.IMAGE].to(self.device)
437
+ outputs[Keys.PRED] = outputs[Keys.PRED].to(self.device)
438
+ for key, value in kwargs.items():
439
+ if key not in self.POSTPROCESSING_EXTRA_ARGS:
440
+ logging.warning(f"Cannot set parameter {key} for postprocessing.")
441
+ if (
442
+ key in self._postprocess_params
443
+ and value != self._postprocess_params[key]
444
+ ) or (key not in self._postprocess_params):
445
+ self._postprocess_params.update(kwargs)
446
+ self.postprocessing_transforms = self._init_postprocessing_transforms(
447
+ **self._postprocess_params
448
+ )
449
+
450
+ outputs = self.postprocessing_transforms(decollate_batch(outputs))
451
+ return outputs
452
+
453
+
454
+ def register_simple_pipeline():
455
+ PIPELINE_REGISTRY.register_pipeline(
456
+ "vista3d",
457
+ pipeline_class=VISTA3DPipeline,
458
+ pt_model=AutoModel,
459
+ default={"pt": (os.path.join(FILE_PATH, "vista3d_pretrained_model"), "")},
460
+ type="image", # current support type: text, audio, image, multimodal
461
+ )
vista3d_pretrained_model/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "VISTA3DModel"
4
+ ],
5
+ "encoder_embed_dim": 48,
6
+ "input_channels": 1,
7
+ "model_type": "VISTA3D",
8
+ "torch_dtype": "float32",
9
+ "transformers_version": "4.46.3"
10
+ }
vista3d_pretrained_model/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c92bab26d00b4a5d89fa8a383900cdeb88302fd318e5e816df0bbec7106d9a1b
3
+ size 871970895
vista3d_pretrained_model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:120ed013722a22780cc01b75cb5c18e4658d69879a983885abf8fa411c9f8f42
3
+ size 871894112