← MID project page
Code tutorial · pytorch-mid

Score your own model in seven steps

The package pytorch-mid computes MID from joint image–mask vectors. It needs NumPy, SciPy and scikit-learn. Steps 2 and 3 build the vectors with MedSigLIP. The other steps use the package only.

  1. 1

    Install

    Install the package from GitHub. The encoder in step 2 needs PyTorch, Transformers and NiBabel. MedSigLIP is a gated model: accept its terms on its Hugging Face page, then log in.

    terminal
    pip install git+https://github.com/erc-caravel/pytorch-mid
    pip install torch transformers nibabel   # for the encoder in step 2
    hf auth login                            # MedSigLIP is a gated model
  2. 2

    Encode with the paper's settings

    The package takes feature vectors and has no encoder. This file renders 16 axial slices per volume, encodes each slice with MedSigLIP and averages the slice embeddings. Each image and foreground class gives one vector of 2304 values, image first. Its renderers give the same pixels as the paper's code.

    mid_encode.py
    import numpy as np
    import nibabel as nib
    import torch
    from transformers import SiglipImageProcessor, SiglipVisionModel
    
    MODEL = "google/medsiglip-448"
    CT_WINDOWS = [(-1024, 1024), (-135, 215), (0, 80)]
    
    
    def load_medsiglip(device="cuda"):
        proc = SiglipImageProcessor.from_pretrained(MODEL)
        model = SiglipVisionModel.from_pretrained(MODEL, dtype=torch.float16).to(device).eval()
        return proc, model
    
    
    def render_ct(s):
        """2-D HU slice -> (3, H, W) uint8, one HU window per channel."""
        return np.stack([np.round((np.clip(s, lo, hi) - lo) / (hi - lo) * 255) for lo, hi in CT_WINDOWS]).astype(np.uint8)
    
    
    def render_mri(s):
        """2-D MRI slice -> (3, H, W) uint8, min-max scaled."""
        lo, hi = s.min(), s.max()
        g = np.round((s - lo) / (hi - lo) * 255) if hi > lo else np.zeros_like(s)
        return np.repeat(g[None].astype(np.uint8), 3, axis=0)
    
    
    def render_mask(s):
        """2-D binary mask -> (3, H, W) uint8, white on black."""
        return np.repeat((s[None] == 1).astype(np.uint8) * 255, 3, axis=0)
    
    
    def slice_ids(depth, n=16):
        return np.arange(depth) if depth <= n else np.linspace(0, depth - 1, n, dtype=int)
    
    
    @torch.no_grad()
    def embed(volume, render, proc, model):
        """Mean of the l2-normalised MedSigLIP embeddings of 16 axial slices -> (1152,)."""
        dev = model.device
        x = torch.from_numpy(np.stack([render(volume[:, :, i]) for i in slice_ids(volume.shape[2])])).to(dev)
        px = proc(images=x, return_tensors="pt", device=dev)["pixel_values"].to(model.dtype)
        e = model(pixel_values=px).pooler_output
        e = e / e.norm(dim=-1, keepdim=True)
        return e.float().mean(0).cpu().numpy()
    
    
    def joint_vectors(image_path, label_path, classes, proc, model, modality="CT", clip=None):
        """One [image || mask] vector (2304,) per foreground class of one case."""
        img = nib.load(image_path).get_fdata(dtype=np.float32)
        lab = nib.load(label_path).get_fdata(dtype=np.float32)
        if clip is not None:
            img = np.clip(img, *clip)
        e_img = embed(img, render_ct if modality == "CT" else render_mri, proc, model)
        return {c: np.concatenate([e_img, embed((lab == c).astype(np.float32), render_mask, proc, model)])
                for c in classes if (lab == c).any()}

    For abdominal CT, the paper clips intensities to [−57, 200] HU before it applies the three windows. Pass clip=(-57, 200) to reproduce its numbers.

  3. 3

    Build the two sets

    The reference set holds images with expert masks. The candidate set holds the test images with the model's masks. The two sets need no common cases. Use one anatomy per set.

    encode_sets.py
    import glob
    import numpy as np
    from mid_encode import load_medsiglip, joint_vectors
    
    proc, model = load_medsiglip()
    LIVER = 1  # label value of the anatomy in your label maps
    
    
    def encode_set(image_dir, label_dir, modality="CT"):
        images = sorted(glob.glob(f"{image_dir}/*.nii.gz"))
        labels = sorted(glob.glob(f"{label_dir}/*.nii.gz"))
        vecs = [joint_vectors(i, l, [LIVER], proc, model, modality, clip=(-57, 200))
                for i, l in zip(images, labels)]
        return np.stack([v[LIVER] for v in vecs if LIVER in v])
    
    
    ref = encode_set("reference/images", "reference/labels")   # expert masks
    cand = encode_set("test/images", "model_a/predictions")     # predicted masks
    np.save("ref.npy", ref)
    np.save("cand_model_a.npy", cand)
  4. 4

    Score

    Fit the PCA on the reference set only, and keep it for every candidate set. A lower MID means that the candidate distribution is closer to the reference. With k = 128, the reference needs at least 128 vectors. Steps 4 to 7 run in one Python session.

    python
    import numpy as np
    from pytorch_mid import PCAProjection, compute_mid_from_latents
    
    ref, cand = np.load("ref.npy"), np.load("cand_model_a.npy")
    proj = PCAProjection(k=128).fit(ref)   # fit on the reference only
    proj.save("pca_liver_k128.pkl")        # reuse it for every candidate set
    print(f"MID = {compute_mid_from_latents(ref, cand, projection=proj):.4f}")
    or from the terminal
    pytorch-mid latents --ref ref.npy --cand cand_model_a.npy --projection pca_liver_k128.pkl
  5. 5

    Compare models at one size

    MID depends on the candidate size. Score every model with the same reference, the same projection and the same number of vectors. Between 100 and 250 vectors per model, subsample all models to the smallest size and repeat the draw. MID has no universal scale, so also measure the clean range of the anatomy: the MID between two random halves of the reference.

    python
    rng = np.random.default_rng(0)
    cands = {m: np.load(f"cand_{m}.npy") for m in ["model_a", "model_b", "model_c"]}
    n = min(len(c) for c in cands.values())
    for name, c in cands.items():
        s = [compute_mid_from_latents(ref, c[rng.choice(len(c), n, replace=False)], projection=proj)
             for _ in range(20)]
        print(f"{name}: MID = {np.mean(s):.4f} ± {np.std(s):.4f}  (n = {n})")
    
    # Clean-versus-clean range of this anatomy: MID between random halves of the reference
    floor = []
    for _ in range(20):
        p = rng.permutation(len(ref))
        floor.append(compute_mid_from_latents(ref[p[::2]], ref[p[1::2]], projection=proj))
    print(f"clean range: {np.mean(floor):.4f} ± {np.std(floor):.4f}")

    The paper's clean ranges for 48 structures are in results/anatomy_reference_index.csv.

  6. 6

    Check the image–mask correspondence

    Project the image half and the mask half with separate PCAs, then split MID into three terms. A mask can have a plausible shape and still be wrong for its image. Such masks raise the cross term, MIDcorr. Shuffling the pairs shows the effect.

    python
    from pytorch_mid.decomposition import compute_mid_decomposed
    
    d = ref.shape[1] // 2                                  # image block size
    pca_img = PCAProjection(k=128).fit(ref[:, :d])
    pca_mask = PCAProjection(k=128).fit(ref[:, d:])
    
    
    def blockwise(x):
        return np.hstack([pca_img.transform(x[:, :d]), pca_mask.transform(x[:, d:])])
    
    
    parts = compute_mid_decomposed(blockwise(ref), blockwise(cand))
    print(parts["img"], parts["mask"], parts["cross"])     # cross = MID_corr
    
    # Same images, same masks, wrong pairs: only the cross term grows
    wrong = np.hstack([cand[:, :d], cand[rng.permutation(len(cand)), d:]])
    print(compute_mid_decomposed(blockwise(ref), blockwise(wrong))["cross"])
  7. 7

    Optional: the paper's estimator

    The package estimates each covariance with the empirical estimator. The paper uses Ledoit–Wolf shrinkage, which has a lower variance for small sets. Use it to compare your scores with the paper's tables.

    python
    from sklearn.covariance import LedoitWolf
    from pytorch_mid import frechet_distance
    
    
    def stats_lw(x):
        return x.mean(axis=0), LedoitWolf().fit(x).covariance_
    
    
    p, q = proj.transform(ref), proj.transform(cand)
    print(f"MID (Ledoit-Wolf) = {frechet_distance(*stats_lw(p), *stats_lw(q)):.4f}")