| """ |
| 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 |
|
|
|
|
| |
| 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"] |
|
|
|
|
| |
| 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() |
|
|
|
|
| |
| 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))] |
|
|
| |
| 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 |
|
|
|
|
| |
| 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)) |
|
|
| |
| 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 |
|
|
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|