upload code/RAEv2/sample_perclass_kermany.py
Browse files
code/RAEv2/sample_perclass_kermany.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, math, dataclasses, csv
|
| 2 |
+
import numpy as np, torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from omegaconf import OmegaConf
|
| 5 |
+
from configs.stage2 import Stage2Config
|
| 6 |
+
from stage2.transport import create_sampler, create_transport
|
| 7 |
+
from utils.guidance_utils import get_model_forward_fn
|
| 8 |
+
from utils.model_utils import instantiate_from_config
|
| 9 |
+
|
| 10 |
+
CFG_PATH = sys.argv[1]
|
| 11 |
+
OUTDIR = sys.argv[2]
|
| 12 |
+
NPER = int(sys.argv[3]) if len(sys.argv) > 3 else 2000
|
| 13 |
+
BATCH = int(sys.argv[4]) if len(sys.argv) > 4 else 50
|
| 14 |
+
ALLCLASSES = ["CNV", "DME", "DRUSEN", "NORMAL"]
|
| 15 |
+
CLASSES = sys.argv[5].split(",") if len(sys.argv) > 5 else ALLCLASSES # subset (names)
|
| 16 |
+
TAG = sys.argv[6] if len(sys.argv) > 6 else "all"
|
| 17 |
+
device = torch.device("cuda", 0)
|
| 18 |
+
torch.set_grad_enabled(False)
|
| 19 |
+
torch.backends.cuda.matmul.allow_tf32 = True; torch.backends.cudnn.allow_tf32 = True
|
| 20 |
+
|
| 21 |
+
config = OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Stage2Config), OmegaConf.load(CFG_PATH)))
|
| 22 |
+
config.post_process()
|
| 23 |
+
latent_size = tuple(config.misc.latent_size)
|
| 24 |
+
rae = instantiate_from_config(config.stage_1).to(device).eval()
|
| 25 |
+
config.prepare_model_params()
|
| 26 |
+
model = instantiate_from_config(config.stage_2).to(device).eval()
|
| 27 |
+
model_fn, sample_model_kwargs = get_model_forward_fn(model, config.guidance)
|
| 28 |
+
use_guidance = config.guidance.any_guidance_active
|
| 29 |
+
null_label = config.misc.num_classes
|
| 30 |
+
tds = math.sqrt((config.misc.time_dist_shift_dim or math.prod(latent_size)) / config.misc.time_dist_shift_base)
|
| 31 |
+
transport = create_transport(config=config.transport, time_dist_shift=tds)
|
| 32 |
+
sampler = create_sampler(transport, guidance_config=config.guidance)
|
| 33 |
+
sample_fn = sampler.sample_ode(**dataclasses.asdict(config.sampler))
|
| 34 |
+
print(f"setup ok; latent={latent_size} use_guidance={use_guidance} ckpt={config.stage_2.ckpt}", flush=True)
|
| 35 |
+
|
| 36 |
+
os.makedirs(OUTDIR, exist_ok=True)
|
| 37 |
+
rows = []
|
| 38 |
+
for c in CLASSES:
|
| 39 |
+
ci = ALLCLASSES.index(c) # GLOBAL class index for conditioning
|
| 40 |
+
cdir = os.path.join(OUTDIR, "images", c); os.makedirs(cdir, exist_ok=True)
|
| 41 |
+
done = 0
|
| 42 |
+
while done < NPER:
|
| 43 |
+
n = min(BATCH, NPER - done)
|
| 44 |
+
z = torch.randn(n, *latent_size, device=device)
|
| 45 |
+
context = torch.full((n,), ci, device=device, dtype=torch.long)
|
| 46 |
+
if use_guidance:
|
| 47 |
+
z = torch.cat([z, z], dim=0)
|
| 48 |
+
context = torch.cat([context, torch.full((n,), null_label, device=device, dtype=torch.long)], dim=0)
|
| 49 |
+
mk = dict(context=context, attn_mask=None, **sample_model_kwargs)
|
| 50 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 51 |
+
samples = sample_fn(z, model_fn, **mk)[-1]
|
| 52 |
+
if use_guidance:
|
| 53 |
+
samples = samples.chunk(2, dim=0)[0]
|
| 54 |
+
imgs = rae.decode(samples).clamp(0, 1)
|
| 55 |
+
arr = imgs.mul(255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()
|
| 56 |
+
for j in range(n):
|
| 57 |
+
rel = f"images/{c}/{c}_{done+j:05d}.png"
|
| 58 |
+
Image.fromarray(arr[j]).save(os.path.join(OUTDIR, rel))
|
| 59 |
+
rows.append((os.path.join(OUTDIR, rel), c))
|
| 60 |
+
done += n
|
| 61 |
+
print(f"{c}: {done} (std={arr.std():.0f})", flush=True)
|
| 62 |
+
with open(os.path.join(OUTDIR, f"synth_{TAG}.csv"), "w", newline="") as f:
|
| 63 |
+
w = csv.writer(f); w.writerow(["image_path", "dx"]); w.writerows(rows)
|
| 64 |
+
print(f"SAMPLE_PERCLASS_DONE tag={TAG} n={len(rows)}", flush=True)
|