#!/usr/bin/env python3 """Run a released checkpoint (navable_*.pth) on a real_ours split and report the paper's metrics. Supports the mmsegmentation 1.x models: DeepLabv3+, EncNet, SegFormer and Mask2Former (Mask2Former also needs mmdet). Needs torch, mmcv 2.x, mmengine and mmsegmentation 1.x, e.g. pip install -U openmim && mim install mmengine "mmcv>=2.0.0,<2.2.0" "mmsegmentation>=1.2,<2" mmdet SAN, SegMAN and SAM 3 use their own code bases; see the GitHub repository linked in the dataset card. The model config is read from the checkpoint itself, and predictions are mapped from the checkpoint's label order to the dataset's class ids before scoring. Examples: python tools/download.py --checkpoints segformer --train-data real python tools/eval_checkpoint.py --checkpoint navable/checkpoints/navable_segformer-real.pth --pred-dir preds_segformer """ from __future__ import annotations import argparse import io import json import pickle import sys import tempfile import time import types from pathlib import Path import numpy as np from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parent)) import navable as nv # noqa: E402 class _Stub: """Stands in for training-state objects (message hub, numpy scalars) that inference doesn't need.""" def __init__(self, *args, **kwargs): pass def __setstate__(self, state): pass def __call__(self, *args, **kwargs): return _Stub() class _Unpickler(pickle.Unpickler): def find_class(self, module, name): if module.split(".")[0] in ("torch", "collections", "builtins", "_codecs"): return super().find_class(module, name) return _Stub def load_checkpoint(path: Path) -> tuple[dict, str]: """(state_dict, config text) from a released checkpoint, independent of numpy/mmengine versions.""" import torch module = types.ModuleType("navable_unpickle") module.Unpickler, module.load = _Unpickler, pickle.load ckpt = torch.load(path, map_location="cpu", weights_only=False, pickle_module=module) meta = ckpt.get("meta") if isinstance(ckpt, dict) else None cfg = meta.get("cfg") if isinstance(meta, dict) else None if not isinstance(cfg, str) or "state_dict" not in ckpt: raise SystemExit(f"{path.name} is not an mmsegmentation 1.x checkpoint (SAN, SegMAN and SAM 3 " f"need their own code; see the GitHub repository in the dataset card)") return ckpt["state_dict"], cfg def build_model(cfg_text: str, state_dict: dict, device: str): from mmengine.config import Config from mmengine.runner import load_state_dict from mmseg.apis import init_model with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f: f.write(cfg_text) cfg = Config.fromfile(f.name, import_custom_modules=False) cfg.pop("custom_imports", None) # training-only plugins (dataset and metric classes) if "SAN" in str(cfg.model.get("type")): raise SystemExit("SAN needs its own plugin code; see the GitHub repository in the dataset card") model = init_model(cfg, checkpoint=None, device=device) load_state_dict(model, state_dict, strict=True) model.dataset_meta = {"classes": nv.CHECKPOINT_CLASSES, "palette": [nv.PALETTE[nv.CLASS_TO_ID[c]] for c in nv.CHECKPOINT_CLASSES]} return model def main() -> int: p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--checkpoint", type=Path, required=True) p.add_argument("--split", choices=nv.CONFIGS["real_ours"], default="test") p.add_argument("--device", default="cuda:0") p.add_argument("--pred-dir", type=Path, help="also save predictions (dataset class ids) as PNGs") p.add_argument("--data-dir", type=Path, help="downloaded copy of the repo (see tools/download.py)") p.add_argument("--out", type=Path, help="write the full results as JSON") args = p.parse_args() from mmseg.apis import inference_model state_dict, cfg_text = load_checkpoint(args.checkpoint) model = build_model(cfg_text, state_dict, args.device) if args.pred_dir: args.pred_dir.mkdir(parents=True, exist_ok=True) metrics, t0, n = nv.SegmentationMetrics(), time.time(), 0 for row in nv.iter_rows(nv.parquet_files("real_ours", args.split, args.data_dir), columns=["image", "mask"]): bgr = np.ascontiguousarray(np.asarray(nv.open_image(row["image"]).convert("RGB"))[..., ::-1]) pred = inference_model(model, bgr).pred_sem_seg.data[0].cpu().numpy() pred = nv.checkpoint_to_dataset_labels(pred) metrics.update(pred, nv.mask_array(row["mask"])) if args.pred_dir: Image.fromarray(pred).save(args.pred_dir / (Path(nv.row_name(row)).stem + ".png")) n += 1 if n % 250 == 0: print(f" {n} images ({time.time() - t0:.0f}s)", flush=True) r = metrics.results() print(f"{args.checkpoint.name} on real_ours/{args.split} ({n} images): mIoU {r['mIoU']:.2f}, " f"mPrecision {r['mPrecision']:.2f}, mRecall {r['mRecall']:.2f} (paper protocol: background + 10 classes)") print("per-class IoU: " + ", ".join(f"{k} {v['IoU']:.1f}" for k, v in r["per_class"].items() if v["gt_pixels"])) if args.out: args.out.write_text(json.dumps({"checkpoint": args.checkpoint.name, "split": args.split, "images": n, **r}, indent=1)) return 0 if __name__ == "__main__": sys.exit(main())