File size: 10,037 Bytes
a8c0492
 
 
f559cc0
a8c0492
 
f559cc0
a8c0492
f559cc0
 
 
a8c0492
 
 
 
 
 
 
f559cc0
 
 
 
 
 
 
a8c0492
 
 
 
 
f559cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c0492
f559cc0
 
 
 
 
a8c0492
 
f559cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c0492
 
 
 
f559cc0
 
 
 
a8c0492
 
 
 
 
 
f559cc0
a8c0492
 
 
 
68bc1c7
 
 
 
 
 
a8c0492
68bc1c7
 
 
 
 
a8c0492
 
 
 
68bc1c7
 
 
 
 
a8c0492
 
 
 
f559cc0
a8c0492
 
 
 
 
 
 
 
 
 
 
 
f559cc0
a8c0492
 
 
f559cc0
 
 
 
 
 
 
 
 
 
a8c0492
 
 
 
 
f559cc0
a8c0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f559cc0
 
a8c0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68bc1c7
 
 
a8c0492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f559cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c0492
f559cc0
a8c0492
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
from __future__ import annotations

from pathlib import Path
from typing import Any, Mapping

import numpy as np
import torch
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.models import EfficientNet_B0_Weights, efficientnet_b0


EFFICIENTNET_VERSION = "efficientnet-b0-ft-v2"
IMAGE_SIZE = 224
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]

EFFICIENTNET_ARCHITECTURE_CURRENT = "gelu-head"
EFFICIENTNET_ARCHITECTURE_LEGACY = "legacy-spatial-attention"
SUPPORTED_EFFICIENTNET_ARCHITECTURES = (
    EFFICIENTNET_ARCHITECTURE_CURRENT,
    EFFICIENTNET_ARCHITECTURE_LEGACY,
)


def clamp(value: float, lower: float = 0.0, upper: float = 1.0) -> float:
    return max(lower, min(upper, value))


class SpatialAttention(nn.Module):
    """Legacy spatial attention block used by the shipped checkpoint."""

    def __init__(self, kernel_size: int = 7) -> None:
        super().__init__()
        self.conv = nn.Conv2d(
            2,
            1,
            kernel_size=kernel_size,
            padding=kernel_size // 2,
            bias=False,
        )
        self.sigmoid = nn.Sigmoid()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        avg_out = torch.mean(x, dim=1, keepdim=True)
        max_out, _ = torch.max(x, dim=1, keepdim=True)
        attention = torch.cat([avg_out, max_out], dim=1)
        scale = self.sigmoid(self.conv(attention))
        return x * scale


def build_efficientnet_model(
    *,
    pretrained: bool = True,
    architecture: str = EFFICIENTNET_ARCHITECTURE_CURRENT,
) -> nn.Module:
    weights = EfficientNet_B0_Weights.IMAGENET1K_V1 if pretrained else None
    model = efficientnet_b0(weights=weights)

    if architecture == EFFICIENTNET_ARCHITECTURE_LEGACY:
        model.features.add_module("spatial_attention", SpatialAttention())
        model.classifier = nn.Sequential(
            nn.Dropout(0.35),
            nn.Linear(1280, 512),
            nn.GELU(),
            nn.BatchNorm1d(512),
            nn.Dropout(0.25),
            nn.Linear(512, 128),
            nn.GELU(),
            nn.BatchNorm1d(128),
            nn.Dropout(0.15),
            nn.Linear(128, 2),
        )
    elif architecture == EFFICIENTNET_ARCHITECTURE_CURRENT:
        model.classifier = nn.Sequential(
            nn.Dropout(0.35),
            nn.Linear(1280, 512),
            nn.GELU(),
            nn.Dropout(0.25),
            nn.Linear(512, 128),
            nn.GELU(),
            nn.Dropout(0.15),
            nn.Linear(128, 2),
        )
    else:
        raise ValueError(
            f"Unsupported EfficientNet architecture {architecture!r}. "
            f"Supported values: {SUPPORTED_EFFICIENTNET_ARCHITECTURES!r}"
        )

    for param in model.features.parameters():
        param.requires_grad = False
    for name, param in model.features.named_parameters():
        if architecture == EFFICIENTNET_ARCHITECTURE_LEGACY:
            if name.startswith(("4", "5", "6", "7", "8", "spatial_attention")):
                param.requires_grad = True
        elif name.startswith(("4", "5", "6", "7", "8")):
            param.requires_grad = True
    for param in model.classifier.parameters():
        param.requires_grad = True
    return model


def build_train_transform() -> transforms.Compose:
    return transforms.Compose(
        [
            transforms.RandomHorizontalFlip(),
            transforms.RandomVerticalFlip(p=0.15),
            transforms.ColorJitter(
                brightness=0.4,
                contrast=0.4,
                saturation=0.3,
                hue=0.05,
            ),
            transforms.RandomRotation(20),
            transforms.RandomAffine(
                degrees=0,
                translate=(0.12, 0.12),
                scale=(0.88, 1.12),
            ),
            transforms.RandomPerspective(distortion_scale=0.15, p=0.3),
            transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
            transforms.ToTensor(),
            transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
            transforms.RandomErasing(
                p=0.25,
                scale=(0.02, 0.12),
                ratio=(0.3, 3.3),
            ),
        ]
    )


