Add RankSEG integration tutorial#2068
Add RankSEG integration tutorial#2068statmlben wants to merge 1 commit intoProject-MONAI:mainProject-MONAI/tutorials:mainfrom rankseg:add-rankseg-integration-tutorialrankseg/tutorials:add-rankseg-integration-tutorialCopy head branch name to clipboard
Conversation
Signed-off-by: statmlben <bdai.hk@protonmail.com>
|
Check out this pull request on See visual diffs & provide feedback on Jupyter Notebooks. Powered by ReviewNB |
WalkthroughAdds a MONAI tutorial integrating RankSEG and RankSEGd with a pretrained pancreas DiNTS model, comparing RankSEG against argmax using Dice scores and visualizations. It also documents the notebook and exempts it from the runner’s ChangesRankSEG integration tutorial
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Notebook
participant DiNTS
participant RankSEG
participant DiceMetric
Notebook->>DiNTS: run sliding-window inference
DiNTS-->>Notebook: return segmentation logits
Notebook->>RankSEG: decode softmax probabilities
RankSEG-->>Notebook: return class-index prediction
Notebook->>DiceMetric: compare prediction with foreground labels
DiceMetric-->>Notebook: return Dice scores
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@modules/rankseg_integration.ipynb`:
- Line 47: Update the dependency-check command in the notebook setup cell to
validate both MONAI and nibabel imports before skipping installation. Ensure any
installation runs through the active kernel interpreter, and retain the existing
MONAI extras including nibabel and tqdm so the later LoadImaged call can read
.nii.gz files.
- Around line 630-653: Update both torch.load calls for the architecture and
checkpoint artifacts in the model-loading flow to use weights_only=True instead
of explicitly enabling full pickle deserialization. Preserve the existing paths
and map_location settings, and only retain weights_only=False if the loaded
files require trusted non-tensor objects.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e68feaab-cd4b-4ade-99e2-419988bdcf7c
📒 Files selected for processing (3)
README.mdmodules/rankseg_integration.ipynbrunner.sh
| }, | ||
| "outputs": [], | ||
| "source": [ | ||
| "!python -c \"import monai\" || pip install -q \"monai-weekly[nibabel, tqdm]\"\n", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Check the NIfTI reader dependency, not just monai.
An existing MONAI installation without nibabel skips this install, but the later LoadImaged call reads downloaded .nii.gz files. Check import monai, nibabel (and install through the kernel interpreter) before continuing.
Proposed fix
-!python -c "import monai" || pip install -q "monai-weekly[nibabel, tqdm]"
+!python -c "import monai, nibabel" || python -m pip install -q "monai-weekly[nibabel, tqdm]"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "!python -c \"import monai\" || pip install -q \"monai-weekly[nibabel, tqdm]\"\n", | |
| "!python -c \"import monai, nibabel\" || python -m pip install -q \"monai-weekly[nibabel, tqdm]\"\n", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@modules/rankseg_integration.ipynb` at line 47, Update the dependency-check
command in the notebook setup cell to validate both MONAI and nibabel imports
before skipping installation. Ensure any installation runs through the active
kernel interpreter, and retain the existing MONAI extras including nibabel and
tqdm so the later LoadImaged call can read .nii.gz files.
There was a problem hiding this comment.
An alternative is to use %pip install -q --upgrade-strategy only-if-needed "monai-weekly[nibabel, tqdm,matplotlib,huggingface_hub]" rankseg in place of the multiple pip commands. This won't install over top of existing MONAI installs but will install missing dependencies.
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python - <<'PY'
import json
from pathlib import Path
path = Path("modules/rankseg_integration.ipynb")
notebook = json.loads(path.read_text())
for index, cell in enumerate(notebook["cells"]):
if cell.get("cell_type") != "code":
continue
source = "".join(cell.get("source", []))
if any(term in source for term in (
"pip install", "%pip", "import ", "from ", "rankseg", "huggingface_hub"
)):
print(f"\n--- code cell {index} ---")
print(source)
PYLength of output: 7394
The PR description image shows six panels: a grayscale “CT image”; a white-mask “Tumor reference”; a purple/red/yellow “Tumor probability” heatmap; “Argmax tumor Dice 0.673”; “RankSEG tumor Dice 0.811”; and a “Changed tumor voxels” difference outline. The RankSEG result visibly aligns more closely with the reference mask.
@ericspod, agreed. This is a cleaner solution for the current setup cell: it replaces all four conditional installs, runs through the active notebook kernel, and declares every dependency the notebook imports—including nibabel for LoadImaged.
%pip install -q --upgrade-strategy only-if-needed "monai-weekly[nibabel, tqdm,matplotlib,huggingface_hub]" ranksegIt is a valid alternative to the import-guard change I suggested, so no separate import monai, nibabel check is needed if this consolidated command replaces the existing install commands.
✏️ Learnings added
Learnt from: ericspod
Repo: Project-MONAI/tutorials PR: 2068
File: modules/rankseg_integration.ipynb:47-47
Timestamp: 2026-07-27T12:45:08.827Z
Learning: In `modules/rankseg_integration.ipynb`, prefer one kernel-aware `%pip install -q --upgrade-strategy only-if-needed "monai-weekly[nibabel, tqdm,matplotlib,huggingface_hub]" rankseg` setup command over separate guarded `pip` commands. It covers the notebook’s MONAI NIfTI reader, tqdm, Matplotlib, Hugging Face Hub, and RankSEG runtime dependencies without unnecessarily replacing a compatible existing MONAI installation.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
ericspod
left a comment
There was a problem hiding this comment.
Hi @statmlben thanks for this tutorial as we had discussed. I think it's fine overall for the existing content, but we need a discussion on what Rankseg is and how the algorithm works. At the top you should describe what it is, how it differs from other components, what it's used for, what the implications of using it are, etc. This by no means needs the same details as in your paper but should be motivating enough so readers know what the notebook is demonstrating and whether they'd want to use it themselves or not. I think the Coderabbit comments should be looked at but I had responses here as well.
| "topology = TopologyInstance(\n", | ||
| " channel_mul=1,\n", | ||
| " num_blocks=12,\n", | ||
| " num_depths=4,\n", | ||
| " use_downsample=True,\n", | ||
| " arch_code=[architecture[\"arch_code_a\"], architecture[\"arch_code_c\"]],\n", | ||
| " device=str(device),\n", | ||
| ")\n", | ||
| "model = DiNTS(\n", | ||
| " dints_space=topology,\n", | ||
| " in_channels=1,\n", | ||
| " num_classes=3,\n", | ||
| " use_downsample=True,\n", | ||
| " node_a=torch.as_tensor(architecture[\"node_a\"], device=device),\n", | ||
| ").to(device)\n", |
There was a problem hiding this comment.
It's possible to use the bundle parser to load the model for you:
p = monai.bundle.ConfigParser()
p.read_config(bundle_dir + "/configs/inference.yaml")
p["arch_ckpt"] = architecture
model = p.get_parsed_content("network_def")| }, | ||
| "outputs": [], | ||
| "source": [ | ||
| "!python -c \"import monai\" || pip install -q \"monai-weekly[nibabel, tqdm]\"\n", |
There was a problem hiding this comment.
An alternative is to use %pip install -q --upgrade-strategy only-if-needed "monai-weekly[nibabel, tqdm,matplotlib,huggingface_hub]" rankseg in place of the multiple pip commands. This won't install over top of existing MONAI installs but will install missing dependencies.
Related to MONAI-#8908
Description
This PR adds a runnable tutorial demonstrating how to use RankSEG as an optional third-party post-processing transform in a MONAI workflow.
The tutorial:
pancreas_ct_dints_segmentationMONAI Bundle and a real MSD Task07 Pancreas case;RankSEGtransform;RankSEGdtransform in a MONAIComposepost-processing pipeline;This PR also adds the tutorial to the repository README and registers it in
doesnt_contain_max_epochsbecause it is an inference-only notebook.Checks
Results
Summary by CodeRabbit
New Features
Documentation