File size: 12,815 Bytes
221683f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08e5029
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
r"""
model.py — AtmosIQ V1, faithful to MODEL_BLUEPRINT v1.1 + Architecture v1.1 FROZEN.

Custom modules: PhysicsBiasedGAT (ADR-014 Am.1 + ADR-019), LogStudentTHead (ADR-015).
No torch_scatter / PyG (pin 4b: hand-rolled segment softmax IS the spec).

Feature contract (F_total=54, four groups, NEVER merged pre-embed):
  A satellite 18 -> 32   B meteorology 12 -> 24   C static 13 -> 16   D calendar 11 -> 16
  fusion Linear(88 -> 96).  Per-group [MASK] tokens (SSL + cloud-blindness).
Encoder: spatial PhysicsBiasedGAT xL=2  BEFORE  temporal Transformer (T=7), last-step pool.
Head input = [N, 96+1] (window-completeness scalar). Output [N, horizons=4, P=7, 3].
SSL recon reads PRE-POOL [N,T,96] per timestep -> 29 continuous channels (discarded after pretrain).
"""
from __future__ import annotations
import torch, torch.nn as nn, torch.nn.functional as F

# ------------------------------------------------------------------ physics bias
def phys_log_bias(w_u1330, w_v1330, blh, src, e_hat, n_hat, eps=1e-4, f_min=0.05):
    """Architecture v1.5: g_ij = relu(w_i,1330 . u_hat_ij) * f(BLH), f in (f_min,1].
    sigma(lambda)=0 baseline -> returns log(g_ij + eps) exactly (ADR-014 Am.1)."""
    w_along = w_u1330[src]*e_hat + w_v1330[src]*n_hat                 # directed: e_ij != e_ji
    f = f_min + (1.0 - f_min)*torch.sigmoid((blh[src]-500.0)/500.0)   # strictly in (f_min,1]
    g = F.relu(w_along) * f
    return torch.log(g + eps)

# ------------------------------------------------------------- PhysicsBiasedGAT (BLUEPRINT §4 verbatim)
class PhysicsBiasedGAT(nn.Module):
    def __init__(self, d_model, n_heads):
        super().__init__()
        self.h, self.dh = n_heads, d_model // n_heads
        self.W = nn.Linear(d_model, d_model, bias=False)
        self.a_src = nn.Parameter(torch.empty(n_heads, self.dh))
        self.a_dst = nn.Parameter(torch.empty(n_heads, self.dh))
        self.self_bias = nn.Parameter(torch.zeros(n_heads))          # learned per-head self term
        self.out = nn.Linear(d_model, d_model)
        nn.init.xavier_uniform_(self.a_src); nn.init.xavier_uniform_(self.a_dst)

    def forward(self, x, edge_index, phys_log_bias, return_attn=False):
        N = x.size(0)
        Wx = self.W(x).view(N, self.h, self.dh)
        src, dst = edge_index[0], edge_index[1]
        e = (Wx[src]*self.a_src).sum(-1) + (Wx[dst]*self.a_dst).sum(-1)
        e = F.leaky_relu(e, 0.2) + phys_log_bias.unsqueeze(-1)       # [E,h]
        e_self = F.leaky_relu((Wx*self.a_src).sum(-1) + (Wx*self.a_dst).sum(-1), 0.2)
        e_self = e_self + self.self_bias                             # [N,h] learned self term
        m = e_self.clone()
        m = m.index_reduce_(0, dst, e, reduce="amax", include_self=True)
        ex = torch.exp(e - m[dst]); ex_self = torch.exp(e_self - m)
        denom = ex_self.clone(); denom.index_add_(0, dst, ex)
        alpha = ex / denom[dst]; alpha_self = ex_self / denom
        out = alpha_self.unsqueeze(-1) * Wx
        out.index_add_(0, dst, alpha.unsqueeze(-1) * Wx[src])
        out = self.out(out.reshape(N, self.h*self.dh))
        if return_attn:
            return out, {"alpha_self": alpha_self, "alpha_edge": alpha, "edge_index": edge_index}
        return out

