AtmosIQ commited on
Commit
019d2c0
·
verified ·
1 Parent(s): a535ffc

Upload scripts/model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/model.py +130 -0
scripts/model.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ model.py — AtmosIQ spatio-temporal air-quality model (~287k params).
3
+
4
+ X[T,N,D] --enc--> per-day PhysicsBiasedGAT(spatial) --> TemporalTransformer(time)
5
+ --> log-Student-t heads (7 pollutants) + SSL masked-reconstruction head
6
+
7
+ PhysicsBiasedGAT (ADR-014 / Amendment 1): attention logits get an ADDITIVE
8
+ log-space physics bias log(g_ij + eps), g_ij = relu(wind_i . edge_unit) * f(BLH_i).
9
+ That is A_ij = softmax(attn_ij + log(g_ij+eps)); eps is the calm-day diffusion floor.
10
+ Edges are DIRECTED (g_ij != g_ji); barrier edges are simply absent (M_ij structural).
11
+
12
+ Trains on GPU (Vast.ai). Uncertainty = Student-t (loc, log_scale, log_df) per pollutant.
13
+ """
14
+ from __future__ import annotations
15
+ import math
16
+ import torch, torch.nn as nn, torch.nn.functional as F
17
+
18
+ # ---------- physics bias (per timestep, from wind + edge geometry) ----------
19
+ def physics_log_bias(wind_u, wind_v, blh, src, e_hat, n_hat, eps=1e-3):
20
+ """g_ij = relu(wind_src . edge_unit) * f(BLH_src); returned in log space."""
21
+ w_along = wind_u[src] * e_hat + wind_v[src] * n_hat # advective component [E]
22
+ f_blh = torch.sigmoid((blh[src] - 500.0) / 500.0) # more mixing with deeper BLH
23
+ g = F.relu(w_along) * (0.5 + f_blh) # >=0
24
+ return torch.log(g + eps) # log-space (Amendment 1)
25
+
26
+ def segment_softmax(scores, index, N):
27
+ """softmax of edge scores grouped by destination node. scores:[E,H] index:[E]."""
28
+ m = scores.new_full((N, scores.shape[1]), float("-inf"))
29
+ m = m.index_reduce(0, index, scores, "amax", include_self=True)
30
+ scores = scores - m[index]
31
+ e = scores.exp()
32
+ denom = e.new_zeros((N, e.shape[1])).index_add(0, index, e) + 1e-16
33
+ return e / denom[index]
34
+
35
+ # ---------- Physics-biased GAT layer ----------
36
+ class PhysicsBiasedGAT(nn.Module):
37
+ def __init__(self, dim, heads=4):
38
+ super().__init__()
39
+ assert dim % heads == 0
40
+ self.h, self.dh = heads, dim // heads
41
+ self.q = nn.Linear(dim, dim); self.k = nn.Linear(dim, dim); self.v = nn.Linear(dim, dim)
42
+ self.out = nn.Linear(dim, dim); self.norm = nn.LayerNorm(dim)
43
+
44
+ def forward(self, x, ei, log_bias):
45
+ N = x.shape[0]; src, dst = ei
46
+ q = self.q(x).view(N, self.h, self.dh); k = self.k(x).view(N, self.h, self.dh)
47
+ v = self.v(x).view(N, self.h, self.dh)
48
+ score = (q[dst] * k[src]).sum(-1) / math.sqrt(self.dh) # [E,H]
49
+ score = score + log_bias.unsqueeze(-1) # + physics (log-space)
50
+ alpha = segment_softmax(score, dst, N) # [E,H]
51
+ msg = alpha.unsqueeze(-1) * v[src] # [E,H,dh]
52
+ agg = msg.new_zeros((N, self.h, self.dh)).index_add(0, dst, msg).view(N, -1)
53
+ return self.norm(x + self.out(agg)) # residual + norm
54
+
55
+ # ---------- Temporal transformer (over T days per node) ----------
56
+ class TemporalTransformer(nn.Module):
57
+ def __init__(self, dim, heads=4, ff=256, layers=2):
58
+ super().__init__()
59
+ enc = nn.TransformerEncoderLayer(dim, heads, ff, batch_first=True, dropout=0.1)
60
+ self.tr = nn.TransformerEncoder(enc, layers)
61
+ self.pos = nn.Parameter(torch.randn(1, 64, dim) * 0.02) # up to 64 timesteps
62
+
63
+ def forward(self, H): # H:[T,N,dim]
64
+ T, N, D = H.shape
65
+ h = H.permute(1, 0, 2) + self.pos[:, :T] # [N,T,dim]
66
+ h = self.tr(h)
67
+ return h[:, -1] # target day -> [N,dim]
68
+
69
+ # ---------- full model ----------
70
+ class AtmosIQNet(nn.Module):
71
+ def __init__(self, d_in, hidden=96, gat_layers=2, heads=4, temporal_layers=2, pollutants=7):
72
+ super().__init__()
73
+ self.P = pollutants
74
+ self.enc = nn.Sequential(nn.Linear(d_in, hidden), nn.GELU(), nn.LayerNorm(hidden))
75
+ self.gats = nn.ModuleList([PhysicsBiasedGAT(hidden, heads) for _ in range(gat_layers)])
76
+ self.temporal = TemporalTransformer(hidden, heads, ff=256, layers=temporal_layers)
77
+ # log-Student-t: (loc, log_scale, log_df) per pollutant
78
+ self.head = nn.Linear(hidden, pollutants * 3)
79
+ self.ssl = nn.Linear(hidden, d_in) # masked-reconstruction head
80
+
81
+ def forward(self, X, ei, e_hat, n_hat, wind_u, wind_v, blh):
82
+ """X:[T,N,D]; ei:[2,E]; e_hat/n_hat:[E]; wind_u/v,blh:[T,N]."""
83
+ T = X.shape[0]; src, dst = ei
84
+ Hs = []
85
+ for t in range(T):
86
+ h = self.enc(X[t])
87
+ lb = physics_log_bias(wind_u[t], wind_v[t], blh[t], src, e_hat, n_hat)
88
+ for gat in self.gats:
89
+ h = gat(h, ei, lb)
90
+ Hs.append(h)
91
+ z = self.temporal(torch.stack(Hs)) # [N,hidden]
92
+ p = self.head(z).view(-1, self.P, 3)
93
+ loc, log_scale, log_df = p[..., 0], p[..., 1], p[..., 2]
94
+ recon = self.ssl(z)
95
+ return dict(loc=loc, log_scale=log_scale, log_df=log_df, recon=recon, emb=z)
96
+
97
+ # ---------- losses ----------
98
+ def student_t_nll(loc, log_scale, log_df, y, mask):
99
+ """Negative log-likelihood of a Student-t; mask=1 where y observed."""
100
+ scale = F.softplus(log_scale) + 1e-3
101
+ df = F.softplus(log_df) + 2.0 # df>2 -> finite variance
102
+ z = (y - loc) / scale
103
+ nll = (torch.lgamma(df/2) - torch.lgamma((df+1)/2) + 0.5*torch.log(df*math.pi)
104
+ + torch.log(scale) + (df+1)/2 * torch.log1p(z**2/df))
105
+ return (nll * mask).sum() / mask.sum().clamp_min(1)
106
+
107
+ def ssl_masked_mse(recon, target, feat_mask):
108
+ """MSE only over masked-out input features (masked reconstruction SSL)."""
109
+ d = (recon - target)**2 * feat_mask
110
+ return d.sum() / feat_mask.sum().clamp_min(1)
111
+
112
+ if __name__ == "__main__":
113
+ torch.manual_seed(0)
114
+ D_in, N, T, E = 37, 500, 7, 3000
115
+ net = AtmosIQNet(D_in)
116
+ n_params = sum(p.numel() for p in net.parameters())
117
+ print(f"AtmosIQNet params: {n_params:,}")
118
+ X = torch.randn(T, N, D_in)
119
+ ei = torch.randint(0, N, (2, E))
120
+ e_hat = torch.randn(E); n_hat = torch.randn(E)
121
+ wu = torch.randn(T, N); wv = torch.randn(T, N); blh = torch.rand(T, N)*1000
122
+ out = net(X, ei, e_hat, n_hat, wu, wv, blh)
123
+ print("forward OK. loc:", tuple(out["loc"].shape), "recon:", tuple(out["recon"].shape))
124
+ y = torch.randn(N, 7); m = (torch.rand(N, 7) > 0.5).float()
125
+ nll = student_t_nll(out["loc"], out["log_scale"], out["log_df"], y, m)
126
+ fm = (torch.rand(N, D_in) > 0.7).float()
127
+ ssl = ssl_masked_mse(out["recon"], X[-1], fm)
128
+ loss = nll + 0.5*ssl
129
+ loss.backward()
130
+ print(f"loss={loss.item():.3f} (nll={nll.item():.3f}, ssl={ssl.item():.3f}) — backward OK")