r"""dataset_v2.py — 4-group loader, GPU-RESIDENT. Big arrays live on GPU as float16 (indexing is GPU-native -> no CPU-index / per-window transfer stall). If they don't fit in VRAM, auto-fallback to CPU (RAM). Subgraph on the pruned training graph (structural holdout §5); 3-mode SSL masking (§1). Physics = raw wind_1330 + BLH.""" from __future__ import annotations import json, pathlib, numpy as np, torch class AtmosData: def __init__(self, tdir, window=7, device="cuda", gpu_resident=True): t=pathlib.Path(tdir); self.w=window; self.dev=device # try to place big arrays on GPU (f16); fallback to CPU on OOM store=device if (gpu_resident and device=="cuda" and torch.cuda.is_available()) else "cpu" def L(f, keepf16=True): a=torch.tensor(np.load(t/f)) if a.dtype==torch.float64: a=a.float() if keepf16 and a.dtype==torch.float32: a=a.half() # store f16 to save VRAM return a try: self.A=L("groupA.npy").to(store); self.B=L("groupB.npy").to(store) self.Cstat=L("groupC_static.npy").to(store); self.Cyear=L("groupC_yearly.npy").to(store) self.LUyear=torch.tensor(np.load(t/"groupC_landuse.npy")).long().to(store) self.yod=torch.tensor(np.load(t/"year_of_day.npy")).long().to(store) self.cal=L("calendar_num.npy").to(store); self.grap=torch.tensor(np.load(t/"grap.npy")).long().to(store) self.PH=L("physics.npy").to(store) self.comp=L("completeness.npy").to(store) self.Y=L("targets.npy").to(store); self.M=torch.tensor(np.load(t/"target_mask.npy")).float().to(store) ed=np.load(t/"edges.npz") self.ei=torch.tensor(ed["ei"]).long().to(store) self.e_hat=torch.tensor(ed["e_hat"]).float().to(store); self.n_hat=torch.tensor(ed["n_hat"]).float().to(store) self.split=torch.tensor(np.load(t/"node_split.npy")).long().to(store) self.store=store except torch.cuda.OutOfMemoryError: print("!! GPU too small for resident data -> falling back to CPU (RAM). Slower.") torch.cuda.empty_cache() return AtmosData.__init__(self, tdir, window, device, gpu_resident=False) self.D,self.N,_=self.A.shape print(f"data resident on: {store} (A{tuple(self.A.shape)} f16)") def target_days(self, fold=0): fn=(self.split==fold) has=((self.M.sum(-1)>0)&fn.unsqueeze(0)).sum(-1) return [t for t in range(self.w-1,self.D) if has[t]>0] def _groups(self, day, nodes): yi=int(self.yod[day]) static_num=torch.cat([self.Cstat[nodes], self.Cyear[yi][nodes]], -1).float() return {"satellite":self.A[day,nodes].float(), "meteorology":self.B[day,nodes].float(), "static_num":static_num, "landuse":self.LUyear[yi][nodes], "calendar_num":self.cal[day].unsqueeze(0).expand(len(nodes),-1).float(), "grap":self.grap[day].expand(len(nodes))} def subgraph(self, size=512, fold=0): cand=torch.where(self.split==fold)[0] nodes=cand[torch.randperm(len(cand),device=cand.device)[:size]] nset=torch.full((self.N,),-1,dtype=torch.long,device=self.store); nset[nodes]=torch.arange(len(nodes),device=self.store) src,dst=self.ei; keep=(nset[src]>=0)&(nset[dst]>=0) ei=torch.stack([nset[src[keep]],nset[dst[keep]]]).to(self.dev) return nodes, ei, self.e_hat[keep].to(self.dev), self.n_hat[keep].to(self.dev) A_FLAGMAP=[0,2,1,3,4,7,8] RECON_GROUP=["satellite"]*9+["meteorology"]*12+["static"]*9 def recon_from_groups(self, groups_t): """target+observed from already-loaded window groups (no re-index).""" T=len(groups_t) A=torch.stack([groups_t[t]["satellite"][:,:9] for t in range(T)],1) Bv=torch.stack([groups_t[t]["meteorology"] for t in range(T)],1) C=torch.stack([groups_t[t]["static_num"] for t in range(T)],1) target=torch.cat([A,Bv,C],-1) Aobs=torch.ones_like(A) for k,fl in enumerate(self.A_FLAGMAP): Aobs[:,:,k]=torch.stack([groups_t[t]["satellite"][:,9+fl] for t in range(T)],1) obs=torch.cat([Aobs,torch.ones_like(Bv),torch.ones_like(C)],-1) return target, obs def window(self, t, nodes, ei, e_hat, n_hat, horizons=4): days=range(t-self.w+1,t+1) groups_t=[{k:v.to(self.dev) for k,v in self._groups(d,nodes).items()} for d in days] wu=torch.stack([self.PH[d,nodes,0] for d in days]).float().to(self.dev) wv=torch.stack([self.PH[d,nodes,1] for d in days]).float().to(self.dev) blh=torch.stack([self.PH[d,nodes,2] for d in days]).float().to(self.dev) ys=[]; ms=[] for h in range(horizons): d2=t+h; valid=d2