# ------------------------------------------------------------- group assembly + [MASK]
class GroupAssembler(nn.Module):
    """Four sub-embedders + categorical embeddings (land_use->4, grap->3) -> fusion.
    Per-group learned [MASK] tokens (SSL + cloud-blindness)."""
    def __init__(self, dims, sub, cat, d_model):
        super().__init__()
        self.sub = sub
        self.emb_sat = nn.Linear(dims["satellite"], sub["satellite"])
        self.emb_met = nn.Linear(dims["meteorology"], sub["meteorology"])
        self.emb_static = nn.Linear(dims["static"], sub["static"])      # 13 = 9 numeric + 4 landuse-emb
        self.emb_cal = nn.Linear(dims["calendar"], sub["calendar"])     # 11 = 8 numeric + 3 grap-emb
        self.landuse = nn.Embedding(cat.get("n_landuse",11), cat.get("land_use_class",4))
        self.grap    = nn.Embedding(cat.get("n_grap",5),     cat.get("grap_stage",3))
        self.fusion  = nn.Linear(sum(sub.values()), d_model)
        self.mask_tok = nn.ParameterDict({g: nn.Parameter(torch.zeros(sub[g]))
                                          for g in ["satellite","meteorology","static","calendar"]})

    def forward(self, g, group_mask=None):
        """g keys: satellite[N,18], meteorology[N,12], static_num[N,9], landuse[N] long,
                   calendar_num[N,8], grap[N] long. group_mask: dict grp->[N] (1=mask)."""
        static = torch.cat([g["static_num"], self.landuse(g["landuse"])], -1)   # [N,13]
        cal    = torch.cat([g["calendar_num"], self.grap(g["grap"])], -1)       # [N,11]
        h = {"satellite": self.emb_sat(g["satellite"]), "meteorology": self.emb_met(g["meteorology"]),
             "static": self.emb_static(static), "calendar": self.emb_cal(cal)}
        if group_mask is not None:
            for grp in h:
                if grp in group_mask:
                    mk = group_mask[grp].unsqueeze(-1).float()
                    mk = mk.to(h[grp].device)
                    h[grp] = h[grp]*(1-mk) + self.mask_tok[grp].unsqueeze(0)*mk
        return self.fusion(torch.cat([h["satellite"],h["meteorology"],h["static"],h["calendar"]], -1))

# ------------------------------------------------------------- temporal
class TemporalEncoder(nn.Module):
    def __init__(self, d_model, n_heads, ff, layers, T=7):
        super().__init__()
        enc = nn.TransformerEncoderLayer(d_model, n_heads, ff, batch_first=True, dropout=0.1)
        self.tr = nn.TransformerEncoder(enc, layers)
        self.slot = nn.Parameter(torch.randn(1, T, d_model)*0.02)     # learned slot positions
    def forward(self, H):                                            # H:[N,T,d]
        return self.tr(H + self.slot[:, :H.size(1)])                 # returns [N,T,d] (pre-pool)

# ------------------------------------------------------------- heads
class LogStudentTHead(nn.Module):                                    # ADR-015
    def __init__(self, d_model, horizons=4, P=7):
        super().__init__()
        self.H, self.P = horizons, P
        self.trunk = nn.Linear(d_model+1, d_model)                   # +1 window-completeness scalar
        self.mu = nn.Linear(d_model, horizons*P)
        self.log_sigma = nn.Linear(d_model, horizons*P)
        self.log_nu = nn.Parameter(torch.zeros(P))                   # nu per pollutant
    def forward(self, z, completeness):
        h = F.gelu(self.trunk(torch.cat([z, completeness.unsqueeze(-1)], -1)))
        N = z.size(0)
        mu = self.mu(h).view(N, self.H, self.P)
        log_sigma = self.log_sigma(h).view(N, self.H, self.P).clamp(-7.0, 7.0)   # bound sigma in (~1e-3, ~1e3): kills backward blow-up
        nu = (F.softplus(self.log_nu) + 2.0).clamp(max=100.0)       # >2 finite variance, capped
        return mu, log_sigma, nu

class ReconHead(nn.Module):                                          # SSL, pre-pool per-timestep
    def __init__(self, d_model, n_cont=29):
        super().__init__(); self.lin = nn.Linear(d_model, n_cont)
    def forward(self, h_seq): return self.lin(h_seq)                # [N,T,29]

