collins909 commited on
Commit
0d05ab1
·
verified ·
1 Parent(s): bacbb22

Upload 2-parameter conditional DDPM (HI emulation, CAMELS LH params_2, epoch 200)

Browse files
README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 — 2 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 **two cosmological parameters**
21
+ (e.g. Ωm, σ8). Sampling supports both full DDPM and accelerated DDIM.
22
+
23
+ This checkpoint is **epoch 200** of the training run carried out under
24
+ `DDPM_HI_Emulation_improved/outputs_conditional_2label_20260408_125646/`.
25
+
26
+ ## Files in this repo
27
+
28
+ | File | Purpose |
29
+ |------|---------|
30
+ | `model.pt` | PyTorch checkpoint (state-dict for `ConditionalDiffusionModel`) |
31
+ | `args.json` / `args.txt` | Training hyper-parameters and U-Net configuration |
32
+ | `config.json` | Architecture summary (for Hub discoverability) |
33
+ | `src/unet_conditional.py` | `ConditionalUNet` module |
34
+ | `src/diffusion_conditional.py` | `GaussianDiffusion` (DDPM + DDIM) and the wrapping `ConditionalDiffusionModel` |
35
+ | `src/dataset_conditional.py` | Helper for loading CAMELS LH data + label normalisation stats |
36
+ | `src/evaluate_conditional.py` | Reference evaluation pipeline (samples + metrics) |
37
+ | `inference_example.py` | Runnable example: downloads weights and generates a sample |
38
+
39
+ ## Architecture
40
+
41
+ Conditional U-Net + Gaussian diffusion process. Hyper-parameters (taken from
42
+ `args.json`):
43
+
44
+ | Field | Value |
45
+ |-------|-------|
46
+ | `label_dim` | 2 |
47
+ | `base_channels` | 64 |
48
+ | `channel_multipliers` | [1, 2, 4, 8] |
49
+ | `attention_levels` | [2, 3] |
50
+ | `dropout` | 0.1 |
51
+ | `timesteps` | 1500 (linear β schedule: 1e-4 → 0.02) |
52
+ | EMA decay | 0.9999 |
53
+ | Sampler | DDIM, 50 steps (DDPM also supported) |
54
+ | Image size | 256 × 256, single channel |
55
+ | Image range | [-1, 1] (training data is rescaled by `x * 2 - 1`) |
56
+
57
+ Labels are z-scored using the **training-split** mean / std. The
58
+ `inference_example.py` shows how to recover this normalisation from the
59
+ CAMELS LH `params_2` dataset, or you can pass already-normalised conditioning
60
+ values directly.
61
+
62
+ ## Quick start
63
+
64
+ ```python
65
+ from huggingface_hub import hf_hub_download
66
+ import sys, torch, json
67
+ from pathlib import Path
68
+
69
+ # 1) Download all needed files
70
+ repo = "collinsmaripane/ddpm-hi-2param"
71
+ ckpt_path = hf_hub_download(repo, "model.pt")
72
+ args_path = hf_hub_download(repo, "args.json")
73
+ # Pull the bundled source files so we can import the model classes.
74
+ for name in ("unet_conditional.py", "diffusion_conditional.py", "__init__.py"):
75
+ hf_hub_download(repo, f"src/{name}")
76
+ sys.path.insert(0, str(Path(ckpt_path).parent / "src"))
77
+
78
+ from unet_conditional import ConditionalUNet
79
+ from diffusion_conditional import GaussianDiffusion, ConditionalDiffusionModel
80
+
81
+ # 2) Rebuild the model from args.json
82
+ args = json.loads(Path(args_path).read_text())
83
+ unet = ConditionalUNet(
84
+ in_channels=1, out_channels=1,
85
+ label_dim=args["label_dim"],
86
+ base_channels=args["base_channels"],
87
+ channel_multipliers=tuple(args["channel_multipliers"]),
88
+ attention_levels=tuple(args["attention_levels"]),
89
+ dropout=args["dropout"],
90
+ )
91
+ diffusion = GaussianDiffusion(
92
+ timesteps=args["timesteps"],
93
+ beta_start=args["beta_start"],
94
+ beta_end=args["beta_end"],
95
+ schedule_type=args["schedule_type"],
96
+ )
97
+ model = ConditionalDiffusionModel(unet, diffusion)
98
+
99
+ # 3) Load the checkpoint and sample
100
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
101
+ model.load_state_dict(ckpt["model_state_dict"])
102
+ model.eval()
103
+
104
+ # Conditioning vector must be z-scored using training-split label statistics.
105
+ labels = torch.tensor([[0.0, 0.0]]) # placeholder; see inference_example.py
106
+ sample = model.sample(labels, channels=1, height=256, width=256,
107
+ device="cpu", use_ddim=True, ddim_steps=50)
108
+ # sample is in [-1, 1]; rescale to physical HI units as needed.
109
+ ```
110
+
111
+ For an end-to-end runnable example (including label normalisation, GPU usage,
112
+ and image saving), see `inference_example.py` in this repo.
113
+
114
+ ## Training data
115
+
116
+ Trained on **CAMELS LH** HI maps with 2-label conditioning. The exact data
117
+ layout used by `src/dataset_conditional.py` is:
118
+
119
+ ```
120
+ <data_dir>/
121
+ train_LH_2.npy, val_LH_2.npy, test_LH_2.npy
122
+ train_labels_LH.npy, val_labels_LH.npy, test_labels_LH.npy
123
+ ```
124
+
125
+ Images are rescaled to `[-1, 1]`; labels are z-scored using train-split
126
+ statistics. The original training paths on the cluster were
127
+ `/scratch/mrpcol001/Diffusion_job/data/LH_data/params_2`.
128
+
129
+ ## Intended use & limitations
130
+
131
+ - Intended for **research** on diffusion emulators for cosmological fields.
132
+ - The 2-label setup is a simplified subset of the full CAMELS LH parameter
133
+ space; see the companion **6-parameter** model
134
+ (`collinsmaripane/ddpm-hi-6param`) for the full conditioning.
135
+ - Outputs are 256 × 256 single-channel maps in the model's normalised range.
136
+ Apply the inverse of any data-pipeline preprocessing before physical
137
+ interpretation.
138
+
139
+ ## Citation
140
+
141
+ If you use this checkpoint, please cite the CAMELS project and the upstream
142
+ DDPM HI emulation work. (Citation block to be filled in once the
143
+ accompanying paper is published.)
args.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "label_dim": 2,
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": 210,
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": false,
26
+ "data_dir": "/scratch/mrpcol001/Diffusion_job/data/LH_data/params_2",
27
+ "normalize_labels": true,
28
+ "output_dir": "outputs_conditional_2label",
29
+ "resume": "outputs_conditional_2label_20260401_164603/checkpoints/checkpoint_epoch_160.pt",
30
+ "resume_refresh_scheduler": true,
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: 2
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: 210
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: False
17
+ data_dir: /scratch/mrpcol001/Diffusion_job/data/LH_data/params_2
18
+ normalize_labels: True
19
+ output_dir: outputs_conditional_2label
20
+ resume: outputs_conditional_2label_20260401_164603/checkpoints/checkpoint_epoch_160.pt
21
+ resume_refresh_scheduler: True
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": 2,
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:545b39a5a4bfb58a230c9abfaf73006069a26f9b50cd2cc9e01b3693764ca1ce
3
+ size 1070314125
src/__init__.py ADDED
File without changes
src/dataset_conditional.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conditional Dataset loader with labels
3
+ """
4
+
5
+ import torch
6
+ from torch.utils.data import Dataset, DataLoader
7
+ import numpy as np
8
+ import os
9
+
10
+
11
+ class ConditionalImageDataset(Dataset):
12
+ def __init__(self, data_path, label_path, transform=None, label_stats=None):
13
+ self.data = np.load(data_path)
14
+ self.labels = np.load(label_path)
15
+ self.transform = transform
16
+ self.label_stats = label_stats
17
+
18
+ assert len(self.data) == len(self.labels), f"Data and labels length mismatch! {len(self.data)} vs {len(self.labels)}"
19
+
20
+ print(f"Loaded {len(self.data)} images | Image shape: {self.data.shape[1:]} | Label shape: {self.labels.shape[1:]}")
21
+
22
+ def __len__(self):
23
+ return len(self.data)
24
+
25
+ def __getitem__(self, idx):
26
+ img = torch.from_numpy(self.data[idx]).float()
27
+ label = torch.from_numpy(self.labels[idx]).float()
28
+
29
+ # Normalize image to [-1, 1]
30
+ img = img * 2.0 - 1.0
31
+
32
+ # Normalize labels
33
+ if self.label_stats is not None:
34
+ label = (label - self.label_stats['mean']) / self.label_stats['std']
35
+
36
+ if img.dim() == 2:
37
+ img = img.unsqueeze(0)
38
+
39
+ return img, label
40
+
41
+
42
+ def get_conditional_dataloaders(
43
+ data_dir='./data/params_2',
44
+ batch_size=8,
45
+ num_workers=4,
46
+ pin_memory=True,
47
+ normalize_labels=True
48
+ ):
49
+ is_6param = 'params_6' in data_dir
50
+
51
+ if is_6param:
52
+ train_data = os.path.join(data_dir, 'train_LH_6.npy')
53
+ val_data = os.path.join(data_dir, 'val_LH_6.npy')
54
+ test_data = os.path.join(data_dir, 'test_LH_6.npy')
55
+ train_labels = os.path.join(data_dir, 'train_labels_LH.npy')
56
+ val_labels = os.path.join(data_dir, 'val_labels_LH.npy')
57
+ test_labels = os.path.join(data_dir, 'test_labels_LH.npy')
58
+ else:
59
+ train_data = os.path.join(data_dir, 'train_LH.npy')
60
+ val_data = os.path.join(data_dir, 'val_LH.npy')
61
+ test_data = os.path.join(data_dir, 'test_LH.npy')
62
+ train_labels = os.path.join(data_dir, 'train_labels_LH_2.npy')
63
+ val_labels = os.path.join(data_dir, 'val_labels_LH_2.npy')
64
+ test_labels = os.path.join(data_dir, 'test_labels_LH_2.npy')
65
+
66
+ print(f"Loading dataset from {data_dir} ({'6-param' if is_6param else '2-param'})")
67
+
68
+ # Label normalization stats
69
+ label_stats = None
70
+ if normalize_labels:
71
+ train_labels_array = np.load(train_labels)
72
+ label_mean = train_labels_array.mean(axis=0)
73
+ label_std = train_labels_array.std(axis=0)
74
+ label_std = np.where(label_std == 0, 1.0, label_std) # guard against zero-variance labels
75
+ label_stats = {'mean': torch.from_numpy(label_mean).float(), 'std': torch.from_numpy(label_std).float()}
76
+ print(f"Label normalization -> mean={label_mean}, std={label_std}")
77
+
78
+ train_dataset = ConditionalImageDataset(train_data, train_labels, label_stats=label_stats)
79
+ val_dataset = ConditionalImageDataset(val_data, val_labels, label_stats=label_stats)
80
+ test_dataset = ConditionalImageDataset(test_data, test_labels, label_stats=label_stats)
81
+
82
+ train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory, drop_last=True)
83
+ val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory, drop_last=False)
84
+ test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory, drop_last=False)
85
+
86
+ 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,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Evaluate Conditional Diffusion Model (2-label: Omega_m, sigma_8)
3
+
4
+ Usage:
5
+ python evaluate_conditional.py --checkpoint outputs_conditional_YYYYMMDD_HHMMSS/checkpoints/best_model.pt
6
+
7
+ Changes from original:
8
+ - Loads args.json (saved by improved training script) for robust config parsing
9
+ - Falls back to args.txt parsing if JSON not available
10
+ - Vectorized power spectrum calculation (~100x speedup)
11
+ - Added weights_only parameter to torch.load
12
+ """
13
+
14
+ import argparse
15
+ import ast
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Dict, Tuple
20
+
21
+ import matplotlib
22
+ matplotlib.use("Agg")
23
+ import matplotlib.pyplot as plt
24
+ import numpy as np
25
+ import torch
26
+
27
+ from diffusion_conditional import GaussianDiffusion, ConditionalDiffusionModel
28
+ from unet_conditional import ConditionalUNet
29
+
30
+
31
+ def parse_args() -> argparse.Namespace:
32
+ parser = argparse.ArgumentParser(description="Evaluate conditional 2-label diffusion model")
33
+ parser.add_argument(
34
+ "--checkpoint",
35
+ type=str,
36
+ required=True,
37
+ help="Path to trained checkpoint (e.g. outputs_conditional_*/checkpoints/best_model.pt)",
38
+ )
39
+ parser.add_argument(
40
+ "--training_args",
41
+ type=str,
42
+ default=None,
43
+ help="Path to args.json or args.txt from training (auto-detected if not provided)",
44
+ )
45
+ parser.add_argument(
46
+ "--data_dir",
47
+ type=str,
48
+ default="./data/params_2",
49
+ help="Directory containing the CAMELS LH dataset (default matches repo structure)",
50
+ )
51
+ parser.add_argument(
52
+ "--split",
53
+ type=str,
54
+ default="test",
55
+ choices=["train", "val", "test"],
56
+ help="Which split to use for real images",
57
+ )
58
+ parser.add_argument(
59
+ "--num_samples",
60
+ type=int,
61
+ default=8,
62
+ help="Number of examples to show in the comparison grid",
63
+ )
64
+ parser.add_argument(
65
+ "--seed",
66
+ type=int,
67
+ default=42,
68
+ help="Random seed for reproducibility",
69
+ )
70
+ parser.add_argument(
71
+ "--output_dir",
72
+ type=str,
73
+ default="evaluation_outputs",
74
+ help="Where to save plots and results",
75
+ )
76
+ parser.add_argument(
77
+ "--ddim_steps",
78
+ type=int,
79
+ default=50,
80
+ help="Number of DDIM sampling steps",
81
+ )
82
+ return parser.parse_args()
83
+
84
+
85
+ def load_training_config(path: str) -> Dict:
86
+ """Load training configuration. Prefers JSON, falls back to txt parsing."""
87
+ # Try JSON first (written by improved training script)
88
+ json_path = path.replace('.txt', '.json') if path.endswith('.txt') else path
89
+ if json_path.endswith('.json') and os.path.isfile(json_path):
90
+ with open(json_path, 'r') as f:
91
+ return json.load(f)
92
+
93
+ # Fall back to txt parsing
94
+ if not os.path.isfile(path):
95
+ raise FileNotFoundError(f"Training args file not found: {path}")
96
+
97
+ config = {}
98
+ with open(path, "r", encoding="utf-8") as f:
99
+ for line in f:
100
+ line = line.strip()
101
+ if not line or ":" not in line:
102
+ continue
103
+ key, value = line.split(":", 1)
104
+ key = key.strip()
105
+ value = value.strip()
106
+
107
+ if value.startswith("[") and value.endswith("]"):
108
+ try:
109
+ config[key] = ast.literal_eval(value)
110
+ except (ValueError, SyntaxError):
111
+ config[key] = value
112
+ elif value.isdigit():
113
+ config[key] = int(value)
114
+ elif value.replace(".", "", 1).replace("e-", "", 1).replace("e", "", 1).isdigit():
115
+ config[key] = float(value)
116
+ else:
117
+ config[key] = value
118
+
119
+ return config
120
+
121
+
122
+ def _detect_label_suffix(data_dir: Path) -> str:
123
+ """Detect whether this is a 2-param or 6-param dataset."""
124
+ if (data_dir / "train_labels_LH_2.npy").exists():
125
+ return "_2"
126
+ elif (data_dir / "train_labels_LH.npy").exists():
127
+ return ""
128
+ else:
129
+ raise FileNotFoundError(f"No label files found in {data_dir}")
130
+
131
+
132
+ def _detect_image_suffix(data_dir: Path) -> str:
133
+ """Detect whether images use _6 suffix (6-param) or not."""
134
+ if (data_dir / "train_LH.npy").exists():
135
+ return ""
136
+ elif (data_dir / "train_LH_6.npy").exists():
137
+ return "_6"
138
+ else:
139
+ raise FileNotFoundError(f"No image files found in {data_dir}")
140
+
141
+
142
+ def load_label_stats(data_dir: Path) -> Tuple[np.ndarray, np.ndarray]:
143
+ """Load mean and std from training labels (used for normalization)."""
144
+ suffix = _detect_label_suffix(data_dir)
145
+ labels_path = data_dir / f"train_labels_LH{suffix}.npy"
146
+ labels = np.load(labels_path)
147
+ mean, std = labels.mean(axis=0), labels.std(axis=0)
148
+ std = np.where(std == 0, 1.0, std) # guard against zero-variance labels
149
+ return mean, std
150
+
151
+
152
+ def load_split(data_dir: Path, split: str) -> Tuple[np.ndarray, np.ndarray]:
153
+ """Load images and labels for a given split."""
154
+ img_suffix = _detect_image_suffix(data_dir)
155
+ label_suffix = _detect_label_suffix(data_dir)
156
+
157
+ image_path = data_dir / f"{split}_LH{img_suffix}.npy"
158
+ label_path = data_dir / f"{split}_labels_LH{label_suffix}.npy"
159
+
160
+ if not image_path.exists():
161
+ raise FileNotFoundError(f"Image file not found: {image_path}")
162
+ if not label_path.exists():
163
+ raise FileNotFoundError(f"Label file not found: {label_path}")
164
+
165
+ images = np.load(image_path).astype(np.float32)
166
+ labels = np.load(label_path).astype(np.float32)
167
+ return images, labels
168
+
169
+
170
+ def build_model(config: Dict, device: torch.device) -> ConditionalDiffusionModel:
171
+ """Rebuild the exact same model architecture used during training."""
172
+ unet = ConditionalUNet(
173
+ in_channels=1,
174
+ out_channels=1,
175
+ label_dim=int(config.get("label_dim", 2)),
176
+ base_channels=int(config.get("base_channels", 64)),
177
+ channel_multipliers=config.get("channel_multipliers", [1, 2, 4, 8]),
178
+ attention_levels=config.get("attention_levels", [2, 3]),
179
+ dropout=float(config.get("dropout", 0.1)),
180
+ )
181
+
182
+ diffusion = GaussianDiffusion(
183
+ timesteps=int(config.get("timesteps", 1500)),
184
+ beta_start=float(config.get("beta_start", 1e-4)),
185
+ beta_end=float(config.get("beta_end", 0.02)),
186
+ schedule_type=config.get("schedule_type", "linear"),
187
+ )
188
+
189
+ return ConditionalDiffusionModel(unet, diffusion).to(device)
190
+
191
+
192
+ def load_checkpoint(model: ConditionalDiffusionModel, checkpoint_path: str, device: torch.device):
193
+ """Load model weights from checkpoint."""
194
+ checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
195
+ state_dict = checkpoint["model_state_dict"] if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint else checkpoint
196
+
197
+ # If EMA weights are available, use them (they are the better weights)
198
+ if isinstance(checkpoint, dict) and "ema_shadow" in checkpoint:
199
+ print("Loading EMA shadow weights from checkpoint")
200
+ ema_shadow = checkpoint["ema_shadow"]
201
+ current_state = model.state_dict()
202
+ for name, param in ema_shadow.items():
203
+ if name in current_state:
204
+ current_state[name] = param
205
+ model.load_state_dict(current_state)
206
+ else:
207
+ model.load_state_dict(state_dict)
208
+
209
+ model.eval()
210
+ print(f"Loaded checkpoint: {checkpoint_path}")
211
+
212
+
213
+ def PowerSpectrum(box: np.ndarray, N: int, dl: float) -> Tuple[np.ndarray, np.ndarray]:
214
+ """Vectorized 2D power spectrum computation."""
215
+ FT_box = np.fft.fftn(box, norm="ortho")
216
+ k = 2 * np.pi * np.fft.fftfreq(N, dl)
217
+ dk_val = 2 * np.pi / (N * dl)
218
+
219
+ # Vectorized: compute k magnitudes and bin indices for all pixels at once
220
+ ki, kj = np.meshgrid(k, k, indexing='ij')
221
+ kbar = np.sqrt(ki**2 + kj**2)
222
+ n_bins = N // 2 # only bins up to Nyquist frequency
223
+ t_idx = np.round(kbar / dk_val).astype(int)
224
+
225
+ # Mask out modes beyond Nyquist to avoid bin contamination
226
+ valid = t_idx < n_bins
227
+ power = (FT_box * np.conj(FT_box)).real
228
+
229
+ pk = np.zeros(n_bins)
230
+ count = np.zeros(n_bins)
231
+ np.add.at(pk, t_idx[valid], power[valid])
232
+ np.add.at(count, t_idx[valid], 1)
233
+
234
+ pk /= np.where(count == 0, 1, count)
235
+ pk *= dl**2
236
+ dk = np.arange(n_bins) * dk_val
237
+ return dk, pk
238
+
239
+
240
+ def calculate_pdf_batch(images: np.ndarray, log_nhi_min=14.0, log_nhi_max=22.0, n_bins=100):
241
+ images_01 = np.clip(images, 0.0, 1.0)
242
+ log_nhi_bins = np.linspace(log_nhi_min, log_nhi_max, n_bins)
243
+ bin_centers = 0.5 * (log_nhi_bins[:-1] + log_nhi_bins[1:])
244
+
245
+ pdfs = []
246
+ for img in images_01:
247
+ log_nhi_values = log_nhi_min + (log_nhi_max - log_nhi_min) * img.reshape(-1)
248
+ hist, _ = np.histogram(log_nhi_values, bins=log_nhi_bins, density=True)
249
+ pdfs.append(hist)
250
+
251
+ pdf_array = np.stack(pdfs)
252
+ return bin_centers, pdf_array.mean(axis=0), pdf_array.std(axis=0)
253
+
254
+
255
+ def calculate_power_spectrum_batch(images: np.ndarray, box_size: float = 25.0):
256
+ N = images.shape[-1]
257
+ dl = box_size / N
258
+
259
+ # Compute k-values once, then reuse for all images
260
+ dk, _ = PowerSpectrum(images[0], N=N, dl=dl)
261
+ power_spectra = [PowerSpectrum(img, N=N, dl=dl)[1] for img in images]
262
+ power_array = np.stack(power_spectra)
263
+ return dk, power_array.mean(axis=0), power_array.std(axis=0)
264
+
265
+
266
+ def prepare_labels_for_model(labels: np.ndarray, mean: np.ndarray, std: np.ndarray) -> torch.Tensor:
267
+ normalized = (labels - mean) / std
268
+ return torch.from_numpy(normalized).float()
269
+
270
+
271
+ def from_model_output(samples: torch.Tensor) -> np.ndarray:
272
+ arrays = samples.cpu().numpy()
273
+ return np.clip((arrays + 1.0) / 2.0, 0.0, 1.0)[:, 0, :, :]
274
+
275
+
276
+ def plot_image_grid(generated, real, labels, output_path: Path, num_samples=8):
277
+ num = min(num_samples, generated.shape[0])
278
+ fig, axes = plt.subplots(num, 2, figsize=(6, 3 * num))
279
+ if num == 1:
280
+ axes = np.expand_dims(axes, axis=0)
281
+
282
+ for i in range(num):
283
+ label_str = ", ".join(f"{v:.3f}" for v in labels[i])
284
+ axes[i, 0].imshow(generated[i], cmap="magma", origin="lower")
285
+ axes[i, 0].set_title(f"Generated\n{label_str}")
286
+ axes[i, 0].axis("off")
287
+
288
+ axes[i, 1].imshow(real[i], cmap="magma", origin="lower")
289
+ axes[i, 1].set_title("Real")
290
+ axes[i, 1].axis("off")
291
+
292
+ plt.tight_layout()
293
+ fig.savefig(output_path, dpi=200, bbox_inches="tight")
294
+ plt.close(fig)
295
+
296
+
297
+ def plot_mean_std(x, mean_real, std_real, mean_gen, std_gen, xlabel, ylabel, title, output_path: Path, yscale="linear"):
298
+ fig, ax = plt.subplots(figsize=(10, 6))
299
+ ax.plot(x, mean_real, label="Real mean", color="tab:blue", linewidth=2)
300
+ ax.plot(x, mean_gen, label="Generated mean", color="tab:orange", linewidth=2)
301
+
302
+ ax.fill_between(x, mean_real - std_real, mean_real + std_real, color="tab:blue", alpha=0.15, label="Real +/-1s")
303
+ ax.fill_between(x, mean_real - 3*std_real, mean_real + 3*std_real, color="tab:blue", alpha=0.05)
304
+
305
+ ax.fill_between(x, mean_gen - std_gen, mean_gen + std_gen, color="tab:orange", alpha=0.15, label="Generated +/-1s")
306
+ ax.fill_between(x, mean_gen - 3*std_gen, mean_gen + 3*std_gen, color="tab:orange", alpha=0.05)
307
+
308
+ ax.set_xlabel(xlabel)
309
+ ax.set_ylabel(ylabel)
310
+ ax.set_title(title)
311
+ ax.set_yscale(yscale)
312
+ ax.legend()
313
+ ax.grid(alpha=0.3)
314
+ fig.tight_layout()
315
+ fig.savefig(output_path, dpi=200, bbox_inches="tight")
316
+ plt.close(fig)
317
+
318
+
319
+ def main():
320
+ args = parse_args()
321
+ torch.manual_seed(args.seed)
322
+ np.random.seed(args.seed)
323
+
324
+ output_dir = Path(args.output_dir)
325
+ output_dir.mkdir(parents=True, exist_ok=True)
326
+
327
+ # Load training config
328
+ if args.training_args is None:
329
+ # Try JSON first, then txt
330
+ possible_json = list(Path(".").glob("outputs_conditional_*/args.json"))
331
+ possible_txt = list(Path(".").glob("outputs_conditional_*/args.txt"))
332
+ possible = possible_json + possible_txt
333
+ if possible:
334
+ args.training_args = str(max(possible, key=os.path.getctime))
335
+ print(f"Auto-detected training args: {args.training_args}")
336
+ else:
337
+ raise FileNotFoundError("Please provide --training_args path to your training args.json or args.txt")
338
+
339
+ config = load_training_config(args.training_args)
340
+
341
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
342
+ model = build_model(config, device)
343
+ load_checkpoint(model, args.checkpoint, device)
344
+
345
+ # Load data
346
+ data_dir = Path(args.data_dir)
347
+ images_split, labels_split = load_split(data_dir, args.split)
348
+ label_mean, label_std = load_label_stats(data_dir)
349
+
350
+ # Select random samples
351
+ num_select = min(100, len(images_split))
352
+ indices = np.random.choice(len(images_split), num_select, replace=False)
353
+
354
+ real_images = images_split[indices]
355
+ original_labels = labels_split[indices]
356
+
357
+ # Generate samples in batches
358
+ batch_size = min(8, num_select)
359
+ generated_list = []
360
+
361
+ print(f"Generating {num_select} samples (batch size = {batch_size})...")
362
+ for i in range(0, num_select, batch_size):
363
+ batch_labels = original_labels[i:i+batch_size]
364
+ batch_labels_tensor = prepare_labels_for_model(batch_labels, label_mean, label_std).to(device)
365
+
366
+ with torch.no_grad():
367
+ batch_gen = model.sample(
368
+ labels=batch_labels_tensor,
369
+ channels=1,
370
+ height=real_images.shape[-2],
371
+ width=real_images.shape[-1],
372
+ device=device,
373
+ progress=False,
374
+ use_ddim=True,
375
+ ddim_steps=args.ddim_steps,
376
+ )
377
+ generated_list.append(from_model_output(batch_gen))
378
+ print(f" Batch {i//batch_size + 1}/{(num_select+batch_size-1)//batch_size} done")
379
+
380
+ generated_images = np.concatenate(generated_list, axis=0)
381
+
382
+ # Plots
383
+ plot_image_grid(generated_images, real_images, original_labels,
384
+ output_dir / "real_vs_generated.png", num_samples=args.num_samples)
385
+
386
+ # PDF
387
+ bin_centers, mean_pdf_real, std_pdf_real = calculate_pdf_batch(real_images)
388
+ _, mean_pdf_gen, std_pdf_gen = calculate_pdf_batch(generated_images)
389
+ plot_mean_std(bin_centers, mean_pdf_real, std_pdf_real, mean_pdf_gen, std_pdf_gen,
390
+ "log N_HI [cm^-2]", "PDF", "Column Density PDF", output_dir / "pdf_mean_std.png")
391
+
392
+ # Power Spectrum (skip k=0 DC component for log-scale plotting)
393
+ dk, mean_pk_real, std_pk_real = calculate_power_spectrum_batch(real_images)
394
+ _, mean_pk_gen, std_pk_gen = calculate_power_spectrum_batch(generated_images)
395
+ plot_mean_std(dk[1:], mean_pk_real[1:], std_pk_real[1:], mean_pk_gen[1:], std_pk_gen[1:],
396
+ "k [h/Mpc]", "P(k)", "Power Spectrum", output_dir / "power_spectrum_mean_std.png", yscale="log")
397
+
398
+ # Save numerical results
399
+ np.savez(
400
+ output_dir / "evaluation_data.npz",
401
+ indices=indices,
402
+ labels_original=original_labels,
403
+ bin_centers=bin_centers,
404
+ mean_pdf_real=mean_pdf_real, std_pdf_real=std_pdf_real,
405
+ mean_pdf_gen=mean_pdf_gen, std_pdf_gen=std_pdf_gen,
406
+ dk=dk,
407
+ mean_pk_real=mean_pk_real, std_pk_real=std_pk_real,
408
+ mean_pk_gen=mean_pk_gen, std_pk_gen=std_pk_gen,
409
+ )
410
+
411
+ print(f"\nEvaluation complete!")
412
+ print(f" Plots saved to: {output_dir}")
413
+ print(f" Numerical data saved to: {output_dir}/evaluation_data.npz")
414
+
415
+
416
+ if __name__ == "__main__":
417
+ 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)