ManmohanSharma commited on
Commit
d6d4411
·
verified ·
1 Parent(s): 3b56974

Upload code/hybrid_redshift.py

Browse files
Files changed (1) hide show
  1. code/hybrid_redshift.py +1278 -0
code/hybrid_redshift.py ADDED
@@ -0,0 +1,1278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import math
7
+ import os
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import matplotlib
14
+
15
+ matplotlib.use("Agg")
16
+
17
+ import matplotlib.pyplot as plt
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from torch import nn
22
+ from torch.optim import AdamW
23
+ from torch.utils.data import DataLoader, WeightedRandomSampler
24
+ from tqdm import tqdm
25
+
26
+ from .data import SpectraListDataset, collect_mmu_desi, compute_sample_stats, split_indices, valid_pixel_mask
27
+ from .metrics import LossConfig, masked_huber, redshift_losses, redshift_metrics
28
+ from .model import fourier_loglam
29
+ from .plots import plot_reconstruction_batch, plot_redshift_scatter
30
+
31
+
32
+ @dataclass
33
+ class RawCollatorConfig:
34
+ target_length: int = 4096
35
+ min_scale: float = 1e-3
36
+ random_mask_ratio: float = 0.0
37
+ eval_mask_ratio: float = 0.25
38
+ mask_mode: str = "pixel"
39
+ mask_span_min: int = 16
40
+ mask_span_max: int = 64
41
+ line_region_percentile: float = 90.0
42
+ augment_ood: bool = False
43
+ crop_prob: float = 0.0
44
+ bad_window_prob: float = 0.0
45
+ throughput_prob: float = 0.0
46
+ noise_prob: float = 0.0
47
+ resolution_prob: float = 0.0
48
+ downsample_prob: float = 0.0
49
+ line_dropout_prob: float = 0.0
50
+ span_dropout_prob: float = 0.0
51
+ redshift_shift: float = 0.0
52
+
53
+
54
+ class RawSpectraCollator:
55
+ def __init__(self, cfg: RawCollatorConfig, train: bool = True, seed: int = 17):
56
+ self.cfg = cfg
57
+ self.train = train
58
+ self.seed = seed
59
+ self.rng = np.random.default_rng(seed)
60
+
61
+ def __call__(self, samples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
62
+ items = [self._prepare_sample(s) for s in samples]
63
+ x = np.stack([item["x"] for item in items], axis=0).astype(np.float32)
64
+ valid = np.stack([item["valid"] for item in items], axis=0).astype(np.bool_)
65
+ loglam = np.stack([item["loglam"] for item in items], axis=0).astype(np.float32)
66
+ target_flux = np.stack([item["target_flux"] for item in items], axis=0).astype(np.float32)
67
+ loss_mask = np.stack([item["loss_mask"] for item in items], axis=0).astype(np.bool_)
68
+ line_weight = np.stack([item["line_weight"] for item in items], axis=0).astype(np.float32)
69
+ line_region = np.stack([item["line_region"] for item in items], axis=0).astype(np.bool_)
70
+ z = np.asarray([item["z"] for item in items], dtype=np.float32)
71
+ y = np.asarray([item["y"] for item in items], dtype=np.float32)
72
+ zwarn = np.asarray([item["zwarn"] for item in items], dtype=np.bool_)
73
+ return {
74
+ "x": torch.from_numpy(x),
75
+ "valid": torch.from_numpy(valid),
76
+ "loglam": torch.from_numpy(loglam),
77
+ "target_flux": torch.from_numpy(target_flux),
78
+ "loss_mask": torch.from_numpy(loss_mask),
79
+ "line_weight": torch.from_numpy(line_weight),
80
+ "line_region": torch.from_numpy(line_region),
81
+ "z": torch.from_numpy(z),
82
+ "y": torch.from_numpy(y),
83
+ "zwarn": torch.from_numpy(zwarn),
84
+ }
85
+
86
+ def _prepare_sample(self, sample: dict[str, Any]) -> dict[str, Any]:
87
+ rng = self.rng if self.train else self._eval_rng(sample)
88
+ flux = np.asarray(sample["flux"], dtype=np.float32).copy()
89
+ ivar = np.asarray(sample["ivar"], dtype=np.float32).copy()
90
+ lam = np.asarray(sample["lambda"], dtype=np.float32)
91
+ lsf = np.asarray(sample["lsf_sigma"], dtype=np.float32)
92
+ bad = np.asarray(sample["bad_mask"], dtype=np.bool_).copy()
93
+
94
+ if self.cfg.augment_ood:
95
+ bad = self._augment_bad_windows(bad, rng)
96
+ flux = self._augment_flux_calibration(flux, lam, rng)
97
+ flux = self._augment_resolution(flux, rng)
98
+ flux, ivar = self._augment_downsample_resample(flux, ivar, lam, rng)
99
+ flux = self._augment_noise(flux, ivar, rng)
100
+
101
+ valid = np.isfinite(flux) & np.isfinite(ivar) & np.isfinite(lam) & (ivar > 0) & (~bad)
102
+ loglam = np.log(np.clip(lam.astype(np.float64), 1.0, None)).astype(np.float32)
103
+ if valid.sum() < 16:
104
+ valid = valid_pixel_mask(sample)
105
+
106
+ grid = np.linspace(float(np.nanmin(loglam)), float(np.nanmax(loglam)), self.cfg.target_length, dtype=np.float32)
107
+ flux_grid = self._interp_valid(loglam, flux, valid, grid, fill=0.0)
108
+ ivar_grid = self._interp_valid(loglam, ivar, valid, grid, fill=0.0)
109
+ lsf_grid = self._interp_valid(loglam, lsf, valid, grid, fill=0.0)
110
+ valid_grid = np.interp(grid, loglam, valid.astype(np.float32), left=0.0, right=0.0) > 0.5
111
+
112
+ center = float(np.nanmedian(flux_grid[valid_grid])) if valid_grid.any() else 0.0
113
+ dev = np.abs(flux_grid[valid_grid] - center) if valid_grid.any() else np.asarray([1.0], dtype=np.float32)
114
+ scale = float(np.nanmedian(dev) * 1.4826)
115
+ if not math.isfinite(scale) or scale < self.cfg.min_scale:
116
+ scale = max(float(np.nanmedian(np.abs(flux_grid[valid_grid]))) if valid_grid.any() else 1.0, self.cfg.min_scale)
117
+
118
+ norm_flux = np.arcsinh((flux_grid - center) / scale).astype(np.float32)
119
+ norm_ivar = np.log1p(np.maximum(ivar_grid * scale * scale, 0.0)).astype(np.float32)
120
+ norm_ivar = np.clip(norm_ivar / 8.0, 0.0, 4.0)
121
+ lsf_norm = np.nan_to_num(lsf_grid / 3.0, nan=0.0, posinf=0.0, neginf=0.0).astype(np.float32)
122
+ loglam_norm = ((grid - math.log(6000.0)) / 0.45).astype(np.float32)
123
+
124
+ grad = np.gradient(norm_flux, grid).astype(np.float32)
125
+ good_grad = np.abs(grad[valid_grid])
126
+ grad_scale = float(np.percentile(good_grad, 95)) if len(good_grad) else 1.0
127
+ if not math.isfinite(grad_scale) or grad_scale <= 0:
128
+ grad_scale = 1.0
129
+ grad = np.clip(grad / grad_scale, -5.0, 5.0).astype(np.float32)
130
+ abs_grad = np.abs(grad).astype(np.float32)
131
+
132
+ target_flux = norm_flux.copy()
133
+ line_weight = self._line_weights(abs_grad, valid_grid)
134
+ line_region = self._line_region(abs_grad, valid_grid)
135
+ corrupt = self._sample_input_dropout(abs_grad, valid_grid, rng)
136
+ if corrupt.any():
137
+ norm_flux = norm_flux.copy()
138
+ grad = grad.copy()
139
+ abs_grad = abs_grad.copy()
140
+ norm_flux[corrupt] = 0.0
141
+ grad[corrupt] = 0.0
142
+ abs_grad[corrupt] = 0.0
143
+
144
+ y = math.log1p(float(sample["z"]))
145
+ if self.train and self.cfg.redshift_shift > 0:
146
+ delta = float(self.rng.uniform(-self.cfg.redshift_shift, self.cfg.redshift_shift))
147
+ y = max(0.0, y + delta)
148
+ grid = (grid + delta).astype(np.float32)
149
+ loglam_norm = ((grid - math.log(6000.0)) / 0.45).astype(np.float32)
150
+
151
+ x = np.stack(
152
+ [
153
+ norm_flux,
154
+ norm_ivar,
155
+ valid_grid.astype(np.float32),
156
+ lsf_norm,
157
+ loglam_norm,
158
+ grad,
159
+ abs_grad,
160
+ corrupt.astype(np.float32),
161
+ ],
162
+ axis=0,
163
+ )
164
+ return {
165
+ "x": x,
166
+ "valid": valid_grid,
167
+ "loglam": grid,
168
+ "target_flux": target_flux,
169
+ "loss_mask": corrupt & valid_grid,
170
+ "line_weight": line_weight,
171
+ "line_region": line_region,
172
+ "z": sample["z"],
173
+ "y": np.float32(y),
174
+ "zwarn": sample["zwarn"],
175
+ }
176
+
177
+ def _eval_rng(self, sample: dict[str, Any]) -> np.random.Generator:
178
+ object_id = str(sample.get("object_id", ""))
179
+ lam = np.asarray(sample["lambda"], dtype=np.float32)
180
+ key = f"{self.seed}|{object_id}|{float(sample['z']):.8g}|{len(lam)}|{float(lam[0]):.4f}|{float(lam[-1]):.4f}"
181
+ digest = hashlib.blake2b(key.encode("utf-8"), digest_size=8).digest()
182
+ return np.random.default_rng(int.from_bytes(digest, "little", signed=False))
183
+
184
+ def _interp_valid(self, x: np.ndarray, y: np.ndarray, valid: np.ndarray, x_new: np.ndarray, fill: float) -> np.ndarray:
185
+ good = valid & np.isfinite(x) & np.isfinite(y)
186
+ if good.sum() < 2:
187
+ return np.full_like(x_new, fill, dtype=np.float32)
188
+ return np.interp(x_new, x[good], y[good], left=fill, right=fill).astype(np.float32)
189
+
190
+ def _augment_bad_windows(self, bad: np.ndarray, rng: np.random.Generator) -> np.ndarray:
191
+ out = bad.copy()
192
+ n = len(out)
193
+ if rng.random() < self.cfg.crop_prob:
194
+ frac = float(rng.uniform(0.62, 0.96))
195
+ width = max(32, int(n * frac))
196
+ start = int(rng.integers(0, max(1, n - width)))
197
+ keep = np.zeros(n, dtype=np.bool_)
198
+ keep[start : start + width] = True
199
+ out |= ~keep
200
+ if rng.random() < self.cfg.bad_window_prob:
201
+ for _ in range(int(rng.integers(1, 5))):
202
+ width = int(rng.integers(max(8, n // 240), max(12, n // 45)))
203
+ start = int(rng.integers(0, max(1, n - width)))
204
+ out[start : start + width] = True
205
+ return out
206
+
207
+ def _augment_flux_calibration(self, flux: np.ndarray, lam: np.ndarray, rng: np.random.Generator) -> np.ndarray:
208
+ if rng.random() >= self.cfg.throughput_prob:
209
+ return flux
210
+ x = np.linspace(-1.0, 1.0, len(flux), dtype=np.float32)
211
+ coeff = rng.normal(0.0, [0.05, 0.025, 0.015]).astype(np.float32)
212
+ curve = 1.0 + coeff[0] * x + coeff[1] * (x * x - 0.33) + coeff[2] * np.sin(np.pi * x)
213
+ return (flux * np.clip(curve, 0.65, 1.35)).astype(np.float32)
214
+
215
+ def _augment_noise(self, flux: np.ndarray, ivar: np.ndarray, rng: np.random.Generator) -> np.ndarray:
216
+ if rng.random() >= self.cfg.noise_prob:
217
+ return flux
218
+ sigma = np.zeros_like(flux, dtype=np.float32)
219
+ good = np.isfinite(ivar) & (ivar > 0)
220
+ sigma[good] = 1.0 / np.sqrt(np.maximum(ivar[good], 1e-8))
221
+ scale = float(rng.uniform(0.15, 0.75))
222
+ return (flux + rng.normal(0.0, sigma * scale).astype(np.float32)).astype(np.float32)
223
+
224
+ def _augment_resolution(self, flux: np.ndarray, rng: np.random.Generator) -> np.ndarray:
225
+ if rng.random() >= self.cfg.resolution_prob:
226
+ return flux
227
+ finite = np.isfinite(flux)
228
+ fill = float(np.nanmedian(flux[finite])) if finite.any() else 0.0
229
+ base = np.nan_to_num(flux, nan=fill, posinf=fill, neginf=fill).astype(np.float32)
230
+ sigma = float(rng.uniform(0.6, 3.0))
231
+ radius = max(2, int(math.ceil(4.0 * sigma)))
232
+ x = np.arange(-radius, radius + 1, dtype=np.float32)
233
+ kernel = np.exp(-0.5 * (x / sigma) ** 2)
234
+ kernel = (kernel / kernel.sum()).astype(np.float32)
235
+ padded = np.pad(base, (radius, radius), mode="edge")
236
+ return np.convolve(padded, kernel, mode="valid").astype(np.float32)
237
+
238
+ def _augment_downsample_resample(
239
+ self,
240
+ flux: np.ndarray,
241
+ ivar: np.ndarray,
242
+ lam: np.ndarray,
243
+ rng: np.random.Generator,
244
+ ) -> tuple[np.ndarray, np.ndarray]:
245
+ if rng.random() >= self.cfg.downsample_prob:
246
+ return flux, ivar
247
+ n = len(flux)
248
+ if n < 32:
249
+ return flux, ivar
250
+ factor = int(rng.choice(np.asarray([2, 3, 4, 6, 8], dtype=np.int64)))
251
+ offset = int(rng.integers(0, factor))
252
+ idx = np.arange(offset, n, factor, dtype=np.int64)
253
+ if len(idx) < 4:
254
+ return flux, ivar
255
+ lam_good = np.asarray(lam[idx], dtype=np.float32)
256
+ flux_good = np.asarray(flux[idx], dtype=np.float32)
257
+ ivar_good = np.asarray(ivar[idx], dtype=np.float32)
258
+ good = np.isfinite(lam_good) & np.isfinite(flux_good) & np.isfinite(ivar_good)
259
+ if np.count_nonzero(good) < 4:
260
+ return flux, ivar
261
+ lam_good = lam_good[good]
262
+ order = np.argsort(lam_good)
263
+ lam_good = lam_good[order]
264
+ flux_good = flux_good[good][order]
265
+ ivar_good = ivar_good[good][order]
266
+ flux_out = np.interp(lam, lam_good, flux_good, left=flux_good[0], right=flux_good[-1]).astype(np.float32)
267
+ ivar_out = np.interp(lam, lam_good, ivar_good, left=0.0, right=0.0).astype(np.float32)
268
+ ivar_out *= float(rng.uniform(0.25, 0.85))
269
+ return flux_out, ivar_out
270
+
271
+ def _sample_input_dropout(self, abs_grad: np.ndarray, valid: np.ndarray, rng: np.random.Generator) -> np.ndarray:
272
+ corrupt = np.zeros_like(valid, dtype=np.bool_)
273
+ if valid.sum() < 16:
274
+ return corrupt
275
+ n = len(valid)
276
+ valid_idx = np.where(valid)[0]
277
+ ratio = self.cfg.random_mask_ratio if self.train else self.cfg.eval_mask_ratio
278
+ if ratio > 0:
279
+ n_rand = max(1, int(round(len(valid_idx) * min(float(ratio), 1.0))))
280
+ if self.cfg.mask_mode == "pixel":
281
+ corrupt[rng.choice(valid_idx, size=min(n_rand, len(valid_idx)), replace=False)] = True
282
+ else:
283
+ line_bias = self.cfg.mask_mode in {"line_span", "mixed_span"}
284
+ self._add_spans_to_mask(corrupt, valid, abs_grad, n_rand, rng, line_bias=line_bias)
285
+ if self.train and rng.random() < self.cfg.span_dropout_prob:
286
+ for _ in range(int(rng.integers(1, 4))):
287
+ width = int(rng.integers(max(4, n // 220), max(8, n // 55)))
288
+ start = int(rng.integers(0, max(1, n - width)))
289
+ corrupt[start : start + width] |= valid[start : start + width]
290
+ if self.train and rng.random() < self.cfg.line_dropout_prob:
291
+ score = abs_grad.copy()
292
+ score[~valid] = 0.0
293
+ if np.count_nonzero(score) > 0:
294
+ k = max(4, n // 96)
295
+ peaks = np.argsort(score)[-k:]
296
+ for j in peaks:
297
+ width = int(rng.integers(max(2, n // 900), max(4, n // 280)))
298
+ lo = max(0, int(j) - width)
299
+ hi = min(n, int(j) + width + 1)
300
+ corrupt[lo:hi] |= valid[lo:hi]
301
+ return corrupt & valid
302
+
303
+ def _add_spans_to_mask(
304
+ self,
305
+ corrupt: np.ndarray,
306
+ valid: np.ndarray,
307
+ abs_grad: np.ndarray,
308
+ target_count: int,
309
+ rng: np.random.Generator,
310
+ *,
311
+ line_bias: bool,
312
+ ) -> None:
313
+ valid_idx = np.where(valid)[0]
314
+ if len(valid_idx) == 0:
315
+ return
316
+ lo_w = max(1, int(self.cfg.mask_span_min))
317
+ hi_w = max(lo_w + 1, int(self.cfg.mask_span_max) + 1)
318
+ probs = None
319
+ if line_bias:
320
+ score = abs_grad[valid_idx].astype(np.float64)
321
+ positive = score[np.isfinite(score) & (score > 0)]
322
+ scale = float(np.percentile(positive, 90)) if len(positive) else 1.0
323
+ if not math.isfinite(scale) or scale <= 0:
324
+ scale = 1.0
325
+ score = np.clip(score / scale, 0.0, 5.0) + 0.05
326
+ probs = score / score.sum()
327
+ max_tries = max(32, target_count * 4)
328
+ tries = 0
329
+ while int(np.count_nonzero(corrupt & valid)) < target_count and tries < max_tries:
330
+ tries += 1
331
+ center = int(rng.choice(valid_idx, p=probs))
332
+ width = int(rng.integers(lo_w, hi_w))
333
+ lo = max(0, center - width // 2)
334
+ hi = min(len(valid), lo + width)
335
+ corrupt[lo:hi] |= valid[lo:hi]
336
+
337
+ def _line_weights(self, abs_grad: np.ndarray, valid: np.ndarray) -> np.ndarray:
338
+ weight = np.ones_like(abs_grad, dtype=np.float32)
339
+ if valid.sum() < 16:
340
+ return weight
341
+ scale = float(np.percentile(abs_grad[valid], 90))
342
+ if math.isfinite(scale) and scale > 0:
343
+ weight += 2.0 * np.clip(abs_grad / scale, 0.0, 2.0)
344
+ weight[~valid] = 1.0
345
+ return np.clip(weight, 1.0, 5.0).astype(np.float32)
346
+
347
+ def _line_region(self, abs_grad: np.ndarray, valid: np.ndarray) -> np.ndarray:
348
+ region = np.zeros_like(valid, dtype=np.bool_)
349
+ if valid.sum() < 16:
350
+ return region
351
+ pct = min(max(float(self.cfg.line_region_percentile), 0.0), 100.0)
352
+ thresh = float(np.percentile(abs_grad[valid], pct))
353
+ if math.isfinite(thresh) and thresh > 0:
354
+ region = (abs_grad >= thresh) & valid
355
+ return region.astype(np.bool_)
356
+
357
+
358
+ class ConvBlock(nn.Module):
359
+ def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 7, stride: int = 1, dropout: float = 0.0):
360
+ super().__init__()
361
+ padding = kernel_size // 2
362
+ self.net = nn.Sequential(
363
+ nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False),
364
+ nn.BatchNorm1d(out_channels),
365
+ nn.GELU(),
366
+ nn.Dropout(dropout),
367
+ nn.Conv1d(out_channels, out_channels, kernel_size=kernel_size, stride=1, padding=padding, bias=False),
368
+ nn.BatchNorm1d(out_channels),
369
+ )
370
+ self.skip = (
371
+ nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
372
+ if stride != 1 or in_channels != out_channels
373
+ else nn.Identity()
374
+ )
375
+ self.act = nn.GELU()
376
+
377
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
378
+ return self.act(self.net(x) + self.skip(x))
379
+
380
+
381
+ class LayerScaleEncoderLayer(nn.Module):
382
+ def __init__(self, d_model: int, heads: int, dropout: float, layerscale_init: float):
383
+ super().__init__()
384
+ self.norm1 = nn.LayerNorm(d_model)
385
+ self.self_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
386
+ self.dropout1 = nn.Dropout(dropout)
387
+ self.norm2 = nn.LayerNorm(d_model)
388
+ self.linear1 = nn.Linear(d_model, d_model * 4)
389
+ self.linear2 = nn.Linear(d_model * 4, d_model)
390
+ self.dropout = nn.Dropout(dropout)
391
+ self.dropout2 = nn.Dropout(dropout)
392
+ self.act = nn.GELU()
393
+ init = float(layerscale_init)
394
+ self.ls1 = nn.Parameter(torch.full((d_model,), init))
395
+ self.ls2 = nn.Parameter(torch.full((d_model,), init))
396
+
397
+ def forward(
398
+ self,
399
+ src: torch.Tensor,
400
+ src_mask: torch.Tensor | None = None,
401
+ src_key_padding_mask: torch.Tensor | None = None,
402
+ is_causal: bool = False,
403
+ ) -> torch.Tensor:
404
+ q = self.norm1(src)
405
+ attn, _ = self.self_attn(
406
+ q,
407
+ q,
408
+ q,
409
+ attn_mask=src_mask,
410
+ key_padding_mask=src_key_padding_mask,
411
+ need_weights=False,
412
+ is_causal=is_causal,
413
+ )
414
+ src = src + self.ls1 * self.dropout1(attn)
415
+ ff = self.linear2(self.dropout(self.act(self.linear1(self.norm2(src)))))
416
+ return src + self.ls2 * self.dropout2(ff)
417
+
418
+
419
+ class HybridSpecZ(nn.Module):
420
+ def __init__(
421
+ self,
422
+ in_channels: int = 8,
423
+ d_model: int = 256,
424
+ conv_width: int = 128,
425
+ layers: int = 5,
426
+ heads: int = 8,
427
+ dropout: float = 0.1,
428
+ fourier_freqs: int = 32,
429
+ z_bins: int = 64,
430
+ y_min: float = 0.0,
431
+ y_max: float = math.log1p(6.0),
432
+ prediction_mode: str = "regression",
433
+ bin_temperature: float = 1.0,
434
+ residual_scale: float = 0.06,
435
+ candidate_topk: int = 5,
436
+ stem_stride: int = 8,
437
+ rec_hidden_mult: int = 0,
438
+ rec_refine_width: int = 16,
439
+ rec_refine_kernel: int = 5,
440
+ layerscale_init: float = 0.0,
441
+ ):
442
+ super().__init__()
443
+ allowed_modes = {"regression", "softbin", "hybrid", "bin_residual", "ranked_bin_residual"}
444
+ if prediction_mode not in allowed_modes:
445
+ raise ValueError(f"prediction_mode must be one of {sorted(allowed_modes)}, got {prediction_mode!r}")
446
+ self.fourier_freqs = fourier_freqs
447
+ self.z_bins = z_bins
448
+ self.y_min = y_min
449
+ self.y_max = y_max
450
+ self.prediction_mode = prediction_mode
451
+ self.bin_temperature = bin_temperature
452
+ self.residual_scale = residual_scale
453
+ self.candidate_topk = max(1, min(int(candidate_topk), z_bins))
454
+ if stem_stride not in {4, 8}:
455
+ raise ValueError(f"stem_stride must be 4 or 8, got {stem_stride}")
456
+ self.stem_stride = int(stem_stride)
457
+ self.rec_pixels_per_token = int(stem_stride)
458
+ self.stride_stages = int(round(math.log2(self.stem_stride)))
459
+ bin_width = (y_max - y_min) / z_bins
460
+ centers = torch.linspace(y_min + 0.5 * bin_width, y_max - 0.5 * bin_width, z_bins)
461
+ self.register_buffer("z_bin_centers", centers, persistent=False)
462
+
463
+ if self.stem_stride == 8:
464
+ self.stem = nn.Sequential(
465
+ ConvBlock(in_channels, conv_width, kernel_size=9, stride=2, dropout=dropout * 0.5),
466
+ ConvBlock(conv_width, conv_width, kernel_size=7, stride=2, dropout=dropout * 0.5),
467
+ ConvBlock(conv_width, d_model, kernel_size=7, stride=2, dropout=dropout * 0.5),
468
+ ConvBlock(d_model, d_model, kernel_size=5, stride=1, dropout=dropout * 0.5),
469
+ )
470
+ else:
471
+ self.stem = nn.Sequential(
472
+ ConvBlock(in_channels, conv_width, kernel_size=9, stride=2, dropout=dropout * 0.5),
473
+ ConvBlock(conv_width, d_model, kernel_size=7, stride=2, dropout=dropout * 0.5),
474
+ ConvBlock(d_model, d_model, kernel_size=5, stride=1, dropout=dropout * 0.5),
475
+ )
476
+ self.pos_proj = nn.Sequential(nn.Linear(fourier_freqs * 2, d_model), nn.LayerNorm(d_model))
477
+ self.cls = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
478
+ # The model never receives true z; this learned query is the always-masked z token.
479
+ self.z_query = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
480
+
481
+ if layerscale_init > 0:
482
+ enc_layer = LayerScaleEncoderLayer(d_model, heads, dropout, layerscale_init)
483
+ else:
484
+ enc_layer = nn.TransformerEncoderLayer(
485
+ d_model=d_model,
486
+ nhead=heads,
487
+ dim_feedforward=d_model * 4,
488
+ dropout=dropout,
489
+ batch_first=True,
490
+ norm_first=True,
491
+ activation="gelu",
492
+ )
493
+ self.encoder = nn.TransformerEncoder(enc_layer, num_layers=layers)
494
+ self.pool_gate = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, 1))
495
+ head_dim = d_model * 5
496
+ self.z_head = nn.Sequential(nn.LayerNorm(head_dim), nn.Linear(head_dim, d_model), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model, 2))
497
+ self.z_bin_head = nn.Sequential(nn.LayerNorm(head_dim), nn.Linear(head_dim, d_model), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model, z_bins))
498
+ self.z_candidate_head = nn.Sequential(
499
+ nn.LayerNorm(head_dim),
500
+ nn.Linear(head_dim, d_model),
501
+ nn.GELU(),
502
+ nn.Dropout(dropout),
503
+ nn.Linear(d_model, z_bins),
504
+ )
505
+ if rec_hidden_mult > 0:
506
+ rec_hidden = int(d_model * rec_hidden_mult)
507
+ self.rec_head = nn.Sequential(
508
+ nn.LayerNorm(d_model),
509
+ nn.Linear(d_model, rec_hidden),
510
+ nn.GELU(),
511
+ nn.Dropout(dropout),
512
+ nn.Linear(rec_hidden, self.rec_pixels_per_token),
513
+ )
514
+ else:
515
+ self.rec_head = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, self.rec_pixels_per_token))
516
+ rec_pad = int(rec_refine_kernel) // 2
517
+ self.rec_refine = nn.Sequential(
518
+ nn.Conv1d(1, rec_refine_width, kernel_size=rec_refine_kernel, padding=rec_pad),
519
+ nn.GELU(),
520
+ nn.Conv1d(rec_refine_width, 1, kernel_size=rec_refine_kernel, padding=rec_pad),
521
+ )
522
+
523
+ def forward(self, x: torch.Tensor, valid: torch.Tensor, loglam: torch.Tensor) -> dict[str, torch.Tensor]:
524
+ bsz = x.shape[0]
525
+ h = self.stem(x).transpose(1, 2)
526
+ tok_valid = valid.float().unsqueeze(1)
527
+ tok_loglam = loglam.unsqueeze(1)
528
+ for _ in range(self.stride_stages):
529
+ tok_valid = F.avg_pool1d(tok_valid, kernel_size=2, stride=2, ceil_mode=True)
530
+ tok_loglam = F.avg_pool1d(tok_loglam, kernel_size=2, stride=2, ceil_mode=True)
531
+ tok_valid = tok_valid.squeeze(1) > 0.20
532
+ tok_loglam = tok_loglam.squeeze(1)
533
+ if tok_valid.shape[1] != h.shape[1]:
534
+ tok_valid = tok_valid[:, : h.shape[1]]
535
+ tok_loglam = tok_loglam[:, : h.shape[1]]
536
+ h = h[:, : tok_valid.shape[1]]
537
+
538
+ h = h + self.pos_proj(fourier_loglam(tok_loglam, self.fourier_freqs))
539
+ cls = self.cls.expand(bsz, -1, -1)
540
+ z_query = self.z_query.expand(bsz, -1, -1)
541
+ src = torch.cat([cls, z_query, h], dim=1)
542
+ special_valid = torch.ones((bsz, 2), dtype=torch.bool, device=x.device)
543
+ src_valid = torch.cat([special_valid, tok_valid], dim=1)
544
+ padding = ~src_valid
545
+ memory = self.encoder(src, src_key_padding_mask=padding)
546
+
547
+ spec = memory[:, 2:]
548
+ spec_valid = src_valid[:, 2:]
549
+ spec_mask = spec_valid.unsqueeze(-1)
550
+ rec = self.rec_head(spec).reshape(bsz, -1)
551
+ rec = rec + self.rec_refine(rec.unsqueeze(1)).squeeze(1)
552
+ if rec.shape[1] > x.shape[-1]:
553
+ rec = rec[:, : x.shape[-1]]
554
+ elif rec.shape[1] < x.shape[-1]:
555
+ rec = F.pad(rec, (0, x.shape[-1] - rec.shape[1]))
556
+ denom = spec_valid.float().sum(dim=1).clamp_min(1.0).unsqueeze(-1)
557
+ mean_pool = (spec * spec_mask.float()).sum(dim=1) / denom
558
+ max_pool = spec.masked_fill(~spec_mask, -1e4).max(dim=1).values
559
+ gate_logits = self.pool_gate(spec).squeeze(-1).masked_fill(~spec_valid, -1e4)
560
+ gate = torch.softmax(gate_logits, dim=1)
561
+ attn_pool = torch.einsum("bn,bnd->bd", gate, spec)
562
+ feat = torch.cat([memory[:, 0], memory[:, 1], mean_pool, max_pool, attn_pool], dim=-1)
563
+ z_params = self.z_head(feat)
564
+ z_bin_logits = self.z_bin_head(feat)
565
+ candidate_residual = self.residual_scale * torch.tanh(self.z_candidate_head(feat))
566
+ centers = self.z_bin_centers.to(dtype=z_bin_logits.dtype, device=z_bin_logits.device)
567
+ candidate_y = (centers.unsqueeze(0) + candidate_residual).clamp(self.y_min, self.y_max)
568
+ topk_logits, topk_bins = torch.topk(z_bin_logits, k=self.candidate_topk, dim=-1)
569
+ candidate_topk_y = candidate_y.gather(1, topk_bins)
570
+ y_reg = z_params[:, 0]
571
+ bin_prob = torch.softmax(z_bin_logits / max(self.bin_temperature, 1e-4), dim=-1)
572
+ y_bin = (bin_prob * self.z_bin_centers.to(dtype=bin_prob.dtype, device=bin_prob.device)).sum(dim=-1)
573
+ y_ranked = (bin_prob * candidate_y.to(dtype=bin_prob.dtype)).sum(dim=-1)
574
+ y_legacy_bin_residual = y_bin + self.residual_scale * torch.tanh(y_reg)
575
+ if self.prediction_mode == "regression":
576
+ y_pred = y_reg
577
+ elif self.prediction_mode == "softbin":
578
+ y_pred = y_bin
579
+ elif self.prediction_mode == "hybrid":
580
+ y_pred = 0.35 * y_reg + 0.65 * y_bin
581
+ elif self.prediction_mode == "ranked_bin_residual":
582
+ y_pred = 0.5 * y_legacy_bin_residual + 0.5 * y_ranked
583
+ else:
584
+ y_pred = y_legacy_bin_residual
585
+ y_pred = y_pred.clamp(self.y_min, self.y_max)
586
+ return {
587
+ "rec": rec,
588
+ "y_mu": y_pred,
589
+ "y_pred": y_pred,
590
+ "y_reg": y_reg,
591
+ "y_bin": y_bin,
592
+ "y_ranked": y_ranked,
593
+ "y_top1_candidate": candidate_topk_y[:, 0],
594
+ "y_logvar": torch.clamp(z_params[:, 1], -8.0, 4.0),
595
+ "z_bin_logits": z_bin_logits,
596
+ "z_feat": feat,
597
+ "candidate_y": candidate_y,
598
+ "candidate_topk_y": candidate_topk_y,
599
+ "candidate_topk_bins": topk_bins,
600
+ "candidate_topk_logits": topk_logits,
601
+ }
602
+
603
+ def y_to_bin(self, y: torch.Tensor) -> torch.Tensor:
604
+ scaled = (y - self.y_min) / max(self.y_max - self.y_min, 1e-6)
605
+ return torch.clamp((scaled * self.z_bins).long(), 0, self.z_bins - 1)
606
+
607
+
608
+ def move_to_device(batch: dict[str, torch.Tensor], device: torch.device) -> dict[str, torch.Tensor]:
609
+ return {k: v.to(device, non_blocking=True) if torch.is_tensor(v) else v for k, v in batch.items()}
610
+
611
+
612
+ def limit_batch_examples(batch: dict[str, torch.Tensor], max_examples: int | None, seen_examples: int) -> dict[str, torch.Tensor] | None:
613
+ if max_examples is None or max_examples <= 0:
614
+ return batch
615
+ remaining = int(max_examples) - int(seen_examples)
616
+ if remaining <= 0:
617
+ return None
618
+ bsz = int(batch["y"].shape[0])
619
+ if remaining >= bsz:
620
+ return batch
621
+ return {k: v[:remaining] if torch.is_tensor(v) and v.shape[:1] == (bsz,) else v for k, v in batch.items()}
622
+
623
+
624
+ def load_checkpoint_into_model(model: nn.Module, state: dict[str, torch.Tensor], allow_mismatched: bool = False) -> None:
625
+ if not allow_mismatched:
626
+ try:
627
+ model.load_state_dict(state, strict=True)
628
+ except RuntimeError:
629
+ missing, unexpected = model.load_state_dict(state, strict=False)
630
+ print(f"RESUME_NONSTRICT missing={list(missing)} unexpected={list(unexpected)}")
631
+ return
632
+
633
+ target_state = model.state_dict()
634
+ compatible = {}
635
+ skipped = []
636
+ for key, value in state.items():
637
+ target = target_state.get(key)
638
+ if target is not None and tuple(target.shape) == tuple(value.shape):
639
+ compatible[key] = value
640
+ else:
641
+ skipped.append(key)
642
+ missing, unexpected = model.load_state_dict(compatible, strict=False)
643
+ print(
644
+ "RESUME_FILTERED "
645
+ f"loaded={len(compatible)} skipped={len(skipped)} "
646
+ f"missing={list(missing)} unexpected={list(unexpected)} skipped_keys={skipped[:20]}"
647
+ )
648
+
649
+
650
+ def redshift_total_loss(model: HybridSpecZ, out: dict[str, torch.Tensor], batch: dict[str, torch.Tensor], cfg: LossConfig) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
651
+ parts = redshift_losses(model, out, batch["y"], batch["zwarn"], cfg)
652
+ if "rec" in out and "target_flux" in batch and "loss_mask" in batch:
653
+ line_weight = batch.get("line_weight")
654
+ if line_weight is not None:
655
+ line_weight = line_weight.pow(cfg.line_weight_power)
656
+ rec = masked_huber(out["rec"], batch["target_flux"], batch["loss_mask"], weight=line_weight)
657
+ else:
658
+ rec = parts["z_huber"].sum() * 0.0
659
+ total = (
660
+ cfg.rec_weight * rec
661
+ + cfg.z_weight * parts["z_huber"]
662
+ + cfg.z_bin_weight * parts["z_bin"]
663
+ + cfg.z_candidate_weight * parts["z_candidate"]
664
+ + cfg.z_nll_weight * parts["z_nll"]
665
+ )
666
+ metrics = {"loss": total.detach(), "rec": rec.detach(), **{k: v.detach() for k, v in parts.items()}}
667
+ return total, metrics
668
+
669
+
670
+ def plot_spectra_batch(path: str | Path, batch: dict[str, torch.Tensor], y_pred: np.ndarray, max_items: int = 4) -> None:
671
+ path = Path(path)
672
+ path.parent.mkdir(parents=True, exist_ok=True)
673
+ x = batch["x"].detach().cpu().numpy()
674
+ loglam = batch["loglam"].detach().cpu().numpy()
675
+ valid = batch["valid"].detach().cpu().numpy()
676
+ z = batch["z"].detach().cpu().numpy()
677
+ bsz = min(max_items, x.shape[0])
678
+ fig, axes = plt.subplots(bsz, 1, figsize=(13, 3.0 * bsz), squeeze=False)
679
+ for i in range(bsz):
680
+ ax = axes[i, 0]
681
+ wave = np.exp(loglam[i])
682
+ good = valid[i].astype(bool)
683
+ ax.plot(wave[good], x[i, 0, good], color="black", linewidth=0.8, label="input flux")
684
+ ax.plot(wave[good], x[i, 6, good], color="#1f77b4", linewidth=0.6, alpha=0.55, label="line score")
685
+ masked = x[i, 7] > 0
686
+ if masked.any():
687
+ ax.scatter(wave[masked], np.zeros(masked.sum()), s=5, color="#d62728", alpha=0.55, label="redshift dropout")
688
+ ax.set_title(f"z true={z[i]:.5f} z pred={np.expm1(y_pred[i]):.5f}")
689
+ ax.set_ylabel("normalized")
690
+ ax.grid(alpha=0.2)
691
+ if i == 0:
692
+ ax.legend(loc="best", fontsize=8)
693
+ axes[-1, 0].set_xlabel("wavelength Angstrom")
694
+ fig.tight_layout()
695
+ fig.savefig(path, dpi=150)
696
+ plt.close(fig)
697
+
698
+
699
+ def add_redshift_slice_metrics(metrics: dict[str, float], prefix: str, y_true: np.ndarray, y_pred: np.ndarray) -> None:
700
+ z_true = np.expm1(y_true)
701
+ z_pred = np.expm1(y_pred)
702
+ slices = {
703
+ "z_lt_0p4": z_true < 0.4,
704
+ "z_0p4_1p0": (z_true >= 0.4) & (z_true < 1.0),
705
+ "z_1p0_2p0": (z_true >= 1.0) & (z_true < 2.0),
706
+ "z_gte_2p0": z_true >= 2.0,
707
+ }
708
+ for name, mask in slices.items():
709
+ count = int(np.count_nonzero(mask))
710
+ metrics[f"{prefix}/{name}_count"] = float(count)
711
+ if count >= 5:
712
+ err = z_pred[mask] - z_true[mask]
713
+ denom = 1.0 + z_true[mask]
714
+ metrics[f"{prefix}/{name}_mae_z"] = float(np.mean(np.abs(err)))
715
+ metrics[f"{prefix}/{name}_bias_z"] = float(np.mean(err))
716
+ metrics[f"{prefix}/{name}_cat_0p05"] = float(np.mean(np.abs(err / denom) > 0.05))
717
+
718
+
719
+ def add_candidate_metrics(
720
+ metrics: dict[str, float],
721
+ prefix: str,
722
+ y_true: np.ndarray,
723
+ candidate_y: np.ndarray,
724
+ candidate_bins: np.ndarray | None,
725
+ *,
726
+ z_bins: int,
727
+ y_min: float,
728
+ y_max: float,
729
+ ) -> None:
730
+ if candidate_y.size == 0:
731
+ return
732
+ z_true = np.expm1(y_true)
733
+ z_candidate = np.expm1(candidate_y)
734
+ abs_dz = np.abs(z_candidate - z_true[:, None])
735
+ norm_dz = abs_dz / (1.0 + z_true[:, None])
736
+ top_limits = [1, 3, 5]
737
+ for k in top_limits:
738
+ kk = min(k, candidate_y.shape[1])
739
+ best_abs = np.min(abs_dz[:, :kk], axis=1)
740
+ best_norm = np.min(norm_dz[:, :kk], axis=1)
741
+ metrics[f"{prefix}/candidate_top{kk}_best_mae_z"] = float(np.mean(best_abs))
742
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p003"] = float(np.mean(best_norm <= 0.003))
743
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p01"] = float(np.mean(best_norm <= 0.01))
744
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p05"] = float(np.mean(best_norm <= 0.05))
745
+ if candidate_bins is not None and candidate_bins.size:
746
+ scaled = (y_true - y_min) / max(y_max - y_min, 1e-6)
747
+ true_bins = np.clip((scaled * z_bins).astype(np.int64), 0, z_bins - 1)
748
+ for k in top_limits:
749
+ kk = min(k, candidate_bins.shape[1])
750
+ metrics[f"{prefix}/candidate_top{kk}_bin_hit"] = float(np.mean(np.any(candidate_bins[:, :kk] == true_bins[:, None], axis=1)))
751
+
752
+
753
+ @torch.no_grad()
754
+ def evaluate(
755
+ model: HybridSpecZ,
756
+ loader: DataLoader,
757
+ loss_cfg: LossConfig,
758
+ device: torch.device,
759
+ run_dir: Path,
760
+ step: int,
761
+ prefix: str = "val",
762
+ max_batches: int | None = 50,
763
+ max_examples: int | None = None,
764
+ ) -> dict[str, float]:
765
+ model.eval()
766
+ losses: dict[str, list[float]] = {}
767
+ y_true_all: list[np.ndarray] = []
768
+ y_pred_all: list[np.ndarray] = []
769
+ candidate_y_all: list[np.ndarray] = []
770
+ candidate_bins_all: list[np.ndarray] = []
771
+ y_true_clean: list[np.ndarray] = []
772
+ y_pred_clean: list[np.ndarray] = []
773
+ candidate_y_clean: list[np.ndarray] = []
774
+ candidate_bins_clean: list[np.ndarray] = []
775
+ zwarn_all: list[np.ndarray] = []
776
+ first_batch = None
777
+ first_pred = None
778
+ first_rec = None
779
+ seen_examples = 0
780
+ for bi, batch in enumerate(loader):
781
+ if max_batches is not None and max_batches > 0 and bi >= max_batches:
782
+ break
783
+ batch = limit_batch_examples(batch, max_examples, seen_examples)
784
+ if batch is None:
785
+ break
786
+ seen_examples += int(batch["y"].shape[0])
787
+ batch = move_to_device(batch, device)
788
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
789
+ out = model(batch["x"], batch["valid"], batch["loglam"])
790
+ _, parts = redshift_total_loss(model, out, batch, loss_cfg)
791
+ y_pred = out.get("y_pred", out["y_mu"])
792
+ for k, v in parts.items():
793
+ losses.setdefault(k, []).append(float(v.detach().cpu()))
794
+ if "rec" in out and "target_flux" in batch and "loss_mask" in batch:
795
+ rec_err = F.smooth_l1_loss(out["rec"].float(), batch["target_flux"].float(), reduction="none", beta=0.5)
796
+ loss_mask = batch["loss_mask"].bool()
797
+ line_region = batch.get("line_region")
798
+ if line_region is not None:
799
+ line_mask = loss_mask & line_region.bool()
800
+ cont_mask = loss_mask & (~line_region.bool())
801
+ for name, mask in (("rec_line", line_mask), ("rec_continuum", cont_mask)):
802
+ denom = mask.float().sum()
803
+ if float(denom.detach().cpu()) > 0:
804
+ losses.setdefault(name, []).append(float(((rec_err * mask.float()).sum() / denom.clamp_min(1.0)).detach().cpu()))
805
+ context_mask = batch["valid"].bool() & (~loss_mask)
806
+ denom = context_mask.float().sum(dim=1).clamp_min(1.0)
807
+ baseline = (batch["target_flux"].float() * context_mask.float()).sum(dim=1, keepdim=True) / denom.unsqueeze(1)
808
+ baseline_err = F.smooth_l1_loss(baseline.expand_as(batch["target_flux"]).float(), batch["target_flux"].float(), reduction="none", beta=0.5)
809
+ mask_denom = loss_mask.float().sum().clamp_min(1.0)
810
+ losses.setdefault("rec_mean_baseline", []).append(float(((baseline_err * loss_mask.float()).sum() / mask_denom).detach().cpu()))
811
+ finite = torch.isfinite(batch["y"]).detach().cpu().numpy()
812
+ clean = ((~batch["zwarn"].bool()) & torch.isfinite(batch["y"])).detach().cpu().numpy()
813
+ zw = batch["zwarn"].detach().cpu().numpy().astype(bool)
814
+ if finite.any():
815
+ y_true_all.append(batch["y"].detach().cpu().numpy()[finite])
816
+ y_pred_all.append(y_pred.float().detach().cpu().numpy()[finite])
817
+ zwarn_all.append(zw[finite])
818
+ if "candidate_topk_y" in out:
819
+ candidate_y_all.append(out["candidate_topk_y"].float().detach().cpu().numpy()[finite])
820
+ if "candidate_topk_bins" in out:
821
+ candidate_bins_all.append(out["candidate_topk_bins"].detach().cpu().numpy()[finite])
822
+ if clean.any():
823
+ y_true_clean.append(batch["y"].detach().cpu().numpy()[clean])
824
+ y_pred_clean.append(y_pred.float().detach().cpu().numpy()[clean])
825
+ if "candidate_topk_y" in out:
826
+ candidate_y_clean.append(out["candidate_topk_y"].float().detach().cpu().numpy()[clean])
827
+ if "candidate_topk_bins" in out:
828
+ candidate_bins_clean.append(out["candidate_topk_bins"].detach().cpu().numpy()[clean])
829
+ if first_batch is None:
830
+ first_batch = {k: v.detach().cpu() if torch.is_tensor(v) else v for k, v in batch.items()}
831
+ first_pred = y_pred.float().detach().cpu().numpy()
832
+ if "rec" in out:
833
+ first_rec = out["rec"].float().detach().cpu().numpy()
834
+
835
+ metrics = {f"{prefix}/{k}": float(np.mean(v)) for k, v in losses.items()}
836
+ if y_true_all:
837
+ y_true = np.concatenate(y_true_all)
838
+ y_pred = np.concatenate(y_pred_all)
839
+ for k, v in redshift_metrics(y_true, y_pred).items():
840
+ metrics[f"{prefix}/{k}"] = v
841
+ add_redshift_slice_metrics(metrics, prefix, y_true, y_pred)
842
+ if candidate_y_all:
843
+ candidate_y_np = np.concatenate(candidate_y_all)
844
+ candidate_bins_np = np.concatenate(candidate_bins_all) if candidate_bins_all else None
845
+ add_candidate_metrics(
846
+ metrics,
847
+ prefix,
848
+ y_true,
849
+ candidate_y_np,
850
+ candidate_bins_np,
851
+ z_bins=model.z_bins,
852
+ y_min=model.y_min,
853
+ y_max=model.y_max,
854
+ )
855
+ metrics[f"{prefix}/z_count"] = float(len(y_true))
856
+ metrics[f"{prefix}/zwarn_fraction"] = float(np.mean(np.concatenate(zwarn_all))) if zwarn_all else 0.0
857
+ plot_redshift_scatter(run_dir / "plots" / f"{prefix}_redshift_step_{step:06d}.png", y_true, y_pred)
858
+ if y_true_clean:
859
+ clean_true = np.concatenate(y_true_clean)
860
+ clean_pred = np.concatenate(y_pred_clean)
861
+ if len(clean_true) >= 5:
862
+ for k, v in redshift_metrics(clean_true, clean_pred).items():
863
+ metrics[f"{prefix}_clean/{k}"] = v
864
+ if candidate_y_clean:
865
+ candidate_y_clean_np = np.concatenate(candidate_y_clean)
866
+ candidate_bins_clean_np = np.concatenate(candidate_bins_clean) if candidate_bins_clean else None
867
+ add_candidate_metrics(
868
+ metrics,
869
+ f"{prefix}_clean",
870
+ clean_true,
871
+ candidate_y_clean_np,
872
+ candidate_bins_clean_np,
873
+ z_bins=model.z_bins,
874
+ y_min=model.y_min,
875
+ y_max=model.y_max,
876
+ )
877
+ metrics[f"{prefix}_clean/z_count"] = float(len(clean_true))
878
+ if first_batch is not None and first_pred is not None:
879
+ if first_rec is not None and "target_flux" in first_batch and "loss_mask" in first_batch:
880
+ plot_reconstruction_batch(
881
+ run_dir / "plots" / f"{prefix}_reconstruction_step_{step:06d}.png",
882
+ first_batch["loglam"].numpy(),
883
+ first_batch["target_flux"].numpy(),
884
+ first_rec,
885
+ first_batch["loss_mask"].numpy(),
886
+ first_batch["valid"].numpy(),
887
+ first_batch["z"].numpy(),
888
+ np.expm1(first_pred),
889
+ )
890
+ plot_spectra_batch(run_dir / "plots" / f"{prefix}_spectra_step_{step:06d}.png", first_batch, first_pred)
891
+ model.train()
892
+ return metrics
893
+
894
+
895
+ def make_loader(
896
+ samples: list[dict[str, Any]],
897
+ indices: np.ndarray,
898
+ cfg: RawCollatorConfig,
899
+ args: argparse.Namespace,
900
+ train: bool,
901
+ sampler: WeightedRandomSampler | None = None,
902
+ ) -> DataLoader:
903
+ return DataLoader(
904
+ SpectraListDataset(samples, indices),
905
+ batch_size=args.batch_size,
906
+ shuffle=train and sampler is None,
907
+ sampler=sampler,
908
+ num_workers=args.num_workers,
909
+ pin_memory=True,
910
+ collate_fn=RawSpectraCollator(cfg, train=train, seed=args.seed + (0 if train else 1000)),
911
+ )
912
+
913
+
914
+ def checkpoint_score(mode: str, val_metrics: dict[str, float], ood_metrics: dict[str, float] | None, z_alpha: float = 0.6) -> float:
915
+ def score_prefix(metrics: dict[str, float], prefix: str) -> float:
916
+ z_score = (
917
+ metrics.get(f"{prefix}/nmad", math.inf)
918
+ + metrics.get(f"{prefix}/cat_0p01", 1.0)
919
+ + metrics.get(f"{prefix}/mae_log1p", 1.0)
920
+ )
921
+ rec_score = metrics.get(f"{prefix}/rec")
922
+ if rec_score is None or not math.isfinite(float(rec_score)):
923
+ return z_score
924
+ alpha = min(max(float(z_alpha), 0.0), 1.0)
925
+ return alpha * z_score + (1.0 - alpha) * float(rec_score)
926
+
927
+ val_score = score_prefix(val_metrics, "val")
928
+ if mode == "rec":
929
+ return float(val_metrics.get("val/rec", math.inf))
930
+ if mode == "val" or ood_metrics is None:
931
+ return val_score
932
+ ood_score = score_prefix(ood_metrics, "ood")
933
+ if mode == "ood":
934
+ return ood_score
935
+ return 0.5 * val_score + 0.5 * ood_score
936
+
937
+
938
+ def scheduled_lr(base_lr: float, min_lr: float, step: int, total_steps: int, warmup_steps: int) -> float:
939
+ if warmup_steps > 0 and step <= warmup_steps:
940
+ return base_lr * float(step) / float(max(1, warmup_steps))
941
+ if min_lr < 0 or total_steps <= warmup_steps:
942
+ return base_lr
943
+ progress = (step - warmup_steps) / float(max(1, total_steps - warmup_steps))
944
+ progress = min(max(progress, 0.0), 1.0)
945
+ return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * progress))
946
+
947
+
948
+ def main() -> None:
949
+ parser = argparse.ArgumentParser()
950
+ parser.add_argument("--dataset-name", default="MultimodalUniverse/desi")
951
+ parser.add_argument("--max-samples", type=int, default=4096)
952
+ parser.add_argument("--cache-dir", default="/workspace/native_specz_mae/cache")
953
+ parser.add_argument("--hf-cache-dir", default=os.environ.get("HF_DATASETS_CACHE", "/workspace/hf_cache/datasets"))
954
+ parser.add_argument("--run-dir", default="/workspace/runs/hybrid_specz")
955
+ parser.add_argument("--resume-checkpoint", default="")
956
+ parser.add_argument("--allow-mismatched-checkpoint", action="store_true")
957
+ parser.add_argument("--refresh-data", action="store_true")
958
+ parser.add_argument("--epochs", type=int, default=8)
959
+ parser.add_argument("--batch-size", type=int, default=64)
960
+ parser.add_argument("--num-workers", type=int, default=2)
961
+ parser.add_argument("--target-length", type=int, default=4096)
962
+ parser.add_argument("--d-model", type=int, default=256)
963
+ parser.add_argument("--conv-width", type=int, default=128)
964
+ parser.add_argument("--layers", type=int, default=5)
965
+ parser.add_argument("--heads", type=int, default=8)
966
+ parser.add_argument("--dropout", type=float, default=0.1)
967
+ parser.add_argument("--z-bins", type=int, default=64)
968
+ parser.add_argument("--stem-stride", type=int, choices=[4, 8], default=8)
969
+ parser.add_argument("--rec-hidden-mult", type=int, default=0)
970
+ parser.add_argument("--rec-refine-width", type=int, default=16)
971
+ parser.add_argument("--rec-refine-kernel", type=int, default=5)
972
+ parser.add_argument("--layerscale-init", type=float, default=0.0)
973
+ parser.add_argument(
974
+ "--prediction-mode",
975
+ choices=["regression", "softbin", "hybrid", "bin_residual", "ranked_bin_residual"],
976
+ default="regression",
977
+ )
978
+ parser.add_argument("--bin-temperature", type=float, default=1.0)
979
+ parser.add_argument("--residual-scale", type=float, default=0.06)
980
+ parser.add_argument("--candidate-topk", type=int, default=5)
981
+ parser.add_argument("--lr", type=float, default=2e-4)
982
+ parser.add_argument("--min-lr", type=float, default=-1.0)
983
+ parser.add_argument("--warmup-steps", type=int, default=0)
984
+ parser.add_argument("--weight-decay", type=float, default=0.03)
985
+ parser.add_argument("--grad-clip", type=float, default=1.0)
986
+ parser.add_argument("--grad-accum-steps", type=int, default=1)
987
+ parser.add_argument("--eval-every", type=int, default=100)
988
+ parser.add_argument("--eval-max-val", type=int, default=800)
989
+ parser.add_argument("--eval-max-ood", type=int, default=480)
990
+ parser.add_argument("--max-steps", type=int, default=0)
991
+ parser.add_argument("--checkpoint-score", choices=["val", "ood", "combined", "rec"], default="combined")
992
+ parser.add_argument("--score-z-alpha", type=float, default=0.6)
993
+ parser.add_argument("--objective", choices=["joint", "rec_only", "z_only"], default="joint")
994
+ parser.add_argument("--balance-redshift", action="store_true")
995
+ parser.add_argument("--train-clean-only", action="store_true")
996
+ parser.add_argument("--clean-sample-boost", type=float, default=1.0)
997
+ parser.add_argument("--augment-ood", action="store_true")
998
+ parser.add_argument("--eval-ood", action="store_true")
999
+ parser.add_argument("--random-mask-ratio", type=float, default=0.0)
1000
+ parser.add_argument("--eval-mask-ratio", type=float, default=0.25)
1001
+ parser.add_argument("--mask-mode", choices=["pixel", "span", "line_span", "mixed_span"], default="pixel")
1002
+ parser.add_argument("--mask-span-min", type=int, default=16)
1003
+ parser.add_argument("--mask-span-max", type=int, default=64)
1004
+ parser.add_argument("--line-region-percentile", type=float, default=90.0)
1005
+ parser.add_argument("--crop-prob", type=float, default=0.0)
1006
+ parser.add_argument("--bad-window-prob", type=float, default=0.0)
1007
+ parser.add_argument("--throughput-prob", type=float, default=0.0)
1008
+ parser.add_argument("--noise-prob", type=float, default=0.0)
1009
+ parser.add_argument("--resolution-prob", type=float, default=0.0)
1010
+ parser.add_argument("--downsample-prob", type=float, default=0.0)
1011
+ parser.add_argument("--line-dropout-prob", type=float, default=0.0)
1012
+ parser.add_argument("--span-dropout-prob", type=float, default=0.0)
1013
+ parser.add_argument("--redshift-shift", type=float, default=0.0)
1014
+ parser.add_argument("--rec-weight", type=float, default=0.0)
1015
+ parser.add_argument("--z-weight", type=float, default=1.0)
1016
+ parser.add_argument("--z-bin-weight", type=float, default=0.25)
1017
+ parser.add_argument("--z-candidate-weight", type=float, default=0.0)
1018
+ parser.add_argument("--z-nll-weight", type=float, default=0.05)
1019
+ parser.add_argument("--zwarn-weight", type=float, default=0.3)
1020
+ parser.add_argument("--high-z-boost", type=float, default=1.0)
1021
+ parser.add_argument("--high-z-threshold", type=float, default=1.0)
1022
+ parser.add_argument("--clean-z-only", action="store_true")
1023
+ parser.add_argument("--seed", type=int, default=17)
1024
+ args = parser.parse_args()
1025
+
1026
+ torch.manual_seed(args.seed)
1027
+ np.random.seed(args.seed)
1028
+ run_dir = Path(args.run_dir) / time.strftime("%Y%m%d_%H%M%S")
1029
+ run_dir.mkdir(parents=True, exist_ok=True)
1030
+ (run_dir / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
1031
+
1032
+ samples = collect_mmu_desi(
1033
+ cache_file=Path(args.cache_dir) / f"desi_{args.max_samples}.pt",
1034
+ max_samples=args.max_samples,
1035
+ dataset_name=args.dataset_name,
1036
+ hf_cache_dir=args.hf_cache_dir,
1037
+ refresh=args.refresh_data,
1038
+ )
1039
+ stats = compute_sample_stats(samples)
1040
+ (run_dir / "data_stats.json").write_text(json.dumps(stats.__dict__, indent=2), encoding="utf-8")
1041
+ print("DATA_STATS", json.dumps(stats.__dict__, sort_keys=True))
1042
+
1043
+ train_idx, val_idx = split_indices(len(samples), val_fraction=0.15, seed=args.seed)
1044
+ if args.train_clean_only:
1045
+ clean_train = np.asarray([not bool(samples[int(i)]["zwarn"]) for i in train_idx], dtype=np.bool_)
1046
+ train_idx = train_idx[clean_train]
1047
+ if len(train_idx) == 0:
1048
+ raise RuntimeError("No clean ZWARN==0 samples are available for --train-clean-only.")
1049
+ print(f"TRAIN_CLEAN_ONLY n_train={len(train_idx)}")
1050
+
1051
+ sampler = None
1052
+ if args.balance_redshift or args.clean_sample_boost != 1.0:
1053
+ weights = np.ones(len(train_idx), dtype=np.float32)
1054
+ y_train = np.asarray([np.log1p(float(samples[int(i)]["z"])) for i in train_idx], dtype=np.float32)
1055
+ if args.balance_redshift:
1056
+ bins = np.linspace(float(y_train.min()), float(y_train.max()) + 1e-6, 28)
1057
+ bin_id = np.clip(np.digitize(y_train, bins) - 1, 0, len(bins) - 2)
1058
+ counts = np.bincount(bin_id, minlength=len(bins) - 1).astype(np.float32)
1059
+ weights *= 1.0 / np.maximum(counts[bin_id], 1.0)
1060
+ if args.clean_sample_boost != 1.0:
1061
+ clean = np.asarray([not bool(samples[int(i)]["zwarn"]) for i in train_idx], dtype=np.bool_)
1062
+ weights *= np.where(clean, float(args.clean_sample_boost), 1.0).astype(np.float32)
1063
+ weights = weights / weights.mean()
1064
+ sampler = WeightedRandomSampler(torch.as_tensor(weights, dtype=torch.double), num_samples=len(weights), replacement=True)
1065
+
1066
+ train_cfg = RawCollatorConfig(
1067
+ target_length=args.target_length,
1068
+ random_mask_ratio=args.random_mask_ratio,
1069
+ eval_mask_ratio=args.eval_mask_ratio,
1070
+ mask_mode=args.mask_mode,
1071
+ mask_span_min=args.mask_span_min,
1072
+ mask_span_max=args.mask_span_max,
1073
+ line_region_percentile=args.line_region_percentile,
1074
+ augment_ood=args.augment_ood,
1075
+ crop_prob=args.crop_prob,
1076
+ bad_window_prob=args.bad_window_prob,
1077
+ throughput_prob=args.throughput_prob,
1078
+ noise_prob=args.noise_prob,
1079
+ resolution_prob=args.resolution_prob,
1080
+ downsample_prob=args.downsample_prob,
1081
+ line_dropout_prob=args.line_dropout_prob,
1082
+ span_dropout_prob=args.span_dropout_prob,
1083
+ redshift_shift=args.redshift_shift,
1084
+ )
1085
+ val_cfg = RawCollatorConfig(
1086
+ target_length=args.target_length,
1087
+ eval_mask_ratio=args.eval_mask_ratio,
1088
+ mask_mode=args.mask_mode,
1089
+ mask_span_min=args.mask_span_min,
1090
+ mask_span_max=args.mask_span_max,
1091
+ line_region_percentile=args.line_region_percentile,
1092
+ )
1093
+ ood_cfg = RawCollatorConfig(
1094
+ target_length=args.target_length,
1095
+ eval_mask_ratio=args.eval_mask_ratio,
1096
+ mask_mode=args.mask_mode,
1097
+ mask_span_min=args.mask_span_min,
1098
+ mask_span_max=args.mask_span_max,
1099
+ line_region_percentile=args.line_region_percentile,
1100
+ augment_ood=True,
1101
+ crop_prob=0.65,
1102
+ bad_window_prob=0.45,
1103
+ throughput_prob=0.65,
1104
+ noise_prob=0.35,
1105
+ resolution_prob=0.45,
1106
+ downsample_prob=0.35,
1107
+ )
1108
+ train_loader = make_loader(samples, train_idx, train_cfg, args, train=True, sampler=sampler)
1109
+ val_loader = make_loader(samples, val_idx, val_cfg, args, train=False)
1110
+ ood_loader = make_loader(samples, val_idx, ood_cfg, args, train=False) if args.eval_ood else None
1111
+
1112
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
1113
+ model = HybridSpecZ(
1114
+ d_model=args.d_model,
1115
+ conv_width=args.conv_width,
1116
+ layers=args.layers,
1117
+ heads=args.heads,
1118
+ dropout=args.dropout,
1119
+ z_bins=args.z_bins,
1120
+ stem_stride=args.stem_stride,
1121
+ rec_hidden_mult=args.rec_hidden_mult,
1122
+ rec_refine_width=args.rec_refine_width,
1123
+ rec_refine_kernel=args.rec_refine_kernel,
1124
+ layerscale_init=args.layerscale_init,
1125
+ prediction_mode=args.prediction_mode,
1126
+ bin_temperature=args.bin_temperature,
1127
+ residual_scale=args.residual_scale,
1128
+ candidate_topk=args.candidate_topk,
1129
+ ).to(device)
1130
+ if args.resume_checkpoint:
1131
+ ckpt = torch.load(args.resume_checkpoint, map_location=device, weights_only=False)
1132
+ state = ckpt["model"] if isinstance(ckpt, dict) and "model" in ckpt else ckpt
1133
+ load_checkpoint_into_model(model, state, allow_mismatched=args.allow_mismatched_checkpoint)
1134
+ print(f"RESUME_CHECKPOINT {args.resume_checkpoint}")
1135
+ n_params = sum(p.numel() for p in model.parameters())
1136
+ print(f"MODEL_PARAMS {n_params}")
1137
+
1138
+ optimizer = AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95))
1139
+ rec_weight = args.rec_weight
1140
+ z_weight = args.z_weight
1141
+ z_bin_weight = args.z_bin_weight
1142
+ z_candidate_weight = args.z_candidate_weight
1143
+ z_nll_weight = args.z_nll_weight
1144
+ if args.objective == "rec_only":
1145
+ rec_weight = rec_weight if rec_weight > 0 else 1.0
1146
+ z_weight = 0.0
1147
+ z_bin_weight = 0.0
1148
+ z_candidate_weight = 0.0
1149
+ z_nll_weight = 0.0
1150
+ elif args.objective == "z_only":
1151
+ rec_weight = 0.0
1152
+
1153
+ loss_cfg = LossConfig(
1154
+ rec_weight=rec_weight,
1155
+ z_weight=z_weight,
1156
+ z_bin_weight=z_bin_weight,
1157
+ z_candidate_weight=z_candidate_weight,
1158
+ z_nll_weight=z_nll_weight,
1159
+ zwarn_weight=args.zwarn_weight,
1160
+ clean_z_only=args.clean_z_only,
1161
+ high_z_boost=args.high_z_boost,
1162
+ high_z_threshold=math.log1p(args.high_z_threshold),
1163
+ )
1164
+ best_score = math.inf
1165
+ global_step = 0
1166
+ micro_step = 0
1167
+ grad_accum_steps = max(1, int(args.grad_accum_steps))
1168
+ total_train_steps = args.max_steps if args.max_steps else int(math.ceil(len(train_loader) / grad_accum_steps) * args.epochs)
1169
+ model.train()
1170
+ optimizer.zero_grad(set_to_none=True)
1171
+ for epoch in range(args.epochs):
1172
+ pbar = tqdm(train_loader, desc=f"hybrid epoch {epoch}")
1173
+ for batch in pbar:
1174
+ micro_step += 1
1175
+ batch = move_to_device(batch, device)
1176
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
1177
+ out = model(batch["x"], batch["valid"], batch["loglam"])
1178
+ loss, parts = redshift_total_loss(model, out, batch, loss_cfg)
1179
+ (loss / grad_accum_steps).backward()
1180
+ if micro_step % grad_accum_steps != 0:
1181
+ pbar.set_postfix(
1182
+ loss=float(parts["loss"].detach().cpu()),
1183
+ rec=float(parts["rec"].detach().cpu()),
1184
+ huber=float(parts["z_huber"].detach().cpu()),
1185
+ accum=f"{micro_step % grad_accum_steps}/{grad_accum_steps}",
1186
+ )
1187
+ continue
1188
+ next_step = global_step + 1
1189
+ lr_now = scheduled_lr(args.lr, args.min_lr, next_step, total_train_steps, int(args.warmup_steps))
1190
+ for group in optimizer.param_groups:
1191
+ group["lr"] = lr_now
1192
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
1193
+ optimizer.step()
1194
+ optimizer.zero_grad(set_to_none=True)
1195
+ global_step = next_step
1196
+ pbar.set_postfix(
1197
+ loss=float(parts["loss"].detach().cpu()),
1198
+ rec=float(parts["rec"].detach().cpu()),
1199
+ huber=float(parts["z_huber"].detach().cpu()),
1200
+ lr=lr_now,
1201
+ grad=float(grad_norm.detach().cpu()) if torch.is_tensor(grad_norm) else float(grad_norm),
1202
+ )
1203
+ if global_step == 1 or global_step % args.eval_every == 0:
1204
+ val_metrics = evaluate(
1205
+ model,
1206
+ val_loader,
1207
+ loss_cfg,
1208
+ device,
1209
+ run_dir,
1210
+ global_step,
1211
+ prefix="val",
1212
+ max_batches=None,
1213
+ max_examples=args.eval_max_val,
1214
+ )
1215
+ print("VAL", global_step, json.dumps(val_metrics, sort_keys=True))
1216
+ ood_metrics = None
1217
+ if ood_loader is not None:
1218
+ ood_metrics = evaluate(
1219
+ model,
1220
+ ood_loader,
1221
+ loss_cfg,
1222
+ device,
1223
+ run_dir,
1224
+ global_step,
1225
+ prefix="ood",
1226
+ max_batches=None,
1227
+ max_examples=args.eval_max_ood,
1228
+ )
1229
+ print("OOD", global_step, json.dumps(ood_metrics, sort_keys=True))
1230
+ score = checkpoint_score(args.checkpoint_score, val_metrics, ood_metrics, z_alpha=args.score_z_alpha)
1231
+ if score < best_score:
1232
+ best_score = score
1233
+ best_metrics = {"step": global_step, "score": best_score, **val_metrics}
1234
+ if ood_metrics is not None:
1235
+ best_metrics.update(ood_metrics)
1236
+ torch.save(
1237
+ {"model": model.state_dict(), "args": vars(args), "step": global_step, "score": best_score, "metrics": best_metrics},
1238
+ run_dir / "best.pt",
1239
+ )
1240
+ (run_dir / "best_metrics.json").write_text(json.dumps(best_metrics, indent=2), encoding="utf-8")
1241
+ if args.max_steps and global_step >= args.max_steps:
1242
+ break
1243
+ if args.max_steps and global_step >= args.max_steps:
1244
+ break
1245
+
1246
+ final_metrics = evaluate(
1247
+ model,
1248
+ val_loader,
1249
+ loss_cfg,
1250
+ device,
1251
+ run_dir,
1252
+ global_step,
1253
+ prefix="val",
1254
+ max_batches=None,
1255
+ max_examples=args.eval_max_val,
1256
+ )
1257
+ if ood_loader is not None:
1258
+ final_metrics.update(
1259
+ evaluate(
1260
+ model,
1261
+ ood_loader,
1262
+ loss_cfg,
1263
+ device,
1264
+ run_dir,
1265
+ global_step,
1266
+ prefix="ood",
1267
+ max_batches=None,
1268
+ max_examples=args.eval_max_ood,
1269
+ )
1270
+ )
1271
+ torch.save({"model": model.state_dict(), "args": vars(args), "step": global_step, "metrics": final_metrics}, run_dir / "last.pt")
1272
+ (run_dir / "final_metrics.json").write_text(json.dumps(final_metrics, indent=2), encoding="utf-8")
1273
+ print("FINAL", json.dumps(final_metrics, sort_keys=True))
1274
+ print("RUN_DIR", run_dir)
1275
+
1276
+
1277
+ if __name__ == "__main__":
1278
+ main()