import os, sys, math, dataclasses, csv import numpy as np, torch from PIL import Image from omegaconf import OmegaConf from configs.stage2 import Stage2Config from stage2.transport import create_sampler, create_transport from utils.guidance_utils import get_model_forward_fn from utils.model_utils import instantiate_from_config CFG_PATH = sys.argv[1] OUTDIR = sys.argv[2] NPER = int(sys.argv[3]) if len(sys.argv) > 3 else 2000 BATCH = int(sys.argv[4]) if len(sys.argv) > 4 else 50 ALLCLASSES = ["CNV", "DME", "DRUSEN", "NORMAL"] CLASSES = sys.argv[5].split(",") if len(sys.argv) > 5 else ALLCLASSES # subset (names) TAG = sys.argv[6] if len(sys.argv) > 6 else "all" device = torch.device("cuda", 0) torch.set_grad_enabled(False) torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = True config = OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Stage2Config), OmegaConf.load(CFG_PATH))) config.post_process() latent_size = tuple(config.misc.latent_size) rae = instantiate_from_config(config.stage_1).to(device).eval() config.prepare_model_params() model = instantiate_from_config(config.stage_2).to(device).eval() model_fn, sample_model_kwargs = get_model_forward_fn(model, config.guidance) use_guidance = config.guidance.any_guidance_active null_label = config.misc.num_classes tds = math.sqrt((config.misc.time_dist_shift_dim or math.prod(latent_size)) / config.misc.time_dist_shift_base) transport = create_transport(config=config.transport, time_dist_shift=tds) sampler = create_sampler(transport, guidance_config=config.guidance) sample_fn = sampler.sample_ode(**dataclasses.asdict(config.sampler)) print(f"setup ok; latent={latent_size} use_guidance={use_guidance} ckpt={config.stage_2.ckpt}", flush=True) os.makedirs(OUTDIR, exist_ok=True) rows = [] for c in CLASSES: ci = ALLCLASSES.index(c) # GLOBAL class index for conditioning cdir = os.path.join(OUTDIR, "images", c); os.makedirs(cdir, exist_ok=True) done = 0 while done < NPER: n = min(BATCH, NPER - done) z = torch.randn(n, *latent_size, device=device) context = torch.full((n,), ci, device=device, dtype=torch.long) if use_guidance: z = torch.cat([z, z], dim=0) context = torch.cat([context, torch.full((n,), null_label, device=device, dtype=torch.long)], dim=0) mk = dict(context=context, attn_mask=None, **sample_model_kwargs) with torch.autocast("cuda", dtype=torch.bfloat16): samples = sample_fn(z, model_fn, **mk)[-1] if use_guidance: samples = samples.chunk(2, dim=0)[0] imgs = rae.decode(samples).clamp(0, 1) arr = imgs.mul(255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy() for j in range(n): rel = f"images/{c}/{c}_{done+j:05d}.png" Image.fromarray(arr[j]).save(os.path.join(OUTDIR, rel)) rows.append((os.path.join(OUTDIR, rel), c)) done += n print(f"{c}: {done} (std={arr.std():.0f})", flush=True) with open(os.path.join(OUTDIR, f"synth_{TAG}.csv"), "w", newline="") as f: w = csv.writer(f); w.writerow(["image_path", "dx"]); w.writerows(rows) print(f"SAMPLE_PERCLASS_DONE tag={TAG} n={len(rows)}", flush=True)