nnInteractive Documentation
repository·master·Indexed 19 days ago
https://github.com/mic-dkfz/nninteractiveA framework for 3D promptable segmentation providing a Python backend for interactive volumetric segmentation using points, scribbles, and lassoes. It includes nnInteractive SuperVoxel for generating 3D pseudo-labels by combining SAM and SAM2, and offers a lightweight nninteractive-client for remote server interaction without requiring torch or nnU-Net dependencies.
What's inside nnInteractive
- nnInteractive is a state-of-the-art framework for 3D promptable segmentation. It provides a comprehensive 3D interactive open-set segmentation method that supports diverse prompts, including points, scribbles, boxes, and a novel lasso prompt. It is designed to leverage intuitive 2D interactions to generate full 3D segmentations and is trained on over 120 diverse volumetric 3D datasets (CT, MRI, PET, 3D Microscopy, etc.).
Overview of SAM 2 training code structure
masterThe SAM 2 training codebase is organized as follows:
dataset/: Contains image/video dataset classes, dataloaders, and transforms.model/: ContainsSAM2Train(inherits fromSAM2Base), which enables training/fine-tuning and handles training-time parameters like iterative point sampling.utils/: Contains loggers and distributed training utilities.scripts/: Includes scripts for data preparation (e.g., extracting SA-V frames).loss_fns.py: Defines theMultiStepMultiMasksAndIousloss class.optimizer.py: Contains optimizer utilities supporting arbitrary schedulers.trainer.py: Contains theTrainerclass which implements the main train/eval loop using Hydra-configurable modules.train.py: The main entry point script to launch training jobs (supports single and multi-node).
Manage remote sessions and concurrency
masterThe server supports multiple concurrent client sessions up to the limit defined by
--max-sessions.Session Lifecycle
- Claiming: A session is automatically claimed when
nnInteractiveRemoteInferenceSessionis instantiated. The client manages a private lease token automatically. - Releasing: Use a context manager or call
session.close()to release the session slot back to the server immediately. - Concurrency: While multiple sessions can exist, the GPU is a shared resource. Prediction calls are serialized via a global GPU lock. Non-prediction calls (like
set_image) can run concurrently across sessions.
Handling Capacity
If the server is at its
--max-sessionslimit, constructing a session will raiseServerAtCapacityError. You should implement a retry mechanism.import time from nnInteractive.inference.remote import ( nnInteractiveRemoteInferenceSession, ServerAtCapacityError, ) for attempt in range(6): try: session = nnInteractiveRemoteInferenceSession(server_url, api_key=KEY) break except ServerAtCapacityError: time.sleep(10) else: raise SystemExit("server has been at capacity for too long")- Claiming: A session is automatically claimed when
Use nnInteractive SuperVoxels for 3D pseudo-label generation
masterThe
nnInteractive/supervoxel/module provides a dedicated workflow for generating 3D supervoxels using foundation models (SAM and SAM2) instead of traditional methods like SLIC.Key capabilities:
- Automatic Generation: Uses axial sampling combined with SAM segmentation and SAM2 mask propagation to create high-quality 3D supervoxels.
- Pseudo-Ground-Truth: The generated supervoxels can be used as pseudo-labels to train promptable 3D segmentation models like
nnInteractive. - nnU-Net Integration: Supports exporting
.pklforeground prompts that are compatible withnnU-Netfor downstream tasks.
For detailed setup and usage, refer to the
nnInteractive/supervoxel/README.mdfile.How nnInteractive Server / Client architecture works
masterThe
nnInteractiveRemoteInferenceSessionallows you to run heavy 3D segmentation models on a remote GPU server while driving the interaction from a lightweight GUI client over HTTP.Key architectural concepts:
- Shared Model: The server loads the model weights into GPU memory only once at startup. All client sessions share these weights.
- Per-Client Sessions: Each client is assigned a unique session via a lease token. Each session maintains its own independent state, including the current image,
target_buffer, and interaction history. - Concurrency: While multiple clients can preprocess images simultaneously, predictions are GPU-serialized (only one prediction runs at a time) to manage GPU resources.
- Session Management: Sessions are managed via
--max-sessions. If a client becomes inactive or loses connection, the server reaps the session based on--idle-timeout-secondsor--liveness-timeout-secondsto free up slots.
[GUI client A] ─┐ │ HTTP [GUI client B] ─┼────► nninteractive-server ──► one shared model on GPU │ (per-client sessions: (loaded once at startup) [GUI client C] ─┘ image, target_buffer, interactions per session)Handle session expiry and timeouts
masterThe server reaps sessions based on two independent timeout mechanisms. If a session is reaped, the next request will raise
SessionExpiredError. Because all state (image, buffer, interactions) is stored on the server, a reaped session cannot be restored; the user must start the workflow over.Timeout Types
- Liveness Timeout (
--liveness-timeout-seconds, default 60s): Triggered if the client process stops responding (e.g., crash). The client library automatically sends heartbeats in a background thread to prevent this. - Idle/Inactivity Timeout (
--idle-timeout-seconds, default 600s): Triggered if the user is inactive. Heartbeats do not reset this timer. Only real interactions (likeset_imageoradd_*_interaction) reset the idle timer.
Monitoring
session.lease_status(): Returns the remaining seconds until the idle timeout. This is a read-only probe and does not affect the timer.
from nnInteractive.inference.remote import SessionExpiredError try: session.add_point_interaction([60, 70, 30], include_interaction=True) except SessionExpiredError: # The server-side session is gone. There is nothing to restore. # The user has to start the segmentation workflow over. session = nnInteractiveRemoteInferenceSession(server_url, api_key=KEY) session.set_image(image) session.set_target_buffer(buf)- Liveness Timeout (
Understand the nnInteractive package split
masternnInteractive is distributed as two pip packages that share the
nnInteractiveimport namespace:nninteractive-client: A torch-free remote client (nnInteractive.inference.remote). It is used to communicate with a remote server.nnInteractive: The full local + server stack. It depends onnninteractive-clientand includes the local inference engine.
Both packages expose the same
nnInteractiveimport namespace, so client code remains identical regardless of which package is installed.Understand model licensing and the `session.license` property
masterThe
nnInteractiverepository is licensed under Apache-2.0, but the model checkpoints have different licensing terms.- Official Checkpoint License:
Creative Commons Attribution Non Commercial Share Alike 4.0(CC BY-NC-SA 4.0). - License Detection: When loading a model, the tool reads the first line of the
LICENSEfile within the checkpoint folder. This value is exposed via thesession.licenseproperty in your application. - Fallback Behavior:
- If a checkpoint folder contains a
LICENSEfile, the first line is used. - If no
LICENSEfile is present and it is the official v1 checkpoint, it defaults toCC BY-NC-SA 4.0. - For any other checkpoint missing a license file, it reports
!!MISSING!!.
- If a checkpoint folder contains a
- Official Checkpoint License:
Retrieve segmentation results
masterThe segmentation result is written directly into the tensor you provided to
set_target_buffer. You do not need to fetch it from the session.- To get a NumPy array:
result_np = target_tensor.cpu().numpy() - To preserve the result before starting a new object:
saved = target_tensor.clone()(for torch) ortarget_tensor.copy()(for numpy). - To start a new segmentation:
session.reset_interactions()clears the buffer and interactions.
# The result is already in your buffer result_np = target_tensor.cpu().numpy() # Reset for next object session.reset_interactions()- To get a NumPy array:
Access session.interactions as a blosc2 NDArray
masterIn v2,
session.interactionsis no longer atorch.Tensor. It is now a blosc2NDArray(numpy-like,float16).Warning for developers: Any code that performs torch-specific operations on this attribute (such as
.to(device),.fill_(...), or other torch-style tensor methods) will break. You must use standard numpy-style indexing and assignment.Use the lightweight `nninteractive-client` for remote inference
masterThe
nninteractive-clientis a lightweight, torch-free package designed for GUIs or thin clients. It allows you to drive a remotennInteractiveserver without requiringtorchornnU-Neton the client machine.Key Features:
- Namespace Sharing: It shares the
nnInteractiveimport namespace with the full package. - Efficient Updates: Predictions and
add_*_interaction()calls return the bounding box of the changed region (clipped to the target buffer). This allows clients to copy only the necessary sub-volumes rather than the entire buffer.
- Namespace Sharing: It shares the
Understand nnInteractive Server Limitations
masterWhen designing your deployment, be aware of the following constraints:
- GPU Serialization: Within a single server process, predictions are serialized. Multiple clients can preprocess concurrently, but only one prediction runs at a time on the GPU. For higher throughput, run multiple server processes on different GPUs.
- Authentication Model: Authentication is a single shared bearer token. There is no per-user identity, quota, or login flow.
- Fixed Checkpoint: The model checkpoint is loaded at startup and remains fixed for the lifetime of the server process.
- No TLS by Default: The server does not terminate TLS; use a reverse proxy for secure deployments.
- No Client-side Retries: The client does not implement automatic reconnection. If a network blip or
SessionExpiredErroroccurs, the error is raised to the caller; the application (e.g., a GUI) must handle re-initialization.