File size: 18,427 Bytes
01fdb75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | """
V4: Segmentation-Generation Cycle Consistency Training.
Supports kvasir (binary), cvc (binary), and refuge2 (3-class).
5 conditions: no_aug, baseline, cycle, consist, cycle_consist
Each condition runs 3 seeds (42, 43, 44), 200 epochs.
Usage:
python scripts/v4_train.py --dataset kvasir --low_data_ratio 1.0 --conditions cycle
python scripts/v4_train.py --dataset cvc --low_data_ratio 1.0 --conditions baseline
python scripts/v4_train.py --dataset refuge2 --low_data_ratio 1.0 --conditions cycle_consist
"""
import sys
sys.path.insert(0, "/data/sichengli/Code/PixelGen")
import argparse
import os
import json
import random
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
import segmentation_models_pytorch as smp
from segmentation.losses import BCEDiceLoss, CEDiceLoss
from segmentation.metrics import compute_dice_iou_binary, compute_dice_iou_multiclass, MetricTracker
# βββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DATASET_CONFIGS = {
"kvasir": {
"data_root": "/data2/sichengli/Data/test/Segmentation/Kvasir-SEG/Kvasir-SEG",
"img_subdir": "images", "mask_subdir": "masks",
"file_ext": (".jpg", ".png", ".jpeg"),
"multi_split": False, "train_ratio": 0.9,
"task": "binary", "num_classes": 1,
},
"cvc": {
"data_root": "/data2/sichengli/Data/test/Segmentation/CVC-ClinicDB",
"img_subdir": "PNG/Original", "mask_subdir": "PNG/Ground Truth",
"file_ext": (".png",),
"multi_split": False, "train_ratio": 0.9,
"task": "binary", "num_classes": 1,
},
"refuge2": {
"data_root": "/data2/sichengli/Data/test/Segmentation/REFUGE2",
"splits": ["train", "val"],
"file_ext": (".jpg", ".png", ".jpeg"),
"mask_ext": (".bmp", ".png"),
"multi_split": True, "val_ratio": 0.1,
"task": "multiclass", "num_classes": 3,
"class_mapping": {0: 0, 128: 1, 255: 2},
},
}
WORK_DIR_BASE = "/data/sichengli/Code/PixelGen/synergy_v4_workdir"
RESOLUTION = 256
SPLIT_SEED = 42
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
EPOCHS = 200
BATCH_SIZE = 16
LR = 1e-4
WEIGHT_DECAY = 1e-4
LAMBDA_CYCLE = 1.0
LAMBDA_CONSIST = 1.0
CONSIST_RAMPUP = 10
SEEDS = [42, 43, 44]
ALL_CONDITIONS = ["no_aug", "baseline", "cycle", "consist", "cycle_consist"]
# βββ Mask Processing βββββββββββββββββββββββββββββββββββββββββββββββββ
def process_mask(mask_pil, task, class_mapping=None):
"""Convert PIL grayscale mask to tensor.
Binary: [1, H, W] float {0, 1}
Multiclass: [H, W] long {0, ..., C-1}
"""
mask_np = np.array(mask_pil)
if task == "binary":
mask_np = (mask_np > 127).astype(np.float32)
return torch.from_numpy(mask_np).unsqueeze(0)
else:
result = np.zeros_like(mask_np, dtype=np.int64)
for pixel_val, class_idx in class_mapping.items():
result[mask_np == pixel_val] = class_idx
for pixel_val in np.unique(mask_np):
if pixel_val not in class_mapping:
closest = min(class_mapping.keys(), key=lambda x: abs(x - pixel_val))
result[mask_np == pixel_val] = class_mapping[closest]
return torch.from_numpy(result).long()
# βββ Datasets βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class RealDataset(Dataset):
"""Real images + masks for supervised training. Supports all three datasets."""
def __init__(self, dataset_name, split="train", augment=True,
low_data_ratio=1.0, low_data_seed=42):
cfg = DATASET_CONFIGS[dataset_name]
self.task = cfg["task"]
self.class_mapping = cfg.get("class_mapping")
self.resolution = RESOLUTION
self.augment = augment and (split == "train")
self.normalize = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
if cfg["multi_split"]:
all_pairs = []
for s in cfg["splits"]:
img_dir = os.path.join(cfg["data_root"], s, "images")
mask_dir = os.path.join(cfg["data_root"], s, "mask")
img_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])])
for img_f in img_files:
base = os.path.splitext(img_f)[0]
img_path = os.path.join(img_dir, img_f)
for ext in cfg["mask_ext"]:
candidate = os.path.join(mask_dir, base + ext)
if os.path.exists(candidate):
all_pairs.append((img_path, candidate))
break
random.seed(SPLIT_SEED)
random.shuffle(all_pairs)
split_idx = int(len(all_pairs) * (1 - cfg.get("val_ratio", 0.1)))
self.pairs = all_pairs[:split_idx] if split == "train" else all_pairs[split_idx:]
else:
img_dir = os.path.join(cfg["data_root"], cfg["img_subdir"])
mask_dir = os.path.join(cfg["data_root"], cfg["mask_subdir"])
all_files = sorted([f for f in os.listdir(img_dir) if f.endswith(cfg["file_ext"])])
random.seed(SPLIT_SEED)
indices = list(range(len(all_files)))
random.shuffle(indices)
split_idx = int(len(indices) * cfg["train_ratio"])
sel = indices[:split_idx] if split == "train" else indices[split_idx:]
sel_files = [all_files[i] for i in sorted(sel)]
self.pairs = [(os.path.join(img_dir, f), os.path.join(mask_dir, f)) for f in sel_files
if os.path.exists(os.path.join(mask_dir, f))]
# Sub-sample for low-data
if split == "train" and low_data_ratio < 1.0:
random.seed(low_data_seed)
n = int(len(self.pairs) * low_data_ratio)
sub = random.sample(range(len(self.pairs)), n)
self.pairs = [self.pairs[i] for i in sorted(sub)]
print(f"[RealDataset-{dataset_name}] {split}: {len(self.pairs)} samples (augment={self.augment})")
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
img_path, mask_path = self.pairs[idx]
image = Image.open(img_path).convert("RGB")
mask = Image.open(mask_path).convert("L")
image = TF.resize(image, (self.resolution, self.resolution),
interpolation=transforms.InterpolationMode.BILINEAR)
mask = TF.resize(mask, (self.resolution, self.resolution),
interpolation=transforms.InterpolationMode.NEAREST)
if self.augment:
if random.random() > 0.5:
image = TF.hflip(image)
mask = TF.hflip(mask)
if random.random() > 0.5:
image = TF.vflip(image)
mask = TF.vflip(mask)
if random.random() > 0.5:
image = TF.adjust_brightness(image, random.uniform(0.85, 1.15))
image = TF.adjust_contrast(image, random.uniform(0.85, 1.15))
image = TF.adjust_saturation(image, random.uniform(0.85, 1.15))
image_tensor = self.normalize(TF.to_tensor(image))
mask_tensor = process_mask(mask, self.task, self.class_mapping)
return image_tensor, mask_tensor
class GeneratedPairDataset(Dataset):
"""Load pre-generated image pairs + masks for cycle/consistency training."""
def __init__(self, gen_dir, task="binary", class_mapping=None):
self.gen_dir = gen_dir
self.task = task
self.class_mapping = class_mapping
self.normalize = transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
mask_dir = os.path.join(gen_dir, "masks")
self.indices = sorted([int(f.split(".")[0]) for f in os.listdir(mask_dir) if f.endswith(".png")])
print(f"[GeneratedPairDataset] {len(self.indices)} triplets")
def __len__(self):
return len(self.indices)
def __getitem__(self, idx):
file_idx = self.indices[idx]
fname = f"{file_idx:04d}.png"
img0 = Image.open(os.path.join(self.gen_dir, "seed0", fname)).convert("RGB")
img1 = Image.open(os.path.join(self.gen_dir, "seed1", fname)).convert("RGB")
mask = Image.open(os.path.join(self.gen_dir, "masks", fname)).convert("L")
if random.random() > 0.5:
img0 = TF.hflip(img0)
img1 = TF.hflip(img1)
mask = TF.hflip(mask)
if random.random() > 0.5:
img0 = TF.vflip(img0)
img1 = TF.vflip(img1)
mask = TF.vflip(mask)
img0_tensor = self.normalize(TF.to_tensor(img0))
img1_tensor = self.normalize(TF.to_tensor(img1))
mask_tensor = process_mask(mask, self.task, self.class_mapping)
return img0_tensor, img1_tensor, mask_tensor
# βββ Training βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def compute_metrics(logits, masks, task, num_classes):
if task == "binary":
return compute_dice_iou_binary(logits, masks)
else:
dice, iou, _, _ = compute_dice_iou_multiclass(logits, masks, num_classes)
return dice, iou
def train_condition(condition, seed, device, dataset_name, low_data_ratio=1.0):
cfg = DATASET_CONFIGS[dataset_name]
task = cfg["task"]
num_classes = cfg["num_classes"]
work_dir = os.path.join(WORK_DIR_BASE, dataset_name)
gen_dir = os.path.join(work_dir, "generated")
data_tag = "full" if low_data_ratio >= 1.0 else "low"
print(f"\n{'='*60}")
print(f" {dataset_name} | {condition} | seed={seed} | {data_tag}")
print(f"{'='*60}")
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
use_aug = condition != "no_aug"
use_cycle = condition in ("cycle", "cycle_consist")
use_consist = condition in ("consist", "cycle_consist")
use_gen = use_cycle or use_consist
train_dataset = RealDataset(dataset_name, "train", augment=use_aug,
low_data_ratio=low_data_ratio, low_data_seed=SPLIT_SEED)
val_dataset = RealDataset(dataset_name, "val", augment=False,
low_data_ratio=1.0, low_data_seed=SPLIT_SEED)
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE,
shuffle=True, num_workers=4, pin_memory=True, drop_last=True)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE,
shuffle=False, num_workers=4, pin_memory=True)
gen_loader_iter = None
if use_gen:
gen_dataset = GeneratedPairDataset(gen_dir, task=task,
class_mapping=cfg.get("class_mapping"))
gen_loader = DataLoader(gen_dataset, batch_size=BATCH_SIZE,
shuffle=True, num_workers=4, pin_memory=True, drop_last=True)
gen_loader_iter = iter(itertools.cycle(gen_loader))
# Model
out_classes = 1 if task == "binary" else num_classes
model = smp.Unet(encoder_name="resnet34", encoder_weights="imagenet",
in_channels=3, classes=out_classes).to(device)
criterion = BCEDiceLoss() if task == "binary" else CEDiceLoss(num_classes=num_classes)
mse_loss = nn.MSELoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
ckpt_dir = os.path.join(work_dir, "checkpoints", f"{data_tag}_{condition}_seed{seed}")
os.makedirs(ckpt_dir, exist_ok=True)
best_dice = 0.0
best_iou = 0.0
for epoch in range(1, EPOCHS + 1):
model.train()
tracker = MetricTracker()
total_loss = 0.0
for real_imgs, real_masks in train_loader:
real_imgs = real_imgs.to(device)
real_masks = real_masks.to(device)
logits = model(real_imgs)
l_sup = criterion(logits, real_masks)
loss = l_sup
if use_gen:
gen_img0, gen_img1, gen_mask = next(gen_loader_iter)
gen_img0 = gen_img0.to(device)
gen_img1 = gen_img1.to(device)
gen_mask = gen_mask.to(device)
pred0 = model(gen_img0)
pred1 = model(gen_img1)
if use_cycle:
l_cycle = 0.5 * (criterion(pred0, gen_mask) + criterion(pred1, gen_mask))
loss = loss + LAMBDA_CYCLE * l_cycle
if use_consist:
rampup = min(1.0, epoch / CONSIST_RAMPUP)
if task == "binary":
l_consist = mse_loss(torch.sigmoid(pred0), torch.sigmoid(pred1))
else:
l_consist = mse_loss(F.softmax(pred0, dim=1), F.softmax(pred1, dim=1))
loss = loss + LAMBDA_CONSIST * rampup * l_consist
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item() * real_imgs.size(0)
with torch.no_grad():
dice, iou = compute_metrics(logits, real_masks, task, num_classes)
tracker.update(dice, iou, real_imgs.size(0))
scheduler.step()
val_loss, val_dice, val_iou = validate(model, val_loader, criterion, device, task, num_classes)
if val_dice > best_dice:
best_dice = val_dice
best_iou = val_iou
torch.save({
"epoch": epoch,
"model_state_dict": model.state_dict(),
"best_dice": best_dice,
"best_iou": best_iou,
"condition": condition,
"seed": seed,
"dataset": dataset_name,
"task": task,
"num_classes": num_classes,
}, os.path.join(ckpt_dir, "best.pth"))
if epoch % 20 == 0 or epoch == 1:
avg_loss = total_loss / max(len(train_loader.dataset), 1)
lr = optimizer.param_groups[0]["lr"]
print(f" Epoch {epoch:>3d}/{EPOCHS} | "
f"Loss: {avg_loss:.4f} Dice: {tracker.avg_dice:.4f} | "
f"Val Dice: {val_dice:.4f} IoU: {val_iou:.4f} | "
f"Best: {best_dice:.4f} | LR: {lr:.2e}")
print(f" -> {condition} seed={seed}: Best Val Dice={best_dice:.4f}, IoU={best_iou:.4f}")
return best_dice, best_iou
@torch.no_grad()
def validate(model, loader, criterion, device, task, num_classes):
model.eval()
tracker = MetricTracker()
total_loss = 0.0
for images, masks in loader:
images = images.to(device)
masks = masks.to(device)
logits = model(images)
loss = criterion(logits, masks)
dice, iou = compute_metrics(logits, masks, task, num_classes)
total_loss += loss.item() * images.size(0)
tracker.update(dice, iou, images.size(0))
return total_loss / max(len(loader.dataset), 1), tracker.avg_dice, tracker.avg_iou
# βββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", type=str, required=True, choices=["kvasir", "cvc", "refuge2"])
parser.add_argument("--conditions", nargs="+", default=ALL_CONDITIONS, choices=ALL_CONDITIONS)
parser.add_argument("--low_data_ratio", type=float, default=1.0)
parser.add_argument("--gpu", type=int, default=0)
args = parser.parse_args()
device = torch.device(f"cuda:{args.gpu}")
work_dir = os.path.join(WORK_DIR_BASE, args.dataset)
os.makedirs(work_dir, exist_ok=True)
data_tag = "full" if args.low_data_ratio >= 1.0 else "low"
print(f"\n Dataset: {args.dataset} | Data: {data_tag} (ratio={args.low_data_ratio})\n")
results = {}
for condition in args.conditions:
cond_results = []
for seed in SEEDS:
best_dice, best_iou = train_condition(
condition, seed, device, args.dataset, args.low_data_ratio)
cond_results.append({"seed": seed, "dice": best_dice, "iou": best_iou})
dices = [r["dice"] for r in cond_results]
ious = [r["iou"] for r in cond_results]
key = f"{data_tag}_{condition}"
results[key] = {
"runs": cond_results,
"mean_dice": float(np.mean(dices)),
"std_dice": float(np.std(dices)),
"mean_iou": float(np.mean(ious)),
"std_iou": float(np.std(ious)),
}
results_path = os.path.join(work_dir, "downstream_results.json")
if os.path.exists(results_path):
with open(results_path, "r") as f:
existing = json.load(f)
existing.update(results)
results = existing
with open(results_path, "w") as f:
json.dump(results, f, indent=2)
# Summary
print(f"\n{'='*75}")
print(f" V4 RESULTS: {args.dataset} ({data_tag})")
print(f"{'='*75}")
print(f"{'Condition':<22s} | {'Dice (mean+/-std)':>20s} | {'IoU (mean+/-std)':>20s} | {'vs baseline':>12s}")
print("-" * 80)
bl_key = f"{data_tag}_baseline"
bl_dice = results.get(bl_key, {}).get("mean_dice", None)
for cond in ALL_CONDITIONS:
key = f"{data_tag}_{cond}"
if key not in results:
continue
r = results[key]
d_str = f"{r['mean_dice']:.4f} +/- {r['std_dice']:.4f}"
i_str = f"{r['mean_iou']:.4f} +/- {r['std_iou']:.4f}"
delta = f"{r['mean_dice'] - bl_dice:+.4f}" if bl_dice and cond != "baseline" else "-"
print(f"{key:<22s} | {d_str:>20s} | {i_str:>20s} | {delta:>12s}")
print("=" * 80)
if __name__ == "__main__":
main()
|