init version
Browse filesSigned-off-by: binliu <binliu@nvidia.com>
- .gitignore +164 -0
- LICENSE +247 -0
- README.md +76 -3
- __init__.py +0 -0
- data_license.txt +6 -0
- hugging_face_pipeline.py +38 -0
- metadata.json +227 -0
- scripts/__init__.py +15 -0
- scripts/early_stop_score_function.py +15 -0
- scripts/evaluator.py +297 -0
- scripts/inferer.py +122 -0
- scripts/trainer.py +211 -0
- vista3d_config.py +19 -0
- vista3d_model.py +38 -0
- vista3d_pipeline.py +454 -0
- vista3d_pretrained_model/config.json +10 -0
- vista3d_pretrained_model/model.safetensors +3 -0
.gitignore
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
*.egg-info/
|
24 |
+
.installed.cfg
|
25 |
+
*.egg
|
26 |
+
MANIFEST
|
27 |
+
|
28 |
+
# PyInstaller
|
29 |
+
# Usually these files are written by a python script from a template
|
30 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
31 |
+
*.manifest
|
32 |
+
*.spec
|
33 |
+
|
34 |
+
# Installer logs
|
35 |
+
pip-log.txt
|
36 |
+
pip-delete-this-directory.txt
|
37 |
+
|
38 |
+
# Unit test / coverage reports
|
39 |
+
htmlcov/
|
40 |
+
.tox/
|
41 |
+
.coverage
|
42 |
+
.coverage.*
|
43 |
+
.coverage/
|
44 |
+
.cache
|
45 |
+
nosetests.xml
|
46 |
+
coverage.xml
|
47 |
+
*.cover
|
48 |
+
.hypothesis/
|
49 |
+
.pytest_cache/
|
50 |
+
|
51 |
+
# temporary unittest artifacts
|
52 |
+
tests/testing_data/temp_*
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
|
63 |
+
# Flask stuff:
|
64 |
+
instance/
|
65 |
+
.webassets-cache
|
66 |
+
|
67 |
+
# Scrapy stuff:
|
68 |
+
.scrapy
|
69 |
+
|
70 |
+
# Sphinx documentation
|
71 |
+
docs/build/
|
72 |
+
docs/source/_gen
|
73 |
+
docs/source/*_properties.csv
|
74 |
+
_build/
|
75 |
+
|
76 |
+
# PyBuilder
|
77 |
+
target/
|
78 |
+
|
79 |
+
# Jupyter Notebook
|
80 |
+
.ipynb_checkpoints
|
81 |
+
|
82 |
+
# pyenv
|
83 |
+
.python-version
|
84 |
+
|
85 |
+
# celery beat schedule file
|
86 |
+
celerybeat-schedule
|
87 |
+
|
88 |
+
# SageMath parsed files
|
89 |
+
*.sage.py
|
90 |
+
|
91 |
+
# Environments
|
92 |
+
.env
|
93 |
+
.venv
|
94 |
+
env/
|
95 |
+
venv/
|
96 |
+
ENV/
|
97 |
+
env.bak/
|
98 |
+
venv.bak/
|
99 |
+
|
100 |
+
# Spyder project settings
|
101 |
+
.spyderproject
|
102 |
+
.spyproject
|
103 |
+
|
104 |
+
# Rope project settings
|
105 |
+
.ropeproject
|
106 |
+
|
107 |
+
# mkdocs documentation
|
108 |
+
/site
|
109 |
+
|
110 |
+
# pytype cache
|
111 |
+
.pytype/
|
112 |
+
|
113 |
+
# mypy
|
114 |
+
.mypy_cache/
|
115 |
+
examples/scd_lvsegs.npz
|
116 |
+
temp/
|
117 |
+
.idea/
|
118 |
+
.dmypy.json
|
119 |
+
|
120 |
+
*~
|
121 |
+
|
122 |
+
# Remove .pyre temporary config files
|
123 |
+
.pyre
|
124 |
+
.pyre_configuration
|
125 |
+
|
126 |
+
# temporary editor files that should not be in git
|
127 |
+
*.orig
|
128 |
+
*.bak
|
129 |
+
*.swp
|
130 |
+
.DS_Store
|
131 |
+
|
132 |
+
# temporary testing data MedNIST
|
133 |
+
tests/testing_data/MedNIST*
|
134 |
+
tests/testing_data/*Hippocampus*
|
135 |
+
tests/testing_data/*.tiff
|
136 |
+
tests/testing_data/schema.json
|
137 |
+
tests/testing_data/endo.mp4
|
138 |
+
tests/testing_data/ultrasound.avi
|
139 |
+
tests/testing_data/train_data_stats.yaml
|
140 |
+
tests/testing_data/eval_data_stats.yaml
|
141 |
+
tests/testing_data/train_data_stats_by_case.yaml
|
142 |
+
tests/testing_data/eval_data_stats_by_case.yaml
|
143 |
+
tests/testing_data/CT_2D_head_fixed.mha
|
144 |
+
tests/testing_data/CT_2D_head_moving.mha
|
145 |
+
tests/testing_data/config_executed.json
|
146 |
+
tests/testing_data/eval
|
147 |
+
tests/testing_data/nrrd_example.nrrd
|
148 |
+
|
149 |
+
# clang format tool
|
150 |
+
.clang-format-bin/
|
151 |
+
|
152 |
+
# VSCode
|
153 |
+
.vscode/
|
154 |
+
*.zip
|
155 |
+
|
156 |
+
# profiling results
|
157 |
+
*.prof
|
158 |
+
runs
|
159 |
+
|
160 |
+
*.gz
|
161 |
+
|
162 |
+
*.pth
|
163 |
+
|
164 |
+
*zarr/*
|
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
CHANGED
@@ -1,3 +1,76 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Model Overview
|
2 |
+
VISTA3D is trained using over 20 partial datasets with more complicated processing. 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).
|
3 |
+
|
4 |
+
## Run pipeline:
|
5 |
+
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.
|
6 |
+
|
7 |
+
Here is a code snippet to showcase how to execute inference with this model.
|
8 |
+
```python
|
9 |
+
import os
|
10 |
+
import tempfile
|
11 |
+
|
12 |
+
import torch
|
13 |
+
from hugging_face_pipeline import HuggingFacePipelineHelper
|
14 |
+
|
15 |
+
|
16 |
+
FILE_PATH = os.path.dirname(__file__)
|
17 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
18 |
+
output_dir = os.path.join(tmp_dir, "output_dir")
|
19 |
+
pipeline_helper = HuggingFacePipelineHelper("vista3d")
|
20 |
+
pipeline = pipeline_helper.init_pipeline(
|
21 |
+
os.path.join(FILE_PATH, "vista3d_pretrained_model"),
|
22 |
+
output_dir=output_dir,
|
23 |
+
device=torch.device("cuda:0"),
|
24 |
+
)
|
25 |
+
inputs = [
|
26 |
+
{
|
27 |
+
"image": "/data/Task09_Spleen/imagesTs/spleen_1.nii.gz",
|
28 |
+
"label_prompt": [3],
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"image": "/data/Task09_Spleen/imagesTs/spleen_11.nii.gz",
|
32 |
+
"label_prompt": [3],
|
33 |
+
},
|
34 |
+
]
|
35 |
+
pipeline(inputs)
|
36 |
+
|
37 |
+
```
|
38 |
+
The inputs defines the image to segment and the prompt for segmentation.
|
39 |
+
```python
|
40 |
+
inputs = {'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'label_prompt':[1]}
|
41 |
+
inputs = {'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'points':[[138,245,18], [271,343,27]], 'point_labels':[1,0]}
|
42 |
+
```
|
43 |
+
- 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`.
|
44 |
+
- 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.
|
45 |
+
- 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
|
46 |
+
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.
|
47 |
+
- **B must be 1 if label_prompt and points are provided together**. The inferer only supports SINGLE OBJECT point click segmentatation.
|
48 |
+
- If no prompt is provided, the model will use `everything_labels` to segment 117 classes:
|
49 |
+
|
50 |
+
```Python
|
51 |
+
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]))
|
52 |
+
```
|
53 |
+
|
54 |
+
- 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`.
|
55 |
+
- 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.
|
56 |
+
|
57 |
+
# References
|
58 |
+
- 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
|
59 |
+
|
60 |
+
- VISTA3D: Versatile Imaging SegmenTation and Annotation model for 3D Computed Tomography. arxiv (2024) https://arxiv.org/abs/2406.05285
|
61 |
+
|
62 |
+
|
63 |
+
# License
|
64 |
+
|
65 |
+
## Code License
|
66 |
+
|
67 |
+
This project includes code licensed under the Apache License 2.0.
|
68 |
+
You may obtain a copy of the License at
|
69 |
+
|
70 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
71 |
+
|
72 |
+
## Model Weights License
|
73 |
+
|
74 |
+
The model weights included in this project are licensed under the NCLS v1 License.
|
75 |
+
|
76 |
+
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.
|
__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.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,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20240725.json",
|
3 |
+
"version": "0.5.7",
|
4 |
+
"changelog": {
|
5 |
+
"0.5.7": "change sw padding mode to replicate",
|
6 |
+
"0.5.6": "add mlflow support",
|
7 |
+
"0.5.5": "add arg for trt compiler base path",
|
8 |
+
"0.5.4": "add undefined label prompt check",
|
9 |
+
"0.5.3": "update readme",
|
10 |
+
"0.5.2": "fix eval issue",
|
11 |
+
"0.5.1": "add description for zero-shot and upate eval",
|
12 |
+
"0.5.0": "update json file link and add test",
|
13 |
+
"0.4.9": "fix oom issue and update readme",
|
14 |
+
"0.4.8": "use 0.3 overlap for inference",
|
15 |
+
"0.4.7": "update tensorrt benchmark results",
|
16 |
+
"0.4.6": "add tensorrt benchmark result and remove the metric part",
|
17 |
+
"0.4.5": "remove wrong path",
|
18 |
+
"0.4.4": "enable tensorrt inference",
|
19 |
+
"0.4.3": "fix CL and batch infer issues",
|
20 |
+
"0.4.2": "use MONAI components for network and utils",
|
21 |
+
"0.4.1": "initial OSS version"
|
22 |
+
},
|
23 |
+
"monai_version": "1.4.0",
|
24 |
+
"pytorch_version": "2.4.0",
|
25 |
+
"numpy_version": "1.24.4",
|
26 |
+
"required_packages_version": {
|
27 |
+
"matplotlib": "3.9.1",
|
28 |
+
"einops": "0.7.0",
|
29 |
+
"scikit-image": "0.23.2",
|
30 |
+
"nibabel": "5.2.1",
|
31 |
+
"pytorch-ignite": "0.4.11",
|
32 |
+
"cucim-cu12": "24.6.0",
|
33 |
+
"mlflow": "2.17.2"
|
34 |
+
},
|
35 |
+
"supported_apps": {
|
36 |
+
"vista3d-nim": ""
|
37 |
+
},
|
38 |
+
"name": "VISTA3D",
|
39 |
+
"task": "Decathlon Spleen segmentation",
|
40 |
+
"description": "VISTA3D bundle",
|
41 |
+
"authors": "MONAI team",
|
42 |
+
"copyright": "Copyright (c) MONAI Consortium",
|
43 |
+
"data_source": "Task09_Spleen.tar from http://medicaldecathlon.com/",
|
44 |
+
"data_type": "nibabel",
|
45 |
+
"image_classes": "1 channel data, intensity scaled to [0, 1]",
|
46 |
+
"label_classes": "single channel data",
|
47 |
+
"pred_classes": "2 channels OneHot data",
|
48 |
+
"intended_use": "This is an example, not to be used for diagnostic purposes",
|
49 |
+
"references": [],
|
50 |
+
"network_data_format": {
|
51 |
+
"inputs": {
|
52 |
+
"image": {
|
53 |
+
"type": "image",
|
54 |
+
"format": "hounsfield",
|
55 |
+
"modality": "CT",
|
56 |
+
"num_channels": 1,
|
57 |
+
"spatial_shape": [
|
58 |
+
128,
|
59 |
+
128,
|
60 |
+
128
|
61 |
+
],
|
62 |
+
"dtype": "float32",
|
63 |
+
"value_range": [
|
64 |
+
0,
|
65 |
+
1
|
66 |
+
],
|
67 |
+
"is_patch_data": true,
|
68 |
+
"channel_def": {
|
69 |
+
"0": "image"
|
70 |
+
}
|
71 |
+
}
|
72 |
+
},
|
73 |
+
"outputs": {
|
74 |
+
"pred": {
|
75 |
+
"type": "image",
|
76 |
+
"format": "segmentation",
|
77 |
+
"num_channels": 1,
|
78 |
+
"spatial_shape": [
|
79 |
+
128,
|
80 |
+
128,
|
81 |
+
128
|
82 |
+
],
|
83 |
+
"dtype": "float32",
|
84 |
+
"value_range": [
|
85 |
+
0,
|
86 |
+
1
|
87 |
+
],
|
88 |
+
"is_patch_data": true,
|
89 |
+
"channel_def": {
|
90 |
+
"0": "background",
|
91 |
+
"1": "liver",
|
92 |
+
"2": "kidney",
|
93 |
+
"3": "spleen",
|
94 |
+
"4": "pancreas",
|
95 |
+
"5": "right kidney",
|
96 |
+
"6": "aorta",
|
97 |
+
"7": "inferior vena cava",
|
98 |
+
"8": "right adrenal gland",
|
99 |
+
"9": "left adrenal gland",
|
100 |
+
"10": "gallbladder",
|
101 |
+
"11": "esophagus",
|
102 |
+
"12": "stomach",
|
103 |
+
"13": "duodenum",
|
104 |
+
"14": "left kidney",
|
105 |
+
"15": "bladder",
|
106 |
+
"16": "prostate or uterus",
|
107 |
+
"17": "portal vein and splenic vein",
|
108 |
+
"18": "rectum",
|
109 |
+
"19": "small bowel",
|
110 |
+
"20": "lung",
|
111 |
+
"21": "bone",
|
112 |
+
"22": "brain",
|
113 |
+
"23": "lung tumor",
|
114 |
+
"24": "pancreatic tumor",
|
115 |
+
"25": "hepatic vessel",
|
116 |
+
"26": "hepatic tumor",
|
117 |
+
"27": "colon cancer primaries",
|
118 |
+
"28": "left lung upper lobe",
|
119 |
+
"29": "left lung lower lobe",
|
120 |
+
"30": "right lung upper lobe",
|
121 |
+
"31": "right lung middle lobe",
|
122 |
+
"32": "right lung lower lobe",
|
123 |
+
"33": "vertebrae L5",
|
124 |
+
"34": "vertebrae L4",
|
125 |
+
"35": "vertebrae L3",
|
126 |
+
"36": "vertebrae L2",
|
127 |
+
"37": "vertebrae L1",
|
128 |
+
"38": "vertebrae T12",
|
129 |
+
"39": "vertebrae T11",
|
130 |
+
"40": "vertebrae T10",
|
131 |
+
"41": "vertebrae T9",
|
132 |
+
"42": "vertebrae T8",
|
133 |
+
"43": "vertebrae T7",
|
134 |
+
"44": "vertebrae T6",
|
135 |
+
"45": "vertebrae T5",
|
136 |
+
"46": "vertebrae T4",
|
137 |
+
"47": "vertebrae T3",
|
138 |
+
"48": "vertebrae T2",
|
139 |
+
"49": "vertebrae T1",
|
140 |
+
"50": "vertebrae C7",
|
141 |
+
"51": "vertebrae C6",
|
142 |
+
"52": "vertebrae C5",
|
143 |
+
"53": "vertebrae C4",
|
144 |
+
"54": "vertebrae C3",
|
145 |
+
"55": "vertebrae C2",
|
146 |
+
"56": "vertebrae C1",
|
147 |
+
"57": "trachea",
|
148 |
+
"58": "left iliac artery",
|
149 |
+
"59": "right iliac artery",
|
150 |
+
"60": "left iliac vena",
|
151 |
+
"61": "right iliac vena",
|
152 |
+
"62": "colon",
|
153 |
+
"63": "left rib 1",
|
154 |
+
"64": "left rib 2",
|
155 |
+
"65": "left rib 3",
|
156 |
+
"66": "left rib 4",
|
157 |
+
"67": "left rib 5",
|
158 |
+
"68": "left rib 6",
|
159 |
+
"69": "left rib 7",
|
160 |
+
"70": "left rib 8",
|
161 |
+
"71": "left rib 9",
|
162 |
+
"72": "left rib 10",
|
163 |
+
"73": "left rib 11",
|
164 |
+
"74": "left rib 12",
|
165 |
+
"75": "right rib 1",
|
166 |
+
"76": "right rib 2",
|
167 |
+
"77": "right rib 3",
|
168 |
+
"78": "right rib 4",
|
169 |
+
"79": "right rib 5",
|
170 |
+
"80": "right rib 6",
|
171 |
+
"81": "right rib 7",
|
172 |
+
"82": "right rib 8",
|
173 |
+
"83": "right rib 9",
|
174 |
+
"84": "right rib 10",
|
175 |
+
"85": "right rib 11",
|
176 |
+
"86": "right rib 12",
|
177 |
+
"87": "left humerus",
|
178 |
+
"88": "right humerus",
|
179 |
+
"89": "left scapula",
|
180 |
+
"90": "right scapula",
|
181 |
+
"91": "left clavicula",
|
182 |
+
"92": "right clavicula",
|
183 |
+
"93": "left femur",
|
184 |
+
"94": "right femur",
|
185 |
+
"95": "left hip",
|
186 |
+
"96": "right hip",
|
187 |
+
"97": "sacrum",
|
188 |
+
"98": "left gluteus maximus",
|
189 |
+
"99": "right gluteus maximus",
|
190 |
+
"100": "left gluteus medius",
|
191 |
+
"101": "right gluteus medius",
|
192 |
+
"102": "left gluteus minimus",
|
193 |
+
"103": "right gluteus minimus",
|
194 |
+
"104": "left autochthon",
|
195 |
+
"105": "right autochthon",
|
196 |
+
"106": "left iliopsoas",
|
197 |
+
"107": "right iliopsoas",
|
198 |
+
"108": "left atrial appendage",
|
199 |
+
"109": "brachiocephalic trunk",
|
200 |
+
"110": "left brachiocephalic vein",
|
201 |
+
"111": "right brachiocephalic vein",
|
202 |
+
"112": "left common carotid artery",
|
203 |
+
"113": "right common carotid artery",
|
204 |
+
"114": "costal cartilages",
|
205 |
+
"115": "heart",
|
206 |
+
"116": "left kidney cyst",
|
207 |
+
"117": "right kidney cyst",
|
208 |
+
"118": "prostate",
|
209 |
+
"119": "pulmonary vein",
|
210 |
+
"120": "skull",
|
211 |
+
"121": "spinal cord",
|
212 |
+
"122": "sternum",
|
213 |
+
"123": "left subclavian artery",
|
214 |
+
"124": "right subclavian artery",
|
215 |
+
"125": "superior vena cava",
|
216 |
+
"126": "thyroid gland",
|
217 |
+
"127": "vertebrae S1",
|
218 |
+
"128": "bone lesion",
|
219 |
+
"129": "kidney mass",
|
220 |
+
"130": "liver tumor",
|
221 |
+
"131": "vertebrae L6",
|
222 |
+
"132": "airway"
|
223 |
+
}
|
224 |
+
}
|
225 |
+
}
|
226 |
+
}
|
227 |
+
}
|
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,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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__(
|
31 |
+
self, roi_size, overlap, use_point_window=False, sw_batch_size=1
|
32 |
+
) -> None:
|
33 |
+
Inferer.__init__(self)
|
34 |
+
self.roi_size = roi_size
|
35 |
+
self.overlap = overlap
|
36 |
+
self.sw_batch_size = sw_batch_size
|
37 |
+
self.use_point_window = use_point_window
|
38 |
+
|
39 |
+
def __call__(
|
40 |
+
self,
|
41 |
+
inputs: Union[List[Tensor], Tensor],
|
42 |
+
network,
|
43 |
+
point_coords,
|
44 |
+
point_labels,
|
45 |
+
class_vector,
|
46 |
+
labels=None,
|
47 |
+
label_set=None,
|
48 |
+
prev_mask=None,
|
49 |
+
):
|
50 |
+
"""
|
51 |
+
Unified callable function API of Inferers.
|
52 |
+
Notice: The point_based_window_inferer currently only supports SINGLE OBJECT INFERENCE with B=1.
|
53 |
+
It only used in interactive segmentation.
|
54 |
+
|
55 |
+
Args:
|
56 |
+
inputs: input tensor images.
|
57 |
+
network: vista3d model.
|
58 |
+
point_coords: point click coordinates. [B, N, 3].
|
59 |
+
point_labels: point click labels (0 for negative, 1 for positive) [B, N].
|
60 |
+
class_vector: class vector of length B.
|
61 |
+
labels: groundtruth labels. Used for sampling validation points.
|
62 |
+
label_set: [0,1,2,3,...,output_classes].
|
63 |
+
prev_mask: [1, B, H, W, D], THE VALUE IS BEFORE SIGMOID!
|
64 |
+
|
65 |
+
"""
|
66 |
+
prompt_class = copy.deepcopy(class_vector)
|
67 |
+
if class_vector is not None:
|
68 |
+
# Check if network has attribute 'point_head' directly or within its 'module'
|
69 |
+
if hasattr(network, "point_head"):
|
70 |
+
point_head = network.point_head
|
71 |
+
elif hasattr(network, "module") and hasattr(network.module, "point_head"):
|
72 |
+
point_head = network.module.point_head
|
73 |
+
else:
|
74 |
+
raise AttributeError("Network does not have attribute 'point_head'.")
|
75 |
+
|
76 |
+
if torch.any(class_vector > point_head.last_supported):
|
77 |
+
class_vector = None
|
78 |
+
val_outputs = None
|
79 |
+
torch.cuda.empty_cache()
|
80 |
+
if self.use_point_window and point_coords is not None:
|
81 |
+
if isinstance(inputs, list):
|
82 |
+
device = inputs[0].device
|
83 |
+
else:
|
84 |
+
device = inputs.device
|
85 |
+
val_outputs = point_based_window_inferer(
|
86 |
+
inputs=inputs,
|
87 |
+
roi_size=self.roi_size,
|
88 |
+
sw_batch_size=self.sw_batch_size,
|
89 |
+
transpose=True,
|
90 |
+
with_coord=True,
|
91 |
+
predictor=network,
|
92 |
+
mode="gaussian",
|
93 |
+
sw_device=device,
|
94 |
+
device=device,
|
95 |
+
overlap=self.overlap,
|
96 |
+
point_coords=point_coords,
|
97 |
+
point_labels=point_labels,
|
98 |
+
class_vector=class_vector,
|
99 |
+
prompt_class=prompt_class,
|
100 |
+
prev_mask=prev_mask,
|
101 |
+
labels=labels,
|
102 |
+
label_set=label_set,
|
103 |
+
)
|
104 |
+
else:
|
105 |
+
val_outputs = SlidingWindowInfererAdapt(
|
106 |
+
roi_size=self.roi_size,
|
107 |
+
sw_batch_size=self.sw_batch_size,
|
108 |
+
with_coord=True,
|
109 |
+
padding_mode="replicate",
|
110 |
+
)(
|
111 |
+
inputs,
|
112 |
+
network,
|
113 |
+
transpose=True,
|
114 |
+
point_coords=point_coords,
|
115 |
+
point_labels=point_labels,
|
116 |
+
class_vector=class_vector,
|
117 |
+
prompt_class=prompt_class,
|
118 |
+
prev_mask=prev_mask,
|
119 |
+
labels=labels,
|
120 |
+
label_set=label_set,
|
121 |
+
)
|
122 |
+
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,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
self.network = monai.networks.nets.vista3d132(
|
17 |
+
encoder_embed_dim=config.encoder_embed_dim,
|
18 |
+
in_channels=config.input_channels,
|
19 |
+
)
|
20 |
+
|
21 |
+
def forward(self, input):
|
22 |
+
return self.network(input)
|
23 |
+
|
24 |
+
|
25 |
+
def register_my_model():
|
26 |
+
"""Utility function to register VISTA3D model so that it can be instantiate by the AutoModel function."""
|
27 |
+
AutoConfig.register("VISTA3D", VISTA3DConfig)
|
28 |
+
AutoModel.register(VISTA3DConfig, VISTA3DModel)
|
29 |
+
|
30 |
+
|
31 |
+
if __name__ == "__main__":
|
32 |
+
FILE_PATH = os.path.dirname(__file__)
|
33 |
+
MODEL_WEIGHT_PATH = os.path.join(FILE_PATH, "models/model.pt")
|
34 |
+
MODEL_PATH = os.path.join(FILE_PATH, "vista3d_pretrained_model")
|
35 |
+
config = VISTA3DConfig()
|
36 |
+
hugging_face_model = VISTA3DModel(config)
|
37 |
+
hugging_face_model.network.load_state_dict(torch.load(MODEL_WEIGHT_PATH))
|
38 |
+
hugging_face_model.save_pretrained(MODEL_PATH)
|
vista3d_pipeline.py
ADDED
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
]
|
56 |
+
INFERENCE_EXTRA_ARGS = [
|
57 |
+
"mode",
|
58 |
+
"amp",
|
59 |
+
"hyper_kwargs",
|
60 |
+
"roi_size",
|
61 |
+
"overlap",
|
62 |
+
"sw_batch_size",
|
63 |
+
"use_point_window",
|
64 |
+
]
|
65 |
+
POSTPROCESSING_EXTRA_ARGS = [
|
66 |
+
"pred_key",
|
67 |
+
"image_key",
|
68 |
+
"output_dir",
|
69 |
+
"output_ext",
|
70 |
+
"output_postfix",
|
71 |
+
"separate_folder",
|
72 |
+
"save_output",
|
73 |
+
]
|
74 |
+
EVERYTHING_LABEL = list(
|
75 |
+
set([i + 1 for i in range(132)])
|
76 |
+
- set([2, 16, 18, 20, 21, 23, 24, 25, 26, 27, 128, 129, 130, 131, 132])
|
77 |
+
)
|
78 |
+
|
79 |
+
def __init__(self, model, **kwargs):
|
80 |
+
super().__init__(model, **kwargs)
|
81 |
+
self.preprocessing_transforms = self._init_preprocessing_transforms(
|
82 |
+
**self._preprocess_params
|
83 |
+
)
|
84 |
+
self.inferer = self._init_inferer(**self._forward_params)
|
85 |
+
self.postprocessing_transforms = self._init_postprocessing_transforms(
|
86 |
+
**self._postprocess_params
|
87 |
+
)
|
88 |
+
|
89 |
+
def _init_inferer(
|
90 |
+
self,
|
91 |
+
roi_size: Sequence = (128, 128, 128),
|
92 |
+
overlap: float = 0.3,
|
93 |
+
sw_batch_size: int = 1,
|
94 |
+
use_point_window: bool = True,
|
95 |
+
):
|
96 |
+
return Vista3dInferer(
|
97 |
+
roi_size=roi_size,
|
98 |
+
overlap=overlap,
|
99 |
+
use_point_window=use_point_window,
|
100 |
+
sw_batch_size=sw_batch_size,
|
101 |
+
)
|
102 |
+
|
103 |
+
def _init_preprocessing_transforms(
|
104 |
+
self,
|
105 |
+
image_key: str = "image",
|
106 |
+
resample_spacing: Sequence = (1.5, 1.5, 1.5),
|
107 |
+
metadata_path: str = os.path.join(FILE_PATH, "metadata.json"),
|
108 |
+
):
|
109 |
+
device = self.device
|
110 |
+
subclass = {
|
111 |
+
"2": [14, 5],
|
112 |
+
"20": [28, 29, 30, 31, 32],
|
113 |
+
"21": list(range(33, 57)) + list(range(63, 98)) + [114, 120, 122],
|
114 |
+
}
|
115 |
+
metadata = json.loads(pathlib.Path(metadata_path).read_text())
|
116 |
+
labels_dict = metadata["network_data_format"]["outputs"]["pred"]["channel_def"]
|
117 |
+
preprocessing_transforms = Compose(
|
118 |
+
[
|
119 |
+
LoadImaged(keys=image_key, image_only=True),
|
120 |
+
EnsureChannelFirstd(keys=image_key),
|
121 |
+
EnsureTyped(keys=image_key, device=device, track_meta=True),
|
122 |
+
Spacingd(keys=image_key, pixdim=resample_spacing, mode="bilinear"),
|
123 |
+
CropForegroundd(
|
124 |
+
keys=image_key, allow_smaller=True, margin=10, source_key=image_key
|
125 |
+
),
|
126 |
+
VistaPreTransformd(
|
127 |
+
keys=image_key, subclass=subclass, labels_dict=labels_dict
|
128 |
+
),
|
129 |
+
ScaleIntensityRanged(
|
130 |
+
keys=image_key,
|
131 |
+
a_min=-963.8247715525971,
|
132 |
+
a_max=1053.678477684517,
|
133 |
+
b_min=0,
|
134 |
+
b_max=1,
|
135 |
+
clip=True,
|
136 |
+
),
|
137 |
+
Orientationd(keys=image_key, axcodes="RAS"),
|
138 |
+
CastToTyped(keys=image_key, dtype=torch.float32),
|
139 |
+
]
|
140 |
+
)
|
141 |
+
return preprocessing_transforms
|
142 |
+
|
143 |
+
def _init_postprocessing_transforms(
|
144 |
+
self,
|
145 |
+
pred_key: str = "pred",
|
146 |
+
image_key: str = "image",
|
147 |
+
output_dir: str = "output_directory",
|
148 |
+
output_ext: str = ".nii.gz",
|
149 |
+
output_dtype: torch.dtype = torch.float32,
|
150 |
+
output_postfix: str = "seg",
|
151 |
+
separate_folder: bool = True,
|
152 |
+
save_output: bool = True,
|
153 |
+
):
|
154 |
+
transforms = [
|
155 |
+
VistaPostTransformd(keys=pred_key),
|
156 |
+
Invertd(
|
157 |
+
keys=pred_key,
|
158 |
+
transform=copy.deepcopy(self.preprocessing_transforms),
|
159 |
+
orig_keys=image_key,
|
160 |
+
nearest_interp=True,
|
161 |
+
to_tensor=True,
|
162 |
+
),
|
163 |
+
Lambdad(keys=pred_key, func=lambda x: torch.nan_to_num(x, nan=255)),
|
164 |
+
]
|
165 |
+
if save_output:
|
166 |
+
transforms.append(
|
167 |
+
SaveImaged(
|
168 |
+
keys=pred_key,
|
169 |
+
resample=False,
|
170 |
+
output_dir=output_dir,
|
171 |
+
output_ext=output_ext,
|
172 |
+
output_dtype=output_dtype,
|
173 |
+
output_postfix=output_postfix,
|
174 |
+
separate_folder=separate_folder,
|
175 |
+
),
|
176 |
+
)
|
177 |
+
postprocessing_transforms = Compose(transforms=transforms)
|
178 |
+
return postprocessing_transforms
|
179 |
+
|
180 |
+
def _sanitize_parameters(self, **kwargs):
|
181 |
+
"""
|
182 |
+
_sanitize_parameters exists to allow users to pass any parameters whenever they wish,
|
183 |
+
be it at initialization time pipeline(...., maybe_arg=4) or at call time pipe = pipeline(...); output = pipe(...., maybe_arg=4).
|
184 |
+
The returns of _sanitize_parameters are the 3 dicts of kwargs that will be passed directly to preprocess, _forward and postprocess.
|
185 |
+
Don't fill anything if the caller didn't call with any extra parameter. That allows to keep the default arguments in the function
|
186 |
+
definition which is always more “natural”."""
|
187 |
+
|
188 |
+
vista3d_preprocessing_kwargs = {}
|
189 |
+
vista3d_infer_kwargs = {}
|
190 |
+
vista3d_postprocessing_kwargs = {}
|
191 |
+
for key in self.INFERENCE_EXTRA_ARGS:
|
192 |
+
if key in kwargs:
|
193 |
+
vista3d_infer_kwargs[key] = kwargs[key]
|
194 |
+
|
195 |
+
for key in self.PREPROCESSING_EXTRA_ARGS:
|
196 |
+
if key in kwargs:
|
197 |
+
vista3d_preprocessing_kwargs[key] = kwargs[key]
|
198 |
+
|
199 |
+
for key in self.POSTPROCESSING_EXTRA_ARGS:
|
200 |
+
if key in kwargs:
|
201 |
+
vista3d_postprocessing_kwargs[key] = kwargs[key]
|
202 |
+
|
203 |
+
return (
|
204 |
+
vista3d_preprocessing_kwargs,
|
205 |
+
vista3d_infer_kwargs,
|
206 |
+
vista3d_postprocessing_kwargs,
|
207 |
+
)
|
208 |
+
|
209 |
+
def check_prompts_format(self, label_prompt, points, point_labels):
|
210 |
+
"""check the format of user prompts
|
211 |
+
label_prompt: [1,2,3,4,...,B] List of tensors
|
212 |
+
points: [[[x,y,z], [x,y,z], ...]] List of coordinates of a single object
|
213 |
+
point_labels: [[1,1,0,...]] List of scalar that matches number of points
|
214 |
+
"""
|
215 |
+
# check prompt is given
|
216 |
+
if label_prompt is None and points is None:
|
217 |
+
everything_labels = self.hyper_kwargs.get("everything_labels", None)
|
218 |
+
if everything_labels is not None:
|
219 |
+
label_prompt = [torch.tensor(_) for _ in everything_labels]
|
220 |
+
return label_prompt, points, point_labels
|
221 |
+
else:
|
222 |
+
raise ValueError("Prompt must be given for inference.")
|
223 |
+
# check label_prompt
|
224 |
+
if label_prompt is not None:
|
225 |
+
if isinstance(label_prompt, list):
|
226 |
+
if not np.all([len(_) == 1 for _ in label_prompt]):
|
227 |
+
raise ValueError(
|
228 |
+
"Label prompt must be a list of single scalar, [1,2,3,4,...,]."
|
229 |
+
)
|
230 |
+
if isinstance(label_prompt[0], list):
|
231 |
+
for prompt in label_prompt:
|
232 |
+
if not np.all([(x < 255).item() for x in prompt]):
|
233 |
+
raise ValueError(
|
234 |
+
"Current bundle only supports label prompt smaller than 255."
|
235 |
+
)
|
236 |
+
else:
|
237 |
+
if not np.all([(x < 255).item() for x in label_prompt]):
|
238 |
+
raise ValueError(
|
239 |
+
"Current bundle only supports label prompt smaller than 255."
|
240 |
+
)
|
241 |
+
if points is None:
|
242 |
+
supported_list = list(
|
243 |
+
{i + 1 for i in range(132)} - {16, 18, 129, 130, 131}
|
244 |
+
)
|
245 |
+
if isinstance(label_prompt[0], list):
|
246 |
+
for prompt in label_prompt:
|
247 |
+
if not np.all([(x < 255).item() for x in prompt]):
|
248 |
+
raise ValueError(
|
249 |
+
"Current bundle only supports label prompt smaller than 255."
|
250 |
+
)
|
251 |
+
else:
|
252 |
+
if not np.all([x in supported_list for x in label_prompt]):
|
253 |
+
raise ValueError(
|
254 |
+
"Undefined label prompt detected. Provide point prompts for zero-shot."
|
255 |
+
)
|
256 |
+
else:
|
257 |
+
raise ValueError("Label prompt must be a list, [1,2,3,4,...,].")
|
258 |
+
# check points
|
259 |
+
if points is not None:
|
260 |
+
if point_labels is None:
|
261 |
+
raise ValueError("Point labels must be given if points are given.")
|
262 |
+
if not np.all([len(_) == 3 for _ in points]):
|
263 |
+
raise ValueError(
|
264 |
+
"Points must be three dimensional (x,y,z) in the shape of [[x,y,z],...,[x,y,z]]."
|
265 |
+
)
|
266 |
+
if len(points) != len(point_labels):
|
267 |
+
raise ValueError("Points must match point labels.")
|
268 |
+
if not np.all([_ in [-1, 0, 1, 2, 3] for _ in point_labels]):
|
269 |
+
raise ValueError(
|
270 |
+
"Point labels can only be -1,0,1 and 2,3 for special flags."
|
271 |
+
)
|
272 |
+
if label_prompt is not None and points is not None:
|
273 |
+
if len(label_prompt) != 1:
|
274 |
+
raise ValueError(
|
275 |
+
"Label prompt can only be a single object if provided with point prompts."
|
276 |
+
)
|
277 |
+
# check point_labels
|
278 |
+
if point_labels is not None:
|
279 |
+
if points is None:
|
280 |
+
raise ValueError("Points must be given if point labels are given.")
|
281 |
+
return label_prompt, points, point_labels
|
282 |
+
|
283 |
+
def transform_points(self, point, affine):
|
284 |
+
"""transform point to the coordinates of the transformed image
|
285 |
+
point: numpy array [bs, N, 3]
|
286 |
+
"""
|
287 |
+
bs, n = point.shape[:2]
|
288 |
+
point = np.concatenate((point, np.ones((bs, n, 1))), axis=-1)
|
289 |
+
point = rearrange(point, "b n d -> d (b n)")
|
290 |
+
point = affine @ point
|
291 |
+
point = rearrange(point, "d (b n)-> b n d", b=bs)[:, :, :3]
|
292 |
+
return point
|
293 |
+
|
294 |
+
def preprocess(
|
295 |
+
self,
|
296 |
+
inputs,
|
297 |
+
**kwargs,
|
298 |
+
):
|
299 |
+
for key, value in kwargs.items():
|
300 |
+
if key in self._preprocess_params and value != self._preprocess_params[key]:
|
301 |
+
logging.warning(
|
302 |
+
f"Please set the parameter {key} during initialization."
|
303 |
+
)
|
304 |
+
|
305 |
+
if key not in self.PREPROCESSING_EXTRA_ARGS:
|
306 |
+
logging.warning(f"Cannot set parameter {key} for preprocessing.")
|
307 |
+
inputs = self.preprocessing_transforms(inputs)
|
308 |
+
inputs = list_data_collate([inputs])
|
309 |
+
return inputs
|
310 |
+
|
311 |
+
def _forward(
|
312 |
+
self,
|
313 |
+
inputs,
|
314 |
+
mode: str = ForwardMode.EVAL,
|
315 |
+
amp: bool = True,
|
316 |
+
hyper_kwargs: dict = {"user_prompt": 1, "everything_labels": 1},
|
317 |
+
):
|
318 |
+
set_determinism(seed=123)
|
319 |
+
|
320 |
+
if inputs is None:
|
321 |
+
raise ValueError("Must provide input data for inference.")
|
322 |
+
self.hyper_kwargs = hyper_kwargs
|
323 |
+
|
324 |
+
label_set = hyper_kwargs.get("label_set", None)
|
325 |
+
# this validation label set should be consistent with 'labels.unique()', used to generate fg/bg points
|
326 |
+
val_label_set = hyper_kwargs.get("val_label_set", label_set)
|
327 |
+
# If user provide prompts in the inference, input image must contain original affine.
|
328 |
+
# the point coordinates are from the original_affine space, while image here is after preprocess transforms.
|
329 |
+
if hyper_kwargs["user_prompt"]:
|
330 |
+
inputs, label_prompt, points, point_labels = (
|
331 |
+
inputs["image"],
|
332 |
+
inputs.get("label_prompt", None),
|
333 |
+
inputs.get("points", None),
|
334 |
+
inputs.get("point_labels", None),
|
335 |
+
)
|
336 |
+
labels = None
|
337 |
+
label_prompt, points, point_labels = self.check_prompts_format(
|
338 |
+
label_prompt, points, point_labels
|
339 |
+
)
|
340 |
+
inputs = inputs.to(self.device)
|
341 |
+
# For N foreground object, label_prompt is [1, N], but the batch number 1 needs to be removed. Convert to [N, 1]
|
342 |
+
label_prompt = (
|
343 |
+
torch.as_tensor([label_prompt]).to(inputs.device)[0].unsqueeze(-1)
|
344 |
+
if label_prompt is not None
|
345 |
+
else None
|
346 |
+
)
|
347 |
+
# For points, the size can only be [1, K, 3], where K is the number of points for this single foreground object.
|
348 |
+
if points is not None:
|
349 |
+
points = torch.as_tensor([points])
|
350 |
+
points = self.transform_points(
|
351 |
+
points,
|
352 |
+
np.linalg.inv(inputs.affine[0])
|
353 |
+
@ inputs.meta["original_affine"][0].numpy(),
|
354 |
+
)
|
355 |
+
points = torch.from_numpy(points).to(inputs.device)
|
356 |
+
point_labels = (
|
357 |
+
torch.as_tensor([point_labels]).to(inputs.device)
|
358 |
+
if point_labels is not None
|
359 |
+
else None
|
360 |
+
)
|
361 |
+
|
362 |
+
# If validation with ground truth label available.
|
363 |
+
else:
|
364 |
+
# TODO add these as attribute.
|
365 |
+
inputs, labels = inputs["image"], inputs["label"]
|
366 |
+
# create label prompt, this should be consistent with the label prompt used for training.
|
367 |
+
if label_set is None:
|
368 |
+
output_classes = hyper_kwargs.get("output_classes", None)
|
369 |
+
label_set = np.arange(output_classes).tolist()
|
370 |
+
label_prompt = torch.tensor(label_set).to(self.device).unsqueeze(-1)
|
371 |
+
# point prompt is generated withing vista3d, provide empty points
|
372 |
+
points = torch.zeros(label_prompt.shape[0], 1, 3).to(inputs.device)
|
373 |
+
point_labels = -1 + torch.zeros(label_prompt.shape[0], 1).to(inputs.device)
|
374 |
+
# validation for either auto or point.
|
375 |
+
if hyper_kwargs.get("val_head", "auto") == "auto":
|
376 |
+
# automatic only validation
|
377 |
+
# remove val_label_set, vista3d will not sample points from gt labels.
|
378 |
+
val_label_set = None
|
379 |
+
else:
|
380 |
+
# point only validation
|
381 |
+
label_prompt = None
|
382 |
+
|
383 |
+
# put iteration outputs into outputs TODO need to align with the customized inputs
|
384 |
+
outputs = {Keys.IMAGE: inputs, Keys.LABEL: labels}
|
385 |
+
mode = look_up_option(mode, ForwardMode)
|
386 |
+
if mode == ForwardMode.EVAL:
|
387 |
+
mode = eval_mode
|
388 |
+
elif mode == ForwardMode.TRAIN:
|
389 |
+
mode = train_mode
|
390 |
+
else:
|
391 |
+
raise ValueError(f"unsupported mode: {mode}, should be 'eval' or 'train'.")
|
392 |
+
|
393 |
+
# execute forward computation
|
394 |
+
self.model.network.to(self.device)
|
395 |
+
with mode(self.model):
|
396 |
+
if amp:
|
397 |
+
with torch.autocast("cuda"):
|
398 |
+
outputs[Keys.PRED] = self.inferer(
|
399 |
+
inputs=inputs,
|
400 |
+
network=self.model.network,
|
401 |
+
point_coords=points,
|
402 |
+
point_labels=point_labels,
|
403 |
+
class_vector=label_prompt,
|
404 |
+
labels=labels,
|
405 |
+
label_set=val_label_set,
|
406 |
+
)
|
407 |
+
else:
|
408 |
+
outputs[Keys.PRED] = self.inferer(
|
409 |
+
inputs=inputs,
|
410 |
+
network=self.model.network,
|
411 |
+
point_coords=points,
|
412 |
+
point_labels=point_labels,
|
413 |
+
class_vector=label_prompt,
|
414 |
+
labels=labels,
|
415 |
+
label_set=val_label_set,
|
416 |
+
)
|
417 |
+
inputs = reset_ops_id(inputs)
|
418 |
+
# Add dim 0 for decollate batch
|
419 |
+
outputs["label_prompt"] = (
|
420 |
+
label_prompt.unsqueeze(0) if label_prompt is not None else None
|
421 |
+
)
|
422 |
+
outputs["points"] = points.unsqueeze(0) if points is not None else None
|
423 |
+
outputs["point_labels"] = (
|
424 |
+
point_labels.unsqueeze(0) if point_labels is not None else None
|
425 |
+
)
|
426 |
+
if torch.cuda.is_available():
|
427 |
+
torch.cuda.empty_cache()
|
428 |
+
|
429 |
+
return outputs
|
430 |
+
|
431 |
+
def postprocess(self, outputs, **kwargs):
|
432 |
+
for key, value in kwargs.items():
|
433 |
+
if (
|
434 |
+
key in self._postprocess_params
|
435 |
+
and value != self._postprocess_params[key]
|
436 |
+
):
|
437 |
+
logging.warning(
|
438 |
+
f"Please set the parameter {key} during initialization."
|
439 |
+
)
|
440 |
+
|
441 |
+
if key not in self.POSTPROCESSING_EXTRA_ARGS:
|
442 |
+
logging.warning(f"Cannot set parameter {key} for postprocessing.")
|
443 |
+
outputs = self.postprocessing_transforms(decollate_batch(outputs))
|
444 |
+
return outputs
|
445 |
+
|
446 |
+
|
447 |
+
def register_simple_pipeline():
|
448 |
+
PIPELINE_REGISTRY.register_pipeline(
|
449 |
+
"vista3d",
|
450 |
+
pipeline_class=VISTA3DPipeline,
|
451 |
+
pt_model=AutoModel,
|
452 |
+
default={"pt": (os.path.join(FILE_PATH, "vista3d_pretrained_model"), "")},
|
453 |
+
type="image", # current support type: text, audio, image, multimodal
|
454 |
+
)
|
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.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:120ed013722a22780cc01b75cb5c18e4658d69879a983885abf8fa411c9f8f42
|
3 |
+
size 871894112
|