File size: 27,082 Bytes
a133a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""Builds REPORT.md for the external-pre-training ("foundation") track from the result files.

Every number is read from a file under results/ (or a training log for in-progress runs); none is typed here.
Called by hf_work/make_reports.py each publishing cycle; also runnable on its own:  python3 make_report.py
`summary()` returns the headline numbers for the repository front page.
"""
import datetime, glob, json, re
from pathlib import Path
import numpy as np

F = Path(__file__).resolve().parent
RES = F / "results"
LOG = F / "logs"
RUNS = F / "runs_planteur"
PLB = Path("/home/ubuntu/pro/baselines/results/planteur/summary.json")
PUB = Path("/home/ubuntu/pro/TSRDA_PLANTEUR/code/published_baselines.json")
NOW = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")


def jl(p, d=None):
    try:
        return json.loads(Path(p).read_text())
    except Exception:
        return d


def f4(x):
    return "–" if x is None else f"{x:.4f}"


def sg(x):
    return "–" if x is None else f"{x:+.4f}"


# ----------------------------------------------------------------------------- readers
def mtlcc_simple():
    return jl(RES / "mtlcc/result.json")


def mtlcc_ladder():
    return jl(RES / "mtlcc_ladder/ladder.json")


def planteur_ladder():
    """The final ladder if it exists, else the partial one (run before the structured-SSL branch finished)."""
    d = jl(RES / "planteur_ladder/ladder.json")
    if d:
        d["_partial"] = False; return d
    d = jl(RES / "planteur_ladder_partial/ladder.json")
    if d:
        d["_partial"] = True
    return d


def planteur_runs():
    out = []
    for p in sorted(glob.glob(str(RES / "planteur/*/result.json"))):
        r = jl(p)
        if not r:
            continue
        out.append(dict(run=r["run"], frac=r["fraction"], seed=r["run_seed"], n=r["n_labelled_patches"],
                        desc=r["selected_gaussian"]["descriptor"], shrink=r["selected_gaussian"]["shrink"],
                        prior=r["selected_gaussian"]["prior"], tau=r["selected_blend"]["temperature"],
                        w=r["selected_blend"]["weight"], v_net=r["val_network"],
                        v_g=r["selected_gaussian"]["val_miou"], v_b=r["selected_blend"]["val_miou"],
                        t_net=r["test"]["network"]["miou"], t_g=r["test"]["gaussian"]["miou"],
                        t_b=r["test"]["blend"]["miou"]))
    return sorted(out, key=lambda r: (r["frac"], r["seed"]))


def planteur_baselines():
    d = jl(PLB, {}) or {}
    bl = d.get("baselines", [])
    best = max(bl, key=lambda b: b["mIoU"]) if bl else None
    pub = jl(PUB, {}) or {}
    prow = [r for r in pub.get("full_label_budget", {}).get("rows", [])]
    return bl, best, prow


def branch_state():
    """In-progress PLANTEUR branch runs, read from their logs / marker files."""
    st = []

    def ft_log(name, log, marker):
        txt = (LOG / log).read_text(errors="ignore") if (LOG / log).exists() else ""
        # chain logs hold two consecutive runs; split at the init line of each
        seg = txt
        if name == "sam":
            k = txt.find("refinement/model_best_raw.tar")
            seg = txt[k:] if k >= 0 else ""
        elif name == "refinement":
            k = txt.find("refinement/model_best_raw.tar")
            seg = txt[:k] if k >= 0 else txt
        eps = re.findall(r"\[ep\s+(\d+)\] .*?val mIoU raw ([\d.]+) ema ([\d.]+) \| best raw ([\d.]+)@\d+ ema ([\d.]+)@\d+", seg)
        done = (RUNS / name / marker).exists()
        started = "[FT]" in seg
        if eps:
            e = eps[-1]
            return dict(name=name, epoch=int(e[0]), best_raw=float(e[3]), best_ema=float(e[4]), done=done, started=True)
        return dict(name=name, epoch=0, best_raw=None, best_ema=None, done=done, started=started)

    st.append(ft_log("refinement", "planteur_chainA.log", "model_best_raw.tar") | {"of": 20})
    st[-1]["done"] = (RUNS / "refinement/result.json").exists()
    s = ft_log("sam", "planteur_chainA.log", "x") | {"of": 20}
    s["done"] = (RUNS / "sam/result.json").exists()
    st.append(s)
    sp = jl(RUNS / "structured_pre/completed.json")
    st.append(dict(name="structured_pre", epoch=3 if sp else None, of=3, done=bool(sp), best_raw=None, best_ema=None,
                   note=f"reconstruction loss {sp['loss_last_epoch']:.4f}" if sp else ""))
    tb = (LOG / "planteur_chainB.log").read_text(errors="ignore") if (LOG / "planteur_chainB.log").exists() else ""
    k = tb.find("pre-trained")
    eps = re.findall(r"\[ep\s+(\d+)\] .*?best raw ([\d.]+)@\d+ ema ([\d.]+)@\d+", tb[k:] if k >= 0 else "")
    st.append(dict(name="structured_ft", epoch=int(eps[-1][0]) if eps else 0, of=100,
                   best_raw=float(eps[-1][1]) if eps else None, best_ema=float(eps[-1][2]) if eps else None,
                   done=(RUNS / "structured_ft/result.json").exists(), started=k >= 0))
    for v in ("old", "new"):
        c = jl(RUNS / f"cnn_{v}/completed.json")
        hist = []
        lt = RUNS / f"cnn_{v}/latest.tar"
        txt = (LOG / "planteur_chainC.log").read_text(errors="ignore") if (LOG / "planteur_chainC.log").exists() else ""
        # chain C runs old then new; split the json lines at the restart of epoch 1
        lines = [json.loads(m) for m in re.findall(r"^(\{\"epoch\".*?\})", txt, re.M)]
        runs, cur = [], []
        for l in lines:
            if l["epoch"] == 1 and cur:
                runs.append(cur); cur = []
            cur.append(l)
        if cur:
            runs.append(cur)
        hist = runs[0 if v == "old" else 1] if len(runs) > (0 if v == "old" else 1) else []
        vals = [h["val_miou"] for h in hist if "val_miou" in h]
        st.append(dict(name=f"cnn_{v}", epoch=hist[-1]["epoch"] if hist else 0, of=100, done=bool(c), started=bool(hist),
                       best_raw=(c or {}).get("best_val_miou", max(vals) if vals else None), best_ema=None))
    return st


# ----------------------------------------------------------------------------- summary for the front page
def summary():
    s = {}
    m = mtlcc_simple()
    lad = mtlcc_ladder()
    if m and lad:
        rows = {r["system"]: r for r in lad["rows"]}
        core = rows["core T-SRDA"]
        s["mtlcc"] = dict(core=core["test"], core_val=core["val"], base=lad["strongest_baseline"]["test"],
                          base_name="STCLN_wp",
                          tess_alone=m["test"]["gaussian_alone"]["mIoU"], net_g=m["test"]["net+G"]["mIoU"],
                          v_tess=m["selected_gaussian"]["val_miou"], v_net_g=m["selected_blend"]["net"]["val_miou"],
                          v_ens3=m["selected_blend"]["ens3"]["val_alone"], v_ens3_g=m["selected_blend"]["ens3"]["val_miou"],
                          ens3=m["test"]["ens3"]["mIoU"], ens3_g=m["test"]["ens3+G"]["mIoU"],
                          best=lad["validation_selected_overall"], best_noext=lad["validation_selected_without_external"],
                          n_rows=len(lad["rows"]))
    pr = planteur_runs()
    if pr:
        full = next((r for r in pr if r["frac"] == 1.0), None)
        _, best, _ = planteur_baselines()
        s["planteur"] = dict(full=full, base=best, n_runs=len(pr),
                             frac=[(fr, float(np.mean([r["t_net"] for r in pr if r["frac"] == fr])),
                                    float(np.mean([r["t_g"] for r in pr if r["frac"] == fr])),
                                    float(np.mean([r["t_b"] for r in pr if r["frac"] == fr])),
                                    sum(r["frac"] == fr for r in pr)) for fr in sorted({r["frac"] for r in pr})])
    s["planteur_ladder"] = planteur_ladder()
    s["branches"] = branch_state()
    return s


# ----------------------------------------------------------------------------- report
def ladder_table(lad, core, base):
    L = ["| Level | System | Components | Ext | Nets | Val mIoU | Test mIoU | Ξ” core | Ξ” strongest baseline |",
         "|---|---|---|---|---|---|---|---|---|"]
    for r in lad["rows"]:
        L.append(f"| {r['level']} | {r['system']} | {r['components']} | {'yes' if r['external'] else 'no'} | {r['nets']} | "
                 f"{r['val']:.4f} | {r['test']:.4f} | {r['test'] - core:+.4f} | {r['test'] - base:+.4f} |")
    return L


def build():
    S = summary()
    L = ["# T-SRDA enhancement track on MTLCC and PLANTEUR β€” PASTIS components, TESSERA, ensembles", "",
         f"*Snapshot {NOW}. Generated by [`make_report.py`](make_report.py) from the files in [`results/`](results) and "
         "[`logs/`](logs); no number on this page is typed by hand. Runs still in progress are labelled, never estimated.*", "",
         "This track asks one question: **do the enhancements that lifted T-SRDA on PASTIS β€” frozen TESSERA v2 features with "
         "a shrinkage-Gaussian readout, extra CNN / SAM / structured-SSL / cluster branches, feature-affinity diffusion and the "
         "nested probability ensembles β€” also lift T-SRDA on MTLCC and PLANTEUR, and if so, which part of the gain belongs "
         "to T-SRDA?** The PASTIS implementations were reused (copied or imported), not rewritten; deviations are listed below.", "",
         "## Protocol", "",
         "* Existing dataset splits and metrics: MTLCC = STCLN protocol (78 train / 78 val entries, 1,495 test tiles, "
         "y > 0 & pred > 0); PLANTEUR = official mIoU-8 (Background scored, void ignored; 411 val / 443 test patches).",
         "* Every readout is fitted on **training** pixels only. Every choice β€” Gaussian descriptor, shrinkage, prior, "
         "softmax temperature Ο„, blend weight w, greedy-ensemble members β€” is made on **validation** mIoU.",
         "* The test set is scored **once per system** with the frozen choice. Systems whose recipe was fixed in advance "
         "(the PASTIS weights) are scored as-is, without re-tuning.",
         "* **Ext = yes** marks any system that uses the frozen TESSERA v2 encoder (pre-trained and distilled by others, "
         "7.1 M-parameter student). Its pre-training data's overlap with Bavaria 2016 / the PLANTEUR regions is not certified, "
         "and none of the baselines gets such features. Those rows are a **separate track**: they do not measure the T-SRDA "
         "architecture.", ""]

    # ---------------- headline
    L += ["## Headline", ""]
    m = S.get("mtlcc")
    p = S.get("planteur")
    L += ["| Dataset | Core T-SRDA (test) | Best **without** external features | TESSERA readout alone | "
          "Best **with** TESSERA (val-selected) | Strongest baseline |", "|---|---|---|---|---|---|"]
    if m:
        L.append(f"| MTLCC | {f4(m['core'])} | {f4(m['ens3'])} (3-seed T-SRDA average, fixed recipe, {sg(m['ens3'] - m['core'])}; "
                 f"the val-selected greedy T-SRDA-only pick scores {f4(m['best_noext']['test'])}) | "
                 f"{f4(m['tess_alone'])} | **{f4(m['best']['test'])}** ({m['best']['system']}, {sg(m['best']['test'] - m['core'])}) | "
                 f"{m['base_name']} {f4(m['base'])} |")
    if p and p["full"]:
        fu = p["full"]; b = p["base"]
        pl = S.get("planteur_ladder")
        best_pl = pl["validation_selected_overall"] if pl else None
        L.append(f"| PLANTEUR (100 % labels) | {f4(fu['t_net'])} | "
                 + (f"{f4(pl['validation_selected_without_external']['test'])}" if pl else "⏳ branch networks still training")
                 + f" | {f4(fu['t_g'])} | **{f4(best_pl['test'] if best_pl else fu['t_b'])}** "
                 + (f"({best_pl['system']})" if best_pl else f"(core + TESSERA blend, w = {fu['w']}, Ο„ = {fu['tau']})")
                 + f" | {b['model']} {f4(b['mIoU'])} |")
    L += [""]
    if m:
        L += [f"* **MTLCC.** The frozen TESSERA readout *alone* scores {f4(m['tess_alone'])}, already level with the "
              f"fine-tuned core T-SRDA ({f4(m['core'])}). Blending the two gives {f4(m['net_g'])}; adding the two other "
              f"T-SRDA seeds gives {f4(m['ens3_g'])}. The best validation-selected system ({f4(m['best']['test'])}) is "
              f"{sg(m['best']['test'] - m['base'])} over {m['base_name']}. **Without TESSERA**, the best defensible gain is the "
              f"3-seed ensemble ({f4(m['ens3'])}, {sg(m['ens3'] - m['base'])} vs {m['base_name']}) β€” an ensemble of three "
              "networks against one baseline network. The PASTIS branches (SAM, refinement, structured SSL, CNNs, cluster "
              "readout) add **nothing measurable** on MTLCC: validation gives the weak ones weight 0, and the fixed PASTIS "
              "ensemble weights *lower* the score."]
    if p and p["full"]:
        fu = p["full"]; b = p["base"]
        L += [f"* **PLANTEUR.** At 100 % labels the core + TESSERA blend scores {f4(fu['t_b'])} vs {f4(fu['t_net'])} for "
              f"T-SRDA alone and {f4(b['mIoU'])} for the strongest reproduced baseline ({b['model']}); one seed. Below 50 % "
              "labels validation gives the TESSERA readout most or all of the weight: the gain there is TESSERA's, not "
              "T-SRDA's. The PASTIS branch networks for PLANTEUR are still training (see *Status*)."]
    L += [""]

    # ---------------- MTLCC simple systems
    if m:
        r = mtlcc_simple()
        sgp = r["selected_gaussian"]; sb = r["selected_blend"]
        L += ["## MTLCC β€” TESSERA Gaussian + T-SRDA (stage 1 / stage 2 selection)", "",
              f"Selected on validation: descriptor **{sgp['descriptor']}** (768-D = feature + 5Γ—5 mean + 5Γ—5 std), shrinkage "
              f"**{sgp['shrink']}**, prior **{sgp['prior']}**; blend with one network Ο„ = {sb['net']['temperature']}, "
              f"w = {sb['net']['weight']}; with the 3-seed ensemble Ο„ = {sb['ens3']['temperature']}, w = {sb['ens3']['weight']}.", "",
              "| System | Ext | Nets | Val mIoU | Test mIoU | Ξ” core | Ξ” STCLN_wp (official lr, 0.6953) |", "|---|---|---|---|---|---|---|"]
        rows = [("core T-SRDA (seed 3407, EMA)", "no", 1, sb["net"]["val_alone"], r["test"]["net"]["mIoU"]),
                ("TESSERA 768-D shrinkage Gaussian alone", "yes", 0, sgp["val_miou"], r["test"]["gaussian_alone"]["mIoU"]),
                ("core + TESSERA Gaussian", "yes", 1, sb["net"]["val_miou"], r["test"]["net+G"]["mIoU"]),
                ("3-seed T-SRDA ensemble", "no", 3, sb["ens3"]["val_alone"], r["test"]["ens3"]["mIoU"]),
                ("3-seed ensemble + TESSERA Gaussian", "yes", 3, sb["ens3"]["val_miou"], r["test"]["ens3+G"]["mIoU"])]
        for n, e, k, v, t in rows:
            L.append(f"| {n} | {e} | {k} | {v:.4f} | {t:.4f} | {t - m['core']:+.4f} | {t - m['base']:+.4f} |")
        L += ["", "Full validation grids, per-class IoU and the selected Gaussian parameters: "
              "[`results/mtlcc/result.json`](results/mtlcc/result.json), [`results/mtlcc/gaussian_selected.npz`](results/mtlcc/gaussian_selected.npz).", ""]

    # ---------------- MTLCC ladder
    lad = mtlcc_ladder()
    if lad:
        L += ["## MTLCC β€” full enhancement ladder", "",
              "Core β†’ each component alone (A) β†’ core + one component (L1) β†’ combinations (L2) β†’ full PASTIS-style "
              "nested ensembles (L3). Ο„ and w for every L1 pair, and the greedy members, were chosen on validation. "
              "The PASTIS recipes (ref4, incumbent, hist58, parent, moments, diffusion, two-branch) use the **fixed PASTIS "
              "weights**; their core-rooted versions replace the PASTIS SAM network by the core T-SRDA.", ""]
        L += ladder_table(lad, m["core"], m["base"])
        vo, vn = lad["validation_selected_overall"], lad["validation_selected_without_external"]
        L += ["", f"* **Validation-selected overall:** {vo['system']} β€” val {vo['val']:.4f}, test **{vo['test']:.4f}**.",
              f"* **Validation-selected without external features:** {vn['system']} β€” val {vn['val']:.4f}, test "
              f"**{vn['test']:.4f}**. Its validation score is the highest of any T-SRDA-only system but its test score is "
              "not: greedy selection over-fits the 78 validation entries. The fixed 3-seed average is the more reliable "
              "T-SRDA-only number.",
              f"* Strongest baseline: {lad['strongest_baseline']['name']} = {lad['strongest_baseline']['test']:.4f} "
              f"({lad['strongest_baseline']['note']}).", "",
              "Source: [`results/mtlcc_ladder/ladder.json`](results/mtlcc_ladder/ladder.json), log "
              "[`logs/mtlcc_ladder_eval.log`](logs/mtlcc_ladder_eval.log).", ""]

    # ---------------- PLANTEUR label curve
    pr = planteur_runs()
    if pr:
        bl, best, prow = planteur_baselines()
        L += ["## PLANTEUR β€” TESSERA Gaussian on every label-curve run", "",
              "Each fine-tuned T-SRDA run gets its own Gaussian, fitted on **exactly the labelled patches that run was "
              "trained on**, so every row keeps its label budget. Selection on the official 411 validation patches; test once.", "",
              "| Run | Labels | Patches | Gaussian (desc / shrink / prior) | Ο„ | w (TESSERA) | Val net | Val blend | Test net | Test TESSERA alone | Test blend | Ξ” core |",
              "|---|---|---|---|---|---|---|---|---|---|---|---|"]
        for r in pr:
            L.append(f"| `{r['run']}` | {r['frac']:.0%} | {r['n']} | {r['desc']} / {r['shrink']} / {r['prior']} | {r['tau']} | {r['w']} | "
                     f"{r['v_net']:.4f} | {r['v_b']:.4f} | {r['t_net']:.4f} | {r['t_g']:.4f} | **{r['t_b']:.4f}** | {r['t_b'] - r['t_net']:+.4f} |")
        L += ["", "**Means over seeds (test mIoU-8):**", "",
              "| Labels | Seeds | T-SRDA alone | TESSERA alone | Blend (val-selected) | Blend βˆ’ T-SRDA | Blend βˆ’ " + (best["model"] if best else "baseline") + " |",
              "|---|---|---|---|---|---|---|"]
        for fr, a, g, b, n in summary()["planteur"]["frac"]:
            L.append(f"| {fr:.0%} | {n} | {a:.4f} | {g:.4f} | {b:.4f} | {b - a:+.4f} | {(b - best['mIoU']) if best else float('nan'):+.4f} |")
        L += ["", f"*The baseline column compares against {best['model']} trained on **100 %** of the labels "
              f"({best['mIoU']:.4f}); only the 100 % row is a same-budget comparison.*" if best else "", ""]
        if prow:
            L += ["Published PLANTEUR results at 100 % labels (transcribed from Wolters et al., arXiv 2611.05223, not re-run here):", "",
                  "| Model | Pre-training | mIoU-8 |", "|---|---|---|"]
            for r in prow:
                L.append(f"| {r['model']} | {r['pretraining']} | {r['mIoU'] / 100:.4f} |")
            L += ["", "The best TESSERA-assisted T-SRDA row stays **below** the published fine-tuned foundation models.", ""]
        L += ["Reading:", "",
              "* At ≀ 25 % labels the TESSERA Gaussian alone beats the fine-tuned T-SRDA by a wide margin, and validation "
              "puts most or all weight on it. These gains belong to the external encoder.",
              "* The TESSERA readout plateaus as labels grow while T-SRDA keeps improving; at 50–100 % the two are "
              "complementary and the blend beats both.",
              "* The 50 % and 100 % rows are single seeds.", ""]

    # ---------------- PLANTEUR ladder
    pl = planteur_ladder()
    L += ["## PLANTEUR β€” enhancement ladder", ""]
    if pl and pl.get("_partial"):
        L += ["⚠️ **Partial ladder** β€” run before the structured-SSL branch finished, so every system that needs it "
              "(the PASTIS incumbent and all nested L3 recipes) is missing; it will be replaced by the full ladder. "
              "Source: [`results/planteur_ladder_partial/`](results/planteur_ladder_partial).", ""]
    if pl:
        bs = pl["strongest_baseline"]["test"]
        core = next(r for r in pl["rows"] if r["level"] == "L0")["test"]
        L += ladder_table(pl, core, bs)
        L += ["", f"* Validation-selected overall: {pl['validation_selected_overall']['system']} β€” test "
              f"**{pl['validation_selected_overall']['test']:.4f}**.",
              f"* Validation-selected without external features: {pl['validation_selected_without_external']['system']} β€” "
              f"test **{pl['validation_selected_without_external']['test']:.4f}**.", ""]
    else:
        L += ["⏳ **Not yet run** β€” it needs the PLANTEUR ports of the PASTIS branch networks, which are training now "
              "(next section). The readouts, caches and ladder code are written "
              "([`planteur_ladder.py`](planteur_ladder.py), [`planteur_ladder_eval.py`](planteur_ladder_eval.py)) and "
              "will run once the branches finish.", ""]

    # ---------------- status
    L += ["## Status of the PLANTEUR branch networks", "",
          "All start from the 100 %-label T-SRDA run (`frac100_seed3407`) or its pre-trained encoder, and use the PASTIS/MTLCC "
          "stage settings. Validation mIoU-8 on the 411 official patches; no test evaluation is done during training.", "",
          "| Branch | What | Progress | Best val so far (raw / EMA) | Core T-SRDA val |", "|---|---|---|---|---|"]
    what = {"refinement": "low-LR refinement (lr 1e-5, encoder Γ—0.2, 20 ep)",
            "sam": "SAM-optimised network (ρ = 0.02, from the refinement net, 20 ep)",
            "structured_pre": "structured masked SSL (4 dates Γ— 4Γ—4 px blocks, mask 0.4, 3 ep, no labels)",
            "structured_ft": "fine-tune of the structured-SSL encoder (100 % labels, patience 30)",
            "cnn_old": "temporal CNN (dilated, masked mean/max) β€” original script",
            "cnn_new": "temporal CNN β€” control script"}
    core_val = p["full"]["v_net"] if p and p["full"] else None
    for b in S["branches"]:
        prog = "βœ… done" if b["done"] else (f"πŸ”„ epoch {b['epoch']}/{b['of']}" if b["epoch"] else
                                           ("πŸ”„ running, first validation pending" if b.get("started") else "⏳ queued"))
        if b["name"] == "structured_pre" and b["done"]:
            prog = "βœ… done (" + b.get("note", "") + ")"
        bv = "–" if b["best_raw"] is None else (f"{b['best_raw']:.4f}" + (f" / {b['best_ema']:.4f}" if b["best_ema"] else ""))
        L.append(f"| `{b['name']}` | {what[b['name']]} | {prog} | {bv} | {f4(core_val) if b['name'] not in ('structured_pre',) else '–'} |")
    L += ["", "Deviation from PASTIS: the structured-SSL fine-tune stops early after 30 epochs without validation gain (PASTIS: patience 0, no early stop) so it "
          "fits the remaining VM time; everything else is the PASTIS/MTLCC setting.", ""]

    # ---------------- enhancement map
    L += ["## Requested enhancements β†’ where they were tested", "",
          "| # | Enhancement | MTLCC | PLANTEUR |", "|---|---|---|---|",
          "| 1 | Frozen TESSERA v2 features + shrinkage-covariance Gaussian | βœ… `tess768_lda`, `net+G` | βœ… all 14 label-curve runs |",
          "| 2 | T-SRDA + TESSERA probability blend (incl. 50/50) | βœ… L1 (val-selected w) and L2 (fixed 50/50) | βœ… val-selected w per run; 50/50 in the ladder ⏳ |",
          "| 3 | Temporal CNN branches (dilated, masked mean/max) | βœ… `cnn_old`, `cnn_new` | ⏳ training |",
          "| 4 | Cosine class-cluster readout and original Gaussian readout | βœ… `cluster`, `orig_gauss` | ⏳ fitted after SAM |",
          "| 5 | Structured SSL branch | βœ… `structured` | ⏳ pre-training done, fine-tune running |",
          "| 6 | SAM-optimised network | βœ… `sam` | ⏳ after refinement |",
          "| 7 | 5Γ—5 mean/std, 768-D local-moments Gaussian | βœ… `tess512_hist`, `tess768_hist`, `tess768_lda` | βœ… (selected descriptor on every run) |",
          "| 8 | Three-pass feature-affinity diffusion | βœ… `core + diffusion`, L3 | ⏳ ladder |",
          "| 9 | Shrinkage grid, quadratic readouts, entropy-weighted ensemble, fusion weights | βœ… `quad005/020`, entropy row, weight grids | ⏳ ladder |",
          "| 10 | PASTIS nested ensembles (ref4 β†’ incumbent β†’ hist58 β†’ parent β†’ moments / diffusion / two-branch), greedy | βœ… L2–L3 | ⏳ ladder |", ""]

    # ---------------- attribution & caveats
    L += ["## Attribution β€” what belongs to T-SRDA", "",
          "* **T-SRDA alone** (one network, no external features) is the L0 row. That is the architecture result.",
          "* **More T-SRDA networks** (seeds) give a real but ordinary ensemble gain; it is not specific to T-SRDA.",
          "* **TESSERA** carries almost all of the remaining gain on both datasets. Its readout alone is level with T-SRDA on "
          "MTLCC and far above it at small PLANTEUR label budgets.",
          "* **PASTIS-specific branches** (SAM, refinement, structured SSL, CNNs, cluster, original Gaussian) do not transfer "
          "to MTLCC: alone they are weaker than the core and validation gives most of them weight 0.",
          "", "## Caveats", "",
          "* Selected shrinkage 0.01 sits at the edge of the grid; it was not extended, to keep the protocol fixed.",
          "* MTLCC validation has 78 entries (73 unique tiles); greedy ensemble selection over-fits it (see the L2 greedy row).",
          "* MTLCC components other than the seeds come from the earlier MTLCC port of the PASTIS recipe (Nov 7); their "
          "checkpoints are in `MTLCC/checkpoints/option2_*` in this repository.",
          "* TESSERA date padding repeats real dates to a multiple of 8; zero-padded MTLCC dates are passed through as-is.",
          "* PLANTEUR: the precomputed TESSERA v2 embeddings (~23 GB per product) were not downloaded (disk cap); features "
          "are computed here from the S2 stacks with the public student checkpoint.", "",
          "## Files", "",
          "| Path | What |", "|---|---|",
          "| `common.py` | TESSERA loading, inputs, 768-D descriptor, sufficient statistics, shrinkage LDA |",
          "| `mtlcc.py`, `planteur.py` | TESSERA Gaussian + blend, stage-1/2 selection, one test pass |",
          "| `mtlcc_ladder.py`, `mtlcc_ladder_eval.py` | MTLCC component cache (val/test) and the ladder |",
          "| `planteur_ladder.py`, `planteur_ladder_eval.py` | the same for PLANTEUR (runs after the branches) |",
          "| `ladder_lib.py` | validation-only selection, entropy weighting, greedy selection, PASTIS combination rules |",
          "| `planteur_branches/` | PLANTEUR ports of the PASTIS branch trainers (refinement/SAM, structured SSL, temporal CNNs) |",
          "| `runs_planteur/*.sh` | the three training chains as launched |",
          "| `foundation_queue.sh` | the unattended queue: keeps the chains alive, runs the partial then the full PLANTEUR ladder, publishes; never starts work at β‰₯ 86 % disk (hard cap 88 %) |",
          "| `results/` | every result file read by this report |",
          "| `checkpoints/` | PLANTEUR branch checkpoints, uploaded as each finishes |",
          "| `logs/` | raw logs |", ""]
    return "\n".join(L) + "\n"


def main():
    (F / "REPORT.md").write_text(build())
    print("[foundation] wrote", F / "REPORT.md")


if __name__ == "__main__":
    main()