nnInteractive Documentation

repository·master·Indexed 19 days ago

https://github.com/mic-dkfz/nninteractive

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

Tokens
27.8K
Snippets
79
Records
104
Agent score
64%

What's inside nnInteractive

  1. What is nnInteractive?

    master
    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.).
  2. Overview of SAM 2 training code structure

    master

    The SAM 2 training codebase is organized as follows:

    • dataset/: Contains image/video dataset classes, dataloaders, and transforms.
    • model/: Contains SAM2Train (inherits from SAM2Base), 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 the MultiStepMultiMasksAndIous loss class.
    • optimizer.py: Contains optimizer utilities supporting arbitrary schedulers.
    • trainer.py: Contains the Trainer class 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).
  3. Manage remote sessions and concurrency

    master

    The server supports multiple concurrent client sessions up to the limit defined by --max-sessions.

    Session Lifecycle

    • Claiming: A session is automatically claimed when nnInteractiveRemoteInferenceSession is 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-sessions limit, constructing a session will raise ServerAtCapacityError. 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")
  4. Use nnInteractive SuperVoxels for 3D pseudo-label generation

    master

    The 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 .pkl foreground prompts that are compatible with nnU-Net for downstream tasks.

    For detailed setup and usage, refer to the nnInteractive/supervoxel/README.md file.

  5. How nnInteractive Server / Client architecture works

    master

    The nnInteractiveRemoteInferenceSession allows 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-seconds or --liveness-timeout-seconds to 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)
  6. Handle session expiry and timeouts

    master

    The 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

    1. 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.
    2. Idle/Inactivity Timeout (--idle-timeout-seconds, default 600s): Triggered if the user is inactive. Heartbeats do not reset this timer. Only real interactions (like set_image or add_*_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)
  7. Understand the nnInteractive package split

    master

    nnInteractive is distributed as two pip packages that share the nnInteractive import namespace:

    1. nninteractive-client: A torch-free remote client (nnInteractive.inference.remote). It is used to communicate with a remote server.
    2. nnInteractive: The full local + server stack. It depends on nninteractive-client and includes the local inference engine.

    Both packages expose the same nnInteractive import namespace, so client code remains identical regardless of which package is installed.

  8. Understand model licensing and the `session.license` property

    master

    The nnInteractive repository 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 LICENSE file within the checkpoint folder. This value is exposed via the session.license property in your application.
    • Fallback Behavior:
      • If a checkpoint folder contains a LICENSE file, the first line is used.
      • If no LICENSE file is present and it is the official v1 checkpoint, it defaults to CC BY-NC-SA 4.0.
      • For any other checkpoint missing a license file, it reports !!MISSING!!.
  9. Retrieve segmentation results

    master

    The 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) or target_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()
  10. Access session.interactions as a blosc2 NDArray

    master

    In v2, session.interactions is no longer a torch.Tensor. It is now a blosc2 NDArray (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.

  11. Use the lightweight `nninteractive-client` for remote inference

    master

    The nninteractive-client is a lightweight, torch-free package designed for GUIs or thin clients. It allows you to drive a remote nnInteractive server without requiring torch or nnU-Net on the client machine.

    Key Features:

    • Namespace Sharing: It shares the nnInteractive import 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.
  12. Understand nnInteractive Server Limitations

    master

    When 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 SessionExpiredError occurs, the error is raised to the caller; the application (e.g., a GUI) must handle re-initialization.