Source code for dipy.nn.mindgrab

"""Class and helper functions for the MindGrab brain extraction model.

Note
----

The model architecture and pre-trained weights come from the BrainChop
project (https://github.com/neuroneural/brainchop-cli, MIT license). The CPU
inference code is adapted from brainchopC (MIT license).
"""

from nibabel.orientations import apply_orientation, axcodes2ornt, ornt_transform
import numpy as np
from scipy.special import expit

from dipy.data import get_fnames
from dipy.nn.meshnet import meshnet_forward_cpu
from dipy.nn.meshnet_webgpu import meshnet_forward_webgpu, webgpu_device, wgpu
from dipy.nn.utils import (
    load_state_dict,
    normalize,
    recover_img,
    set_logger_level,
    transform_img,
)
from dipy.segment.utils import remove_holes_and_islands
from dipy.utils.logging import get_logger
from dipy.utils.optpkg import optional_package

logger = get_logger(name="dipy.nn")

torch, have_torch, _ = optional_package("torch", min_version="2.2.0")
if have_torch:
    from torch.nn import GELU, Conv3d, GroupNorm, Module, Sequential
else:

    class Module:
        pass


MODEL_SHAPE = (256, 256, 256)
DILATIONS = (16, 8, 4, 2, 1) * 5
CHANNELS = 15
N_CLASSES = 2
DEVICES = ("auto", "cpu", "webgpu", "cuda")
# MindGrab was trained on volumes conformed to the FreeSurfer LIA orientation.
_RAS_TO_LIA = ornt_transform(axcodes2ornt("RAS"), axcodes2ornt("LIA"))
_LIA_TO_RAS = ornt_transform(axcodes2ornt("LIA"), axcodes2ornt("RAS"))