# ------------------------------------------------------------- full model
class AtmosIQNet(nn.Module):
    def __init__(self, cfg=None):
        super().__init__()
        cfg = cfg or {}
        d = cfg.get("d_model",96); heads = cfg.get("n_heads",4); ff = cfg.get("ff_dim",384)
        L = cfg.get("n_blocks_L",2); T = cfg.get("seq_len_T",7)
        cat  = cfg.get("categorical",        {"land_use_class":4,"grap_stage":3,"n_landuse":18,"n_grap":5})
        cal_num = cfg.get("calendar_num_dim", 16)                          # Group D numeric width (from meta.json)
        dims = cfg.get("feature_group_dims", {"satellite":18,"meteorology":12,"static":13,
                                              "calendar": cal_num + cat.get("grap_stage",3)})
        sub  = cfg.get("sub_embed_dims",     {"satellite":32,"meteorology":24,"static":16,"calendar":16})
        P = len(cfg.get("pollutants", ["pm2_5","pm10","no2","so2","co","o3","nh3"]))
        horizons = len(cfg.get("horizons",[0,1,2,3]))
        self.assemble = GroupAssembler(dims, sub, cat, d)
        self.gats = nn.ModuleList([PhysicsBiasedGAT(d, heads) for _ in range(L)])
        self.temporal = TemporalEncoder(d, heads, ff, L, T)
        self.head = LogStudentTHead(d, horizons, P)
        self.recon = ReconHead(d, n_cont=cfg.get("n_recon_channels",29))

    def encode(self, groups_t, ei, e_hat, n_hat, wu, wv, blh, group_mask_t=None):
        """Window encode. Spatial GAT is BATCHED across T timesteps (block-diagonal graph):
        T*N nodes, edges replicated + offset by t*N, physics bias per timestep. One GAT pass
        instead of a Python T-loop -> big GPU speedup. Timesteps stay disconnected."""
        T = len(groups_t); N = groups_t[0]["satellite"].shape[0]
        src, dst = ei[0], ei[1]; E = src.numel()
        # assemble each timestep (cheap Linears) -> [T*N, d]
        H = torch.cat([self.assemble(groups_t[t], None if group_mask_t is None else group_mask_t[t])
                       for t in range(T)], 0)                        # [T*N, d]
        # replicate edges for each timestep, offset by t*N
        offs = (torch.arange(T, device=src.device)*N).view(T,1)
        src_b = (src.unsqueeze(0)+offs).reshape(-1); dst_b = (dst.unsqueeze(0)+offs).reshape(-1)
        ei_b = torch.stack([src_b, dst_b])                          # [2, T*E]
        # physics bias per timestep (cheap) -> [T*E]
        lb = torch.cat([phys_log_bias(wu[t], wv[t], blh[t], src, e_hat, n_hat) for t in range(T)])
        for gat in self.gats: H = gat(H, ei_b, lb)                  # ONE batched spatial pass per layer
        H = H.view(T, N, -1).permute(1,0,2)                         # [N,T,d]
        return self.temporal(H)                                    # [N,T,d] pre-pool

    def forward(self, groups_t, ei, e_hat, n_hat, wu, wv, blh, completeness, group_mask_t=None):
        h_seq = self.encode(groups_t, ei, e_hat, n_hat, wu, wv, blh, group_mask_t)
        z = h_seq[:, -1]                                            # last-step pooling (pinned)
        mu, log_sigma, nu = self.head(z, completeness)
        return dict(mu=mu, log_sigma=log_sigma, nu=nu, h_seq=h_seq)

# ------------------------------------------------------------- losses
def student_t_nll(mu, log_sigma, nu, y, mask, y_logmean=None, y_logstd=None, y_eps=1e-3):
    """log-Student-t NLL on PER-POLLUTANT STANDARDIZED log(y+eps). mu is in standardized log space."""
    import math
    yl = torch.log(y.clamp_min(0) + y_eps)
    if y_logmean is not None:
        yl = (yl - y_logmean.view(1,1,-1)) / y_logstd.view(1,1,-1)   # standardize per pollutant
    sigma = F.softplus(log_sigma) + 1e-3                       # log_sigma already clamped in head
    nu = nu.clamp(2.05, 100.0).view(1,1,-1)
    z = ((yl - mu) / sigma).clamp(-1e3, 1e3)
    nll = (torch.lgamma(nu/2) - torch.lgamma((nu+1)/2) + 0.5*torch.log(nu*math.pi)
           + torch.log(sigma) + (nu+1)/2*torch.log1p((z*z/nu).clamp(max=1e6)))
    nll = torch.nan_to_num(nll, nan=0.0, posinf=1e4, neginf=0.0)  # last-resort guard
    return (nll*mask).sum()/mask.sum().clamp_min(1)

def ssl_recon_loss(recon, target, masked_and_observed):
    """SSL_ROADMAP §2: MSE over {masked AND originally-observed} standardized channels."""
    d = (recon - target)**2 * masked_and_observed
    return d.sum()/masked_and_observed.sum().clamp_min(1)

if __name__ == "__main__":
    torch.manual_seed(0)
    net = AtmosIQNet()
    n = sum(p.numel() for p in net.parameters())
    print(f"AtmosIQNet params: {n:,}  (blueprint target ~287k)")
    N, E, T = 600, 4000, 7
    groups_t = [{"satellite":torch.randn(N,18),"meteorology":torch.randn(N,12),
                 "static_num":torch.randn(N,9),"landuse":torch.randint(0,11,(N,)),
                 "calendar_num":torch.randn(N,16),"grap":torch.randint(0,5,(N,))} for _ in range(T)]
    ei = torch.randint(0,N,(2,E)); e_hat=torch.randn(E); n_hat=torch.randn(E)
    wu=torch.randn(T,N); wv=torch.randn(T,N); blh=torch.rand(T,N)*1000; comp=torch.rand(N)
    out = net(groups_t, ei, e_hat, n_hat, wu, wv, blh, comp)
    print("forward OK. mu", tuple(out["mu"].shape), "nu", tuple(out["nu"].shape), "h_seq", tuple(out["h_seq"].shape))
    y = torch.rand(N,4,7)*100; m=(torch.rand(N,4,7)>0.5).float()
    nll = student_t_nll(out["mu"], out["log_sigma"], out["nu"], y, m)
    rec = net.recon(out["h_seq"]); tgt=torch.randn(N,T,29); mo=(torch.rand(N,T,29)>0.7).float()
    ssl = ssl_recon_loss(rec, tgt, mo)
    (nll+0.5*ssl).backward()
    print(f"nll={nll.item():.3f} ssl={ssl.item():.3f} — backward OK")