Tonic's picture
Protostar Climate submission: v2 forecast + v3/DCPP amendment audit (29 gated candidates)
49f3de8 verified
Raw History Blame Contribute Delete
9.12 kB
"""OlmoEarth-2018: OlmoEarth-architecture encoder, random init, <=2018 data only.
Architecture follows the OlmoEarth pattern (patch tokenisation across space,
time and modality band-sets; ViT encoder; pooled token embedding) at Nano
scale (dim 128, depth 4), reimplemented in plain PyTorch so that no released
weights -- and no code path that downloads them -- are involved. The random
initialisation seed is logged; every learned parameter comes from Sentinel-2
scenes dated <= 2018-12-31 (see eo_fetch.py manifest) and challenge labels
<= 2018.
Task: multi-task regression of the four annual metrics for a city-year from
its 4 quarterly Sentinel-2 timesteps. The pooled 128-d embedding is then used
as a static city descriptor and put through the pre-registered gate
(eo_gate.py) before it may touch any forecast.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
sys.path.insert(0, str(Path(__file__).parent))
from dataset import METRIC_COLUMNS, download, load_annual, add_validity, load_coverage
SEED = 20181231
DIM, DEPTH, HEADS, PATCH = 128, 4, 4, 8
N_BANDS, N_TIMESTEPS, SIZE = 12, 4, 64
class OlmoEarthNanoScratch(nn.Module):
"""Patch tokens per timestep -> transformer -> pooled embedding + head."""
def __init__(self, n_targets: int = 4):
super().__init__()
self.patch_embed = nn.Conv2d(N_BANDS, DIM, kernel_size=PATCH, stride=PATCH)
n_tokens = (SIZE // PATCH) ** 2
self.spatial_pos = nn.Parameter(torch.zeros(1, n_tokens, DIM))
self.time_embed = nn.Parameter(torch.zeros(1, N_TIMESTEPS, 1, DIM))
layer = nn.TransformerEncoderLayer(
d_model=DIM, nhead=HEADS, dim_feedforward=DIM * 4,
dropout=0.1, batch_first=True, norm_first=True)
self.encoder = nn.TransformerEncoder(layer, num_layers=DEPTH)
self.norm = nn.LayerNorm(DIM)
self.head = nn.Sequential(nn.Linear(DIM, 64), nn.GELU(), nn.Linear(64, n_targets))
nn.init.trunc_normal_(self.spatial_pos, std=0.02)
nn.init.trunc_normal_(self.time_embed, std=0.02)
def embed(self, x: torch.Tensor) -> torch.Tensor:
"""x: (B,T,C,H,W) -> pooled embedding (B,DIM)."""
b, t, c, h, w = x.shape
tok = self.patch_embed(x.reshape(b * t, c, h, w)) # (B*T,D,8,8)
tok = tok.flatten(2).transpose(1, 2).reshape(b, t, -1, tok.shape[1])
tok = tok + self.spatial_pos.unsqueeze(1) + self.time_embed
tok = tok.reshape(b, t * tok.shape[2], -1)
out = self.norm(self.encoder(tok))
return out.mean(dim=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.head(self.embed(x))
def load_samples(eo_dir: Path, annual: pd.DataFrame, years: list[int]):
samples = []
lookup = {(r.ID, int(r.Year)): r for r in annual.itertuples()}
for path in sorted(eo_dir.glob("s2_*_*.npz")):
city, year = path.stem[3:].rsplit("_", 1)
year = int(year)
if year not in years:
continue
row = lookup.get((city, year))
if row is None:
continue
targets, valid = [], True
for metric, col in METRIC_COLUMNS.items():
v = getattr(row, col.replace(" ", "_")) if hasattr(row, col.replace(" ", "_")) else row._asdict().get(col)
targets.append(np.nan if v is None else float(v))
data = np.load(path)["data"] # (T,C,H,W)
if data.shape != (N_TIMESTEPS, N_BANDS, SIZE, SIZE):
continue
samples.append({"city_id": city, "year": year,
"x": data, "y": np.array(targets, dtype=np.float32)})
return samples
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--eo-dir", default="data/eo")
ap.add_argument("--epochs", type=int, default=60)
ap.add_argument("--out", default="outputs/eo")
args = ap.parse_args()
torch.manual_seed(SEED)
np.random.seed(SEED)
root = Path(__file__).resolve().parent.parent
eo_dir = root / args.eo_dir
data_root = download(root / "data" / "_source")
annual = add_validity(load_annual(data_root), load_coverage(data_root))
# Column names with spaces are awkward in itertuples; rename for lookup.
annual = annual.rename(columns={"Avg Temp": "AvgTemp", "ToT Prcp": "ToTPrcp",
"Max Tmax": "MaxTmax"})
col_map = {"annual_avg_temp": "AvgTemp", "total_precip_in": "ToTPrcp",
"hottest_day_temp": "MaxTmax", "cdd": "cdd"}
samples = []
for path in sorted(eo_dir.glob("s2_*_*.npz")):
city, year_s = path.stem[3:].rsplit("_", 1)
year = int(year_s)
sel = annual[(annual["ID"] == city) & (annual["Year"] == year)]
if sel.empty:
continue
r = sel.iloc[0]
y = np.array([r[col_map[m]] for m in METRIC_COLUMNS], dtype=np.float32)
if not np.isfinite(y).all():
continue
samples.append({"city_id": city, "year": year,
"x": np.load(path)["data"], "y": y})
print(f"samples: {len(samples)} city-years "
f"({len(set(s['city_id'] for s in samples))} cities)")
if len(samples) < 40:
raise SystemExit("too few EO samples; run eo_fetch.py first")
y_all = np.stack([s["y"] for s in samples])
y_mean, y_std = y_all.mean(0), y_all.std(0) + 1e-6
cities = sorted(set(s["city_id"] for s in samples))
rng = np.random.default_rng(SEED)
rng.shuffle(cities)
val_cities = set(cities[: max(5, len(cities) // 5)])
train = [s for s in samples if s["city_id"] not in val_cities]
val = [s for s in samples if s["city_id"] in val_cities]
print(f"train {len(train)} / val(city-held-out) {len(val)}")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = OlmoEarthNanoScratch().to(device)
init_hash = hash(tuple(model.patch_embed.weight.detach().cpu().numpy().ravel()[:8]))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.05)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=args.epochs)
def batch(split):
xs = torch.tensor(np.stack([s["x"] for s in split]), device=device)
ys = torch.tensor((np.stack([s["y"] for s in split]) - y_mean) / y_std,
device=device)
return xs, ys
vx, vy = batch(val)
best = float("inf")
out_dir = root / args.out
out_dir.mkdir(parents=True, exist_ok=True)
for epoch in range(args.epochs):
model.train()
order = rng.permutation(len(train))
losses = []
for i in range(0, len(order), 16):
idx = order[i:i + 16]
xs = torch.tensor(np.stack([train[j]["x"] for j in idx]), device=device)
ys = torch.tensor((np.stack([train[j]["y"] for j in idx]) - y_mean) / y_std,
device=device)
if rng.random() < 0.5:
xs = xs.flip(-1)
if rng.random() < 0.5:
xs = xs.flip(-2)
opt.zero_grad()
loss = nn.functional.smooth_l1_loss(model(xs), ys)
loss.backward()
opt.step()
losses.append(float(loss))
sched.step()
model.eval()
with torch.no_grad():
vloss = float(nn.functional.smooth_l1_loss(model(vx), vy))
best = min(best, vloss)
if epoch % 10 == 0 or epoch == args.epochs - 1:
print(f"epoch {epoch}: train {np.mean(losses):.4f} val {vloss:.4f}")
# Extract static city embeddings (mean over years) with the trained encoder.
model.eval()
emb_rows = []
with torch.no_grad():
for s in samples:
x = torch.tensor(s["x"][None], device=device)
emb_rows.append({"city_id": s["city_id"], "year": s["year"],
**{f"emb_{i}": float(v) for i, v in
enumerate(model.embed(x).cpu().numpy()[0])}})
emb = pd.DataFrame(emb_rows)
emb.to_csv(out_dir / "embeddings_by_year.csv", index=False)
static = emb.groupby("city_id").mean(numeric_only=True).reset_index()
static = static.drop(columns=["year"])
static.to_csv(out_dir / "city_embeddings.csv", index=False)
(out_dir / "train_log.json").write_text(json.dumps({
"seed": SEED, "init_weight_fingerprint": init_hash,
"n_samples": len(samples), "n_cities": len(cities),
"best_val_smoothl1_standardised": best,
"y_mean": y_mean.tolist(), "y_std": y_std.tolist(),
"device": str(device),
"note": "random init; no released OlmoEarth weights used anywhere",
}, indent=2))
torch.save(model.state_dict(), out_dir / "olmoearth2018_encoder.pt")
print(f"wrote embeddings for {len(static)} cities; best val loss {best:.4f}")
if __name__ == "__main__":
main()