Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Add RankSEG integration tutorial#2068

Open
statmlben wants to merge 1 commit into
Project-MONAI:mainProject-MONAI/tutorials:mainfrom
rankseg:add-rankseg-integration-tutorialrankseg/tutorials:add-rankseg-integration-tutorialCopy head branch name to clipboard
Open

Add RankSEG integration tutorial#2068
statmlben wants to merge 1 commit into
Project-MONAI:mainProject-MONAI/tutorials:mainfrom
rankseg:add-rankseg-integration-tutorialrankseg/tutorials:add-rankseg-integration-tutorialCopy head branch name to clipboard

Conversation

@statmlben

@statmlben statmlben commented Jul 27, 2026

Copy link
Copy Markdown

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:

  • uses the pretrained pancreas_ct_dints_segmentation MONAI Bundle and a real MSD Task07 Pancreas case;
  • compares conventional argmax decoding with RankSEG using per-class Dice scores and a visualization;
  • demonstrates the array-based RankSEG transform;
  • demonstrates the dictionary-based RankSEGd transform in a MONAI Compose post-processing pipeline;
  • documents the public dataset source, CC BY-SA 4.0 license, and research-use context.

This PR also adds the tutorial to the repository README and registers it in doesnt_contain_max_epochs because it is an inference-only notebook.

Checks

  • Avoid including large-size files in the PR.
  • Clean up long text outputs from code cells in the notebook.
  • Check the contents and remove sensitive information such as user names and private keys.
  • Verify hyperlinks, markdown content, and relative repository paths.
  • Notebook runs automatically with:
./runner.sh -t modules/rankseg_integration.ipynb

Results

Argmax macro Dice: 0.7747
RankSEG macro Dice: 0.8502
Paired Dice change: +0.0755
Pancreas Dice: 0.8764 -> 0.8898
Tumor Dice: 0.6730 -> 0.8106
image

Summary by CodeRabbit

  • New Features

    • Added a tutorial demonstrating optional RankSEG/RankSEGd post-processing with MONAI segmentation workflows.
    • Compares RankSEG decoding with standard argmax predictions using a pretrained pancreas segmentation model.
    • Includes Dice score evaluation, visual comparisons, and examples for both tensor and dictionary-based workflows.
  • Documentation

    • Added the RankSEG integration notebook to the documented list of available modules and examples.

Signed-off-by: statmlben <bdai.hk@protonmail.com>
@review-notebook-app

Copy link
Copy Markdown

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Walkthrough

Adds 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 max_epochs check.

Changes

RankSEG integration tutorial

Layer / File(s) Summary
RankSEG transform wrappers
modules/rankseg_integration.ipynb
Introduces RankSEG for multiclass probability-map decoding and documents configuration and expected inputs.
Pancreas model inference
modules/rankseg_integration.ipynb
Downloads and preprocesses a pancreas case, loads the MONAI DiNTS bundle, and runs sliding-window inference.
Decoder comparison and evaluation
modules/rankseg_integration.ipynb
Compares argmax and RankSEG predictions, calculates foreground Dice scores, and visualizes tumor-region differences.
Dictionary integration and execution support
modules/rankseg_integration.ipynb, README.md, runner.sh
Demonstrates RankSEGd, cleans temporary data, documents the notebook, and adds its runner exemption.

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
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a RankSEG integration tutorial.
Description check ✅ Passed The description follows the template well, with a summary, checklist, results, and relevant links/context.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81dcf0f and 13eed5c.

📒 Files selected for processing (3)
  • README.md
  • modules/rankseg_integration.ipynb
  • runner.sh

},
"outputs": [],
"source": [
"!python -c \"import monai\" || pip install -q \"monai-weekly[nibabel, tqdm]\"\n",

@coderabbitai coderabbitai Bot Jul 27, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
"!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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 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)
PY

Length 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]" rankseg

It 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.

Comment thread modules/rankseg_integration.ipynb

@ericspod ericspod left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +635 to +649
"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",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Morty Proxy This is a proxified and sanitized view of the page, visit original site.