project-monai commited on
Commit
2ffbace
·
verified ·
1 Parent(s): f2ae8ec

Upload vista3d version 0.5.9

Browse files
configs/metadata.json CHANGED
@@ -1,7 +1,8 @@
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.8",
4
  "changelog": {
 
5
  "0.5.8": "update to huggingface hosting",
6
  "0.5.7": "change sw padding mode to replicate",
7
  "0.5.6": "add mlflow support",
 
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.9",
4
  "changelog": {
5
+ "0.5.9": "fix finetuning bug and update readme",
6
  "0.5.8": "update to huggingface hosting",
7
  "0.5.7": "change sw padding mode to replicate",
8
  "0.5.6": "add mlflow support",
configs/train.json CHANGED
@@ -15,7 +15,7 @@
15
  "finetune": false,
16
  "finetune_model_path": "$@bundle_root + '/models/model.pt'",
17
  "early_stop": false,
18
- "use_mlflow": false,
19
  "mlflow_dir": "$@bundle_root + '/mlruns'",
20
  "fold": 0,
21
  "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
 
15
  "finetune": false,
16
  "finetune_model_path": "$@bundle_root + '/models/model.pt'",
17
  "early_stop": false,
18
+ "use_mlflow": true,
19
  "mlflow_dir": "$@bundle_root + '/mlruns'",
20
  "fold": 0,
21
  "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')",
configs/train_continual.json CHANGED
@@ -4,8 +4,8 @@
4
  "finetune": true,
5
  "val_at_start": true,
6
  "finetune_model_path": "$@bundle_root + '/models/model.pt'",
7
- "n_train_samples": 10,
8
- "n_val_samples": 10,
9
  "val_interval": 1,
10
  "learning_rate": 5e-05,
11
  "lr_schedule#activate": false,
@@ -69,6 +69,77 @@
69
  "indices_key": "$@cache_cls_idx#indices_key",
70
  "warn": false
71
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  {
73
  "_target_": "monai.apps.vista3d.transforms.Relabeld",
74
  "keys": "label",
 
4
  "finetune": true,
5
  "val_at_start": true,
6
  "finetune_model_path": "$@bundle_root + '/models/model.pt'",
7
+ "n_train_samples": null,
8
+ "n_val_samples": null,
9
  "val_interval": 1,
10
  "learning_rate": 5e-05,
11
  "lr_schedule#activate": false,
 
69
  "indices_key": "$@cache_cls_idx#indices_key",
70
  "warn": false
71
  },
72
+ {
73
+ "_target_": "RandZoomd",
74
+ "keys": [
75
+ "image",
76
+ "label"
77
+ ],
78
+ "min_zoom": 0.8,
79
+ "max_zoom": 1.2,
80
+ "mode": [
81
+ "trilinear",
82
+ "nearest"
83
+ ],
84
+ "prob": 0.2,
85
+ "allow_missing_keys": true
86
+ },
87
+ {
88
+ "_target_": "RandSimulateLowResolutiond",
89
+ "keys": [
90
+ "image"
91
+ ],
92
+ "zoom_range": [
93
+ 0.3,
94
+ 1
95
+ ],
96
+ "prob": 0.2,
97
+ "allow_missing_keys": true
98
+ },
99
+ {
100
+ "_target_": "RandGaussianSmoothd",
101
+ "keys": [
102
+ "image"
103
+ ],
104
+ "prob": 0.2,
105
+ "sigma_x": [
106
+ 0.5,
107
+ 1.0
108
+ ],
109
+ "sigma_y": [
110
+ 0.5,
111
+ 1.0
112
+ ],
113
+ "sigma_z": [
114
+ 0.5,
115
+ 1.0
116
+ ]
117
+ },
118
+ {
119
+ "_target_": "RandScaleIntensityd",
120
+ "keys": [
121
+ "image"
122
+ ],
123
+ "factors": 0.1,
124
+ "prob": 0.2
125
+ },
126
+ {
127
+ "_target_": "RandShiftIntensityd",
128
+ "keys": [
129
+ "image"
130
+ ],
131
+ "offsets": 0.1,
132
+ "prob": 0.2
133
+ },
134
+ {
135
+ "_target_": "RandGaussianNoised",
136
+ "keys": [
137
+ "image"
138
+ ],
139
+ "prob": 0.2,
140
+ "mean": 0.0,
141
+ "std": 0.2
142
+ },
143
  {
144
  "_target_": "monai.apps.vista3d.transforms.Relabeld",
145
  "keys": "label",
docs/README.md CHANGED
@@ -1,16 +1,54 @@
1
  # Model Overview
2
  Vista3D model fintuning/evaluation/inference pipeline. VISTA3D is trained using over 20 partial datasets with more complicated pipeline. To avoid confusion, we will only provide finetuning/continual learning APIs for users to finetune on their
3
- own datasets.
4
 
5
- ## Continual learning
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- For continual learning, user can change `configs/train_continual.json`. More advanced users can change configurations in `configs/train.json`. The hyperparameters in `configs/train_continual.json` will overwrite ones in `configs/train.json`. Most hyperparameters are straighforward and user can tell based on their names. We list hyperparameters that needs to be modified.
 
 
 
 
 
 
 
 
8
 
9
- ### Data
10
 
11
- The spleen Task from the Medical Segmentation Decathalon is selected as an example to show how to continuous learning. Users can find more details on the datasets at http://medicaldecathlon.com/.
12
 
13
- To train with other datasets, users need to provide a json data split for training and continuous learning (`configs/msd_task09_spleen_folds.json` is an example for reference). The data split should meet the following format ('testing' labels are optional):
 
14
  ```json
15
  {
16
  "training": [
@@ -25,124 +63,57 @@ To train with other datasets, users need to provide a json data split for traini
25
  ]
26
  }
27
  ```
28
-
29
  ```
30
- Note the data is not the absolute path to the image and label file. The actual image file will be `os.path.join(dataset_dir, data["training"][item]["image"])`, where `dataset_dir` is defined in `configs/train_continual.json`. Also 5-fold cross-validation is not required! `fold=0` is defined in train.json, which means any data item with fold==0 will be used as validation and other fold will be used for training. So if you only have 2 data, you can manually set one data to be validation by setting "fold": 0 in its datalist and the other to be training by setting "fold" to any number other than 0.
31
  ```
32
-
33
- ### Best practice to generate data list
34
- User can use monai to generate the 5-fold data lists. Full exampls can be found in VISTA3D open source [codebase](https://github.com/Project-MONAI/VISTA/blob/main/vista3d/data/make_datalists.py)
35
- ```python
36
- from monai.data.utils import partition_dataset
37
- from monai.bundle import ConfigParser
38
- base_url = "/path_to_your_folder/"
39
- json_name = "./your_5_folds.json"
40
- # create matching image and label lists.
41
- # The code to generate the lists is based on your local data structure.
42
- # You can use glob.glob("**.nii.gz") e.t.c.
43
- image_list = ['images/1.nii.gz', 'images/2.nii.gz', ...]
44
- label_list = ['labels/1.nii.gz', 'labels/2.nii.gz', ...]
45
- items = [{"image": img, "label": lab} for img, lab in zip(image_list, label_list)]
46
- # 80% for training 20% for testing.
47
- train_test = partition_dataset(items, ratios=[0.8, 0.2], shuffle=True, seed=0)
48
- print(f"training: {len(train_test[0])}, testing: {len(train_test[1])}")
49
- # num_partitions-fold split for the training set.
50
- train_val = partition_dataset(train_test[0], num_partitions=5, shuffle=True, seed=0)
51
- print(f"training validation folds sizes: {[len(x) for x in train_val]}")
52
- # add the fold index to each training data.
53
- training = []
54
- for f, x in enumerate(train_val):
55
- for item in x:
56
- item["fold"] = f
57
- training.append(item)
58
- # save json file
59
- parser = ConfigParser({})
60
- parser["training"] = training
61
- parser["testing"] = train_test[1]
62
- print(f"writing {json_name}\n\n")
63
- if os.path.exists(json_name):
64
- logger.warning(f"rewrite existing datalist file: {json_name}")
65
- ConfigParser.export_config_file(parser.config, json_name, indent=4)
66
  ```
67
-
68
- ### Configurations
69
-
70
- #### `label_mappings`
71
- The core concept of label_mapping is to convert ground-truth label index of each dataset to a unified class index. For example, "Spleen" in MSD09 groundtruth will be represented by 1, while in AbdomenCT-1K it's 3. We unified a global label index (`docs/labels.json`) to represent all 132 classes, and create a label mapping to map those local index to this global index. So when a user is training on their own dataset, we need to know this mapping.
72
-
73
- The current label mapping `[[1, 3]]` indicates that training labels' class indices `1` is mapped
74
- to the VISTA model's class `3` (format `[[src_class_0, dst_class_0], [src_class_1, dst_class_1], ...]`). So during inference, "3" is used to segment spleen.
75
-
76
- Since it's finetuning, you can map your local class to any global class. If you use [[1,4]], where "4" represents pancreas, the finetuning can still work but requires more training data and epoch because the class "4" is already assigned and trained with pancreas. If you use [[1,3]], where "3" already represents spleen, the finetuning will converge much faster.
77
-
78
- #### Best practice to set label_mapping
79
-
80
- For a class that represent the same or similar class as the global index, directly map it to the global index. For example, "mouse left lung" (e.g. index 2 in the mouse dataset) can be mapped to the 28 "left lung upper lobe"(or 29 "left lung lower lobe") with [[2,28]]. After finetuning, 28 now represents "mouse left lung" and will be used for segmentation. If you want to segment 4 substructures of aorta, you can map one of the substructuress to 6 aorta and the rest to any unused classes (class > 132), [[1,6],[2,133],[3,134],[4,135]]. For a completely novel class that none of the VISTA global classes are related, directly map to unused classes (class > 132).
81
- ```
82
- NOTE: Do not map to global index value >= 255. `num_classes=255` in the config only represent the maximum mapping index, while the actual output class number only depends on your label_mapping definition. The 255 value in the inference output is also used to represent 'NaN' value.
83
  ```
84
- #### `n_train_samples` and `n_val_samples`
85
- In `train_continual.json`, only `n_train_samples` and `n_val_samples` are used for training and validation. Remember to change these two values.
86
 
87
- #### `patch_size`
88
- The patch size parameter is defined in `configs/train_continual.json`: `"patch_size": [128, 128, 128]`. For finetuning purposes, this value needs to be changed acccording to user's task and GPU memory. Usually a larger patch_size will give better final results.
89
 
90
- #### `resample_to_spacing`
91
- The resample_to_spacing parameter is defined in `configs/train_continual.json` and it represents the resolution the model will be trained on. The `1.5,1.5,1.5` mm default is suitable for large CT organs, but for other tasks, this value should be changed to achive the optimal performance.
92
 
93
- #### Advanced user: `drop_label_prob` and `drop_point_prob` (in train.json)
94
- VISTA3D is trained to perform both automatic (class prompts) and interactive point segmentation.
95
- `drop_label_prob` and `drop_point_prob` means percentage to remove class prompts and point prompts during training respectively. If `drop_point_prob=1`, the
96
- model is only finetuning for automatic segmentation, while `drop_label_prob=1` means only finetuning for interactive segmentation. The VISTA3D foundation
97
- model is trained with interactive only (drop_label_prob=1) and then froze the point branch and trained with fully automatic segmentation (`drop_point_prob=1`).
98
- In this bundle, the training is simplified by jointly training with class prompts and point prompts and both of the drop ratio is set to 0.25.
99
- ```
100
- NOTE: If user doesn't use interactive segmentation, set `drop_point_prob=1` and `drop_label_prob=0` in train.json might provide a faster and easier finetuning process.
101
- ```
102
- #### Other explanatory items
103
- In `train.json`, `validate[evaluator][val_head]` can be `auto` and `point`. If `auto`, the validation results will be automatic segmentation. If `point`,
104
- the validation results will be sampling one positive point per object per patch. The validation scheme of combining auto and point is deprecated due to
105
- speed issue.
106
-
107
- In `train_continual.json`, `valid_remap` is a transform that maps the groundtruth label indexes, e.g. [0,2,3,5,6] to sequential and continuous labels [0,1,2,3,4]. This is
108
- required by monai dice calculation. It is not related to mapping label index to VISTA3D defined global class index. The validation data is not mapped
109
- to the VISTA3D global class index.
110
-
111
- `label_set` is used to identify the VISTA model classes for providing training prompts.
112
- `val_label_set` is used to identify the original training label classes for computing foreground/background mask during validation.
113
- The default configs for both variables are derived from the `label_mappings` config and include `[0]`:
114
- ```
115
- "label_set": "$[0] + list(x[1] for x in @label_mappings#default)"
116
- "val_label_set": "$[0] + list(x[0] for x in @label_mappings#default)"
117
- ```
118
-
119
- Note: Please ensure the input data header is correct. The output file will use the same header as the input data, but if the input data is missing header information, MONAI will automatically provide some default values for missing values (e.g. `np.eye(4)` will be used if affine information is absent). This may cause a visualization misalignment depending on the visualization tool.
120
-
121
-
122
- ### Commands
123
 
124
  Single-GPU:
125
  ```bash
126
  python -m monai.bundle run \
127
- --config_file="['configs/train.json','configs/train_continual.json']" --epochs=320 --learning_rate=0.00005
128
  ```
129
 
130
  Multi-GPU:
131
  ```bash
132
  torchrun --nnodes=1 --nproc_per_node=8 -m monai.bundle run \
133
- --config_file="['configs/train.json','configs/train_continual.json','configs/multi_gpu_train.json']" --epochs=320 --learning_rate=0.00005
134
  ```
135
 
136
- ### MLFlow support
137
 
138
- MLflow can be enabled to track and manage your machine learning experiments. To enable MLflow, set the `use_mlflow` parameter to `True`. Below is an example of how to run a single-GPU training command with MLflow enabled:
139
-
140
- ```bash
141
- python -m monai.bundle run \
142
- --config_file="['configs/train.json','configs/train_continual.json']" --epochs=320 --learning_rate=0.00005 --use_mlflow True
143
- ```
144
-
145
- By default, the data of MLflow is stored in the `mlruns/` folder under the bundle's root directory. To launch the MLflow UI and track your experiment data, follow these steps:
146
 
147
  1. Open a terminal and navigate to the root directory of your bundle where the `mlruns/` folder is located.
148
 
@@ -152,7 +123,7 @@ By default, the data of MLflow is stored in the `mlruns/` folder under the bundl
152
  mlflow ui
153
  ```
154
 
155
- ## Evaluation
156
  Evaluation can be used to calculate dice scores for the model or a finetuned model. Change the `ckpt_path` to the checkpoint you wish to evaluate. The dice score is calculated on the original image spacing using `invertd`, while the dice score during finetuning is calculated on resampled space.
157
 
158
  ```
@@ -173,121 +144,27 @@ torchrun --nnodes=1 --nproc_per_node=8 -m monai.bundle run \
173
  #### Other explanatory items
174
  The `label_mapping` in `evaluation.json` does not include `0` because the postprocessing step performs argmax (`VistaPostTransformd`), and a `0` prediction would negatively impact performance. In continuous learning, however, `0` is included for validation because no argmax is performed, and validation is done channel-wise (include_background=False). Additionally, `Relabeld` in `postprocessing` is required to map `label` and `pred` back to sequential indexes like `0, 1, 2, 3, 4` for dice calculation, as they are not in one-hot format. Evaluation does not support `point`, but finetuning does, as it does not perform argmax.
175
 
176
- ## Inference:
177
- For inference, VISTA3d bundle requires at least one prompt for segmentation. It supports label prompt, which is the index of the class for automatic segmentation.
178
- It also supports point click prompts for binary interactive segmentation. User can provide both prompts at the same time.
179
-
180
- All the configurations for inference is stored in inference.json, change those parameters:
181
- ### `input_dict`
182
- `input_dict` defines the image to segment and the prompt for segmentation.
183
- ```
184
- "input_dict": "$[{'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'label_prompt':[1]}]",
185
- "input_dict": "$[{'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'points':[[138,245,18], [271,343,27]], 'point_labels':[1,0]}]"
186
- ```
187
- - The input_dict 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`.
188
- - 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.
189
- - 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
190
- 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.
191
- - **B must be 1 if label_prompt and points are provided together**. The inferer only supports SINGLE OBJECT point click segmentatation.
192
- - If no prompt is provided, the model will use `everything_labels` to segment 117 classes:
193
-
194
- ```Python
195
- 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]))
196
- ```
197
-
198
- - 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`.
199
- - 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.
200
-
201
- ### `label_prompt` and `label_dict`
202
- The `label_dict` defined in `docs/labels.json` has in total 132 classes. However, there are 5 we do not support and we keep them due to legacy issue. So in total
203
- VISTA3D support 127 classes.
204
-
205
- ```
206
- "16, # prostate or uterus" since we already have "prostate" class,
207
- "18, # rectum", insufficient data or dataset excluded.
208
- "130, # liver tumor" already have hepatic tumor.
209
- "129, # kidney mass" insufficient data or dataset excluded.
210
- "131, # vertebrae L6", insufficient data or dataset excluded.
211
- ```
212
-
213
- These 5 are excluded in the `everything_labels`. Another 7 tumor and vessel classes are also removed since they will overlap with other organs and make the output messy. To segment those 7 classes, we recommend users to directly set `label_prompt` to those indexes and avoid using them in `everything_labels`. For "Kidney", "Lung", "Bone" (class index [2, 20, 21]), VISTA3D did not directly use the class index for segmentation, but instead convert them to their subclass indexes as defined by `subclass` dict. For example, "2-Kidney" is converted to "14-Left Kidney" + "5-Right Kidney" since "2" is defined in `subclasss` dict.
214
-
215
- ```
216
- Note: if the finetuning mapped the local user data index to global index "2, 20, 21", remove the `subclass` dict from inference.json since those values defined in `subclass` will trigger the wrong subclass segmentation.
217
- ```
218
-
219
- ### `resample_spacing`
220
- The optimal inference resample spacing should be changed according to the task. For monkey data, a high resolution of [1,1,1] showed better automatic inference results. This spacing applies to both automatic and interactive segmentation. For zero-shot interactive segmentation for non-human CTs e.g. mouse CT or even rock/stone CT, using original resolution (set `resample_spacing` to [-1,-1,-1]) may give better interactive results.
221
-
222
- ### `use_point_window`
223
- When user click a point, there is no need to perform whole image sliding window inference. Set "use_point_window" to true in the inference.json to enable this function.
224
- A window centered at the clicked points will be used for inference. All values outside of the window will set to be "NaN" unless "prev_mask" is passed to the inferer (255 is used to represent NaN).
225
- If no point click exists, this function will not be used. Notice if "use_point_window" is true and user provided point clicks, there will be obvious cut-off box artefacts.
226
-
227
- ### Inference GPU benchmarks
228
- Benchmarks on a 16GB V100 GPU with 400G system cpu memory.
229
- | Volume size at 1.5x1.5x1.5 mm | 333x333x603 | 512x512x512 | 512x512x768 | 1024x1024x512 | 1024x1024x768 |
230
- | :---: | :---: | :---: | :---: | :---: | :---: |
231
- |RunTime| 1m07s | 2m09s | 3m25s| 9m20s| killed |
232
- ## Commands
233
- The bundle only provides single-gpu inference.
234
- ### Single image inference
235
- ```
236
- python -m monai.bundle run --config_file configs/inference.json
237
- ```
238
-
239
- ### Batch inference for segmenting everything
240
- ```
241
- python -m monai.bundle run --config_file="['configs/inference.json', 'configs/batch_inference.json']" --input_dir="/data/Task09_Spleen/imagesTr" --output_dir="./eval_task09"
242
- ```
243
-
244
- `configs/batch_inference.json` by default runs the segment everything workflow (classes defined by `everything_labels`) on all (`*.nii.gz`) files in `input_dir`.
245
- This default is overridable by changing the input folder `input_dir`, or the input image name suffix `input_suffix`, or directly setting the list of filenames `input_list`.
246
 
247
-
248
- ### Execute inference with the TensorRT model:
249
-
250
- ```
251
- python -m monai.bundle run --config_file "['configs/inference.json', 'configs/inference_trt.json']"
252
- ```
253
-
254
- By default, the argument `head_trt_enabled` is set to `false` in `configs/inference_trt.json`. This means that the `class_head` module of the network will not be converted into a TensorRT model. Setting this to `true` may accelerate the process, but there are some limitations:
255
-
256
- Since the `label_prompt` will be converted into a tensor and input into the `class_head` module, the batch size of this input tensor will equal the length of the original `label_prompt` list (if no prompt is provided, the length is 117). To make the TensorRT model work on the `class_head` module, you should set a suitable dynamic batch size range. The maximum dynamic batch size can be configured using the argument `max_prompt_size` in `configs/inference_trt.json`. If the length of the `label_prompt` list exceeds `max_prompt_size`, the engine will fall back to using the normal PyTorch model for inference. Setting a larger `max_prompt_size` can cover more input cases but may require more GPU memory (the default value is 4, which requires 16 GB of GPU memory). Therefore, please set it to a reasonable value according to your actual requirements.
257
-
258
-
259
- ### TroubleShoot for Out-of-Memory
260
  - Changing `patch_size` to a smaller value such as `"patch_size": [96, 96, 96]` would reduce the training/inference memory footprint.
261
  - Changing `train_dataset_cache_rate` and `val_dataset_cache_rate` to a smaller value like `0.1` can solve the out-of-cpu memory issue when using huge finetuning dataset.
262
  - Set `"postprocessing#transforms#0#_disabled_": false` to move the postprocessing to cpu to reduce the GPU memory footprint.
263
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
 
266
- ### TensorRT speedup
267
- The `vista3d` bundle supports acceleration with TensorRT. The table below displays the speedup ratios observed on an A100 80G GPU. Please note for 32bit precision models, they are benchmarked with tf32 weight format.
268
-
269
- | method | torch_tf32(ms) | torch_amp(ms) | trt_tf32(ms) | trt_fp16(ms) | speedup amp | speedup tf32 | speedup fp16 | amp vs fp16|
270
- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
271
- | model computation | 108.53| 91.9 | 106.84 | 60.02 | 1.18 | 1.02 | 1.81 | 1.53 |
272
- | end2end | 6740 | 5166 | 5242 | 3386 | 1.30 | 1.29 | 1.99 | 1.53 |
273
-
274
- Where:
275
- - `model computation` means the speedup ratio of model's inference with a random input without preprocessing and postprocessing
276
- - `end2end` means run the bundle end-to-end with the TensorRT based model.
277
- - `torch_tf32` and `torch_amp` are for the PyTorch models with or without `amp` mode.
278
- - `trt_tf32` and `trt_fp16` are for the TensorRT based models converted in corresponding precision.
279
- - `speedup amp`, `speedup tf32` and `speedup fp16` are the speedup ratios of corresponding models versus the PyTorch float32 model
280
- - `amp vs fp16` is the speedup ratio between the PyTorch amp model and the TensorRT float16 based model.
281
-
282
- This result is benchmarked under:
283
- - TensorRT: 10.3.0+cuda12.6
284
- - Torch-TensorRT Version: 2.4.0
285
- - CPU Architecture: x86-64
286
- - OS: ubuntu 20.04
287
- - Python version:3.10.12
288
- - CUDA version: 12.6
289
- - GPU models and configuration: A100 80G
290
-
291
  # References
292
  - 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
293
 
 
1
  # Model Overview
2
  Vista3D model fintuning/evaluation/inference pipeline. VISTA3D is trained using over 20 partial datasets with more complicated pipeline. To avoid confusion, we will only provide finetuning/continual learning APIs for users to finetune on their
3
+ own datasets. To reproduce the paper results, please refer to https://github.com/Project-MONAI/VISTA/tree/main/vista3d
4
 
5
+ # Installation Guide
6
+ ```
7
+ pip install "monai[fire]"
8
+ python -m monai.bundle download "vista3d" --bundle_dir "bundles/"
9
+ ```
10
+ Please refer to monai model zoo (https://github.com/Project-MONAI/model-zoo) for more details.
11
+ # Inference:
12
+ The bundle only provides single-gpu inference. User can modify within the inference [config](../configs/inference.json).
13
+ ## Single image inference to segment everything (automatic)
14
+ The output will be saved to `output_dir/spleen_03/spleen_03_{output_postfix}{output_ext}`.
15
+ ```
16
+ python -m monai.bundle run --config_file configs/inference.json --input_dict "{'image':'spleen_03.nii.gz'}
17
+ ```
18
+ ## Single image inference to segment specific class (automatic)
19
+ The detailed automatic segmentation class index can be found [here](../configs/metadata.json).
20
+ ```
21
+ python -m monai.bundle run --config_file configs/inference.json --input_dict "{'image':'spleen_03.nii.gz','label_prompt':[3]}
22
+ ```
23
+
24
+ ## Batch inference for segmenting everything (automatic)
25
+ ```
26
+ python -m monai.bundle run --config_file="['configs/inference.json', 'configs/batch_inference.json']" --input_dir="/data/Task09_Spleen/imagesTr" --output_dir="./eval_task09"
27
+ ```
28
+ `configs/batch_inference.json` by default runs the segment everything workflow (classes defined by `everything_labels`) on all (`*.nii.gz`) files in `input_dir`.
29
+ This default is overridable by changing the input folder `input_dir`, or the input image name suffix `input_suffix`, or directly setting the list of filenames `input_list`.
30
+
31
+ ```
32
+ Note: if using the finetuned checkpoint and the finetuning label_mapping mapped to global index "2, 20, 21", remove the `subclass` dict from inference.json since those values defined in `subclass` will trigger the wrong subclass segmentation.
33
+ ```
34
+
35
+ ## Configuration details and interactive segmentation
36
 
37
+ For inference, VISTA3d bundle requires at least one prompt for segmentation. It supports label prompt, which is the index of the class for automatic segmentation.
38
+ It also supports point click prompts for binary interactive segmentation. User can provide both prompts at the same time. Please refer to [this](inference.md).
39
+
40
+ ## Execute inference with the TensorRT model:
41
+
42
+ ```
43
+ python -m monai.bundle run --config_file "['configs/inference.json', 'configs/inference_trt.json']"
44
+ ```
45
+ For more details, please refer to [this](inference.md).
46
 
 
47
 
48
+ # Continual learning / Finetuning
49
 
50
+ ## Step1: Generate Data json file
51
+ Users need to provide a json data split for continuous learning (`configs/msd_task09_spleen_folds.json` from the [MSD](http://medicaldecathlon.com/) is provided as an example). The data split should meet the following format ('testing' labels are optional):
52
  ```json
53
  {
54
  "training": [
 
63
  ]
64
  }
65
  ```
66
+ Example code for 5 fold cross-validation generation can be found [here](data.md)
67
  ```
68
+ Note the data is not the absolute path to the image and label file. The actual image file will be `os.path.join(dataset_dir, data["training"][item]["image"])`, where `dataset_dir` is defined in `configs/train_continual.json`. Also 5-fold cross-validation is not required! `fold=0` is defined in train.json, which means any data item with fold==0 will be used as validation and other fold will be used for training. So if you only have train/val split, you can manually set validation data with "fold": 0 in its datalist and the other to be training by setting "fold" to any number other than 0.
69
  ```
70
+ ## Step2: Changing hyperparameters
71
+ For continual learning, user can change `configs/train_continual.json`. More advanced users can change configurations in `configs/train.json`. Most hyperparameters are straighforward and user can tell based on their names. The users must manually change the following keys in `configs/train_continual.json`.
72
+ #### 1. `label_mappings`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  ```
74
+ "label_mappings": {
75
+ "default": [
76
+ [
77
+ index_1_in_user_data, # e.g. 1
78
+ mapped_index_1, # e.g. 1
79
+ ],
80
+ [
81
+ index_2_in_user_data, # e.g. 2
82
+ mapped_index_2, # e.g. 2
83
+ ], ...,
84
+ [
85
+ index_last_in_user_data, # e.g. N
86
+ mapped_index_N, # e.g. N
87
+ ]
88
+ ]
89
+ },
90
  ```
91
+ `index_1_in_user_data`,...,`index_N_in_user_data` is the class index value in the groundtruth that user tries to segment. `mapped_index_1`,...,`mapped_index_N` is the mapped index value that the bundle will output. You can make these two the same for finetuning, but we suggest finding the semantic relevant mappings from our unified [global label index](../configs/metadata.json). For example, "Spleen" in MSD09 groundtruth label is represented by 1, but "Spleen" is 3 in `docs/labels.json`. So by defining label mapping `[[1, 3]]`, VISTA3D can segment "Spleen" using its pretrained weights out-of-the-box, and can speed up the finetuning convergence speed. If you cannot find a relevant semantic label for your class, just use any value < `num_classes` defined in train_continue.json. For more details about this label_mapping, please read [this](finetune.md).
 
92
 
93
+ #### 2. `data_list_file_path` and `dataset_dir`
94
+ Change `data_list_file_path` to the absolute path of your data json split. Change `dataset_dir` to the root folder that combines with the relative path in the data json split.
95
 
96
+ #### 3. Optional hyperparameters and details are [here](finetune.md).
97
+ Hyperparameteers finetuning is important and varies from task to task.
98
 
99
+ ## Step3: Run finetuning
100
+ The hyperparameters in `configs/train_continual.json` will overwrite ones in `configs/train.json`. Configs in the back will overide the previous ones if they have the same key.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  Single-GPU:
103
  ```bash
104
  python -m monai.bundle run \
105
+ --config_file="['configs/train.json','configs/train_continual.json']"
106
  ```
107
 
108
  Multi-GPU:
109
  ```bash
110
  torchrun --nnodes=1 --nproc_per_node=8 -m monai.bundle run \
111
+ --config_file="['configs/train.json','configs/train_continual.json','configs/multi_gpu_train.json']"
112
  ```
113
 
114
+ #### MLFlow Visualization
115
 
116
+ MLFlow is enabled by default (defined in train.json, use_mlflow) and the data is stored in the `mlruns/` folder under the bundle's root directory. To launch the MLflow UI and track your experiment data, follow these steps:
 
 
 
 
 
 
 
117
 
118
  1. Open a terminal and navigate to the root directory of your bundle where the `mlruns/` folder is located.
119
 
 
123
  mlflow ui
124
  ```
125
 
126
+ # Evaluation
127
  Evaluation can be used to calculate dice scores for the model or a finetuned model. Change the `ckpt_path` to the checkpoint you wish to evaluate. The dice score is calculated on the original image spacing using `invertd`, while the dice score during finetuning is calculated on resampled space.
128
 
129
  ```
 
144
  #### Other explanatory items
145
  The `label_mapping` in `evaluation.json` does not include `0` because the postprocessing step performs argmax (`VistaPostTransformd`), and a `0` prediction would negatively impact performance. In continuous learning, however, `0` is included for validation because no argmax is performed, and validation is done channel-wise (include_background=False). Additionally, `Relabeld` in `postprocessing` is required to map `label` and `pred` back to sequential indexes like `0, 1, 2, 3, 4` for dice calculation, as they are not in one-hot format. Evaluation does not support `point`, but finetuning does, as it does not perform argmax.
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ # FAQ
149
+ ## TroubleShoot for Out-of-Memory
 
 
 
 
 
 
 
 
 
 
 
150
  - Changing `patch_size` to a smaller value such as `"patch_size": [96, 96, 96]` would reduce the training/inference memory footprint.
151
  - Changing `train_dataset_cache_rate` and `val_dataset_cache_rate` to a smaller value like `0.1` can solve the out-of-cpu memory issue when using huge finetuning dataset.
152
  - Set `"postprocessing#transforms#0#_disabled_": false` to move the postprocessing to cpu to reduce the GPU memory footprint.
153
 
154
+ ## Multi-channel input
155
+ - Change `input_channels` in `train.json` to your desired channel number
156
+ - Data split json can be a single multi-channel image or can be a list of single channeled images. Those images must have the same spatial shape and aligned/registered.
157
+ ```
158
+ {
159
+ "image": ["modality1.nii.gz", "modality2.nii.gz", "modality3.nii.gz"]
160
+ "label": "label.nii.gz"
161
+ },
162
+ ```
163
+ ## Wrong inference results from finetuned checkpoint
164
+ - Make sure you removed the `subclass` dictionary from inference.json if you ever mapped local index to [2,20,21]
165
+ - Make sure `0` is not included in your inference prompt for automatic segmentation.
166
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  # References
169
  - 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
170
 
docs/data.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Best practice to generate data list
2
+ User can use monai to generate the 5-fold data lists. Full exampls can be found in VISTA3D open source [codebase](https://github.com/Project-MONAI/VISTA/blob/main/vista3d/data/make_datalists.py)
3
+ ```python
4
+ from monai.data.utils import partition_dataset
5
+ from monai.bundle import ConfigParser
6
+ base_url = "/path_to_your_folder/"
7
+ json_name = "./your_5_folds.json"
8
+ # create matching image and label lists.
9
+ # The code to generate the lists is based on your local data structure.
10
+ # You can use glob.glob("**.nii.gz") e.t.c.
11
+ image_list = ['images/1.nii.gz', 'images/2.nii.gz', ...]
12
+ label_list = ['labels/1.nii.gz', 'labels/2.nii.gz', ...]
13
+ items = [{"image": img, "label": lab} for img, lab in zip(image_list, label_list)]
14
+ # 80% for training 20% for testing.
15
+ train_test = partition_dataset(items, ratios=[0.8, 0.2], shuffle=True, seed=0)
16
+ print(f"training: {len(train_test[0])}, testing: {len(train_test[1])}")
17
+ # num_partitions-fold split for the training set.
18
+ train_val = partition_dataset(train_test[0], num_partitions=5, shuffle=True, seed=0)
19
+ print(f"training validation folds sizes: {[len(x) for x in train_val]}")
20
+ # add the fold index to each training data.
21
+ training = []
22
+ for f, x in enumerate(train_val):
23
+ for item in x:
24
+ item["fold"] = f
25
+ training.append(item)
26
+ # save json file
27
+ parser = ConfigParser({})
28
+ parser["training"] = training
29
+ parser["testing"] = train_test[1]
30
+ print(f"writing {json_name}\n\n")
31
+ if os.path.exists(json_name):
32
+ logger.warning(f"rewrite existing datalist file: {json_name}")
33
+ ConfigParser.export_config_file(parser.config, json_name, indent=4)
34
+ ```
docs/finetune.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Configurations
2
+
3
+
4
+
5
+ #### Best practice to set label_mapping
6
+
7
+ For a class that represent the same or similar class as the global index, directly map it to the global index. For example, "mouse left lung" (e.g. index 2 in the mouse dataset) can be mapped to the 28 "left lung upper lobe"(or 29 "left lung lower lobe") with [[2,28]]. After finetuning, 28 now represents "mouse left lung" and will be used for segmentation. If you want to segment 4 substructures of aorta, you can map one of the substructuress to 6 aorta and the rest to any value, [[1,6],[2,133],[3,134],[4,135]].
8
+ ```
9
+ NOTE: Do not map to global index value >= 255. `num_classes=255` in the config only represent the maximum mapping index, while the actual output class number only depends on your label_mapping definition. The 255 value in the inference output is also used to represent 'NaN' value.
10
+ ```
11
+
12
+ #### `val_at_start`
13
+ Default `true`, VISTA3D will perform out-of-the-box segmentation before the training.
14
+ Users can disable if the validation takes too long.
15
+
16
+
17
+ #### `n_train_samples` and `n_val_samples`
18
+ In `train_continual.json`, only `n_train_samples` and `n_val_samples` are used for training and validation.
19
+
20
+ #### `patch_size`
21
+ The patch size parameter is defined in `configs/train_continual.json`: `"patch_size": [128, 128, 128]`. For finetuning purposes, this value needs to be changed acccording to user's task and GPU memory. Usually a larger patch_size will give better final results. `[192,192,128]` is a good value for larger memory GPU.
22
+
23
+ #### `resample_to_spacing`
24
+ The resample_to_spacing parameter is defined in `configs/train_continual.json` and it represents the resolution the model will be trained on. The `1.5,1.5,1.5` mm default is suitable for large CT organs, but for other tasks, this value should be changed to achive the optimal performance.
25
+
26
+ #### Advanced user: `drop_label_prob` and `drop_point_prob` (in train.json)
27
+ VISTA3D is trained to perform both automatic (class prompts) and interactive point segmentation.
28
+ `drop_label_prob` and `drop_point_prob` means percentage to remove class prompts and point prompts during training respectively. If `drop_point_prob=1`, the
29
+ model is only finetuning for automatic segmentation, while `drop_label_prob=1` means only finetuning for interactive segmentation. The VISTA3D foundation
30
+ model is trained with interactive only (drop_label_prob=1) and then froze the point branch and trained with fully automatic segmentation (`drop_point_prob=1`).
31
+ In this bundle, the training is simplified by jointly training with class prompts and point prompts and both of the drop ratio is set to 0.25.
32
+ ```
33
+ NOTE: If user doesn't use interactive segmentation, set `drop_point_prob=1` and `drop_label_prob=0` in train.json might provide a faster and easier finetuning process.
34
+ ```
35
+ #### Other explanatory items
36
+ In `train.json`, `validate[evaluator][val_head]` can be `auto` and `point`. If `auto`, the validation results will be automatic segmentation. If `point`,
37
+ the validation results will be sampling one positive point per object per patch. The validation scheme of combining auto and point is deprecated due to
38
+ speed issue.
39
+
40
+ In `train_continual.json`, `valid_remap` is a transform that maps the groundtruth label indexes, e.g. [0,2,3,5,6] to sequential and continuous labels [0,1,2,3,4]. This is
41
+ required by monai dice calculation. It is not related to mapping label index to VISTA3D defined global class index. The validation data is not mapped
42
+ to the VISTA3D global class index.
43
+
44
+ `label_set` is used to identify the VISTA model classes for providing training prompts.
45
+ `val_label_set` is used to identify the original training label classes for computing foreground/background mask during validation.
46
+ The default configs for both variables are derived from the `label_mappings` config and include `[0]`:
47
+ ```
48
+ "label_set": "$[0] + list(x[1] for x in @label_mappings#default)"
49
+ "val_label_set": "$[0] + list(x[0] for x in @label_mappings#default)"
50
+ ```
51
+
52
+ Note: Please ensure the input data header is correct. The output file will use the same header as the input data, but if the input data is missing header information, MONAI will automatically provide some default values for missing values (e.g. `np.eye(4)` will be used if affine information is absent). This may cause a visualization misalignment depending on the visualization tool.
docs/inference.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ All the configurations for inference is stored in inference.json, change those parameters:
2
+ ### `input_dict`
3
+ `input_dict` defines the image to segment and the prompt for segmentation.
4
+ ```
5
+ "input_dict": "$[{'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'label_prompt':[1]}]",
6
+ "input_dict": "$[{'image': '/data/Task09_Spleen/imagesTs/spleen_15.nii.gz', 'points':[[138,245,18], [271,343,27]], 'point_labels':[1,0]}]"
7
+ ```
8
+ - The input_dict 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`.
9
+ - 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.
10
+ - 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
11
+ 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.
12
+ - **B must be 1 if label_prompt and points are provided together**. The inferer only supports SINGLE OBJECT point click segmentatation.
13
+ - If no prompt is provided, the model will use `everything_labels` to segment 117 classes:
14
+
15
+ ```Python
16
+ 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]))
17
+ ```
18
+
19
+ - 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`.
20
+ - 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.
21
+
22
+ ### `label_prompt` and `label_dict`
23
+ The `label_dict` defined in `configs/metadata.json` has in total 132 classes. However, there are 5 we do not support and we keep them due to legacy issue. So in total
24
+ VISTA3D support 127 classes.
25
+
26
+ ```
27
+ "16, # prostate or uterus" since we already have "prostate" class,
28
+ "18, # rectum", insufficient data or dataset excluded.
29
+ "130, # liver tumor" already have hepatic tumor.
30
+ "129, # kidney mass" insufficient data or dataset excluded.
31
+ "131, # vertebrae L6", insufficient data or dataset excluded.
32
+ ```
33
+
34
+ These 5 are excluded in the `everything_labels`. Another 7 tumor and vessel classes are also removed since they will overlap with other organs and make the output messy. To segment those 7 classes, we recommend users to directly set `label_prompt` to those indexes and avoid using them in `everything_labels`. For "Kidney", "Lung", "Bone" (class index [2, 20, 21]), VISTA3D did not directly use the class index for segmentation, but instead convert them to their subclass indexes as defined by `subclass` dict. For example, "2-Kidney" is converted to "14-Left Kidney" + "5-Right Kidney" since "2" is defined in `subclasss` dict.
35
+
36
+ ### `resample_spacing`
37
+ The optimal inference resample spacing should be changed according to the task. For monkey data, a high resolution of [1,1,1] showed better automatic inference results. This spacing applies to both automatic and interactive segmentation. For zero-shot interactive segmentation for non-human CTs e.g. mouse CT or even rock/stone CT, using original resolution (set `resample_spacing` to [-1,-1,-1]) may give better interactive results.
38
+
39
+ ### `use_point_window`
40
+ When user click a point, there is no need to perform whole image sliding window inference. Set "use_point_window" to true in the inference.json to enable this function.
41
+ A window centered at the clicked points will be used for inference. All values outside of the window will set to be "NaN" unless "prev_mask" is passed to the inferer (255 is used to represent NaN).
42
+ If no point click exists, this function will not be used. Notice if "use_point_window" is true and user provided point clicks, there will be obvious cut-off box artefacts.
43
+
44
+
45
+ ### Inference GPU benchmarks
46
+ Benchmarks on a 16GB V100 GPU with 400G system cpu memory.
47
+ | Volume size at 1.5x1.5x1.5 mm | 333x333x603 | 512x512x512 | 512x512x768 | 1024x1024x512 | 1024x1024x768 |
48
+ | :---: | :---: | :---: | :---: | :---: | :---: |
49
+ |RunTime| 1m07s | 2m09s | 3m25s| 9m20s| killed |
50
+
51
+
52
+
53
+ ### Execute inference with the TensorRT model:
54
+
55
+ ```
56
+ python -m monai.bundle run --config_file "['configs/inference.json', 'configs/inference_trt.json']"
57
+ ```
58
+
59
+ By default, the argument `head_trt_enabled` is set to `false` in `configs/inference_trt.json`. This means that the `class_head` module of the network will not be converted into a TensorRT model. Setting this to `true` may accelerate the process, but there are some limitations:
60
+
61
+ Since the `label_prompt` will be converted into a tensor and input into the `class_head` module, the batch size of this input tensor will equal the length of the original `label_prompt` list (if no prompt is provided, the length is 117). To make the TensorRT model work on the `class_head` module, you should set a suitable dynamic batch size range. The maximum dynamic batch size can be configured using the argument `max_prompt_size` in `configs/inference_trt.json`. If the length of the `label_prompt` list exceeds `max_prompt_size`, the engine will fall back to using the normal PyTorch model for inference. Setting a larger `max_prompt_size` can cover more input cases but may require more GPU memory (the default value is 4, which requires 16 GB of GPU memory). Therefore, please set it to a reasonable value according to your actual requirements.
62
+
63
+
64
+ ### TensorRT speedup
65
+ The `vista3d` bundle supports acceleration with TensorRT. The table below displays the speedup ratios observed on an A100 80G GPU. Please note for 32bit precision models, they are benchmarked with tf32 weight format.
66
+
67
+ | method | torch_tf32(ms) | torch_amp(ms) | trt_tf32(ms) | trt_fp16(ms) | speedup amp | speedup tf32 | speedup fp16 | amp vs fp16|
68
+ | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
69
+ | model computation | 108.53| 91.9 | 106.84 | 60.02 | 1.18 | 1.02 | 1.81 | 1.53 |
70
+ | end2end | 6740 | 5166 | 5242 | 3386 | 1.30 | 1.29 | 1.99 | 1.53 |
71
+
72
+ Where:
73
+ - `model computation` means the speedup ratio of model's inference with a random input without preprocessing and postprocessing
74
+ - `end2end` means run the bundle end-to-end with the TensorRT based model.
75
+ - `torch_tf32` and `torch_amp` are for the PyTorch models with or without `amp` mode.
76
+ - `trt_tf32` and `trt_fp16` are for the TensorRT based models converted in corresponding precision.
77
+ - `speedup amp`, `speedup tf32` and `speedup fp16` are the speedup ratios of corresponding models versus the PyTorch float32 model
78
+ - `amp vs fp16` is the speedup ratio between the PyTorch amp model and the TensorRT float16 based model.
79
+
80
+ This result is benchmarked under:
81
+ - TensorRT: 10.3.0+cuda12.6
82
+ - Torch-TensorRT Version: 2.4.0
83
+ - CPU Architecture: x86-64
84
+ - OS: ubuntu 20.04
85
+ - Python version:3.10.12
86
+ - CUDA version: 12.6
87
+ - GPU models and configuration: A100 80G
scripts/inferer.py CHANGED
@@ -62,8 +62,11 @@ class Vista3dInferer(Inferer):
62
 
63
  """
64
  prompt_class = copy.deepcopy(class_vector)
65
- if class_vector is not None:
66
- # Check if network has attribute 'point_head' directly or within its 'module'
 
 
 
67
  if hasattr(network, "point_head"):
68
  point_head = network.point_head
69
  elif hasattr(network, "module") and hasattr(network.module, "point_head"):
 
62
 
63
  """
64
  prompt_class = copy.deepcopy(class_vector)
65
+ if class_vector is not None and (point_labels is not None and torch.any(point_labels != -1)):
66
+ # Only when user perform zero-shot interactive during inference. Remove the class vector
67
+ # and keep the prompt_class to inform the model about the zero-shot. During finetuning,
68
+ # a novel class > last_supported is possible and should be taken care of.
69
+ # This check should be moved to evaluator and prompt_class should be added as input to the inferer.
70
  if hasattr(network, "point_head"):
71
  point_head = network.point_head
72
  elif hasattr(network, "module") and hasattr(network.module, "point_head"):
scripts/trainer.py CHANGED
@@ -184,6 +184,8 @@ class Vista3dTrainer(Trainer):
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)
 
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
+ if prompt_class[id] == 0:
188
+ continue
189
  loss += engine.loss_function(outputs[[id]].float(), labels == prompt_class[id])
190
  loss_n += 1.0
191
  loss /= max(loss_n, 1.0)