def build_val_transform() -> transforms.Compose:
    return transforms.Compose(
        [
            transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
            transforms.ToTensor(),
            transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )


def load_efficientnet_checkpoint(
    path: str | Path,
    *,
    map_location: str | torch.device = "cpu",
) -> dict[str, Any]:
    checkpoint = torch.load(path, map_location=map_location)
    state_dict = checkpoint["state_dict"] if "state_dict" in checkpoint else checkpoint
    architecture_hint = checkpoint.get("architecture")
    architecture = _normalize_architecture_hint(
        architecture_hint,
        state_dict=state_dict,
    )
    model, resolved_architecture = _load_compatible_model(
        state_dict,
        architecture_hint=architecture,
    )

    device = torch.device(map_location)
    model.to(device)
    model.eval()
    return {
        "version": checkpoint.get("version", EFFICIENTNET_VERSION),
        "architecture": resolved_architecture,
        "created_at": checkpoint.get("created_at"),
        "decision_threshold": float(checkpoint.get("decision_threshold", 0.5)),
        "hb_mean": float(checkpoint.get("hb_mean", 0.0)),
        "hb_std": float(checkpoint.get("hb_std", 1.0)),
        "val_metrics": checkpoint.get("val_metrics"),
        "model": model,
        "device": device,
        "transform": build_val_transform(),
    }


def predict_with_efficientnet_model(
    bundle: dict[str, Any],
    image: Image.Image,
    *,
    mc_passes: int = 10,
) -> dict[str, float]:
    model: nn.Module = bundle["model"]
    device: torch.device = bundle["device"]
    transform = bundle["transform"]
    hb_mean = float(bundle.get("hb_mean", 0.0))
    hb_std_scale = max(float(bundle.get("hb_std", 1.0)), 1e-6)

    rgb = image.convert("RGB")
    tta_images = [
        rgb,
        rgb.transpose(Image.FLIP_LEFT_RIGHT),
    ]

    probabilities: list[float] = []
    hemoglobin_values: list[float] = []

    with torch.no_grad():
        for tta_img in tta_images:
            tensor = transform(tta_img).unsqueeze(0).to(device)
            for _ in range(max(mc_passes, 1)):
                model.eval()
                if mc_passes > 1:
                    _enable_dropout(model)
                output = model(tensor)
                probabilities.append(float(torch.sigmoid(output[:, 0]).item()))
                hemoglobin_values.append(
                    float((output[:, 1].item() * hb_std_scale) + hb_mean)
                )

    mean_probability = float(np.mean(probabilities))
    mean_hemoglobin = float(np.mean(hemoglobin_values))
    probability_std = float(np.std(probabilities))
    hemoglobin_std = float(np.std(hemoglobin_values))

    margin_uncertainty = 1.0 - min(1.0, abs(mean_probability - 0.5) * 2.5)
    uncertainty = clamp(
        (probability_std * 2.2)
        + (min(hemoglobin_std / 2.0, 1.0) * 0.30)
        + (margin_uncertainty * 0.18),
        0.04,
        0.95,
    )

    model.eval()
    return {
        "anemia_risk": mean_probability,
        "predicted_hemoglobin": mean_hemoglobin,
        "uncertainty": uncertainty,
        "decision_threshold": float(bundle.get("decision_threshold", 0.5)),
        "probability_std": probability_std,
        "hemoglobin_std": hemoglobin_std,
    }


def _normalize_architecture_hint(
    architecture_hint: object,
    *,
    state_dict: Mapping[str, Any],
) -> str:
    hint = str(architecture_hint).strip().lower() if architecture_hint else ""
    aliases = {
        EFFICIENTNET_ARCHITECTURE_CURRENT: EFFICIENTNET_ARCHITECTURE_CURRENT,
        "current": EFFICIENTNET_ARCHITECTURE_CURRENT,
        "gelu": EFFICIENTNET_ARCHITECTURE_CURRENT,
        "gelu-head": EFFICIENTNET_ARCHITECTURE_CURRENT,
        EFFICIENTNET_ARCHITECTURE_LEGACY: EFFICIENTNET_ARCHITECTURE_LEGACY,
        "legacy": EFFICIENTNET_ARCHITECTURE_LEGACY,
        "legacy-spatial-attention": EFFICIENTNET_ARCHITECTURE_LEGACY,
        "spatial-attention": EFFICIENTNET_ARCHITECTURE_LEGACY,
        "spatial_attention": EFFICIENTNET_ARCHITECTURE_LEGACY,
    }
    if hint in aliases:
        return aliases[hint]
    return _detect_checkpoint_architecture(state_dict)


def _detect_checkpoint_architecture(state_dict: Mapping[str, Any]) -> str:
    keys = set(state_dict.keys())
    if (
        "features.spatial_attention.conv.weight" in keys
        or "classifier.3.running_mean" in keys
        or "classifier.7.running_mean" in keys
        or "classifier.9.weight" in keys
    ):
        return EFFICIENTNET_ARCHITECTURE_LEGACY
    return EFFICIENTNET_ARCHITECTURE_CURRENT


def _load_compatible_model(
    state_dict: Mapping[str, Any],
    *,
    architecture_hint: str,
) -> tuple[nn.Module, str]:
    candidate_architectures = [architecture_hint] + [
        architecture
        for architecture in SUPPORTED_EFFICIENTNET_ARCHITECTURES
        if architecture != architecture_hint
    ]
    errors: dict[str, str] = {}

    for architecture in candidate_architectures:
        model = build_efficientnet_model(
            pretrained=False,
            architecture=architecture,
        )
        try:
            model.load_state_dict(state_dict, strict=True)
            return model, architecture
        except RuntimeError as exc:
            errors[architecture] = str(exc)

    error_summary = " | ".join(
        f"{architecture}: {message}"
        for architecture, message in errors.items()
    )
    raise RuntimeError(
        "EfficientNet checkpoint does not match any supported architecture. "
        f"Tried {candidate_architectures!r}. Errors: {error_summary}"
    )


def _enable_dropout(model: nn.Module) -> None:
    for module in model.modules():
        if isinstance(module, nn.Dropout):
            module.train()