File size: 2,922 Bytes
54fd3a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Self-contained inference for the selected HEMIT benchmark checkpoint."""
from __future__ import annotations

import importlib.util
import json
from pathlib import Path

import numpy as np
from PIL import Image
import torch
from safetensors.torch import load_file


def load_model(directory=None, device="cpu"):
    directory = Path(directory) if directory is not None else Path(__file__).resolve().parent
    config = json.loads((directory / "config.json").read_text())
    spec = importlib.util.spec_from_file_location("_hemit_release_architecture", directory / "architecture.py")
    architecture = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(architecture)
    model = getattr(architecture, config["architecture"]["class_name"])(**config["architecture"]["kwargs"])
    tensors = load_file(str(directory / "model.safetensors"), device="cpu")
    model.load_state_dict(tensors, strict=True)
    if any(not torch.isfinite(value).all() for value in model.state_dict().values()):
        raise ValueError("The released state contains nonfinite tensors")
    return model.to(device=device, dtype=torch.float32).eval()


def load_rgb_center_crop(path):
    """Match the benchmark: stored RGB uint8 /255, native center256, no resize."""
    with Image.open(path) as image:
        if image.mode != "RGB":
            raise ValueError("Input must be stored 8-bit RGB H&E, without implicit colour conversion")
        array = np.asarray(image)
    if array.dtype != np.uint8 or array.ndim != 3 or array.shape[-1] != 3:
        raise ValueError("Input must be an HWC RGB uint8 image")
    height, width = array.shape[:2]
    if min(height, width) < 256:
        raise ValueError("Input must be at least256x256 native pixels; this loader never resizes")
    top, left = (height - 256) // 2, (width - 256) // 2
    crop = array[top:top + 256, left:left + 256].copy()
    tensor = torch.from_numpy(crop).permute(2, 0, 1).float().div(255).unsqueeze(0)
    return tensor, {"top": top, "left": left, "height": 256, "width": 256}


@torch.inference_mode()
def predict_tensor(model, rgb):
    """Return the unmodified FP32 forward result in DAPI/CD3/panCK order."""
    if rgb.ndim != 4 or rgb.shape[1:] != (3, 256, 256):
        raise ValueError("Expected NCHW RGB at the benchmark's256x256 native crop")
    if not torch.is_floating_point(rgb) or not torch.isfinite(rgb).all() or rgb.min() < 0 or rgb.max() > 1:
        raise ValueError("Input must contain finite RGB values in[0,1]")
    device = next(model.parameters()).device
    if device.type == "cuda":
        torch.backends.cuda.matmul.allow_tf32 = False
        torch.backends.cudnn.allow_tf32 = False
    prediction = model(rgb.to(device=device, dtype=torch.float32)).float()
    if prediction.shape != rgb.shape or not torch.isfinite(prediction).all():
        raise ValueError("Invalid output shape or nonfinite model output")
    return prediction