NV-Segment-CT Finetune
Purpose
- Used for smoke or dataset finetuning of NV-Segment-CT VISTA3D on CT NIfTI labels. Not for clinical validation.
- Wraps the upstream MONAI bundle entrypoint; do not replace it with handwritten training or inference code.
- Manifest inputs are
dataset_dir, datalist, target_anatomy, label_mapping, smoke, sanity, auto_seg, and skip_formal_eval.
- Manifest outputs are
finetuned_ckpt and schema-checked result_json.
Instructions
- Run
scripts/run_finetune.py; do not patch files under bundle/ or upstream checkouts during normal skill use.
- For standalone Bash, include the fresh-environment setup line before the wrapper; benchmark venvs start empty.
- Run the committed script in place from the repo root. Do not copy this skill to a runtime directory, and do not use
rm or cleanup commands in generated invocations.
- If a host exposes
run_script, use run_script("scripts/run_finetune.py", args=[...]); otherwise run from the repo root.
- For the shortest workflow check, use
--smoke; for MSD Task06 Lung Tumor reproduction, use --sanity.
- Read
references/task06-and-results.md only when you need Task06 reference details, output-field definitions, or manual bundle setup notes.
Available Scripts
| Script |
Purpose |
Arguments |
scripts/run_finetune.py |
Primary entrypoint declared by skill_manifest.yaml; stages configs, runs MONAI, and writes output.json. |
[FIXTURE_OR_DATASET] --output-dir OUT_DIR [--smoke] [--sanity] [--auto-seg] [--dataset-dir DIR] [--datalist JSON] [--target-anatomy TEXT] [--label-mapping JSON] [--patch-size JSON] |
Prerequisites
- Python 3.10+ with CUDA-capable Torch for GPU runs.
- Runtime packages from
skill_manifest.yaml, especially monai==1.4.0, numpy<2, nibabel, scipy, typer, PyYAML, fire, pytorch-ignite, einops, and huggingface_hub.
- Optional environment variables:
CUDA_VISIBLE_DEVICES restricts visible GPUs; NPROC_PER_NODE overrides GPU count and values >=2 select multi-GPU mode for non-sanity runs.
- Side effects: writes generated bundle configs under
skills/nv-segment-ct-finetune/bundle/configs/, including skills/nv-segment-ct-finetune/bundle/configs/auto_override.json, skills/nv-segment-ct-finetune/bundle/configs/train_continual_task06_lung.json, and skills/nv-segment-ct-finetune/bundle/configs/dfw_no_logging.json; writes checkpoints/evidence under --output-dir, may cache model assets under ~/.cache/huggingface/, and may contact https://huggingface.co or https://raw.githubusercontent.com.
Fresh environment setup:
python -m pip install "monai==1.4.0" "numpy<2" pytorch-ignite einops nibabel scipy typer PyYAML fire huggingface_hub
Known upstream compatibility constraints:
- DFW Task06 reference: Python
3.10.16, MONAI 1.4.0, Torch 2.7.0+cu126.
- Use exact
monai==1.4.0 for smoke, sanity, and evidence runs; MONAI 1.5.x can crash the upstream finetune loss on boolean labels.
- Do not float the dependency as
monai>=1.4,<1.6 in generated commands.
Usage
Smoke-scale workflow check:
python -m pip install "monai==1.4.0" "numpy<2" pytorch-ignite einops nibabel scipy typer PyYAML fire huggingface_hub && \
python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
PATH_TO_DATASET \
--smoke \
--patch-size '[64,64,64]' \
--output-dir runs/nvseg_smoke
Use the staged dataset as PATH_TO_DATASET. For the micro fixture, use skills/nv-segment-ct-finetune/fixtures/spleen_micro. Smoke mode proves wiring, config generation, checkpoint loading, and runtime compatibility; it is not a quality bar.
MSD Task06 Lung Tumor sanity reproduction:
python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
/path/to/Task06 \
--sanity \
--output-dir runs/nvseg_task06_sanity
The sanity preset follows the single-GPU DFW recipe: fold-0 validation, label mapping [[1, 23]] for lung tumor, automatic class-prompt segmentation, patch [128,128,128], 5 epochs, and original-spacing configs/evaluate.json scoring before and after training. Expected reference range is pretrained Dice about 0.6697, training-best Dice about 0.6905, and fine-tuned formal Dice about 0.6836.
User-data finetune:
python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
--dataset-dir /path/to/dataset \
--datalist /path/to/datalist.json \
--target-anatomy "lung tumor" \
--auto-seg \
--epochs 5 \
--patch-size '[128,128,128]' \
--output-dir runs/nvseg_user_finetune
Use --label-mapping '[[1, 23]]' when local label values are custom or the anatomy name is ambiguous.
Examples
Smoke run on a staged tiny dataset:
python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
runs/with_vs_without_nv/_inputs/nv_segment_ct_finetune/input_dataset \
--smoke \
--patch-size '[64,64,64]' \
--output-dir runs/nvseg_smoke
Task06 sanity run on a local MSD cache:
python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
.workbench_data/datasets/Task06_Lung \
--sanity \
--output-dir runs/nvseg_task06_sanity
Data Contract
- Preferred layout:
dataset/imagesTr/*.nii.gz and dataset/labelsTr/*.nii.gz.
- Labels must align one-to-one with images by basename.
- The target label value must be present in the training labels.
- Use a datalist when patient-level splitting matters. The bundle default
fold is 0, so fold: 0 entries are validation and all other folds are training.
- Every trained foreground label must map to an existing VISTA3D global class id from
bundle/label_dict.json; this skill cannot invent a new class.
Results
Check output.json in the run directory first:
formal_pretrained_val_dice and formal_finetuned_val_dice: original-spacing pre/post scores when formal eval is enabled.
training_start_val_dice, val_dice_per_epoch, and training_best_val_dice: training-time validation trace.
finetuned_ckpt_matches_pretrained_weights: detects the epoch-0 checkpoint trap when val_at_start=true.
recommended_ckpt: checkpoint to keep. Do not blindly use the last epoch or model_finetune.pt.
runtime.oom, runtime.peak_gpu_mb, and phase logs: distinguish OOM, slow validation, and process failure.
Decision rule: prefer formal original-spacing pre/post scores when present; reject tensor-identical "fine-tuned" checkpoints for sanity recovery; treat improved: false as valid evidence rather than a wrapper failure.
Limitations
- Thin wrapper. Training, validation, transforms, and checkpointing are delegated to the upstream bundle in
bundle/.
- Reproduction record only: the successful five-epoch Task06 run used Python
3.12.3, PyTorch 2.12.0+cu130 with CUDA 13.0, MONAI 1.4.0, NumPy
1.26.4, PyTorch-Ignite 0.5.4, NiBabel 5.4.2, SciPy 1.16.0, einops
0.8.2, Fire 0.7.1, Hugging Face Hub 0.36.2, Transformers 4.57.6,
Typer 0.25.1, PyYAML 6.0.3, and MLflow 3.14.0 on one NVIDIA RTX 6000
Ada 48 GB GPU. These versions document the evidence environment; they are
not additional package constraints or a claim that other versions cannot
work.
- The auto-derived plan is heuristic; caller-provided
--patch-size, --cache-rate, --epochs, and --learning-rate win.
- The Task06 sanity recipe intentionally forces single-GPU execution to match the DFW reference. Multi-GPU mode for other datasets requires host
torchrun support.
- The paired verifier is CPU-only and audits the evidence pack; it does not re-run GPU segmentation.
- Not for clinical deployment, clinical interpretation, autonomous diagnosis, or regulatory submission.
Troubleshooting
| Error |
Cause |
Fix |
| Missing dependency or import error |
Runtime drift from skill_manifest.yaml. |
Install the packages above or use the documented environment. |
| Low Task06 pretrained Dice |
Wrong config, wrong checkpoint, data split drift, or dependency drift. |
Compare environment fields and staged configs before changing training logic. |
model_finetune.pt matches pretrained |
val_at_start=true selected epoch 0 as best. |
Use recommended_ckpt; treat sanity recovery as failed unless a changed checkpoint improves formal Dice. |
| Missing formal Dice fields |
Formal eval failed or was skipped. |
Inspect eval_pretrained.log, eval_finetuned.log, and metrics.csv. |
| GPU out of memory |
Patch/cache settings too large. |
Reduce --patch-size, lower --cache-rate, or reduce workers. |
| No validation cases |
Datalist lacks fold: 0. |
Provide at least one validation entry. |
Verification
Run the implemented verifier when quality gates matter:
python -m eval_engine.run_trusted skills/nv-segment-ct-finetune \
--fixture skills/nv-segment-ct-finetune/fixtures/spleen_micro \
--out runs/nvseg_trusted
1---
2name: nv-segment-ct-finetune
3description: Used for smoke or dataset finetuning of NV-Segment-CT VISTA3D on CT NIfTI labels. Not for clinical validation.
4license: Apache-2.0
5allowed-tools: Bash
6metadata:
7 source: https://skillmd.com/skills/solizardking/nv-segment-ct-finetune
8 author: NVIDIA MedTech Team
9 tags:
10 - MedTech
11 - CT
12 - finetuning
13 - segmentation
14---
15
16# NV-Segment-CT Finetune
17
18## Purpose
19
20- Used for smoke or dataset finetuning of NV-Segment-CT VISTA3D on CT NIfTI labels. Not for clinical validation.
21- Wraps the upstream MONAI bundle entrypoint; do not replace it with handwritten training or inference code.
22- Manifest inputs are `dataset_dir`, `datalist`, `target_anatomy`, `label_mapping`, `smoke`, `sanity`, `auto_seg`, and `skip_formal_eval`.
23- Manifest outputs are `finetuned_ckpt` and schema-checked `result_json`.
24
25## Instructions
26
27- Run `scripts/run_finetune.py`; do not patch files under `bundle/` or upstream checkouts during normal skill use.
28- For standalone Bash, include the fresh-environment setup line before the wrapper; benchmark venvs start empty.
29- Run the committed script in place from the repo root. Do not copy this skill to a runtime directory, and do not use `rm` or cleanup commands in generated invocations.
30- If a host exposes `run_script`, use `run_script("scripts/run_finetune.py", args=[...])`; otherwise run from the repo root.
31- For the shortest workflow check, use `--smoke`; for MSD Task06 Lung Tumor reproduction, use `--sanity`.
32- Read `references/task06-and-results.md` only when you need Task06 reference details, output-field definitions, or manual bundle setup notes.
33
34## Available Scripts
35
36| Script | Purpose | Arguments |
37|---|---|---|
38| `scripts/run_finetune.py` | Primary entrypoint declared by `skill_manifest.yaml`; stages configs, runs MONAI, and writes `output.json`. | `[FIXTURE_OR_DATASET] --output-dir OUT_DIR [--smoke] [--sanity] [--auto-seg] [--dataset-dir DIR] [--datalist JSON] [--target-anatomy TEXT] [--label-mapping JSON] [--patch-size JSON]` |
39
40## Prerequisites
41
42- Python 3.10+ with CUDA-capable Torch for GPU runs.
43- Runtime packages from `skill_manifest.yaml`, especially `monai==1.4.0`, `numpy<2`, `nibabel`, `scipy`, `typer`, `PyYAML`, `fire`, `pytorch-ignite`, `einops`, and `huggingface_hub`.
44- Optional environment variables: `CUDA_VISIBLE_DEVICES` restricts visible GPUs; `NPROC_PER_NODE` overrides GPU count and values `>=2` select multi-GPU mode for non-sanity runs.
45- Side effects: writes generated bundle configs under `skills/nv-segment-ct-finetune/bundle/configs/`, including `skills/nv-segment-ct-finetune/bundle/configs/auto_override.json`, `skills/nv-segment-ct-finetune/bundle/configs/train_continual_task06_lung.json`, and `skills/nv-segment-ct-finetune/bundle/configs/dfw_no_logging.json`; writes checkpoints/evidence under `--output-dir`, may cache model assets under `~/.cache/huggingface/`, and may contact `https://huggingface.co` or `https://raw.githubusercontent.com`.
46
47Fresh environment setup:
48
49```bash
50python -m pip install "monai==1.4.0" "numpy<2" pytorch-ignite einops nibabel scipy typer PyYAML fire huggingface_hub
51```
52
53Known upstream compatibility constraints:
54
55- DFW Task06 reference: Python `3.10.16`, MONAI `1.4.0`, Torch `2.7.0+cu126`.
56- Use exact `monai==1.4.0` for smoke, sanity, and evidence runs; MONAI 1.5.x can crash the upstream finetune loss on boolean labels.
57- Do not float the dependency as `monai>=1.4,<1.6` in generated commands.
58
59## Usage
60
61Smoke-scale workflow check:
62
63```bash
64python -m pip install "monai==1.4.0" "numpy<2" pytorch-ignite einops nibabel scipy typer PyYAML fire huggingface_hub && \
65python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
66 PATH_TO_DATASET \
67 --smoke \
68 --patch-size '[64,64,64]' \
69 --output-dir runs/nvseg_smoke
70```
71
72Use the staged dataset as `PATH_TO_DATASET`. For the micro fixture, use `skills/nv-segment-ct-finetune/fixtures/spleen_micro`. Smoke mode proves wiring, config generation, checkpoint loading, and runtime compatibility; it is not a quality bar.
73
74MSD Task06 Lung Tumor sanity reproduction:
75
76```bash
77python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
78 /path/to/Task06 \
79 --sanity \
80 --output-dir runs/nvseg_task06_sanity
81```
82
83The sanity preset follows the single-GPU DFW recipe: fold-0 validation, label mapping `[[1, 23]]` for `lung tumor`, automatic class-prompt segmentation, patch `[128,128,128]`, 5 epochs, and original-spacing `configs/evaluate.json` scoring before and after training. Expected reference range is pretrained Dice about `0.6697`, training-best Dice about `0.6905`, and fine-tuned formal Dice about `0.6836`.
84
85User-data finetune:
86
87```bash
88python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
89 --dataset-dir /path/to/dataset \
90 --datalist /path/to/datalist.json \
91 --target-anatomy "lung tumor" \
92 --auto-seg \
93 --epochs 5 \
94 --patch-size '[128,128,128]' \
95 --output-dir runs/nvseg_user_finetune
96```
97
98Use `--label-mapping '[[1, 23]]'` when local label values are custom or the anatomy name is ambiguous.
99
100## Examples
101
102Smoke run on a staged tiny dataset:
103
104```bash
105python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
106 runs/with_vs_without_nv/_inputs/nv_segment_ct_finetune/input_dataset \
107 --smoke \
108 --patch-size '[64,64,64]' \
109 --output-dir runs/nvseg_smoke
110```
111
112Task06 sanity run on a local MSD cache:
113
114```bash
115python skills/nv-segment-ct-finetune/scripts/run_finetune.py \
116 .workbench_data/datasets/Task06_Lung \
117 --sanity \
118 --output-dir runs/nvseg_task06_sanity
119```
120
121## Data Contract
122
123- Preferred layout: `dataset/imagesTr/*.nii.gz` and `dataset/labelsTr/*.nii.gz`.
124- Labels must align one-to-one with images by basename.
125- The target label value must be present in the training labels.
126- Use a datalist when patient-level splitting matters. The bundle default `fold` is `0`, so `fold: 0` entries are validation and all other folds are training.
127- Every trained foreground label must map to an existing VISTA3D global class id from `bundle/label_dict.json`; this skill cannot invent a new class.
128
129## Results
130
131Check `output.json` in the run directory first:
132
133- `formal_pretrained_val_dice` and `formal_finetuned_val_dice`: original-spacing pre/post scores when formal eval is enabled.
134- `training_start_val_dice`, `val_dice_per_epoch`, and `training_best_val_dice`: training-time validation trace.
135- `finetuned_ckpt_matches_pretrained_weights`: detects the epoch-0 checkpoint trap when `val_at_start=true`.
136- `recommended_ckpt`: checkpoint to keep. Do not blindly use the last epoch or `model_finetune.pt`.
137- `runtime.oom`, `runtime.peak_gpu_mb`, and phase logs: distinguish OOM, slow validation, and process failure.
138
139Decision rule: prefer formal original-spacing pre/post scores when present; reject tensor-identical "fine-tuned" checkpoints for sanity recovery; treat `improved: false` as valid evidence rather than a wrapper failure.
140
141## Limitations
142
143- Thin wrapper. Training, validation, transforms, and checkpointing are delegated to the upstream bundle in `bundle/`.
144- Reproduction record only: the successful five-epoch Task06 run used Python
145 `3.12.3`, PyTorch `2.12.0+cu130` with CUDA `13.0`, MONAI `1.4.0`, NumPy
146 `1.26.4`, PyTorch-Ignite `0.5.4`, NiBabel `5.4.2`, SciPy `1.16.0`, einops
147 `0.8.2`, Fire `0.7.1`, Hugging Face Hub `0.36.2`, Transformers `4.57.6`,
148 Typer `0.25.1`, PyYAML `6.0.3`, and MLflow `3.14.0` on one NVIDIA RTX 6000
149 Ada 48 GB GPU. These versions document the evidence environment; they are
150 not additional package constraints or a claim that other versions cannot
151 work.
152- The auto-derived plan is heuristic; caller-provided `--patch-size`, `--cache-rate`, `--epochs`, and `--learning-rate` win.
153- The Task06 sanity recipe intentionally forces single-GPU execution to match the DFW reference. Multi-GPU mode for other datasets requires host `torchrun` support.
154- The paired verifier is CPU-only and audits the evidence pack; it does not re-run GPU segmentation.
155- Not for clinical deployment, clinical interpretation, autonomous diagnosis, or regulatory submission.
156
157## Troubleshooting
158
159| Error | Cause | Fix |
160|---|---|---|
161| Missing dependency or import error | Runtime drift from `skill_manifest.yaml`. | Install the packages above or use the documented environment. |
162| Low Task06 pretrained Dice | Wrong config, wrong checkpoint, data split drift, or dependency drift. | Compare environment fields and staged configs before changing training logic. |
163| `model_finetune.pt` matches pretrained | `val_at_start=true` selected epoch 0 as best. | Use `recommended_ckpt`; treat sanity recovery as failed unless a changed checkpoint improves formal Dice. |
164| Missing formal Dice fields | Formal eval failed or was skipped. | Inspect `eval_pretrained.log`, `eval_finetuned.log`, and `metrics.csv`. |
165| GPU out of memory | Patch/cache settings too large. | Reduce `--patch-size`, lower `--cache-rate`, or reduce workers. |
166| No validation cases | Datalist lacks `fold: 0`. | Provide at least one validation entry. |
167
168## Verification
169
170Run the implemented verifier when quality gates matter:
171
172```bash
173python -m eval_engine.run_trusted skills/nv-segment-ct-finetune \
174 --fixture skills/nv-segment-ct-finetune/fixtures/spleen_micro \
175 --out runs/nvseg_trusted
176```