Skip to content

Commit bfde3a2

Browse files
committed
add cchmc-tcv-fast: TCV cardiac+lung nnUNet MAP (batch + serve modes)
Signed-off-by: chezhia <chezhipower@gmail.com>
1 parent 5ecde8e commit bfde3a2

51 files changed

Lines changed: 13334 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# ~5.3 GB model bundle (5 nnUNet fold checkpoints + bundle config),
2+
# downloaded via scripts/download_models.sh (see README).
3+
models/
4+
tmp/
5+
__pycache__/
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
88235d17c650afae4b95e5939c25b50506fd624cb1e8a233c25d0368b6bc8c80 models/3d_fullres/fold_0/final_model.pt
2+
4159b0514354c487f5f5db2eaedf2ec51f5ab5227e67b30b24ae0fe9a7aefe02 models/3d_fullres/fold_1/final_model.pt
3+
13064914e8d4c3d03c99e4a22292ece0da3abbf6a993544500ee99498c718c22 models/3d_fullres/fold_2/final_model.pt
4+
524fc3653ab25e95e7fe3c8885dd1131b532ab6e3c6e18374812204b9b7c4e5e models/3d_fullres/fold_3/final_model.pt
5+
2fdedf5ba820f9e8df4c0dc5b7c6b436df405b9e0cf5453c1a5e8c81aeb1a019 models/3d_fullres/fold_4/final_model.pt
6+
d3f72d9e13f1413a42388ca9eedd270ea9cf1edc8c500dca0b24ac05bf2542ed models/3d_fullres/nnunet_checkpoint.pth
7+
ac53706b77166f936a08911c232c23916713b449f9bbb9eeec764acdbcfe979f models/jsonpkls/dataset.json
8+
2ca81eb0133c5b905cfb784e4c6485db773cbbe5327647a2babf5228e0687ac5 models/jsonpkls/plans.json
9+
2d46ecb5c41fd4f6df4f5665ebbda1aac4e8c32f7c65b756c3c3dcdc15817ced models/jsonpkls/postprocessing.pkl
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
# cchmc-tcv-fast
2+
3+
Research/evaluation use only — not a cleared clinical device.
4+
5+
Segments **heart, left lung, right lung** from chest CT. A Holoscan-native
6+
MONAI Deploy App Package (MAP) running a 5-fold `3d_fullres` nnUNet ensemble
7+
fine-tuned on the TCV cardiac/lung dataset. Two modes: one-shot **batch** and a
8+
persistent **serve** gRPC daemon.
9+
10+
- Labels: `1 heart` · `2 l_lung` · `3 r_lung`
11+
- Output: one **DICOM-SEG** + one **DICOM-SR** (per-structure volumes) per study
12+
13+
> **For coding agents:** every command below is copy-paste runnable. The only
14+
> environment variable that matters is `VENV`. Set it once (see step 0) and
15+
> run the rest verbatim.
16+
17+
---
18+
19+
## 0. Prerequisites
20+
21+
| Need | Value |
22+
|---|---|
23+
| GPU | 1× NVIDIA with ≥ 20 GiB free VRAM (the baked manifest requests `gpuMemory: 20Gi`); pick **any free GPU** and substitute it for `<N>` below |
24+
| Docker | with `buildx` + NVIDIA Container Toolkit |
25+
| `monai-deploy` CLI | this repo (editable install in the build venv). The PyPI SDK predates the CUDA-13 packager support this bake relies on — do **not** substitute `pip install monai-deploy-app-sdk` |
26+
| Python venv (build/clients) | a dedicated venv with the editable SDK install + client deps (see below) |
27+
28+
```bash
29+
# Point VENV at the build venv (it carries the editable SDK install +
30+
# client deps). Example:
31+
python3 -m venv .venv && source .venv/bin/activate
32+
pip install -e <repo-root>
33+
pip install grpcio==1.83.1 protobuf==6.33.6
34+
VENV=$VIRTUAL_ENV
35+
```
36+
37+
- **Do not** use the system Python. **Do not** `pip install nnunetv2` from PyPI
38+
in the build venv — the vendored editable copy under the repo root (`nnUNet/`)
39+
is the canonical source; the MAP image pins PyPI `nnunetv2==2.8.1`.
40+
41+
---
42+
43+
## 0b. Download model weights
44+
45+
The 5.3 GB weight bundle is **not** in git. Download it from Zenodo
46+
([record 23391210](https://zenodo.org/records/23391210), DOI
47+
[10.5281/zenodo.23391210](https://doi.org/10.5281/zenodo.23391210)):
48+
49+
```bash
50+
cd examples/apps/cchmc-tcv-fast
51+
bash scripts/download_models.sh
52+
# (override with ZENODO_RECORD=<number> if the bundle moves to a new record)
53+
```
54+
55+
The script downloads and extracts the bundle into `models/`, then verifies
56+
checksums against `MANIFEST.sha256`.
57+
58+
Expected layout after download:
59+
60+
```
61+
models/
62+
├── 3d_fullres/
63+
│ ├── fold_0/final_model.pt
64+
│ ├── fold_1/final_model.pt
65+
│ ├── fold_2/final_model.pt
66+
│ ├── fold_3/final_model.pt
67+
│ ├── fold_4/final_model.pt
68+
│ └── nnunet_checkpoint.pth
69+
└── jsonpkls/
70+
├── plans.json
71+
├── postprocessing.pkl
72+
└── dataset.json
73+
```
74+
75+
---
76+
77+
## 1. Build the MAP image (once)
78+
79+
```bash
80+
cd <repo>/examples/apps/cchmc-tcv-fast
81+
WHEEL_DIR=$(mktemp -d)
82+
83+
# 1a. Build the SDK wheel from this repo. (Verified: the public PyPI SDK's
84+
# packager predates CUDA-13 holoscan handling and bakes a broken CPU
85+
# holoscan — use this repo's packager.)
86+
( cd ../../ && "$VENV/bin/python" -m pip wheel . --no-deps -w "$WHEEL_DIR" )
87+
WHEEL=$(ls "$WHEEL_DIR"/monai_deploy_app_sdk-*.whl)
88+
89+
# 1b. Bake. ~6 min. Produces:
90+
# cchmc-tcv-fast-x64-workstation-dgpu-linux-amd64:latest
91+
"$VENV/bin/monai-deploy" package my_app -c my_app/app.yaml \
92+
-m "$PWD/models" \
93+
--monai-deploy-sdk-file "$WHEEL" \
94+
-t cchmc-tcv-fast:latest --platform x86_64 --cuda 13
95+
```
96+
97+
What's baked: 5× fold weights + `jsonpkls/` at `/opt/holoscan/models/`, app
98+
code at `/opt/holoscan/app`, `nnunetv2==2.8.1` (PyPI), `torch 2.13.0+cu130`,
99+
`monai 1.5.2`, `holoscan-cu13`. Manifest sets `sharedMemory: "4Gi"`.
100+
**Verified image:** sha256 `eb0f12609d85…27db35` (16.4 GB).
101+
102+
---
103+
104+
## 2. Run — batch (one study, one shot)
105+
106+
```bash
107+
monai-deploy run cchmc-tcv-fast-x64-workstation-dgpu-linux-amd64:latest \
108+
-i <input-dicom-dir> -o <output-dir> \
109+
--gpus <N> --uid 1000 --gid 10000
110+
```
111+
112+
- `<input-dicom-dir>`: one flat folder of a single study's `.dcm` files.
113+
- `<output-dir>`: must be writable by uid 1000 → `chmod 0777 <output-dir>`.
114+
- Produces `<output-dir>/SEG/*.dcm` + `<output-dir>/SR/*.dcm`.
115+
- No `.npy`/`emit_meta.json` in the MAP. (Re-enable dev emission: add
116+
`-e HOLOSCAN_EMIT_NPY=1`.)
117+
- **Gotcha:** `monai-deploy run` exits `0` even on app failure. The real
118+
signal is the log line `Application exited with N`.
119+
120+
---
121+
122+
## 3. Run — serve (persistent daemon, many studies)
123+
124+
`monai-deploy run` has no port-forward flag, so launch serve with raw docker:
125+
126+
```bash
127+
docker run -d --name tcv-serve \
128+
--gpus '"device=<N>"' --shm-size=4g \
129+
-v <host-payloads>:/payloads \
130+
-p 8765:8765 \
131+
-e MAP_GRPC_PORT=8765 -e MAP_PAYLOADS_ROOT=/payloads \
132+
-e HOLOSCAN_MODEL_PATH=/opt/holoscan/models \
133+
--entrypoint bash cchmc-tcv-fast-x64-workstation-dgpu-linux-amd64:latest \
134+
-c "cd /opt/holoscan/app && python3 __main__.py serve"
135+
```
136+
137+
- Models load **once** (5/0 residency). No per-study reload.
138+
- Wait for readiness: `CheckHealth` returns `INITIALIZING` → `IDLE`.
139+
- **Both** `input_path` and `output_path` must live **under `MAP_PAYLOADS_ROOT`**
140+
(i.e. under `/payloads` in the container).
141+
- RPC `study_uid` must equal the on-disk DICOM **`StudyID`** (the short
142+
numeric tag), not the long `StudyInstanceUID`.
143+
- Tear down: `docker stop tcv-serve && docker rm tcv-serve`.
144+
145+
---
146+
147+
## 4. Drive the daemon — folder-pointing client
148+
149+
```bash
150+
"$VENV/bin/python" scripts/serve_folder_client.py \
151+
--folder <dir-with-studies> --staging <staging-dir> --port 8765
152+
```
153+
154+
- `<dir-with-studies>`: `<folder>/<name>/series1/*.dcm` (≥ 2 levels; deeper
155+
nesting searched, non-`.dcm` skipped).
156+
- Prints `DISCOVERED …`, one `STUDY <id> … OK latency=…ms stages=…` per study,
157+
then a final JSON summary. **Exit 0 only if every study succeeded.**
158+
- Outputs land under `<staging>/out_<uid-slug>/{SEG,SR}`.
159+
- Worked example: 2 studies → `{"ok": 2, "failed": 0}`.
160+
161+
---
162+
163+
## 5. Output contract
164+
165+
| File | SOP class | Content |
166+
|---|---|---|
167+
| **SEG** | `1.2.840.10008.5.1.4.1.1.66.4` | 3 bitplane segments (heart / l_lung / r_lung, SCT codes), `NumberOfFrames = 3 × slices`, original CT geometry |
168+
| **SR** | `1.2.840.10008.5.1.4.1.1.88.11` | exactly 3 lines: `Heart Volume: <v> mL`, `Left lung Volume: <v> mL`, `Right lung Volume: <v> mL` (v = voxels × |det(affine)|/1000, 2 dp) |
169+
| *(optional / diagnostic)* | — | `seg_tcv_dhw.npy` (uint8 DHW) + `emit_meta.json`, gated by `HOLOSCAN_EMIT_NPY` (off by default in the MAP) |
170+
171+
---
172+
173+
## 6. Serve contract (what the daemon guarantees)
174+
175+
- **CheckHealth:** `INITIALIZING → IDLE(models[0]={config 3d_fullres,
176+
trainer nnUNetTrainer_250epochs_NoMirroring, folds 5, patch [256,256,256]},
177+
queue_depth/capacity, in_flight_study_uid) → BUSY → IDLE`.
178+
- **ProcessStudy** (paths-only `study_uid` + `input_path` + `output_path`):
179+
bounded FIFO (capacity 4). Typed rejections: `INVALID_ARGUMENT`,
180+
`ALREADY_EXISTS` (same uid in-flight/queued), `RESOURCE_EXHAUSTED`
181+
(queue full / scratch space), `INTERNAL` + `stage_at_failure`.
182+
Response carries `stages[]` + `latency_ms`.
183+
- **Scratch:** per-study private dir (`$MAP_SCRATCH_ROOT`, default a 0700
184+
tempdir; point it at a `--shm-size` tmpfs mount for RAM-backed scratch);
185+
deterministic purge on success, fault, and rejection (RESIDUE = 0).
186+
- **Kill safety:** SIGKILL mid-write → **0 files at the final output path**
187+
(atomic staging-then-rename at egress); re-submitting the killed uid
188+
republishes idempotently after a restart.
189+
190+
---
191+
192+
## 7. Performance — batch vs serve (measured)
193+
194+
Batch pays a fixed per-run cost (container start + 5-fold model load, ~20–30 s
195+
on the reference GPU) on top of inference; serve pays it once at daemon boot
196+
and each study is pure pipeline. Measured end-to-end per study
197+
(`3d_fullres` 5-fold ensemble):
198+
199+
| Study (slices) | batch wall (GPU host) | serve RPC (GPU host) | serve RPC (baked image)¹ |
200+
|---|---|---|---|
201+
| Study 1 (160) | 52 s | 22.6 s | 41.4 s |
202+
| Study 2 (480) | 117 s | 85.1 s | 109.8 s² |
203+
204+
¹ The baked-image run used a GPU with ~10 GiB of unrelated baseline load;
205+
GPU-host rows share one idle GPU and are the cleaner comparison.
206+
² Post-kill re-publish on the restarted daemon (same daemon lifetime, no
207+
reload — residency 5/0).
208+
209+
Rule of thumb: one study → batch is fine; more than a couple of studies →
210+
serve (first study amortizes the load, the rest run pipeline-only).
211+
212+
---
213+
214+
## 8. Verification (4-study reference corpus)
215+
216+
- **Parity vs pinned pythonic nnUNetv2 oracle** — 12/12 per-class IoU cells
217+
≥ 0.99. Worst cell 0.999840. Repeat run byte-identical (deterministic).
218+
219+
| Study | heart | l_lung | r_lung |
220+
|---|---|---|---|
221+
| Study 1 (160 slices) | 0.999947 | 0.999938 | 0.999946 |
222+
| Study 2 (480 slices) | 0.999967 | 0.999955 | 0.999840 |
223+
| Study 3 (192 slices) | 0.999964 | 0.999968 | 0.999962 |
224+
| Study 4 (417 slices) | 0.999969 | 0.999961 | 0.999976 |
225+
226+
- **In-container E2E on the baked image** — 22/22 PASS: batch
227+
(exit-0, baked-weights, contract, zero-npy, SEG byte-identical to the host
228+
batch baseline) + serve (lifecycle, `ALREADY_EXISTS`,
229+
0 final files, 4 GiB shm zero-residue, 5/0 residency, clean teardown, GPU
230+
released).
231+
232+
---
233+
234+
## 9. Caveats
235+
236+
- **Corpus:** 4 reference studies (Study 1–4); generalization beyond them
237+
is unverified here.
238+
- **Stack:** build venv and image are near-identical (monai 1.5.2, numpy 2.2.6,
239+
pydicom 3.0.2, nnunetv2 2.8.1, torch 2.13.0); the image's torch is `+cu130`
240+
and its `holoscan-cu13` is ≥ 4.3.0 — pixel-identical in-container.
241+
- **SR sha256 is run-volatile** (timestamps/internal UIDs). The bar is
242+
content-level parity, not file hash.
243+
244+
---
245+
246+
## 10. Development notes
247+
248+
- **Build venv:** create a dedicated venv with the editable SDK install
249+
(`pip install -e <repo-root>`); never use the system Python.
250+
- **`nnunetv2`:** the vendored editable copy under the repo root (`nnUNet/`)
251+
is the canonical source; the MAP image pins PyPI `nnunetv2==2.8.1`.
252+
- **Model weights:** 5.3 GB; downloaded via `scripts/download_models.sh`
253+
(Zenodo); stored under `models/` (gitignored); verified against
254+
`MANIFEST.sha256`.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Copyright 2021-2025 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+
# __init__.py ensures this directory is treated as a Python package and
13+
# adds it to sys.path so relative imports work at runtime.
14+
15+
import os
16+
import sys
17+
18+
_current_dir = os.path.abspath(os.path.dirname(__file__))
19+
20+
if sys.path and os.path.abspath(sys.path[0]) != _current_dir:
21+
sys.path.insert(0, _current_dir)
22+
23+
del _current_dir

0 commit comments

Comments
 (0)