Upload 171 files
Browse files- milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/cli.py +2 -0
- milk10k_effb2_metadata/inference.py +10 -3
- milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/milk10k_effb2_metadata/cli.py +83 -1
- milk10k_effb2_metadata/milk10k_effb2_metadata/inference.py +95 -11
- milk10k_effb2_metadata/milk10k_effb2_metadata/model_setup.py +50 -6
- milk10k_effb2_metadata/milk10k_effb2_metadata/models.py +155 -27
- milk10k_effb2_metadata/milk10k_effb2_metadata/training.py +60 -2
- milk10k_effb2_metadata/model_setup.py +31 -5
- milk10k_effb2_metadata/models.py +120 -23
- milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc +0 -0
- milk10k_effb2_metadata/tests/test_fusion_and_f1_loss.py +69 -0
- milk10k_effb2_metadata/training.py +7 -1
milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/cli.py
CHANGED
|
@@ -83,6 +83,8 @@ def parse_args() -> argparse.Namespace:
|
|
| 83 |
"adaptive_gate",
|
| 84 |
"moe",
|
| 85 |
"shared_private",
|
|
|
|
|
|
|
| 86 |
],
|
| 87 |
default="concat",
|
| 88 |
help="Image representation fusion mode. concat keeps the baseline final fusion.",
|
|
|
|
| 83 |
"adaptive_gate",
|
| 84 |
"moe",
|
| 85 |
"shared_private",
|
| 86 |
+
"single_encoder_canvas",
|
| 87 |
+
"shared_encoder_pool",
|
| 88 |
],
|
| 89 |
default="concat",
|
| 90 |
help="Image representation fusion mode. concat keeps the baseline final fusion.",
|
milk10k_effb2_metadata/inference.py
CHANGED
|
@@ -29,6 +29,7 @@ from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
|
| 29 |
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 30 |
from milk10k_effb2_metadata.models import (
|
| 31 |
DualEffB2MetadataClassifier,
|
|
|
|
| 32 |
model_class_for_backbone,
|
| 33 |
normalize_backbone_name,
|
| 34 |
resolve_image_size,
|
|
@@ -198,9 +199,15 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 198 |
state = checkpoint["model_state"]
|
| 199 |
checkpoint_args = checkpoint.get("args", {})
|
| 200 |
class_names = checkpoint["class_names"]
|
| 201 |
-
clinical_backend = infer_backend_from_model_state(state, "clinical_encoder.")
|
| 202 |
-
dermoscopic_backend = infer_backend_from_model_state(state, "dermoscopic_encoder.")
|
| 203 |
backbone = normalize_backbone_name(checkpoint_arg(checkpoint_args, "backbone", "efficientnet_b2"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
model_class = model_class_for_backbone(backbone)
|
| 205 |
saved_model_type = checkpoint.get("model_type")
|
| 206 |
if saved_model_type is not None and saved_model_type != model_class.__name__:
|
|
@@ -221,7 +228,7 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 221 |
backbone=backbone,
|
| 222 |
disable_metadata=checkpoint_arg(checkpoint_args, "disable_metadata", False),
|
| 223 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 224 |
-
image_fusion=
|
| 225 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
| 226 |
classifier_style=checkpoint_arg(checkpoint_args, "classifier_style", "legacy"),
|
| 227 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
|
|
|
| 29 |
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 30 |
from milk10k_effb2_metadata.models import (
|
| 31 |
DualEffB2MetadataClassifier,
|
| 32 |
+
is_one_encoder_image_fusion,
|
| 33 |
model_class_for_backbone,
|
| 34 |
normalize_backbone_name,
|
| 35 |
resolve_image_size,
|
|
|
|
| 199 |
state = checkpoint["model_state"]
|
| 200 |
checkpoint_args = checkpoint.get("args", {})
|
| 201 |
class_names = checkpoint["class_names"]
|
|
|
|
|
|
|
| 202 |
backbone = normalize_backbone_name(checkpoint_arg(checkpoint_args, "backbone", "efficientnet_b2"))
|
| 203 |
+
image_fusion = checkpoint_arg(checkpoint_args, "image_fusion", "concat")
|
| 204 |
+
if is_one_encoder_image_fusion(image_fusion):
|
| 205 |
+
shared_backend = infer_backend_from_model_state(state, "shared_encoder.")
|
| 206 |
+
clinical_backend = shared_backend
|
| 207 |
+
dermoscopic_backend = shared_backend
|
| 208 |
+
else:
|
| 209 |
+
clinical_backend = infer_backend_from_model_state(state, "clinical_encoder.")
|
| 210 |
+
dermoscopic_backend = infer_backend_from_model_state(state, "dermoscopic_encoder.")
|
| 211 |
model_class = model_class_for_backbone(backbone)
|
| 212 |
saved_model_type = checkpoint.get("model_type")
|
| 213 |
if saved_model_type is not None and saved_model_type != model_class.__name__:
|
|
|
|
| 228 |
backbone=backbone,
|
| 229 |
disable_metadata=checkpoint_arg(checkpoint_args, "disable_metadata", False),
|
| 230 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 231 |
+
image_fusion=image_fusion,
|
| 232 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
| 233 |
classifier_style=checkpoint_arg(checkpoint_args, "classifier_style", "legacy"),
|
| 234 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc and b/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/cli.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc and b/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/inference.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc and b/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/model_setup.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc and b/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/models.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc and b/milk10k_effb2_metadata/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/milk10k_effb2_metadata/cli.py
CHANGED
|
@@ -9,6 +9,18 @@ from pathlib import Path
|
|
| 9 |
def parse_args() -> argparse.Namespace:
|
| 10 |
parser = argparse.ArgumentParser(description="Train MILK10k dual-image backbones with metadata fusion.")
|
| 11 |
parser.add_argument("--data-dir", type=Path, default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
parser.add_argument(
|
| 13 |
"--clinical-checkpoint",
|
| 14 |
type=Path,
|
|
@@ -35,7 +47,10 @@ def parse_args() -> argparse.Namespace:
|
|
| 35 |
parser.add_argument(
|
| 36 |
"--backbone",
|
| 37 |
default="efficientnet_b2",
|
| 38 |
-
help=
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
parser.add_argument(
|
| 41 |
"--num-workers",
|
|
@@ -68,6 +83,8 @@ def parse_args() -> argparse.Namespace:
|
|
| 68 |
"adaptive_gate",
|
| 69 |
"moe",
|
| 70 |
"shared_private",
|
|
|
|
|
|
|
| 71 |
],
|
| 72 |
default="concat",
|
| 73 |
help="Image representation fusion mode. concat keeps the baseline final fusion.",
|
|
@@ -95,10 +112,42 @@ def parse_args() -> argparse.Namespace:
|
|
| 95 |
action="store_true",
|
| 96 |
help="Keep synthetic lesion IDs containing __sdpair_ in train only; validation is split from real lesions.",
|
| 97 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
parser.add_argument("--seed", type=int, default=42)
|
| 99 |
parser.add_argument("--branch-dim", type=int, default=512)
|
| 100 |
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 101 |
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
parser.add_argument("--dropout", type=float, default=0.3)
|
| 103 |
parser.add_argument(
|
| 104 |
"--logit-fusion-mode",
|
|
@@ -112,6 +161,30 @@ def parse_args() -> argparse.Namespace:
|
|
| 112 |
parser.add_argument("--class-weight", action="store_true")
|
| 113 |
parser.add_argument("--weighted-sampler", action="store_true")
|
| 114 |
parser.add_argument("--sampler-power", type=float, default=1.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
parser.add_argument("--loss", choices=["ce", "focal", "ldam", "ce_dice", "ce_f1"], default="ce")
|
| 116 |
parser.add_argument("--focal-gamma", type=float, default=2.0)
|
| 117 |
parser.add_argument("--dice-weight", type=float, default=0.3)
|
|
@@ -172,4 +245,13 @@ def parse_args() -> argparse.Namespace:
|
|
| 172 |
parser.add_argument("--calibration-step", type=float, default=0.25)
|
| 173 |
parser.add_argument("--calibration-passes", type=int, default=3)
|
| 174 |
parser.add_argument("--patience", type=int, default=6)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
return parser.parse_args()
|
|
|
|
| 9 |
def parse_args() -> argparse.Namespace:
|
| 10 |
parser = argparse.ArgumentParser(description="Train MILK10k dual-image backbones with metadata fusion.")
|
| 11 |
parser.add_argument("--data-dir", type=Path, default=None)
|
| 12 |
+
parser.add_argument(
|
| 13 |
+
"--dermoscopic-mask-dir",
|
| 14 |
+
type=Path,
|
| 15 |
+
default=None,
|
| 16 |
+
help="Optional directory containing <lesion_id>_dermoscopic_mask.png files.",
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--min-dermoscopic-mask-ratio",
|
| 20 |
+
type=float,
|
| 21 |
+
default=0.01,
|
| 22 |
+
help="Fallback to the original dermoscopic image when mask foreground ratio is below this value.",
|
| 23 |
+
)
|
| 24 |
parser.add_argument(
|
| 25 |
"--clinical-checkpoint",
|
| 26 |
type=Path,
|
|
|
|
| 47 |
parser.add_argument(
|
| 48 |
"--backbone",
|
| 49 |
default="efficientnet_b2",
|
| 50 |
+
help=(
|
| 51 |
+
"Backbone model architecture (efficientnet_b2, tf_efficientnetv2_b2, "
|
| 52 |
+
"efficientnet_b1, resnet50, convnext_base)."
|
| 53 |
+
),
|
| 54 |
)
|
| 55 |
parser.add_argument(
|
| 56 |
"--num-workers",
|
|
|
|
| 83 |
"adaptive_gate",
|
| 84 |
"moe",
|
| 85 |
"shared_private",
|
| 86 |
+
"single_encoder_canvas",
|
| 87 |
+
"shared_encoder_pool",
|
| 88 |
],
|
| 89 |
default="concat",
|
| 90 |
help="Image representation fusion mode. concat keeps the baseline final fusion.",
|
|
|
|
| 112 |
action="store_true",
|
| 113 |
help="Keep synthetic lesion IDs containing __sdpair_ in train only; validation is split from real lesions.",
|
| 114 |
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--augmented-data-dir",
|
| 117 |
+
type=Path,
|
| 118 |
+
default=None,
|
| 119 |
+
help="Optional augmented MILK10k-style data dir. Only extra lesion IDs are appended to the train split.",
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--augmented-max-per-class",
|
| 123 |
+
type=int,
|
| 124 |
+
default=0,
|
| 125 |
+
help="Cap extra augmented lesions per class. 0 keeps all extra rows from --augmented-data-dir.",
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--augmented-classes",
|
| 129 |
+
nargs="*",
|
| 130 |
+
default=[],
|
| 131 |
+
help="Optional class-name allowlist for appended augmented lesions, e.g. --augmented-classes INF BEN_OTH DF VASC.",
|
| 132 |
+
)
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--zero-augmented-metadata",
|
| 135 |
+
action="store_true",
|
| 136 |
+
help="Set metadata vectors to all zeros for rows appended from --augmented-data-dir.",
|
| 137 |
+
)
|
| 138 |
parser.add_argument("--seed", type=int, default=42)
|
| 139 |
parser.add_argument("--branch-dim", type=int, default=512)
|
| 140 |
parser.add_argument("--metadata-dim", type=int, default=64)
|
| 141 |
parser.add_argument("--classifier-hidden-dim", type=int, default=512)
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--classifier-style",
|
| 144 |
+
choices=["legacy", "simple"],
|
| 145 |
+
default="legacy",
|
| 146 |
+
help=(
|
| 147 |
+
"Final fused classifier architecture. legacy keeps the existing LayerNorm/GELU head; "
|
| 148 |
+
"simple uses Linear-ReLU-Dropout-Linear."
|
| 149 |
+
),
|
| 150 |
+
)
|
| 151 |
parser.add_argument("--dropout", type=float, default=0.3)
|
| 152 |
parser.add_argument(
|
| 153 |
"--logit-fusion-mode",
|
|
|
|
| 161 |
parser.add_argument("--class-weight", action="store_true")
|
| 162 |
parser.add_argument("--weighted-sampler", action="store_true")
|
| 163 |
parser.add_argument("--sampler-power", type=float, default=1.0)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--balance-mode",
|
| 166 |
+
choices=["none", "hybrid"],
|
| 167 |
+
default="none",
|
| 168 |
+
help="Train-only epoch balancing. hybrid caps the largest class and mildly oversamples eligible tail classes.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--balance-head-ratio",
|
| 172 |
+
type=float,
|
| 173 |
+
default=2.0,
|
| 174 |
+
help="In hybrid mode, cap the largest class at this multiple of the second-largest class.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--balance-tail-floor",
|
| 178 |
+
type=int,
|
| 179 |
+
default=100,
|
| 180 |
+
help="In hybrid mode, oversample eligible classes below this count up to this many rows per epoch.",
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--balance-min-source-count",
|
| 184 |
+
type=int,
|
| 185 |
+
default=20,
|
| 186 |
+
help="Do not oversample a class with fewer real train rows than this value.",
|
| 187 |
+
)
|
| 188 |
parser.add_argument("--loss", choices=["ce", "focal", "ldam", "ce_dice", "ce_f1"], default="ce")
|
| 189 |
parser.add_argument("--focal-gamma", type=float, default=2.0)
|
| 190 |
parser.add_argument("--dice-weight", type=float, default=0.3)
|
|
|
|
| 245 |
parser.add_argument("--calibration-step", type=float, default=0.25)
|
| 246 |
parser.add_argument("--calibration-passes", type=int, default=3)
|
| 247 |
parser.add_argument("--patience", type=int, default=6)
|
| 248 |
+
parser.add_argument("--tau", type=float, default=0.0, help="Generalized Balanced Softmax strength in [0, 0.5].")
|
| 249 |
+
parser.add_argument("--lws-epochs", type=int, default=0, help="Number of LWS post-training epochs; 0 disables LWS.")
|
| 250 |
+
parser.add_argument("--lws-lr", type=float, default=1e-2)
|
| 251 |
+
parser.add_argument("--lws-sampler-power", type=float, default=0.5)
|
| 252 |
+
parser.add_argument("--lws-min-scale", type=float, default=0.75)
|
| 253 |
+
parser.add_argument("--lws-max-scale", type=float, default=1.5)
|
| 254 |
+
parser.add_argument("--ema", action="store_true", help="Enable Exponential Moving Average (EMA) for model weights")
|
| 255 |
+
parser.add_argument("--ema-decay", type=float, default=0.999, help="Decay rate for EMA")
|
| 256 |
+
parser.add_argument("--fit-temperature", action="store_true", help="Fit one positive validation temperature per checkpoint variant.")
|
| 257 |
return parser.parse_args()
|
milk10k_effb2_metadata/milk10k_effb2_metadata/inference.py
CHANGED
|
@@ -15,10 +15,21 @@ from torch.utils.data import DataLoader, Dataset
|
|
| 15 |
from tqdm.auto import tqdm
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
-
from milk10k_effb2_metadata.data import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
|
|
|
| 20 |
from milk10k_effb2_metadata.models import (
|
| 21 |
DualEffB2MetadataClassifier,
|
|
|
|
| 22 |
model_class_for_backbone,
|
| 23 |
normalize_backbone_name,
|
| 24 |
resolve_image_size,
|
|
@@ -35,9 +46,9 @@ class InferencePairedDataset(Dataset):
|
|
| 35 |
def __len__(self) -> int:
|
| 36 |
return len(self.df)
|
| 37 |
|
| 38 |
-
def _load_image(self, path: str) -> torch.Tensor:
|
| 39 |
with Image.open(path) as img:
|
| 40 |
-
image =
|
| 41 |
if self.transform is not None:
|
| 42 |
image = self.transform(image)
|
| 43 |
return image
|
|
@@ -46,7 +57,10 @@ class InferencePairedDataset(Dataset):
|
|
| 46 |
row = self.df.iloc[idx]
|
| 47 |
return {
|
| 48 |
"clinical": self._load_image(row["clinical_path"]),
|
| 49 |
-
"dermoscopic": self._load_image(
|
|
|
|
|
|
|
|
|
|
| 50 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 51 |
}
|
| 52 |
|
|
@@ -63,6 +77,18 @@ def parse_args() -> argparse.Namespace:
|
|
| 63 |
parser.add_argument("--data-dir", type=Path, default=None, help="Directory containing MILK10k input/metadata files.")
|
| 64 |
parser.add_argument("--input-dir", type=Path, default=None, help="Image root. Overrides --data-dir/MILK10k_Training_Input.")
|
| 65 |
parser.add_argument("--metadata-csv", type=Path, default=None, help="Metadata CSV. Overrides --data-dir/MILK10k_Training_Metadata.csv.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
parser.add_argument("--groundtruth-csv", type=Path, default=None, help="Optional ground-truth CSV for metrics.")
|
| 67 |
parser.add_argument("--output", type=Path, default=Path("test_predictions.csv"))
|
| 68 |
parser.add_argument("--batch-size", type=int, default=16)
|
|
@@ -173,9 +199,15 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 173 |
state = checkpoint["model_state"]
|
| 174 |
checkpoint_args = checkpoint.get("args", {})
|
| 175 |
class_names = checkpoint["class_names"]
|
| 176 |
-
clinical_backend = infer_backend_from_model_state(state, "clinical_encoder.")
|
| 177 |
-
dermoscopic_backend = infer_backend_from_model_state(state, "dermoscopic_encoder.")
|
| 178 |
backbone = normalize_backbone_name(checkpoint_arg(checkpoint_args, "backbone", "efficientnet_b2"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
model_class = model_class_for_backbone(backbone)
|
| 180 |
saved_model_type = checkpoint.get("model_type")
|
| 181 |
if saved_model_type is not None and saved_model_type != model_class.__name__:
|
|
@@ -196,20 +228,29 @@ def build_model_from_checkpoint(checkpoint: dict[str, Any], metadata_dim: int, d
|
|
| 196 |
backbone=backbone,
|
| 197 |
disable_metadata=checkpoint_arg(checkpoint_args, "disable_metadata", False),
|
| 198 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 199 |
-
image_fusion=
|
| 200 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
|
|
|
| 201 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
| 202 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 203 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 204 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 205 |
).to(device)
|
| 206 |
-
|
| 207 |
model.eval()
|
| 208 |
return model
|
| 209 |
|
| 210 |
|
| 211 |
@torch.no_grad()
|
| 212 |
-
def predict_dataframe(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
probs_all = []
|
| 214 |
for batch in tqdm(loader, leave=False):
|
| 215 |
clinical = batch["clinical"].to(device, non_blocking=True)
|
|
@@ -227,7 +268,7 @@ def predict_dataframe(model: DualEffB2MetadataClassifier, loader: DataLoader, de
|
|
| 227 |
probs = None
|
| 228 |
for clinical_view, dermoscopic_view in views:
|
| 229 |
logits = model(clinical_view, dermoscopic_view, metadata)
|
| 230 |
-
view_prob = torch.softmax(logits, dim=1)
|
| 231 |
probs = view_prob if probs is None else probs + view_prob
|
| 232 |
probs_all.append((probs / len(views)).cpu().numpy())
|
| 233 |
return np.concatenate(probs_all)
|
|
@@ -294,6 +335,21 @@ def main() -> None:
|
|
| 294 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 295 |
input_dir, metadata_csv, groundtruth_csv = resolve_input_paths(args)
|
| 296 |
df = load_inference_dataframe(input_dir, metadata_csv, groundtruth_csv)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
checkpoint_paths = resolve_checkpoint_paths(args)
|
| 298 |
ensemble_probs = []
|
| 299 |
class_names: list[str] | None = None
|
|
@@ -324,7 +380,18 @@ def main() -> None:
|
|
| 324 |
shuffle=False,
|
| 325 |
)
|
| 326 |
model = build_model_from_checkpoint(checkpoint, dataset.metadata.shape[1], device)
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
class_bias = load_calibration_bias(checkpoint_path, args, checkpoint_class_names)
|
| 329 |
if class_bias is not None:
|
| 330 |
y_prob = apply_class_bias(y_prob, class_bias)
|
|
@@ -334,6 +401,23 @@ def main() -> None:
|
|
| 334 |
y_prob = np.mean(ensemble_probs, axis=0)
|
| 335 |
save_inference_outputs(df, y_prob, class_names, args.output, args.include_debug_columns)
|
| 336 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
print(f"Saved predictions: {args.output}")
|
| 338 |
if "label" in df.columns and df["label"].notna().all():
|
| 339 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
|
|
|
| 15 |
from tqdm.auto import tqdm
|
| 16 |
|
| 17 |
from datasets import LABEL_COLUMNS, normalize_image_type
|
| 18 |
+
from milk10k_effb2_metadata.data import (
|
| 19 |
+
DERMOSCOPIC_MASK_PATH_COLUMN,
|
| 20 |
+
METADATA_COLUMNS,
|
| 21 |
+
apply_dermoscopic_mask,
|
| 22 |
+
audit_dermoscopic_masks,
|
| 23 |
+
make_transforms,
|
| 24 |
+
metadata_vector,
|
| 25 |
+
print_mask_audit_summary,
|
| 26 |
+
resolve_monet_columns,
|
| 27 |
+
)
|
| 28 |
from milk10k_effb2_metadata.metrics import apply_class_bias, compute_metrics
|
| 29 |
+
from milk10k_effb2_metadata.model_setup import load_model_state_compat
|
| 30 |
from milk10k_effb2_metadata.models import (
|
| 31 |
DualEffB2MetadataClassifier,
|
| 32 |
+
is_one_encoder_image_fusion,
|
| 33 |
model_class_for_backbone,
|
| 34 |
normalize_backbone_name,
|
| 35 |
resolve_image_size,
|
|
|
|
| 46 |
def __len__(self) -> int:
|
| 47 |
return len(self.df)
|
| 48 |
|
| 49 |
+
def _load_image(self, path: str, mask_path: str | Path | None = None) -> torch.Tensor:
|
| 50 |
with Image.open(path) as img:
|
| 51 |
+
image = apply_dermoscopic_mask(img, mask_path)
|
| 52 |
if self.transform is not None:
|
| 53 |
image = self.transform(image)
|
| 54 |
return image
|
|
|
|
| 57 |
row = self.df.iloc[idx]
|
| 58 |
return {
|
| 59 |
"clinical": self._load_image(row["clinical_path"]),
|
| 60 |
+
"dermoscopic": self._load_image(
|
| 61 |
+
row["dermoscopic_path"],
|
| 62 |
+
row.get(DERMOSCOPIC_MASK_PATH_COLUMN),
|
| 63 |
+
),
|
| 64 |
"metadata": torch.from_numpy(self.metadata[idx]),
|
| 65 |
}
|
| 66 |
|
|
|
|
| 77 |
parser.add_argument("--data-dir", type=Path, default=None, help="Directory containing MILK10k input/metadata files.")
|
| 78 |
parser.add_argument("--input-dir", type=Path, default=None, help="Image root. Overrides --data-dir/MILK10k_Training_Input.")
|
| 79 |
parser.add_argument("--metadata-csv", type=Path, default=None, help="Metadata CSV. Overrides --data-dir/MILK10k_Training_Metadata.csv.")
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--dermoscopic-mask-dir",
|
| 82 |
+
type=Path,
|
| 83 |
+
default=None,
|
| 84 |
+
help="Optional directory containing <lesion_id>_dermoscopic_mask.png files.",
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--min-dermoscopic-mask-ratio",
|
| 88 |
+
type=float,
|
| 89 |
+
default=0.01,
|
| 90 |
+
help="Fallback to the original dermoscopic image when mask foreground ratio is below this value.",
|
| 91 |
+
)
|
| 92 |
parser.add_argument("--groundtruth-csv", type=Path, default=None, help="Optional ground-truth CSV for metrics.")
|
| 93 |
parser.add_argument("--output", type=Path, default=Path("test_predictions.csv"))
|
| 94 |
parser.add_argument("--batch-size", type=int, default=16)
|
|
|
|
| 199 |
state = checkpoint["model_state"]
|
| 200 |
checkpoint_args = checkpoint.get("args", {})
|
| 201 |
class_names = checkpoint["class_names"]
|
|
|
|
|
|
|
| 202 |
backbone = normalize_backbone_name(checkpoint_arg(checkpoint_args, "backbone", "efficientnet_b2"))
|
| 203 |
+
image_fusion = checkpoint_arg(checkpoint_args, "image_fusion", "concat")
|
| 204 |
+
if is_one_encoder_image_fusion(image_fusion):
|
| 205 |
+
shared_backend = infer_backend_from_model_state(state, "shared_encoder.")
|
| 206 |
+
clinical_backend = shared_backend
|
| 207 |
+
dermoscopic_backend = shared_backend
|
| 208 |
+
else:
|
| 209 |
+
clinical_backend = infer_backend_from_model_state(state, "clinical_encoder.")
|
| 210 |
+
dermoscopic_backend = infer_backend_from_model_state(state, "dermoscopic_encoder.")
|
| 211 |
model_class = model_class_for_backbone(backbone)
|
| 212 |
saved_model_type = checkpoint.get("model_type")
|
| 213 |
if saved_model_type is not None and saved_model_type != model_class.__name__:
|
|
|
|
| 228 |
backbone=backbone,
|
| 229 |
disable_metadata=checkpoint_arg(checkpoint_args, "disable_metadata", False),
|
| 230 |
metadata_fusion=checkpoint_arg(checkpoint_args, "metadata_fusion", "concat"),
|
| 231 |
+
image_fusion=image_fusion,
|
| 232 |
metadata_gate_hidden_dim=checkpoint_args.get("metadata_gate_hidden_dim"),
|
| 233 |
+
classifier_style=checkpoint_arg(checkpoint_args, "classifier_style", "legacy"),
|
| 234 |
logit_fusion_mode=checkpoint_arg(checkpoint_args, "logit_fusion_mode", "single"),
|
| 235 |
fusion_logit_weight=checkpoint_arg(checkpoint_args, "fusion_logit_weight", 0.6),
|
| 236 |
clinical_logit_weight=checkpoint_arg(checkpoint_args, "clinical_logit_weight", 0.2),
|
| 237 |
dermoscopic_logit_weight=checkpoint_arg(checkpoint_args, "dermoscopic_logit_weight", 0.2),
|
| 238 |
).to(device)
|
| 239 |
+
load_model_state_compat(model, state)
|
| 240 |
model.eval()
|
| 241 |
return model
|
| 242 |
|
| 243 |
|
| 244 |
@torch.no_grad()
|
| 245 |
+
def predict_dataframe(
|
| 246 |
+
model: DualEffB2MetadataClassifier,
|
| 247 |
+
loader: DataLoader,
|
| 248 |
+
device: torch.device,
|
| 249 |
+
tta_flips: bool = False,
|
| 250 |
+
temperature: float = 1.0,
|
| 251 |
+
) -> np.ndarray:
|
| 252 |
+
if temperature <= 0.0:
|
| 253 |
+
raise ValueError(f"Checkpoint temperature must be positive, got {temperature}.")
|
| 254 |
probs_all = []
|
| 255 |
for batch in tqdm(loader, leave=False):
|
| 256 |
clinical = batch["clinical"].to(device, non_blocking=True)
|
|
|
|
| 268 |
probs = None
|
| 269 |
for clinical_view, dermoscopic_view in views:
|
| 270 |
logits = model(clinical_view, dermoscopic_view, metadata)
|
| 271 |
+
view_prob = torch.softmax(logits / temperature, dim=1)
|
| 272 |
probs = view_prob if probs is None else probs + view_prob
|
| 273 |
probs_all.append((probs / len(views)).cpu().numpy())
|
| 274 |
return np.concatenate(probs_all)
|
|
|
|
| 335 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 336 |
input_dir, metadata_csv, groundtruth_csv = resolve_input_paths(args)
|
| 337 |
df = load_inference_dataframe(input_dir, metadata_csv, groundtruth_csv)
|
| 338 |
+
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 339 |
+
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 340 |
+
if args.dermoscopic_mask_dir is not None:
|
| 341 |
+
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 342 |
+
df, mask_audit = audit_dermoscopic_masks(
|
| 343 |
+
df,
|
| 344 |
+
args.dermoscopic_mask_dir,
|
| 345 |
+
args.min_dermoscopic_mask_ratio,
|
| 346 |
+
mask_id_column="dermoscopic_isic_id",
|
| 347 |
+
mask_suffix="_mask.png",
|
| 348 |
+
)
|
| 349 |
+
audit_output = args.output.with_name(f"{args.output.stem}.mask_audit.csv")
|
| 350 |
+
audit_output.parent.mkdir(parents=True, exist_ok=True)
|
| 351 |
+
mask_audit.to_csv(audit_output, index=False)
|
| 352 |
+
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 353 |
checkpoint_paths = resolve_checkpoint_paths(args)
|
| 354 |
ensemble_probs = []
|
| 355 |
class_names: list[str] | None = None
|
|
|
|
| 380 |
shuffle=False,
|
| 381 |
)
|
| 382 |
model = build_model_from_checkpoint(checkpoint, dataset.metadata.shape[1], device)
|
| 383 |
+
temperature = float(checkpoint.get("temperature", 1.0))
|
| 384 |
+
y_prob = predict_dataframe(
|
| 385 |
+
model,
|
| 386 |
+
loader,
|
| 387 |
+
device,
|
| 388 |
+
tta_flips=args.tta_flips,
|
| 389 |
+
temperature=temperature,
|
| 390 |
+
)
|
| 391 |
+
print(
|
| 392 |
+
f"Checkpoint {checkpoint_path.name}: variant={checkpoint.get('checkpoint_variant', 'legacy')}, "
|
| 393 |
+
f"temperature={temperature:.4f}"
|
| 394 |
+
)
|
| 395 |
class_bias = load_calibration_bias(checkpoint_path, args, checkpoint_class_names)
|
| 396 |
if class_bias is not None:
|
| 397 |
y_prob = apply_class_bias(y_prob, class_bias)
|
|
|
|
| 401 |
y_prob = np.mean(ensemble_probs, axis=0)
|
| 402 |
save_inference_outputs(df, y_prob, class_names, args.output, args.include_debug_columns)
|
| 403 |
|
| 404 |
+
y_pred = y_prob.argmax(axis=1)
|
| 405 |
+
for tail_name in ("DF", "INF"):
|
| 406 |
+
if tail_name not in class_names:
|
| 407 |
+
continue
|
| 408 |
+
idx = class_names.index(tail_name)
|
| 409 |
+
predicted_count = int((y_pred == idx).sum())
|
| 410 |
+
max_probability = float(y_prob[:, idx].max())
|
| 411 |
+
mean_probability = float(y_prob[:, idx].mean())
|
| 412 |
+
print(
|
| 413 |
+
f"Tail audit {tail_name}: predicted_count={predicted_count}, "
|
| 414 |
+
f"mean_probability={mean_probability:.6f}, max_probability={max_probability:.6f}"
|
| 415 |
+
)
|
| 416 |
+
if predicted_count == 0:
|
| 417 |
+
print(f"WARNING: no sample is predicted as {tail_name}.")
|
| 418 |
+
if max_probability < 0.01:
|
| 419 |
+
print(f"WARNING: {tail_name} maximum probability is below 0.01.")
|
| 420 |
+
|
| 421 |
print(f"Saved predictions: {args.output}")
|
| 422 |
if "label" in df.columns and df["label"].notna().all():
|
| 423 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
milk10k_effb2_metadata/milk10k_effb2_metadata/model_setup.py
CHANGED
|
@@ -12,7 +12,25 @@ from milk10k_effb2_metadata.checkpoints import (
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
| 15 |
-
from milk10k_effb2_metadata.models import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefix: str) -> str:
|
|
@@ -31,6 +49,21 @@ def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefi
|
|
| 31 |
|
| 32 |
|
| 33 |
def resolve_training_backbone_backends(args: argparse.Namespace, device: torch.device) -> tuple[str, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
if args.backbone_backend != "auto":
|
| 35 |
return args.backbone_backend, args.backbone_backend
|
| 36 |
if args.clinical_checkpoint is not None and args.dermoscopic_checkpoint is not None:
|
|
@@ -74,9 +107,16 @@ def build_optimizer(
|
|
| 74 |
for name, param in model.named_parameters():
|
| 75 |
if not param.requires_grad:
|
| 76 |
continue
|
| 77 |
-
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.")):
|
| 78 |
encoder_params.append(param)
|
| 79 |
-
elif name.startswith(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
metadata_params.append(param)
|
| 81 |
else:
|
| 82 |
head_params.append(param)
|
|
@@ -92,7 +132,7 @@ def build_optimizer(
|
|
| 92 |
def set_metadata_head_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 93 |
for param in model.metadata_head.parameters():
|
| 94 |
param.requires_grad = trainable
|
| 95 |
-
for module_name in ("clinical_metadata_gate", "dermoscopic_metadata_gate"):
|
| 96 |
module = getattr(model, module_name, None)
|
| 97 |
if module is not None:
|
| 98 |
for param in module.parameters():
|
|
@@ -103,6 +143,7 @@ def load_resume_checkpoint(
|
|
| 103 |
checkpoint_path: Path | None,
|
| 104 |
model: DualEffB2MetadataClassifier,
|
| 105 |
device: torch.device,
|
|
|
|
| 106 |
) -> tuple[int, float, str | None]:
|
| 107 |
if checkpoint_path is None:
|
| 108 |
return 1, float("-inf"), None
|
|
@@ -110,7 +151,9 @@ def load_resume_checkpoint(
|
|
| 110 |
if not checkpoint_path.exists():
|
| 111 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 112 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 115 |
best_val_f1 = float(
|
| 116 |
checkpoint.get(
|
|
@@ -152,12 +195,13 @@ def build_model(
|
|
| 152 |
metadata_fusion=args.metadata_fusion,
|
| 153 |
image_fusion=getattr(args, "image_fusion", "concat"),
|
| 154 |
metadata_gate_hidden_dim=args.metadata_gate_hidden_dim,
|
|
|
|
| 155 |
logit_fusion_mode=args.logit_fusion_mode,
|
| 156 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 157 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 158 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 159 |
).to(device)
|
| 160 |
-
if args.resume_checkpoint is None:
|
| 161 |
if args.clinical_checkpoint is not None:
|
| 162 |
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 163 |
if args.dermoscopic_checkpoint is not None:
|
|
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
| 15 |
+
from milk10k_effb2_metadata.models import (
|
| 16 |
+
DualEffB2MetadataClassifier,
|
| 17 |
+
is_one_encoder_image_fusion,
|
| 18 |
+
model_class_for_backbone,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_model_state_compat(model: DualEffB2MetadataClassifier, state: dict[str, torch.Tensor]) -> None:
|
| 23 |
+
"""Load checkpoints created before LWS added the class_scales parameter."""
|
| 24 |
+
incompatible = model.load_state_dict(state, strict=False)
|
| 25 |
+
missing = set(incompatible.missing_keys)
|
| 26 |
+
unexpected = set(incompatible.unexpected_keys)
|
| 27 |
+
allowed_missing = {"class_scales"}
|
| 28 |
+
if missing - allowed_missing or unexpected:
|
| 29 |
+
raise RuntimeError(
|
| 30 |
+
f"Checkpoint state mismatch: missing={sorted(missing)}, unexpected={sorted(unexpected)}"
|
| 31 |
+
)
|
| 32 |
+
if "class_scales" in missing:
|
| 33 |
+
model.class_scales.data.fill_(1.0)
|
| 34 |
|
| 35 |
|
| 36 |
def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefix: str) -> str:
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
def resolve_training_backbone_backends(args: argparse.Namespace, device: torch.device) -> tuple[str, str]:
|
| 52 |
+
image_fusion = getattr(args, "image_fusion", "concat")
|
| 53 |
+
if is_one_encoder_image_fusion(image_fusion):
|
| 54 |
+
if args.backbone_backend != "auto":
|
| 55 |
+
return args.backbone_backend, args.backbone_backend
|
| 56 |
+
if args.resume_checkpoint is not None:
|
| 57 |
+
checkpoint = torch.load(args.resume_checkpoint.expanduser().resolve(), map_location=device, weights_only=False)
|
| 58 |
+
state = checkpoint["model_state"]
|
| 59 |
+
backend = infer_branch_backend_from_state(state, "shared_encoder.")
|
| 60 |
+
checkpoint_args = checkpoint.get("args", {})
|
| 61 |
+
if checkpoint_args.get("backbone") and args.backbone == "efficientnet_b2":
|
| 62 |
+
args.backbone = checkpoint_args["backbone"]
|
| 63 |
+
print(f"Auto-detected resume shared backend: shared={backend}")
|
| 64 |
+
return backend, backend
|
| 65 |
+
print("One-encoder image fusion: using timm backbone initialized from ImageNet weights.")
|
| 66 |
+
return "timm", "timm"
|
| 67 |
if args.backbone_backend != "auto":
|
| 68 |
return args.backbone_backend, args.backbone_backend
|
| 69 |
if args.clinical_checkpoint is not None and args.dermoscopic_checkpoint is not None:
|
|
|
|
| 107 |
for name, param in model.named_parameters():
|
| 108 |
if not param.requires_grad:
|
| 109 |
continue
|
| 110 |
+
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.", "shared_encoder.")):
|
| 111 |
encoder_params.append(param)
|
| 112 |
+
elif name.startswith(
|
| 113 |
+
(
|
| 114 |
+
"metadata_head.",
|
| 115 |
+
"clinical_metadata_gate.",
|
| 116 |
+
"dermoscopic_metadata_gate.",
|
| 117 |
+
"shared_metadata_gate.",
|
| 118 |
+
)
|
| 119 |
+
):
|
| 120 |
metadata_params.append(param)
|
| 121 |
else:
|
| 122 |
head_params.append(param)
|
|
|
|
| 132 |
def set_metadata_head_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 133 |
for param in model.metadata_head.parameters():
|
| 134 |
param.requires_grad = trainable
|
| 135 |
+
for module_name in ("clinical_metadata_gate", "dermoscopic_metadata_gate", "shared_metadata_gate"):
|
| 136 |
module = getattr(model, module_name, None)
|
| 137 |
if module is not None:
|
| 138 |
for param in module.parameters():
|
|
|
|
| 143 |
checkpoint_path: Path | None,
|
| 144 |
model: DualEffB2MetadataClassifier,
|
| 145 |
device: torch.device,
|
| 146 |
+
ema_model: torch.nn.Module | None = None,
|
| 147 |
) -> tuple[int, float, str | None]:
|
| 148 |
if checkpoint_path is None:
|
| 149 |
return 1, float("-inf"), None
|
|
|
|
| 151 |
if not checkpoint_path.exists():
|
| 152 |
raise FileNotFoundError(f"Resume checkpoint not found: {checkpoint_path}")
|
| 153 |
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 154 |
+
load_model_state_compat(model, checkpoint["model_state"])
|
| 155 |
+
if ema_model is not None and "ema_model_state" in checkpoint:
|
| 156 |
+
ema_model.load_state_dict(checkpoint["ema_model_state"])
|
| 157 |
next_epoch = int(checkpoint.get("epoch", 0)) + 1
|
| 158 |
best_val_f1 = float(
|
| 159 |
checkpoint.get(
|
|
|
|
| 195 |
metadata_fusion=args.metadata_fusion,
|
| 196 |
image_fusion=getattr(args, "image_fusion", "concat"),
|
| 197 |
metadata_gate_hidden_dim=args.metadata_gate_hidden_dim,
|
| 198 |
+
classifier_style=getattr(args, "classifier_style", "legacy"),
|
| 199 |
logit_fusion_mode=args.logit_fusion_mode,
|
| 200 |
fusion_logit_weight=args.fusion_logit_weight,
|
| 201 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 202 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 203 |
).to(device)
|
| 204 |
+
if args.resume_checkpoint is None and not is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 205 |
if args.clinical_checkpoint is not None:
|
| 206 |
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 207 |
if args.dermoscopic_checkpoint is not None:
|
milk10k_effb2_metadata/milk10k_effb2_metadata/models.py
CHANGED
|
@@ -7,6 +7,12 @@ import torch
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from torch import nn
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
class ProjectionHead(nn.Module):
|
| 12 |
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
|
@@ -107,6 +113,7 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 107 |
metadata_fusion: str = "concat",
|
| 108 |
image_fusion: str = "concat",
|
| 109 |
metadata_gate_hidden_dim: int | None = None,
|
|
|
|
| 110 |
logit_fusion_mode: str = "single",
|
| 111 |
fusion_logit_weight: float = 0.6,
|
| 112 |
clinical_logit_weight: float = 0.2,
|
|
@@ -124,10 +131,15 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 124 |
"adaptive_gate",
|
| 125 |
"moe",
|
| 126 |
"shared_private",
|
|
|
|
| 127 |
):
|
| 128 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 129 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 130 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
self.clinical_backbone_backend = clinical_backbone_backend
|
| 132 |
self.dermoscopic_backbone_backend = dermoscopic_backbone_backend
|
| 133 |
self.backbone = normalize_backbone_name(backbone)
|
|
@@ -135,38 +147,61 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 135 |
self.metadata_dim = metadata_dim
|
| 136 |
self.metadata_fusion = metadata_fusion
|
| 137 |
self.image_fusion = image_fusion
|
|
|
|
| 138 |
self.logit_fusion_mode = logit_fusion_mode
|
| 139 |
self.fusion_logit_weight = fusion_logit_weight
|
| 140 |
self.clinical_logit_weight = clinical_logit_weight
|
| 141 |
self.dermoscopic_logit_weight = dermoscopic_logit_weight
|
| 142 |
-
self.
|
| 143 |
-
|
| 144 |
-
clinical_backbone_backend
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
self.clinical_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 154 |
self.dermoscopic_head = ProjectionHead(dermoscopic_feature_dim, branch_dim, dropout)
|
|
|
|
|
|
|
| 155 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 156 |
if metadata_fusion in ("gated_concat", "gated_only"):
|
| 157 |
gate_hidden_dim = metadata_gate_hidden_dim if metadata_gate_hidden_dim is not None else metadata_dim
|
| 158 |
-
self.
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
metadata_output_dim = 0 if metadata_fusion == "gated_only" else metadata_dim
|
| 171 |
fused_dim = self._fusion_dim(branch_dim, metadata_output_dim, image_fusion)
|
| 172 |
heads = 4 if branch_dim % 4 == 0 else 1
|
|
@@ -212,16 +247,37 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 212 |
if clinical_feature_dim != dermoscopic_feature_dim:
|
| 213 |
raise ValueError("shared_private image fusion requires matching branch feature dimensions.")
|
| 214 |
self.shared_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 215 |
-
self.classifier =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
if logit_fusion_mode == "fixed":
|
| 217 |
self.clinical_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 218 |
self.dermoscopic_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 219 |
else:
|
| 220 |
self.clinical_classifier = None
|
| 221 |
self.dermoscopic_classifier = None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
@staticmethod
|
| 224 |
-
def _classifier(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return nn.Sequential(
|
| 226 |
nn.LayerNorm(in_dim),
|
| 227 |
nn.Dropout(dropout),
|
|
@@ -235,8 +291,16 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 235 |
def _fusion_dim(branch_dim: int, metadata_dim: int, image_fusion: str) -> int:
|
| 236 |
if image_fusion in ("concat", "cross_attention"):
|
| 237 |
image_dim = branch_dim * 2
|
| 238 |
-
elif image_fusion in (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
image_dim = branch_dim * 3
|
|
|
|
|
|
|
| 240 |
elif image_fusion == "co_attention":
|
| 241 |
image_dim = branch_dim * 4
|
| 242 |
elif image_fusion == "moe":
|
|
@@ -251,6 +315,10 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 251 |
dermoscopic: torch.Tensor,
|
| 252 |
metadata: torch.Tensor,
|
| 253 |
) -> torch.Tensor:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 255 |
clinical_features = self.encode_with_metadata_gate(
|
| 256 |
self.clinical_encoder,
|
|
@@ -287,14 +355,64 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 287 |
fused = self._fused_features(clinical_features, dermoscopic_features, clinical_repr, dermoscopic_repr, metadata_repr)
|
| 288 |
fusion_logits = self.classifier(fused)
|
| 289 |
if self.logit_fusion_mode != "fixed":
|
| 290 |
-
return fusion_logits
|
| 291 |
clinical_logits = self.clinical_classifier(clinical_repr)
|
| 292 |
dermoscopic_logits = self.dermoscopic_classifier(dermoscopic_repr)
|
| 293 |
return (
|
| 294 |
self.fusion_logit_weight * fusion_logits
|
| 295 |
+ self.clinical_logit_weight * clinical_logits
|
| 296 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 297 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 300 |
if metadata_repr is None:
|
|
@@ -401,6 +519,8 @@ class DualConvNeXtMetadataClassifier(DualEffB2MetadataClassifier):
|
|
| 401 |
|
| 402 |
def normalize_backbone_name(name: str) -> str:
|
| 403 |
name = name.lower().replace(" ", "").replace("_", "").replace("-", "")
|
|
|
|
|
|
|
| 404 |
if name in ("efficientnetb2", "effnetb2", "effb2"):
|
| 405 |
return "efficientnet_b2"
|
| 406 |
if name in ("efficientnetb1", "effnetb1", "effb1"):
|
|
@@ -425,6 +545,8 @@ def default_image_size(backbone: str) -> int:
|
|
| 425 |
backbone = normalize_backbone_name(backbone)
|
| 426 |
if backbone == "efficientnet_b2":
|
| 427 |
return 260
|
|
|
|
|
|
|
| 428 |
if backbone == "efficientnet_b1":
|
| 429 |
return 240
|
| 430 |
if backbone == "convnext_base":
|
|
@@ -478,6 +600,8 @@ def build_feature_encoder(backbone: str, backbone_backend: str, imagenet_pretrai
|
|
| 478 |
return model, int(model.num_features)
|
| 479 |
|
| 480 |
if backbone_backend == "torchvision":
|
|
|
|
|
|
|
| 481 |
if backbone == "efficientnet_b2":
|
| 482 |
from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
|
| 483 |
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
|
@@ -513,6 +637,10 @@ def build_feature_encoder(backbone: str, backbone_backend: str, imagenet_pretrai
|
|
| 513 |
|
| 514 |
|
| 515 |
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
for param in model.clinical_encoder.parameters():
|
| 517 |
param.requires_grad = trainable
|
| 518 |
for param in model.dermoscopic_encoder.parameters():
|
|
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from torch import nn
|
| 9 |
|
| 10 |
+
ONE_ENCODER_IMAGE_FUSIONS = ("single_encoder_canvas", "shared_encoder_pool")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def is_one_encoder_image_fusion(image_fusion: str) -> bool:
|
| 14 |
+
return image_fusion in ONE_ENCODER_IMAGE_FUSIONS
|
| 15 |
+
|
| 16 |
|
| 17 |
class ProjectionHead(nn.Module):
|
| 18 |
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
|
|
|
| 113 |
metadata_fusion: str = "concat",
|
| 114 |
image_fusion: str = "concat",
|
| 115 |
metadata_gate_hidden_dim: int | None = None,
|
| 116 |
+
classifier_style: str = "legacy",
|
| 117 |
logit_fusion_mode: str = "single",
|
| 118 |
fusion_logit_weight: float = 0.6,
|
| 119 |
clinical_logit_weight: float = 0.2,
|
|
|
|
| 131 |
"adaptive_gate",
|
| 132 |
"moe",
|
| 133 |
"shared_private",
|
| 134 |
+
*ONE_ENCODER_IMAGE_FUSIONS,
|
| 135 |
):
|
| 136 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 137 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 138 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
| 139 |
+
if is_one_encoder_image_fusion(image_fusion) and logit_fusion_mode != "single":
|
| 140 |
+
raise ValueError(f"{image_fusion} supports only --logit-fusion-mode single.")
|
| 141 |
+
if classifier_style not in ("legacy", "simple"):
|
| 142 |
+
raise ValueError(f"Unsupported classifier_style: {classifier_style}")
|
| 143 |
self.clinical_backbone_backend = clinical_backbone_backend
|
| 144 |
self.dermoscopic_backbone_backend = dermoscopic_backbone_backend
|
| 145 |
self.backbone = normalize_backbone_name(backbone)
|
|
|
|
| 147 |
self.metadata_dim = metadata_dim
|
| 148 |
self.metadata_fusion = metadata_fusion
|
| 149 |
self.image_fusion = image_fusion
|
| 150 |
+
self.classifier_style = classifier_style
|
| 151 |
self.logit_fusion_mode = logit_fusion_mode
|
| 152 |
self.fusion_logit_weight = fusion_logit_weight
|
| 153 |
self.clinical_logit_weight = clinical_logit_weight
|
| 154 |
self.dermoscopic_logit_weight = dermoscopic_logit_weight
|
| 155 |
+
self.one_encoder = is_one_encoder_image_fusion(image_fusion)
|
| 156 |
+
if self.one_encoder:
|
| 157 |
+
if clinical_backbone_backend != dermoscopic_backbone_backend:
|
| 158 |
+
raise ValueError(f"{image_fusion} requires one shared backend, got different branch backends.")
|
| 159 |
+
self.shared_encoder, shared_feature_dim = build_feature_encoder(
|
| 160 |
+
backbone,
|
| 161 |
+
clinical_backbone_backend,
|
| 162 |
+
imagenet_pretrained,
|
| 163 |
+
)
|
| 164 |
+
clinical_feature_dim = shared_feature_dim
|
| 165 |
+
dermoscopic_feature_dim = shared_feature_dim
|
| 166 |
+
else:
|
| 167 |
+
self.clinical_encoder, clinical_feature_dim = build_feature_encoder(
|
| 168 |
+
backbone,
|
| 169 |
+
clinical_backbone_backend,
|
| 170 |
+
imagenet_pretrained,
|
| 171 |
+
)
|
| 172 |
+
self.dermoscopic_encoder, dermoscopic_feature_dim = build_feature_encoder(
|
| 173 |
+
backbone,
|
| 174 |
+
dermoscopic_backbone_backend,
|
| 175 |
+
imagenet_pretrained,
|
| 176 |
+
)
|
| 177 |
|
| 178 |
self.clinical_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 179 |
self.dermoscopic_head = ProjectionHead(dermoscopic_feature_dim, branch_dim, dropout)
|
| 180 |
+
if self.one_encoder:
|
| 181 |
+
self.shared_head = ProjectionHead(shared_feature_dim, branch_dim, dropout)
|
| 182 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 183 |
if metadata_fusion in ("gated_concat", "gated_only"):
|
| 184 |
gate_hidden_dim = metadata_gate_hidden_dim if metadata_gate_hidden_dim is not None else metadata_dim
|
| 185 |
+
if self.one_encoder:
|
| 186 |
+
self.shared_metadata_gate = MetadataChannelGate(
|
| 187 |
+
metadata_input_dim,
|
| 188 |
+
shared_feature_dim,
|
| 189 |
+
gate_hidden_dim,
|
| 190 |
+
dropout,
|
| 191 |
+
)
|
| 192 |
+
else:
|
| 193 |
+
self.clinical_metadata_gate = MetadataChannelGate(
|
| 194 |
+
metadata_input_dim,
|
| 195 |
+
clinical_feature_dim,
|
| 196 |
+
gate_hidden_dim,
|
| 197 |
+
dropout,
|
| 198 |
+
)
|
| 199 |
+
self.dermoscopic_metadata_gate = MetadataChannelGate(
|
| 200 |
+
metadata_input_dim,
|
| 201 |
+
dermoscopic_feature_dim,
|
| 202 |
+
gate_hidden_dim,
|
| 203 |
+
dropout,
|
| 204 |
+
)
|
| 205 |
metadata_output_dim = 0 if metadata_fusion == "gated_only" else metadata_dim
|
| 206 |
fused_dim = self._fusion_dim(branch_dim, metadata_output_dim, image_fusion)
|
| 207 |
heads = 4 if branch_dim % 4 == 0 else 1
|
|
|
|
| 247 |
if clinical_feature_dim != dermoscopic_feature_dim:
|
| 248 |
raise ValueError("shared_private image fusion requires matching branch feature dimensions.")
|
| 249 |
self.shared_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 250 |
+
self.classifier = (
|
| 251 |
+
None
|
| 252 |
+
if image_fusion == "moe"
|
| 253 |
+
else self._classifier(fused_dim, classifier_hidden_dim, num_classes, dropout, classifier_style)
|
| 254 |
+
)
|
| 255 |
if logit_fusion_mode == "fixed":
|
| 256 |
self.clinical_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 257 |
self.dermoscopic_classifier = BranchClassifier(branch_dim, num_classes, dropout)
|
| 258 |
else:
|
| 259 |
self.clinical_classifier = None
|
| 260 |
self.dermoscopic_classifier = None
|
| 261 |
+
|
| 262 |
+
# LWS is a post-training stage. Keep scales frozen during normal
|
| 263 |
+
# representation/classifier training and enable them explicitly later.
|
| 264 |
+
self.class_scales = nn.Parameter(torch.ones(num_classes), requires_grad=False)
|
| 265 |
|
| 266 |
@staticmethod
|
| 267 |
+
def _classifier(
|
| 268 |
+
in_dim: int,
|
| 269 |
+
hidden_dim: int,
|
| 270 |
+
num_classes: int,
|
| 271 |
+
dropout: float,
|
| 272 |
+
classifier_style: str,
|
| 273 |
+
) -> nn.Sequential:
|
| 274 |
+
if classifier_style == "simple":
|
| 275 |
+
return nn.Sequential(
|
| 276 |
+
nn.Linear(in_dim, hidden_dim),
|
| 277 |
+
nn.ReLU(),
|
| 278 |
+
nn.Dropout(dropout),
|
| 279 |
+
nn.Linear(hidden_dim, num_classes),
|
| 280 |
+
)
|
| 281 |
return nn.Sequential(
|
| 282 |
nn.LayerNorm(in_dim),
|
| 283 |
nn.Dropout(dropout),
|
|
|
|
| 291 |
def _fusion_dim(branch_dim: int, metadata_dim: int, image_fusion: str) -> int:
|
| 292 |
if image_fusion in ("concat", "cross_attention"):
|
| 293 |
image_dim = branch_dim * 2
|
| 294 |
+
elif image_fusion in (
|
| 295 |
+
"compact_bilinear",
|
| 296 |
+
"low_rank_bilinear",
|
| 297 |
+
"adaptive_gate",
|
| 298 |
+
"shared_private",
|
| 299 |
+
"shared_encoder_pool",
|
| 300 |
+
):
|
| 301 |
image_dim = branch_dim * 3
|
| 302 |
+
elif image_fusion == "single_encoder_canvas":
|
| 303 |
+
image_dim = branch_dim
|
| 304 |
elif image_fusion == "co_attention":
|
| 305 |
image_dim = branch_dim * 4
|
| 306 |
elif image_fusion == "moe":
|
|
|
|
| 315 |
dermoscopic: torch.Tensor,
|
| 316 |
metadata: torch.Tensor,
|
| 317 |
) -> torch.Tensor:
|
| 318 |
+
if self.one_encoder:
|
| 319 |
+
fusion_logits = self._one_encoder_logits(clinical, dermoscopic, metadata)
|
| 320 |
+
return fusion_logits * self.class_scales
|
| 321 |
+
|
| 322 |
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 323 |
clinical_features = self.encode_with_metadata_gate(
|
| 324 |
self.clinical_encoder,
|
|
|
|
| 355 |
fused = self._fused_features(clinical_features, dermoscopic_features, clinical_repr, dermoscopic_repr, metadata_repr)
|
| 356 |
fusion_logits = self.classifier(fused)
|
| 357 |
if self.logit_fusion_mode != "fixed":
|
| 358 |
+
return fusion_logits * self.class_scales
|
| 359 |
clinical_logits = self.clinical_classifier(clinical_repr)
|
| 360 |
dermoscopic_logits = self.dermoscopic_classifier(dermoscopic_repr)
|
| 361 |
return (
|
| 362 |
self.fusion_logit_weight * fusion_logits
|
| 363 |
+ self.clinical_logit_weight * clinical_logits
|
| 364 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 365 |
+
) * self.class_scales
|
| 366 |
+
|
| 367 |
+
def _one_encoder_logits(
|
| 368 |
+
self,
|
| 369 |
+
clinical: torch.Tensor,
|
| 370 |
+
dermoscopic: torch.Tensor,
|
| 371 |
+
metadata: torch.Tensor,
|
| 372 |
+
) -> torch.Tensor:
|
| 373 |
+
if self.image_fusion == "single_encoder_canvas":
|
| 374 |
+
combined = torch.cat([clinical, dermoscopic], dim=-1)
|
| 375 |
+
features = self._encode_shared(combined, metadata)
|
| 376 |
+
repr_ = self.shared_head(features)
|
| 377 |
+
fused_image = repr_
|
| 378 |
+
elif self.image_fusion == "shared_encoder_pool":
|
| 379 |
+
clinical_features = self._encode_shared(clinical, metadata)
|
| 380 |
+
dermoscopic_features = self._encode_shared(dermoscopic, metadata)
|
| 381 |
+
clinical_repr = self.shared_head(clinical_features)
|
| 382 |
+
dermoscopic_repr = self.shared_head(dermoscopic_features)
|
| 383 |
+
fused_image = torch.cat(
|
| 384 |
+
[
|
| 385 |
+
0.5 * (clinical_repr + dermoscopic_repr),
|
| 386 |
+
torch.abs(clinical_repr - dermoscopic_repr),
|
| 387 |
+
clinical_repr * dermoscopic_repr,
|
| 388 |
+
],
|
| 389 |
+
dim=1,
|
| 390 |
+
)
|
| 391 |
+
else:
|
| 392 |
+
raise ValueError(f"Unsupported one-encoder image_fusion: {self.image_fusion}")
|
| 393 |
+
|
| 394 |
+
metadata_repr = self._metadata_repr(fused_image, metadata)
|
| 395 |
+
return self.classifier(self._append_metadata(fused_image, metadata_repr))
|
| 396 |
+
|
| 397 |
+
def _encode_shared(self, images: torch.Tensor, metadata: torch.Tensor) -> torch.Tensor:
|
| 398 |
+
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 399 |
+
features = self.encode_with_metadata_gate(
|
| 400 |
+
self.shared_encoder,
|
| 401 |
+
self.clinical_backbone_backend,
|
| 402 |
+
images,
|
| 403 |
+
metadata,
|
| 404 |
+
self.shared_metadata_gate,
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
features = self.shared_encoder(images)
|
| 408 |
+
return torch.flatten(features, 1)
|
| 409 |
+
|
| 410 |
+
def _metadata_repr(self, image_repr: torch.Tensor, metadata: torch.Tensor) -> torch.Tensor | None:
|
| 411 |
+
if self.metadata_fusion == "gated_only":
|
| 412 |
+
return None
|
| 413 |
+
if self.disable_metadata:
|
| 414 |
+
return image_repr.new_zeros((image_repr.size(0), self.metadata_dim))
|
| 415 |
+
return self.metadata_head(metadata)
|
| 416 |
|
| 417 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 418 |
if metadata_repr is None:
|
|
|
|
| 519 |
|
| 520 |
def normalize_backbone_name(name: str) -> str:
|
| 521 |
name = name.lower().replace(" ", "").replace("_", "").replace("-", "")
|
| 522 |
+
if name in ("tfefficientnetv2b2", "efficientnetv2b2", "effnetv2b2", "effv2b2"):
|
| 523 |
+
return "tf_efficientnetv2_b2"
|
| 524 |
if name in ("efficientnetb2", "effnetb2", "effb2"):
|
| 525 |
return "efficientnet_b2"
|
| 526 |
if name in ("efficientnetb1", "effnetb1", "effb1"):
|
|
|
|
| 545 |
backbone = normalize_backbone_name(backbone)
|
| 546 |
if backbone == "efficientnet_b2":
|
| 547 |
return 260
|
| 548 |
+
if backbone == "tf_efficientnetv2_b2":
|
| 549 |
+
return 384
|
| 550 |
if backbone == "efficientnet_b1":
|
| 551 |
return 240
|
| 552 |
if backbone == "convnext_base":
|
|
|
|
| 600 |
return model, int(model.num_features)
|
| 601 |
|
| 602 |
if backbone_backend == "torchvision":
|
| 603 |
+
if backbone == "tf_efficientnetv2_b2":
|
| 604 |
+
raise ValueError("tf_efficientnetv2_b2 is only available with --backbone-backend timm.")
|
| 605 |
if backbone == "efficientnet_b2":
|
| 606 |
from torchvision.models import efficientnet_b2, EfficientNet_B2_Weights
|
| 607 |
weights = EfficientNet_B2_Weights.IMAGENET1K_V1 if imagenet_pretrained else None
|
|
|
|
| 637 |
|
| 638 |
|
| 639 |
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 640 |
+
if getattr(model, "one_encoder", False):
|
| 641 |
+
for param in model.shared_encoder.parameters():
|
| 642 |
+
param.requires_grad = trainable
|
| 643 |
+
return
|
| 644 |
for param in model.clinical_encoder.parameters():
|
| 645 |
param.requires_grad = trainable
|
| 646 |
for param in model.dermoscopic_encoder.parameters():
|
milk10k_effb2_metadata/milk10k_effb2_metadata/training.py
CHANGED
|
@@ -7,17 +7,58 @@ import argparse
|
|
| 7 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def run(args: argparse.Namespace) -> None:
|
| 11 |
import torch
|
| 12 |
|
| 13 |
from datasets import resolve_data_dir, set_seed
|
| 14 |
-
from milk10k_effb2_metadata.data import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 16 |
-
from milk10k_effb2_metadata.models import normalize_backbone_name, resolve_image_size
|
| 17 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 18 |
|
| 19 |
if args.k_folds < 1:
|
| 20 |
raise ValueError("--k-folds must be at least 1.")
|
|
|
|
| 21 |
|
| 22 |
set_seed(args.seed)
|
| 23 |
data_dir = resolve_data_dir(args.data_dir)
|
|
@@ -26,11 +67,28 @@ def run(args: argparse.Namespace) -> None:
|
|
| 26 |
args.backbone = normalize_backbone_name(args.backbone)
|
| 27 |
if args.metadata_gate_hidden_dim is None:
|
| 28 |
args.metadata_gate_hidden_dim = args.metadata_dim
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
if args.resume_checkpoint is None and args.clinical_checkpoint is None and args.dermoscopic_checkpoint is None:
|
| 30 |
args.imagenet_pretrained = True
|
| 31 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
| 32 |
|
| 33 |
df = load_paired_dataframe(data_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class_names = sorted(df["label"].unique())
|
| 35 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 36 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 7 |
from milk10k_effb2_metadata.training_utils import json_safe
|
| 8 |
|
| 9 |
|
| 10 |
+
def validate_balance_args(args: argparse.Namespace) -> None:
|
| 11 |
+
if args.balance_mode == "hybrid" and args.weighted_sampler:
|
| 12 |
+
raise ValueError("--balance-mode hybrid cannot be combined with --weighted-sampler.")
|
| 13 |
+
if args.balance_head_ratio <= 0:
|
| 14 |
+
raise ValueError("--balance-head-ratio must be greater than 0.")
|
| 15 |
+
if args.balance_tail_floor < 0:
|
| 16 |
+
raise ValueError("--balance-tail-floor must be >= 0.")
|
| 17 |
+
if args.balance_min_source_count < 1:
|
| 18 |
+
raise ValueError("--balance-min-source-count must be at least 1.")
|
| 19 |
+
tau = float(getattr(args, "tau", 0.0))
|
| 20 |
+
class_weight = bool(getattr(args, "class_weight", False))
|
| 21 |
+
loss = str(getattr(args, "loss", "ce"))
|
| 22 |
+
lws_epochs = int(getattr(args, "lws_epochs", 0))
|
| 23 |
+
lws_lr = float(getattr(args, "lws_lr", 1e-2))
|
| 24 |
+
lws_sampler_power = float(getattr(args, "lws_sampler_power", 0.5))
|
| 25 |
+
lws_min_scale = float(getattr(args, "lws_min_scale", 0.75))
|
| 26 |
+
lws_max_scale = float(getattr(args, "lws_max_scale", 1.5))
|
| 27 |
+
ema_decay = float(getattr(args, "ema_decay", 0.999))
|
| 28 |
+
if not 0.0 <= tau <= 0.5:
|
| 29 |
+
raise ValueError("--tau must be between 0.0 and 0.5.")
|
| 30 |
+
if tau > 0.0 and class_weight:
|
| 31 |
+
raise ValueError("--tau > 0 cannot be combined with --class-weight.")
|
| 32 |
+
if tau > 0.0 and loss in {"focal", "ldam"}:
|
| 33 |
+
raise ValueError("--tau > 0 requires a CE-based loss (ce, ce_dice, or ce_f1).")
|
| 34 |
+
if lws_epochs < 0:
|
| 35 |
+
raise ValueError("--lws-epochs must be >= 0.")
|
| 36 |
+
if lws_lr <= 0.0:
|
| 37 |
+
raise ValueError("--lws-lr must be > 0.")
|
| 38 |
+
if not 0.0 <= lws_sampler_power <= 1.0:
|
| 39 |
+
raise ValueError("--lws-sampler-power must be between 0.0 and 1.0.")
|
| 40 |
+
if lws_min_scale <= 0.0 or lws_max_scale < lws_min_scale:
|
| 41 |
+
raise ValueError("LWS scale bounds must satisfy 0 < min <= max.")
|
| 42 |
+
if not 0.0 < ema_decay < 1.0:
|
| 43 |
+
raise ValueError("--ema-decay must be between 0 and 1.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
def run(args: argparse.Namespace) -> None:
|
| 47 |
import torch
|
| 48 |
|
| 49 |
from datasets import resolve_data_dir, set_seed
|
| 50 |
+
from milk10k_effb2_metadata.data import (
|
| 51 |
+
audit_dermoscopic_masks,
|
| 52 |
+
load_paired_dataframe,
|
| 53 |
+
print_mask_audit_summary,
|
| 54 |
+
)
|
| 55 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 56 |
+
from milk10k_effb2_metadata.models import is_one_encoder_image_fusion, normalize_backbone_name, resolve_image_size
|
| 57 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 58 |
|
| 59 |
if args.k_folds < 1:
|
| 60 |
raise ValueError("--k-folds must be at least 1.")
|
| 61 |
+
validate_balance_args(args)
|
| 62 |
|
| 63 |
set_seed(args.seed)
|
| 64 |
data_dir = resolve_data_dir(args.data_dir)
|
|
|
|
| 67 |
args.backbone = normalize_backbone_name(args.backbone)
|
| 68 |
if args.metadata_gate_hidden_dim is None:
|
| 69 |
args.metadata_gate_hidden_dim = args.metadata_dim
|
| 70 |
+
if is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 71 |
+
if args.clinical_checkpoint is not None or args.dermoscopic_checkpoint is not None:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"--image-fusion {args.image_fusion} uses one ImageNet-initialized encoder; "
|
| 74 |
+
"do not pass --clinical-checkpoint or --dermoscopic-checkpoint."
|
| 75 |
+
)
|
| 76 |
if args.resume_checkpoint is None and args.clinical_checkpoint is None and args.dermoscopic_checkpoint is None:
|
| 77 |
args.imagenet_pretrained = True
|
| 78 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
| 79 |
|
| 80 |
df = load_paired_dataframe(data_dir)
|
| 81 |
+
if not 0.0 <= args.min_dermoscopic_mask_ratio <= 1.0:
|
| 82 |
+
raise ValueError("--min-dermoscopic-mask-ratio must be between 0 and 1.")
|
| 83 |
+
if args.dermoscopic_mask_dir is not None:
|
| 84 |
+
args.dermoscopic_mask_dir = args.dermoscopic_mask_dir.expanduser().resolve()
|
| 85 |
+
df, mask_audit = audit_dermoscopic_masks(
|
| 86 |
+
df,
|
| 87 |
+
args.dermoscopic_mask_dir,
|
| 88 |
+
args.min_dermoscopic_mask_ratio,
|
| 89 |
+
)
|
| 90 |
+
mask_audit.to_csv(args.output_dir / "dermoscopic_mask_audit.csv", index=False)
|
| 91 |
+
print_mask_audit_summary(mask_audit, args.min_dermoscopic_mask_ratio)
|
| 92 |
class_names = sorted(df["label"].unique())
|
| 93 |
label_to_idx = {label: idx for idx, label in enumerate(class_names)}
|
| 94 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
milk10k_effb2_metadata/model_setup.py
CHANGED
|
@@ -12,7 +12,11 @@ from milk10k_effb2_metadata.checkpoints import (
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
| 15 |
-
from milk10k_effb2_metadata.models import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def load_model_state_compat(model: DualEffB2MetadataClassifier, state: dict[str, torch.Tensor]) -> None:
|
|
@@ -45,6 +49,21 @@ def infer_branch_backend_from_state(state: dict[str, torch.Tensor], branch_prefi
|
|
| 45 |
|
| 46 |
|
| 47 |
def resolve_training_backbone_backends(args: argparse.Namespace, device: torch.device) -> tuple[str, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if args.backbone_backend != "auto":
|
| 49 |
return args.backbone_backend, args.backbone_backend
|
| 50 |
if args.clinical_checkpoint is not None and args.dermoscopic_checkpoint is not None:
|
|
@@ -88,9 +107,16 @@ def build_optimizer(
|
|
| 88 |
for name, param in model.named_parameters():
|
| 89 |
if not param.requires_grad:
|
| 90 |
continue
|
| 91 |
-
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.")):
|
| 92 |
encoder_params.append(param)
|
| 93 |
-
elif name.startswith(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
metadata_params.append(param)
|
| 95 |
else:
|
| 96 |
head_params.append(param)
|
|
@@ -106,7 +132,7 @@ def build_optimizer(
|
|
| 106 |
def set_metadata_head_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 107 |
for param in model.metadata_head.parameters():
|
| 108 |
param.requires_grad = trainable
|
| 109 |
-
for module_name in ("clinical_metadata_gate", "dermoscopic_metadata_gate"):
|
| 110 |
module = getattr(model, module_name, None)
|
| 111 |
if module is not None:
|
| 112 |
for param in module.parameters():
|
|
@@ -175,7 +201,7 @@ def build_model(
|
|
| 175 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 176 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 177 |
).to(device)
|
| 178 |
-
if args.resume_checkpoint is None:
|
| 179 |
if args.clinical_checkpoint is not None:
|
| 180 |
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 181 |
if args.dermoscopic_checkpoint is not None:
|
|
|
|
| 12 |
load_encoder_checkpoint,
|
| 13 |
resolve_backbone_backends,
|
| 14 |
)
|
| 15 |
+
from milk10k_effb2_metadata.models import (
|
| 16 |
+
DualEffB2MetadataClassifier,
|
| 17 |
+
is_one_encoder_image_fusion,
|
| 18 |
+
model_class_for_backbone,
|
| 19 |
+
)
|
| 20 |
|
| 21 |
|
| 22 |
def load_model_state_compat(model: DualEffB2MetadataClassifier, state: dict[str, torch.Tensor]) -> None:
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
def resolve_training_backbone_backends(args: argparse.Namespace, device: torch.device) -> tuple[str, str]:
|
| 52 |
+
image_fusion = getattr(args, "image_fusion", "concat")
|
| 53 |
+
if is_one_encoder_image_fusion(image_fusion):
|
| 54 |
+
if args.backbone_backend != "auto":
|
| 55 |
+
return args.backbone_backend, args.backbone_backend
|
| 56 |
+
if args.resume_checkpoint is not None:
|
| 57 |
+
checkpoint = torch.load(args.resume_checkpoint.expanduser().resolve(), map_location=device, weights_only=False)
|
| 58 |
+
state = checkpoint["model_state"]
|
| 59 |
+
backend = infer_branch_backend_from_state(state, "shared_encoder.")
|
| 60 |
+
checkpoint_args = checkpoint.get("args", {})
|
| 61 |
+
if checkpoint_args.get("backbone") and args.backbone == "efficientnet_b2":
|
| 62 |
+
args.backbone = checkpoint_args["backbone"]
|
| 63 |
+
print(f"Auto-detected resume shared backend: shared={backend}")
|
| 64 |
+
return backend, backend
|
| 65 |
+
print("One-encoder image fusion: using timm backbone initialized from ImageNet weights.")
|
| 66 |
+
return "timm", "timm"
|
| 67 |
if args.backbone_backend != "auto":
|
| 68 |
return args.backbone_backend, args.backbone_backend
|
| 69 |
if args.clinical_checkpoint is not None and args.dermoscopic_checkpoint is not None:
|
|
|
|
| 107 |
for name, param in model.named_parameters():
|
| 108 |
if not param.requires_grad:
|
| 109 |
continue
|
| 110 |
+
if name.startswith(("clinical_encoder.", "dermoscopic_encoder.", "shared_encoder.")):
|
| 111 |
encoder_params.append(param)
|
| 112 |
+
elif name.startswith(
|
| 113 |
+
(
|
| 114 |
+
"metadata_head.",
|
| 115 |
+
"clinical_metadata_gate.",
|
| 116 |
+
"dermoscopic_metadata_gate.",
|
| 117 |
+
"shared_metadata_gate.",
|
| 118 |
+
)
|
| 119 |
+
):
|
| 120 |
metadata_params.append(param)
|
| 121 |
else:
|
| 122 |
head_params.append(param)
|
|
|
|
| 132 |
def set_metadata_head_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 133 |
for param in model.metadata_head.parameters():
|
| 134 |
param.requires_grad = trainable
|
| 135 |
+
for module_name in ("clinical_metadata_gate", "dermoscopic_metadata_gate", "shared_metadata_gate"):
|
| 136 |
module = getattr(model, module_name, None)
|
| 137 |
if module is not None:
|
| 138 |
for param in module.parameters():
|
|
|
|
| 201 |
clinical_logit_weight=args.clinical_logit_weight,
|
| 202 |
dermoscopic_logit_weight=args.dermoscopic_logit_weight,
|
| 203 |
).to(device)
|
| 204 |
+
if args.resume_checkpoint is None and not is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 205 |
if args.clinical_checkpoint is not None:
|
| 206 |
load_encoder_checkpoint(args.clinical_checkpoint, model.clinical_encoder, "clinical", device)
|
| 207 |
if args.dermoscopic_checkpoint is not None:
|
milk10k_effb2_metadata/models.py
CHANGED
|
@@ -7,6 +7,12 @@ import torch
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from torch import nn
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
class ProjectionHead(nn.Module):
|
| 12 |
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
|
@@ -125,10 +131,13 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 125 |
"adaptive_gate",
|
| 126 |
"moe",
|
| 127 |
"shared_private",
|
|
|
|
| 128 |
):
|
| 129 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 130 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 131 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
|
|
|
|
|
|
| 132 |
if classifier_style not in ("legacy", "simple"):
|
| 133 |
raise ValueError(f"Unsupported classifier_style: {classifier_style}")
|
| 134 |
self.clinical_backbone_backend = clinical_backbone_backend
|
|
@@ -143,34 +152,56 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 143 |
self.fusion_logit_weight = fusion_logit_weight
|
| 144 |
self.clinical_logit_weight = clinical_logit_weight
|
| 145 |
self.dermoscopic_logit_weight = dermoscopic_logit_weight
|
| 146 |
-
self.
|
| 147 |
-
|
| 148 |
-
clinical_backbone_backend
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
self.clinical_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 158 |
self.dermoscopic_head = ProjectionHead(dermoscopic_feature_dim, branch_dim, dropout)
|
|
|
|
|
|
|
| 159 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 160 |
if metadata_fusion in ("gated_concat", "gated_only"):
|
| 161 |
gate_hidden_dim = metadata_gate_hidden_dim if metadata_gate_hidden_dim is not None else metadata_dim
|
| 162 |
-
self.
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
metadata_output_dim = 0 if metadata_fusion == "gated_only" else metadata_dim
|
| 175 |
fused_dim = self._fusion_dim(branch_dim, metadata_output_dim, image_fusion)
|
| 176 |
heads = 4 if branch_dim % 4 == 0 else 1
|
|
@@ -260,8 +291,16 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 260 |
def _fusion_dim(branch_dim: int, metadata_dim: int, image_fusion: str) -> int:
|
| 261 |
if image_fusion in ("concat", "cross_attention"):
|
| 262 |
image_dim = branch_dim * 2
|
| 263 |
-
elif image_fusion in (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
image_dim = branch_dim * 3
|
|
|
|
|
|
|
| 265 |
elif image_fusion == "co_attention":
|
| 266 |
image_dim = branch_dim * 4
|
| 267 |
elif image_fusion == "moe":
|
|
@@ -276,6 +315,10 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 276 |
dermoscopic: torch.Tensor,
|
| 277 |
metadata: torch.Tensor,
|
| 278 |
) -> torch.Tensor:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 280 |
clinical_features = self.encode_with_metadata_gate(
|
| 281 |
self.clinical_encoder,
|
|
@@ -321,6 +364,56 @@ class DualEffB2MetadataClassifier(nn.Module):
|
|
| 321 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 322 |
) * self.class_scales
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 325 |
if metadata_repr is None:
|
| 326 |
return features
|
|
@@ -544,6 +637,10 @@ def build_feature_encoder(backbone: str, backbone_backend: str, imagenet_pretrai
|
|
| 544 |
|
| 545 |
|
| 546 |
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
for param in model.clinical_encoder.parameters():
|
| 548 |
param.requires_grad = trainable
|
| 549 |
for param in model.dermoscopic_encoder.parameters():
|
|
|
|
| 7 |
import torch.nn.functional as F
|
| 8 |
from torch import nn
|
| 9 |
|
| 10 |
+
ONE_ENCODER_IMAGE_FUSIONS = ("single_encoder_canvas", "shared_encoder_pool")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def is_one_encoder_image_fusion(image_fusion: str) -> bool:
|
| 14 |
+
return image_fusion in ONE_ENCODER_IMAGE_FUSIONS
|
| 15 |
+
|
| 16 |
|
| 17 |
class ProjectionHead(nn.Module):
|
| 18 |
def __init__(self, in_dim: int, out_dim: int, dropout: float) -> None:
|
|
|
|
| 131 |
"adaptive_gate",
|
| 132 |
"moe",
|
| 133 |
"shared_private",
|
| 134 |
+
*ONE_ENCODER_IMAGE_FUSIONS,
|
| 135 |
):
|
| 136 |
raise ValueError(f"Unsupported image_fusion: {image_fusion}")
|
| 137 |
if logit_fusion_mode not in ("single", "fixed"):
|
| 138 |
raise ValueError(f"Unsupported logit_fusion_mode: {logit_fusion_mode}")
|
| 139 |
+
if is_one_encoder_image_fusion(image_fusion) and logit_fusion_mode != "single":
|
| 140 |
+
raise ValueError(f"{image_fusion} supports only --logit-fusion-mode single.")
|
| 141 |
if classifier_style not in ("legacy", "simple"):
|
| 142 |
raise ValueError(f"Unsupported classifier_style: {classifier_style}")
|
| 143 |
self.clinical_backbone_backend = clinical_backbone_backend
|
|
|
|
| 152 |
self.fusion_logit_weight = fusion_logit_weight
|
| 153 |
self.clinical_logit_weight = clinical_logit_weight
|
| 154 |
self.dermoscopic_logit_weight = dermoscopic_logit_weight
|
| 155 |
+
self.one_encoder = is_one_encoder_image_fusion(image_fusion)
|
| 156 |
+
if self.one_encoder:
|
| 157 |
+
if clinical_backbone_backend != dermoscopic_backbone_backend:
|
| 158 |
+
raise ValueError(f"{image_fusion} requires one shared backend, got different branch backends.")
|
| 159 |
+
self.shared_encoder, shared_feature_dim = build_feature_encoder(
|
| 160 |
+
backbone,
|
| 161 |
+
clinical_backbone_backend,
|
| 162 |
+
imagenet_pretrained,
|
| 163 |
+
)
|
| 164 |
+
clinical_feature_dim = shared_feature_dim
|
| 165 |
+
dermoscopic_feature_dim = shared_feature_dim
|
| 166 |
+
else:
|
| 167 |
+
self.clinical_encoder, clinical_feature_dim = build_feature_encoder(
|
| 168 |
+
backbone,
|
| 169 |
+
clinical_backbone_backend,
|
| 170 |
+
imagenet_pretrained,
|
| 171 |
+
)
|
| 172 |
+
self.dermoscopic_encoder, dermoscopic_feature_dim = build_feature_encoder(
|
| 173 |
+
backbone,
|
| 174 |
+
dermoscopic_backbone_backend,
|
| 175 |
+
imagenet_pretrained,
|
| 176 |
+
)
|
| 177 |
|
| 178 |
self.clinical_head = ProjectionHead(clinical_feature_dim, branch_dim, dropout)
|
| 179 |
self.dermoscopic_head = ProjectionHead(dermoscopic_feature_dim, branch_dim, dropout)
|
| 180 |
+
if self.one_encoder:
|
| 181 |
+
self.shared_head = ProjectionHead(shared_feature_dim, branch_dim, dropout)
|
| 182 |
self.metadata_head = MetadataHead(metadata_input_dim, metadata_dim, dropout)
|
| 183 |
if metadata_fusion in ("gated_concat", "gated_only"):
|
| 184 |
gate_hidden_dim = metadata_gate_hidden_dim if metadata_gate_hidden_dim is not None else metadata_dim
|
| 185 |
+
if self.one_encoder:
|
| 186 |
+
self.shared_metadata_gate = MetadataChannelGate(
|
| 187 |
+
metadata_input_dim,
|
| 188 |
+
shared_feature_dim,
|
| 189 |
+
gate_hidden_dim,
|
| 190 |
+
dropout,
|
| 191 |
+
)
|
| 192 |
+
else:
|
| 193 |
+
self.clinical_metadata_gate = MetadataChannelGate(
|
| 194 |
+
metadata_input_dim,
|
| 195 |
+
clinical_feature_dim,
|
| 196 |
+
gate_hidden_dim,
|
| 197 |
+
dropout,
|
| 198 |
+
)
|
| 199 |
+
self.dermoscopic_metadata_gate = MetadataChannelGate(
|
| 200 |
+
metadata_input_dim,
|
| 201 |
+
dermoscopic_feature_dim,
|
| 202 |
+
gate_hidden_dim,
|
| 203 |
+
dropout,
|
| 204 |
+
)
|
| 205 |
metadata_output_dim = 0 if metadata_fusion == "gated_only" else metadata_dim
|
| 206 |
fused_dim = self._fusion_dim(branch_dim, metadata_output_dim, image_fusion)
|
| 207 |
heads = 4 if branch_dim % 4 == 0 else 1
|
|
|
|
| 291 |
def _fusion_dim(branch_dim: int, metadata_dim: int, image_fusion: str) -> int:
|
| 292 |
if image_fusion in ("concat", "cross_attention"):
|
| 293 |
image_dim = branch_dim * 2
|
| 294 |
+
elif image_fusion in (
|
| 295 |
+
"compact_bilinear",
|
| 296 |
+
"low_rank_bilinear",
|
| 297 |
+
"adaptive_gate",
|
| 298 |
+
"shared_private",
|
| 299 |
+
"shared_encoder_pool",
|
| 300 |
+
):
|
| 301 |
image_dim = branch_dim * 3
|
| 302 |
+
elif image_fusion == "single_encoder_canvas":
|
| 303 |
+
image_dim = branch_dim
|
| 304 |
elif image_fusion == "co_attention":
|
| 305 |
image_dim = branch_dim * 4
|
| 306 |
elif image_fusion == "moe":
|
|
|
|
| 315 |
dermoscopic: torch.Tensor,
|
| 316 |
metadata: torch.Tensor,
|
| 317 |
) -> torch.Tensor:
|
| 318 |
+
if self.one_encoder:
|
| 319 |
+
fusion_logits = self._one_encoder_logits(clinical, dermoscopic, metadata)
|
| 320 |
+
return fusion_logits * self.class_scales
|
| 321 |
+
|
| 322 |
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 323 |
clinical_features = self.encode_with_metadata_gate(
|
| 324 |
self.clinical_encoder,
|
|
|
|
| 364 |
+ self.dermoscopic_logit_weight * dermoscopic_logits
|
| 365 |
) * self.class_scales
|
| 366 |
|
| 367 |
+
def _one_encoder_logits(
|
| 368 |
+
self,
|
| 369 |
+
clinical: torch.Tensor,
|
| 370 |
+
dermoscopic: torch.Tensor,
|
| 371 |
+
metadata: torch.Tensor,
|
| 372 |
+
) -> torch.Tensor:
|
| 373 |
+
if self.image_fusion == "single_encoder_canvas":
|
| 374 |
+
combined = torch.cat([clinical, dermoscopic], dim=-1)
|
| 375 |
+
features = self._encode_shared(combined, metadata)
|
| 376 |
+
repr_ = self.shared_head(features)
|
| 377 |
+
fused_image = repr_
|
| 378 |
+
elif self.image_fusion == "shared_encoder_pool":
|
| 379 |
+
clinical_features = self._encode_shared(clinical, metadata)
|
| 380 |
+
dermoscopic_features = self._encode_shared(dermoscopic, metadata)
|
| 381 |
+
clinical_repr = self.shared_head(clinical_features)
|
| 382 |
+
dermoscopic_repr = self.shared_head(dermoscopic_features)
|
| 383 |
+
fused_image = torch.cat(
|
| 384 |
+
[
|
| 385 |
+
0.5 * (clinical_repr + dermoscopic_repr),
|
| 386 |
+
torch.abs(clinical_repr - dermoscopic_repr),
|
| 387 |
+
clinical_repr * dermoscopic_repr,
|
| 388 |
+
],
|
| 389 |
+
dim=1,
|
| 390 |
+
)
|
| 391 |
+
else:
|
| 392 |
+
raise ValueError(f"Unsupported one-encoder image_fusion: {self.image_fusion}")
|
| 393 |
+
|
| 394 |
+
metadata_repr = self._metadata_repr(fused_image, metadata)
|
| 395 |
+
return self.classifier(self._append_metadata(fused_image, metadata_repr))
|
| 396 |
+
|
| 397 |
+
def _encode_shared(self, images: torch.Tensor, metadata: torch.Tensor) -> torch.Tensor:
|
| 398 |
+
if self.metadata_fusion in ("gated_concat", "gated_only"):
|
| 399 |
+
features = self.encode_with_metadata_gate(
|
| 400 |
+
self.shared_encoder,
|
| 401 |
+
self.clinical_backbone_backend,
|
| 402 |
+
images,
|
| 403 |
+
metadata,
|
| 404 |
+
self.shared_metadata_gate,
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
features = self.shared_encoder(images)
|
| 408 |
+
return torch.flatten(features, 1)
|
| 409 |
+
|
| 410 |
+
def _metadata_repr(self, image_repr: torch.Tensor, metadata: torch.Tensor) -> torch.Tensor | None:
|
| 411 |
+
if self.metadata_fusion == "gated_only":
|
| 412 |
+
return None
|
| 413 |
+
if self.disable_metadata:
|
| 414 |
+
return image_repr.new_zeros((image_repr.size(0), self.metadata_dim))
|
| 415 |
+
return self.metadata_head(metadata)
|
| 416 |
+
|
| 417 |
def _append_metadata(self, features: torch.Tensor, metadata_repr: torch.Tensor | None) -> torch.Tensor:
|
| 418 |
if metadata_repr is None:
|
| 419 |
return features
|
|
|
|
| 637 |
|
| 638 |
|
| 639 |
def set_encoder_trainable(model: DualEffB2MetadataClassifier, trainable: bool) -> None:
|
| 640 |
+
if getattr(model, "one_encoder", False):
|
| 641 |
+
for param in model.shared_encoder.parameters():
|
| 642 |
+
param.requires_grad = trainable
|
| 643 |
+
return
|
| 644 |
for param in model.clinical_encoder.parameters():
|
| 645 |
param.requires_grad = trainable
|
| 646 |
for param in model.dermoscopic_encoder.parameters():
|
milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc
CHANGED
|
Binary files a/milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc and b/milk10k_effb2_metadata/tests/__pycache__/test_fusion_and_f1_loss.cpython-314.pyc differ
|
|
|
milk10k_effb2_metadata/tests/test_fusion_and_f1_loss.py
CHANGED
|
@@ -180,6 +180,8 @@ if MISSING_DEPENDENCY is None:
|
|
| 180 |
"adaptive_gate": 30,
|
| 181 |
"shared_private": 30,
|
| 182 |
"moe": 22,
|
|
|
|
|
|
|
| 183 |
}
|
| 184 |
for mode, expected_dim in expected.items():
|
| 185 |
with self.subTest(mode=mode):
|
|
@@ -187,6 +189,73 @@ if MISSING_DEPENDENCY is None:
|
|
| 187 |
gated_only_dim = expected_dim - metadata_dim
|
| 188 |
self.assertEqual(DualEffB2MetadataClassifier._fusion_dim(branch_dim, 0, mode), gated_only_dim)
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
class MetadataAugmentationTest(unittest.TestCase):
|
| 192 |
def test_image_transform_does_not_change_metadata(self) -> None:
|
|
|
|
| 180 |
"adaptive_gate": 30,
|
| 181 |
"shared_private": 30,
|
| 182 |
"moe": 22,
|
| 183 |
+
"single_encoder_canvas": 14,
|
| 184 |
+
"shared_encoder_pool": 30,
|
| 185 |
}
|
| 186 |
for mode, expected_dim in expected.items():
|
| 187 |
with self.subTest(mode=mode):
|
|
|
|
| 189 |
gated_only_dim = expected_dim - metadata_dim
|
| 190 |
self.assertEqual(DualEffB2MetadataClassifier._fusion_dim(branch_dim, 0, mode), gated_only_dim)
|
| 191 |
|
| 192 |
+
def test_one_encoder_fusions_forward_with_and_without_metadata(self) -> None:
|
| 193 |
+
with patch("milk10k_effb2_metadata.models.build_feature_encoder", side_effect=fake_build_feature_encoder):
|
| 194 |
+
for mode in ("single_encoder_canvas", "shared_encoder_pool"):
|
| 195 |
+
for disable_metadata in (False, True):
|
| 196 |
+
with self.subTest(mode=mode, disable_metadata=disable_metadata):
|
| 197 |
+
model = DualEffB2MetadataClassifier(
|
| 198 |
+
num_classes=4,
|
| 199 |
+
metadata_input_dim=5,
|
| 200 |
+
branch_dim=8,
|
| 201 |
+
metadata_dim=6,
|
| 202 |
+
classifier_hidden_dim=12,
|
| 203 |
+
dropout=0.0,
|
| 204 |
+
imagenet_pretrained=False,
|
| 205 |
+
clinical_backbone_backend="torchvision",
|
| 206 |
+
dermoscopic_backbone_backend="torchvision",
|
| 207 |
+
backbone="efficientnet_b2",
|
| 208 |
+
disable_metadata=disable_metadata,
|
| 209 |
+
image_fusion=mode,
|
| 210 |
+
)
|
| 211 |
+
self.assertTrue(hasattr(model, "shared_encoder"))
|
| 212 |
+
self.assertFalse(hasattr(model, "clinical_encoder"))
|
| 213 |
+
self.assertFalse(hasattr(model, "dermoscopic_encoder"))
|
| 214 |
+
logits = model(
|
| 215 |
+
torch.randn(2, 3, 8, 8),
|
| 216 |
+
torch.randn(2, 3, 8, 8),
|
| 217 |
+
torch.randn(2, 5),
|
| 218 |
+
)
|
| 219 |
+
self.assertEqual(tuple(logits.shape), (2, 4))
|
| 220 |
+
|
| 221 |
+
def test_checkpoint_reconstructs_one_encoder_model(self) -> None:
|
| 222 |
+
checkpoint_args = {
|
| 223 |
+
"branch_dim": 8,
|
| 224 |
+
"metadata_dim": 6,
|
| 225 |
+
"classifier_hidden_dim": 12,
|
| 226 |
+
"dropout": 0.0,
|
| 227 |
+
"metadata_fusion": "concat",
|
| 228 |
+
"image_fusion": "single_encoder_canvas",
|
| 229 |
+
"logit_fusion_mode": "single",
|
| 230 |
+
"backbone": "efficientnet_b2",
|
| 231 |
+
}
|
| 232 |
+
with patch("milk10k_effb2_metadata.models.build_feature_encoder", side_effect=fake_build_feature_encoder):
|
| 233 |
+
model = DualEffB2MetadataClassifier(
|
| 234 |
+
num_classes=4,
|
| 235 |
+
metadata_input_dim=5,
|
| 236 |
+
branch_dim=8,
|
| 237 |
+
metadata_dim=6,
|
| 238 |
+
classifier_hidden_dim=12,
|
| 239 |
+
dropout=0.0,
|
| 240 |
+
imagenet_pretrained=False,
|
| 241 |
+
clinical_backbone_backend="timm",
|
| 242 |
+
dermoscopic_backbone_backend="timm",
|
| 243 |
+
backbone="efficientnet_b2",
|
| 244 |
+
image_fusion="single_encoder_canvas",
|
| 245 |
+
)
|
| 246 |
+
with patch("milk10k_effb2_metadata.inference.infer_backend_from_model_state", return_value="timm"):
|
| 247 |
+
loaded = build_model_from_checkpoint(
|
| 248 |
+
{
|
| 249 |
+
"model_state": model.state_dict(),
|
| 250 |
+
"class_names": ["A", "B", "C", "D"],
|
| 251 |
+
"args": checkpoint_args,
|
| 252 |
+
},
|
| 253 |
+
metadata_dim=5,
|
| 254 |
+
device=torch.device("cpu"),
|
| 255 |
+
)
|
| 256 |
+
self.assertTrue(hasattr(loaded, "shared_encoder"))
|
| 257 |
+
self.assertFalse(hasattr(loaded, "clinical_encoder"))
|
| 258 |
+
|
| 259 |
|
| 260 |
class MetadataAugmentationTest(unittest.TestCase):
|
| 261 |
def test_image_transform_does_not_change_metadata(self) -> None:
|
milk10k_effb2_metadata/training.py
CHANGED
|
@@ -53,7 +53,7 @@ def run(args: argparse.Namespace) -> None:
|
|
| 53 |
print_mask_audit_summary,
|
| 54 |
)
|
| 55 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 56 |
-
from milk10k_effb2_metadata.models import normalize_backbone_name, resolve_image_size
|
| 57 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 58 |
|
| 59 |
if args.k_folds < 1:
|
|
@@ -67,6 +67,12 @@ def run(args: argparse.Namespace) -> None:
|
|
| 67 |
args.backbone = normalize_backbone_name(args.backbone)
|
| 68 |
if args.metadata_gate_hidden_dim is None:
|
| 69 |
args.metadata_gate_hidden_dim = args.metadata_dim
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
if args.resume_checkpoint is None and args.clinical_checkpoint is None and args.dermoscopic_checkpoint is None:
|
| 71 |
args.imagenet_pretrained = True
|
| 72 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|
|
|
|
| 53 |
print_mask_audit_summary,
|
| 54 |
)
|
| 55 |
from milk10k_effb2_metadata.model_setup import resolve_training_backbone_backends
|
| 56 |
+
from milk10k_effb2_metadata.models import is_one_encoder_image_fusion, normalize_backbone_name, resolve_image_size
|
| 57 |
from milk10k_effb2_metadata.runner import train_kfold, train_single_run
|
| 58 |
|
| 59 |
if args.k_folds < 1:
|
|
|
|
| 67 |
args.backbone = normalize_backbone_name(args.backbone)
|
| 68 |
if args.metadata_gate_hidden_dim is None:
|
| 69 |
args.metadata_gate_hidden_dim = args.metadata_dim
|
| 70 |
+
if is_one_encoder_image_fusion(getattr(args, "image_fusion", "concat")):
|
| 71 |
+
if args.clinical_checkpoint is not None or args.dermoscopic_checkpoint is not None:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"--image-fusion {args.image_fusion} uses one ImageNet-initialized encoder; "
|
| 74 |
+
"do not pass --clinical-checkpoint or --dermoscopic-checkpoint."
|
| 75 |
+
)
|
| 76 |
if args.resume_checkpoint is None and args.clinical_checkpoint is None and args.dermoscopic_checkpoint is None:
|
| 77 |
args.imagenet_pretrained = True
|
| 78 |
args.image_size = resolve_image_size(args.backbone, args.image_size)
|