File size: 9,191 Bytes
3c366de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Train ResNet / ViT baselines (timm, ImageNet-pretrained) on one dataset.

Same data layout, augmentation, optimizer and model-selection rule as the RETFound
runs so the three models are directly comparable. After training it reloads the
best-val checkpoint, predicts the test set and saves:
    <output_dir>/<task>/checkpoint-best.pth
    <output_dir>/<task>/test_pred.npz   (y_true, y_prob)   <- consumed by evaluate.py
    <output_dir>/<task>/log.csv
Model selection score = (f1_macro + auroc + kappa)/3 on val (mirrors RETFound).
"""
import os, csv, json, math, argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import timm
from timm.data import resolve_data_config, create_transform
from torchvision import datasets, transforms
from sklearn.metrics import f1_score, roc_auc_score, cohen_kappa_score, accuracy_score

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)


def build_loaders(data_path, input_size, batch_size, workers):
    train_tf = transforms.Compose([
        transforms.RandomResizedCrop(input_size, scale=(0.6, 1.0)),
        transforms.RandomHorizontalFlip(),
        transforms.ColorJitter(0.1, 0.1, 0.1),
        transforms.ToTensor(),
        transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ])
    eval_tf = transforms.Compose([
        transforms.Resize(int(input_size * 1.15)),
        transforms.CenterCrop(input_size),
        transforms.ToTensor(),
        transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ])
    ds = {s: datasets.ImageFolder(os.path.join(data_path, s),
                                  train_tf if s == "train" else eval_tf)
          for s in ["train", "val", "test"]}
    ld = {s: DataLoader(ds[s], batch_size=batch_size, shuffle=(s == "train"),
                        num_workers=workers, pin_memory=True, drop_last=(s == "train"))
          for s in ds}
    return ds, ld


@torch.no_grad()
def predict(model, loader, device):
    model.eval()
    probs, labels = [], []
    for x, y in loader:
        x = x.to(device, non_blocking=True)
        with torch.cuda.amp.autocast():
            out = model(x)
        probs.append(F.softmax(out.float(), 1).cpu().numpy())
        labels.append(y.numpy())
    return np.concatenate(labels), np.concatenate(probs)


def val_score(y_true, y_prob):
    C = y_prob.shape[1]
    y_pred = y_prob.argmax(1)
    f1 = f1_score(y_true, y_pred, average="macro", zero_division=0)
    kap = cohen_kappa_score(y_true, y_pred)
    try:
        if C == 2:
            auc = roc_auc_score(y_true, y_prob[:, 1])
        else:
            auc = roc_auc_score(np.eye(C)[y_true], y_prob, multi_class="ovr", average="macro")
    except Exception:
        auc = 0.0
    return (f1 + auc + kap) / 3, accuracy_score(y_true, y_pred), auc


def build_param_groups(model, weight_decay, layer_decay):
    """Split params into (weight-decay / no-decay) groups.
    If layer_decay < 1 and the model is a ViT (has .blocks), apply layer-wise lr
    decay (MAE/BeiT style): shallower layers get exponentially smaller lr via lr_scale.
    no-decay = biases, 1-D params (norms), cls_token, pos_embed."""
    blocks = getattr(model, "blocks", None)
    use_lld = (blocks is not None) and (layer_decay < 1.0)
    num_layers = (len(blocks) + 1) if blocks is not None else 1

    def layer_id(name):
        if name in ("cls_token", "pos_embed") or name.startswith("patch_embed"):
            return 0
        if name.startswith("blocks."):
            return int(name.split(".")[1]) + 1
        return num_layers

    groups = {}
    for n, p in model.named_parameters():
        if not p.requires_grad:
            continue
        no_decay = (p.ndim == 1 or n.endswith(".bias") or n in ("cls_token", "pos_embed"))
        lid = layer_id(n) if use_lld else 0
        scale = (layer_decay ** (num_layers - lid)) if use_lld else 1.0
        key = (lid, no_decay)
        if key not in groups:
            groups[key] = {"params": [], "weight_decay": 0.0 if no_decay else weight_decay,
                           "lr_scale": scale}
        groups[key]["params"].append(p)
    return list(groups.values())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data_path", required=True)
    ap.add_argument("--nb_classes", type=int, required=True)
    ap.add_argument("--model", required=True, help="timm name e.g. resnet50 / vit_base_patch16_224")
    ap.add_argument("--input_size", type=int, default=224)
    ap.add_argument("--batch_size", type=int, default=64)
    ap.add_argument("--epochs", type=int, default=50)
    ap.add_argument("--lr", type=float, default=5e-4)
    ap.add_argument("--weight_decay", type=float, default=0.05)
    ap.add_argument("--warmup_epochs", type=int, default=3)
    ap.add_argument("--patience", type=int, default=10)
    # ViT-friendly fine-tuning knobs (defaults OFF -> identical to old behaviour)
    ap.add_argument("--layer_decay", type=float, default=1.0, help="<1.0 enables layer-wise lr decay (ViT)")
    ap.add_argument("--drop_path", type=float, default=0.0, help="stochastic depth rate (ViT)")
    ap.add_argument("--label_smoothing", type=float, default=0.0)
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--output_dir", required=True)
    ap.add_argument("--task", required=True)
    args = ap.parse_args()

    out = os.path.join(args.output_dir, args.task)
    os.makedirs(out, exist_ok=True)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    torch.manual_seed(42); np.random.seed(42)

    ds, ld = build_loaders(args.data_path, args.input_size, args.batch_size, args.workers)
    print(f"[{args.task}] train={len(ds['train'])} val={len(ds['val'])} test={len(ds['test'])} "
          f"classes={ds['train'].classes}")

    model = timm.create_model(args.model, pretrained=True, num_classes=args.nb_classes,
                              drop_path_rate=args.drop_path).to(device)

    # class-weighted loss (+ optional label smoothing) from train distribution
    counts = np.bincount([y for _, y in ds["train"].samples], minlength=args.nb_classes)
    w = counts.sum() / (args.nb_classes * np.clip(counts, 1, None))
    criterion = nn.CrossEntropyLoss(weight=torch.tensor(w, dtype=torch.float32, device=device),
                                    label_smoothing=args.label_smoothing)

    groups = build_param_groups(model, args.weight_decay, args.layer_decay)
    opt = torch.optim.AdamW(groups, lr=args.lr, weight_decay=args.weight_decay)
    print(f"[{args.task}] optim groups={len(groups)} layer_decay={args.layer_decay} "
          f"drop_path={args.drop_path} ls={args.label_smoothing} lr={args.lr}")
    scaler = torch.cuda.amp.GradScaler()
    steps = len(ld["train"])

    def lr_at(ep_frac):  # warmup + cosine
        if ep_frac < args.warmup_epochs:
            return args.lr * ep_frac / max(1, args.warmup_epochs)
        p = (ep_frac - args.warmup_epochs) / max(1, args.epochs - args.warmup_epochs)
        return args.lr * 0.5 * (1 + math.cos(math.pi * min(1.0, p)))

    log_path = os.path.join(out, "log.csv")
    lf = open(log_path, "w", newline=""); lw = csv.writer(lf)
    lw.writerow(["epoch", "train_loss", "val_acc", "val_auc", "val_score", "lr"]); lf.flush()

    best_score, best_ep, since = -1, -1, 0
    ckpt = os.path.join(out, "checkpoint-best.pth")
    for ep in range(args.epochs):
        model.train(); running = 0.0
        for it, (x, y) in enumerate(ld["train"]):
            for g in opt.param_groups:
                g["lr"] = lr_at(ep + it / steps) * g.get("lr_scale", 1.0)
            x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
            opt.zero_grad()
            with torch.cuda.amp.autocast():
                loss = criterion(model(x), y)
            scaler.scale(loss).backward(); scaler.step(opt); scaler.update()
            running += loss.item()
        yv, pv = predict(model, ld["val"], device)
        sc, vacc, vauc = val_score(yv, pv)
        lw.writerow([ep, running / steps, vacc, vauc, sc, opt.param_groups[0]["lr"]]); lf.flush()
        print(f"[{args.task}] ep{ep} loss={running/steps:.4f} val_acc={vacc:.4f} "
              f"val_auc={vauc:.4f} score={sc:.4f}")
        if sc > best_score:
            best_score, best_ep, since = sc, ep, 0
            torch.save({"model": model.state_dict(), "epoch": ep, "val_score": sc}, ckpt)
        else:
            since += 1
            if since >= args.patience:
                print(f"[{args.task}] early stop at ep{ep} (best ep{best_ep} score={best_score:.4f})")
                break
    lf.close()

    # reload best, predict test, save raw predictions for unified evaluate.py
    state = torch.load(ckpt, map_location="cpu", weights_only=False)
    model.load_state_dict(state["model"]); model.to(device)
    yt, pt = predict(model, ld["test"], device)
    np.savez(os.path.join(out, "test_pred.npz"), y_true=yt, y_prob=pt)
    print(f"[{args.task}] DONE best_ep={best_ep} best_val_score={best_score:.4f} "
          f"-> saved test_pred.npz ({len(yt)} samples)")


if __name__ == "__main__":
    main()