TSRDA / PAPER /tools /paper_analysis.py
Dhruv1000's picture
PAPER: results, logs and README refreshed (2026-11-10 05:52 UTC)
dd7826b verified
Raw History Blame Contribute Delete
16.4 kB
"""Extra measurements and figures for the manuscript. Everything here is computed from code and
result files; nothing is typed. Outputs go to PAPER/results/*.json and PAPER/figures/*.
python3 tools/paper_analysis.py bench # temporal-block efficiency + parameter counts (JSON)
python3 tools/paper_analysis.py figs # all figures that need no GPU
python3 tools/paper_analysis.py qual # qualitative MTLCC prediction maps (needs the GPU, a few GB)
"""
import os, sys, json, glob, time
from pathlib import Path
import numpy as np
PAPER = Path(__file__).resolve().parents[1]
RES, FIG = PAPER / "results", PAPER / "figures"
RES.mkdir(exist_ok=True); FIG.mkdir(exist_ok=True)
M = Path("/home/ubuntu/pro/TSRDA_MTLCC")
B = Path("/home/ubuntu/pro/baselines")
os.environ.setdefault("EXP_ROOT", str(M / "runs"))
sys.path.insert(0, str(M / "code"))
BLUE, ORANGE, GRAY, LGRAY, INK, INK2, GRID = "#2a78d6", "#eb6834", "#9a9893", "#d6d5d0", "#0b0b0b", "#52514e", "#e4e3df"
def mpl():
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family": "DejaVu Serif", "font.size": 8, "axes.edgecolor": INK2, "axes.linewidth": 0.6,
"axes.spines.top": False, "axes.spines.right": False, "xtick.color": INK2, "ytick.color": INK2,
"axes.labelcolor": INK, "figure.dpi": 150, "savefig.dpi": 300, "savefig.bbox": "tight",
"legend.frameon": False, "legend.fontsize": 7})
return plt
# ----------------------------------------------------------------------------- benchmark
def bench():
import torch, torch.nn as nn
from torch.utils.flop_counter import FlopCounterMode
from temporal_srda import TemporalSRDABlock
class FullAttnBlock(nn.Module):
"""Reference: a standard pre-norm transformer block (full T x T self-attention + MLP).
Used only to put the cost of the SRDA block in context; it is not part of any experiment."""
def __init__(s, d=256, h=8):
super().__init__()
s.l = nn.TransformerEncoderLayer(d, h, 4 * d, dropout=0.0, activation="gelu", batch_first=True, norm_first=True)
def forward(s, x): return s.l(x)
dev = "cuda" if torch.cuda.is_available() and torch.cuda.mem_get_info()[0] > 8e9 else "cpu"
d, h, N = 256, 8, 256
out = {"device": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "d_model": d, "heads": h,
"sequences_per_batch": N, "normalised_to": 1024, "note": "forward only, fp16 autocast on GPU; the GPU is shared, so latency is indicative "
"and the FLOP counts (exact, from torch's FlopCounterMode) are the reliable column", "rows": []}
for T in (16, 32, 64, 128, 256):
for name, mk in [("Full self-attention", lambda: FullAttnBlock(d, h))] + [(f"SRDA R={R}", (lambda R=R: TemporalSRDABlock(d, h, R=R))) for R in (1, 2, 4, 8)]:
blk = mk().to(dev).train() # train() keeps torch off its fused eval fast path so FLOPs are counted; dropout is 0
x = torch.randn(N, T, d, device=dev)
with torch.no_grad():
with FlopCounterMode(display=False) as fc:
blk(x)
fl = fc.get_total_flops()
ms, mem = None, None
if dev == "cuda":
torch.cuda.reset_peak_memory_stats(); torch.cuda.synchronize()
with torch.autocast("cuda", dtype=torch.float16):
for _ in range(3): blk(x)
torch.cuda.synchronize(); t0 = time.time()
for _ in range(10): blk(x)
torch.cuda.synchronize()
ms = (time.time() - t0) / 10 * 1000; mem = torch.cuda.max_memory_allocated() / 1e6
R = 1 if name.startswith("Full") else int(name.split("=")[1])
out["rows"].append({"T": T, "method": name, "R": None if name.startswith("Full") else R,
"params_M": sum(p.numel() for p in blk.parameters()) / 1e6,
"attn_entries_per_head": T * T if name.startswith("Full") else T * (T // R),
"GFLOPs": fl / 1e9 * 1024 / N, "ms": None if ms is None else ms * 1024 / N, "peak_MB": mem})
del blk, x
if dev == "cuda": torch.cuda.empty_cache()
# parameter breakdown of the MTLCC model
import config as C
from model import UTAE_ASPP, UTAEClassificationDual
enc = UTAE_ASPP(n_channels=13, d_model=256, n_heads=8)
net = UTAEClassificationDual(enc, d_model=256, num_classes=18)
cnt = lambda m: sum(p.numel() for p in m.parameters()) / 1e6
parts = {"Atrous spatial encoder": cnt(enc.spatial_encoder), "Temporal SRDA encoder (3 blocks)": cnt(enc.temporal_encoder)}
parts["Pre-training / fine-tuning heads"] = cnt(net) - cnt(enc)
parts["Total (fine-tuning model)"] = cnt(net)
out["params_breakdown_M"] = parts
json.dump(out, open(RES / "efficiency.json", "w"), indent=1)
print(json.dumps(parts, indent=1)); print("wrote efficiency.json on", out["device"])
# ----------------------------------------------------------------------------- figures without GPU
def fig_attention_patterns():
plt = mpl()
T, R, w = 12, 4, 4
fig, axs = plt.subplots(1, 4, figsize=(7.1, 1.9), gridspec_kw={"width_ratios": [1, 1, 0.5, 1.15]})
full = np.ones((T, T))
win = np.zeros((T, T))
for i in range(T):
s = (i // w) * w
win[i, s:s + w] = 1
srda = np.ones((T, T // R))
for ax, mat, title, c in [(axs[0], full, "Full self-attention\n$T\\times T$ = 144", ORANGE),
(axs[1], win, "One window layer\n$T\\times w$ = 48", GRAY),
(axs[2], srda, "SRDA, $R$=4\n$T\\times T/R$=36", BLUE)]:
ax.imshow(mat, cmap="Blues" if c == BLUE else "Oranges" if c == ORANGE else "Greys", vmin=0, vmax=1.6, aspect="auto")
ax.set_title(title, fontsize=7.2, color=INK)
ax.set_xlabel("key", fontsize=7); ax.set_ylabel("query", fontsize=7)
ax.set_xticks([]); ax.set_yticks([])
# receptive field of query t=0 after one layer, as a strip
ax = axs[3]
rf = np.zeros((3, T))
rf[0, :] = 1
rf[1, :w] = 1
rf[2, :] = 1
ax.imshow(rf, cmap="Blues", vmin=0, vmax=1.6, aspect="auto")
ax.set_yticks([0, 1, 2]); ax.set_yticklabels(["full", "window", "SRDA"], fontsize=7)
ax.set_xticks([0, T - 1]); ax.set_xticklabels(["$t_1$", f"$t_{{{T}}}$"], fontsize=7)
ax.set_title("Acquisitions reachable by\nquery $t_1$ after ONE layer", fontsize=7.2, color=INK)
for s in ax.spines.values(): s.set_visible(False)
fig.tight_layout(w_pad=1.2)
fig.savefig(FIG / "fig_attention_patterns.pdf"); fig.savefig(FIG / "fig_attention_patterns.png", dpi=130); plt.close(fig)
print("wrote fig_attention_patterns.pdf")
def fig_overview():
plt = mpl()
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
fig, ax = plt.subplots(figsize=(7.1, 2.9)); ax.set_xlim(0, 14.2); ax.set_ylim(0, 5.8); ax.axis("off")
def box(x, y, w, h, t, fc="#ffffff", ec=GRAY, fs=6.2, lw=1.0):
ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02,rounding_size=0.12", fc=fc, ec=ec, lw=lw))
ax.text(x + w / 2, y + h / 2, t, ha="center", va="center", fontsize=fs, linespacing=1.3, color=INK)
def arr(p, q, c=INK2):
ax.add_patch(FancyArrowPatch(p, q, arrowstyle="-|>", mutation_scale=8, color=c, lw=1.0))
ax.text(0.05, 5.55, "Stage 1 — self-supervised pre-training (no labels)", fontsize=8, fontweight="bold", color=ORANGE)
box(0.05, 3.55, 2.2, 1.45, "Unlabelled series\nMTLCC 4,873 tiles\nPLANTEUR 1,896")
box(2.9, 3.55, 2.2, 1.45, "Mask frames\nNDVI-gated,\nper frame", fc="#fbeee8", ec=ORANGE)
box(5.75, 3.55, 2.6, 1.45, "Encoder\natrous spatial +\ntemporal SRDA", fc="#e8f0fb", ec=BLUE, lw=1.6)
box(9.0, 3.55, 2.3, 1.45, "Reconstruction\nheads: MSE on\nmasked positions", fc="#fbeee8", ec=ORANGE)
for a, b in [(2.25, 2.9), (5.1, 5.75), (8.35, 9.0)]: arr((a, 4.27), (b, 4.27))
box(11.95, 3.55, 2.2, 1.45, "Heads dropped;\nencoder\nweights kept", fc="#ffffff")
arr((11.3, 4.27), (11.95, 4.27))
ax.text(0.05, 2.9, "Stage 2 — supervised fine-tuning (few labels)", fontsize=8, fontweight="bold", color=BLUE)
box(0.05, 0.9, 2.2, 1.5, "Labelled subset\n78 tiles or\n2–100 % of\nPLANTEUR")
box(2.9, 0.9, 2.2, 1.5, "Pre-trained\nencoder\n(initialisation)", fc="#e8f0fb", ec=BLUE, lw=1.6)
box(5.75, 0.9, 2.6, 1.5, "STA pool over time\nsemantic + boundary\ndecoders, gated refine", fc="#e8f0fb", ec=BLUE)
box(9.0, 0.9, 2.3, 1.5, "Loss: CE + 0.75\nLovász + 0.5\nboundary BCE", fc="#ffffff")
box(11.95, 0.9, 2.2, 1.5, "Selection on\nvalidation mIoU\n(raw / EMA)", fc="#ffffff")
for a, b in [(2.25, 2.9), (5.1, 5.75), (8.35, 9.0), (11.3, 11.95)]: arr((a, 1.65), (b, 1.65))
arr((13.05, 3.55), (4.0, 2.4), c=ORANGE)
ax.text(8.6, 2.95, "weights", fontsize=6.8, color=ORANGE, rotation=-8)
ax.text(0.05, 0.25, "Test: the held-out split, scored with each benchmark's own metric definition.", fontsize=7, color=INK2)
fig.savefig(FIG / "fig_overview.pdf"); fig.savefig(FIG / "fig_overview.png", dpi=130); plt.close(fig)
print("wrote fig_overview.pdf")
def fig_efficiency():
plt = mpl()
e = json.load(open(RES / "efficiency.json"))
rows = e["rows"]
fig, axs = plt.subplots(1, 2, figsize=(7.1, 2.4))
series = [("Full self-attention", ORANGE, "o"), ("SRDA R=1", "#7db1ee", "s"), ("SRDA R=2", "#4f95e8", "^"), ("SRDA R=4", BLUE, "D"), ("SRDA R=8", "#1a4f94", "v")]
for name, c, mk in series:
rr = [r for r in rows if r["method"] == name]
axs[0].plot([r["T"] for r in rr], [r["GFLOPs"] for r in rr], marker=mk, color=c, lw=1.4, ms=4, label=name)
if rr and rr[0]["peak_MB"]:
axs[1].plot([r["T"] for r in rr], [r["peak_MB"] for r in rr], marker=mk, color=c, lw=1.4, ms=4, label=name)
axs[0].set_ylabel("GFLOPs per block\n(per 1,024 pixel sequences)"); axs[1].set_ylabel("peak GPU memory (MB)\n256 sequences")
for ax in axs:
ax.set_xlabel("acquisitions $T$"); ax.set_xscale("log", base=2); ax.set_yscale("log"); ax.set_xticks([16, 32, 64, 128, 256]); ax.set_xticklabels([16, 32, 64, 128, 256]); ax.grid(axis="y", color=GRID, lw=0.6)
axs[0].legend(loc="upper left")
axs[0].set_title("(a) exact FLOP count", fontsize=8); axs[1].set_title("(b) measured peak memory", fontsize=8)
fig.tight_layout(); fig.savefig(FIG / "fig_efficiency.pdf"); fig.savefig(FIG / "fig_efficiency.png", dpi=130); plt.close(fig)
print("wrote fig_efficiency.pdf")
def fig_curves():
plt = mpl()
runs = [("Full recipe", M / "runs/initial/history.json", BLUE, "-"),
("No boundary loss", M / "runs_ablate/no_boundary/history.json", GRAY, "-"),
("Plain cross-entropy", M / "runs_ablate/plain_ce/history.json", ORANGE, "-"),
("No pre-training, R=1", M / "runs_ablate/scratch_R1/history.json", "#c9a227", "--"),
("No pre-training, R=4", M / "runs_ablate/scratch_R4/history.json", "#b0431f", "--")]
fig, ax = plt.subplots(figsize=(3.4, 2.6))
for n, p, c, ls in runs:
h = json.load(open(p))
y = [(e["ema"]["miou"] if isinstance(e.get("ema"), dict) else e.get("val_miou_ema", np.nan)) for e in h]
ax.plot(range(len(y)), y, color=c, ls=ls, lw=1.3, label=n)
ax.set_xlabel("fine-tuning epoch"); ax.set_ylabel("validation mIoU (EMA weights)")
ax.grid(axis="y", color=GRID, lw=0.6); ax.legend(loc="lower right", fontsize=6.3)
fig.tight_layout(); fig.savefig(FIG / "fig_curves.pdf"); fig.savefig(FIG / "fig_curves.png", dpi=130); plt.close(fig)
print("wrote fig_curves.pdf")
def fig_perclass():
plt = mpl()
names = [l.split("|")[1].strip() for l in open("/home/ubuntu/pro/MTLCC_data/classes.txt")][1:]
bl = json.load(open(B / "results/mtlcc/summary.json"))
get = lambda k: next(r for r in bl if r["key"] == k)["per_class"]
series = [("T-SRDA (seed 3407)", get("tsrda"), BLUE), ("STCLN_wp", get("stcln_wp"), GRAY), ("STCLN (no pre-training)", get("stcln"), LGRAY)]
ids = [str(i) for i in range(1, 18)]
fig, ax = plt.subplots(figsize=(7.1, 2.7))
wdt = 0.27
for j, (n, pc, c) in enumerate(series):
ax.bar(np.arange(len(ids)) + (j - 1) * wdt, [pc.get(i, 0) for i in ids], wdt, color=c, label=n, edgecolor="white", lw=0.4)
ax.set_xticks(range(len(ids))); ax.set_xticklabels([names[int(i) - 1] if int(i) - 1 < len(names) else i for i in ids], rotation=40, ha="right", fontsize=6.5)
ax.set_ylabel("test IoU"); ax.set_ylim(0, 1.12); ax.grid(axis="y", color=GRID, lw=0.6); ax.set_axisbelow(True); ax.legend(ncol=3, loc="upper left")
fig.tight_layout(); fig.savefig(FIG / "fig_perclass.pdf"); fig.savefig(FIG / "fig_perclass.png", dpi=130); plt.close(fig)
print("wrote fig_perclass.pdf")
# ----------------------------------------------------------------------------- qualitative maps
def qual():
import torch
import config as C
from dataset import MTLCCTileDataset, test_patch_ids, pad_collate
from eval_mtlcc import load_network
plt = mpl()
from matplotlib.colors import ListedColormap
dev = "cuda"
ids = test_patch_ids()
rng = np.random.default_rng(7)
ds = MTLCCTileDataset(ids, train=False)
# choose tiles with many classes present, spread across the test set
cand = rng.choice(len(ids), 400, replace=False)
scored = []
for i in cand:
(x, pos, _), y = ds[int(i)] if len(ds[int(i)]) == 2 else (ds[int(i)][0], ds[int(i)][1])
y = y.numpy() if hasattr(y, "numpy") else np.asarray(y)
scored.append((len(np.unique(y[y > 0])), int(i)))
pick = [i for _, i in sorted(scored, reverse=True)[:40]]
pick = list(rng.choice(pick, 5, replace=False))
nets = {"full": load_network(M / "runs/initial/model_best_ema.tar", dev),
"scratch": load_network(M / "runs_ablate/scratch_R4/model_best_ema.tar", dev)}
cmap = ListedColormap(["#ffffff"] + [plt.cm.tab20(i) for i in range(17)])
fig, axs = plt.subplots(5, 4, figsize=(5.2, 6.3))
cols = ["Sentinel-2 (RGB, clearest date)", "Ground truth", "T-SRDA (pre-trained)", "T-SRDA, no pre-training"]
for r, i in enumerate(pick):
item = ds[int(i)]
(x, pos, _), y = item if len(item) == 2 else ((item[0], item[1], None), item[2])
xb, pb = pad_collate([item])[0][:2] if False else (x.unsqueeze(0), pos.unsqueeze(0))
preds = {}
with torch.no_grad(), torch.autocast("cuda", dtype=torch.float16):
for k, net in nets.items():
preds[k] = net(xb.to(dev), pb.to(dev))["refined_logits"].float().argmax(1)[0].cpu().numpy()
valid = [t for t in range(x.shape[0]) if float(x[t].abs().sum()) > 0]
tt = min(valid, key=lambda t: float(x[t, 1].mean())) if valid else x.shape[0] // 2
rgb = np.clip(x[tt, [3, 2, 1]].permute(1, 2, 0).numpy() / 0.3, 0, 1) ** 0.8
yy = y.numpy() if hasattr(y, "numpy") else np.asarray(y)
mask = yy > 0
for c, im in enumerate([rgb, yy, np.where(mask, preds["full"], 0), np.where(mask, preds["scratch"], 0)]):
ax = axs[r, c]; ax.set_xticks([]); ax.set_yticks([])
for s in ax.spines.values(): s.set_visible(False)
ax.imshow(im, interpolation="nearest") if c == 0 else ax.imshow(im, cmap=cmap, vmin=0, vmax=17, interpolation="nearest")
if r == 0: ax.set_title(cols[c], fontsize=6.2)
names = [l.split("|")[1].strip() for l in open("/home/ubuntu/pro/MTLCC_data/classes.txt")][1:18]
from matplotlib.patches import Patch
fig.legend(handles=[Patch(fc=cmap(i + 1), label=n) for i, n in enumerate(names)], loc="lower center", ncol=6, fontsize=5.4, frameon=False,
handlelength=1, columnspacing=0.9)
fig.subplots_adjust(bottom=0.1, wspace=0.03, hspace=0.04)
fig.savefig(FIG / "fig_qualitative.pdf"); fig.savefig(FIG / "fig_qualitative.png", dpi=130); plt.close(fig)
print("wrote fig_qualitative.pdf, tiles", pick)
if __name__ == "__main__":
m = sys.argv[1] if len(sys.argv) > 1 else "figs"
if m == "bench": bench()
elif m == "figs": fig_attention_patterns(); fig_overview(); fig_efficiency(); fig_curves(); fig_perclass()
elif m == "qual": qual()