ManmohanSharma commited on
Commit
cdc206b
·
verified ·
1 Parent(s): 5b207c6

Upload code/metrics.py

Browse files
Files changed (1) hide show
  1. code/metrics.py +108 -0
code/metrics.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn.functional as F
9
+
10
+
11
+ @dataclass
12
+ class LossConfig:
13
+ rec_weight: float = 1.0
14
+ z_weight: float = 2.0
15
+ z_bin_weight: float = 0.2
16
+ z_candidate_weight: float = 0.0
17
+ z_rerank_weight: float = 0.0
18
+ z_nll_weight: float = 0.05
19
+ line_weight_power: float = 1.0
20
+ clean_z_only: bool = False
21
+ zwarn_weight: float = 0.3
22
+ high_z_boost: float = 1.0
23
+ high_z_threshold: float = math.log1p(1.0)
24
+
25
+
26
+ def masked_huber(pred: torch.Tensor, target: torch.Tensor, mask: torch.Tensor, weight: torch.Tensor | None = None) -> torch.Tensor:
27
+ loss = F.smooth_l1_loss(pred, target, reduction="none", beta=0.5)
28
+ m = mask.float()
29
+ if weight is not None:
30
+ loss = loss * weight.float()
31
+ denom = m.sum().clamp_min(1.0)
32
+ return (loss * m).sum() / denom
33
+
34
+
35
+ def redshift_losses(model, out: dict[str, torch.Tensor], y: torch.Tensor, zwarn: torch.Tensor, cfg: LossConfig) -> dict[str, torch.Tensor]:
36
+ clean = (~zwarn.bool()) & torch.isfinite(y) if cfg.clean_z_only else torch.isfinite(y)
37
+ y_pred_all = out.get("y_pred", out["y_mu"])
38
+ if clean.sum() == 0:
39
+ zero = y_pred_all.sum() * 0.0
40
+ return {"z_huber": zero, "z_bin": zero, "z_candidate": zero, "z_rerank": zero, "z_nll": zero}
41
+ y_mu = y_pred_all[clean]
42
+ y_true = y[clean]
43
+ y_logvar = out["y_logvar"][clean]
44
+ sample_weight = torch.where(zwarn[clean].bool(), torch.full_like(y_true, cfg.zwarn_weight), torch.ones_like(y_true))
45
+ if cfg.high_z_boost != 1.0:
46
+ high_z_weight = torch.where(
47
+ y_true >= cfg.high_z_threshold,
48
+ torch.full_like(y_true, cfg.high_z_boost),
49
+ torch.ones_like(y_true),
50
+ )
51
+ sample_weight = sample_weight * high_z_weight
52
+ huber = F.smooth_l1_loss(y_mu, y_true, beta=0.01, reduction="none")
53
+ z_huber = (huber * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
54
+ bins = model.y_to_bin(y_true)
55
+ z_bin_each = F.cross_entropy(out["z_bin_logits"][clean], bins, reduction="none")
56
+ z_bin = (z_bin_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
57
+ if "candidate_y" in out:
58
+ candidate_y = out["candidate_y"][clean]
59
+ true_candidate_y = candidate_y.gather(1, bins.unsqueeze(1)).squeeze(1)
60
+ z_candidate_each = F.smooth_l1_loss(true_candidate_y, y_true, beta=0.01, reduction="none")
61
+ z_candidate = (z_candidate_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
62
+ else:
63
+ z_candidate = y_mu.sum() * 0.0
64
+ if "rerank_logits" in out and "candidate_topk_y" in out:
65
+ candidate_topk_y = out["candidate_topk_y"][clean]
66
+ target_rank = torch.abs(candidate_topk_y - y_true.unsqueeze(1)).argmin(dim=1)
67
+ z_rerank_each = F.cross_entropy(out["rerank_logits"][clean], target_rank, reduction="none")
68
+ z_rerank = (z_rerank_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
69
+ else:
70
+ z_rerank = y_mu.sum() * 0.0
71
+ z_nll_each = 0.5 * (torch.exp(-y_logvar) * (y_mu - y_true).pow(2) + y_logvar)
72
+ z_nll = (z_nll_each * sample_weight).sum() / sample_weight.sum().clamp_min(1.0)
73
+ return {"z_huber": z_huber, "z_bin": z_bin, "z_candidate": z_candidate, "z_rerank": z_rerank, "z_nll": z_nll}
74
+
75
+
76
+ def total_loss(model, out: dict[str, torch.Tensor], batch: dict[str, torch.Tensor], cfg: LossConfig) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
77
+ line_weight = batch["line_weight"].pow(cfg.line_weight_power)
78
+ rec = masked_huber(out["rec"], batch["target_flux"], batch["loss_mask"], weight=line_weight)
79
+ z_parts = redshift_losses(model, out, batch["y"], batch["zwarn"], cfg)
80
+ total = (
81
+ cfg.rec_weight * rec
82
+ + cfg.z_weight * z_parts["z_huber"]
83
+ + cfg.z_bin_weight * z_parts["z_bin"]
84
+ + cfg.z_candidate_weight * z_parts["z_candidate"]
85
+ + cfg.z_rerank_weight * z_parts["z_rerank"]
86
+ + cfg.z_nll_weight * z_parts["z_nll"]
87
+ )
88
+ metrics = {"loss": total.detach(), "rec": rec.detach(), **{k: v.detach() for k, v in z_parts.items()}}
89
+ return total, metrics
90
+
91
+
92
+ def redshift_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
93
+ z_true = np.expm1(y_true)
94
+ z_pred = np.expm1(y_pred)
95
+ dz_norm = (z_pred - z_true) / (1.0 + z_true)
96
+ med = np.nanmedian(dz_norm)
97
+ nmad = 1.4826 * np.nanmedian(np.abs(dz_norm - med))
98
+ return {
99
+ "mae_z": float(np.nanmean(np.abs(z_pred - z_true))),
100
+ "mae_log1p": float(np.nanmean(np.abs(y_pred - y_true))),
101
+ "rmse_z": float(math.sqrt(np.nanmean((z_pred - z_true) ** 2))),
102
+ "nmad": float(nmad),
103
+ "cat_0p003": float(np.nanmean(np.abs(dz_norm) > 0.003)),
104
+ "cat_0p01": float(np.nanmean(np.abs(dz_norm) > 0.01)),
105
+ "cat_0p05": float(np.nanmean(np.abs(dz_norm) > 0.05)),
106
+ "pred_std_z": float(np.nanstd(z_pred)),
107
+ "true_std_z": float(np.nanstd(z_true)),
108
+ }