fix(mri): try weights_only=True first; fall back only for trusted module pickles
Browse files- src/models/mri_dl_2d.py +23 -3
src/models/mri_dl_2d.py
CHANGED
|
@@ -8,6 +8,7 @@ code paths don't care which backend produced the prediction.
|
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
|
|
| 11 |
from pathlib import Path
|
| 12 |
from typing import Any
|
| 13 |
|
|
@@ -47,17 +48,36 @@ def _build_resnet18_4class() -> nn.Module:
|
|
| 47 |
|
| 48 |
|
| 49 |
def load(path: Path) -> nn.Module:
|
| 50 |
-
"""Load checkpoint. Supports state_dict (preferred) or full pickled model.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
path = Path(path)
|
| 52 |
if not path.exists():
|
| 53 |
raise FileNotFoundError(f"MRI 2D checkpoint not found: {path}")
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
if isinstance(obj, nn.Module):
|
| 56 |
model = obj
|
| 57 |
-
|
| 58 |
model = _build_resnet18_4class()
|
| 59 |
clean = {k.removeprefix("module."): v for k, v in obj.items()}
|
| 60 |
model.load_state_dict(clean, strict=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
model.eval()
|
| 62 |
return model
|
| 63 |
|
|
|
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
+
import pickle
|
| 12 |
from pathlib import Path
|
| 13 |
from typing import Any
|
| 14 |
|
|
|
|
| 48 |
|
| 49 |
|
| 50 |
def load(path: Path) -> nn.Module:
|
| 51 |
+
"""Load checkpoint. Supports state_dict (preferred) or full pickled model.
|
| 52 |
+
|
| 53 |
+
Tries `weights_only=True` first (safe; refuses arbitrary pickle opcodes);
|
| 54 |
+
falls back to `weights_only=False` only when the artifact turns out to be
|
| 55 |
+
a full `nn.Module` pickle (rare). The fallback path executes pickle code
|
| 56 |
+
and should only be used with trusted artifacts.
|
| 57 |
+
"""
|
| 58 |
path = Path(path)
|
| 59 |
if not path.exists():
|
| 60 |
raise FileNotFoundError(f"MRI 2D checkpoint not found: {path}")
|
| 61 |
+
try:
|
| 62 |
+
obj = torch.load(str(path), map_location="cpu", weights_only=True)
|
| 63 |
+
except (pickle.UnpicklingError, RuntimeError) as e:
|
| 64 |
+
logger.warning(
|
| 65 |
+
"MRI 2D checkpoint at %s is not a state_dict (weights_only=True failed: %s); "
|
| 66 |
+
"falling back to weights_only=False — only safe with trusted artifacts.",
|
| 67 |
+
path, e,
|
| 68 |
+
)
|
| 69 |
+
obj = torch.load(str(path), map_location="cpu", weights_only=False)
|
| 70 |
if isinstance(obj, nn.Module):
|
| 71 |
model = obj
|
| 72 |
+
elif isinstance(obj, dict):
|
| 73 |
model = _build_resnet18_4class()
|
| 74 |
clean = {k.removeprefix("module."): v for k, v in obj.items()}
|
| 75 |
model.load_state_dict(clean, strict=True)
|
| 76 |
+
else:
|
| 77 |
+
raise ValueError(
|
| 78 |
+
f"MRI 2D checkpoint at {path} has unexpected type {type(obj).__name__}; "
|
| 79 |
+
"expected state_dict (dict) or a full nn.Module pickle."
|
| 80 |
+
)
|
| 81 |
model.eval()
|
| 82 |
return model
|
| 83 |
|