Upload 6-parameter conditional DDPM (HI emulation, CAMELS LH params_6, best checkpoint)
Browse files- README.md +146 -0
- args.json +38 -0
- args.txt +28 -0
- config.json +24 -0
- inference_example.py +290 -0
- model.pt +3 -0
- src/__init__.py +0 -0
- src/dataset_conditional.py +130 -0
- src/diffusion_conditional.py +172 -0
- src/evaluate_conditional.py +436 -0
- src/unet_conditional.py +179 -0
README.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
tags:
|
| 5 |
+
- diffusion
|
| 6 |
+
- ddpm
|
| 7 |
+
- ddim
|
| 8 |
+
- cosmology
|
| 9 |
+
- astrophysics
|
| 10 |
+
- camels
|
| 11 |
+
- emulator
|
| 12 |
+
- conditional-generation
|
| 13 |
+
pipeline_tag: unconditional-image-generation
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# DDPM HI Emulator — 6 Parameter (CAMELS LH)
|
| 17 |
+
|
| 18 |
+
A conditional Denoising Diffusion Probabilistic Model (DDPM) that emulates
|
| 19 |
+
**neutral-hydrogen (HI) 2D maps** from the CAMELS Latin-Hypercube (LH)
|
| 20 |
+
simulation suite, conditioned on the **full 6 CAMELS LH parameters**
|
| 21 |
+
(Ωm, σ8, ASN1, AAGN1, ASN2, AAGN2). Sampling supports both full DDPM and
|
| 22 |
+
accelerated DDIM.
|
| 23 |
+
|
| 24 |
+
This is the **best-validation checkpoint** from the training run under
|
| 25 |
+
`ddpm_hi_lh6/outputs_conditional_6param_20260413_132226/`.
|
| 26 |
+
|
| 27 |
+
## Files in this repo
|
| 28 |
+
|
| 29 |
+
| File | Purpose |
|
| 30 |
+
|------|---------|
|
| 31 |
+
| `model.pt` | PyTorch checkpoint (state-dict for `ConditionalDiffusionModel`) |
|
| 32 |
+
| `args.json` / `args.txt` | Training hyper-parameters and U-Net configuration |
|
| 33 |
+
| `config.json` | Architecture summary (for Hub discoverability) |
|
| 34 |
+
| `src/unet_conditional.py` | `ConditionalUNet` module |
|
| 35 |
+
| `src/diffusion_conditional.py` | `GaussianDiffusion` (DDPM + DDIM) and the wrapping `ConditionalDiffusionModel` |
|
| 36 |
+
| `src/dataset_conditional.py` | Helper for loading CAMELS LH data + label normalisation stats |
|
| 37 |
+
| `src/evaluate_conditional.py` | Reference evaluation pipeline (samples + metrics) |
|
| 38 |
+
| `inference_example.py` | Runnable example: downloads weights and generates a sample |
|
| 39 |
+
|
| 40 |
+
## Architecture
|
| 41 |
+
|
| 42 |
+
Conditional U-Net + Gaussian diffusion process. Hyper-parameters (taken from
|
| 43 |
+
`args.json`):
|
| 44 |
+
|
| 45 |
+
| Field | Value |
|
| 46 |
+
|-------|-------|
|
| 47 |
+
| `label_dim` | 6 |
|
| 48 |
+
| `base_channels` | 64 |
|
| 49 |
+
| `channel_multipliers` | [1, 2, 4, 8] |
|
| 50 |
+
| `attention_levels` | [2, 3] |
|
| 51 |
+
| `dropout` | 0.1 |
|
| 52 |
+
| `timesteps` | 1500 (linear β schedule: 1e-4 → 0.02) |
|
| 53 |
+
| EMA decay | 0.9999 |
|
| 54 |
+
| Mixed precision | Yes (`use_amp = true` during training) |
|
| 55 |
+
| Sampler | DDIM, 50 steps (DDPM also supported) |
|
| 56 |
+
| Image size | 256 × 256, single channel |
|
| 57 |
+
| Image range | [-1, 1] (training data is rescaled by `x * 2 - 1`) |
|
| 58 |
+
|
| 59 |
+
Labels are z-scored using the **training-split** mean / std. The
|
| 60 |
+
`inference_example.py` shows how to recover this normalisation from the
|
| 61 |
+
CAMELS LH `params_6` dataset, or you can pass already-normalised conditioning
|
| 62 |
+
values directly.
|
| 63 |
+
|
| 64 |
+
## Quick start
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
from huggingface_hub import hf_hub_download
|
| 68 |
+
import sys, torch, json
|
| 69 |
+
from pathlib import Path
|
| 70 |
+
|
| 71 |
+
# 1) Download all needed files
|
| 72 |
+
repo = "collinsmaripane/ddpm-hi-6param"
|
| 73 |
+
ckpt_path = hf_hub_download(repo, "model.pt")
|
| 74 |
+
args_path = hf_hub_download(repo, "args.json")
|
| 75 |
+
for name in ("unet_conditional.py", "diffusion_conditional.py", "__init__.py"):
|
| 76 |
+
hf_hub_download(repo, f"src/{name}")
|
| 77 |
+
sys.path.insert(0, str(Path(ckpt_path).parent / "src"))
|
| 78 |
+
|
| 79 |
+
from unet_conditional import ConditionalUNet
|
| 80 |
+
from diffusion_conditional import GaussianDiffusion, ConditionalDiffusionModel
|
| 81 |
+
|
| 82 |
+
# 2) Rebuild the model from args.json
|
| 83 |
+
args = json.loads(Path(args_path).read_text())
|
| 84 |
+
unet = ConditionalUNet(
|
| 85 |
+
in_channels=1, out_channels=1,
|
| 86 |
+
label_dim=args["label_dim"],
|
| 87 |
+
base_channels=args["base_channels"],
|
| 88 |
+
channel_multipliers=tuple(args["channel_multipliers"]),
|
| 89 |
+
attention_levels=tuple(args["attention_levels"]),
|
| 90 |
+
dropout=args["dropout"],
|
| 91 |
+
)
|
| 92 |
+
diffusion = GaussianDiffusion(
|
| 93 |
+
timesteps=args["timesteps"],
|
| 94 |
+
beta_start=args["beta_start"],
|
| 95 |
+
beta_end=args["beta_end"],
|
| 96 |
+
schedule_type=args["schedule_type"],
|
| 97 |
+
)
|
| 98 |
+
model = ConditionalDiffusionModel(unet, diffusion)
|
| 99 |
+
|
| 100 |
+
# 3) Load the checkpoint and sample
|
| 101 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 102 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 103 |
+
model.eval()
|
| 104 |
+
|
| 105 |
+
# 6-parameter conditioning vector (order: Ωm, σ8, ASN1, AAGN1, ASN2, AAGN2),
|
| 106 |
+
# z-scored with training-split stats. See inference_example.py for the helper.
|
| 107 |
+
labels = torch.zeros((1, 6))
|
| 108 |
+
sample = model.sample(labels, channels=1, height=256, width=256,
|
| 109 |
+
device="cpu", use_ddim=True, ddim_steps=50)
|
| 110 |
+
# sample is in [-1, 1]; rescale to physical HI units as needed.
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
For an end-to-end runnable example (including label normalisation, GPU usage,
|
| 114 |
+
and image saving), see `inference_example.py` in this repo.
|
| 115 |
+
|
| 116 |
+
## Training data
|
| 117 |
+
|
| 118 |
+
Trained on **CAMELS LH** HI maps with full 6-parameter conditioning. The
|
| 119 |
+
data layout consumed by `src/dataset_conditional.py` is:
|
| 120 |
+
|
| 121 |
+
```
|
| 122 |
+
<data_dir>/
|
| 123 |
+
train_LH_6.npy, val_LH_6.npy, test_LH_6.npy
|
| 124 |
+
train_labels_LH.npy, val_labels_LH.npy, test_labels_LH.npy
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Images are rescaled to `[-1, 1]`; labels are z-scored using train-split
|
| 128 |
+
statistics. The original training paths on the cluster were
|
| 129 |
+
`/scratch/mrpcol001/Diffusion_job/data/LH_data/params_6`.
|
| 130 |
+
|
| 131 |
+
## Intended use & limitations
|
| 132 |
+
|
| 133 |
+
- Intended for **research** on diffusion emulators for cosmological fields,
|
| 134 |
+
posterior inference, and sensitivity studies across cosmology /
|
| 135 |
+
astrophysics nuisance parameters.
|
| 136 |
+
- The companion **2-parameter** model (`collinsmaripane/ddpm-hi-2param`) is
|
| 137 |
+
available for the simpler 2-label setup.
|
| 138 |
+
- Outputs are 256 × 256 single-channel maps in the model's normalised range.
|
| 139 |
+
Apply the inverse of any data-pipeline preprocessing before physical
|
| 140 |
+
interpretation.
|
| 141 |
+
|
| 142 |
+
## Citation
|
| 143 |
+
|
| 144 |
+
If you use this checkpoint, please cite the CAMELS project and the upstream
|
| 145 |
+
DDPM HI emulation work. (Citation block to be filled in once the
|
| 146 |
+
accompanying paper is published.)
|
args.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"label_dim": 6,
|
| 3 |
+
"base_channels": 64,
|
| 4 |
+
"channel_multipliers": [
|
| 5 |
+
1,
|
| 6 |
+
2,
|
| 7 |
+
4,
|
| 8 |
+
8
|
| 9 |
+
],
|
| 10 |
+
"attention_levels": [
|
| 11 |
+
2,
|
| 12 |
+
3
|
| 13 |
+
],
|
| 14 |
+
"dropout": 0.1,
|
| 15 |
+
"timesteps": 1500,
|
| 16 |
+
"beta_start": 0.0001,
|
| 17 |
+
"beta_end": 0.02,
|
| 18 |
+
"schedule_type": "linear",
|
| 19 |
+
"epochs": 200,
|
| 20 |
+
"batch_size": 8,
|
| 21 |
+
"lr": 0.0002,
|
| 22 |
+
"ema_decay": 0.9999,
|
| 23 |
+
"num_workers": 4,
|
| 24 |
+
"early_stop_patience": 100,
|
| 25 |
+
"use_amp": true,
|
| 26 |
+
"data_dir": "/scratch/mrpcol001/Diffusion_job/data/LH_data/params_6",
|
| 27 |
+
"normalize_labels": true,
|
| 28 |
+
"output_dir": "outputs_conditional_6param",
|
| 29 |
+
"resume": "",
|
| 30 |
+
"resume_refresh_scheduler": false,
|
| 31 |
+
"sample_every": 10,
|
| 32 |
+
"use_ddim": true,
|
| 33 |
+
"ddim_steps": 50,
|
| 34 |
+
"use_wandb": false,
|
| 35 |
+
"wandb_project": "ddpm_cosmology",
|
| 36 |
+
"wandb_entity": "",
|
| 37 |
+
"wandb_run_name": ""
|
| 38 |
+
}
|
args.txt
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
label_dim: 6
|
| 2 |
+
base_channels: 64
|
| 3 |
+
channel_multipliers: [1, 2, 4, 8]
|
| 4 |
+
attention_levels: [2, 3]
|
| 5 |
+
dropout: 0.1
|
| 6 |
+
timesteps: 1500
|
| 7 |
+
beta_start: 0.0001
|
| 8 |
+
beta_end: 0.02
|
| 9 |
+
schedule_type: linear
|
| 10 |
+
epochs: 200
|
| 11 |
+
batch_size: 8
|
| 12 |
+
lr: 0.0002
|
| 13 |
+
ema_decay: 0.9999
|
| 14 |
+
num_workers: 4
|
| 15 |
+
early_stop_patience: 100
|
| 16 |
+
use_amp: True
|
| 17 |
+
data_dir: /scratch/mrpcol001/Diffusion_job/data/LH_data/params_6
|
| 18 |
+
normalize_labels: True
|
| 19 |
+
output_dir: outputs_conditional_6param
|
| 20 |
+
resume:
|
| 21 |
+
resume_refresh_scheduler: False
|
| 22 |
+
sample_every: 10
|
| 23 |
+
use_ddim: True
|
| 24 |
+
ddim_steps: 50
|
| 25 |
+
use_wandb: False
|
| 26 |
+
wandb_project: ddpm_cosmology
|
| 27 |
+
wandb_entity:
|
| 28 |
+
wandb_run_name:
|
config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architecture": "ConditionalUNet + GaussianDiffusion",
|
| 3 |
+
"task": "conditional-image-generation",
|
| 4 |
+
"image_size": 256,
|
| 5 |
+
"in_channels": 1,
|
| 6 |
+
"out_channels": 1,
|
| 7 |
+
"label_dim": 6,
|
| 8 |
+
"base_channels": 64,
|
| 9 |
+
"channel_multipliers": [
|
| 10 |
+
1,
|
| 11 |
+
2,
|
| 12 |
+
4,
|
| 13 |
+
8
|
| 14 |
+
],
|
| 15 |
+
"attention_levels": [
|
| 16 |
+
2,
|
| 17 |
+
3
|
| 18 |
+
],
|
| 19 |
+
"dropout": 0.1,
|
| 20 |
+
"timesteps": 1500,
|
| 21 |
+
"beta_start": 0.0001,
|
| 22 |
+
"beta_end": 0.02,
|
| 23 |
+
"schedule_type": "linear"
|
| 24 |
+
}
|
inference_example.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# ---------------------------------------------------------------------------
|
| 3 |
+
# inference_example.py
|
| 4 |
+
#
|
| 5 |
+
# Self-contained example that downloads a conditional-DDPM checkpoint from
|
| 6 |
+
# the Hugging Face Hub and generates one HI map.
|
| 7 |
+
#
|
| 8 |
+
# Works for **both** uploaded models -- the script picks which one to load
|
| 9 |
+
# from a CLI argument:
|
| 10 |
+
#
|
| 11 |
+
# python inference_example.py --model 2param
|
| 12 |
+
# python inference_example.py --model 6param
|
| 13 |
+
# python inference_example.py --model 2param --repo myuser/my-fork
|
| 14 |
+
# python inference_example.py --model 6param --device cuda --ddim-steps 50
|
| 15 |
+
#
|
| 16 |
+
# The script:
|
| 17 |
+
# 1. Downloads `model.pt`, `args.json`, and the bundled src/*.py files.
|
| 18 |
+
# 2. Imports `ConditionalUNet` and `GaussianDiffusion` from the downloaded
|
| 19 |
+
# code (no need for a separate pip-installed package).
|
| 20 |
+
# 3. Rebuilds the model from `args.json` so weights and architecture
|
| 21 |
+
# cannot drift apart.
|
| 22 |
+
# 4. Samples one image with DDIM (or DDPM, with `--no-ddim`).
|
| 23 |
+
# 5. Saves a `.npy` of the raw [-1, 1] output and a PNG visualisation.
|
| 24 |
+
#
|
| 25 |
+
# This file is bundled inside each HF repo so users can grab a single script
|
| 26 |
+
# and immediately do inference.
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import json
|
| 31 |
+
import sys
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
import torch
|
| 36 |
+
|
| 37 |
+
# huggingface_hub is the only "extra" dependency; everything else (torch,
|
| 38 |
+
# numpy) is already required to run the model.
|
| 39 |
+
from huggingface_hub import hf_hub_download
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# --------------------------------------------------------------------------
|
| 43 |
+
# Defaults -- adjust here or override via CLI flags
|
| 44 |
+
# --------------------------------------------------------------------------
|
| 45 |
+
DEFAULT_REPOS = {
|
| 46 |
+
"2param": "collinsmaripane/ddpm-hi-2param",
|
| 47 |
+
"6param": "collinsmaripane/ddpm-hi-6param",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# All files we expect to find in every uploaded repo. We download each one
|
| 51 |
+
# explicitly (rather than `snapshot_download`) so we can give a clear error
|
| 52 |
+
# message if anything is missing.
|
| 53 |
+
REQUIRED_FILES = [
|
| 54 |
+
"model.pt",
|
| 55 |
+
"args.json",
|
| 56 |
+
"src/__init__.py",
|
| 57 |
+
"src/unet_conditional.py",
|
| 58 |
+
"src/diffusion_conditional.py",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def parse_args() -> argparse.Namespace:
|
| 63 |
+
p = argparse.ArgumentParser(description="Sample one HI map from the HF-hosted DDPM.")
|
| 64 |
+
p.add_argument(
|
| 65 |
+
"--model",
|
| 66 |
+
choices=sorted(DEFAULT_REPOS.keys()),
|
| 67 |
+
required=True,
|
| 68 |
+
help="Which model to download. Picks the matching default HF repo.",
|
| 69 |
+
)
|
| 70 |
+
p.add_argument(
|
| 71 |
+
"--repo",
|
| 72 |
+
default=None,
|
| 73 |
+
help="Override the HF repo id (default: see DEFAULT_REPOS in this file).",
|
| 74 |
+
)
|
| 75 |
+
p.add_argument(
|
| 76 |
+
"--device",
|
| 77 |
+
default="cuda" if torch.cuda.is_available() else "cpu",
|
| 78 |
+
help="Torch device for sampling. Defaults to cuda if available else cpu.",
|
| 79 |
+
)
|
| 80 |
+
p.add_argument(
|
| 81 |
+
"--ddim-steps",
|
| 82 |
+
type=int,
|
| 83 |
+
default=50,
|
| 84 |
+
help="Number of DDIM steps (ignored when --no-ddim).",
|
| 85 |
+
)
|
| 86 |
+
p.add_argument(
|
| 87 |
+
"--no-ddim",
|
| 88 |
+
action="store_true",
|
| 89 |
+
help="Use the full DDPM sampler (slow, all 1500 steps) instead of DDIM.",
|
| 90 |
+
)
|
| 91 |
+
p.add_argument(
|
| 92 |
+
"--seed",
|
| 93 |
+
type=int,
|
| 94 |
+
default=0,
|
| 95 |
+
help="RNG seed for reproducible sampling.",
|
| 96 |
+
)
|
| 97 |
+
p.add_argument(
|
| 98 |
+
"--labels",
|
| 99 |
+
type=float,
|
| 100 |
+
nargs="+",
|
| 101 |
+
default=None,
|
| 102 |
+
help=(
|
| 103 |
+
"Conditioning vector (already z-scored). Length must match label_dim "
|
| 104 |
+
"(2 or 6). If omitted, an all-zeros vector is used (i.e. the training-set mean)."
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
p.add_argument(
|
| 108 |
+
"--output-dir",
|
| 109 |
+
type=Path,
|
| 110 |
+
default=Path("inference_outputs"),
|
| 111 |
+
help="Where to write the generated sample (.npy + .png).",
|
| 112 |
+
)
|
| 113 |
+
return p.parse_args()
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def download_repo(repo_id: str) -> Path:
|
| 117 |
+
"""Download every required file from `repo_id`, return the local cache dir.
|
| 118 |
+
|
| 119 |
+
We rely on `hf_hub_download` to manage caching -- it stores files under
|
| 120 |
+
`~/.cache/huggingface/hub/` and returns the local path. We assume all the
|
| 121 |
+
required files end up in the same directory (which they do, modulo the
|
| 122 |
+
`src/` subfolder).
|
| 123 |
+
"""
|
| 124 |
+
print(f"[inference] Downloading {len(REQUIRED_FILES)} files from {repo_id}")
|
| 125 |
+
local_paths = [Path(hf_hub_download(repo_id, f)) for f in REQUIRED_FILES]
|
| 126 |
+
# The repo root in the local cache is the parent of `model.pt`.
|
| 127 |
+
repo_root = local_paths[0].parent
|
| 128 |
+
print(f"[inference] Cached at: {repo_root}")
|
| 129 |
+
return repo_root
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def build_model(args_json: dict):
|
| 133 |
+
"""Re-create `ConditionalDiffusionModel` from the training args dict.
|
| 134 |
+
|
| 135 |
+
Importing the model classes from the just-downloaded `src/` package is
|
| 136 |
+
the safest way to avoid drift between weights and architecture: if the
|
| 137 |
+
repo ships a particular version of the U-Net code, that's the version
|
| 138 |
+
we use.
|
| 139 |
+
"""
|
| 140 |
+
from unet_conditional import ConditionalUNet
|
| 141 |
+
from diffusion_conditional import ConditionalDiffusionModel, GaussianDiffusion
|
| 142 |
+
|
| 143 |
+
unet = ConditionalUNet(
|
| 144 |
+
in_channels=1,
|
| 145 |
+
out_channels=1,
|
| 146 |
+
label_dim=args_json["label_dim"],
|
| 147 |
+
base_channels=args_json["base_channels"],
|
| 148 |
+
channel_multipliers=tuple(args_json["channel_multipliers"]),
|
| 149 |
+
attention_levels=tuple(args_json["attention_levels"]),
|
| 150 |
+
dropout=args_json["dropout"],
|
| 151 |
+
)
|
| 152 |
+
diffusion = GaussianDiffusion(
|
| 153 |
+
timesteps=args_json["timesteps"],
|
| 154 |
+
beta_start=args_json["beta_start"],
|
| 155 |
+
beta_end=args_json["beta_end"],
|
| 156 |
+
schedule_type=args_json["schedule_type"],
|
| 157 |
+
)
|
| 158 |
+
return ConditionalDiffusionModel(unet, diffusion)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def load_weights(model: torch.nn.Module, ckpt_path: Path, device: str) -> None:
|
| 162 |
+
"""Load the state-dict produced by `train_conditional.py`.
|
| 163 |
+
|
| 164 |
+
The checkpoint is a dict with keys:
|
| 165 |
+
model_state_dict, optimizer_state_dict, ema_shadow, epoch, loss, ...
|
| 166 |
+
We only need `model_state_dict` for inference.
|
| 167 |
+
"""
|
| 168 |
+
# weights_only=False because the checkpoint also serialises optimizer
|
| 169 |
+
# state, EMA shadows, scheduler, etc. Safe here because we trust the
|
| 170 |
+
# source (the file came from our own training run on the cluster).
|
| 171 |
+
ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
|
| 172 |
+
if "model_state_dict" not in ckpt:
|
| 173 |
+
raise KeyError(
|
| 174 |
+
f"{ckpt_path} doesn't contain 'model_state_dict' -- got keys: {list(ckpt)}"
|
| 175 |
+
)
|
| 176 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 177 |
+
epoch = ckpt.get("epoch", "?")
|
| 178 |
+
loss = ckpt.get("loss", "?")
|
| 179 |
+
print(f"[inference] Loaded weights (epoch={epoch}, loss={loss})")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def save_outputs(sample: torch.Tensor, output_dir: Path, model_name: str) -> None:
|
| 183 |
+
"""Write the generated map to disk both as raw .npy and as a PNG preview."""
|
| 184 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 185 |
+
|
| 186 |
+
# `sample` is shape (1, 1, 256, 256) in [-1, 1]; squeeze and bring to CPU.
|
| 187 |
+
arr = sample.squeeze().detach().cpu().numpy()
|
| 188 |
+
npy_path = output_dir / f"sample_{model_name}.npy"
|
| 189 |
+
np.save(npy_path, arr)
|
| 190 |
+
print(f"[inference] Wrote {npy_path} shape={arr.shape} range=[{arr.min():.3f}, {arr.max():.3f}]")
|
| 191 |
+
|
| 192 |
+
# Optional PNG -- only if matplotlib is around. Keeps the hard dependency
|
| 193 |
+
# list short (matplotlib isn't strictly needed for the science workflow).
|
| 194 |
+
try:
|
| 195 |
+
import matplotlib.pyplot as plt
|
| 196 |
+
except ImportError:
|
| 197 |
+
print("[inference] matplotlib not installed -- skipping PNG preview.")
|
| 198 |
+
return
|
| 199 |
+
png_path = output_dir / f"sample_{model_name}.png"
|
| 200 |
+
plt.figure(figsize=(5, 5))
|
| 201 |
+
plt.imshow(arr, cmap="inferno", origin="lower")
|
| 202 |
+
plt.axis("off")
|
| 203 |
+
plt.title(f"DDPM {model_name} sample")
|
| 204 |
+
plt.tight_layout()
|
| 205 |
+
plt.savefig(png_path, dpi=120, bbox_inches="tight")
|
| 206 |
+
plt.close()
|
| 207 |
+
print(f"[inference] Wrote {png_path}")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main() -> None:
|
| 211 |
+
args = parse_args()
|
| 212 |
+
repo_id = args.repo or DEFAULT_REPOS[args.model]
|
| 213 |
+
|
| 214 |
+
# ----------------------------------------------------------------------
|
| 215 |
+
# 1. Pull files from the Hub and make src/ importable
|
| 216 |
+
# ----------------------------------------------------------------------
|
| 217 |
+
repo_root = download_repo(repo_id)
|
| 218 |
+
sys.path.insert(0, str(repo_root / "src"))
|
| 219 |
+
|
| 220 |
+
# ----------------------------------------------------------------------
|
| 221 |
+
# 2. Rebuild the model from args.json
|
| 222 |
+
# ----------------------------------------------------------------------
|
| 223 |
+
with open(repo_root / "args.json") as f:
|
| 224 |
+
train_args = json.load(f)
|
| 225 |
+
expected_dim = train_args["label_dim"]
|
| 226 |
+
if expected_dim != (2 if args.model == "2param" else 6):
|
| 227 |
+
raise ValueError(
|
| 228 |
+
f"args.json says label_dim={expected_dim} but --model={args.model}; "
|
| 229 |
+
"did you point --repo at the wrong checkpoint?"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
model = build_model(train_args).to(args.device)
|
| 233 |
+
load_weights(model, repo_root / "model.pt", args.device)
|
| 234 |
+
model.eval()
|
| 235 |
+
|
| 236 |
+
# ----------------------------------------------------------------------
|
| 237 |
+
# 3. Build the conditioning vector
|
| 238 |
+
# ----------------------------------------------------------------------
|
| 239 |
+
# By default we feed zeros, i.e. the training-set mean in the normalised
|
| 240 |
+
# space. To condition on physical (Ωm, σ8, ...) values, z-score them
|
| 241 |
+
# using the train-split statistics produced by `dataset_conditional.py`
|
| 242 |
+
# and pass the result via --labels.
|
| 243 |
+
if args.labels is None:
|
| 244 |
+
labels = torch.zeros((1, expected_dim), device=args.device)
|
| 245 |
+
print(f"[inference] Using zero (training-mean) conditioning, label_dim={expected_dim}")
|
| 246 |
+
else:
|
| 247 |
+
if len(args.labels) != expected_dim:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"--labels has {len(args.labels)} entries but model expects {expected_dim}"
|
| 250 |
+
)
|
| 251 |
+
labels = torch.tensor([args.labels], dtype=torch.float32, device=args.device)
|
| 252 |
+
print(f"[inference] Using user-supplied labels: {args.labels}")
|
| 253 |
+
|
| 254 |
+
# ----------------------------------------------------------------------
|
| 255 |
+
# 4. Sample
|
| 256 |
+
# ----------------------------------------------------------------------
|
| 257 |
+
# Fix the RNG seed for reproducibility -- diffusion sampling is very
|
| 258 |
+
# sensitive to the initial Gaussian noise.
|
| 259 |
+
torch.manual_seed(args.seed)
|
| 260 |
+
if args.device.startswith("cuda"):
|
| 261 |
+
torch.cuda.manual_seed_all(args.seed)
|
| 262 |
+
|
| 263 |
+
use_ddim = not args.no_ddim
|
| 264 |
+
print(
|
| 265 |
+
f"[inference] Sampling 1 image with "
|
| 266 |
+
f"{'DDIM ' + str(args.ddim_steps) + ' steps' if use_ddim else 'DDPM ' + str(train_args['timesteps']) + ' steps'} "
|
| 267 |
+
f"on {args.device} ..."
|
| 268 |
+
)
|
| 269 |
+
with torch.no_grad():
|
| 270 |
+
sample = model.sample(
|
| 271 |
+
labels=labels,
|
| 272 |
+
channels=1,
|
| 273 |
+
height=256,
|
| 274 |
+
width=256,
|
| 275 |
+
device=args.device,
|
| 276 |
+
progress=True,
|
| 277 |
+
use_ddim=use_ddim,
|
| 278 |
+
ddim_steps=args.ddim_steps,
|
| 279 |
+
eta=0.0,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
# ----------------------------------------------------------------------
|
| 283 |
+
# 5. Save outputs
|
| 284 |
+
# ----------------------------------------------------------------------
|
| 285 |
+
save_outputs(sample, args.output_dir, args.model)
|
| 286 |
+
print("[inference] Done.")
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:17daa73748047908fef96f4fa0436ff1c4f3a59e387c48641b10145cd4c1a55a
|
| 3 |
+
size 1070309253
|
src/__init__.py
ADDED
|
File without changes
|
src/dataset_conditional.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Conditional dataset loader for CAMELS LH 6-parameter layout.
|
| 3 |
+
|
| 4 |
+
Same layout convention as DDPM_HI_Emulation_improved/dataset_conditional.py when
|
| 5 |
+
is_6param is true (that repo enables 6-param mode when the string 'params_6'
|
| 6 |
+
appears in data_dir):
|
| 7 |
+
|
| 8 |
+
data_dir/
|
| 9 |
+
train_LH_6.npy, val_LH_6.npy, test_LH_6.npy
|
| 10 |
+
train_labels_LH.npy, val_labels_LH.npy, test_labels_LH.npy
|
| 11 |
+
|
| 12 |
+
Pass data_dir as the directory that directly contains these files (e.g. the
|
| 13 |
+
absolute path to params_6 under LH_data, analogous to params_2 for 2 labels).
|
| 14 |
+
|
| 15 |
+
Images are scaled to [-1, 1]; labels are z-scored using train-split statistics.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch.utils.data import DataLoader, Dataset
|
| 23 |
+
|
| 24 |
+
# Mirrors shell training for 2-label data at .../LH_data/params_2; 6-param lives in params_6.
|
| 25 |
+
DEFAULT_DATA_DIR = "/scratch/mrpcol001/Diffusion_job/data/LH_data/params_6"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ConditionalImageDataset(Dataset):
|
| 29 |
+
def __init__(self, data_path, label_path, transform=None, label_stats=None):
|
| 30 |
+
self.data = np.load(data_path)
|
| 31 |
+
self.labels = np.load(label_path)
|
| 32 |
+
self.transform = transform
|
| 33 |
+
self.label_stats = label_stats
|
| 34 |
+
|
| 35 |
+
assert len(self.data) == len(self.labels), (
|
| 36 |
+
f"Data and labels length mismatch! {len(self.data)} vs {len(self.labels)}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
print(
|
| 40 |
+
f"Loaded {len(self.data)} images | Image shape: {self.data.shape[1:]} | "
|
| 41 |
+
f"Label shape: {self.labels.shape[1:]}"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def __len__(self):
|
| 45 |
+
return len(self.data)
|
| 46 |
+
|
| 47 |
+
def __getitem__(self, idx):
|
| 48 |
+
img = torch.from_numpy(self.data[idx]).float()
|
| 49 |
+
label = torch.from_numpy(self.labels[idx]).float()
|
| 50 |
+
|
| 51 |
+
# Normalize image to [-1, 1]
|
| 52 |
+
img = img * 2.0 - 1.0
|
| 53 |
+
|
| 54 |
+
# Normalize labels
|
| 55 |
+
if self.label_stats is not None:
|
| 56 |
+
label = (label - self.label_stats["mean"]) / self.label_stats["std"]
|
| 57 |
+
|
| 58 |
+
if img.dim() == 2:
|
| 59 |
+
img = img.unsqueeze(0)
|
| 60 |
+
|
| 61 |
+
return img, label
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_conditional_dataloaders(
|
| 65 |
+
data_dir=DEFAULT_DATA_DIR,
|
| 66 |
+
batch_size=8,
|
| 67 |
+
num_workers=4,
|
| 68 |
+
pin_memory=True,
|
| 69 |
+
normalize_labels=True,
|
| 70 |
+
label_dim=6,
|
| 71 |
+
):
|
| 72 |
+
"""
|
| 73 |
+
Load LH 6-parameter splits. label_dim must match the second axis of *_labels_LH.npy.
|
| 74 |
+
"""
|
| 75 |
+
train_data = os.path.join(data_dir, "train_LH_6.npy")
|
| 76 |
+
val_data = os.path.join(data_dir, "val_LH_6.npy")
|
| 77 |
+
test_data = os.path.join(data_dir, "test_LH_6.npy")
|
| 78 |
+
train_labels = os.path.join(data_dir, "train_labels_LH.npy")
|
| 79 |
+
val_labels = os.path.join(data_dir, "val_labels_LH.npy")
|
| 80 |
+
test_labels = os.path.join(data_dir, "test_labels_LH.npy")
|
| 81 |
+
|
| 82 |
+
print(f"Loading 6-parameter LH dataset from {data_dir}")
|
| 83 |
+
|
| 84 |
+
label_stats = None
|
| 85 |
+
if normalize_labels:
|
| 86 |
+
train_labels_array = np.load(train_labels)
|
| 87 |
+
if train_labels_array.shape[1] != label_dim:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
f"train_labels_LH.npy has {train_labels_array.shape[1]} columns; "
|
| 90 |
+
f"expected label_dim={label_dim}"
|
| 91 |
+
)
|
| 92 |
+
label_mean = train_labels_array.mean(axis=0)
|
| 93 |
+
label_std = train_labels_array.std(axis=0)
|
| 94 |
+
label_std = np.where(label_std == 0, 1.0, label_std)
|
| 95 |
+
label_stats = {
|
| 96 |
+
"mean": torch.from_numpy(label_mean).float(),
|
| 97 |
+
"std": torch.from_numpy(label_std).float(),
|
| 98 |
+
}
|
| 99 |
+
print(f"Label normalization -> mean={label_mean}, std={label_std}")
|
| 100 |
+
|
| 101 |
+
train_dataset = ConditionalImageDataset(train_data, train_labels, label_stats=label_stats)
|
| 102 |
+
val_dataset = ConditionalImageDataset(val_data, val_labels, label_stats=label_stats)
|
| 103 |
+
test_dataset = ConditionalImageDataset(test_data, test_labels, label_stats=label_stats)
|
| 104 |
+
|
| 105 |
+
train_loader = DataLoader(
|
| 106 |
+
train_dataset,
|
| 107 |
+
batch_size=batch_size,
|
| 108 |
+
shuffle=True,
|
| 109 |
+
num_workers=num_workers,
|
| 110 |
+
pin_memory=pin_memory,
|
| 111 |
+
drop_last=True,
|
| 112 |
+
)
|
| 113 |
+
val_loader = DataLoader(
|
| 114 |
+
val_dataset,
|
| 115 |
+
batch_size=batch_size,
|
| 116 |
+
shuffle=False,
|
| 117 |
+
num_workers=num_workers,
|
| 118 |
+
pin_memory=pin_memory,
|
| 119 |
+
drop_last=False,
|
| 120 |
+
)
|
| 121 |
+
test_loader = DataLoader(
|
| 122 |
+
test_dataset,
|
| 123 |
+
batch_size=batch_size,
|
| 124 |
+
shuffle=False,
|
| 125 |
+
num_workers=num_workers,
|
| 126 |
+
pin_memory=pin_memory,
|
| 127 |
+
drop_last=False,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
return train_loader, val_loader, test_loader
|
src/diffusion_conditional.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Diffusion Process Implementation (DDPM + DDIM)
|
| 3 |
+
|
| 4 |
+
Changes from original:
|
| 5 |
+
- Fixed q_posterior_mean_variance return value count (was 3, caller expected 4)
|
| 6 |
+
- Fixed DDIM sigma/dir_xt formula inconsistency
|
| 7 |
+
- Made GaussianDiffusion an nn.Module with registered buffers for proper device handling
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class GaussianDiffusion(nn.Module):
|
| 17 |
+
def __init__(self, timesteps=1500, beta_start=1e-4, beta_end=0.02, schedule_type="linear"):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.timesteps = timesteps
|
| 20 |
+
|
| 21 |
+
if schedule_type == "linear":
|
| 22 |
+
betas = torch.linspace(beta_start, beta_end, timesteps)
|
| 23 |
+
elif schedule_type == "cosine":
|
| 24 |
+
betas = self._cosine_beta_schedule(timesteps)
|
| 25 |
+
else:
|
| 26 |
+
raise ValueError(f"Unknown schedule: {schedule_type}")
|
| 27 |
+
|
| 28 |
+
alphas = 1.0 - betas
|
| 29 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 30 |
+
alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.0)
|
| 31 |
+
|
| 32 |
+
# Register all schedule tensors as buffers so they move with .to(device)
|
| 33 |
+
self.register_buffer('betas', betas)
|
| 34 |
+
self.register_buffer('alphas', alphas)
|
| 35 |
+
self.register_buffer('alphas_cumprod', alphas_cumprod)
|
| 36 |
+
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev)
|
| 37 |
+
self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod))
|
| 38 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1.0 - alphas_cumprod))
|
| 39 |
+
|
| 40 |
+
posterior_variance = betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
|
| 41 |
+
self.register_buffer('posterior_variance', posterior_variance)
|
| 42 |
+
self.register_buffer('posterior_log_variance_clipped', torch.log(torch.clamp(posterior_variance, min=1e-20)))
|
| 43 |
+
self.register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod))
|
| 44 |
+
self.register_buffer('posterior_mean_coef2', (1.0 - alphas_cumprod_prev) * torch.sqrt(alphas) / (1.0 - alphas_cumprod))
|
| 45 |
+
|
| 46 |
+
# Precompute reciprocals used in _predict_xstart_from_noise (avoids recomputation per step)
|
| 47 |
+
self.register_buffer('recip_sqrt_alphas_cumprod', 1.0 / torch.sqrt(alphas_cumprod))
|
| 48 |
+
self.register_buffer('sqrt_recip_minus_one', torch.sqrt(1.0 / alphas_cumprod - 1.0))
|
| 49 |
+
|
| 50 |
+
def _cosine_beta_schedule(self, timesteps, s=0.008):
|
| 51 |
+
steps = timesteps + 1
|
| 52 |
+
x = torch.linspace(0, timesteps, steps)
|
| 53 |
+
alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2
|
| 54 |
+
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
| 55 |
+
betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1])
|
| 56 |
+
return torch.clip(betas, 0.0001, 0.9999)
|
| 57 |
+
|
| 58 |
+
def q_sample(self, x_start, t, noise=None):
|
| 59 |
+
if noise is None:
|
| 60 |
+
noise = torch.randn_like(x_start)
|
| 61 |
+
sqrt_alphas_cumprod_t = self._extract(self.sqrt_alphas_cumprod, t, x_start.shape)
|
| 62 |
+
sqrt_one_minus_alphas_cumprod_t = self._extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
|
| 63 |
+
return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise
|
| 64 |
+
|
| 65 |
+
def p_mean_variance(self, model, x_t, t, labels, clip_denoised=True):
|
| 66 |
+
pred_noise = model(x_t, t, labels)
|
| 67 |
+
x_start = self._predict_xstart_from_noise(x_t, t, pred_noise)
|
| 68 |
+
if clip_denoised:
|
| 69 |
+
x_start = torch.clamp(x_start, -1.0, 1.0)
|
| 70 |
+
# FIX: q_posterior_mean_variance returns 3 values, not 4
|
| 71 |
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior_mean_variance(x_start, x_t, t)
|
| 72 |
+
return model_mean, posterior_variance, posterior_log_variance, x_start
|
| 73 |
+
|
| 74 |
+
def _predict_xstart_from_noise(self, x_t, t, noise):
|
| 75 |
+
return (
|
| 76 |
+
self._extract(self.recip_sqrt_alphas_cumprod, t, x_t.shape) * x_t -
|
| 77 |
+
self._extract(self.sqrt_recip_minus_one, t, x_t.shape) * noise
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def q_posterior_mean_variance(self, x_start, x_t, t):
|
| 81 |
+
posterior_mean = (
|
| 82 |
+
self._extract(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
| 83 |
+
self._extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
| 84 |
+
)
|
| 85 |
+
posterior_variance = self._extract(self.posterior_variance, t, x_t.shape)
|
| 86 |
+
posterior_log_variance = self._extract(self.posterior_log_variance_clipped, t, x_t.shape)
|
| 87 |
+
return posterior_mean, posterior_variance, posterior_log_variance
|
| 88 |
+
|
| 89 |
+
def p_sample(self, model, x_t, t, labels):
|
| 90 |
+
model_mean, _, model_log_variance, _ = self.p_mean_variance(model, x_t, t, labels)
|
| 91 |
+
noise = torch.randn_like(x_t)
|
| 92 |
+
nonzero_mask = ((t != 0).float().view(-1, *([1] * (len(x_t.shape) - 1))))
|
| 93 |
+
return model_mean + nonzero_mask * torch.exp(0.5 * model_log_variance) * noise
|
| 94 |
+
|
| 95 |
+
def ddim_sample_step(self, model, x_t, t, t_next, labels, eta=0.0):
|
| 96 |
+
pred_noise = model(x_t, t, labels)
|
| 97 |
+
alpha_t = self._extract(self.alphas_cumprod, t, x_t.shape)
|
| 98 |
+
alpha_t_next = self._extract(self.alphas_cumprod, t_next, x_t.shape) if t_next[0] >= 0 else torch.ones_like(alpha_t)
|
| 99 |
+
|
| 100 |
+
x0_pred = (x_t - torch.sqrt(1 - alpha_t) * pred_noise) / torch.sqrt(alpha_t)
|
| 101 |
+
x0_pred = torch.clamp(x0_pred, -1.0, 1.0)
|
| 102 |
+
|
| 103 |
+
# FIX: Consistent DDIM sigma computation
|
| 104 |
+
# sigma^2 = eta^2 * (1 - alpha_{t-1}) / (1 - alpha_t) * (1 - alpha_t / alpha_{t-1})
|
| 105 |
+
sigma_sq = eta**2 * (1 - alpha_t_next) / (1 - alpha_t) * (1 - alpha_t / alpha_t_next) if eta > 0 else 0
|
| 106 |
+
sigma_t = torch.sqrt(torch.clamp(sigma_sq, min=0)) if eta > 0 else 0
|
| 107 |
+
|
| 108 |
+
# dir_xt uses the same sigma^2
|
| 109 |
+
dir_xt = torch.sqrt(torch.clamp(1 - alpha_t_next - sigma_sq, min=0)) * pred_noise
|
| 110 |
+
|
| 111 |
+
noise = torch.randn_like(x_t) if eta > 0 else 0
|
| 112 |
+
return torch.sqrt(alpha_t_next) * x0_pred + dir_xt + sigma_t * noise
|
| 113 |
+
|
| 114 |
+
def sample(self, model, labels, channels, height, width, device, progress=False, use_ddim=True, ddim_steps=50, eta=0.0):
|
| 115 |
+
batch_size = labels.shape[0]
|
| 116 |
+
img = torch.randn((batch_size, channels, height, width), device=device)
|
| 117 |
+
|
| 118 |
+
if use_ddim:
|
| 119 |
+
skip = self.timesteps // ddim_steps
|
| 120 |
+
seq = list(range(0, self.timesteps, skip))
|
| 121 |
+
seq_next = [-1] + seq[:-1]
|
| 122 |
+
seq_iter = reversed(list(zip(seq, seq_next)))
|
| 123 |
+
if progress:
|
| 124 |
+
from tqdm import tqdm
|
| 125 |
+
seq_iter = tqdm(seq_iter, desc=f'DDIM Sampling ({ddim_steps} steps)', total=len(seq))
|
| 126 |
+
for i, j in seq_iter:
|
| 127 |
+
t = torch.full((batch_size,), i, device=device, dtype=torch.long)
|
| 128 |
+
t_next = torch.full((batch_size,), j, device=device, dtype=torch.long)
|
| 129 |
+
img = self.ddim_sample_step(model, img, t, t_next, labels, eta)
|
| 130 |
+
else:
|
| 131 |
+
if progress:
|
| 132 |
+
from tqdm import tqdm
|
| 133 |
+
timesteps_iter = tqdm(reversed(range(self.timesteps)), total=self.timesteps)
|
| 134 |
+
else:
|
| 135 |
+
timesteps_iter = reversed(range(self.timesteps))
|
| 136 |
+
for i in timesteps_iter:
|
| 137 |
+
t = torch.full((batch_size,), i, device=device, dtype=torch.long)
|
| 138 |
+
img = self.p_sample(model, img, t, labels)
|
| 139 |
+
return img
|
| 140 |
+
|
| 141 |
+
def training_losses(self, model, x_start, labels, t, noise=None):
|
| 142 |
+
if noise is None:
|
| 143 |
+
noise = torch.randn_like(x_start)
|
| 144 |
+
x_t = self.q_sample(x_start, t, noise)
|
| 145 |
+
pred_noise = model(x_t, t, labels)
|
| 146 |
+
return F.mse_loss(pred_noise, noise, reduction='none').mean(dim=list(range(1, len(pred_noise.shape))))
|
| 147 |
+
|
| 148 |
+
def _extract(self, a, t, x_shape):
|
| 149 |
+
batch_size = t.shape[0]
|
| 150 |
+
out = a.gather(0, t)
|
| 151 |
+
return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class ConditionalDiffusionModel(nn.Module):
|
| 155 |
+
def __init__(self, unet, diffusion_process):
|
| 156 |
+
super().__init__()
|
| 157 |
+
self.unet = unet
|
| 158 |
+
self.diffusion = diffusion_process
|
| 159 |
+
|
| 160 |
+
def forward(self, x, t, labels):
|
| 161 |
+
return self.unet(x, t, labels)
|
| 162 |
+
|
| 163 |
+
def get_loss(self, x, labels, noise=None):
|
| 164 |
+
batch_size = x.shape[0]
|
| 165 |
+
device = x.device
|
| 166 |
+
t = torch.randint(0, self.diffusion.timesteps, (batch_size,), device=device).long()
|
| 167 |
+
return self.diffusion.training_losses(self, x, labels, t, noise=noise).mean()
|
| 168 |
+
|
| 169 |
+
def sample(self, labels, channels, height, width, device, progress=False, use_ddim=True, ddim_steps=50, eta=0.0):
|
| 170 |
+
self.eval()
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
return self.diffusion.sample(self, labels, channels, height, width, device, progress, use_ddim, ddim_steps, eta)
|
src/evaluate_conditional.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Evaluate Conditional Diffusion Model (6 cosmological parameters, CAMELS LH).
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python evaluate_conditional.py
|
| 6 |
+
python evaluate_conditional.py --checkpoint outputs_conditional_6param_*/checkpoints/best_model.pt
|
| 7 |
+
|
| 8 |
+
Changes from original:
|
| 9 |
+
- Loads args.json (saved by training script) for robust config parsing
|
| 10 |
+
- Falls back to args.txt parsing if JSON not available
|
| 11 |
+
- Vectorized power spectrum calculation (~100x speedup)
|
| 12 |
+
- Added weights_only parameter to torch.load
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import ast
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Dict, Tuple
|
| 21 |
+
|
| 22 |
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
| 23 |
+
# Trained weights live under april_26 (this Models tree holds code only).
|
| 24 |
+
_DEFAULT_CHECKPOINT = Path(
|
| 25 |
+
"/scratch/mrpcol001/Diffusion_job/april_26/ddpm_hi_lh6/"
|
| 26 |
+
"outputs_conditional_6param_20260413_132226/checkpoints/best_model.pt"
|
| 27 |
+
)
|
| 28 |
+
_DEFAULT_DATA_DIR = "/scratch/mrpcol001/Diffusion_job/data/LH_data/params_6"
|
| 29 |
+
|
| 30 |
+
import matplotlib
|
| 31 |
+
matplotlib.use("Agg")
|
| 32 |
+
import matplotlib.pyplot as plt
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
|
| 36 |
+
from diffusion_conditional import GaussianDiffusion, ConditionalDiffusionModel
|
| 37 |
+
from unet_conditional import ConditionalUNet
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def parse_args() -> argparse.Namespace:
|
| 41 |
+
parser = argparse.ArgumentParser(description="Evaluate conditional 6-parameter diffusion model")
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--checkpoint",
|
| 44 |
+
type=str,
|
| 45 |
+
default=str(_DEFAULT_CHECKPOINT),
|
| 46 |
+
help="Path to trained checkpoint (default: 6-param run best_model.pt next to this script)",
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--training_args",
|
| 50 |
+
type=str,
|
| 51 |
+
default=None,
|
| 52 |
+
help="Path to args.json or args.txt from training (auto-detected from checkpoint folder if not provided)",
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--data_dir",
|
| 56 |
+
type=str,
|
| 57 |
+
default=_DEFAULT_DATA_DIR,
|
| 58 |
+
help="Directory with train_LH_6.npy / train_labels_LH.npy (CAMELS LH params_6 layout)",
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--split",
|
| 62 |
+
type=str,
|
| 63 |
+
default="test",
|
| 64 |
+
choices=["train", "val", "test"],
|
| 65 |
+
help="Which split to use for real images",
|
| 66 |
+
)
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--num_samples",
|
| 69 |
+
type=int,
|
| 70 |
+
default=8,
|
| 71 |
+
help="Number of examples to show in the comparison grid",
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--seed",
|
| 75 |
+
type=int,
|
| 76 |
+
default=42,
|
| 77 |
+
help="Random seed for reproducibility",
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--output_dir",
|
| 81 |
+
type=str,
|
| 82 |
+
default="evaluation_outputs",
|
| 83 |
+
help="Where to save plots and results",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--ddim_steps",
|
| 87 |
+
type=int,
|
| 88 |
+
default=50,
|
| 89 |
+
help="Number of DDIM sampling steps",
|
| 90 |
+
)
|
| 91 |
+
return parser.parse_args()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def load_training_config(path: str) -> Dict:
|
| 95 |
+
"""Load training configuration. Prefers JSON, falls back to txt parsing."""
|
| 96 |
+
# Try JSON first (written by improved training script)
|
| 97 |
+
json_path = path.replace('.txt', '.json') if path.endswith('.txt') else path
|
| 98 |
+
if json_path.endswith('.json') and os.path.isfile(json_path):
|
| 99 |
+
with open(json_path, 'r') as f:
|
| 100 |
+
return json.load(f)
|
| 101 |
+
|
| 102 |
+
# Fall back to txt parsing
|
| 103 |
+
if not os.path.isfile(path):
|
| 104 |
+
raise FileNotFoundError(f"Training args file not found: {path}")
|
| 105 |
+
|
| 106 |
+
config = {}
|
| 107 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 108 |
+
for line in f:
|
| 109 |
+
line = line.strip()
|
| 110 |
+
if not line or ":" not in line:
|
| 111 |
+
continue
|
| 112 |
+
key, value = line.split(":", 1)
|
| 113 |
+
key = key.strip()
|
| 114 |
+
value = value.strip()
|
| 115 |
+
|
| 116 |
+
if value.startswith("[") and value.endswith("]"):
|
| 117 |
+
try:
|
| 118 |
+
config[key] = ast.literal_eval(value)
|
| 119 |
+
except (ValueError, SyntaxError):
|
| 120 |
+
config[key] = value
|
| 121 |
+
elif value.isdigit():
|
| 122 |
+
config[key] = int(value)
|
| 123 |
+
elif value.replace(".", "", 1).replace("e-", "", 1).replace("e", "", 1).isdigit():
|
| 124 |
+
config[key] = float(value)
|
| 125 |
+
else:
|
| 126 |
+
config[key] = value
|
| 127 |
+
|
| 128 |
+
return config
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _detect_label_suffix(data_dir: Path) -> str:
|
| 132 |
+
"""Detect whether this is a 2-param or 6-param dataset."""
|
| 133 |
+
if (data_dir / "train_labels_LH_2.npy").exists():
|
| 134 |
+
return "_2"
|
| 135 |
+
elif (data_dir / "train_labels_LH.npy").exists():
|
| 136 |
+
return ""
|
| 137 |
+
else:
|
| 138 |
+
raise FileNotFoundError(f"No label files found in {data_dir}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _detect_image_suffix(data_dir: Path) -> str:
|
| 142 |
+
"""Detect whether images use _6 suffix (6-param) or not."""
|
| 143 |
+
if (data_dir / "train_LH.npy").exists():
|
| 144 |
+
return ""
|
| 145 |
+
elif (data_dir / "train_LH_6.npy").exists():
|
| 146 |
+
return "_6"
|
| 147 |
+
else:
|
| 148 |
+
raise FileNotFoundError(f"No image files found in {data_dir}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def load_label_stats(data_dir: Path) -> Tuple[np.ndarray, np.ndarray]:
|
| 152 |
+
"""Load mean and std from training labels (used for normalization)."""
|
| 153 |
+
suffix = _detect_label_suffix(data_dir)
|
| 154 |
+
labels_path = data_dir / f"train_labels_LH{suffix}.npy"
|
| 155 |
+
labels = np.load(labels_path)
|
| 156 |
+
mean, std = labels.mean(axis=0), labels.std(axis=0)
|
| 157 |
+
std = np.where(std == 0, 1.0, std) # guard against zero-variance labels
|
| 158 |
+
return mean, std
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def load_split(data_dir: Path, split: str) -> Tuple[np.ndarray, np.ndarray]:
|
| 162 |
+
"""Load images and labels for a given split."""
|
| 163 |
+
img_suffix = _detect_image_suffix(data_dir)
|
| 164 |
+
label_suffix = _detect_label_suffix(data_dir)
|
| 165 |
+
|
| 166 |
+
image_path = data_dir / f"{split}_LH{img_suffix}.npy"
|
| 167 |
+
label_path = data_dir / f"{split}_labels_LH{label_suffix}.npy"
|
| 168 |
+
|
| 169 |
+
if not image_path.exists():
|
| 170 |
+
raise FileNotFoundError(f"Image file not found: {image_path}")
|
| 171 |
+
if not label_path.exists():
|
| 172 |
+
raise FileNotFoundError(f"Label file not found: {label_path}")
|
| 173 |
+
|
| 174 |
+
images = np.load(image_path).astype(np.float32)
|
| 175 |
+
labels = np.load(label_path).astype(np.float32)
|
| 176 |
+
return images, labels
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def build_model(config: Dict, device: torch.device) -> ConditionalDiffusionModel:
|
| 180 |
+
"""Rebuild the exact same model architecture used during training."""
|
| 181 |
+
unet = ConditionalUNet(
|
| 182 |
+
in_channels=1,
|
| 183 |
+
out_channels=1,
|
| 184 |
+
label_dim=int(config.get("label_dim", 6)),
|
| 185 |
+
base_channels=int(config.get("base_channels", 64)),
|
| 186 |
+
channel_multipliers=config.get("channel_multipliers", [1, 2, 4, 8]),
|
| 187 |
+
attention_levels=config.get("attention_levels", [2, 3]),
|
| 188 |
+
dropout=float(config.get("dropout", 0.1)),
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
diffusion = GaussianDiffusion(
|
| 192 |
+
timesteps=int(config.get("timesteps", 1500)),
|
| 193 |
+
beta_start=float(config.get("beta_start", 1e-4)),
|
| 194 |
+
beta_end=float(config.get("beta_end", 0.02)),
|
| 195 |
+
schedule_type=config.get("schedule_type", "linear"),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
return ConditionalDiffusionModel(unet, diffusion).to(device)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def load_checkpoint(model: ConditionalDiffusionModel, checkpoint_path: str, device: torch.device):
|
| 202 |
+
"""Load model weights from checkpoint."""
|
| 203 |
+
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
|
| 204 |
+
state_dict = checkpoint["model_state_dict"] if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint else checkpoint
|
| 205 |
+
|
| 206 |
+
# If EMA weights are available, use them (they are the better weights)
|
| 207 |
+
if isinstance(checkpoint, dict) and "ema_shadow" in checkpoint:
|
| 208 |
+
print("Loading EMA shadow weights from checkpoint")
|
| 209 |
+
ema_shadow = checkpoint["ema_shadow"]
|
| 210 |
+
current_state = model.state_dict()
|
| 211 |
+
for name, param in ema_shadow.items():
|
| 212 |
+
if name in current_state:
|
| 213 |
+
current_state[name] = param
|
| 214 |
+
model.load_state_dict(current_state)
|
| 215 |
+
else:
|
| 216 |
+
model.load_state_dict(state_dict)
|
| 217 |
+
|
| 218 |
+
model.eval()
|
| 219 |
+
print(f"Loaded checkpoint: {checkpoint_path}")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def PowerSpectrum(box: np.ndarray, N: int, dl: float) -> Tuple[np.ndarray, np.ndarray]:
|
| 223 |
+
"""Vectorized 2D power spectrum computation."""
|
| 224 |
+
FT_box = np.fft.fftn(box, norm="ortho")
|
| 225 |
+
k = 2 * np.pi * np.fft.fftfreq(N, dl)
|
| 226 |
+
dk_val = 2 * np.pi / (N * dl)
|
| 227 |
+
|
| 228 |
+
# Vectorized: compute k magnitudes and bin indices for all pixels at once
|
| 229 |
+
ki, kj = np.meshgrid(k, k, indexing='ij')
|
| 230 |
+
kbar = np.sqrt(ki**2 + kj**2)
|
| 231 |
+
n_bins = N // 2 # only bins up to Nyquist frequency
|
| 232 |
+
t_idx = np.round(kbar / dk_val).astype(int)
|
| 233 |
+
|
| 234 |
+
# Mask out modes beyond Nyquist to avoid bin contamination
|
| 235 |
+
valid = t_idx < n_bins
|
| 236 |
+
power = (FT_box * np.conj(FT_box)).real
|
| 237 |
+
|
| 238 |
+
pk = np.zeros(n_bins)
|
| 239 |
+
count = np.zeros(n_bins)
|
| 240 |
+
np.add.at(pk, t_idx[valid], power[valid])
|
| 241 |
+
np.add.at(count, t_idx[valid], 1)
|
| 242 |
+
|
| 243 |
+
pk /= np.where(count == 0, 1, count)
|
| 244 |
+
pk *= dl**2
|
| 245 |
+
dk = np.arange(n_bins) * dk_val
|
| 246 |
+
return dk, pk
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def calculate_pdf_batch(images: np.ndarray, log_nhi_min=14.0, log_nhi_max=22.0, n_bins=100):
|
| 250 |
+
images_01 = np.clip(images, 0.0, 1.0)
|
| 251 |
+
log_nhi_bins = np.linspace(log_nhi_min, log_nhi_max, n_bins)
|
| 252 |
+
bin_centers = 0.5 * (log_nhi_bins[:-1] + log_nhi_bins[1:])
|
| 253 |
+
|
| 254 |
+
pdfs = []
|
| 255 |
+
for img in images_01:
|
| 256 |
+
log_nhi_values = log_nhi_min + (log_nhi_max - log_nhi_min) * img.reshape(-1)
|
| 257 |
+
hist, _ = np.histogram(log_nhi_values, bins=log_nhi_bins, density=True)
|
| 258 |
+
pdfs.append(hist)
|
| 259 |
+
|
| 260 |
+
pdf_array = np.stack(pdfs)
|
| 261 |
+
return bin_centers, pdf_array.mean(axis=0), pdf_array.std(axis=0)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def calculate_power_spectrum_batch(images: np.ndarray, box_size: float = 25.0):
|
| 265 |
+
N = images.shape[-1]
|
| 266 |
+
dl = box_size / N
|
| 267 |
+
|
| 268 |
+
# Compute k-values once, then reuse for all images
|
| 269 |
+
dk, _ = PowerSpectrum(images[0], N=N, dl=dl)
|
| 270 |
+
power_spectra = [PowerSpectrum(img, N=N, dl=dl)[1] for img in images]
|
| 271 |
+
power_array = np.stack(power_spectra)
|
| 272 |
+
return dk, power_array.mean(axis=0), power_array.std(axis=0)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def prepare_labels_for_model(labels: np.ndarray, mean: np.ndarray, std: np.ndarray) -> torch.Tensor:
|
| 276 |
+
normalized = (labels - mean) / std
|
| 277 |
+
return torch.from_numpy(normalized).float()
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def from_model_output(samples: torch.Tensor) -> np.ndarray:
|
| 281 |
+
arrays = samples.cpu().numpy()
|
| 282 |
+
return np.clip((arrays + 1.0) / 2.0, 0.0, 1.0)[:, 0, :, :]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def plot_image_grid(generated, real, labels, output_path: Path, num_samples=8):
|
| 286 |
+
num = min(num_samples, generated.shape[0])
|
| 287 |
+
fig, axes = plt.subplots(num, 2, figsize=(6, 3 * num))
|
| 288 |
+
if num == 1:
|
| 289 |
+
axes = np.expand_dims(axes, axis=0)
|
| 290 |
+
|
| 291 |
+
for i in range(num):
|
| 292 |
+
label_str = ", ".join(f"{v:.3f}" for v in labels[i])
|
| 293 |
+
axes[i, 0].imshow(generated[i], origin="lower")
|
| 294 |
+
axes[i, 0].set_title(f"Generated\n{label_str}")
|
| 295 |
+
axes[i, 0].axis("off")
|
| 296 |
+
|
| 297 |
+
axes[i, 1].imshow(real[i], origin="lower")
|
| 298 |
+
axes[i, 1].set_title("Real")
|
| 299 |
+
axes[i, 1].axis("off")
|
| 300 |
+
|
| 301 |
+
plt.tight_layout()
|
| 302 |
+
fig.savefig(output_path, dpi=200, bbox_inches="tight")
|
| 303 |
+
plt.close(fig)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def plot_mean_std(x, mean_real, std_real, mean_gen, std_gen, xlabel, ylabel, title, output_path: Path, yscale="linear"):
|
| 307 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 308 |
+
ax.plot(x, mean_real, label="Real mean", color="tab:blue", linewidth=2)
|
| 309 |
+
ax.plot(x, mean_gen, label="Generated mean", color="tab:orange", linewidth=2)
|
| 310 |
+
|
| 311 |
+
ax.fill_between(x, mean_real - std_real, mean_real + std_real, color="tab:blue", alpha=0.15, label="Real +/-1s")
|
| 312 |
+
ax.fill_between(x, mean_real - 3*std_real, mean_real + 3*std_real, color="tab:blue", alpha=0.05)
|
| 313 |
+
|
| 314 |
+
ax.fill_between(x, mean_gen - std_gen, mean_gen + std_gen, color="tab:orange", alpha=0.15, label="Generated +/-1s")
|
| 315 |
+
ax.fill_between(x, mean_gen - 3*std_gen, mean_gen + 3*std_gen, color="tab:orange", alpha=0.05)
|
| 316 |
+
|
| 317 |
+
ax.set_xlabel(xlabel)
|
| 318 |
+
ax.set_ylabel(ylabel)
|
| 319 |
+
ax.set_title(title)
|
| 320 |
+
ax.set_yscale(yscale)
|
| 321 |
+
ax.legend()
|
| 322 |
+
ax.grid(alpha=0.3)
|
| 323 |
+
fig.tight_layout()
|
| 324 |
+
fig.savefig(output_path, dpi=200, bbox_inches="tight")
|
| 325 |
+
plt.close(fig)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def main():
|
| 329 |
+
args = parse_args()
|
| 330 |
+
torch.manual_seed(args.seed)
|
| 331 |
+
np.random.seed(args.seed)
|
| 332 |
+
|
| 333 |
+
output_dir = Path(args.output_dir)
|
| 334 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 335 |
+
|
| 336 |
+
# Load training config (prefer args.json next to the checkpoint run directory)
|
| 337 |
+
if args.training_args is None:
|
| 338 |
+
ckpt_path = Path(args.checkpoint).resolve()
|
| 339 |
+
run_dir = ckpt_path.parent.parent
|
| 340 |
+
for name in ("args.json", "args.txt"):
|
| 341 |
+
candidate = run_dir / name
|
| 342 |
+
if candidate.is_file():
|
| 343 |
+
args.training_args = str(candidate)
|
| 344 |
+
print(f"Auto-detected training args: {args.training_args}")
|
| 345 |
+
break
|
| 346 |
+
if args.training_args is None:
|
| 347 |
+
possible_json = list(_SCRIPT_DIR.glob("outputs_conditional_*/args.json"))
|
| 348 |
+
possible_txt = list(_SCRIPT_DIR.glob("outputs_conditional_*/args.txt"))
|
| 349 |
+
possible = possible_json + possible_txt
|
| 350 |
+
if possible:
|
| 351 |
+
args.training_args = str(max(possible, key=os.path.getctime))
|
| 352 |
+
print(f"Auto-detected training args (fallback): {args.training_args}")
|
| 353 |
+
else:
|
| 354 |
+
raise FileNotFoundError(
|
| 355 |
+
"Please provide --training_args path to your training args.json or args.txt"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
config = load_training_config(args.training_args)
|
| 359 |
+
|
| 360 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 361 |
+
model = build_model(config, device)
|
| 362 |
+
load_checkpoint(model, args.checkpoint, device)
|
| 363 |
+
|
| 364 |
+
# Load data
|
| 365 |
+
data_dir = Path(args.data_dir)
|
| 366 |
+
images_split, labels_split = load_split(data_dir, args.split)
|
| 367 |
+
label_mean, label_std = load_label_stats(data_dir)
|
| 368 |
+
|
| 369 |
+
# Select random samples
|
| 370 |
+
num_select = min(100, len(images_split))
|
| 371 |
+
indices = np.random.choice(len(images_split), num_select, replace=False)
|
| 372 |
+
|
| 373 |
+
real_images = images_split[indices]
|
| 374 |
+
original_labels = labels_split[indices]
|
| 375 |
+
|
| 376 |
+
# Generate samples in batches
|
| 377 |
+
batch_size = min(8, num_select)
|
| 378 |
+
generated_list = []
|
| 379 |
+
|
| 380 |
+
print(f"Generating {num_select} samples (batch size = {batch_size})...")
|
| 381 |
+
for i in range(0, num_select, batch_size):
|
| 382 |
+
batch_labels = original_labels[i:i+batch_size]
|
| 383 |
+
batch_labels_tensor = prepare_labels_for_model(batch_labels, label_mean, label_std).to(device)
|
| 384 |
+
|
| 385 |
+
with torch.no_grad():
|
| 386 |
+
batch_gen = model.sample(
|
| 387 |
+
labels=batch_labels_tensor,
|
| 388 |
+
channels=1,
|
| 389 |
+
height=real_images.shape[-2],
|
| 390 |
+
width=real_images.shape[-1],
|
| 391 |
+
device=device,
|
| 392 |
+
progress=False,
|
| 393 |
+
use_ddim=True,
|
| 394 |
+
ddim_steps=args.ddim_steps,
|
| 395 |
+
)
|
| 396 |
+
generated_list.append(from_model_output(batch_gen))
|
| 397 |
+
print(f" Batch {i//batch_size + 1}/{(num_select+batch_size-1)//batch_size} done")
|
| 398 |
+
|
| 399 |
+
generated_images = np.concatenate(generated_list, axis=0)
|
| 400 |
+
|
| 401 |
+
# Plots
|
| 402 |
+
plot_image_grid(generated_images, real_images, original_labels,
|
| 403 |
+
output_dir / "real_vs_generated.png", num_samples=args.num_samples)
|
| 404 |
+
|
| 405 |
+
# PDF
|
| 406 |
+
bin_centers, mean_pdf_real, std_pdf_real = calculate_pdf_batch(real_images)
|
| 407 |
+
_, mean_pdf_gen, std_pdf_gen = calculate_pdf_batch(generated_images)
|
| 408 |
+
plot_mean_std(bin_centers, mean_pdf_real, std_pdf_real, mean_pdf_gen, std_pdf_gen,
|
| 409 |
+
"log N_HI [cm^-2]", "PDF", "Column Density PDF", output_dir / "pdf_mean_std.png")
|
| 410 |
+
|
| 411 |
+
# Power Spectrum (skip k=0 DC component for log-scale plotting)
|
| 412 |
+
dk, mean_pk_real, std_pk_real = calculate_power_spectrum_batch(real_images)
|
| 413 |
+
_, mean_pk_gen, std_pk_gen = calculate_power_spectrum_batch(generated_images)
|
| 414 |
+
plot_mean_std(dk[1:], mean_pk_real[1:], std_pk_real[1:], mean_pk_gen[1:], std_pk_gen[1:],
|
| 415 |
+
"k [h/Mpc]", "P(k)", "Power Spectrum", output_dir / "power_spectrum_mean_std.png", yscale="log")
|
| 416 |
+
|
| 417 |
+
# Save numerical results
|
| 418 |
+
np.savez(
|
| 419 |
+
output_dir / "evaluation_data.npz",
|
| 420 |
+
indices=indices,
|
| 421 |
+
labels_original=original_labels,
|
| 422 |
+
bin_centers=bin_centers,
|
| 423 |
+
mean_pdf_real=mean_pdf_real, std_pdf_real=std_pdf_real,
|
| 424 |
+
mean_pdf_gen=mean_pdf_gen, std_pdf_gen=std_pdf_gen,
|
| 425 |
+
dk=dk,
|
| 426 |
+
mean_pk_real=mean_pk_real, std_pk_real=std_pk_real,
|
| 427 |
+
mean_pk_gen=mean_pk_gen, std_pk_gen=std_pk_gen,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
print(f"\nEvaluation complete!")
|
| 431 |
+
print(f" Plots saved to: {output_dir}")
|
| 432 |
+
print(f" Numerical data saved to: {output_dir}/evaluation_data.npz")
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
main()
|
src/unet_conditional.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Conditional U-Net Architecture for Diffusion Model
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import math
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TimeEmbedding(nn.Module):
|
| 12 |
+
def __init__(self, dim):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.dim = dim
|
| 15 |
+
|
| 16 |
+
def forward(self, time):
|
| 17 |
+
device = time.device
|
| 18 |
+
half_dim = self.dim // 2
|
| 19 |
+
embeddings = math.log(10000) / (half_dim - 1)
|
| 20 |
+
embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings)
|
| 21 |
+
embeddings = time[:, None] * embeddings[None, :]
|
| 22 |
+
return torch.cat([torch.sin(embeddings), torch.cos(embeddings)], dim=-1)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class LabelEmbedding(nn.Module):
|
| 26 |
+
def __init__(self, label_dim, emb_dim):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.mlp = nn.Sequential(
|
| 29 |
+
nn.Linear(label_dim, emb_dim),
|
| 30 |
+
nn.SiLU(),
|
| 31 |
+
nn.Linear(emb_dim, emb_dim)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def forward(self, labels):
|
| 35 |
+
return self.mlp(labels)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ResidualBlock(nn.Module):
|
| 39 |
+
def __init__(self, in_channels, out_channels, time_emb_dim, dropout=0.1):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.conv1 = nn.Sequential(
|
| 42 |
+
nn.GroupNorm(8, in_channels),
|
| 43 |
+
nn.SiLU(),
|
| 44 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
|
| 45 |
+
)
|
| 46 |
+
self.time_emb = nn.Sequential(nn.SiLU(), nn.Linear(time_emb_dim, out_channels))
|
| 47 |
+
self.conv2 = nn.Sequential(
|
| 48 |
+
nn.GroupNorm(8, out_channels),
|
| 49 |
+
nn.SiLU(),
|
| 50 |
+
nn.Dropout(dropout),
|
| 51 |
+
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
|
| 52 |
+
)
|
| 53 |
+
self.shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1) if in_channels != out_channels else nn.Identity()
|
| 54 |
+
|
| 55 |
+
def forward(self, x, emb):
|
| 56 |
+
h = self.conv1(x)
|
| 57 |
+
h = h + self.time_emb(emb)[:, :, None, None]
|
| 58 |
+
h = self.conv2(h)
|
| 59 |
+
return h + self.shortcut(x)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class AttentionBlock(nn.Module):
|
| 63 |
+
def __init__(self, channels, num_heads=4):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.channels = channels
|
| 66 |
+
self.num_heads = num_heads
|
| 67 |
+
self.norm = nn.GroupNorm(8, channels)
|
| 68 |
+
self.qkv = nn.Conv2d(channels, channels * 3, kernel_size=1)
|
| 69 |
+
self.proj = nn.Conv2d(channels, channels, kernel_size=1)
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
B, C, H, W = x.shape
|
| 73 |
+
h = self.norm(x)
|
| 74 |
+
q, k, v = self.qkv(h).chunk(3, dim=1)
|
| 75 |
+
head_dim = C // self.num_heads
|
| 76 |
+
q = q.view(B, self.num_heads, head_dim, H*W).transpose(2, 3)
|
| 77 |
+
k = k.view(B, self.num_heads, head_dim, H*W).transpose(2, 3)
|
| 78 |
+
v = v.view(B, self.num_heads, head_dim, H*W).transpose(2, 3)
|
| 79 |
+
|
| 80 |
+
h = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0)
|
| 81 |
+
h = h.transpose(2, 3).reshape(B, C, H, W)
|
| 82 |
+
return x + self.proj(h)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ConditionalUNet(nn.Module):
|
| 86 |
+
def __init__(self, in_channels=1, out_channels=1, label_dim=2,
|
| 87 |
+
base_channels=64, channel_multipliers=(1,2,4,8),
|
| 88 |
+
attention_levels=(2,3), dropout=0.1, time_emb_dim=256, label_emb_dim=256):
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.label_dim = label_dim
|
| 91 |
+
|
| 92 |
+
self.time_embedding = TimeEmbedding(time_emb_dim)
|
| 93 |
+
self.time_mlp = nn.Sequential(nn.Linear(time_emb_dim, time_emb_dim*4), nn.SiLU(), nn.Linear(time_emb_dim*4, time_emb_dim))
|
| 94 |
+
|
| 95 |
+
self.label_embedding = LabelEmbedding(label_dim, label_emb_dim)
|
| 96 |
+
self.combined_emb_dim = time_emb_dim + label_emb_dim
|
| 97 |
+
self.combined_mlp = nn.Sequential(nn.Linear(self.combined_emb_dim, time_emb_dim*4), nn.SiLU(), nn.Linear(time_emb_dim*4, time_emb_dim))
|
| 98 |
+
|
| 99 |
+
self.conv_in = nn.Conv2d(in_channels, base_channels, kernel_size=3, padding=1)
|
| 100 |
+
|
| 101 |
+
self.down_blocks = nn.ModuleList()
|
| 102 |
+
channels = [base_channels]
|
| 103 |
+
now_channels = base_channels
|
| 104 |
+
|
| 105 |
+
for i, mult in enumerate(channel_multipliers):
|
| 106 |
+
out_ch = base_channels * mult
|
| 107 |
+
for _ in range(2):
|
| 108 |
+
self.down_blocks.append(ResidualBlock(now_channels, out_ch, time_emb_dim, dropout))
|
| 109 |
+
if i in attention_levels:
|
| 110 |
+
self.down_blocks.append(AttentionBlock(out_ch))
|
| 111 |
+
now_channels = out_ch
|
| 112 |
+
channels.append(now_channels)
|
| 113 |
+
if i != len(channel_multipliers) - 1:
|
| 114 |
+
self.down_blocks.append(nn.Conv2d(now_channels, now_channels, kernel_size=3, stride=2, padding=1))
|
| 115 |
+
channels.append(now_channels)
|
| 116 |
+
|
| 117 |
+
self.middle = nn.ModuleList([
|
| 118 |
+
ResidualBlock(now_channels, now_channels, time_emb_dim, dropout),
|
| 119 |
+
AttentionBlock(now_channels),
|
| 120 |
+
ResidualBlock(now_channels, now_channels, time_emb_dim, dropout)
|
| 121 |
+
])
|
| 122 |
+
|
| 123 |
+
self.up_blocks = nn.ModuleList()
|
| 124 |
+
for i, mult in reversed(list(enumerate(channel_multipliers))):
|
| 125 |
+
out_ch = base_channels * mult
|
| 126 |
+
for _ in range(3):
|
| 127 |
+
self.up_blocks.append(ResidualBlock(now_channels + channels.pop(), out_ch, time_emb_dim, dropout))
|
| 128 |
+
if i in attention_levels:
|
| 129 |
+
self.up_blocks.append(AttentionBlock(out_ch))
|
| 130 |
+
now_channels = out_ch
|
| 131 |
+
if i != 0:
|
| 132 |
+
self.up_blocks.append(nn.ConvTranspose2d(now_channels, now_channels, kernel_size=4, stride=2, padding=1))
|
| 133 |
+
|
| 134 |
+
self.conv_out = nn.Sequential(
|
| 135 |
+
nn.GroupNorm(8, now_channels),
|
| 136 |
+
nn.SiLU(),
|
| 137 |
+
nn.Conv2d(now_channels, out_channels, kernel_size=3, padding=1)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def forward(self, x, t, labels=None):
|
| 141 |
+
t_emb = self.time_embedding(t)
|
| 142 |
+
t_emb = self.time_mlp(t_emb)
|
| 143 |
+
|
| 144 |
+
if labels is not None:
|
| 145 |
+
label_emb = self.label_embedding(labels)
|
| 146 |
+
combined = torch.cat([t_emb, label_emb], dim=-1)
|
| 147 |
+
emb = self.combined_mlp(combined)
|
| 148 |
+
else:
|
| 149 |
+
emb = t_emb
|
| 150 |
+
|
| 151 |
+
h = self.conv_in(x)
|
| 152 |
+
skips = [h]
|
| 153 |
+
|
| 154 |
+
for module in self.down_blocks:
|
| 155 |
+
if isinstance(module, ResidualBlock):
|
| 156 |
+
h = module(h, emb)
|
| 157 |
+
skips.append(h)
|
| 158 |
+
elif isinstance(module, AttentionBlock):
|
| 159 |
+
h = module(h)
|
| 160 |
+
else:
|
| 161 |
+
h = module(h)
|
| 162 |
+
skips.append(h)
|
| 163 |
+
|
| 164 |
+
for module in self.middle:
|
| 165 |
+
if isinstance(module, ResidualBlock):
|
| 166 |
+
h = module(h, emb)
|
| 167 |
+
else:
|
| 168 |
+
h = module(h)
|
| 169 |
+
|
| 170 |
+
for module in self.up_blocks:
|
| 171 |
+
if isinstance(module, ResidualBlock):
|
| 172 |
+
h = torch.cat([h, skips.pop()], dim=1)
|
| 173 |
+
h = module(h, emb)
|
| 174 |
+
elif isinstance(module, AttentionBlock):
|
| 175 |
+
h = module(h)
|
| 176 |
+
else:
|
| 177 |
+
h = module(h)
|
| 178 |
+
|
| 179 |
+
return self.conv_out(h)
|