ManmohanSharma commited on
Commit
9febe80
·
verified ·
1 Parent(s): 742c5f6

Upload code/hybrid_redshift.py

Browse files
Files changed (1) hide show
  1. code/hybrid_redshift.py +1729 -0
code/hybrid_redshift.py ADDED
@@ -0,0 +1,1729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ grid_jitter_prob: float = 0.0
52
+ grid_shift_frac: float = 0.0
53
+ grid_scale_frac: float = 0.0
54
+ grid_jitter_warmup_steps: int = 0
55
+ redshift_shift: float = 0.0
56
+
57
+
58
+ class RawSpectraCollator:
59
+ def __init__(self, cfg: RawCollatorConfig, train: bool = True, seed: int = 17):
60
+ self.cfg = cfg
61
+ self.train = train
62
+ self.seed = seed
63
+ self.rng = np.random.default_rng(seed)
64
+ self.batch_count = 0
65
+ self.jitter_scale = 1.0
66
+
67
+ def __call__(self, samples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
68
+ if self.train:
69
+ self.batch_count += 1
70
+ warmup = max(0, int(self.cfg.grid_jitter_warmup_steps))
71
+ self.jitter_scale = min(1.0, self.batch_count / float(warmup)) if warmup > 0 else 1.0
72
+ items = [self._prepare_sample(s) for s in samples]
73
+ x = np.stack([item["x"] for item in items], axis=0).astype(np.float32)
74
+ valid = np.stack([item["valid"] for item in items], axis=0).astype(np.bool_)
75
+ loglam = np.stack([item["loglam"] for item in items], axis=0).astype(np.float32)
76
+ target_flux = np.stack([item["target_flux"] for item in items], axis=0).astype(np.float32)
77
+ loss_mask = np.stack([item["loss_mask"] for item in items], axis=0).astype(np.bool_)
78
+ line_weight = np.stack([item["line_weight"] for item in items], axis=0).astype(np.float32)
79
+ line_region = np.stack([item["line_region"] for item in items], axis=0).astype(np.bool_)
80
+ z = np.asarray([item["z"] for item in items], dtype=np.float32)
81
+ y = np.asarray([item["y"] for item in items], dtype=np.float32)
82
+ zwarn = np.asarray([item["zwarn"] for item in items], dtype=np.bool_)
83
+ return {
84
+ "x": torch.from_numpy(x),
85
+ "valid": torch.from_numpy(valid),
86
+ "loglam": torch.from_numpy(loglam),
87
+ "target_flux": torch.from_numpy(target_flux),
88
+ "loss_mask": torch.from_numpy(loss_mask),
89
+ "line_weight": torch.from_numpy(line_weight),
90
+ "line_region": torch.from_numpy(line_region),
91
+ "z": torch.from_numpy(z),
92
+ "y": torch.from_numpy(y),
93
+ "zwarn": torch.from_numpy(zwarn),
94
+ }
95
+
96
+ def _prepare_sample(self, sample: dict[str, Any]) -> dict[str, Any]:
97
+ rng = self.rng if self.train else self._eval_rng(sample)
98
+ flux = np.asarray(sample["flux"], dtype=np.float32).copy()
99
+ ivar = np.asarray(sample["ivar"], dtype=np.float32).copy()
100
+ lam = np.asarray(sample["lambda"], dtype=np.float32)
101
+ lsf = np.asarray(sample["lsf_sigma"], dtype=np.float32)
102
+ bad = np.asarray(sample["bad_mask"], dtype=np.bool_).copy()
103
+
104
+ if self.cfg.augment_ood:
105
+ bad = self._augment_bad_windows(bad, rng)
106
+ flux = self._augment_flux_calibration(flux, lam, rng)
107
+ flux = self._augment_resolution(flux, rng)
108
+ flux, ivar = self._augment_downsample_resample(flux, ivar, lam, rng)
109
+ flux = self._augment_noise(flux, ivar, rng)
110
+
111
+ valid = np.isfinite(flux) & np.isfinite(ivar) & np.isfinite(lam) & (ivar > 0) & (~bad)
112
+ loglam = np.log(np.clip(lam.astype(np.float64), 1.0, None)).astype(np.float32)
113
+ if valid.sum() < 16:
114
+ valid = valid_pixel_mask(sample)
115
+
116
+ grid_lo = float(np.nanmin(loglam))
117
+ grid_hi = float(np.nanmax(loglam))
118
+ if (
119
+ self.train
120
+ and self.cfg.grid_jitter_prob > 0
121
+ and rng.random() < self.cfg.grid_jitter_prob * self.jitter_scale
122
+ and math.isfinite(grid_lo)
123
+ and math.isfinite(grid_hi)
124
+ and grid_hi > grid_lo
125
+ ):
126
+ span = grid_hi - grid_lo
127
+ shift = float(rng.normal(0.0, max(0.0, self.cfg.grid_shift_frac) * self.jitter_scale)) * span
128
+ scale_max = max(0.0, self.cfg.grid_scale_frac) * self.jitter_scale
129
+ scale_delta = float(rng.uniform(-scale_max, scale_max))
130
+ scaled_span = span * max(0.50, 1.0 + scale_delta)
131
+ center = 0.5 * (grid_lo + grid_hi) + shift
132
+ grid_lo = center - 0.5 * scaled_span
133
+ grid_hi = center + 0.5 * scaled_span
134
+ grid = np.linspace(grid_lo, grid_hi, self.cfg.target_length, dtype=np.float32)
135
+ flux_grid = self._interp_valid(loglam, flux, valid, grid, fill=0.0)
136
+ ivar_grid = self._interp_valid(loglam, ivar, valid, grid, fill=0.0)
137
+ lsf_grid = self._interp_valid(loglam, lsf, valid, grid, fill=0.0)
138
+ valid_grid = np.interp(grid, loglam, valid.astype(np.float32), left=0.0, right=0.0) > 0.5
139
+
140
+ center = float(np.nanmedian(flux_grid[valid_grid])) if valid_grid.any() else 0.0
141
+ dev = np.abs(flux_grid[valid_grid] - center) if valid_grid.any() else np.asarray([1.0], dtype=np.float32)
142
+ scale = float(np.nanmedian(dev) * 1.4826)
143
+ if not math.isfinite(scale) or scale < self.cfg.min_scale:
144
+ scale = max(float(np.nanmedian(np.abs(flux_grid[valid_grid]))) if valid_grid.any() else 1.0, self.cfg.min_scale)
145
+
146
+ norm_flux = np.arcsinh((flux_grid - center) / scale).astype(np.float32)
147
+ norm_ivar = np.log1p(np.maximum(ivar_grid * scale * scale, 0.0)).astype(np.float32)
148
+ norm_ivar = np.clip(norm_ivar / 8.0, 0.0, 4.0)
149
+ lsf_norm = np.nan_to_num(lsf_grid / 3.0, nan=0.0, posinf=0.0, neginf=0.0).astype(np.float32)
150
+ loglam_norm = ((grid - math.log(6000.0)) / 0.45).astype(np.float32)
151
+
152
+ grad = np.gradient(norm_flux, grid).astype(np.float32)
153
+ good_grad = np.abs(grad[valid_grid])
154
+ grad_scale = float(np.percentile(good_grad, 95)) if len(good_grad) else 1.0
155
+ if not math.isfinite(grad_scale) or grad_scale <= 0:
156
+ grad_scale = 1.0
157
+ grad = np.clip(grad / grad_scale, -5.0, 5.0).astype(np.float32)
158
+ abs_grad = np.abs(grad).astype(np.float32)
159
+
160
+ target_flux = norm_flux.copy()
161
+ line_weight = self._line_weights(abs_grad, valid_grid)
162
+ line_region = self._line_region(abs_grad, valid_grid)
163
+ corrupt = self._sample_input_dropout(abs_grad, valid_grid, rng)
164
+ if corrupt.any():
165
+ norm_flux = norm_flux.copy()
166
+ grad = grad.copy()
167
+ abs_grad = abs_grad.copy()
168
+ norm_flux[corrupt] = 0.0
169
+ grad[corrupt] = 0.0
170
+ abs_grad[corrupt] = 0.0
171
+
172
+ y = math.log1p(float(sample["z"]))
173
+ if self.train and self.cfg.redshift_shift > 0:
174
+ delta = float(self.rng.uniform(-self.cfg.redshift_shift, self.cfg.redshift_shift))
175
+ y = max(0.0, y + delta)
176
+ grid = (grid + delta).astype(np.float32)
177
+ loglam_norm = ((grid - math.log(6000.0)) / 0.45).astype(np.float32)
178
+
179
+ x = np.stack(
180
+ [
181
+ norm_flux,
182
+ norm_ivar,
183
+ valid_grid.astype(np.float32),
184
+ lsf_norm,
185
+ loglam_norm,
186
+ grad,
187
+ abs_grad,
188
+ corrupt.astype(np.float32),
189
+ ],
190
+ axis=0,
191
+ )
192
+ return {
193
+ "x": x,
194
+ "valid": valid_grid,
195
+ "loglam": grid,
196
+ "target_flux": target_flux,
197
+ "loss_mask": corrupt & valid_grid,
198
+ "line_weight": line_weight,
199
+ "line_region": line_region,
200
+ "z": sample["z"],
201
+ "y": np.float32(y),
202
+ "zwarn": sample["zwarn"],
203
+ }
204
+
205
+ def _eval_rng(self, sample: dict[str, Any]) -> np.random.Generator:
206
+ object_id = str(sample.get("object_id", ""))
207
+ lam = np.asarray(sample["lambda"], dtype=np.float32)
208
+ key = f"{self.seed}|{object_id}|{float(sample['z']):.8g}|{len(lam)}|{float(lam[0]):.4f}|{float(lam[-1]):.4f}"
209
+ digest = hashlib.blake2b(key.encode("utf-8"), digest_size=8).digest()
210
+ return np.random.default_rng(int.from_bytes(digest, "little", signed=False))
211
+
212
+ def _interp_valid(self, x: np.ndarray, y: np.ndarray, valid: np.ndarray, x_new: np.ndarray, fill: float) -> np.ndarray:
213
+ good = valid & np.isfinite(x) & np.isfinite(y)
214
+ if good.sum() < 2:
215
+ return np.full_like(x_new, fill, dtype=np.float32)
216
+ return np.interp(x_new, x[good], y[good], left=fill, right=fill).astype(np.float32)
217
+
218
+ def _augment_bad_windows(self, bad: np.ndarray, rng: np.random.Generator) -> np.ndarray:
219
+ out = bad.copy()
220
+ n = len(out)
221
+ if rng.random() < self.cfg.crop_prob:
222
+ frac = float(rng.uniform(0.62, 0.96))
223
+ width = max(32, int(n * frac))
224
+ start = int(rng.integers(0, max(1, n - width)))
225
+ keep = np.zeros(n, dtype=np.bool_)
226
+ keep[start : start + width] = True
227
+ out |= ~keep
228
+ if rng.random() < self.cfg.bad_window_prob:
229
+ for _ in range(int(rng.integers(1, 5))):
230
+ width = int(rng.integers(max(8, n // 240), max(12, n // 45)))
231
+ start = int(rng.integers(0, max(1, n - width)))
232
+ out[start : start + width] = True
233
+ return out
234
+
235
+ def _augment_flux_calibration(self, flux: np.ndarray, lam: np.ndarray, rng: np.random.Generator) -> np.ndarray:
236
+ if rng.random() >= self.cfg.throughput_prob:
237
+ return flux
238
+ x = np.linspace(-1.0, 1.0, len(flux), dtype=np.float32)
239
+ coeff = rng.normal(0.0, [0.05, 0.025, 0.015]).astype(np.float32)
240
+ curve = 1.0 + coeff[0] * x + coeff[1] * (x * x - 0.33) + coeff[2] * np.sin(np.pi * x)
241
+ return (flux * np.clip(curve, 0.65, 1.35)).astype(np.float32)
242
+
243
+ def _augment_noise(self, flux: np.ndarray, ivar: np.ndarray, rng: np.random.Generator) -> np.ndarray:
244
+ if rng.random() >= self.cfg.noise_prob:
245
+ return flux
246
+ sigma = np.zeros_like(flux, dtype=np.float32)
247
+ good = np.isfinite(ivar) & (ivar > 0)
248
+ sigma[good] = 1.0 / np.sqrt(np.maximum(ivar[good], 1e-8))
249
+ scale = float(rng.uniform(0.15, 0.75))
250
+ return (flux + rng.normal(0.0, sigma * scale).astype(np.float32)).astype(np.float32)
251
+
252
+ def _augment_resolution(self, flux: np.ndarray, rng: np.random.Generator) -> np.ndarray:
253
+ if rng.random() >= self.cfg.resolution_prob:
254
+ return flux
255
+ finite = np.isfinite(flux)
256
+ fill = float(np.nanmedian(flux[finite])) if finite.any() else 0.0
257
+ base = np.nan_to_num(flux, nan=fill, posinf=fill, neginf=fill).astype(np.float32)
258
+ sigma = float(rng.uniform(0.6, 3.0))
259
+ radius = max(2, int(math.ceil(4.0 * sigma)))
260
+ x = np.arange(-radius, radius + 1, dtype=np.float32)
261
+ kernel = np.exp(-0.5 * (x / sigma) ** 2)
262
+ kernel = (kernel / kernel.sum()).astype(np.float32)
263
+ padded = np.pad(base, (radius, radius), mode="edge")
264
+ return np.convolve(padded, kernel, mode="valid").astype(np.float32)
265
+
266
+ def _augment_downsample_resample(
267
+ self,
268
+ flux: np.ndarray,
269
+ ivar: np.ndarray,
270
+ lam: np.ndarray,
271
+ rng: np.random.Generator,
272
+ ) -> tuple[np.ndarray, np.ndarray]:
273
+ if rng.random() >= self.cfg.downsample_prob:
274
+ return flux, ivar
275
+ n = len(flux)
276
+ if n < 32:
277
+ return flux, ivar
278
+ factor = int(rng.choice(np.asarray([2, 3, 4, 6, 8], dtype=np.int64)))
279
+ offset = int(rng.integers(0, factor))
280
+ idx = np.arange(offset, n, factor, dtype=np.int64)
281
+ if len(idx) < 4:
282
+ return flux, ivar
283
+ lam_good = np.asarray(lam[idx], dtype=np.float32)
284
+ flux_good = np.asarray(flux[idx], dtype=np.float32)
285
+ ivar_good = np.asarray(ivar[idx], dtype=np.float32)
286
+ good = np.isfinite(lam_good) & np.isfinite(flux_good) & np.isfinite(ivar_good)
287
+ if np.count_nonzero(good) < 4:
288
+ return flux, ivar
289
+ lam_good = lam_good[good]
290
+ order = np.argsort(lam_good)
291
+ lam_good = lam_good[order]
292
+ flux_good = flux_good[good][order]
293
+ ivar_good = ivar_good[good][order]
294
+ flux_out = np.interp(lam, lam_good, flux_good, left=flux_good[0], right=flux_good[-1]).astype(np.float32)
295
+ ivar_out = np.interp(lam, lam_good, ivar_good, left=0.0, right=0.0).astype(np.float32)
296
+ ivar_out *= float(rng.uniform(0.25, 0.85))
297
+ return flux_out, ivar_out
298
+
299
+ def _sample_input_dropout(self, abs_grad: np.ndarray, valid: np.ndarray, rng: np.random.Generator) -> np.ndarray:
300
+ corrupt = np.zeros_like(valid, dtype=np.bool_)
301
+ if valid.sum() < 16:
302
+ return corrupt
303
+ n = len(valid)
304
+ valid_idx = np.where(valid)[0]
305
+ ratio = self.cfg.random_mask_ratio if self.train else self.cfg.eval_mask_ratio
306
+ if ratio > 0:
307
+ n_rand = max(1, int(round(len(valid_idx) * min(float(ratio), 1.0))))
308
+ if self.cfg.mask_mode == "pixel":
309
+ corrupt[rng.choice(valid_idx, size=min(n_rand, len(valid_idx)), replace=False)] = True
310
+ else:
311
+ line_bias = self.cfg.mask_mode in {"line_span", "mixed_span"}
312
+ self._add_spans_to_mask(corrupt, valid, abs_grad, n_rand, rng, line_bias=line_bias)
313
+ if self.train and rng.random() < self.cfg.span_dropout_prob:
314
+ for _ in range(int(rng.integers(1, 4))):
315
+ width = int(rng.integers(max(4, n // 220), max(8, n // 55)))
316
+ start = int(rng.integers(0, max(1, n - width)))
317
+ corrupt[start : start + width] |= valid[start : start + width]
318
+ if self.train and rng.random() < self.cfg.line_dropout_prob:
319
+ score = abs_grad.copy()
320
+ score[~valid] = 0.0
321
+ if np.count_nonzero(score) > 0:
322
+ k = max(4, n // 96)
323
+ peaks = np.argsort(score)[-k:]
324
+ for j in peaks:
325
+ width = int(rng.integers(max(2, n // 900), max(4, n // 280)))
326
+ lo = max(0, int(j) - width)
327
+ hi = min(n, int(j) + width + 1)
328
+ corrupt[lo:hi] |= valid[lo:hi]
329
+ return corrupt & valid
330
+
331
+ def _add_spans_to_mask(
332
+ self,
333
+ corrupt: np.ndarray,
334
+ valid: np.ndarray,
335
+ abs_grad: np.ndarray,
336
+ target_count: int,
337
+ rng: np.random.Generator,
338
+ *,
339
+ line_bias: bool,
340
+ ) -> None:
341
+ valid_idx = np.where(valid)[0]
342
+ if len(valid_idx) == 0:
343
+ return
344
+ lo_w = max(1, int(self.cfg.mask_span_min))
345
+ hi_w = max(lo_w + 1, int(self.cfg.mask_span_max) + 1)
346
+ probs = None
347
+ if line_bias:
348
+ score = abs_grad[valid_idx].astype(np.float64)
349
+ positive = score[np.isfinite(score) & (score > 0)]
350
+ scale = float(np.percentile(positive, 90)) if len(positive) else 1.0
351
+ if not math.isfinite(scale) or scale <= 0:
352
+ scale = 1.0
353
+ score = np.clip(score / scale, 0.0, 5.0) + 0.05
354
+ probs = score / score.sum()
355
+ max_tries = max(32, target_count * 4)
356
+ tries = 0
357
+ while int(np.count_nonzero(corrupt & valid)) < target_count and tries < max_tries:
358
+ tries += 1
359
+ center = int(rng.choice(valid_idx, p=probs))
360
+ width = int(rng.integers(lo_w, hi_w))
361
+ lo = max(0, center - width // 2)
362
+ hi = min(len(valid), lo + width)
363
+ corrupt[lo:hi] |= valid[lo:hi]
364
+
365
+ def _line_weights(self, abs_grad: np.ndarray, valid: np.ndarray) -> np.ndarray:
366
+ weight = np.ones_like(abs_grad, dtype=np.float32)
367
+ if valid.sum() < 16:
368
+ return weight
369
+ scale = float(np.percentile(abs_grad[valid], 90))
370
+ if math.isfinite(scale) and scale > 0:
371
+ weight += 2.0 * np.clip(abs_grad / scale, 0.0, 2.0)
372
+ weight[~valid] = 1.0
373
+ return np.clip(weight, 1.0, 5.0).astype(np.float32)
374
+
375
+ def _line_region(self, abs_grad: np.ndarray, valid: np.ndarray) -> np.ndarray:
376
+ region = np.zeros_like(valid, dtype=np.bool_)
377
+ if valid.sum() < 16:
378
+ return region
379
+ pct = min(max(float(self.cfg.line_region_percentile), 0.0), 100.0)
380
+ thresh = float(np.percentile(abs_grad[valid], pct))
381
+ if math.isfinite(thresh) and thresh > 0:
382
+ region = (abs_grad >= thresh) & valid
383
+ return region.astype(np.bool_)
384
+
385
+
386
+ class ConvBlock(nn.Module):
387
+ def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 7, stride: int = 1, dropout: float = 0.0):
388
+ super().__init__()
389
+ padding = kernel_size // 2
390
+ self.net = nn.Sequential(
391
+ nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False),
392
+ nn.BatchNorm1d(out_channels),
393
+ nn.GELU(),
394
+ nn.Dropout(dropout),
395
+ nn.Conv1d(out_channels, out_channels, kernel_size=kernel_size, stride=1, padding=padding, bias=False),
396
+ nn.BatchNorm1d(out_channels),
397
+ )
398
+ self.skip = (
399
+ nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)
400
+ if stride != 1 or in_channels != out_channels
401
+ else nn.Identity()
402
+ )
403
+ self.act = nn.GELU()
404
+
405
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
406
+ return self.act(self.net(x) + self.skip(x))
407
+
408
+
409
+ class LayerScaleEncoderLayer(nn.Module):
410
+ def __init__(self, d_model: int, heads: int, dropout: float, layerscale_init: float):
411
+ super().__init__()
412
+ self.norm1 = nn.LayerNorm(d_model)
413
+ self.self_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
414
+ self.dropout1 = nn.Dropout(dropout)
415
+ self.norm2 = nn.LayerNorm(d_model)
416
+ self.linear1 = nn.Linear(d_model, d_model * 4)
417
+ self.linear2 = nn.Linear(d_model * 4, d_model)
418
+ self.dropout = nn.Dropout(dropout)
419
+ self.dropout2 = nn.Dropout(dropout)
420
+ self.act = nn.GELU()
421
+ init = float(layerscale_init)
422
+ self.ls1 = nn.Parameter(torch.full((d_model,), init))
423
+ self.ls2 = nn.Parameter(torch.full((d_model,), init))
424
+
425
+ def forward(
426
+ self,
427
+ src: torch.Tensor,
428
+ src_mask: torch.Tensor | None = None,
429
+ src_key_padding_mask: torch.Tensor | None = None,
430
+ is_causal: bool = False,
431
+ ) -> torch.Tensor:
432
+ q = self.norm1(src)
433
+ attn, _ = self.self_attn(
434
+ q,
435
+ q,
436
+ q,
437
+ attn_mask=src_mask,
438
+ key_padding_mask=src_key_padding_mask,
439
+ need_weights=False,
440
+ is_causal=is_causal,
441
+ )
442
+ src = src + self.ls1 * self.dropout1(attn)
443
+ ff = self.linear2(self.dropout(self.act(self.linear1(self.norm2(src)))))
444
+ return src + self.ls2 * self.dropout2(ff)
445
+
446
+
447
+ class HybridSpecZ(nn.Module):
448
+ def __init__(
449
+ self,
450
+ in_channels: int = 8,
451
+ d_model: int = 256,
452
+ conv_width: int = 128,
453
+ layers: int = 5,
454
+ heads: int = 8,
455
+ dropout: float = 0.1,
456
+ fourier_freqs: int = 32,
457
+ z_bins: int = 64,
458
+ y_min: float = 0.0,
459
+ y_max: float = math.log1p(6.0),
460
+ prediction_mode: str = "regression",
461
+ bin_temperature: float = 1.0,
462
+ residual_scale: float = 0.06,
463
+ candidate_topk: int = 5,
464
+ stem_stride: int = 8,
465
+ rec_hidden_mult: int = 0,
466
+ rec_refine_width: int = 16,
467
+ rec_refine_kernel: int = 5,
468
+ layerscale_init: float = 0.0,
469
+ ):
470
+ super().__init__()
471
+ allowed_modes = {
472
+ "regression",
473
+ "softbin",
474
+ "hybrid",
475
+ "bin_residual",
476
+ "ranked_bin_residual",
477
+ "candidate_rerank",
478
+ "calibrated_bin_residual",
479
+ }
480
+ if prediction_mode not in allowed_modes:
481
+ raise ValueError(f"prediction_mode must be one of {sorted(allowed_modes)}, got {prediction_mode!r}")
482
+ self.fourier_freqs = fourier_freqs
483
+ self.z_bins = z_bins
484
+ self.y_min = y_min
485
+ self.y_max = y_max
486
+ self.prediction_mode = prediction_mode
487
+ self.bin_temperature = bin_temperature
488
+ self.residual_scale = residual_scale
489
+ self.candidate_topk = max(1, min(int(candidate_topk), z_bins))
490
+ if stem_stride not in {4, 8}:
491
+ raise ValueError(f"stem_stride must be 4 or 8, got {stem_stride}")
492
+ self.stem_stride = int(stem_stride)
493
+ self.rec_pixels_per_token = int(stem_stride)
494
+ self.stride_stages = int(round(math.log2(self.stem_stride)))
495
+ bin_width = (y_max - y_min) / z_bins
496
+ centers = torch.linspace(y_min + 0.5 * bin_width, y_max - 0.5 * bin_width, z_bins)
497
+ self.register_buffer("z_bin_centers", centers, persistent=False)
498
+
499
+ if self.stem_stride == 8:
500
+ self.stem = nn.Sequential(
501
+ ConvBlock(in_channels, conv_width, kernel_size=9, stride=2, dropout=dropout * 0.5),
502
+ ConvBlock(conv_width, conv_width, kernel_size=7, stride=2, dropout=dropout * 0.5),
503
+ ConvBlock(conv_width, d_model, kernel_size=7, stride=2, dropout=dropout * 0.5),
504
+ ConvBlock(d_model, d_model, kernel_size=5, stride=1, dropout=dropout * 0.5),
505
+ )
506
+ else:
507
+ self.stem = nn.Sequential(
508
+ ConvBlock(in_channels, conv_width, kernel_size=9, stride=2, dropout=dropout * 0.5),
509
+ ConvBlock(conv_width, d_model, kernel_size=7, stride=2, dropout=dropout * 0.5),
510
+ ConvBlock(d_model, d_model, kernel_size=5, stride=1, dropout=dropout * 0.5),
511
+ )
512
+ self.pos_proj = nn.Sequential(nn.Linear(fourier_freqs * 2, d_model), nn.LayerNorm(d_model))
513
+ self.cls = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
514
+ # The model never receives true z; this learned query is the always-masked z token.
515
+ self.z_query = nn.Parameter(torch.randn(1, 1, d_model) * 0.02)
516
+
517
+ if layerscale_init > 0:
518
+ enc_layer = LayerScaleEncoderLayer(d_model, heads, dropout, layerscale_init)
519
+ else:
520
+ enc_layer = nn.TransformerEncoderLayer(
521
+ d_model=d_model,
522
+ nhead=heads,
523
+ dim_feedforward=d_model * 4,
524
+ dropout=dropout,
525
+ batch_first=True,
526
+ norm_first=True,
527
+ activation="gelu",
528
+ )
529
+ self.encoder = nn.TransformerEncoder(enc_layer, num_layers=layers)
530
+ self.pool_gate = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, 1))
531
+ head_dim = d_model * 5
532
+ 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))
533
+ 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))
534
+ self.z_candidate_head = nn.Sequential(
535
+ nn.LayerNorm(head_dim),
536
+ nn.Linear(head_dim, d_model),
537
+ nn.GELU(),
538
+ nn.Dropout(dropout),
539
+ nn.Linear(d_model, z_bins),
540
+ )
541
+ self.z_rerank_head = nn.Sequential(
542
+ nn.LayerNorm(head_dim + 3),
543
+ nn.Linear(head_dim + 3, max(64, d_model // 2)),
544
+ nn.GELU(),
545
+ nn.Dropout(dropout),
546
+ nn.Linear(max(64, d_model // 2), 1),
547
+ )
548
+ self.z_calib_head = nn.Sequential(
549
+ nn.LayerNorm(head_dim + 3),
550
+ nn.Linear(head_dim + 3, max(64, d_model // 2)),
551
+ nn.GELU(),
552
+ nn.Dropout(dropout),
553
+ nn.Linear(max(64, d_model // 2), 1),
554
+ )
555
+ nn.init.zeros_(self.z_calib_head[-1].weight)
556
+ nn.init.zeros_(self.z_calib_head[-1].bias)
557
+ if rec_hidden_mult > 0:
558
+ rec_hidden = int(d_model * rec_hidden_mult)
559
+ self.rec_head = nn.Sequential(
560
+ nn.LayerNorm(d_model),
561
+ nn.Linear(d_model, rec_hidden),
562
+ nn.GELU(),
563
+ nn.Dropout(dropout),
564
+ nn.Linear(rec_hidden, self.rec_pixels_per_token),
565
+ )
566
+ else:
567
+ self.rec_head = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, self.rec_pixels_per_token))
568
+ rec_pad = int(rec_refine_kernel) // 2
569
+ self.rec_refine = nn.Sequential(
570
+ nn.Conv1d(1, rec_refine_width, kernel_size=rec_refine_kernel, padding=rec_pad),
571
+ nn.GELU(),
572
+ nn.Conv1d(rec_refine_width, 1, kernel_size=rec_refine_kernel, padding=rec_pad),
573
+ )
574
+
575
+ def forward(self, x: torch.Tensor, valid: torch.Tensor, loglam: torch.Tensor) -> dict[str, torch.Tensor]:
576
+ bsz = x.shape[0]
577
+ h = self.stem(x).transpose(1, 2)
578
+ tok_valid = valid.float().unsqueeze(1)
579
+ tok_loglam = loglam.unsqueeze(1)
580
+ for _ in range(self.stride_stages):
581
+ tok_valid = F.avg_pool1d(tok_valid, kernel_size=2, stride=2, ceil_mode=True)
582
+ tok_loglam = F.avg_pool1d(tok_loglam, kernel_size=2, stride=2, ceil_mode=True)
583
+ tok_valid = tok_valid.squeeze(1) > 0.20
584
+ tok_loglam = tok_loglam.squeeze(1)
585
+ if tok_valid.shape[1] != h.shape[1]:
586
+ tok_valid = tok_valid[:, : h.shape[1]]
587
+ tok_loglam = tok_loglam[:, : h.shape[1]]
588
+ h = h[:, : tok_valid.shape[1]]
589
+
590
+ h = h + self.pos_proj(fourier_loglam(tok_loglam, self.fourier_freqs))
591
+ cls = self.cls.expand(bsz, -1, -1)
592
+ z_query = self.z_query.expand(bsz, -1, -1)
593
+ src = torch.cat([cls, z_query, h], dim=1)
594
+ special_valid = torch.ones((bsz, 2), dtype=torch.bool, device=x.device)
595
+ src_valid = torch.cat([special_valid, tok_valid], dim=1)
596
+ padding = ~src_valid
597
+ memory = self.encoder(src, src_key_padding_mask=padding)
598
+
599
+ spec = memory[:, 2:]
600
+ spec_valid = src_valid[:, 2:]
601
+ spec_mask = spec_valid.unsqueeze(-1)
602
+ rec = self.rec_head(spec).reshape(bsz, -1)
603
+ rec = rec + self.rec_refine(rec.unsqueeze(1)).squeeze(1)
604
+ if rec.shape[1] > x.shape[-1]:
605
+ rec = rec[:, : x.shape[-1]]
606
+ elif rec.shape[1] < x.shape[-1]:
607
+ rec = F.pad(rec, (0, x.shape[-1] - rec.shape[1]))
608
+ denom = spec_valid.float().sum(dim=1).clamp_min(1.0).unsqueeze(-1)
609
+ mean_pool = (spec * spec_mask.float()).sum(dim=1) / denom
610
+ max_pool = spec.masked_fill(~spec_mask, -1e4).max(dim=1).values
611
+ gate_logits = self.pool_gate(spec).squeeze(-1).masked_fill(~spec_valid, -1e4)
612
+ gate = torch.softmax(gate_logits, dim=1)
613
+ attn_pool = torch.einsum("bn,bnd->bd", gate, spec)
614
+ feat = torch.cat([memory[:, 0], memory[:, 1], mean_pool, max_pool, attn_pool], dim=-1)
615
+ z_params = self.z_head(feat)
616
+ z_bin_logits = self.z_bin_head(feat)
617
+ candidate_residual = self.residual_scale * torch.tanh(self.z_candidate_head(feat))
618
+ centers = self.z_bin_centers.to(dtype=z_bin_logits.dtype, device=z_bin_logits.device)
619
+ candidate_y = (centers.unsqueeze(0) + candidate_residual).clamp(self.y_min, self.y_max)
620
+ topk_logits, topk_bins = torch.topk(z_bin_logits, k=self.candidate_topk, dim=-1)
621
+ candidate_topk_y = candidate_y.gather(1, topk_bins)
622
+ rank = torch.linspace(0.0, 1.0, self.candidate_topk, device=x.device, dtype=feat.dtype).view(1, self.candidate_topk, 1)
623
+ rerank_feat = feat.unsqueeze(1).expand(-1, self.candidate_topk, -1)
624
+ rerank_in = torch.cat(
625
+ [
626
+ rerank_feat,
627
+ candidate_topk_y.to(dtype=feat.dtype).unsqueeze(-1),
628
+ topk_logits.to(dtype=feat.dtype).unsqueeze(-1),
629
+ rank.expand(bsz, -1, -1),
630
+ ],
631
+ dim=-1,
632
+ )
633
+ rerank_logits = self.z_rerank_head(rerank_in).squeeze(-1)
634
+ rerank_idx = rerank_logits.argmax(dim=-1, keepdim=True)
635
+ y_reranked = candidate_topk_y.gather(1, rerank_idx).squeeze(1)
636
+ y_reg = z_params[:, 0]
637
+ bin_prob = torch.softmax(z_bin_logits / max(self.bin_temperature, 1e-4), dim=-1)
638
+ y_bin = (bin_prob * self.z_bin_centers.to(dtype=bin_prob.dtype, device=bin_prob.device)).sum(dim=-1)
639
+ y_ranked = (bin_prob * candidate_y.to(dtype=bin_prob.dtype)).sum(dim=-1)
640
+ y_legacy_bin_residual = y_bin + self.residual_scale * torch.tanh(y_reg)
641
+ calib_in = torch.cat(
642
+ [
643
+ feat,
644
+ y_legacy_bin_residual.to(dtype=feat.dtype).unsqueeze(-1),
645
+ y_ranked.to(dtype=feat.dtype).unsqueeze(-1),
646
+ candidate_topk_y[:, 0].to(dtype=feat.dtype).unsqueeze(-1),
647
+ ],
648
+ dim=-1,
649
+ )
650
+ y_calibrated = y_legacy_bin_residual + self.residual_scale * torch.tanh(self.z_calib_head(calib_in).squeeze(-1))
651
+ if self.prediction_mode == "regression":
652
+ y_pred = y_reg
653
+ elif self.prediction_mode == "softbin":
654
+ y_pred = y_bin
655
+ elif self.prediction_mode == "hybrid":
656
+ y_pred = 0.35 * y_reg + 0.65 * y_bin
657
+ elif self.prediction_mode == "ranked_bin_residual":
658
+ y_pred = 0.5 * y_legacy_bin_residual + 0.5 * y_ranked
659
+ elif self.prediction_mode == "candidate_rerank":
660
+ y_pred = y_reranked
661
+ elif self.prediction_mode == "calibrated_bin_residual":
662
+ y_pred = y_calibrated
663
+ else:
664
+ y_pred = y_legacy_bin_residual
665
+ y_pred = y_pred.clamp(self.y_min, self.y_max)
666
+ return {
667
+ "rec": rec,
668
+ "y_mu": y_pred,
669
+ "y_pred": y_pred,
670
+ "y_reg": y_reg,
671
+ "y_bin": y_bin,
672
+ "y_ranked": y_ranked,
673
+ "y_top1_candidate": candidate_topk_y[:, 0],
674
+ "y_reranked": y_reranked,
675
+ "y_calibrated": y_calibrated,
676
+ "y_logvar": torch.clamp(z_params[:, 1], -8.0, 4.0),
677
+ "z_bin_logits": z_bin_logits,
678
+ "z_feat": feat,
679
+ "candidate_y": candidate_y,
680
+ "candidate_topk_y": candidate_topk_y,
681
+ "candidate_topk_bins": topk_bins,
682
+ "candidate_topk_logits": topk_logits,
683
+ "rerank_logits": rerank_logits,
684
+ }
685
+
686
+ def y_to_bin(self, y: torch.Tensor) -> torch.Tensor:
687
+ scaled = (y - self.y_min) / max(self.y_max - self.y_min, 1e-6)
688
+ return torch.clamp((scaled * self.z_bins).long(), 0, self.z_bins - 1)
689
+
690
+
691
+ class WavelengthTokenSpecZ(HybridSpecZ):
692
+ """Transformer encoder over wavelength-conditioned tokens instead of a conv pixel stem."""
693
+
694
+ def __init__(
695
+ self,
696
+ in_channels: int = 8,
697
+ d_model: int = 256,
698
+ conv_width: int = 128,
699
+ layers: int = 5,
700
+ heads: int = 8,
701
+ dropout: float = 0.1,
702
+ fourier_freqs: int = 32,
703
+ z_bins: int = 64,
704
+ y_min: float = 0.0,
705
+ y_max: float = math.log1p(6.0),
706
+ prediction_mode: str = "regression",
707
+ bin_temperature: float = 1.0,
708
+ residual_scale: float = 0.06,
709
+ candidate_topk: int = 5,
710
+ token_stride: int = 8,
711
+ rec_hidden_mult: int = 0,
712
+ rec_refine_width: int = 16,
713
+ rec_refine_kernel: int = 5,
714
+ layerscale_init: float = 0.0,
715
+ ):
716
+ super().__init__(
717
+ in_channels=in_channels,
718
+ d_model=d_model,
719
+ conv_width=conv_width,
720
+ layers=layers,
721
+ heads=heads,
722
+ dropout=dropout,
723
+ fourier_freqs=fourier_freqs,
724
+ z_bins=z_bins,
725
+ y_min=y_min,
726
+ y_max=y_max,
727
+ prediction_mode=prediction_mode,
728
+ bin_temperature=bin_temperature,
729
+ residual_scale=residual_scale,
730
+ candidate_topk=candidate_topk,
731
+ stem_stride=8,
732
+ rec_hidden_mult=rec_hidden_mult,
733
+ rec_refine_width=rec_refine_width,
734
+ rec_refine_kernel=rec_refine_kernel,
735
+ layerscale_init=layerscale_init,
736
+ )
737
+ self.token_stride = max(1, int(token_stride))
738
+ self.rec_pixels_per_token = self.token_stride
739
+ self.stem = nn.Identity()
740
+ self.input_proj = nn.Sequential(
741
+ nn.Linear(in_channels + fourier_freqs * 2, d_model),
742
+ nn.LayerNorm(d_model),
743
+ nn.GELU(),
744
+ nn.Dropout(dropout),
745
+ nn.Linear(d_model, d_model),
746
+ )
747
+ if rec_hidden_mult > 0:
748
+ rec_hidden = int(d_model * rec_hidden_mult)
749
+ self.rec_head = nn.Sequential(
750
+ nn.LayerNorm(d_model),
751
+ nn.Linear(d_model, rec_hidden),
752
+ nn.GELU(),
753
+ nn.Dropout(dropout),
754
+ nn.Linear(rec_hidden, self.rec_pixels_per_token),
755
+ )
756
+ else:
757
+ self.rec_head = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, self.rec_pixels_per_token))
758
+
759
+ def _pool_wavelength_tokens(
760
+ self,
761
+ x: torch.Tensor,
762
+ valid: torch.Tensor,
763
+ loglam: torch.Tensor,
764
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
765
+ bsz, channels, length = x.shape
766
+ stride = self.token_stride
767
+ pad = (-length) % stride
768
+ if pad:
769
+ x = F.pad(x, (0, pad))
770
+ valid = F.pad(valid.float(), (0, pad)).bool()
771
+ loglam = torch.cat([loglam, loglam[:, -1:].expand(-1, pad)], dim=1)
772
+ token_count = x.shape[-1] // stride
773
+ x_group = x.reshape(bsz, channels, token_count, stride)
774
+ valid_group = valid.reshape(bsz, 1, token_count, stride).float()
775
+ loglam_group = loglam.reshape(bsz, 1, token_count, stride)
776
+ counts = valid_group.sum(dim=-1)
777
+ denom = counts.clamp_min(1.0)
778
+ token_x = (x_group * valid_group).sum(dim=-1) / denom
779
+ token_loglam = (loglam_group * valid_group).sum(dim=-1) / denom
780
+ fallback_loglam = loglam_group.mean(dim=-1)
781
+ token_loglam = torch.where(counts > 0, token_loglam, fallback_loglam).squeeze(1)
782
+ token_valid = counts.squeeze(1) > 0
783
+ return token_x.transpose(1, 2), token_valid, token_loglam
784
+
785
+ def forward(self, x: torch.Tensor, valid: torch.Tensor, loglam: torch.Tensor) -> dict[str, torch.Tensor]:
786
+ bsz = x.shape[0]
787
+ token_x, tok_valid, tok_loglam = self._pool_wavelength_tokens(x, valid, loglam)
788
+ h = self.input_proj(torch.cat([token_x, fourier_loglam(tok_loglam, self.fourier_freqs)], dim=-1))
789
+ cls = self.cls.expand(bsz, -1, -1)
790
+ z_query = self.z_query.expand(bsz, -1, -1)
791
+ src = torch.cat([cls, z_query, h], dim=1)
792
+ special_valid = torch.ones((bsz, 2), dtype=torch.bool, device=x.device)
793
+ src_valid = torch.cat([special_valid, tok_valid], dim=1)
794
+ padding = ~src_valid
795
+ memory = self.encoder(src, src_key_padding_mask=padding)
796
+
797
+ spec = memory[:, 2:]
798
+ spec_valid = src_valid[:, 2:]
799
+ spec_mask = spec_valid.unsqueeze(-1)
800
+ rec = self.rec_head(spec).reshape(bsz, -1)
801
+ rec = rec + self.rec_refine(rec.unsqueeze(1)).squeeze(1)
802
+ if rec.shape[1] > x.shape[-1]:
803
+ rec = rec[:, : x.shape[-1]]
804
+ elif rec.shape[1] < x.shape[-1]:
805
+ rec = F.pad(rec, (0, x.shape[-1] - rec.shape[1]))
806
+ denom = spec_valid.float().sum(dim=1).clamp_min(1.0).unsqueeze(-1)
807
+ mean_pool = (spec * spec_mask.float()).sum(dim=1) / denom
808
+ max_pool = spec.masked_fill(~spec_mask, -1e4).max(dim=1).values
809
+ gate_logits = self.pool_gate(spec).squeeze(-1).masked_fill(~spec_valid, -1e4)
810
+ gate = torch.softmax(gate_logits, dim=1)
811
+ attn_pool = torch.einsum("bn,bnd->bd", gate, spec)
812
+ feat = torch.cat([memory[:, 0], memory[:, 1], mean_pool, max_pool, attn_pool], dim=-1)
813
+ z_params = self.z_head(feat)
814
+ z_bin_logits = self.z_bin_head(feat)
815
+ candidate_residual = self.residual_scale * torch.tanh(self.z_candidate_head(feat))
816
+ centers = self.z_bin_centers.to(dtype=z_bin_logits.dtype, device=z_bin_logits.device)
817
+ candidate_y = (centers.unsqueeze(0) + candidate_residual).clamp(self.y_min, self.y_max)
818
+ topk_logits, topk_bins = torch.topk(z_bin_logits, k=self.candidate_topk, dim=-1)
819
+ candidate_topk_y = candidate_y.gather(1, topk_bins)
820
+ rank = torch.linspace(0.0, 1.0, self.candidate_topk, device=x.device, dtype=feat.dtype).view(1, self.candidate_topk, 1)
821
+ rerank_feat = feat.unsqueeze(1).expand(-1, self.candidate_topk, -1)
822
+ rerank_in = torch.cat(
823
+ [
824
+ rerank_feat,
825
+ candidate_topk_y.to(dtype=feat.dtype).unsqueeze(-1),
826
+ topk_logits.to(dtype=feat.dtype).unsqueeze(-1),
827
+ rank.expand(bsz, -1, -1),
828
+ ],
829
+ dim=-1,
830
+ )
831
+ rerank_logits = self.z_rerank_head(rerank_in).squeeze(-1)
832
+ rerank_idx = rerank_logits.argmax(dim=-1, keepdim=True)
833
+ y_reranked = candidate_topk_y.gather(1, rerank_idx).squeeze(1)
834
+ y_reg = z_params[:, 0]
835
+ bin_prob = torch.softmax(z_bin_logits / max(self.bin_temperature, 1e-4), dim=-1)
836
+ y_bin = (bin_prob * self.z_bin_centers.to(dtype=bin_prob.dtype, device=bin_prob.device)).sum(dim=-1)
837
+ y_ranked = (bin_prob * candidate_y.to(dtype=bin_prob.dtype)).sum(dim=-1)
838
+ y_legacy_bin_residual = y_bin + self.residual_scale * torch.tanh(y_reg)
839
+ calib_in = torch.cat(
840
+ [
841
+ feat,
842
+ y_legacy_bin_residual.to(dtype=feat.dtype).unsqueeze(-1),
843
+ y_ranked.to(dtype=feat.dtype).unsqueeze(-1),
844
+ candidate_topk_y[:, 0].to(dtype=feat.dtype).unsqueeze(-1),
845
+ ],
846
+ dim=-1,
847
+ )
848
+ y_calibrated = y_legacy_bin_residual + self.residual_scale * torch.tanh(self.z_calib_head(calib_in).squeeze(-1))
849
+ if self.prediction_mode == "regression":
850
+ y_pred = y_reg
851
+ elif self.prediction_mode == "softbin":
852
+ y_pred = y_bin
853
+ elif self.prediction_mode == "hybrid":
854
+ y_pred = 0.35 * y_reg + 0.65 * y_bin
855
+ elif self.prediction_mode == "ranked_bin_residual":
856
+ y_pred = 0.5 * y_legacy_bin_residual + 0.5 * y_ranked
857
+ elif self.prediction_mode == "candidate_rerank":
858
+ y_pred = y_reranked
859
+ elif self.prediction_mode == "calibrated_bin_residual":
860
+ y_pred = y_calibrated
861
+ else:
862
+ y_pred = y_legacy_bin_residual
863
+ y_pred = y_pred.clamp(self.y_min, self.y_max)
864
+ return {
865
+ "rec": rec,
866
+ "y_mu": y_pred,
867
+ "y_pred": y_pred,
868
+ "y_reg": y_reg,
869
+ "y_bin": y_bin,
870
+ "y_ranked": y_ranked,
871
+ "y_top1_candidate": candidate_topk_y[:, 0],
872
+ "y_reranked": y_reranked,
873
+ "y_calibrated": y_calibrated,
874
+ "y_logvar": torch.clamp(z_params[:, 1], -8.0, 4.0),
875
+ "z_bin_logits": z_bin_logits,
876
+ "z_feat": feat,
877
+ "candidate_y": candidate_y,
878
+ "candidate_topk_y": candidate_topk_y,
879
+ "candidate_topk_bins": topk_bins,
880
+ "candidate_topk_logits": topk_logits,
881
+ "rerank_logits": rerank_logits,
882
+ }
883
+
884
+
885
+ def move_to_device(batch: dict[str, torch.Tensor], device: torch.device) -> dict[str, torch.Tensor]:
886
+ return {k: v.to(device, non_blocking=True) if torch.is_tensor(v) else v for k, v in batch.items()}
887
+
888
+
889
+ def limit_batch_examples(batch: dict[str, torch.Tensor], max_examples: int | None, seen_examples: int) -> dict[str, torch.Tensor] | None:
890
+ if max_examples is None or max_examples <= 0:
891
+ return batch
892
+ remaining = int(max_examples) - int(seen_examples)
893
+ if remaining <= 0:
894
+ return None
895
+ bsz = int(batch["y"].shape[0])
896
+ if remaining >= bsz:
897
+ return batch
898
+ return {k: v[:remaining] if torch.is_tensor(v) and v.shape[:1] == (bsz,) else v for k, v in batch.items()}
899
+
900
+
901
+ def load_checkpoint_into_model(model: nn.Module, state: dict[str, torch.Tensor], allow_mismatched: bool = False) -> None:
902
+ if not allow_mismatched:
903
+ try:
904
+ model.load_state_dict(state, strict=True)
905
+ except RuntimeError:
906
+ missing, unexpected = model.load_state_dict(state, strict=False)
907
+ print(f"RESUME_NONSTRICT missing={list(missing)} unexpected={list(unexpected)}")
908
+ return
909
+
910
+ target_state = model.state_dict()
911
+ compatible = {}
912
+ skipped = []
913
+ for key, value in state.items():
914
+ target = target_state.get(key)
915
+ if target is not None and tuple(target.shape) == tuple(value.shape):
916
+ compatible[key] = value
917
+ else:
918
+ skipped.append(key)
919
+ missing, unexpected = model.load_state_dict(compatible, strict=False)
920
+ print(
921
+ "RESUME_FILTERED "
922
+ f"loaded={len(compatible)} skipped={len(skipped)} "
923
+ f"missing={list(missing)} unexpected={list(unexpected)} skipped_keys={skipped[:20]}"
924
+ )
925
+
926
+
927
+ def configure_trainable_parameters(model: nn.Module, freeze_mode: str, train_top_layers: int, train_layernorms: bool) -> int:
928
+ if freeze_mode == "none":
929
+ for param in model.parameters():
930
+ param.requires_grad = True
931
+ elif freeze_mode == "rerank":
932
+ for param in model.parameters():
933
+ param.requires_grad = False
934
+ for name, param in model.named_parameters():
935
+ if name.startswith("z_rerank_head"):
936
+ param.requires_grad = True
937
+ elif freeze_mode == "calib":
938
+ for param in model.parameters():
939
+ param.requires_grad = False
940
+ for name, param in model.named_parameters():
941
+ if name.startswith("z_calib_head"):
942
+ param.requires_grad = True
943
+ elif freeze_mode == "adapter":
944
+ for param in model.parameters():
945
+ param.requires_grad = False
946
+ train_prefixes = (
947
+ "stem",
948
+ "input_proj",
949
+ "pos_proj",
950
+ "pool_gate",
951
+ "z_head",
952
+ "z_bin_head",
953
+ "z_candidate_head",
954
+ "z_rerank_head",
955
+ "z_calib_head",
956
+ "rec_head",
957
+ "rec_refine",
958
+ "cls",
959
+ "z_query",
960
+ )
961
+ for name, param in model.named_parameters():
962
+ if name.startswith(train_prefixes):
963
+ param.requires_grad = True
964
+ if train_layernorms and (".norm" in name or name.endswith("norm.weight") or name.endswith("norm.bias")):
965
+ param.requires_grad = True
966
+ layers = getattr(getattr(model, "encoder", None), "layers", None)
967
+ if layers is not None and train_top_layers > 0:
968
+ for layer in list(layers)[-int(train_top_layers) :]:
969
+ for param in layer.parameters():
970
+ param.requires_grad = True
971
+ else:
972
+ raise ValueError(f"Unknown freeze mode {freeze_mode!r}")
973
+ return sum(p.numel() for p in model.parameters() if p.requires_grad)
974
+
975
+
976
+ def replay_loss(
977
+ student_out: dict[str, torch.Tensor],
978
+ teacher_out: dict[str, torch.Tensor],
979
+ batch: dict[str, torch.Tensor],
980
+ *,
981
+ y_weight: float,
982
+ bin_weight: float,
983
+ clean_only: bool,
984
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
985
+ y_student = student_out.get("y_pred", student_out["y_mu"]).float()
986
+ y_teacher = teacher_out.get("y_pred", teacher_out["y_mu"]).float().detach()
987
+ mask = torch.isfinite(batch["y"])
988
+ if clean_only:
989
+ mask = mask & (~batch["zwarn"].bool())
990
+ if mask.sum() == 0:
991
+ zero = y_student.sum() * 0.0
992
+ return zero, {"replay_y": zero.detach(), "replay_bin": zero.detach()}
993
+ replay_y = F.smooth_l1_loss(y_student[mask], y_teacher[mask], beta=0.01)
994
+ replay_bin = y_student.sum() * 0.0
995
+ if bin_weight > 0 and "z_bin_logits" in student_out and "z_bin_logits" in teacher_out:
996
+ student_logp = F.log_softmax(student_out["z_bin_logits"][mask].float(), dim=-1)
997
+ teacher_p = F.softmax(teacher_out["z_bin_logits"][mask].float().detach(), dim=-1)
998
+ replay_bin = F.kl_div(student_logp, teacher_p, reduction="batchmean")
999
+ total = y_weight * replay_y + bin_weight * replay_bin
1000
+ return total, {"replay_y": replay_y.detach(), "replay_bin": replay_bin.detach()}
1001
+
1002
+
1003
+ 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]]:
1004
+ parts = redshift_losses(model, out, batch["y"], batch["zwarn"], cfg)
1005
+ if "rec" in out and "target_flux" in batch and "loss_mask" in batch:
1006
+ line_weight = batch.get("line_weight")
1007
+ if line_weight is not None:
1008
+ line_weight = line_weight.pow(cfg.line_weight_power)
1009
+ rec = masked_huber(out["rec"], batch["target_flux"], batch["loss_mask"], weight=line_weight)
1010
+ else:
1011
+ rec = parts["z_huber"].sum() * 0.0
1012
+ total = (
1013
+ cfg.rec_weight * rec
1014
+ + cfg.z_weight * parts["z_huber"]
1015
+ + cfg.z_bin_weight * parts["z_bin"]
1016
+ + cfg.z_candidate_weight * parts["z_candidate"]
1017
+ + cfg.z_rerank_weight * parts["z_rerank"]
1018
+ + cfg.z_nll_weight * parts["z_nll"]
1019
+ )
1020
+ metrics = {"loss": total.detach(), "rec": rec.detach(), **{k: v.detach() for k, v in parts.items()}}
1021
+ return total, metrics
1022
+
1023
+
1024
+ def plot_spectra_batch(path: str | Path, batch: dict[str, torch.Tensor], y_pred: np.ndarray, max_items: int = 4) -> None:
1025
+ path = Path(path)
1026
+ path.parent.mkdir(parents=True, exist_ok=True)
1027
+ x = batch["x"].detach().cpu().numpy()
1028
+ loglam = batch["loglam"].detach().cpu().numpy()
1029
+ valid = batch["valid"].detach().cpu().numpy()
1030
+ z = batch["z"].detach().cpu().numpy()
1031
+ bsz = min(max_items, x.shape[0])
1032
+ fig, axes = plt.subplots(bsz, 1, figsize=(13, 3.0 * bsz), squeeze=False)
1033
+ for i in range(bsz):
1034
+ ax = axes[i, 0]
1035
+ wave = np.exp(loglam[i])
1036
+ good = valid[i].astype(bool)
1037
+ ax.plot(wave[good], x[i, 0, good], color="black", linewidth=0.8, label="input flux")
1038
+ ax.plot(wave[good], x[i, 6, good], color="#1f77b4", linewidth=0.6, alpha=0.55, label="line score")
1039
+ masked = x[i, 7] > 0
1040
+ if masked.any():
1041
+ ax.scatter(wave[masked], np.zeros(masked.sum()), s=5, color="#d62728", alpha=0.55, label="redshift dropout")
1042
+ ax.set_title(f"z true={z[i]:.5f} z pred={np.expm1(y_pred[i]):.5f}")
1043
+ ax.set_ylabel("normalized")
1044
+ ax.grid(alpha=0.2)
1045
+ if i == 0:
1046
+ ax.legend(loc="best", fontsize=8)
1047
+ axes[-1, 0].set_xlabel("wavelength Angstrom")
1048
+ fig.tight_layout()
1049
+ fig.savefig(path, dpi=150)
1050
+ plt.close(fig)
1051
+
1052
+
1053
+ def add_redshift_slice_metrics(metrics: dict[str, float], prefix: str, y_true: np.ndarray, y_pred: np.ndarray) -> None:
1054
+ z_true = np.expm1(y_true)
1055
+ z_pred = np.expm1(y_pred)
1056
+ slices = {
1057
+ "z_lt_0p4": z_true < 0.4,
1058
+ "z_0p4_1p0": (z_true >= 0.4) & (z_true < 1.0),
1059
+ "z_1p0_2p0": (z_true >= 1.0) & (z_true < 2.0),
1060
+ "z_gte_2p0": z_true >= 2.0,
1061
+ }
1062
+ for name, mask in slices.items():
1063
+ count = int(np.count_nonzero(mask))
1064
+ metrics[f"{prefix}/{name}_count"] = float(count)
1065
+ if count >= 5:
1066
+ err = z_pred[mask] - z_true[mask]
1067
+ denom = 1.0 + z_true[mask]
1068
+ metrics[f"{prefix}/{name}_mae_z"] = float(np.mean(np.abs(err)))
1069
+ metrics[f"{prefix}/{name}_bias_z"] = float(np.mean(err))
1070
+ metrics[f"{prefix}/{name}_cat_0p05"] = float(np.mean(np.abs(err / denom) > 0.05))
1071
+
1072
+
1073
+ def add_candidate_metrics(
1074
+ metrics: dict[str, float],
1075
+ prefix: str,
1076
+ y_true: np.ndarray,
1077
+ candidate_y: np.ndarray,
1078
+ candidate_bins: np.ndarray | None,
1079
+ *,
1080
+ z_bins: int,
1081
+ y_min: float,
1082
+ y_max: float,
1083
+ ) -> None:
1084
+ if candidate_y.size == 0:
1085
+ return
1086
+ z_true = np.expm1(y_true)
1087
+ z_candidate = np.expm1(candidate_y)
1088
+ abs_dz = np.abs(z_candidate - z_true[:, None])
1089
+ norm_dz = abs_dz / (1.0 + z_true[:, None])
1090
+ top_limits = [1, 3, 5]
1091
+ for k in top_limits:
1092
+ kk = min(k, candidate_y.shape[1])
1093
+ best_abs = np.min(abs_dz[:, :kk], axis=1)
1094
+ best_norm = np.min(norm_dz[:, :kk], axis=1)
1095
+ metrics[f"{prefix}/candidate_top{kk}_best_mae_z"] = float(np.mean(best_abs))
1096
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p003"] = float(np.mean(best_norm <= 0.003))
1097
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p01"] = float(np.mean(best_norm <= 0.01))
1098
+ metrics[f"{prefix}/candidate_top{kk}_hit_0p05"] = float(np.mean(best_norm <= 0.05))
1099
+ if candidate_bins is not None and candidate_bins.size:
1100
+ scaled = (y_true - y_min) / max(y_max - y_min, 1e-6)
1101
+ true_bins = np.clip((scaled * z_bins).astype(np.int64), 0, z_bins - 1)
1102
+ for k in top_limits:
1103
+ kk = min(k, candidate_bins.shape[1])
1104
+ metrics[f"{prefix}/candidate_top{kk}_bin_hit"] = float(np.mean(np.any(candidate_bins[:, :kk] == true_bins[:, None], axis=1)))
1105
+
1106
+
1107
+ @torch.no_grad()
1108
+ def evaluate(
1109
+ model: HybridSpecZ,
1110
+ loader: DataLoader,
1111
+ loss_cfg: LossConfig,
1112
+ device: torch.device,
1113
+ run_dir: Path,
1114
+ step: int,
1115
+ prefix: str = "val",
1116
+ max_batches: int | None = 50,
1117
+ max_examples: int | None = None,
1118
+ ) -> dict[str, float]:
1119
+ model.eval()
1120
+ losses: dict[str, list[float]] = {}
1121
+ y_true_all: list[np.ndarray] = []
1122
+ y_pred_all: list[np.ndarray] = []
1123
+ candidate_y_all: list[np.ndarray] = []
1124
+ candidate_bins_all: list[np.ndarray] = []
1125
+ y_true_clean: list[np.ndarray] = []
1126
+ y_pred_clean: list[np.ndarray] = []
1127
+ candidate_y_clean: list[np.ndarray] = []
1128
+ candidate_bins_clean: list[np.ndarray] = []
1129
+ zwarn_all: list[np.ndarray] = []
1130
+ first_batch = None
1131
+ first_pred = None
1132
+ first_rec = None
1133
+ seen_examples = 0
1134
+ for bi, batch in enumerate(loader):
1135
+ if max_batches is not None and max_batches > 0 and bi >= max_batches:
1136
+ break
1137
+ batch = limit_batch_examples(batch, max_examples, seen_examples)
1138
+ if batch is None:
1139
+ break
1140
+ seen_examples += int(batch["y"].shape[0])
1141
+ batch = move_to_device(batch, device)
1142
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
1143
+ out = model(batch["x"], batch["valid"], batch["loglam"])
1144
+ _, parts = redshift_total_loss(model, out, batch, loss_cfg)
1145
+ y_pred = out.get("y_pred", out["y_mu"])
1146
+ for k, v in parts.items():
1147
+ losses.setdefault(k, []).append(float(v.detach().cpu()))
1148
+ if "rec" in out and "target_flux" in batch and "loss_mask" in batch:
1149
+ rec_err = F.smooth_l1_loss(out["rec"].float(), batch["target_flux"].float(), reduction="none", beta=0.5)
1150
+ loss_mask = batch["loss_mask"].bool()
1151
+ line_region = batch.get("line_region")
1152
+ if line_region is not None:
1153
+ line_mask = loss_mask & line_region.bool()
1154
+ cont_mask = loss_mask & (~line_region.bool())
1155
+ for name, mask in (("rec_line", line_mask), ("rec_continuum", cont_mask)):
1156
+ denom = mask.float().sum()
1157
+ if float(denom.detach().cpu()) > 0:
1158
+ losses.setdefault(name, []).append(float(((rec_err * mask.float()).sum() / denom.clamp_min(1.0)).detach().cpu()))
1159
+ context_mask = batch["valid"].bool() & (~loss_mask)
1160
+ denom = context_mask.float().sum(dim=1).clamp_min(1.0)
1161
+ baseline = (batch["target_flux"].float() * context_mask.float()).sum(dim=1, keepdim=True) / denom.unsqueeze(1)
1162
+ baseline_err = F.smooth_l1_loss(baseline.expand_as(batch["target_flux"]).float(), batch["target_flux"].float(), reduction="none", beta=0.5)
1163
+ mask_denom = loss_mask.float().sum().clamp_min(1.0)
1164
+ losses.setdefault("rec_mean_baseline", []).append(float(((baseline_err * loss_mask.float()).sum() / mask_denom).detach().cpu()))
1165
+ finite = torch.isfinite(batch["y"]).detach().cpu().numpy()
1166
+ clean = ((~batch["zwarn"].bool()) & torch.isfinite(batch["y"])).detach().cpu().numpy()
1167
+ zw = batch["zwarn"].detach().cpu().numpy().astype(bool)
1168
+ if finite.any():
1169
+ y_true_all.append(batch["y"].detach().cpu().numpy()[finite])
1170
+ y_pred_all.append(y_pred.float().detach().cpu().numpy()[finite])
1171
+ zwarn_all.append(zw[finite])
1172
+ if "candidate_topk_y" in out:
1173
+ candidate_y_all.append(out["candidate_topk_y"].float().detach().cpu().numpy()[finite])
1174
+ if "candidate_topk_bins" in out:
1175
+ candidate_bins_all.append(out["candidate_topk_bins"].detach().cpu().numpy()[finite])
1176
+ if clean.any():
1177
+ y_true_clean.append(batch["y"].detach().cpu().numpy()[clean])
1178
+ y_pred_clean.append(y_pred.float().detach().cpu().numpy()[clean])
1179
+ if "candidate_topk_y" in out:
1180
+ candidate_y_clean.append(out["candidate_topk_y"].float().detach().cpu().numpy()[clean])
1181
+ if "candidate_topk_bins" in out:
1182
+ candidate_bins_clean.append(out["candidate_topk_bins"].detach().cpu().numpy()[clean])
1183
+ if first_batch is None:
1184
+ first_batch = {k: v.detach().cpu() if torch.is_tensor(v) else v for k, v in batch.items()}
1185
+ first_pred = y_pred.float().detach().cpu().numpy()
1186
+ if "rec" in out:
1187
+ first_rec = out["rec"].float().detach().cpu().numpy()
1188
+
1189
+ metrics = {f"{prefix}/{k}": float(np.mean(v)) for k, v in losses.items()}
1190
+ if y_true_all:
1191
+ y_true = np.concatenate(y_true_all)
1192
+ y_pred = np.concatenate(y_pred_all)
1193
+ for k, v in redshift_metrics(y_true, y_pred).items():
1194
+ metrics[f"{prefix}/{k}"] = v
1195
+ add_redshift_slice_metrics(metrics, prefix, y_true, y_pred)
1196
+ if candidate_y_all:
1197
+ candidate_y_np = np.concatenate(candidate_y_all)
1198
+ candidate_bins_np = np.concatenate(candidate_bins_all) if candidate_bins_all else None
1199
+ add_candidate_metrics(
1200
+ metrics,
1201
+ prefix,
1202
+ y_true,
1203
+ candidate_y_np,
1204
+ candidate_bins_np,
1205
+ z_bins=model.z_bins,
1206
+ y_min=model.y_min,
1207
+ y_max=model.y_max,
1208
+ )
1209
+ metrics[f"{prefix}/z_count"] = float(len(y_true))
1210
+ metrics[f"{prefix}/zwarn_fraction"] = float(np.mean(np.concatenate(zwarn_all))) if zwarn_all else 0.0
1211
+ plot_redshift_scatter(run_dir / "plots" / f"{prefix}_redshift_step_{step:06d}.png", y_true, y_pred)
1212
+ if y_true_clean:
1213
+ clean_true = np.concatenate(y_true_clean)
1214
+ clean_pred = np.concatenate(y_pred_clean)
1215
+ if len(clean_true) >= 5:
1216
+ for k, v in redshift_metrics(clean_true, clean_pred).items():
1217
+ metrics[f"{prefix}_clean/{k}"] = v
1218
+ if candidate_y_clean:
1219
+ candidate_y_clean_np = np.concatenate(candidate_y_clean)
1220
+ candidate_bins_clean_np = np.concatenate(candidate_bins_clean) if candidate_bins_clean else None
1221
+ add_candidate_metrics(
1222
+ metrics,
1223
+ f"{prefix}_clean",
1224
+ clean_true,
1225
+ candidate_y_clean_np,
1226
+ candidate_bins_clean_np,
1227
+ z_bins=model.z_bins,
1228
+ y_min=model.y_min,
1229
+ y_max=model.y_max,
1230
+ )
1231
+ metrics[f"{prefix}_clean/z_count"] = float(len(clean_true))
1232
+ if first_batch is not None and first_pred is not None:
1233
+ if first_rec is not None and "target_flux" in first_batch and "loss_mask" in first_batch:
1234
+ plot_reconstruction_batch(
1235
+ run_dir / "plots" / f"{prefix}_reconstruction_step_{step:06d}.png",
1236
+ first_batch["loglam"].numpy(),
1237
+ first_batch["target_flux"].numpy(),
1238
+ first_rec,
1239
+ first_batch["loss_mask"].numpy(),
1240
+ first_batch["valid"].numpy(),
1241
+ first_batch["z"].numpy(),
1242
+ np.expm1(first_pred),
1243
+ )
1244
+ plot_spectra_batch(run_dir / "plots" / f"{prefix}_spectra_step_{step:06d}.png", first_batch, first_pred)
1245
+ model.train()
1246
+ return metrics
1247
+
1248
+
1249
+ def make_loader(
1250
+ samples: list[dict[str, Any]],
1251
+ indices: np.ndarray,
1252
+ cfg: RawCollatorConfig,
1253
+ args: argparse.Namespace,
1254
+ train: bool,
1255
+ sampler: WeightedRandomSampler | None = None,
1256
+ ) -> DataLoader:
1257
+ return DataLoader(
1258
+ SpectraListDataset(samples, indices),
1259
+ batch_size=args.batch_size,
1260
+ shuffle=train and sampler is None,
1261
+ sampler=sampler,
1262
+ num_workers=args.num_workers,
1263
+ pin_memory=True,
1264
+ collate_fn=RawSpectraCollator(cfg, train=train, seed=args.seed + (0 if train else 1000)),
1265
+ )
1266
+
1267
+
1268
+ def checkpoint_score(
1269
+ mode: str,
1270
+ val_metrics: dict[str, float],
1271
+ ood_metrics: dict[str, float] | None,
1272
+ z_alpha: float = 0.6,
1273
+ desi_mae_ceiling: float = 0.0,
1274
+ desi_mae_penalty: float = 0.0,
1275
+ ) -> float:
1276
+ def score_prefix(metrics: dict[str, float], prefix: str) -> float:
1277
+ z_score = (
1278
+ metrics.get(f"{prefix}/nmad", math.inf)
1279
+ + metrics.get(f"{prefix}/cat_0p01", 1.0)
1280
+ + metrics.get(f"{prefix}/mae_log1p", 1.0)
1281
+ )
1282
+ rec_score = metrics.get(f"{prefix}/rec")
1283
+ if rec_score is None or not math.isfinite(float(rec_score)):
1284
+ return z_score
1285
+ alpha = min(max(float(z_alpha), 0.0), 1.0)
1286
+ return alpha * z_score + (1.0 - alpha) * float(rec_score)
1287
+
1288
+ val_score = score_prefix(val_metrics, "val")
1289
+ if mode == "rec":
1290
+ return float(val_metrics.get("val/rec", math.inf))
1291
+ if mode == "val" or ood_metrics is None:
1292
+ score = val_score
1293
+ if desi_mae_ceiling > 0 and desi_mae_penalty > 0:
1294
+ val_mae = float(val_metrics.get("val/mae_z", 0.0))
1295
+ score += float(desi_mae_penalty) * max(0.0, val_mae - float(desi_mae_ceiling))
1296
+ return score
1297
+ ood_score = score_prefix(ood_metrics, "ood")
1298
+ if mode == "ood":
1299
+ score = ood_score
1300
+ else:
1301
+ score = 0.5 * val_score + 0.5 * ood_score
1302
+ if desi_mae_ceiling > 0 and desi_mae_penalty > 0:
1303
+ val_mae = float(val_metrics.get("val/mae_z", 0.0))
1304
+ score += float(desi_mae_penalty) * max(0.0, val_mae - float(desi_mae_ceiling))
1305
+ return score
1306
+
1307
+
1308
+ def scheduled_lr(base_lr: float, min_lr: float, step: int, total_steps: int, warmup_steps: int) -> float:
1309
+ if warmup_steps > 0 and step <= warmup_steps:
1310
+ return base_lr * float(step) / float(max(1, warmup_steps))
1311
+ if min_lr < 0 or total_steps <= warmup_steps:
1312
+ return base_lr
1313
+ progress = (step - warmup_steps) / float(max(1, total_steps - warmup_steps))
1314
+ progress = min(max(progress, 0.0), 1.0)
1315
+ return min_lr + 0.5 * (base_lr - min_lr) * (1.0 + math.cos(math.pi * progress))
1316
+
1317
+
1318
+ def main() -> None:
1319
+ parser = argparse.ArgumentParser()
1320
+ parser.add_argument("--dataset-name", default="MultimodalUniverse/desi")
1321
+ parser.add_argument("--max-samples", type=int, default=4096)
1322
+ parser.add_argument("--cache-dir", default="/workspace/native_specz_mae/cache")
1323
+ parser.add_argument("--hf-cache-dir", default=os.environ.get("HF_DATASETS_CACHE", "/workspace/hf_cache/datasets"))
1324
+ parser.add_argument("--run-dir", default="/workspace/runs/hybrid_specz")
1325
+ parser.add_argument("--resume-checkpoint", default="")
1326
+ parser.add_argument("--allow-mismatched-checkpoint", action="store_true")
1327
+ parser.add_argument("--refresh-data", action="store_true")
1328
+ parser.add_argument("--epochs", type=int, default=8)
1329
+ parser.add_argument("--batch-size", type=int, default=64)
1330
+ parser.add_argument("--num-workers", type=int, default=2)
1331
+ parser.add_argument("--target-length", type=int, default=4096)
1332
+ parser.add_argument("--architecture", choices=["conv", "wave_token"], default="conv")
1333
+ parser.add_argument("--d-model", type=int, default=256)
1334
+ parser.add_argument("--conv-width", type=int, default=128)
1335
+ parser.add_argument("--layers", type=int, default=5)
1336
+ parser.add_argument("--heads", type=int, default=8)
1337
+ parser.add_argument("--dropout", type=float, default=0.1)
1338
+ parser.add_argument("--z-bins", type=int, default=64)
1339
+ parser.add_argument("--stem-stride", type=int, choices=[4, 8], default=8)
1340
+ parser.add_argument("--token-stride", type=int, default=8)
1341
+ parser.add_argument("--rec-hidden-mult", type=int, default=0)
1342
+ parser.add_argument("--rec-refine-width", type=int, default=16)
1343
+ parser.add_argument("--rec-refine-kernel", type=int, default=5)
1344
+ parser.add_argument("--layerscale-init", type=float, default=0.0)
1345
+ parser.add_argument(
1346
+ "--prediction-mode",
1347
+ choices=[
1348
+ "regression",
1349
+ "softbin",
1350
+ "hybrid",
1351
+ "bin_residual",
1352
+ "ranked_bin_residual",
1353
+ "candidate_rerank",
1354
+ "calibrated_bin_residual",
1355
+ ],
1356
+ default="regression",
1357
+ )
1358
+ parser.add_argument("--bin-temperature", type=float, default=1.0)
1359
+ parser.add_argument("--residual-scale", type=float, default=0.06)
1360
+ parser.add_argument("--candidate-topk", type=int, default=5)
1361
+ parser.add_argument("--lr", type=float, default=2e-4)
1362
+ parser.add_argument("--min-lr", type=float, default=-1.0)
1363
+ parser.add_argument("--warmup-steps", type=int, default=0)
1364
+ parser.add_argument("--weight-decay", type=float, default=0.03)
1365
+ parser.add_argument("--grad-clip", type=float, default=1.0)
1366
+ parser.add_argument("--grad-accum-steps", type=int, default=1)
1367
+ parser.add_argument("--eval-every", type=int, default=100)
1368
+ parser.add_argument("--eval-max-val", type=int, default=800)
1369
+ parser.add_argument("--eval-max-ood", type=int, default=480)
1370
+ parser.add_argument("--max-steps", type=int, default=0)
1371
+ parser.add_argument("--checkpoint-score", choices=["val", "ood", "combined", "rec"], default="combined")
1372
+ parser.add_argument("--score-z-alpha", type=float, default=0.6)
1373
+ parser.add_argument("--desi-mae-ceiling", type=float, default=0.0)
1374
+ parser.add_argument("--desi-mae-penalty", type=float, default=0.0)
1375
+ parser.add_argument("--objective", choices=["joint", "rec_only", "z_only"], default="joint")
1376
+ parser.add_argument("--freeze-mode", choices=["none", "adapter", "rerank", "calib"], default="none")
1377
+ parser.add_argument("--train-top-layers", type=int, default=0)
1378
+ parser.add_argument("--train-layernorms", action="store_true")
1379
+ parser.add_argument("--replay-checkpoint", default="")
1380
+ parser.add_argument("--replay-y-weight", type=float, default=0.0)
1381
+ parser.add_argument("--replay-bin-weight", type=float, default=0.0)
1382
+ parser.add_argument("--replay-clean-only", action="store_true")
1383
+ parser.add_argument("--balance-redshift", action="store_true")
1384
+ parser.add_argument("--train-clean-only", action="store_true")
1385
+ parser.add_argument("--clean-sample-boost", type=float, default=1.0)
1386
+ parser.add_argument("--augment-ood", action="store_true")
1387
+ parser.add_argument("--eval-ood", action="store_true")
1388
+ parser.add_argument("--random-mask-ratio", type=float, default=0.0)
1389
+ parser.add_argument("--eval-mask-ratio", type=float, default=0.25)
1390
+ parser.add_argument("--mask-mode", choices=["pixel", "span", "line_span", "mixed_span"], default="pixel")
1391
+ parser.add_argument("--mask-span-min", type=int, default=16)
1392
+ parser.add_argument("--mask-span-max", type=int, default=64)
1393
+ parser.add_argument("--line-region-percentile", type=float, default=90.0)
1394
+ parser.add_argument("--crop-prob", type=float, default=0.0)
1395
+ parser.add_argument("--bad-window-prob", type=float, default=0.0)
1396
+ parser.add_argument("--throughput-prob", type=float, default=0.0)
1397
+ parser.add_argument("--noise-prob", type=float, default=0.0)
1398
+ parser.add_argument("--resolution-prob", type=float, default=0.0)
1399
+ parser.add_argument("--downsample-prob", type=float, default=0.0)
1400
+ parser.add_argument("--line-dropout-prob", type=float, default=0.0)
1401
+ parser.add_argument("--span-dropout-prob", type=float, default=0.0)
1402
+ parser.add_argument("--grid-jitter-prob", type=float, default=0.0)
1403
+ parser.add_argument("--grid-shift-frac", type=float, default=0.0)
1404
+ parser.add_argument("--grid-scale-frac", type=float, default=0.0)
1405
+ parser.add_argument("--grid-jitter-warmup-steps", type=int, default=0)
1406
+ parser.add_argument("--redshift-shift", type=float, default=0.0)
1407
+ parser.add_argument("--rec-weight", type=float, default=0.0)
1408
+ parser.add_argument("--z-weight", type=float, default=1.0)
1409
+ parser.add_argument("--z-bin-weight", type=float, default=0.25)
1410
+ parser.add_argument("--z-candidate-weight", type=float, default=0.0)
1411
+ parser.add_argument("--z-rerank-weight", type=float, default=0.0)
1412
+ parser.add_argument("--z-nll-weight", type=float, default=0.05)
1413
+ parser.add_argument("--zwarn-weight", type=float, default=0.3)
1414
+ parser.add_argument("--high-z-boost", type=float, default=1.0)
1415
+ parser.add_argument("--high-z-threshold", type=float, default=1.0)
1416
+ parser.add_argument("--clean-z-only", action="store_true")
1417
+ parser.add_argument("--seed", type=int, default=17)
1418
+ args = parser.parse_args()
1419
+
1420
+ torch.manual_seed(args.seed)
1421
+ np.random.seed(args.seed)
1422
+ run_dir = Path(args.run_dir) / time.strftime("%Y%m%d_%H%M%S")
1423
+ run_dir.mkdir(parents=True, exist_ok=True)
1424
+ (run_dir / "args.json").write_text(json.dumps(vars(args), indent=2), encoding="utf-8")
1425
+
1426
+ samples = collect_mmu_desi(
1427
+ cache_file=Path(args.cache_dir) / f"desi_{args.max_samples}.pt",
1428
+ max_samples=args.max_samples,
1429
+ dataset_name=args.dataset_name,
1430
+ hf_cache_dir=args.hf_cache_dir,
1431
+ refresh=args.refresh_data,
1432
+ )
1433
+ stats = compute_sample_stats(samples)
1434
+ (run_dir / "data_stats.json").write_text(json.dumps(stats.__dict__, indent=2), encoding="utf-8")
1435
+ print("DATA_STATS", json.dumps(stats.__dict__, sort_keys=True))
1436
+
1437
+ train_idx, val_idx = split_indices(len(samples), val_fraction=0.15, seed=args.seed)
1438
+ if args.train_clean_only:
1439
+ clean_train = np.asarray([not bool(samples[int(i)]["zwarn"]) for i in train_idx], dtype=np.bool_)
1440
+ train_idx = train_idx[clean_train]
1441
+ if len(train_idx) == 0:
1442
+ raise RuntimeError("No clean ZWARN==0 samples are available for --train-clean-only.")
1443
+ print(f"TRAIN_CLEAN_ONLY n_train={len(train_idx)}")
1444
+
1445
+ sampler = None
1446
+ if args.balance_redshift or args.clean_sample_boost != 1.0:
1447
+ weights = np.ones(len(train_idx), dtype=np.float32)
1448
+ y_train = np.asarray([np.log1p(float(samples[int(i)]["z"])) for i in train_idx], dtype=np.float32)
1449
+ if args.balance_redshift:
1450
+ bins = np.linspace(float(y_train.min()), float(y_train.max()) + 1e-6, 28)
1451
+ bin_id = np.clip(np.digitize(y_train, bins) - 1, 0, len(bins) - 2)
1452
+ counts = np.bincount(bin_id, minlength=len(bins) - 1).astype(np.float32)
1453
+ weights *= 1.0 / np.maximum(counts[bin_id], 1.0)
1454
+ if args.clean_sample_boost != 1.0:
1455
+ clean = np.asarray([not bool(samples[int(i)]["zwarn"]) for i in train_idx], dtype=np.bool_)
1456
+ weights *= np.where(clean, float(args.clean_sample_boost), 1.0).astype(np.float32)
1457
+ weights = weights / weights.mean()
1458
+ sampler = WeightedRandomSampler(torch.as_tensor(weights, dtype=torch.double), num_samples=len(weights), replacement=True)
1459
+
1460
+ train_cfg = RawCollatorConfig(
1461
+ target_length=args.target_length,
1462
+ random_mask_ratio=args.random_mask_ratio,
1463
+ eval_mask_ratio=args.eval_mask_ratio,
1464
+ mask_mode=args.mask_mode,
1465
+ mask_span_min=args.mask_span_min,
1466
+ mask_span_max=args.mask_span_max,
1467
+ line_region_percentile=args.line_region_percentile,
1468
+ augment_ood=args.augment_ood,
1469
+ crop_prob=args.crop_prob,
1470
+ bad_window_prob=args.bad_window_prob,
1471
+ throughput_prob=args.throughput_prob,
1472
+ noise_prob=args.noise_prob,
1473
+ resolution_prob=args.resolution_prob,
1474
+ downsample_prob=args.downsample_prob,
1475
+ line_dropout_prob=args.line_dropout_prob,
1476
+ span_dropout_prob=args.span_dropout_prob,
1477
+ grid_jitter_prob=args.grid_jitter_prob,
1478
+ grid_shift_frac=args.grid_shift_frac,
1479
+ grid_scale_frac=args.grid_scale_frac,
1480
+ grid_jitter_warmup_steps=args.grid_jitter_warmup_steps,
1481
+ redshift_shift=args.redshift_shift,
1482
+ )
1483
+ val_cfg = RawCollatorConfig(
1484
+ target_length=args.target_length,
1485
+ eval_mask_ratio=args.eval_mask_ratio,
1486
+ mask_mode=args.mask_mode,
1487
+ mask_span_min=args.mask_span_min,
1488
+ mask_span_max=args.mask_span_max,
1489
+ line_region_percentile=args.line_region_percentile,
1490
+ )
1491
+ ood_cfg = RawCollatorConfig(
1492
+ target_length=args.target_length,
1493
+ eval_mask_ratio=args.eval_mask_ratio,
1494
+ mask_mode=args.mask_mode,
1495
+ mask_span_min=args.mask_span_min,
1496
+ mask_span_max=args.mask_span_max,
1497
+ line_region_percentile=args.line_region_percentile,
1498
+ augment_ood=True,
1499
+ crop_prob=0.65,
1500
+ bad_window_prob=0.45,
1501
+ throughput_prob=0.65,
1502
+ noise_prob=0.35,
1503
+ resolution_prob=0.45,
1504
+ downsample_prob=0.35,
1505
+ grid_jitter_prob=0.65,
1506
+ grid_shift_frac=0.04,
1507
+ grid_scale_frac=0.08,
1508
+ )
1509
+ train_loader = make_loader(samples, train_idx, train_cfg, args, train=True, sampler=sampler)
1510
+ val_loader = make_loader(samples, val_idx, val_cfg, args, train=False)
1511
+ ood_loader = make_loader(samples, val_idx, ood_cfg, args, train=False) if args.eval_ood else None
1512
+
1513
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
1514
+ model_kwargs = dict(
1515
+ d_model=args.d_model,
1516
+ conv_width=args.conv_width,
1517
+ layers=args.layers,
1518
+ heads=args.heads,
1519
+ dropout=args.dropout,
1520
+ z_bins=args.z_bins,
1521
+ rec_hidden_mult=args.rec_hidden_mult,
1522
+ rec_refine_width=args.rec_refine_width,
1523
+ rec_refine_kernel=args.rec_refine_kernel,
1524
+ layerscale_init=args.layerscale_init,
1525
+ prediction_mode=args.prediction_mode,
1526
+ bin_temperature=args.bin_temperature,
1527
+ residual_scale=args.residual_scale,
1528
+ candidate_topk=args.candidate_topk,
1529
+ )
1530
+ if args.architecture == "wave_token":
1531
+ model = WavelengthTokenSpecZ(token_stride=args.token_stride, **model_kwargs).to(device)
1532
+ else:
1533
+ model = HybridSpecZ(stem_stride=args.stem_stride, **model_kwargs).to(device)
1534
+ if args.resume_checkpoint:
1535
+ ckpt = torch.load(args.resume_checkpoint, map_location=device, weights_only=False)
1536
+ state = ckpt["model"] if isinstance(ckpt, dict) and "model" in ckpt else ckpt
1537
+ load_checkpoint_into_model(model, state, allow_mismatched=args.allow_mismatched_checkpoint)
1538
+ print(f"RESUME_CHECKPOINT {args.resume_checkpoint}")
1539
+ n_params = sum(p.numel() for p in model.parameters())
1540
+ print(f"MODEL_PARAMS {n_params}")
1541
+
1542
+ teacher_model = None
1543
+ if args.replay_y_weight > 0 or args.replay_bin_weight > 0:
1544
+ replay_path = args.replay_checkpoint or args.resume_checkpoint
1545
+ if not replay_path:
1546
+ raise RuntimeError("--replay-checkpoint or --resume-checkpoint is required when replay weights are nonzero.")
1547
+ if args.architecture == "wave_token":
1548
+ teacher_model = WavelengthTokenSpecZ(token_stride=args.token_stride, **model_kwargs).to(device)
1549
+ else:
1550
+ teacher_model = HybridSpecZ(stem_stride=args.stem_stride, **model_kwargs).to(device)
1551
+ ckpt = torch.load(replay_path, map_location=device, weights_only=False)
1552
+ state = ckpt["model"] if isinstance(ckpt, dict) and "model" in ckpt else ckpt
1553
+ load_checkpoint_into_model(teacher_model, state, allow_mismatched=args.allow_mismatched_checkpoint)
1554
+ teacher_model.eval()
1555
+ for param in teacher_model.parameters():
1556
+ param.requires_grad = False
1557
+ print(f"REPLAY_TEACHER {replay_path}")
1558
+
1559
+ trainable_params = configure_trainable_parameters(model, args.freeze_mode, args.train_top_layers, args.train_layernorms)
1560
+ print(f"TRAINABLE_PARAMS {trainable_params} freeze_mode={args.freeze_mode} train_top_layers={args.train_top_layers}")
1561
+ opt_params = [p for p in model.parameters() if p.requires_grad]
1562
+ if not opt_params:
1563
+ raise RuntimeError("No trainable parameters remain after freeze configuration.")
1564
+ optimizer = AdamW(opt_params, lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95))
1565
+ rec_weight = args.rec_weight
1566
+ z_weight = args.z_weight
1567
+ z_bin_weight = args.z_bin_weight
1568
+ z_candidate_weight = args.z_candidate_weight
1569
+ z_rerank_weight = args.z_rerank_weight
1570
+ z_nll_weight = args.z_nll_weight
1571
+ if args.objective == "rec_only":
1572
+ rec_weight = rec_weight if rec_weight > 0 else 1.0
1573
+ z_weight = 0.0
1574
+ z_bin_weight = 0.0
1575
+ z_candidate_weight = 0.0
1576
+ z_rerank_weight = 0.0
1577
+ z_nll_weight = 0.0
1578
+ elif args.objective == "z_only":
1579
+ rec_weight = 0.0
1580
+
1581
+ loss_cfg = LossConfig(
1582
+ rec_weight=rec_weight,
1583
+ z_weight=z_weight,
1584
+ z_bin_weight=z_bin_weight,
1585
+ z_candidate_weight=z_candidate_weight,
1586
+ z_rerank_weight=z_rerank_weight,
1587
+ z_nll_weight=z_nll_weight,
1588
+ zwarn_weight=args.zwarn_weight,
1589
+ clean_z_only=args.clean_z_only,
1590
+ high_z_boost=args.high_z_boost,
1591
+ high_z_threshold=math.log1p(args.high_z_threshold),
1592
+ )
1593
+ best_score = math.inf
1594
+ global_step = 0
1595
+ micro_step = 0
1596
+ grad_accum_steps = max(1, int(args.grad_accum_steps))
1597
+ total_train_steps = args.max_steps if args.max_steps else int(math.ceil(len(train_loader) / grad_accum_steps) * args.epochs)
1598
+ model.train()
1599
+ optimizer.zero_grad(set_to_none=True)
1600
+ for epoch in range(args.epochs):
1601
+ pbar = tqdm(train_loader, desc=f"hybrid epoch {epoch}")
1602
+ for batch in pbar:
1603
+ micro_step += 1
1604
+ batch = move_to_device(batch, device)
1605
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
1606
+ out = model(batch["x"], batch["valid"], batch["loglam"])
1607
+ loss, parts = redshift_total_loss(model, out, batch, loss_cfg)
1608
+ if teacher_model is not None:
1609
+ with torch.no_grad():
1610
+ teacher_out = teacher_model(batch["x"], batch["valid"], batch["loglam"])
1611
+ replay, replay_parts = replay_loss(
1612
+ out,
1613
+ teacher_out,
1614
+ batch,
1615
+ y_weight=args.replay_y_weight,
1616
+ bin_weight=args.replay_bin_weight,
1617
+ clean_only=args.replay_clean_only,
1618
+ )
1619
+ loss = loss + replay
1620
+ parts = {**parts, "loss": parts["loss"] + replay.detach(), "replay": replay.detach(), **replay_parts}
1621
+ (loss / grad_accum_steps).backward()
1622
+ if micro_step % grad_accum_steps != 0:
1623
+ pbar.set_postfix(
1624
+ loss=float(parts["loss"].detach().cpu()),
1625
+ rec=float(parts["rec"].detach().cpu()),
1626
+ huber=float(parts["z_huber"].detach().cpu()),
1627
+ replay=float(parts.get("replay", parts["loss"].sum() * 0.0).detach().cpu()),
1628
+ accum=f"{micro_step % grad_accum_steps}/{grad_accum_steps}",
1629
+ )
1630
+ continue
1631
+ next_step = global_step + 1
1632
+ lr_now = scheduled_lr(args.lr, args.min_lr, next_step, total_train_steps, int(args.warmup_steps))
1633
+ for group in optimizer.param_groups:
1634
+ group["lr"] = lr_now
1635
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
1636
+ optimizer.step()
1637
+ optimizer.zero_grad(set_to_none=True)
1638
+ global_step = next_step
1639
+ pbar.set_postfix(
1640
+ loss=float(parts["loss"].detach().cpu()),
1641
+ rec=float(parts["rec"].detach().cpu()),
1642
+ huber=float(parts["z_huber"].detach().cpu()),
1643
+ replay=float(parts.get("replay", parts["loss"].sum() * 0.0).detach().cpu()),
1644
+ lr=lr_now,
1645
+ grad=float(grad_norm.detach().cpu()) if torch.is_tensor(grad_norm) else float(grad_norm),
1646
+ )
1647
+ if global_step == 1 or global_step % args.eval_every == 0:
1648
+ val_metrics = evaluate(
1649
+ model,
1650
+ val_loader,
1651
+ loss_cfg,
1652
+ device,
1653
+ run_dir,
1654
+ global_step,
1655
+ prefix="val",
1656
+ max_batches=None,
1657
+ max_examples=args.eval_max_val,
1658
+ )
1659
+ print("VAL", global_step, json.dumps(val_metrics, sort_keys=True))
1660
+ ood_metrics = None
1661
+ if ood_loader is not None:
1662
+ ood_metrics = evaluate(
1663
+ model,
1664
+ ood_loader,
1665
+ loss_cfg,
1666
+ device,
1667
+ run_dir,
1668
+ global_step,
1669
+ prefix="ood",
1670
+ max_batches=None,
1671
+ max_examples=args.eval_max_ood,
1672
+ )
1673
+ print("OOD", global_step, json.dumps(ood_metrics, sort_keys=True))
1674
+ score = checkpoint_score(
1675
+ args.checkpoint_score,
1676
+ val_metrics,
1677
+ ood_metrics,
1678
+ z_alpha=args.score_z_alpha,
1679
+ desi_mae_ceiling=args.desi_mae_ceiling,
1680
+ desi_mae_penalty=args.desi_mae_penalty,
1681
+ )
1682
+ if score < best_score:
1683
+ best_score = score
1684
+ best_metrics = {"step": global_step, "score": best_score, **val_metrics}
1685
+ if ood_metrics is not None:
1686
+ best_metrics.update(ood_metrics)
1687
+ torch.save(
1688
+ {"model": model.state_dict(), "args": vars(args), "step": global_step, "score": best_score, "metrics": best_metrics},
1689
+ run_dir / "best.pt",
1690
+ )
1691
+ (run_dir / "best_metrics.json").write_text(json.dumps(best_metrics, indent=2), encoding="utf-8")
1692
+ if args.max_steps and global_step >= args.max_steps:
1693
+ break
1694
+ if args.max_steps and global_step >= args.max_steps:
1695
+ break
1696
+
1697
+ final_metrics = evaluate(
1698
+ model,
1699
+ val_loader,
1700
+ loss_cfg,
1701
+ device,
1702
+ run_dir,
1703
+ global_step,
1704
+ prefix="val",
1705
+ max_batches=None,
1706
+ max_examples=args.eval_max_val,
1707
+ )
1708
+ if ood_loader is not None:
1709
+ final_metrics.update(
1710
+ evaluate(
1711
+ model,
1712
+ ood_loader,
1713
+ loss_cfg,
1714
+ device,
1715
+ run_dir,
1716
+ global_step,
1717
+ prefix="ood",
1718
+ max_batches=None,
1719
+ max_examples=args.eval_max_ood,
1720
+ )
1721
+ )
1722
+ torch.save({"model": model.state_dict(), "args": vars(args), "step": global_step, "metrics": final_metrics}, run_dir / "last.pt")
1723
+ (run_dir / "final_metrics.json").write_text(json.dumps(final_metrics, indent=2), encoding="utf-8")
1724
+ print("FINAL", json.dumps(final_metrics, sort_keys=True))
1725
+ print("RUN_DIR", run_dir)
1726
+
1727
+
1728
+ if __name__ == "__main__":
1729
+ main()