""" Shared EA-LSTM + attribution utilities for the EcoMemory project. The architecture follows Kratzert et al. (2019) and the official gpp-interpretive-dl implementation (corecode/ealstm.py), with three changes needed for cell-level monthly analysis: * monthly instead of weekly sequence (60 months = 5 years, same as NG's 260 weeks) * static features are standardised cell attributes (crop/forest/aridity) * target is GPP normalised by the cell mean, i.e. a dimensionless productivity index, so that cross-cell differences do not dominate the loss """ from __future__ import annotations import numpy as np import torch import torch.nn as nn class EALSTM(nn.Module): """Entity-aware LSTM: the input gate is a function of static attributes.""" def __init__(self, input_size_dyn, input_size_stat, hidden_size, initial_forget_bias=0): super().__init__() self.input_size_dyn = input_size_dyn self.input_size_stat = input_size_stat self.hidden_size = hidden_size self.weight_ih = nn.Parameter(torch.empty(input_size_dyn, 3 * hidden_size)) self.weight_hh = nn.Parameter(torch.empty(hidden_size, 3 * hidden_size)) self.weight_sh = nn.Parameter(torch.empty(input_size_stat, hidden_size)) self.bias = nn.Parameter(torch.empty(3 * hidden_size)) self.bias_s = nn.Parameter(torch.empty(hidden_size)) self.reset_parameters(initial_forget_bias) def reset_parameters(self, initial_forget_bias=0): nn.init.orthogonal_(self.weight_ih.data) nn.init.orthogonal_(self.weight_sh.data) self.weight_hh.data = torch.eye(self.hidden_size).repeat(1, 3) nn.init.constant_(self.bias.data, 0) nn.init.constant_(self.bias_s.data, 0) if initial_forget_bias: self.bias.data[:self.hidden_size] = initial_forget_bias def forward(self, x_d, x_s): # x_d: (batch, seq, dyn) ; x_s: (batch, stat) x_d = x_d.transpose(0, 1) seq_len, batch_size, _ = x_d.size() h = x_d.new_zeros(batch_size, self.hidden_size) c = x_d.new_zeros(batch_size, self.hidden_size) bias_batch = self.bias.unsqueeze(0).expand(batch_size, -1) bias_s_batch = self.bias_s.unsqueeze(0).expand(batch_size, -1) i = torch.sigmoid(torch.addmm(bias_s_batch, x_s, self.weight_sh)) hs = [] for t in range(seq_len): gates = (torch.addmm(bias_batch, h, self.weight_hh) + torch.mm(x_d[t], self.weight_ih)) f, o, g = gates.chunk(3, 1) c = torch.sigmoid(f) * c + i * torch.tanh(g) h = torch.sigmoid(o) * torch.tanh(c) hs.append(h) return torch.stack(hs, 0).transpose(0, 1) class GPPModel(nn.Module): def __init__(self, n_dyn, n_stat, hidden=48, dropout=0.3): super().__init__() self.lstm = EALSTM(n_dyn, n_stat, hidden) self.drop = nn.Dropout(dropout) self.head = nn.Sequential( nn.Linear(hidden, 16), nn.BatchNorm1d(16), nn.ReLU(), nn.Linear(16, 1)) def forward(self, x_d, x_s): h = self.lstm(x_d, x_s) return self.head(self.drop(h[:, -1, :])).squeeze(-1) # -------------------------------------------------------------------------- # sample construction # -------------------------------------------------------------------------- def build_windows(dyn, y, months, seq=60): """Return (x, ys, idx_cell, idx_time) for every valid window.""" n_cell, nt, n_dyn = dyn.shape t0 = seq - 1 xs, ys, ci, ti = [], [], [], [] for c in range(n_cell): d = dyn[c] yy = y[c] for t in range(t0, nt): if not np.isfinite(yy[t]): continue w = d[t - seq + 1:t + 1] if not np.isfinite(w).all(): continue xs.append(w.astype(np.float32)) ys.append(yy[t]) ci.append(c) ti.append(t) return (np.stack(xs), np.asarray(ys, dtype=np.float32), np.asarray(ci, dtype=np.int32), np.asarray(ti, dtype=np.int32)) def standardise(dyn, static, y, tr_mask): """Standardise dynamic/static features using training windows only.""" mu_d = np.nanmean(dyn[tr_mask], axis=(0, 1), keepdims=True) sd_d = np.nanstd(dyn[tr_mask], axis=(0, 1), keepdims=True) sd_d[sd_d == 0] = 1 mu_s = np.nanmean(static, axis=0, keepdims=True) sd_s = np.nanstd(static, axis=0, keepdims=True) sd_s[sd_s == 0] = 1 return (dyn - mu_d) / sd_d, (static - mu_s) / sd_s, mu_d[0, 0], sd_d[0, 0] # -------------------------------------------------------------------------- # training # -------------------------------------------------------------------------- def train_model(x_tr, s_tr, y_tr, x_va, s_va, y_va, n_stat, hidden=48, epochs=60, batch=1024, lr=1e-3, patience=8, device="cpu", seed=0, verbose=True, ckpt_path=None): torch.manual_seed(seed) np.random.seed(seed) model = GPPModel(x_tr.shape[-1], n_stat, hidden).to(device) opt = torch.optim.Adam(model.parameters(), lr=lr) sched = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, factor=0.5, patience=3) lossf = nn.MSELoss() xt = torch.from_numpy(x_tr) st = torch.from_numpy(s_tr) yt = torch.from_numpy(y_tr) xv = torch.from_numpy(x_va).to(device) sv = torch.from_numpy(s_va).to(device) yv = torch.from_numpy(y_va).to(device) n = len(xt) best = (np.inf, None) bad = 0 hist = [] for ep in range(1, epochs + 1): model.train() perm = torch.randperm(n) tot = 0.0 for i in range(0, n, batch): idx = perm[i:i + batch] if len(idx) < 8: continue xb = xt[idx].to(device) sb = st[idx].to(device) yb = yt[idx].to(device) opt.zero_grad() loss = lossf(model(xb, sb), yb) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step() tot += loss.item() * len(idx) model.eval() with torch.no_grad(): vpred = model(xv, sv) vloss = lossf(vpred, yv).item() vnse = 1 - ((vpred - yv) ** 2).sum().item() / ((yv - yv.mean()) ** 2).sum().item() sched.step(vloss) hist.append((ep, tot / n, vloss, vnse)) if verbose: print(f" epoch {ep:3d} train {tot/n:.4f} val {vloss:.4f} NSE {vnse:.3f}", flush=True) if vloss < best[0] - 1e-5: best = (vloss, {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}) if ckpt_path is not None: torch.save({"state": best[1], "epoch": ep, "val_loss": vloss, "n_stat": n_stat, "n_dyn": x_tr.shape[-1], "hidden": hidden}, ckpt_path) bad = 0 else: bad += 1 if bad >= patience: print(f" early stop at epoch {ep}", flush=True) break model.load_state_dict(best[1]) return model, hist # -------------------------------------------------------------------------- # integrated gradients (manual, so it works for any window length) # -------------------------------------------------------------------------- def integrated_gradients(model, x, s, baseline, n_steps=32, batch=256, device="cpu"): """IG for a model with two inputs; only the dynamic input has a baseline. Returns array (n, seq, n_dyn) of attributions, and the convergence delta. """ model.eval() x = np.asarray(x, dtype=np.float32) baseline = np.asarray(baseline, dtype=np.float32) assert x.shape == baseline.shape n = len(x) out = np.zeros_like(x) delta = np.zeros(n, dtype=np.float32) for i in range(0, n, batch): xb = x[i:i + batch] bb = baseline[i:i + batch] sb = s[i:i + batch] diff = xb - bb acc = np.zeros_like(xb) for k in range(1, n_steps + 1): alpha = k / n_steps xi = torch.from_numpy(bb + alpha * diff).to(device).requires_grad_(True) st = torch.from_numpy(sb).to(device) y = model(xi, st).sum() g, = torch.autograd.grad(y, xi) acc += g.detach().cpu().numpy() att = diff * acc / n_steps out[i:i + batch] = att with torch.no_grad(): y1 = model(torch.from_numpy(xb).to(device), torch.from_numpy(sb).to(device)) y0 = model(torch.from_numpy(bb).to(device), torch.from_numpy(sb).to(device)) delta[i:i + batch] = (y1 - y0).cpu().numpy() - att.sum(axis=(1, 2)) return out, delta def memory_metrics(attr, n_current=4): """Summarise lag-resolved attributions. attr : (n, seq, n_dyn), lags counted backwards from the last time step. Returns dict of per-sample arrays. """ seq = attr.shape[1] a = np.abs(attr) total = a.sum(axis=(1, 2)) ant = a[:, :seq - n_current, :].sum(axis=(1, 2)) cur = a[:, seq - n_current:, :].sum(axis=(1, 2)) with np.errstate(invalid="ignore", divide="ignore"): share = ant / total # lag at which cumulative absolute attribution reaches 50 % cum = np.cumsum(a[:, ::-1, :].sum(axis=2), axis=1) cum = cum / np.maximum(cum[:, -1:], 1e-12) half = np.argmax(cum >= 0.5, axis=1) return {"total": total, "antecedent": ant, "current": cur, "mem_share": share, "half_lag": half} def lag_profile(attr, n_bins=12): """Mean |attribution| by lag (0 = current month), binned 2 months.""" a = np.abs(attr).sum(axis=2).mean(axis=0) # (seq,) a = a[::-1] # lag 0 first a = a / a.sum() k = len(a) // n_bins return a[:k * n_bins].reshape(n_bins, k).mean(axis=1)