"""Shared helpers for the FlowLensing evaluation scripts. Normalization contract ---------------------- Images are stored as raw simulation output in physical brightness units. Every evaluation applies the same two steps the model was trained with: 1. minmax_to_unit : stretch each image to [0, 1] using its own min and max 2. Normalize(.5,.5): map [0, 1] -> [-1, 1] Generated samples come out of the sampler on [-1, 1] and are returned on [0, 1] by `sample_cfg`, which is the scale the regressor and classifier expect. Step 1 is idempotent, so it is safe to leave on for data that was already normalized offline. """ import numpy as np import torch import torch.nn as nn def minmax_to_unit(img): """Stretch one image to [0, 1] using its own min and max.""" lo, hi = img.min(), img.max() rng = hi - lo if rng <= 0: return torch.zeros_like(img) return (img - lo) / rng def load_npy_image(path, normalize=True): """Load a .npy sample and return a (1, 64, 64) tensor on [0, 1].""" data = np.load(path, allow_pickle=True) if data.dtype == object or (data.ndim == 1 and data.shape[0] == 5): data = data[0] # (image, theta_E, x, y, beta) packing img = np.asarray(data, dtype=np.float32).squeeze() t = torch.from_numpy(img).float().unsqueeze(0) return minmax_to_unit(t) if normalize else t def to_imagenet_rgb(img01): """(B,1,H,W) on [0,1] -> (B,3,H,W) ImageNet-normalized, for the ResNet.""" if img01.dim() == 3: img01 = img01.unsqueeze(0) x = img01.repeat(1, 3, 1, 1) mean = torch.tensor([0.485, 0.456, 0.406], device=x.device).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225], device=x.device).view(1, 3, 1, 1) return (x - mean) / std def pick_device(spec="auto"): if spec != "auto": return torch.device(spec) if torch.cuda.is_available(): return torch.device("cuda") if torch.backends.mps.is_available(): return torch.device("mps") return torch.device("cpu") # -------------------------------------------------------------------------- # Model loading # -------------------------------------------------------------------------- ARCH = dict(input_size=64, patch_size=2, in_channels=1, hidden_size=512, depth=6, num_heads=8, timestep_freq_scale=1000) def load_flow_model(ckpt_path, kind, device): """kind='class' -> 3-class model (model.py); kind='param' -> 4-var model.""" if kind == "class": from model import NanoDiT net = NanoDiT(num_classes=3, **ARCH) elif kind == "param": from model_regress import NanoDiT net = NanoDiT(cond_dim=4, **ARCH) else: raise ValueError(f"unknown kind: {kind}") sd = torch.load(ckpt_path, map_location="cpu", weights_only=False) if isinstance(sd, dict) and "model_state_dict" in sd: sd = sd["model_state_dict"] sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()} net.load_state_dict(sd, strict=True) return net.to(device).eval() def load_classifier(ckpt_path, arch, device, num_classes=3): """ResNet classifier: 3-channel ImageNet-normalized input, Linear head.""" from torchvision.models import resnet18, resnet34 net = {"resnet18": resnet18, "resnet34": resnet34}[arch](weights=None) net.fc = nn.Linear(net.fc.in_features, num_classes) ck = torch.load(ckpt_path, map_location="cpu", weights_only=False) sd = ck.get("model_state_dict", ck) if isinstance(ck, dict) else ck sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()} net.load_state_dict(sd, strict=True) return net.to(device).eval() def load_regressor(ckpt_path, device): from regression_model import ImageRegressor net = ImageRegressor(num_outputs=4) sd = torch.load(ckpt_path, map_location="cpu", weights_only=False) sd = sd.get("model_state_dict", sd) if isinstance(sd, dict) else sd net.load_state_dict({k.replace("_orig_mod.", ""): v for k, v in sd.items()}) return net.to(device).eval() # -------------------------------------------------------------------------- # Sampling (Euler ODE + classifier-free guidance), matching the training code # -------------------------------------------------------------------------- @torch.no_grad() def sample_cfg(model, cond, ode_steps=100, cfg_scale=2.0, device=None, img_size=64, channels=1): """cond: LongTensor (B,) of class ids, or FloatTensor (B,4) of parameters. Returns (B, 1, H, W) on [0, 1]. """ device = device or next(model.parameters()).device n = cond.shape[0] z = torch.randn((n, channels, img_size, img_size), device=device) y = cond.to(device) using_cfg = cfg_scale >= 1.0 if using_cfg: if y.dim() == 1: # class ids -> null token id 3 y_null = torch.full_like(y, 3) else: # parameter vectors -> zeros y_null = torch.zeros_like(y) y = torch.cat([y, y_null], 0) dt = 1.0 / ode_steps for i in range(ode_steps, 0, -1): z_in = torch.cat([z, z], 0) if using_cfg else z t = torch.full((z_in.shape[0],), i / ode_steps, device=device, dtype=z_in.dtype) v = model(z_in, t, y) if using_cfg: v_cond, v_uncond = v.chunk(2, dim=0) v = v_uncond + cfg_scale * (v_cond - v_uncond) z = z - dt * v return torch.clamp((z + 1) / 2.0, 0.0, 1.0)