Add FlowLensing models, code and evals
Browse filesFiles changed (18)
- README.mdAdded+136
- checkpoints/eval_classifier_resnet34.ptAdded+3
- checkpoints/eval_regressor.ptAdded+3
- checkpoints/flowlensing_dit_class_cond.pthAdded+3
- checkpoints/flowlensing_dit_param_cond.pthAdded+3
- code/dataset.pyAdded+131
- code/latency.pyAdded+120
- code/model.pyAdded+405
- code/model_regress.pyAdded+389
- code/regression_model.pyAdded+38
- code/train_og.pyAdded+201
- code/train_regress.pyAdded+246
- evals/common.pyAdded+142
- evals/eval_classify.pyAdded+98
- evals/eval_fid.pyAdded+45
- evals/eval_image_quality.pyAdded+48
- evals/eval_regression.pyAdded+79
- requirements.txtAdded+7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136---license: mitlibrary_name: pytorchpipeline_tag: unconditional-image-generationtags:- flow-matching- diffusion-transformer- dit- gravitational-lensing- astrophysics- dark-matter- deeplense---
# FlowLensing — models, code and evaluation
Companion artefacts for *FlowLensing: Simulating Gravitational Lensing with Flow Matching*(Sayed, Reddy, Toomey, Gleyzer). A ~30M-parameter DiT trained with flow matchingto generate strong-lensing images, replacing ray-tracing simulation.
## Layout
```checkpoints/ flowlensing_dit_class_cond.pth 3-class model (CDM / no_sub / axion), 29.81M params flowlensing_dit_param_cond.pth parameter-conditioned model, 30.07M params eval_classifier_resnet34.pt ResNet-34 classifier, for the 3-class evaluation eval_regressor.pt ImageRegressor, for the parameter evaluationcode/ model.py NanoDiT, class-conditional (needs timm) model_regress.py NanoDiT, parameter-conditional dataset.py DiffusionDataset / VariableDataset / ClassifierDataset train_og.py training, 3-class train_regress.py training, parameter-conditioned regression_model.py ImageRegressor definition latency.py standalone sampling / timingevals/ common.py shared loading, normalization and sampling eval_regression.py parameter recovery (MSE / MAE / RMSE / R2) eval_classify.py accuracy, per-class AUC, confusion matrix eval_fid.py FID, real vs generated eval_image_quality.py PSNR / SSIM on paired images```
## Install
```bashpip install -r requirements.txt```
`timm` is required only by `code/model.py` (the class-conditional model).
## Normalization contract — read this first
Images are stored as raw simulation output in physical brightness units, spanningroughly 1e-12 to 4. Two steps put them on the scale the model was trained with:
1. **Stretch to [0, 1]** — each image by its own min and max (`minmax_to_unit`).2. **Recentre to [-1, 1]** — `Normalize((0.5,), (0.5,))`.
Sampling reverses step 2 (`(z + 1) / 2`) and returns images on [0, 1], which is thescale both the classifier and the regressor expect.
Step 1 is idempotent, so leaving it on is safe for data that was already normalizedoffline. It is **not invertible** — the original per-image min and max are not stored,so generated images carry relative brightness, not physical flux.
Historically step 1 was an offline pass that wrote `*_normalized` copies of the data,and no live code performed it. It is now applied inside the dataset classes(`normalize=True` by default) and inside every evaluation script, so the scripts workdirectly on raw `.npy` files.
## Running the evaluations
Parameter-conditioned model (works with the released `cdm_regress_multi_param` data):
```bashpython evals/eval_regression.py \ --data /path/to/cdm_regress_multi_param \ --flow-ckpt checkpoints/flowlensing_dit_param_cond.pth \ --regressor-ckpt checkpoints/eval_regressor.pt \ --n 1000```
3-class model (needs the Model_II dataset — see *Known gaps*):
```bashpython evals/eval_classify.py \ --flow-ckpt checkpoints/flowlensing_dit_class_cond.pth \ --classifier-ckpt checkpoints/eval_classifier_resnet34.pt --arch resnet34```
`--real-data DIR` classifies real images instead of generated ones, as a baseline.
FID and PSNR/SSIM take two directories of `.npy` files:
```bashpython evals/eval_fid.py --real REAL_DIR --generated GEN_DIRpython evals/eval_image_quality.py --real REAL_DIR --generated GEN_DIR```
All scripts take `--device` (`auto` by default: cuda, then mps, then cpu),`--ode-steps`, `--cfg-scale` and `--seed`.
## Known gaps
These are limitations of the released artefacts, stated so results are notmisread:
- **The Model_II dataset (89,104 images) is not included** and was not recovered. Without it the 3-class results — PSNR, SSIM and classification AUC — cannot be reproduced. Only the 30,000-image `cdm_regress_multi_param` set survives, which covers the parameter-conditioned model.- **Einstein radius is constant** (1.2815) across all 30,000 samples of that set. The parameter-conditioned model therefore has four conditioning inputs but only three that ever varied in training, and `eval_regression.py` reports that parameter as constant rather than scoring R2 on it.- **`eval_classify.py` is unvalidated.** The classifier checkpoints take 3-channel ImageNet-normalized input, but the script that originally fed them was broken (bad imports, a transform called as a function), so the preprocessing in `common.to_imagenet_rgb` is reconstructed, not recovered. On a short CPU smoke test (6 samples/class, 20 ODE steps) it scored at chance. That may simply be too few sampling steps, but it could not be checked against real images because none survive. Treat any number it prints as unverified until it is run against real Model_II data.- **`eval_image_quality.py` is a reimplementation.** The script that produced the paper's PSNR and SSIM numbers is not among the recovered files; this one uses standard torchmetrics definitions and its output should be treated as indicative rather than as the paper's exact procedure.- **The evaluation scripts were rewritten** from the originals, which had broken imports (`from in_progress.dataset import ...`), a classifier builder that did not match the released checkpoints, and absolute paths to a machine that is no longer reachable. Metric definitions are unchanged; plumbing is not.- `train_classifier.py` is not included: it builds a 1-channel ResNet with a different head and does not match the released classifier checkpoint, which takes 3-channel ImageNet-normalized input.123version https://git-lfs.github.com/spec/v1oid sha256:cfa078a377de8a12bc9168ce0b6b1213ba39b749fae1f37aa49c7a9f262989e1size 244850803123version https://git-lfs.github.com/spec/v1oid sha256:58a13a8bad73691fc74e6acdd1acb4163d08211befa9150c73a879b79d5c2dbasize 17427973123version https://git-lfs.github.com/spec/v1oid sha256:77c944fa72fae1e5ad0522b6baf3cd313b293d242cb8a36d287406077de5d9edsize 119262279123version https://git-lfs.github.com/spec/v1oid sha256:90da13461fd6b28f15a5434b9e2aa3537106891565bddf3e850fb3ae86dc059dsize 120318567123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import torchvision.transforms as transformsimport numpy as npfrom pathlib import Pathfrom torch.utils.data import Datasetimport osimport torchimport numpy as np
def minmax_to_unit(img): """Stretch one image to [0, 1] using its own min and max.
This is step one of the two-step normalization; step two is diffusion_transforms, which maps [0, 1] -> [-1, 1]. It is idempotent, so it is safe to leave on for data that was already normalized offline. """ lo, hi = img.min(), img.max() rng = hi - lo if rng <= 0: return torch.zeros_like(img) return (img - lo) / rng
class DiffusionDataset(Dataset): def __init__(self, data_dir, transform=None, normalize=True): self.data_dir = data_dir self.transform = transform self.normalize = normalize self.samples = [] self.class_to_idx = {} for idx, class_name in enumerate(sorted(os.listdir(data_dir))): class_path = os.path.join(data_dir, class_name) if os.path.isdir(class_path): self.class_to_idx[class_name] = idx for npy_file in os.listdir(class_path): if npy_file.endswith('.npy'): self.samples.append((os.path.join(class_path, npy_file), idx)) def __len__(self): return len(self.samples) def __getitem__(self, idx): path, class_idx = self.samples[idx] data = np.load(path) data = torch.from_numpy(data).float().unsqueeze(0) # 1, 64, 64 if self.normalize: data = minmax_to_unit(data) if self.transform: data = self.transform(data) return data, class_idx class VariableDataset(Dataset): def __init__(self, root_dir, transform=None, normalize=True): self.root_dir = root_dir self.transform = transform self.normalize = normalize self.file_paths = [] for root, dirs, files in os.walk(root_dir): for file in files: if file.endswith('.npy'): self.file_paths.append(os.path.join(root, file)) def __len__(self): return len(self.file_paths) def __getitem__(self, idx): npy_path = self.file_paths[idx] data = np.load(npy_path, allow_pickle=True) image = data[0] variables = data[1:5].astype(np.float32) image = torch.from_numpy(image).float().unsqueeze(0) # 1, 64, 64 variables = torch.from_numpy(variables).float() if self.normalize: image = minmax_to_unit(image) if self.transform: image = self.transform(image) return image, variables, npy_path
class ClassifierDataset(Dataset): def __init__(self, file_paths, labels, transform=None, normalize=True): self.file_paths = file_paths self.labels = labels self.transform = transform self.normalize = normalize def __len__(self): return len(self.file_paths) def __getitem__(self, idx): img = np.load(self.file_paths[idx]) img = torch.FloatTensor(img).unsqueeze(0) if self.normalize: img = minmax_to_unit(img) if self.transform: img = self.transform(img) return img, self.labels[idx] class RegressionDataset(Dataset): def __init__(self, data): self.data = data
def __len__(self): return len(self.data)
def __getitem__(self, idx): image, *targets = self.data[idx] image = torch.tensor(image, dtype=torch.float32).unsqueeze(0) target = torch.tensor(targets, dtype=torch.float32) # (4,) return image, target
diffusion_transforms = transforms.Compose([ transforms.Normalize((0.5,), (0.5,)) # Normalize to [-1, 1] ])
def classifier_transforms(): train_transform = transforms.Compose([ transforms.RandomRotation(degrees=15), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomErasing(p=0.5, scale=(0.02, 0.1), ratio=(0.3, 3.3)) ]) val_transform = None return train_transform, val_transform123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import os, time, cv2, torch, numpy as npimport torchvision.transforms as transformsimport matplotlib.pyplot as pltfrom tqdm import tqdmfrom model import NanoDiT # your custom NanoDiTfrom ema_pytorch import EMA # still here if you want to swap in EMA weightsfrom torchmetrics.image import FrechetInceptionDistancefrom torchvision.models import resnet18
NUM_CLASSES = 3IMG_SIZE = 64IMG_CHANNELS = 1LATENT_DIM = 512PATCH_SIZE = 2MODEL_DEPTH = 6MODEL_HEADS = 8DEVICE = "cuda:3" if torch.cuda.is_available() else "cpu"USE_BF16 = False # flip to False if your GPU cries
torch.set_float32_matmul_precision('high') # amp it up
def load_model(checkpoint_path, compile=False, use_bf16=False): model = NanoDiT( input_size=IMG_SIZE, patch_size=PATCH_SIZE, in_channels=IMG_CHANNELS, hidden_size=LATENT_DIM, depth=MODEL_DEPTH, num_heads=MODEL_HEADS, num_classes=NUM_CLASSES, timestep_freq_scale=1000, ).to(DEVICE)
ckpt = torch.load(checkpoint_path, map_location=DEVICE) model.load_state_dict(ckpt)
if use_bf16: model = model.to(torch.bfloat16) # stash weights as bf16
if compile: print("Compiling… hold tight ⏳") model = torch.compile(model, mode="max-autotune")
model.eval() return model
@torch.inference_mode()def generate_image( model, target_class, *, ode_steps=100, cfg_scale=2.0, num_samples=1, use_bf16=False,): """ Generates `num_samples` images of `target_class` with optional classifier‑free guidance. Everything inside the autocast context runs in bf16 when `use_bf16` is True. """ autocast_context = torch.autocast( device_type="cuda", dtype=torch.bfloat16, enabled=use_bf16 and torch.cuda.is_available() ) with autocast_context: dtype = torch.bfloat16 if use_bf16 else torch.float32 z = torch.randn( (num_samples, IMG_CHANNELS, IMG_SIZE, IMG_SIZE), device=DEVICE, dtype=dtype, )
y = torch.tensor([target_class] * num_samples, device=DEVICE, dtype=torch.long) using_cfg = cfg_scale >= 1.0 if using_cfg: null_id = torch.tensor([NUM_CLASSES] * num_samples, device=DEVICE) y = torch.cat([y, null_id], 0)
dt = (1.0 / ode_steps) dt = torch.tensor( [dt] * num_samples, device=DEVICE, dtype=dtype ).view(num_samples, *([1] * (z.ndim - 1)))
# Reverse‑time ODE sampler for i in range(ode_steps, 0, -1): z_final = torch.cat([z, z], 0) if using_cfg else z t = torch.full( (z_final.size(0),), i / ode_steps, device=DEVICE, dtype=dtype, ) v_pred = model(z_final, t, y) if using_cfg: pred_cond, pred_uncond = v_pred.chunk(2, 0) v_pred = pred_uncond + cfg_scale * (pred_cond - pred_uncond) z = (z - dt * v_pred).to(dtype)
images = torch.clamp((z + 1) / 2.0, 0.0, 1.0)
return images.cpu() # back on CPU as float32 for downstream use
if __name__ == "__main__": model = load_model( "checkpoints/flowlensing_dit_class_cond.pth", compile=False, use_bf16=USE_BF16, )
times = [] for _ in tqdm(range(105), desc="Sampling"): start = time.time() _ = generate_image(model, target_class=0, use_bf16=USE_BF16) times.append((time.time() - start) * 1000)
# ignore first 5 runs (warm‑up jit) print(f"Mean latency: {np.mean(times[5:]):.2f} ms (bf16={USE_BF16})")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405"""Adapted fromhttps://github.com/facebookresearch/DiT/blob/main/models.py
Implements the `Attention`, `PatchEmbed`, and `Mlp` classeswithout relying on `timm`."""
import torchimport torch.nn as nnimport numpy as npimport mathimport torch.nn.functional as Ffrom timm.models.layers import trunc_normal_, DropPath
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
################################################################################## Patch embedding ##################################################################################
class PatchEmbed(nn.Module): def __init__( self, img_size: int = 224, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, bias: bool = True, ): super().__init__() self.patch_size = patch_size if isinstance(patch_size, tuple) else (patch_size, patch_size) self.img_size = img_size if isinstance(img_size, tuple) else (img_size, img_size) self.grid_size = tuple([s // p for s, p in zip(self.img_size, self.patch_size)]) self.num_patches = self.grid_size[0] * self.grid_size[1]
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
def forward(self, x: torch.Tensor): x = self.proj(x) x = x.flatten(2).transpose(1, 2) # NCHW -> NLC return x
################################################################################## Attention ##################################################################################
class Attention(nn.Module): def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, ) -> None: super().__init__() assert dim % num_heads == 0, "dim should be divisible by num_heads" self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x: torch.Tensor) -> torch.Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) x = F.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0, ) x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
################################################################################## MLP ##################################################################################
class Mlp(nn.Module): # Adapted from `timm`. def __init__( self, in_features, hidden_features=None, out_features=None, bias=True, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features bias = bias if isinstance(bias, tuple) else (bias, bias) drop_probs = drop if isinstance(drop, tuple) else (drop, drop)
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0]) self.act = nn.GELU() self.drop1 = nn.Dropout(drop_probs[0]) self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1]) self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
################################################################################## Embedding Layers for Timesteps and Class Labels ##################################################################################
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256, use_bias=True): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=use_bias), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=use_bias), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000, freq_scale=1): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :freq_scale: controls the scaling factor of the frequencies :return: an (N, D) Tensor of positional embeddings. """ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py half = dim // 2 freqs = freq_scale * torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( device=t.device ) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t, freq_scale=1): t_freq = self.timestep_embedding(t, self.frequency_embedding_size, freq_scale=freq_scale) t_emb = self.mlp(t_freq) return t_emb
class LabelEmbedder(nn.Module): """ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance. """
def __init__(self, num_classes, hidden_size, dropout_prob): super().__init__() use_cfg_embedding = dropout_prob > 0 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) self.num_classes = num_classes self.dropout_prob = dropout_prob
def token_drop(self, labels, force_drop_ids=None): """ Drops labels to enable classifier-free guidance. """ if force_drop_ids is None: drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob else: drop_ids = force_drop_ids == 1 labels = torch.where(drop_ids, self.num_classes, labels) return labels
def forward(self, labels, train, force_drop_ids=None): use_dropout = self.dropout_prob > 0 if (train and use_dropout) or (force_drop_ids is not None): labels = self.token_drop(labels, force_drop_ids) embeddings = self.embedding_table(labels) return embeddings
################################################################################## Core DiT Model with mods ##################################################################################
class DiTBlock(nn.Module): def __init__(self, hidden_size, num_heads, mlp_ratio=4.0): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = Attention(hidden_size, num_heads=num_heads) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) return x
class FinalLayer(nn.Module): """ The final layer of DiT. """
def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class NanoDiT(nn.Module): """ Diffusion model with a Transformer backbone. """
def __init__( self, input_size=32, patch_size=2, in_channels=3, hidden_size=384, depth=12, num_heads=6, mlp_ratio=4.0, num_classes=10, timestep_freq_scale=1.0, ): super().__init__() self.in_channels = in_channels self.out_channels = in_channels self.patch_size = patch_size self.num_heads = num_heads self.timestep_freq_scale=timestep_freq_scale
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size) self.t_embedder = TimestepEmbedder(hidden_size) self.y_embedder = LabelEmbedder(num_classes, hidden_size, dropout_prob=0.1) num_patches = self.x_embedder.num_patches # Will use fixed sin-cos embedding: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
self.blocks = nn.ModuleList([DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for i in range(depth)]) self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5)) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1])) if getattr(self.x_embedder.proj, "bias", None) is not None: nn.init.constant_(self.x_embedder.proj.bias, 0)
# Initialize label embedding table: nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in DiT blocks: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) if getattr(self.final_layer.linear, "bias", None) is not None: nn.init.constant_(self.final_layer.linear.bias, 0)
def unpatchify(self, x): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum("nhwpqc->nchpwq", x) imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) return imgs
def forward(self, x, t, y): """ Forward pass of DiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N,) tensor of class labels """ x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2 t = self.t_embedder(t, freq_scale=self.timestep_freq_scale) # (N, D) y = self.y_embedder(y, self.training) # (N, D) c = t + y # (N, D) for block in self.blocks: x = block(x, c=c) # (N, T, D) x = self.final_layer(x, c) x = self.unpatchify(x) # (N, out_channels, H, W) return x
################################################################################## Sine/Cosine Positional Embedding Functions ################################################################################### https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): """ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) """ grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) # here w goes first grid = np.stack(grid, axis=0)
grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): """ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) """ assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2.0 omega = 1.0 / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,) out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2) emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) return emb123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389"""Adapted fromhttps://github.com/facebookresearch/DiT/blob/main/models.py
Implements the `Attention`, `PatchEmbed`, and `Mlp` classeswithout relying on `timm`.
**Modified to support continuous variable conditioning.**"""
import torchimport torch.nn as nnimport numpy as npimport mathimport torch.nn.functional as F
def modulate(x, shift, scale): return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
################################################################################## Patch embedding ##################################################################################
class PatchEmbed(nn.Module): def __init__( self, img_size: int = 224, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, bias: bool = True, ): super().__init__() self.patch_size = patch_size if isinstance(patch_size, tuple) else (patch_size, patch_size) self.img_size = img_size if isinstance(img_size, tuple) else (img_size, img_size) self.grid_size = tuple([s // p for s, p in zip(self.img_size, self.patch_size)]) self.num_patches = self.grid_size[0] * self.grid_size[1]
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias)
def forward(self, x: torch.Tensor): x = self.proj(x) x = x.flatten(2).transpose(1, 2) # NCHW -> NLC return x
################################################################################## Attention ##################################################################################
class Attention(nn.Module): def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, ) -> None: super().__init__() assert dim % num_heads == 0, "dim should be divisible by num_heads" self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x: torch.Tensor) -> torch.Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) x = F.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0, ) x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
################################################################################## MLP ##################################################################################
class Mlp(nn.Module): # Adapted from `timm`. def __init__( self, in_features, hidden_features=None, out_features=None, bias=True, drop=0.0, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features bias = bias if isinstance(bias, tuple) else (bias, bias) drop_probs = drop if isinstance(drop, tuple) else (drop, drop)
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias[0]) self.act = nn.GELU() self.drop1 = nn.Dropout(drop_probs[0]) self.fc2 = nn.Linear(hidden_features, out_features, bias=bias[1]) self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.fc2(x) x = self.drop2(x) return x
################################################################################## Embedding Layers for Timesteps and Cond-Variables ##################################################################################
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__(self, hidden_size, frequency_embedding_size=256, use_bias=True): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=use_bias), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=use_bias), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000, freq_scale=1): """ Create sinusoidal timestep embeddings. """ half = dim // 2 freqs = freq_scale * torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( device=t.device ) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t, freq_scale=1): t_freq = self.timestep_embedding(t, self.frequency_embedding_size, freq_scale=freq_scale) t_emb = self.mlp(t_freq) return t_emb
# NEW: An embedder for the continuous conditioning variablesclass ConditioningEmbedder(nn.Module): """ Embeds conditioning vectors into vector representations. Also handles dropping the conditioning for classifier-free guidance. """ def __init__(self, cond_dim, hidden_size, dropout_prob): super().__init__() self.mlp = nn.Sequential( nn.Linear(cond_dim, hidden_size), nn.SiLU(), nn.Linear(hidden_size, hidden_size) ) self.dropout_prob = dropout_prob self.null_embedding = nn.Parameter(torch.randn(hidden_size))
def forward(self, y_cond, train): """ y_cond: (B, cond_dim) tensor of conditioning vectors train: boolean, whether we are in training mode """ # Project the conditioning vector to the hidden dimension y_emb = self.mlp(y_cond) # (B, hidden_size)
if train and self.dropout_prob > 0: bsz = y_emb.shape[0] mask = torch.rand(bsz, device=y_emb.device) < self.dropout_prob y_emb[mask] = self.null_embedding
is_unconditional = torch.all(y_cond == 0, dim=1) y_emb[is_unconditional] = self.null_embedding
return y_emb
################################################################################## Core DiT Model with mods ##################################################################################
class DiTBlock(nn.Module): def __init__(self, hidden_size, num_heads, mlp_ratio=4.0): super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = Attention(hidden_size, num_heads=num_heads) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) mlp_hidden_dim = int(hidden_size * mlp_ratio) self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, drop=0) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True))
def forward(self, x, c): shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) return x
class FinalLayer(nn.Module): """ The final layer of DiT. """
def __init__(self, hidden_size, patch_size, out_channels): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift, scale) x = self.linear(x) return x
class NanoDiT(nn.Module): """ Diffusion model with a Transformer backbone. **MODIFIED** to accept a continuous conditioning vector. """
def __init__( self, input_size=32, patch_size=2, in_channels=3, hidden_size=384, depth=12, num_heads=6, mlp_ratio=4.0, cond_dim=4, # MODIFIED: from num_classes to cond_dim timestep_freq_scale=1.0, ): super().__init__() self.in_channels = in_channels self.out_channels = in_channels self.patch_size = patch_size self.num_heads = num_heads self.timestep_freq_scale=timestep_freq_scale
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size) self.t_embedder = TimestepEmbedder(hidden_size) # MODIFIED: Use the new ConditioningEmbedder self.y_embedder = ConditioningEmbedder(cond_dim, hidden_size, dropout_prob=0.1) num_patches = self.x_embedder.num_patches # Will use fixed sin-cos embedding: self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
self.blocks = nn.ModuleList([DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for i in range(depth)]) self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels) self.initialize_weights()
def initialize_weights(self): # Initialize transformer layers: def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(_basic_init)
# Initialize (and freeze) pos_embed by sin-cos embedding: pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches**0.5)) self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): w = self.x_embedder.proj.weight.data nn.init.xavier_uniform_(w.view([w.shape[0], -1])) if getattr(self.x_embedder.proj, "bias", None) is not None: nn.init.constant_(self.x_embedder.proj.bias, 0)
# MODIFIED: Initialize conditioning embedder MLP for layer in self.y_embedder.mlp: if isinstance(layer, nn.Linear): nn.init.normal_(layer.weight, std=0.02) nn.init.constant_(layer.bias, 0) # Initialize null embedding nn.init.normal_(self.y_embedder.null_embedding, std=0.02)
# Initialize timestep embedding MLP: nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
# Zero-out adaLN modulation layers in DiT blocks: for block in self.blocks: nn.init.constant_(block.adaLN_modulation[-1].weight, 0) nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
# Zero-out output layers: nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) nn.init.constant_(self.final_layer.linear.weight, 0) if getattr(self.final_layer.linear, "bias", None) is not None: nn.init.constant_(self.final_layer.linear.bias, 0)
def unpatchify(self, x): """ x: (N, T, patch_size**2 * C) imgs: (N, H, W, C) """ c = self.out_channels p = self.x_embedder.patch_size[0] h = w = int(x.shape[1] ** 0.5) assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) x = torch.einsum("nhwpqc->nchpwq", x) imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) return imgs
def forward(self, x, t, y): """ Forward pass of DiT. x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) t: (N,) tensor of diffusion timesteps y: (N, cond_dim) tensor of conditioning vectors """ x = self.x_embedder(x) + self.pos_embed # (N, T, D) t = self.t_embedder(t, freq_scale=self.timestep_freq_scale) # (N, D) y = self.y_embedder(y, self.training) # (N, D) c = t + y # (N, D) for block in self.blocks: x = block(x, c=c) # (N, T, D) x = self.final_layer(x, c) x = self.unpatchify(x) # (N, out_channels, H, W) return x
################################################################################## Sine/Cosine Positional Embedding Functions ################################################################################### https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): grid_h = np.arange(grid_size, dtype=np.float32) grid_w = np.arange(grid_size, dtype=np.float32) grid = np.meshgrid(grid_w, grid_h) grid = np.stack(grid, axis=0) grid = grid.reshape([2, 1, grid_size, grid_size]) pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) if cls_token and extra_tokens > 0: pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0) return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid): assert embed_dim % 2 == 0 emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) emb = np.concatenate([emb_h, emb_w], axis=1) return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): assert embed_dim % 2 == 0 omega = np.arange(embed_dim // 2, dtype=np.float64) omega /= embed_dim / 2.0 omega = 1.0 / 10000**omega pos = pos.reshape(-1) out = np.einsum("m,d->md", pos, omega) emb_sin = np.sin(out) emb_cos = np.cos(out) emb = np.concatenate([emb_sin, emb_cos], axis=1) return emb1234567891011121314151617181920212223242526272829303132333435363738import torch.nn.functional as Fimport torch.nn as nn
class ImageRegressor(nn.Module): def __init__(self, num_outputs=4): super(ImageRegressor, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, padding=1) self.bn1 = nn.BatchNorm2d(32) self.conv2 = nn.Conv2d(32, 64, 3, padding=1) self.bn2 = nn.BatchNorm2d(64) self.conv3 = nn.Conv2d(64, 128, 3, padding=1) self.bn3 = nn.BatchNorm2d(128) self.pool = nn.MaxPool2d(2, 2) self.dropout_conv = nn.Dropout2d(0.25) self.dropout_fc = nn.Dropout(0.5) self.fc1 = nn.Linear(128 * 8 * 8, 512) self.fc2 = nn.Linear(512, 128) self.fc3 = nn.Linear(128, num_outputs) def forward(self, x): x = self.pool(F.relu(self.bn1(self.conv1(x)))) x = self.dropout_conv(x) x = self.pool(F.relu(self.bn2(self.conv2(x)))) x = self.dropout_conv(x) x = self.pool(F.relu(self.bn3(self.conv3(x)))) x = self.dropout_conv(x) x = x.view(-1, 128 * 8 * 8) x = F.relu(self.fc1(x)) x = self.dropout_fc(x) x = F.relu(self.fc2(x)) x = self.dropout_fc(x) x = self.fc3(x) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201import torchimport torch.nn as nnimport torch.optim as optimfrom model import DiTfrom torch.utils.data import DataLoader, Datasetimport torchvision.transforms as transformsimport torchvisionfrom contextlib import nullcontextfrom tqdm import tqdmimport numpy as npimport osfrom dataset import DiffusionDataset, diffusion_transforms
torch.set_float32_matmul_precision("high")
# --- Hyperparameters ---NUM_CLASSES = 3 IMG_SIZE = 64IMG_CHANNELS = 1 # DiT specific parametersLATENT_DIM = 512PATCH_SIZE = 2MODEL_DEPTH = 6MODEL_HEADS = 8# Diffusion process parametersNUM_ODE_STEPS = 150# Training parametersLEARNING_RATE = 1e-5BATCH_SIZE = 128EPOCHS = 300DEVICE = "cuda" if torch.cuda.is_available() else "cpu"COMPILE = TrueAMP_DTYPE = torch.float32 # automatic mixed-precision unless you wanna touch grass# Sampling parametersSAMPLE_INTERVAL = 1 # Sample every N epochsNUM_SAMPLES_PER_CLASS = 4 # Number of images to sample per class during evaluationCFG_SCALE = 2.0# OthersCHECKPOINT_SAVE_INTERVAL = 3DATA_DIR = "/speech/advait/rooshil/nanoDiT/Model_II_normalized" # Directory where the dataset is stored.SAVE_DIR = "diffusion_training_og"os.makedirs(SAVE_DIR, exist_ok=True)
# --- Helper functions for flow-matching math ---def flow_lerp(x): bsz = x.shape[0] t = torch.rand((bsz,)).to(x.device) t_broadcast = t.view(bsz, 1, 1, 1) z1 = torch.randn_like(x) # the flow-matching lerp zt = (1 - t_broadcast) * x + t_broadcast * z1 return zt, z1, t
# --- Sampling function (Euler) ---@torch.no_grad()def sample_conditional_cfg( model, target_classes_list, ode_steps, cfg_scale=5.0, num_samples_per_cls=1, null_token_id=NUM_CLASSES): """Generate images for specified target classes using CFG.""" model.eval() num_target_cls = len(target_classes_list) total_images_to_sample = num_samples_per_cls * num_target_cls
# Initial state z = torch.randn((total_images_to_sample, IMG_CHANNELS, IMG_SIZE, IMG_SIZE), device=DEVICE)
# Prepare conditional labels sample_cls_labels_list = [] for c_idx in target_classes_list: sample_cls_labels_list.extend([c_idx] * num_samples_per_cls) conditional_labels = torch.tensor(sample_cls_labels_list, device=DEVICE).long()
# CFG stuff using_cfg = cfg_scale >= 1.0 y = conditional_labels if using_cfg: n = conditional_labels.shape[0] y_null = torch.tensor([null_token_id] * n, device=conditional_labels.device) y = torch.cat([y, y_null], 0)
# ODE derivative term bsz = z.shape[0] dt = 1.0 / ode_steps dt = torch.tensor([dt] * bsz).to(z.device).view([bsz, *([1] * len(z.shape[1:]))]) # Flow-sampling for i in range(ode_steps, 0, -1): z_final = torch.cat([z, z], 0) if using_cfg else z t = i / ode_steps t = torch.tensor([t] * z_final.shape[0]).to(z_final.device, dtype=z_final.dtype) predicted_velocity = model(z_final, t, y) if using_cfg: pred_cond, pred_uncond = predicted_velocity.chunk(2, dim=0) predicted_velocity = pred_uncond + cfg_scale * (pred_cond - pred_uncond) # Euler step z = (z - dt * predicted_velocity).to(z.dtype) images = (z + 1) / 2.0 # De-normalize from [-1, 1] to [0, 1] images = torch.clamp(images, 0.0, 1.0)
model.train() # Set model to train. return images, conditional_labels
def train(): # --- Model Instantiation --- model = DiT( input_size=IMG_SIZE, patch_size=PATCH_SIZE, in_channels=IMG_CHANNELS, hidden_size=LATENT_DIM, depth=MODEL_DEPTH, num_heads=MODEL_HEADS, num_classes=NUM_CLASSES, timestep_freq_scale=1000, ).to(DEVICE) if COMPILE: print("`torch.compile()` enabled.") model.compile()
# --- Optimizer and loss --- optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE) scaler = torch.GradScaler() if AMP_DTYPE is not None else None criterion = nn.MSELoss() amp_context = ( torch.autocast(device_type=torch.device(DEVICE).type, dtype=AMP_DTYPE) if AMP_DTYPE is not None else nullcontext() ) if AMP_DTYPE: print(f"Using automatic mixed-precision in {AMP_DTYPE} (change if needed).")
# --- Dataset and DataLoader --- train_dataset = DiffusionDataset(DATA_DIR, transform=diffusion_transforms) train_classes = list(set(train_dataset.class_to_idx.values())) assert NUM_CLASSES == len(train_classes) train_dataloader = DataLoader( train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, # Adjust based on your system pin_memory=True, # Useful when training on GPU drop_last=True, prefetch_factor=2, # Adjust based on your system )
# --- Training Loop --- print(f"Training on {DEVICE}") print(f"Using custom model: {type(model).__name__}") print(f"Model Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}") for epoch in range(EPOCHS): model.train() for step, (real_images, class_ids) in enumerate(tqdm(train_dataloader, desc=f"Epoch {epoch+1}/{EPOCHS}")): optimizer.zero_grad() real_images = real_images.to(DEVICE, non_blocking=True) # Shape: (B, C, H, W) class_ids = class_ids.to(DEVICE, non_blocking=True) # Shape: (B,)
# 1. Interpolate between clean data and noise zt, z1, t = flow_lerp(real_images) # 2. Target velocity: u_t = x1 - x0 target_velocity_field = z1 - real_images with amp_context: # 3. Predict velocity using the model predicted_velocity = model(zt, t, class_ids) # 4. Calculate loss loss = criterion(target_velocity_field, predicted_velocity) # 5. Backpropagate and update weights if scaler is not None: scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() else: loss.backward() optimizer.step()
print(f"Epoch [{epoch + 1}/{EPOCHS}], Step [{step + 1}/{len(train_dataloader)}], Loss: {loss.item():.4f}")
# --- Perform Sampling and Save Images (Intermediate Evaluation) --- if (epoch + 1) % SAMPLE_INTERVAL == 0 or epoch == EPOCHS - 1: print(f"\nSampling images at epoch {epoch + 1}...") classes_to_sample_list = list(range(min(NUM_CLASSES, 5))) generated_sample_images, _ = sample_conditional_cfg( model, classes_to_sample_list, ode_steps=NUM_ODE_STEPS, cfg_scale=CFG_SCALE, num_samples_per_cls=NUM_SAMPLES_PER_CLASS ) # Save as a grid if generated_sample_images.nelement() > 0: # Check if any images were generated grid = torchvision.utils.make_grid(generated_sample_images, nrow=NUM_SAMPLES_PER_CLASS) torchvision.utils.save_image(grid, f"{SAVE_DIR}/sample_epoch_{epoch + 1}.png") print(f"Saved sample images to sample_epoch_{epoch + 1}.png") print("-" * 30)
# Optional: Save model checkpoint if (epoch + 1) % CHECKPOINT_SAVE_INTERVAL == 0: torch.save(model.state_dict(), f"{SAVE_DIR}/dit_conditional_epoch_{epoch + 1}.pth")
print("Training finished.")
if __name__ == "__main__": train()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""Thanks to Gemini 2.5 for pairing here and there.**Modified to train a model conditioned on continuous variables.**"""
import torchimport torch.nn as nnimport torch.optim as optimfrom model import DiT from torch.utils.data import DataLoaderfrom contextlib import nullcontextfrom tqdm import tqdmimport torchvisionimport osimport refrom dataset import VariableDataset, diffusion_transforms
# Assuming your new dataset loader is ready.# from dataset import YourNewDiffusionDataset, diffusion_transforms# For demonstration, we'll use a placeholder.from torch.utils.data import TensorDataset
torch.set_float32_matmul_precision("high")
# --- Hyperparameters ---COND_SIZE = 4 # MODIFIED: Dimension of the conditioning vector (4 float values)IMG_SIZE = 64IMG_CHANNELS = 1# DiT specific parametersLATENT_DIM = 512PATCH_SIZE = 2MODEL_DEPTH = 6MODEL_HEADS = 8# Diffusion process parametersNUM_ODE_STEPS = 100# Training parametersLEARNING_RATE = 1e-5BATCH_SIZE = 128EPOCHS = 300DEVICE = "cuda:7" if torch.cuda.is_available() else "cpu"COMPILE = TrueAMP_DTYPE = torch.float32 if torch.cuda.is_available() else torch.bfloat16# Sampling parametersSAMPLE_INTERVAL = 3 # Sample every N epochsNUM_SAMPLES_PER_VECTOR = 4 # Number of images to sample for each conditioning vectorCFG_SCALE = 2.0# OthersCHECKPOINT_SAVE_INTERVAL = 3DATA_DIR = "/speech/advait/rooshil/nanoDiT/cdm_regress_multi_param_normalized" # MODIFIED: Update with your dataset pathSAVE_DIR = "diffusion_training_variable_conditioned"os.makedirs(SAVE_DIR, exist_ok=True)
# --- Helper functions for flow-matching math ---def flow_lerp(x): bsz = x.shape[0] t = torch.rand((bsz,)).to(x.device) t_broadcast = t.view(bsz, 1, 1, 1) z1 = torch.randn_like(x) # the flow-matching lerp zt = (1 - t_broadcast) * x + t_broadcast * z1 return zt, z1, t
# --- Sampling function (Euler) ---@torch.no_grad()def sample_conditional_cfg( model, conditioning_vectors, ode_steps=100, cfg_scale=5.0): """ Generate images for specified conditioning vectors using CFG. conditioning_vectors: A tensor of shape (N, cond_size) """ model.eval() num_samples = conditioning_vectors.shape[0]
# Initial state z = torch.randn((num_samples, IMG_CHANNELS, IMG_SIZE, IMG_SIZE), device=DEVICE)
# Prepare conditional vectors y = conditioning_vectors.to(DEVICE).float()
# For CFG, create a batch of unconditional inputs (zeros) using_cfg = cfg_scale >= 1.0 if using_cfg: y_null = torch.zeros_like(y) y = torch.cat([y, y_null], 0)
# ODE derivative term dt = 1.0 / ode_steps dt_tensor = torch.tensor([dt], device=z.device).view(1, *([1] * (z.dim() - 1)))
# Flow-sampling for i in range(ode_steps, 0, -1): z_final = torch.cat([z, z], 0) if using_cfg else z t = torch.full((z_final.shape[0],), i / ode_steps, device=z_final.device, dtype=z_final.dtype) predicted_velocity = model(z_final, t, y)
if using_cfg: pred_cond, pred_uncond = predicted_velocity.chunk(2, dim=0) predicted_velocity = pred_uncond + cfg_scale * (pred_cond - pred_uncond)
# Euler step z = z - dt_tensor * predicted_velocity z = z.to(z.dtype) #
images = (z + 1) / 2.0 # De-normalize from [-1, 1] to [0, 1] images = torch.clamp(images, 0.0, 1.0)
model.train() return images
def train(): # --- Model Instantiation --- model = NanoDiT( input_size=IMG_SIZE, patch_size=PATCH_SIZE, in_channels=IMG_CHANNELS, hidden_size=LATENT_DIM, depth=MODEL_DEPTH, num_heads=MODEL_HEADS, cond_size=COND_SIZE, timestep_freq_scale=1000, label_conditioning=False ).to(DEVICE) start_epoch = 0 checkpoint_files = [f for f in os.listdir(SAVE_DIR) if f.endswith('.pth')] if checkpoint_files: latest_checkpoint_file = max( checkpoint_files, key=lambda f: int(re.search(r'(\d+)', f).group()) ) latest_checkpoint_path = os.path.join(SAVE_DIR, latest_checkpoint_file)
try: # Extract the epoch number from the filename to resume training start_epoch = int(re.search(r'(\d+)', latest_checkpoint_file).group()) print(f"Resuming training from checkpoint: {latest_checkpoint_path}") # Load the model's state dictionary model.load_state_dict(torch.load(latest_checkpoint_path, map_location=DEVICE)) print(f"✅ Successfully loaded checkpoint. Resuming from epoch {start_epoch + 1}.") except Exception as e: print(f"❌ Could not load checkpoint: {e}. Starting training from scratch.") start_epoch = 0 else: print("No checkpoints found. Starting training from scratch.") if COMPILE: print("`torch.compile()` enabled.") model = torch.compile(model)
# --- Optimizer and loss --- optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE) scaler = torch.amp.GradScaler() if AMP_DTYPE is not None and DEVICE.startswith("cuda") else None criterion = nn.MSELoss() amp_context = ( torch.autocast(device_type=torch.device(DEVICE).type, dtype=AMP_DTYPE) if AMP_DTYPE is not None and scaler is not None else nullcontext() ) if AMP_DTYPE and scaler: print(f"Using automatic mixed-precision in {AMP_DTYPE}.")
# train_dataset = YourNewDiffusionDataset(DATA_DIR, transform=diffusion_transforms) train_dataset = VariableDataset(DATA_DIR, transform=diffusion_transforms) train_dataloader = DataLoader( train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=4, pin_memory=True, drop_last=True, )
# --- Training Loop --- print(f"Training on {DEVICE}") print(f"Using custom model: {type(model).__name__}") print(f"Model Parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}")
for epoch in range(start_epoch, EPOCHS): model.train() for step, (real_images, cond_vectors) in enumerate(tqdm(train_dataloader, desc=f"Epoch {epoch+1}/{EPOCHS}")): optimizer.zero_grad() real_images = real_images.to(DEVICE, non_blocking=True) cond_vectors = cond_vectors.to(DEVICE, non_blocking=True).float() # Ensure it's float
# 1. Interpolate between clean data and noise zt, z1, t = flow_lerp(real_images) # 2. Target velocity: u_t = z1 - x0 target_velocity_field = z1 - real_images
with amp_context: # 3. Predict velocity using the model with conditioning vectors predicted_velocity = model(zt, t, cond_vectors) # 4. Calculate loss loss = criterion(target_velocity_field, predicted_velocity)
# 5. Backpropagate and update weights if scaler is not None: scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() else: loss.backward() optimizer.step()
# if step % 50 == 0: # Print less frequently print(f"Epoch [{epoch + 1}/{EPOCHS}], Step [{step + 1}/{len(train_dataloader)}], Loss: {loss.item():.4f}")
# --- Perform Sampling and Save Images (Intermediate Evaluation) --- if (epoch + 1) % SAMPLE_INTERVAL == 0 or epoch == EPOCHS - 1: print(f"\nSampling images at epoch {epoch + 1}...") # MODIFIED: Create a list of conditioning vectors to sample. # You should replace these with meaningful values for your use case. sample_vectors = torch.tensor([ [1.2815, -0.1781, 0.2004, 1.5728], [1.2815, -0.1019, -0.2664, -0.4410], [1.2815, 0.0671, -0.3282, -1.4732], [1.2815, 0.3388, -0.2729, 1.4220], ], device=DEVICE).float()
# Repeat each vector to get multiple samples per vector sample_vectors_repeated = sample_vectors.repeat_interleave(NUM_SAMPLES_PER_VECTOR, dim=0)
generated_sample_images = sample_conditional_cfg( model, sample_vectors_repeated, ode_steps=NUM_ODE_STEPS, cfg_scale=CFG_SCALE ) # Save as a grid if generated_sample_images.nelement() > 0: grid = torchvision.utils.make_grid(generated_sample_images, nrow=NUM_SAMPLES_PER_VECTOR) torchvision.utils.save_image(grid, f"{SAVE_DIR}/sample_epoch_{epoch + 1}.png") print(f"Saved sample images to {SAVE_DIR}/sample_epoch_{epoch + 1}.png") print("-" * 30)
# Optional: Save model checkpoint if (epoch + 1) % CHECKPOINT_SAVE_INTERVAL == 0: # Unwrap the compiled model before saving the state_dict model_to_save = model._orig_mod if COMPILE else model torch.save(model_to_save.state_dict(), f"{SAVE_DIR}/dit_variable_cond_epoch_{epoch + 1}.pth")
print("Training finished.")
if __name__ == "__main__": train()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142"""Shared helpers for the FlowLensing evaluation scripts.
Normalization contract----------------------Images are stored as raw simulation output in physical brightness units. Everyevaluation 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 alreadynormalized offline."""import numpy as npimport torchimport 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""3-class evaluation: can a classifier tell generated images apart correctly?
WARNING: the preprocessing here is reconstructed, not recovered -- the originalevaluation script did not run. On a short CPU smoke test this scored at chance,which may be too few ODE steps or may be wrong preprocessing; it could not bechecked against real images because none survive. See README "Known gaps".
Generates images for each dark matter class and reports accuracy, per-classAUC and the confusion matrix, using the ResNet trained on real images.
python eval_classify.py --flow-ckpt X.pth --classifier-ckpt Y.pt --arch resnet34"""import argparse, os, sysimport numpy as npimport torchimport torch.nn.functional as Ffrom tqdm import tqdmfrom sklearn.metrics import (accuracy_score, roc_curve, auc, confusion_matrix, classification_report)from sklearn.preprocessing import label_binarize
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "code"))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from common import (load_flow_model, load_classifier, sample_cfg, pick_device, to_imagenet_rgb, load_npy_image)
CLASS_NAMES = ["axion", "cdm", "no_sub"]
def classify(clf, imgs01, device): with torch.no_grad(): return F.softmax(clf(to_imagenet_rgb(imgs01.to(device))), dim=1).cpu().numpy()
def main(): ap = argparse.ArgumentParser() ap.add_argument("--flow-ckpt", help="generate samples with this model") ap.add_argument("--real-data", help="instead, classify real .npy under <dir>/<class>/") ap.add_argument("--classifier-ckpt", required=True) ap.add_argument("--arch", default="resnet34", choices=["resnet18", "resnet34"]) ap.add_argument("--n-per-class", type=int, default=400) ap.add_argument("--batch-size", type=int, default=50) ap.add_argument("--ode-steps", type=int, default=100) ap.add_argument("--cfg-scale", type=float, default=2.0) ap.add_argument("--device", default="auto") ap.add_argument("--seed", type=int, default=0) args = ap.parse_args() if not args.flow_ckpt and not args.real_data: raise SystemExit("pass --flow-ckpt (generated) or --real-data (real)")
torch.manual_seed(args.seed) device = pick_device(args.device) print(f"device: {device}") clf = load_classifier(args.classifier_ckpt, args.arch, device)
probs, labels = [], [] if args.flow_ckpt: flow = load_flow_model(args.flow_ckpt, "class", device) for cid, cname in enumerate(CLASS_NAMES): for i in tqdm(range(0, args.n_per_class, args.batch_size), desc=f"gen {cname}"): b = min(args.batch_size, args.n_per_class - i) cond = torch.full((b,), cid, dtype=torch.long) imgs = sample_cfg(flow, cond, args.ode_steps, args.cfg_scale, device) probs.append(classify(clf, imgs, device)) labels.extend([cid] * b) else: for cid, cname in enumerate(CLASS_NAMES): d = os.path.join(args.real_data, cname) files = sorted(f for f in os.listdir(d) if f.endswith(".npy"))[: args.n_per_class] for i in tqdm(range(0, len(files), args.batch_size), desc=f"real {cname}"): batch = torch.stack([load_npy_image(os.path.join(d, f)) for f in files[i : i + args.batch_size]]) probs.append(classify(clf, batch, device)) labels.extend([cid] * batch.shape[0])
probs = np.concatenate(probs) y = np.array(labels) pred = probs.argmax(1)
print(f"\nAccuracy: {accuracy_score(y, pred):.4f}\n") print(classification_report(y, pred, target_names=CLASS_NAMES, digits=4)) yb = label_binarize(y, classes=[0, 1, 2]) print("Per-class AUC:") aucs = [] for i, name in enumerate(CLASS_NAMES): fpr, tpr, _ = roc_curve(yb[:, i], probs[:, i]) a = auc(fpr, tpr) aucs.append(a) print(f" {name:8s} {a:.4f}") print(f" {'macro':8s} {np.mean(aucs):.4f}") print("\nConfusion matrix (rows = true, cols = predicted):") print(" " + "".join(f"{c:>9s}" for c in CLASS_NAMES)) for name, row in zip(CLASS_NAMES, confusion_matrix(y, pred)): print(f" {name:8s} " + "".join(f"{v:9d}" for v in row))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445"""FID between a directory of real .npy images and a directory of generated ones.
python eval_fid.py --real DIR --generated DIR"""import argparse, os, sysimport torchfrom tqdm import tqdmfrom torchmetrics.image.fid import FrechetInceptionDistance
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "code"))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from common import load_npy_image, pick_device
def feed(fid, directory, real, batch_size, device): files = sorted(f for f in os.listdir(directory) if f.endswith(".npy")) if not files: raise SystemExit(f"no .npy files in {directory}") for i in tqdm(range(0, len(files), batch_size), desc=("real" if real else "generated")): batch = torch.stack([load_npy_image(os.path.join(directory, f)) for f in files[i : i + batch_size]]) fid.update(batch.repeat(1, 3, 1, 1).to(device), real=real) return len(files)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--real", required=True) ap.add_argument("--generated", required=True) ap.add_argument("--batch-size", type=int, default=50) ap.add_argument("--device", default="auto") args = ap.parse_args()
device = pick_device(args.device) print(f"device: {device}") # normalize=True: inputs are on [0,1], which is what FID expects here. fid = FrechetInceptionDistance(normalize=True).to(device) n_real = feed(fid, args.real, True, args.batch_size, device) n_gen = feed(fid, args.generated, False, args.batch_size, device) print(f"\n{n_real} real / {n_gen} generated") print(f"FID: {fid.compute().item():.4f}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""PSNR / SSIM between paired real and generated images (matched by filename).
NOTE: the original script that produced the PSNR and SSIM numbers in the paperis not present in the recovered project. This is a standard reimplementationusing torchmetrics; treat its output as indicative, not as the paper's exactprocedure.
python eval_image_quality.py --real DIR --generated DIR"""import argparse, os, sysimport torchfrom tqdm import tqdmfrom torchmetrics.functional import peak_signal_noise_ratio as psnrfrom torchmetrics.functional import structural_similarity_index_measure as ssim
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "code"))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from common import load_npy_image, pick_device
def main(): ap = argparse.ArgumentParser() ap.add_argument("--real", required=True) ap.add_argument("--generated", required=True) ap.add_argument("--device", default="auto") args = ap.parse_args()
device = pick_device(args.device) shared = sorted(set(f for f in os.listdir(args.real) if f.endswith(".npy")) & set(f for f in os.listdir(args.generated) if f.endswith(".npy"))) if not shared: raise SystemExit("no filenames common to both directories; " "generated samples must be saved under the real filename") print(f"device: {device} | {len(shared)} paired images")
ps, ss = [], [] for f in tqdm(shared): r = load_npy_image(os.path.join(args.real, f)).unsqueeze(0).to(device) g = load_npy_image(os.path.join(args.generated, f)).unsqueeze(0).to(device) ps.append(psnr(g, r, data_range=1.0).item()) ss.append(ssim(g, r, data_range=1.0).item())
print(f"\nPSNR: {sum(ps)/len(ps):.4f}") print(f"SSIM: {sum(ss)/len(ss):.6f}")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Parameter-conditioned evaluation.
Generates an image for each test conditioning vector, runs the trainedImageRegressor on it, and reports how well the recovered parameters match theones the sample was conditioned on (per-parameter MSE / MAE / RMSE / R2).
python eval_regression.py --data DIR --flow-ckpt X.pth --regressor-ckpt Y.pt"""import argparse, os, sysimport numpy as npimport torchfrom tqdm import tqdmfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "code"))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from common import load_flow_model, load_regressor, sample_cfg, pick_device, minmax_to_unit
PARAM_NAMES = ["Einstein radius", "x", "y", "slope beta"]
def main(): ap = argparse.ArgumentParser() ap.add_argument("--data", required=True, help="dir of .npy samples (image + 4 params)") ap.add_argument("--flow-ckpt", required=True) ap.add_argument("--regressor-ckpt", required=True) ap.add_argument("--n", type=int, default=1000) ap.add_argument("--batch-size", type=int, default=50) ap.add_argument("--ode-steps", type=int, default=100) ap.add_argument("--cfg-scale", type=float, default=2.0) ap.add_argument("--device", default="auto") ap.add_argument("--seed", type=int, default=0) args = ap.parse_args()
torch.manual_seed(args.seed) device = pick_device(args.device) print(f"device: {device}")
flow = load_flow_model(args.flow_ckpt, "param", device) reg = load_regressor(args.regressor_ckpt, device)
files = sorted(f for f in os.listdir(args.data) if f.endswith(".npy"))[: args.n] if not files: raise SystemExit(f"no .npy files in {args.data}") print(f"evaluating {len(files)} samples")
conds = [] for f in files: d = np.load(os.path.join(args.data, f), allow_pickle=True) conds.append(np.asarray(d[1:5], dtype=np.float32)) conds = torch.from_numpy(np.stack(conds))
preds = [] for i in tqdm(range(0, len(conds), args.batch_size), desc="sampling"): batch = conds[i : i + args.batch_size] imgs = sample_cfg(flow, batch, args.ode_steps, args.cfg_scale, device) imgs = torch.stack([minmax_to_unit(im) for im in imgs]) with torch.no_grad(): preds.append(reg(imgs).cpu()) preds = torch.cat(preds).numpy() actual = conds.numpy()
print("\nPer-Parameter Metrics (conditioned value vs. value recovered from the generated image)") print("-" * 78) for i, name in enumerate(PARAM_NAMES): a, p = actual[:, i], preds[:, i] rng = a.max() - a.min() mae = mean_absolute_error(a, p) print(f"{name}:") print(f" Range: [{a.min():.3f}, {a.max():.3f}]") print(f" MSE: {mean_squared_error(a, p):.6f}") print(f" MAE: {mae:.6f}" + (f" ({mae / rng * 100:.1f}% of range)" if rng > 0 else " (constant parameter)")) print(f" RMSE: {np.sqrt(mean_squared_error(a, p)):.6f}") print(f" R2: {r2_score(a, p):.6f}" if rng > 0 else " R2: n/a (constant parameter)") print()
if __name__ == "__main__": main()1234567torch>=2.0torchvision>=0.15timmnumpyscikit-learntorchmetrics[image]tqdmREADME.mdAdded+136
checkpoints/eval_classifier_resnet34.ptAdded+3
checkpoints/eval_regressor.ptAdded+3
checkpoints/flowlensing_dit_class_cond.pthAdded+3
checkpoints/flowlensing_dit_param_cond.pthAdded+3
code/dataset.pyAdded+131
code/latency.pyAdded+120
code/model.pyAdded+405
code/model_regress.pyAdded+389
code/regression_model.pyAdded+38
code/train_og.pyAdded+201
code/train_regress.pyAdded+246
evals/common.pyAdded+142
evals/eval_classify.pyAdded+98
evals/eval_fid.pyAdded+45
evals/eval_image_quality.pyAdded+48
evals/eval_regression.pyAdded+79
requirements.txtAdded+7