[docs] def read_mindgrab_weights(fname): """Read the MindGrab weights from a PyTorch state dict, without PyTorch. Parameters ---------- fname : str or Path Path to the weights, saved by ``torch.save``. Returns ------- kernels : list of np.ndarray (15, in_channels, 3, 3, 3) Weights of the dilated convolutions. classifier : np.ndarray (2, 15) Weights of the final 1x1x1 convolution. bias : np.ndarray (2,) Bias of the final 1x1x1 convolution. """ state = load_state_dict(fname) n_layers = len(DILATIONS) try: kernels = [state[f"model.{i}.0.weight"] for i in range(n_layers)] classifier = state[f"model.{n_layers}.weight"] bias = state[f"model.{n_layers}.bias"] except KeyError as e: raise ValueError(f"{fname} does not hold MindGrab weights") from e expected = [(CHANNELS, 1, 3, 3, 3)] + [(CHANNELS, CHANNELS, 3, 3, 3)] * ( n_layers - 1 ) if ( len(state) != n_layers + 2 or [kernel.shape for kernel in kernels] != expected or classifier.shape != (N_CLASSES, CHANNELS, 1, 1, 1) or bias.shape != (N_CLASSES,) ): raise ValueError(f"{fname} does not hold MindGrab weights") return kernels, classifier[:, :, 0, 0, 0], bias
[docs] class MeshNet(Module): """MeshNet architecture used by MindGrab. A fully convolutional network made of a stack of dilated 3D convolutions, each followed by a parameter-free group normalization and a GELU activation :footcite:p:`Fedorov2017`. MindGrab repeats the dilation schedule 16, 8, 4, 2, 1 five times :footcite:p:`Fani2026`. Parameters ---------- in_channels : int, optional Number of input channels. channels : int, optional Number of feature channels of each hidden layer. n_classes : int, optional Number of output classes. dilations : sequence of int, optional Dilation of each hidden layer. References ---------- .. footbibliography:: """ def __init__( self, *, in_channels=1, channels=CHANNELS, n_classes=N_CLASSES, dilations=DILATIONS, ): super().__init__() layers = [] for i, dilation in enumerate(dilations): layers.append( Sequential( Conv3d( in_channels if i == 0 else channels, channels, kernel_size=3, padding=dilation, dilation=dilation, bias=False, ), GroupNorm(channels, channels, affine=False), GELU(approximate="tanh"), ) ) layers.append(Conv3d(channels, n_classes, kernel_size=1)) self.model = Sequential(*layers)
[docs] def forward(self, x): """Forward pass of the MeshNet model. Parameters ---------- x : torch.Tensor (batch, in_channels, X, Y, Z) Input tensor. Returns ------- torch.Tensor (batch, n_classes, X, Y, Z) Class logits. """ return self.model(x)
[docs] class MindGrab: """This class is intended for the MindGrab model. The MindGrab model :footcite:p:`Fani2026` is a lightweight (146k parameters) fully convolutional network for skull stripping. It was trained only on synthetic data, which makes it modality agnostic: it handles T1w, T2w, FLAIR, DWI, CT or PET volumes alike. Inference runs on the CPU with a compiled kernel that needs no deep learning framework, or on any GPU through WebGPU with the ``wgpu`` package, or on CUDA with PyTorch. References ---------- .. footbibliography:: """ def __init__( self, *, verbose=False, device="auto", half_precision=False, num_threads=None ): """Model initialization Parameters ---------- verbose : bool, optional Whether to show information about the processing. device : {'auto', 'cpu', 'webgpu', 'cuda'}, optional Where to run the network. - 'auto': a GPU through WebGPU if the ``wgpu`` package finds one, otherwise CUDA if PyTorch finds an NVIDIA GPU, otherwise the CPU. WebGPU comes first as it is faster and uses less GPU memory than PyTorch. - 'cpu': compiled CPU kernel, which needs no extra package. - 'webgpu': any GPU through Vulkan, Metal or Direct3D 12, which needs the ``wgpu`` package. Software adapters emulating a GPU on the CPU are ignored. - 'cuda': PyTorch on CUDA, or on the Apple MPS GPU. If the requested GPU is not available, WebGPU is tried before falling back to the CPU. half_precision : bool, optional Whether to store activations in float16 on WebGPU, halving the GPU memory needed at the cost of a few differing voxels. Float16 is also used, when supported, if float32 activations do not fit in the GPU memory. num_threads : int, optional Number of threads to use on the CPU. If None, the value of the ``OMP_NUM_THREADS`` environment variable is used if set, otherwise all available cores. If < 0, the maximal number of threads minus $|num_threads + 1|$ is used (enter -1 to use as many threads as possible). 0 raises an error. """ if device not in DEVICES: raise ValueError(f"device should be one of {DEVICES}, got {device!r}") log_level = "INFO" if verbose else "CRITICAL" set_logger_level(log_level, logger) self.half_precision = half_precision self.num_threads = num_threads self.torch_device = None self.webgpu_device = None if device in ("auto", "webgpu"): self.webgpu_device = webgpu_device() if self.webgpu_device is None and device in ("auto", "cuda") and have_torch: if torch.cuda.is_available(): self.torch_device = torch.device("cuda") elif device == "cuda" and torch.backends.mps.is_available(): self.torch_device = torch.device("mps") if self.torch_device is None and device == "cuda": self.webgpu_device = webgpu_device() if self.webgpu_device is not None: logger.warning("No GPU found by PyTorch, switching to WebGPU") if self.torch_device is not None: self.device = self.torch_device.type elif self.webgpu_device is not None: self.device = "webgpu" else: self.device = "cpu" if device in ("cuda", "webgpu"): logger.warning( "No GPU found, switching to CPU. Using WebGPU requires the " "wgpu package and a GPU driver." ) logger.info(f"MindGrab runs on {self.device}") self.model = None self.fetch_default_weights()
[docs] def fetch_default_weights(self): """Load the model pre-training weights to use for the fitting. While the user can load different weights, the function is mainly intended for the class function 'predict'. """ fetch_model_weights_path = get_fnames(name="mindgrab_weights") self.load_model_weights(fetch_model_weights_path)
[docs] def load_model_weights(self, weights_path): """Load the custom pre-training weights to use for the fitting. Parameters ---------- weights_path : str or Path Path to the file containing the weights (pth, saved by Pytorch) """ kernels, classifier, bias = read_mindgrab_weights(weights_path) self.kernels, self.classifier, self.bias = kernels, classifier, bias if self.torch_device is None: return state = {f"model.{i}.0.weight": kernel for i, kernel in enumerate(kernels)} state[f"model.{len(kernels)}.weight"] = classifier[..., None, None, None] state[f"model.{len(kernels)}.bias"] = bias self.model = MeshNet() self.model.load_state_dict({k: torch.from_numpy(v) for k, v in state.items()}) self.model.to(self.torch_device).eval()
def _predict_volume(self, volume): """Compute the brain probability of a conformed volume. Parameters ---------- volume : np.ndarray (256, 256, 256) Normalized volume in the LIA orientation. Returns ------- np.ndarray (256, 256, 256) Brain probability. """ logits = None if self.model is not None: x = torch.from_numpy(np.ascontiguousarray(volume)[None, None]) with torch.no_grad(): logits = self.model(x.to(self.torch_device))[0].cpu().numpy() elif self.webgpu_device is not None: logits = self._predict_webgpu(volume) if logits is None: logits = meshnet_forward_cpu( volume, self.kernels, DILATIONS, self.classifier, self.bias, num_threads=self.num_threads, ) return expit(logits[1] - logits[0]) def _predict_webgpu(self, volume): """Compute the class logits of a conformed volume on WebGPU. Falls back to float16 storage when float32 activations do not fit in the GPU, and gives up WebGPU for the CPU on any other GPU error. Parameters ---------- volume : np.ndarray (256, 256, 256) Normalized volume in the LIA orientation. Returns ------- np.ndarray (2, 256, 256, 256) or None Class logits, or None if WebGPU failed. """ precisions = [self.half_precision] if not self.half_precision and "shader-f16" in self.webgpu_device.features: precisions.append(True) for half in precisions: try: return meshnet_forward_webgpu( volume, self.kernels, DILATIONS, self.classifier, self.bias, device=self.webgpu_device, half_precision=half, ) except MemoryError as e: error = e except (RuntimeError, ValueError, wgpu.GPUError) as e: error = e break logger.warning(f"WebGPU inference failed, switching to CPU: {error}") self.webgpu_device = None self.device = "cpu" return None
[docs] def predict(self, image, affine, *, return_prob=False, finalize_mask=True): """Extract the brain from one or several volumes. Each volume is resampled to 1 mm isotropic, reoriented to LIA and padded or cropped to 256x256x256 before being fed to the model. The output is brought back to the original image space. Parameters ---------- image : np.ndarray or list of np.ndarray For a single image, input should be a 3D array. If multiple images, it should be a list or tuple of 3D arrays. affine : np.ndarray (4, 4) or (batch, 4, 4) or list of np.ndarrays with len of batch Affine matrix of the image. Should have a batch dimension if ``image`` has one. return_prob : bool, optional Whether to return the brain probability map instead of a binary mask. finalize_mask : bool, optional Whether to remove potential holes or islands. Useful for solving minor errors. Ignored if ``return_prob`` is True. Returns ------- np.ndarray (...) or (batch, ...) Predicted brain mask, or brain probability map if ``return_prob`` is True, in the original image space. """ affine = np.asarray(affine) if isinstance(image, (list, tuple)): single = False elif image.ndim == 3: single = True image = [image] affine = affine[None] else: raise ValueError( "Input data should be a np.ndarray of dimension 3 or a list/tuple of it" ) outputs = [] for img, aff in zip(image, affine): t_img, params = transform_img( np.asarray(img, dtype=np.float32), aff, target_voxsize=(1.0, 1.0, 1.0), final_size=MODEL_SHAPE, order=1, ) t_img = apply_orientation(t_img, _RAS_TO_LIA) qlow, qhigh = np.quantile(t_img, (0.02, 0.98)) t_img = normalize(t_img, min_v=qlow, max_v=qhigh, new_min=0, new_max=1) prob = self._predict_volume(t_img.astype(np.float32)) prob = apply_orientation(prob, _LIA_TO_RAS) output = np.clip(recover_img(prob, params, order=1), 0, 1) if not return_prob: output = (output >= 0.5).astype(np.uint8) if finalize_mask: output = remove_holes_and_islands(output).astype(np.uint8) outputs.append(output) return outputs[0] if single else np.stack(outputs)