File size: 6,590 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Downsample experiment: train 3 models (RetFound/ResNet/ViT) on ADAM/AIROGS/PAPILA
at 100/50/25/10/5% training data fractions (stratified per class, train only),
evaluate on the FULL val/test set. Produces a learning-vs-data curve.

Output layout:  results/downsample/<dataset>/<pct>/<model>/{metrics.json, ...}
"""
import os, sys, csv, json, math, time, argparse, subprocess, random, shutil
from collections import defaultdict
from itertools import product

PROJ = "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/GPT-Image"
DSROOT = f"{PROJ}/Dataset"
CODE = f"{PROJ}/Code"
RETF = f"{CODE}/RETFound"
CFP = f"{PROJ}/weights/pretrained/RETFound_mae_natureCFP.pth"
RESULTS = f"{PROJ}/results/downsample"
PY = "/root/miniconda3/envs/retfound/bin/python"
TORCHRUN = "/root/miniconda3/envs/retfound/bin/torchrun"
GPUS = [0, 1, 2, 3, 4, 5, 6, 7]
TMPROOT = "/tmp/downsample_exp"  # local, not JuiceFS (symlinks can be slow on FUSE)
SEED = 42
FRACTIONS = [1.0, 0.5, 0.25, 0.10, 0.05]
DATASETS = {
    "adam":   ("AMD/adamdataset",                2, None),
    "airogs": ("Glaucoma/eyepacs-airogs-light",  2, 30),
    "papila": ("Glaucoma/papila-retinal-fundus-images", 2, None),
}
CLASS_NAMES = {"adam": "NonAMD,AMD", "airogs": "NRG,RG", "papila": "healthy,glaucoma"}
MODELS = ["retfound", "resnet", "vit"]


def make_downsampled_dir(dsk, frac):
    """Symlink full val/test + stratified-downsampled train into a temp dir.
    Returns (data_path, n_train)."""
    rel, nc, max_ep = DATASETS[dsk]
    src = os.path.join(DSROOT, rel)
    dst = os.path.join(TMPROOT, f"{dsk}_{int(frac*100)}")
    shutil.rmtree(dst, ignore_errors=True)
    os.makedirs(dst)
    rows = list(csv.DictReader(open(os.path.join(src, "labels.csv"))))
    by = defaultdict(list)
    for r in rows:
        if r["split"] == "train":
            by[r["label"]].append(r["filepath"])
    rnd = random.Random(SEED)
    chosen = []  # relative paths like "train/0/img.jpg"
    for lab in sorted(by, key=int):
        files = sorted(by[lab])
        rnd.shuffle(files)
        n = max(1, int(round(len(files) * frac)))
        chosen.extend(files[:n])
    # symlink val + test entirely
    for sp in ["val", "test"]:
        os.symlink(os.path.join(src, sp), os.path.join(dst, sp))
    # build train from chosen files only
    os.makedirs(os.path.join(dst, "train"))
    for fp in chosen:
        parts = fp.split("/")        # ["train", "<label>", "<filename>"]
        cls_dir = parts[-2]
        os.makedirs(os.path.join(dst, "train", cls_dir), exist_ok=True)
        os.symlink(os.path.join(src, fp), os.path.join(dst, "train", cls_dir, os.path.basename(fp)))
    n_train = len(chosen)
    return dst, n_train


def train_cmd(model, dsk, frac, data_path, n_train):
    rel, nc, max_ep = DATASETS[dsk]
    # epochs: scale slightly for very small datasets; keep original for normal
    ep = max_ep or (80 if n_train < 32 else 50)
    # batch_size: must be <= n_train, and preferably n_train // 2. min 4, max 64/32
    bs = min(32 if model == "retfound" else 64, max(4, n_train // 2 + 1))
    frac_str = f"{int(frac*100)}".zfill(3)
    odir = os.path.join(RESULTS, dsk, frac_str, model)  # model-specific
    if model == "retfound":
        port = random.Random(hash(f"{dsk}_{frac_str}_{model}") % 30000 + 25000).randint(25000, 55000)
        # use --task so evaluate.py finds test_pred.npz in odir/task/ → match our odir
        return (f"cd {RETF} && {TORCHRUN} --nproc_per_node=1 --master_port={port} "
                f"main_finetune.py --model RETFound_mae --model_arch retfound_mae "
                f"--finetune {CFP} --savemodel --global_pool --batch_size {bs} --world_size 1 "
                f"--epochs {ep} --nb_classes {nc} --data_path {data_path} --input_size 224 "
                f"--task {model} --output_dir {os.path.join(RESULTS, dsk, frac_str)} --adaptation finetune")
    timm_name = "resnet50" if model == "resnet" else "vit_base_patch16_224"
    extra = "" if model == "resnet" else " --lr 1e-4 --layer_decay 0.65 --drop_path 0.1 --label_smoothing 0.1 --warmup_epochs 5"
    return (f"cd {CODE} && {PY} train_cnn_vit.py --data_path {data_path} --nb_classes {nc} "
            f"--model {timm_name} --input_size 224 --batch_size {bs} --epochs {ep} "
            f"--output_dir {os.path.join(RESULTS, dsk, frac_str)} --task {model}{extra}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry_run", action="store_true")
    args = ap.parse_args()

    jobs = []
    port = 29500
    for dsk in sorted(DATASETS):
        for frac in FRACTIONS:
            dst, n = make_downsampled_dir(dsk, frac)
            for model in MODELS:
                frac_str = f"{int(frac*100)}".zfill(3)
                odir = os.path.join(RESULTS, dsk, frac_str, model)
                os.makedirs(odir, exist_ok=True)
                ev = f"{PY} {CODE}/evaluate.py --run_dir {odir} --class_names {CLASS_NAMES[dsk]}"
                cmd = f"{train_cmd(model, dsk, frac, dst, n)} && {ev}"
                jobs.append({"name": f"{dsk}/{frac_str}pct/{model}", "cmd": cmd, "odir": odir})

    print(f"=== {len(jobs)} jobs over {len(GPUS)} GPUs ===")
    for j in jobs:
        print(f"  {j['name']}")
        if args.dry_run:
            print(f"    {j['cmd'][:120]}...")

    if args.dry_run:
        return

    free = list(GPUS)
    running = {}
    pending = list(jobs)
    done, failed = [], []
    while pending or running:
        while pending and free:
            g = free.pop(0)
            j = pending.pop(0)
            env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(g))
            fh = open(os.path.join(j["odir"], "train.log"), "w")
            p = subprocess.Popen(["bash", "-lc", j["cmd"]], env=env, stdout=fh, stderr=subprocess.STDOUT)
            running[p.pid] = (j, g, fh, p)
            print(f"[launch] GPU{g} {j['name']} (pid {p.pid}) [{len(done)+len(failed)}/{len(jobs)}]")
        time.sleep(15)
        for pid in list(running):
            j, g, fh, p = running[pid]
            rc = p.poll()
            if rc is None:
                continue
            fh.close(); free.append(g); del running[pid]
            ok = (rc == 0 and os.path.isfile(os.path.join(j["odir"], "metrics.json")))
            (done if ok else failed).append(j["name"])
            print(f"[{'done' if ok else 'FAIL'}] GPU{g} {j['name']} rc={rc} [{len(done)+len(failed)}/{len(jobs)}]")
    print(f"\n=== finished: {len(done)} ok, {len(failed)} failed ===")
    if failed:
        print("FAILED:", failed)


if __name__ == "__main__":
    main()