File size: 4,948 Bytes
a62fa5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate every model config actually builds + runs a forward pass at IMG_SIZE=128
with ImageNet weights -- for BOTH strategy 2 (plain SMP) and strategy 3 (refinement stack).

Run this on the GPU box BEFORE launching the full matrix:
    python validate_models.py

For each model it reports:
  * whether strategy 2 builds/forwards (and at which encoder_depth: tries 5, falls back to 4)
  * the encoder's out_channels (what the strategy-3 projection consumes)
  * whether strategy 3 (PixelDRLMG_WithDecoder) builds/forwards
Anything marked FAIL must be fixed (or the model swapped) before you burn compute.
"""
from __future__ import annotations

import importlib.util
import json
import pathlib
import sys
import traceback

import torch
import segmentation_models_pytorch as smp

REPO = pathlib.Path(__file__).resolve().parent
IMG = 128
BATCH = 2
MANIFEST = json.loads((REPO / "params" / "models_manifest.json").read_text(encoding="utf-8"))


def load_runner():
    """Import the simplified runner module (module-level only; main() is guarded)."""
    path = REPO / "foldsrunner_simplified_after_ablation.py"
    spec = importlib.util.spec_from_file_location("foldsrunner_simplified_after_ablation", path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = mod  # register BEFORE exec so @dataclass can resolve its module
    spec.loader.exec_module(mod)
    return mod


def short(exc: BaseException) -> str:
    return f"{type(exc).__name__}: {str(exc)[:180]}"


def main() -> int:
    runner = load_runner()
    x = torch.randn(BATCH, 3, IMG, IMG)
    results = []

    for key, cfg in MANIFEST.items():
        arch, enc, proj = cfg["arch"], cfg["encoder"], cfg["proj_dim"]
        row = {"model": key, "arch": arch, "encoder": enc, "proj_dim": proj,
               "depth": None, "out_channels": None, "s2": "FAIL", "s3": "FAIL"}

        # ---- strategy 2: plain SMP model -------------------------------------
        for depth in (5, 4):
            try:
                m2 = smp.create_model(arch=arch, encoder_name=enc, encoder_weights="imagenet",
                                      encoder_depth=depth, in_channels=3, classes=1)
                m2.eval()
                with torch.no_grad():
                    y = m2(x)
                row["depth"] = depth
                row["out_channels"] = list(m2.encoder.out_channels)
                row["s2"] = f"OK  out={tuple(y.shape)}"
                del m2
                break
            except Exception as exc:  # noqa: BLE001
                row["s2"] = f"FAIL(depth={depth}) {short(exc)}"

        # ---- strategy 3: refinement stack ------------------------------------
        if row["depth"] is not None:
            try:
                m3 = runner.PixelDRLMG_WithDecoder(
                    arch=arch, encoder_name=enc, encoder_weights="imagenet",
                    encoder_depth=row["depth"], proj_dim=proj, dropout_p=0.0,
                )
                m3.eval()
                with torch.no_grad():
                    ctx = m3.prepare_refinement_context(x)
                    state = m3.forward_refinement_state(
                        ctx["base_features"], ctx["decoder_prob"].detach(), ctx["decoder_prob"],
                        ctx["mc_variance"], ctx["pred_entropy"],
                        encoder_features=ctx.get("encoder_features"),
                    )
                    policy, _ = m3.forward_from_state(state)
                row["s3"] = f"OK  state={tuple(state.shape)} policy={tuple(policy.shape)}"
                del m3
            except Exception as exc:  # noqa: BLE001
                row["s3"] = f"FAIL {short(exc)}"
                traceback.print_exc()

        results.append(row)

    # ---- report --------------------------------------------------------------
    print("\n" + "=" * 110)
    print(f"MODEL VALIDATION @ {IMG}x{IMG}, ImageNet weights")
    print("=" * 110)
    for r in results:
        ok = r["s2"].startswith("OK") and r["s3"].startswith("OK")
        print(f"\n[{'PASS' if ok else 'FAIL'}] {r['model']}   arch={r['arch']}  encoder={r['encoder']}")
        print(f"        encoder_depth : {r['depth']}")
        print(f"        out_channels  : {r['out_channels']}")
        print(f"        strategy 2    : {r['s2']}")
        print(f"        strategy 3    : {r['s3']}")

    failed = [r["model"] for r in results if not (r["s2"].startswith("OK") and r["s3"].startswith("OK"))]
    depth4 = [r["model"] for r in results if r["depth"] == 4]
    print("\n" + "=" * 110)
    if depth4:
        print(f"NOTE: these need SMP_ENCODER_DEPTH = 4 (not 5): {depth4}")
        print("      -> add  -e 's/^SMP_ENCODER_DEPTH = .*/SMP_ENCODER_DEPTH = 4/'  to that model's command.")
    if failed:
        print(f"FAILED: {failed}  -- fix/swap these before running the matrix.")
        return 1
    print("ALL MODELS PASS.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())