khalidsyfullah commited on
Commit
4d50b2c
·
verified ·
1 Parent(s): 1bbb3a3

Upload folder using huggingface_hub

Browse files
Files changed (17) hide show
  1. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_02.txt +2 -0
  2. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_04.txt +151 -0
  3. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_06.txt +138 -0
  4. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_07.txt +14 -0
  5. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_09.txt +164 -0
  6. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_10.txt +2 -0
  7. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_12.txt +51 -0
  8. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_14.txt +101 -0
  9. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_16.txt +160 -0
  10. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_18.txt +327 -0
  11. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_20.txt +282 -0
  12. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_22.txt +150 -0
  13. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_24.txt +36 -0
  14. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/code_checksums.json +17 -0
  15. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/inference.py +50 -0
  16. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/student_model.py +163 -0
  17. sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/execution_policy.json +8 -0
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_02.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # MODULE04_CELL: 02
2
+ %pip -q install "transformers==4.57.1" "timm==1.0.22" "huggingface_hub==0.36.2" "safetensors>=0.5" "Pillow>=10" "pandas>=2" "matplotlib>=3.7" "tqdm>=4.66"
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_04.txt ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 04
2
+ import os, io, gc, json, math, time, random, hashlib, tarfile, zipfile, shutil, platform
3
+ from pathlib import Path
4
+ from contextlib import nullcontext
5
+ from collections import Counter, defaultdict
6
+ import numpy as np
7
+ import pandas as pd
8
+ import matplotlib.pyplot as plt
9
+ from PIL import Image, ImageOps
10
+ import torch
11
+ from torch import nn
12
+ from torch.nn import functional as F
13
+ from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
14
+ import timm
15
+ import inspect
16
+ import transformers
17
+ from transformers import AutoModel, AutoConfig
18
+ from safetensors.torch import load_file, save_file
19
+ from huggingface_hub import HfApi, hf_hub_download
20
+ from huggingface_hub.errors import EntryNotFoundError
21
+ from tqdm.auto import tqdm
22
+ from getpass import getpass
23
+
24
+ try:
25
+ from google.colab import userdata
26
+
27
+ HF_TOKEN = userdata.get("HF_TOKEN")
28
+ except Exception:
29
+ HF_TOKEN = os.environ.get("HF_TOKEN") or getpass(
30
+ "HF token with read/write access: "
31
+ )
32
+ # Retry temporary Hub read failures, including the HTTP 500 encountered in module 03.
33
+ import requests
34
+ from requests.adapters import HTTPAdapter
35
+ from urllib3.util.retry import Retry
36
+ from huggingface_hub import configure_http_backend
37
+
38
+
39
+ def retrying_hf_session():
40
+ session = requests.Session()
41
+ retry = Retry(
42
+ total=5,
43
+ backoff_factor=2,
44
+ status_forcelist=[429, 500, 502, 503, 504],
45
+ allowed_methods=["GET", "HEAD"],
46
+ respect_retry_after_header=True,
47
+ raise_on_status=False,
48
+ )
49
+ adapter = HTTPAdapter(max_retries=retry)
50
+ session.mount("https://", adapter)
51
+ session.mount("http://", adapter)
52
+ return session
53
+
54
+
55
+ configure_http_backend(backend_factory=retrying_hf_session)
56
+
57
+ api = HfApi(token=HF_TOKEN)
58
+ api.whoami()
59
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
60
+ if DEVICE != "cuda":
61
+ raise RuntimeError("Choose a T4, L4 or A100 GPU runtime, then run again.")
62
+ GPU = torch.cuda.get_device_name(0)
63
+ AMP_DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
64
+
65
+ TEACHER_RESULTS_REPO = "khalidsyfullah/sensitivity-teacher-results"
66
+ TEACHER_RUN = "dinov3-binary-v1-seed42"
67
+ RESULTS_REPO = "khalidsyfullah/sensitivity-student-results"
68
+ MODEL_REPO = "khalidsyfullah/sensitivity-student-models"
69
+ RUN_ID = "sensicontext-mobilevit075-v2-seed42"
70
+ # Keep this ID unchanged when resuming. Use a NEW ID after changing the recipe.
71
+ CFG = dict(
72
+ seed=42,
73
+ epochs=60, # Maximum, not a required number of epochs.
74
+ early_stopping_patience=3,
75
+ early_stopping_min_delta=1e-4,
76
+ early_stopping_min_epochs=15,
77
+ batch_size=2 if "T4" in GPU else (8 if "A100" in GPU else 4),
78
+ effective_batch_size=16,
79
+ workers=2,
80
+ decoder_channels=96,
81
+ encoder_lr=1e-4,
82
+ decoder_lr=1e-3,
83
+ weight_decay=0.01,
84
+ kd_weight=0.15,
85
+ kd_temperature=1.5,
86
+ kd_warmup_epochs=5,
87
+ kd_ramp_epochs=10,
88
+ lr_warmup_epochs=5,
89
+ auxiliary_weight=0.1,
90
+ boundary_weight=0.03,
91
+ parameter_cap=3_200_000,
92
+ maximum_background_fpr=0.10,
93
+ target_recall=0.95,
94
+ histogram_bins=1000,
95
+ bootstrap_samples=1000,
96
+ overlay_count_per_dataset=12,
97
+ save_probability_maps=False,
98
+ )
99
+ ROOT = Path("/content/sensitivity_student_04_v2")
100
+ ROOT.mkdir(parents=True, exist_ok=True)
101
+ RUN_ROOT = ROOT / RUN_ID
102
+ RUN_ROOT.mkdir(exist_ok=True)
103
+
104
+
105
+ def write_json(path, value):
106
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
107
+ Path(path).write_text(json.dumps(value, indent=2, allow_nan=False))
108
+
109
+
110
+ def digest_file(path):
111
+ h = hashlib.sha256()
112
+ with open(path, "rb") as f:
113
+ for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
114
+ h.update(block)
115
+ return h.hexdigest()
116
+
117
+
118
+ def fetch(repo, path, kind, revision):
119
+ return Path(
120
+ hf_hub_download(repo, path, repo_type=kind, revision=revision, token=HF_TOKEN)
121
+ )
122
+
123
+
124
+ def read_remote(repo, path, kind, revision):
125
+ return json.loads(fetch(repo, path, kind, revision).read_text())
126
+
127
+
128
+ def seed_all(seed):
129
+ random.seed(seed)
130
+ np.random.seed(seed)
131
+ torch.manual_seed(seed)
132
+ torch.cuda.manual_seed_all(seed)
133
+ torch.backends.cudnn.benchmark = False
134
+ torch.backends.cudnn.deterministic = True
135
+ torch.backends.cuda.matmul.allow_tf32 = False
136
+
137
+
138
+ def upload(folder, repo, kind, prefix):
139
+ commit = api.upload_folder(
140
+ repo_id=repo, repo_type=kind, folder_path=str(folder), path_in_repo=prefix
141
+ )
142
+ return commit.oid
143
+
144
+
145
+ for repo, kind in [(RESULTS_REPO, "dataset"), (MODEL_REPO, "model")]:
146
+ api.create_repo(repo_id=repo, repo_type=kind, private=True, exist_ok=True)
147
+ if not api.repo_info(repo, repo_type=kind).private:
148
+ raise RuntimeError(
149
+ f"{repo} is public. Use a private output repository for masks and image overlays."
150
+ )
151
+ print("GPU:", GPU, "precision:", AMP_DTYPE, "microbatch:", CFG["batch_size"])
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_06.txt ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 06
2
+ # Pin the teacher receipt and every input to immutable Hub commits.
3
+ SOURCE_REV = api.repo_info(TEACHER_RESULTS_REPO, repo_type="dataset").sha
4
+ receipt = read_remote(
5
+ TEACHER_RESULTS_REPO,
6
+ f"{TEACHER_RUN}/combined/combined_model_receipt.json",
7
+ "dataset",
8
+ SOURCE_REV,
9
+ )
10
+ TEACHER_REPO, TEACHER_REV, TEACHER_PREFIX = (
11
+ receipt["repo"],
12
+ receipt["revision"],
13
+ receipt["prefix"],
14
+ )
15
+ if TEACHER_PREFIX != f"{TEACHER_RUN}/combined":
16
+ raise ValueError("Unexpected teacher release.")
17
+ TEACHER_CONFIG = read_remote(
18
+ TEACHER_REPO, f"{TEACHER_PREFIX}/teacher_config.json", "model", TEACHER_REV
19
+ )
20
+ BACKBONE_CONFIG = read_remote(
21
+ TEACHER_REPO, f"{TEACHER_PREFIX}/backbone_config.json", "model", TEACHER_REV
22
+ )
23
+ TEACHER_WEIGHTS = fetch(
24
+ TEACHER_REPO, f"{TEACHER_PREFIX}/teacher.safetensors", "model", TEACHER_REV
25
+ )
26
+ if digest_file(TEACHER_WEIGHTS) != receipt["weights_sha256"]:
27
+ raise ValueError("Teacher checksum mismatch.")
28
+ PREPARED_REPO = TEACHER_CONFIG["prepared_repo"]
29
+ PREP_REVISION = TEACHER_CONFIG["prepared_revision"]
30
+ PREP_ID = TEACHER_CONFIG["prepared_id"]
31
+ PREP_PREFIX = f"releases/{PREP_ID}"
32
+ PREP = ROOT / "prepared" / PREP_ID
33
+ PREP.mkdir(parents=True, exist_ok=True)
34
+ for name in ["records.json", "preparation.json", "shards.json"]:
35
+ shutil.copy2(
36
+ fetch(PREPARED_REPO, f"{PREP_PREFIX}/{name}", "dataset", PREP_REVISION),
37
+ PREP / name,
38
+ )
39
+ ROWS = json.loads((PREP / "records.json").read_text())
40
+ teacher_plan = read_remote(
41
+ TEACHER_RESULTS_REPO, f"{TEACHER_RUN}/run_plan.json", "dataset", SOURCE_REV
42
+ )
43
+ if teacher_plan["split_manifest_sha256"] != digest_file(PREP / "records.json"):
44
+ raise ValueError("Prepared records differ from the teacher training manifest.")
45
+ if teacher_plan["plan_sha256"] != TEACHER_CONFIG["plan_sha256"]:
46
+ raise ValueError(
47
+ "Teacher model and reported results belong to different training plans."
48
+ )
49
+ PREPARATION = json.loads((PREP / "preparation.json").read_text())
50
+ CFG["image_size"] = TEACHER_CONFIG["recipe"]["image_size"]
51
+ CFG["normalization_mean"] = TEACHER_CONFIG["recipe"]["normalization_mean"]
52
+ CFG["normalization_std"] = TEACHER_CONFIG["recipe"]["normalization_std"]
53
+ MEAN = np.array(CFG["normalization_mean"], dtype=np.float32).reshape(1, 1, 3)
54
+ STD = np.array(CFG["normalization_std"], dtype=np.float32).reshape(1, 1, 3)
55
+
56
+ for shard in tqdm(
57
+ json.loads((PREP / "shards.json").read_text()), desc="Download prepared shards"
58
+ ):
59
+ archive = fetch(
60
+ PREPARED_REPO, f"{PREP_PREFIX}/{shard['path']}", "dataset", PREP_REVISION
61
+ )
62
+ if digest_file(archive) != shard["sha256"]:
63
+ raise ValueError("Prepared shard checksum mismatch.")
64
+ marker = PREP / (shard["path"] + ".extracted")
65
+ if not marker.exists():
66
+ with tarfile.open(archive) as tf:
67
+ for member in tf.getmembers():
68
+ target = (PREP / member.name).resolve()
69
+ if not target.is_relative_to(PREP.resolve()) or not (
70
+ member.isfile() or member.isdir()
71
+ ):
72
+ raise ValueError("Unsafe archive member.")
73
+ tf.extractall(PREP, filter="data")
74
+ marker.write_text(shard["sha256"])
75
+
76
+ ids = [r["id"] for r in ROWS]
77
+ if len(ids) != len(set(ids)):
78
+ raise ValueError("Duplicate record IDs.")
79
+ for key in ["group", "sha256_pixels"]:
80
+ seen = {}
81
+ for r in ROWS:
82
+ if r[key] in seen and seen[r[key]] != r["split"]:
83
+ raise ValueError(f"{key} crosses splits.")
84
+ seen[r[key]] = r["split"]
85
+ if set(r["split"] for r in ROWS) != {"train", "validation", "test"}:
86
+ raise ValueError("Missing or unexpected split.")
87
+ for r in tqdm(ROWS, desc="Verify prepared images and masks"):
88
+ for path_key, hash_key in [
89
+ ("image", "image_sha256"),
90
+ ("mask_native", "mask_sha256"),
91
+ ("mask_train", "training_mask_sha256"),
92
+ ]:
93
+ p = (PREP / r[path_key]).resolve()
94
+ if not p.is_relative_to(PREP.resolve()) or digest_file(p) != r[hash_key]:
95
+ raise ValueError(f'Invalid file: {r["id"]}')
96
+ with Image.open(PREP / r["mask_train"]) as mask:
97
+ a = np.asarray(mask)
98
+ if (
99
+ a.shape != (CFG["image_size"], CFG["image_size"])
100
+ or not np.isin(a, [0, 1]).all()
101
+ ):
102
+ raise ValueError("Expected prepared square 0/1 training masks.")
103
+ SPLITS = {
104
+ s: [r for r in ROWS if r["split"] == s] for s in ["train", "validation", "test"]
105
+ }
106
+ teacher_splits = read_remote(
107
+ TEACHER_RESULTS_REPO,
108
+ f"{TEACHER_RUN}/combined/split_ids.json",
109
+ "dataset",
110
+ SOURCE_REV,
111
+ )
112
+ for s, records in SPLITS.items():
113
+ if set(teacher_splits[s]) != {r["id"] for r in records}:
114
+ raise ValueError(f"Teacher/student {s} split differs.")
115
+ if {r["dataset"] for r in records} != {"visual_redactions", "biv_priv_seg"}:
116
+ raise ValueError("Both domains required in each split.")
117
+ write_json(
118
+ RUN_ROOT / "split_ids.json", {s: [r["id"] for r in rr] for s, rr in SPLITS.items()}
119
+ )
120
+ write_json(
121
+ RUN_ROOT / "source_provenance.json",
122
+ dict(
123
+ teacher_receipt=receipt,
124
+ teacher_results_revision=SOURCE_REV,
125
+ teacher_config=TEACHER_CONFIG,
126
+ prepared_repo=PREPARED_REPO,
127
+ prepared_revision=PREP_REVISION,
128
+ prepared_id=PREP_ID,
129
+ records_sha256=digest_file(PREP / "records.json"),
130
+ preparation=PREPARATION,
131
+ ),
132
+ )
133
+ display(
134
+ pd.crosstab(
135
+ pd.Series([r["dataset"] for r in ROWS], name="dataset"),
136
+ pd.Series([r["split"] for r in ROWS], name="split"),
137
+ )
138
+ )
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_07.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 07
2
+ # This immutable revision was checked when preparing the notebook.
3
+ ENCODER_REPO = "timm/mobilevitv2_075.cvnets_in1k"
4
+ ENCODER_REVISION = "a569b246b7d503850160fa5dd87fb35a485fa6fe"
5
+ ENCODER_WEIGHTS = fetch(ENCODER_REPO, "model.safetensors", "model", ENCODER_REVISION)
6
+ ENCODER_PROVENANCE = {
7
+ "repo": ENCODER_REPO,
8
+ "revision": ENCODER_REVISION,
9
+ "weights_sha256": digest_file(ENCODER_WEIGHTS),
10
+ "pretraining": "ImageNet-1k",
11
+ "encoder_input_mean": [0.0, 0.0, 0.0],
12
+ "encoder_input_std": [1.0, 1.0, 1.0],
13
+ }
14
+ print("Pinned pretrained encoder:", ENCODER_REPO, ENCODER_REVISION)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_09.txt ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%writefile student_model.py
2
+ # MODULE04_CELL: 09
3
+ """SensiContextNet: pretrained context encoder and custom lightweight decoder."""
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ import timm
9
+
10
+
11
+ class DecoderConv(nn.Sequential):
12
+ """Batch-size-independent decoder convolution."""
13
+
14
+ def __init__(self, in_channels, out_channels, kernel_size=1, groups=1):
15
+ super().__init__(
16
+ nn.Conv2d(
17
+ in_channels,
18
+ out_channels,
19
+ kernel_size,
20
+ padding=kernel_size // 2,
21
+ groups=groups,
22
+ bias=False,
23
+ ),
24
+ nn.GroupNorm(8, out_channels),
25
+ nn.SiLU(inplace=True),
26
+ )
27
+
28
+
29
+ class SpatialRefinement(nn.Module):
30
+ def __init__(self, channels):
31
+ super().__init__()
32
+ self.depthwise = DecoderConv(channels, channels, 3, groups=channels)
33
+ self.pointwise = DecoderConv(channels, channels)
34
+
35
+ def forward(self, features):
36
+ return features + self.pointwise(self.depthwise(features))
37
+
38
+
39
+ class ContextFusion(nn.Module):
40
+ """Cheap top-down fusion with normalized, learned nonnegative weights."""
41
+
42
+ def __init__(self, skip_channels, channels):
43
+ super().__init__()
44
+ self.lateral = DecoderConv(skip_channels, channels)
45
+ self.weights = nn.Parameter(torch.zeros(2))
46
+ self.refine = SpatialRefinement(channels)
47
+
48
+ def forward(self, coarse, skip):
49
+ coarse = F.interpolate(
50
+ coarse, size=skip.shape[-2:], mode="bilinear", align_corners=False
51
+ )
52
+ weights = self.weights.softmax(dim=0)
53
+ fused = weights[0] * coarse + weights[1] * self.lateral(skip)
54
+ return self.refine(fused)
55
+
56
+
57
+ class SensitivityStudent(nn.Module):
58
+ """Custom binary segmenter. The MobileViTv2 encoder is an existing architecture.
59
+
60
+ Input uses the saved teacher's normalization. Buffers reverse it for the
61
+ pretrained encoder, which expects RGB values in [0, 1]. No teacher is needed
62
+ at inference. The auxiliary heads are executed only by forward_train().
63
+ """
64
+
65
+ def __init__(self, channels=96, pretrained=False, encoder_checkpoint=None):
66
+ super().__init__()
67
+ if pretrained and encoder_checkpoint is None:
68
+ raise ValueError(
69
+ "Provide the pinned local encoder checkpoint for initialization."
70
+ )
71
+ options = {}
72
+ if pretrained:
73
+ options["pretrained_cfg_overlay"] = {
74
+ "file": str(encoder_checkpoint),
75
+ "hf_hub_id": "",
76
+ }
77
+ self.encoder = timm.create_model(
78
+ "mobilevitv2_075.cvnets_in1k",
79
+ pretrained=pretrained,
80
+ features_only=True,
81
+ out_indices=(1, 2, 3, 4),
82
+ **options
83
+ )
84
+ feature_channels = self.encoder.feature_info.channels()
85
+ if self.encoder.feature_info.reduction() != [4, 8, 16, 32]:
86
+ raise RuntimeError("Unexpected encoder feature strides.")
87
+ self.register_buffer(
88
+ "input_mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
89
+ )
90
+ self.register_buffer(
91
+ "input_std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
92
+ )
93
+ self.coarse = DecoderConv(feature_channels[-1], channels)
94
+ self.context = DecoderConv(channels, channels, 7, groups=channels)
95
+ self.global_gate = nn.Sequential(
96
+ nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels, 1), nn.Sigmoid()
97
+ )
98
+ self.fusions = nn.ModuleList(
99
+ [ContextFusion(skip, channels) for skip in reversed(feature_channels[:-1])]
100
+ )
101
+ # A narrow image-detail path supplies edges without a wide stride-2 decoder.
102
+ self.detail = nn.Sequential(
103
+ nn.Conv2d(3, 16, 3, stride=2, padding=1, bias=False),
104
+ nn.GroupNorm(8, 16),
105
+ nn.SiLU(),
106
+ nn.Conv2d(16, 32, 3, stride=2, padding=1, bias=False),
107
+ nn.GroupNorm(8, 32),
108
+ nn.SiLU(),
109
+ )
110
+ self.detail_fuse = nn.Sequential(
111
+ DecoderConv(channels + 32, channels + 32, 3, groups=channels + 32),
112
+ DecoderConv(channels + 32, 64),
113
+ SpatialRefinement(64),
114
+ )
115
+ self.head = nn.Conv2d(64, 1, 1)
116
+ self.aux_heads = nn.ModuleList([nn.Conv2d(channels, 1, 1) for _ in range(2)])
117
+ self.boundary_head = nn.Conv2d(64, 1, 1)
118
+
119
+ def train(self, mode=True):
120
+ super().train(mode)
121
+ # Pretrained BN running statistics remain stable even with a T4 microbatch of 2.
122
+ # Affine BN parameters still receive gradients.
123
+ for layer in self.encoder.modules():
124
+ if isinstance(layer, nn.BatchNorm2d):
125
+ layer.eval()
126
+ return self
127
+
128
+ def _decode(self, inputs):
129
+ rgb = inputs * self.input_std + self.input_mean
130
+ features = self.encoder(rgb)
131
+ coarse = self.coarse(features[-1])
132
+ coarse = coarse + self.context(coarse) * self.global_gate(coarse)
133
+ decoded = []
134
+ for fusion, skip in zip(self.fusions, reversed(features[:-1])):
135
+ coarse = fusion(coarse, skip)
136
+ decoded.append(coarse)
137
+ detail = self.detail(rgb)
138
+ detail = F.interpolate(
139
+ detail, size=coarse.shape[-2:], mode="bilinear", align_corners=False
140
+ )
141
+ fine = self.detail_fuse(torch.cat([coarse, detail], dim=1))
142
+ return fine, decoded
143
+
144
+ def forward(self, inputs):
145
+ fine, _ = self._decode(inputs)
146
+ return F.interpolate(
147
+ self.head(fine),
148
+ size=inputs.shape[-2:],
149
+ mode="bilinear",
150
+ align_corners=False,
151
+ )
152
+
153
+ def forward_train(self, inputs):
154
+ fine, decoded = self._decode(inputs)
155
+ logits = F.interpolate(
156
+ self.head(fine),
157
+ size=inputs.shape[-2:],
158
+ mode="bilinear",
159
+ align_corners=False,
160
+ )
161
+ auxiliary = [
162
+ head(feature) for head, feature in zip(self.aux_heads, decoded[:2])
163
+ ]
164
+ return logits, auxiliary, self.boundary_head(fine)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_10.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # MODULE04_CELL: 10
2
+ from student_model import SensitivityStudent
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_12.txt ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%writefile inference.py
2
+ # MODULE04_CELL: 12
3
+ from pathlib import Path
4
+ import json
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn import functional as F
8
+ from PIL import Image, ImageOps
9
+ from safetensors.torch import load_file
10
+ from student_model import SensitivityStudent
11
+
12
+
13
+ def load_student(directory, device="cpu"):
14
+ directory = Path(directory)
15
+ config = json.loads((directory / "student_config.json").read_text())
16
+ model = SensitivityStudent(config["decoder_channels"])
17
+ model.load_state_dict(
18
+ load_file(str(directory / "student.safetensors")), strict=True
19
+ )
20
+ return model.to(device).eval(), config
21
+
22
+
23
+ @torch.inference_mode()
24
+ def predict_image(model, config, image, threshold=None):
25
+ if not isinstance(image, Image.Image):
26
+ image = Image.open(image)
27
+ image = ImageOps.exif_transpose(image).convert("RGB")
28
+ w, h = image.size
29
+ size = config["image_size"]
30
+ ratio = min(size / w, size / h)
31
+ nw = max(1, round(w * ratio))
32
+ nh = max(1, round(h * ratio))
33
+ canvas = Image.new("RGB", (size, size), (124, 116, 104))
34
+ canvas.paste(image.resize((nw, nh), Image.Resampling.BILINEAR), (0, 0))
35
+ a = np.asarray(canvas, dtype=np.float32) / 255.0
36
+ mean = np.asarray(config["normalization_mean"], dtype=np.float32)
37
+ std = np.asarray(config["normalization_std"], dtype=np.float32)
38
+ x = torch.from_numpy(((a - mean) / std).transpose(2, 0, 1).copy())[None].to(
39
+ next(model.parameters()).device
40
+ )
41
+ dtype = torch.bfloat16 if config.get("amp") == "torch.bfloat16" else torch.float16
42
+ with torch.autocast(x.device.type, dtype=dtype, enabled=x.device.type == "cuda"):
43
+ logits = model(x)
44
+ p = logits.float().sigmoid()[:, :, :nh, :nw]
45
+ p = (
46
+ F.interpolate(p, size=(h, w), mode="bilinear", align_corners=False)[0, 0]
47
+ .cpu()
48
+ .numpy()
49
+ )
50
+ t = config["threshold"] if threshold is None else threshold
51
+ return {"probability": p, "mask": (p >= t).astype(np.uint8), "threshold": t}
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_14.txt ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 14
2
+ class ConvBlock(nn.Sequential):
3
+ def __init__(self, channels):
4
+ super().__init__(
5
+ nn.Conv2d(channels, channels, 3, padding=1, bias=False),
6
+ nn.GroupNorm(8, channels),
7
+ nn.GELU(),
8
+ nn.Conv2d(channels, channels, 3, padding=1, bias=False),
9
+ nn.GroupNorm(8, channels),
10
+ nn.GELU(),
11
+ )
12
+
13
+
14
+ class SensitivityTeacher(nn.Module):
15
+ def __init__(self, config, encoder_config=None):
16
+ super().__init__()
17
+ self.recipe = dict(config)
18
+ if encoder_config is None:
19
+ self.encoder = AutoModel.from_pretrained(
20
+ config["backbone"],
21
+ revision=config["backbone_revision"],
22
+ token=HF_TOKEN,
23
+ attn_implementation="sdpa",
24
+ )
25
+ else:
26
+ encoder_config = dict(encoder_config)
27
+ model_type = encoder_config.pop("model_type")
28
+ self.encoder = AutoModel.from_config(
29
+ AutoConfig.for_model(model_type, **encoder_config),
30
+ attn_implementation="sdpa",
31
+ )
32
+ dim = self.encoder.config.hidden_size
33
+ c = config["decoder_channels"]
34
+ self.project = nn.ModuleList(
35
+ [nn.Conv2d(dim, c, 1) for _ in config["feature_layers"]]
36
+ )
37
+ self.fuse = nn.ModuleList([ConvBlock(c) for _ in range(4)])
38
+ self.head = nn.Conv2d(c, 1, 1)
39
+ if self.encoder.config.patch_size != 16:
40
+ raise ValueError("This recipe expects 16px patches")
41
+ for p in self.encoder.parameters():
42
+ p.requires_grad = False
43
+
44
+ def set_epoch(self, epoch):
45
+ for p in self.encoder.parameters():
46
+ p.requires_grad = False
47
+ n = (
48
+ self.recipe["unfreeze_last_blocks"]
49
+ if epoch >= self.recipe["warmup_epochs"]
50
+ else 0
51
+ )
52
+ if n:
53
+ for block in self.encoder.layer[-n:]:
54
+ for p in block.parameters():
55
+ p.requires_grad = True
56
+ # Keep pretrained positional stochastic augmentation disabled, even while fine-tuning.
57
+ self.encoder.eval()
58
+
59
+ def train(self, mode=True):
60
+ super().train(mode)
61
+ self.encoder.eval()
62
+ return self
63
+
64
+ def forward(self, x):
65
+ gh, gw = x.shape[-2] // 16, x.shape[-1] // 16
66
+ grad = any(p.requires_grad for p in self.encoder.parameters()) and self.training
67
+ with nullcontext() if grad else torch.no_grad():
68
+ states = self.encoder(
69
+ pixel_values=x, output_hidden_states=True
70
+ ).hidden_states
71
+ features = []
72
+ for layer, project, stride in zip(
73
+ self.recipe["feature_layers"], self.project, [4, 8, 16, 32]
74
+ ):
75
+ tokens = states[layer][:, 1 + self.encoder.config.num_register_tokens :, :]
76
+ if tokens.shape[1] != gh * gw:
77
+ raise RuntimeError("Unexpected patch-token count")
78
+ tokens = F.layer_norm(tokens, (tokens.shape[-1],))
79
+ feature = project(tokens.transpose(1, 2).reshape(x.shape[0], -1, gh, gw))
80
+ features.append(
81
+ F.interpolate(
82
+ feature,
83
+ size=(x.shape[-2] // stride, x.shape[-1] // stride),
84
+ mode="bilinear",
85
+ align_corners=False,
86
+ )
87
+ )
88
+ fused = self.fuse[3](features[3])
89
+ for idx in [2, 1, 0]:
90
+ fused = self.fuse[idx](
91
+ F.interpolate(
92
+ fused,
93
+ size=features[idx].shape[-2:],
94
+ mode="bilinear",
95
+ align_corners=False,
96
+ )
97
+ + features[idx]
98
+ )
99
+ return F.interpolate(
100
+ self.head(fused), size=x.shape[-2:], mode="bilinear", align_corners=False
101
+ )
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_16.txt ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 16
2
+ class SensitivityDataset(Dataset):
3
+ def __init__(self, records, augment=False, epoch=0):
4
+ self.records = records
5
+ self.augment = augment
6
+ self.epoch = epoch
7
+
8
+ def __len__(self):
9
+ return len(self.records)
10
+
11
+ def __getitem__(self, index):
12
+ r = self.records[index]
13
+ image = (
14
+ np.asarray(Image.open(PREP / r["image"]).convert("RGB"), dtype=np.float32)
15
+ / 255.0
16
+ )
17
+ if self.augment:
18
+ # Same image receives identical augmentation in both arms, including on resume.
19
+ salt = hashlib.sha256(
20
+ f"{CFG['seed']}:{self.epoch}:{r['id']}".encode()
21
+ ).digest()
22
+ rng = np.random.default_rng(int.from_bytes(salt[:8], "little"))
23
+ image = np.clip((image - 0.5) * rng.uniform(0.9, 1.1) + 0.5, 0, 1)
24
+ image = np.clip(image * rng.uniform(0.9, 1.1), 0, 1)
25
+ image = (image - MEAN) / STD
26
+ mask = np.asarray(Image.open(PREP / r["mask_train"]), dtype=np.float32)
27
+ valid = np.zeros_like(mask)
28
+ valid[: r["nh"], : r["nw"]] = 1
29
+ return (
30
+ torch.from_numpy(image.transpose(2, 0, 1).copy()),
31
+ torch.from_numpy(mask[None].copy()),
32
+ torch.from_numpy(valid[None]),
33
+ index,
34
+ )
35
+
36
+
37
+ def loader(records, training=False, balanced=False, epoch=0):
38
+ generator = torch.Generator().manual_seed(CFG["seed"] + epoch)
39
+ sampler = None
40
+ if balanced:
41
+ counts = Counter(r["dataset"] for r in records)
42
+ sampler = WeightedRandomSampler(
43
+ [1 / counts[r["dataset"]] for r in records],
44
+ len(records),
45
+ replacement=True,
46
+ generator=generator,
47
+ )
48
+ return DataLoader(
49
+ SensitivityDataset(records, training, epoch),
50
+ batch_size=CFG["batch_size"],
51
+ sampler=sampler,
52
+ shuffle=training and sampler is None,
53
+ generator=generator,
54
+ num_workers=CFG["workers"],
55
+ pin_memory=True,
56
+ persistent_workers=False,
57
+ )
58
+
59
+
60
+ def segmentation_loss(logits, target, valid):
61
+ logits = logits.float()
62
+ target = target.float()
63
+ valid = valid.float()
64
+ bce = (
65
+ F.binary_cross_entropy_with_logits(logits, target, reduction="none") * valid
66
+ ).sum((1, 2, 3)) / valid.sum((1, 2, 3)).clamp_min(1)
67
+ p = logits.sigmoid() * valid
68
+ y = target * valid
69
+ dice = (2 * (p * y).sum((1, 2, 3)) + 1) / (p.sum((1, 2, 3)) + y.sum((1, 2, 3)) + 1)
70
+ return (bce + 1 - dice).mean(), dice.detach()
71
+
72
+
73
+ def boundary_supervision(boundary_logits, target, valid):
74
+ # Build boundaries at their prediction resolution. Remove invalid-padding neighbors.
75
+ size = boundary_logits.shape[-2:]
76
+ y = F.interpolate(target.float(), size=size, mode="nearest")
77
+ v = (F.adaptive_avg_pool2d(valid.float(), size) >= 0.999).float()
78
+ eroded_valid = 1 - F.max_pool2d(F.pad(1 - v, (1, 1, 1, 1), value=1), 3, stride=1)
79
+ outer = F.max_pool2d(y, 3, stride=1, padding=1)
80
+ inner = 1 - F.max_pool2d(1 - y, 3, stride=1, padding=1)
81
+ edge = (outer - inner).clamp(0, 1)
82
+ return segmentation_loss(boundary_logits, edge, eroded_valid)[0]
83
+
84
+
85
+ def supervised_objective(logits, auxiliary, boundary, target, valid):
86
+ main, _ = segmentation_loss(logits, target, valid)
87
+ losses = []
88
+ for aux in auxiliary:
89
+ y = F.interpolate(target, size=aux.shape[-2:], mode="nearest")
90
+ v = (F.adaptive_avg_pool2d(valid, aux.shape[-2:]) >= 0.999).float()
91
+ losses.append(segmentation_loss(aux, y, v)[0])
92
+ auxiliary_loss = torch.stack(losses).mean()
93
+ boundary_loss = boundary_supervision(boundary, target, valid)
94
+ return (
95
+ main
96
+ + CFG["auxiliary_weight"] * auxiliary_loss
97
+ + CFG["boundary_weight"] * boundary_loss
98
+ )
99
+
100
+
101
+ def distillation_loss(student_logits, teacher_logits, target, valid):
102
+ # Ground-truth-conditioned reliability reduces imitation of teacher annotation errors.
103
+ t = CFG["kd_temperature"]
104
+ s = student_logits.float() / t
105
+ teacher_logits = teacher_logits.detach().float()
106
+ p = (teacher_logits / t).sigmoid().clamp(1e-6, 1 - 1e-6)
107
+ entropy = -(p * p.log() + (1 - p) * torch.log1p(-p))
108
+ kl = (
109
+ F.binary_cross_entropy_with_logits(s, p, reduction="none") - entropy
110
+ ).clamp_min(0)
111
+ truth = target.float()
112
+ q = teacher_logits.sigmoid()
113
+ agreement = truth * q + (1 - truth) * (1 - q)
114
+ weighted = kl * agreement
115
+ # Equal foreground/background means per image when both regions exist.
116
+ terms = []
117
+ present = []
118
+ for region in [truth, 1 - truth]:
119
+ mask = region * valid
120
+ count = mask.sum((1, 2, 3))
121
+ terms.append((weighted * mask).sum((1, 2, 3)) / count.clamp_min(1))
122
+ present.append((count > 0).float())
123
+ numerator = terms[0] * present[0] + terms[1] * present[1]
124
+ return t * t * (numerator / (present[0] + present[1]).clamp_min(1)).mean()
125
+
126
+
127
+ @torch.no_grad()
128
+ def validation_score(model, records):
129
+ """Equal-domain pixel IoU at 0.5 on the valid prepared grid, validation only."""
130
+ model.eval()
131
+ totals = defaultdict(lambda: np.zeros(3, dtype=np.int64))
132
+ for images, targets, valid, indices in loader(records):
133
+ with torch.autocast("cuda", dtype=AMP_DTYPE):
134
+ logits = model(images.to(DEVICE))
135
+ predicted = logits.float().sigmoid().cpu() >= 0.5
136
+ truth = targets.bool()
137
+ usable = valid.bool()
138
+ for offset, index in enumerate(indices.tolist()):
139
+ prediction = predicted[offset]
140
+ target = truth[offset]
141
+ region = usable[offset]
142
+ counts = [
143
+ (prediction & target & region).sum().item(),
144
+ (prediction & ~target & region).sum().item(),
145
+ (~prediction & target & region).sum().item(),
146
+ ]
147
+ totals[records[index]["dataset"]] += np.asarray(counts)
148
+ scores = {
149
+ domain: float(tp / max(1, tp + fp + fn))
150
+ for domain, (tp, fp, fn) in totals.items()
151
+ }
152
+ return float(np.mean(list(scores.values()))), scores
153
+
154
+
155
+ def load_teacher():
156
+ teacher = SensitivityTeacher(TEACHER_CONFIG["recipe"], BACKBONE_CONFIG)
157
+ teacher.load_state_dict(load_file(str(TEACHER_WEIGHTS)), strict=True)
158
+ teacher.requires_grad_(False)
159
+ teacher.eval()
160
+ return teacher.to(DEVICE)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_18.txt ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 18
2
+ @torch.no_grad()
3
+ def native_predictions(model, records):
4
+ model.eval()
5
+ for x, _, _, indices in loader(records):
6
+ with torch.autocast("cuda", dtype=AMP_DTYPE):
7
+ logits = model(x.to(DEVICE))
8
+ probability = logits.float().sigmoid().cpu()
9
+ for offset, index in enumerate(indices.tolist()):
10
+ r = records[index]
11
+ cropped = probability[offset : offset + 1, :, : r["nh"], : r["nw"]]
12
+ native = F.interpolate(
13
+ cropped,
14
+ size=(r["height"], r["width"]),
15
+ mode="bilinear",
16
+ align_corners=False,
17
+ )[0, 0].numpy()
18
+ truth = np.asarray(
19
+ Image.open(PREP / r["mask_native"]), dtype=np.uint8
20
+ ).astype(bool)
21
+ yield r, native, truth
22
+
23
+
24
+ def metrics_from_counts(tp, fp, fn, tn):
25
+ def ratio(n, d):
26
+ return float(n / d) if d else None
27
+
28
+ total = tp + fp + fn + tn
29
+ return {
30
+ "iou": ratio(tp, tp + fp + fn),
31
+ "dice": ratio(2 * tp, 2 * tp + fp + fn),
32
+ "precision": ratio(tp, tp + fp),
33
+ "recall": ratio(tp, tp + fn),
34
+ "background_fpr": ratio(fp, fp + tn),
35
+ "predicted_fraction": ratio(tp + fp, total),
36
+ "true_sensitive_fraction": ratio(tp + fn, total),
37
+ }
38
+
39
+
40
+ def choose_operating_point(curves, target, maximum_fpr):
41
+ """Return None when recall and FPR requirements cannot be met together."""
42
+ eligible = [
43
+ row
44
+ for row in curves
45
+ if 0 < row["threshold"] < 1
46
+ and all(
47
+ values["recall"] is not None
48
+ and values["recall"] >= target
49
+ and values["background_fpr"] is not None
50
+ and values["background_fpr"] <= maximum_fpr
51
+ for values in row["domains"].values()
52
+ )
53
+ ]
54
+ if not eligible:
55
+ return None
56
+ return min(
57
+ eligible,
58
+ key=lambda row: (
59
+ np.mean([v["background_fpr"] for v in row["domains"].values()]),
60
+ -row["threshold"],
61
+ ),
62
+ )
63
+
64
+
65
+ def calibrate(model, records, out):
66
+ bins = CFG["histogram_bins"]
67
+ hist = {
68
+ d: np.zeros((2, bins + 1), dtype=np.int64)
69
+ for d in {r["dataset"] for r in records}
70
+ }
71
+ for r, p, y in tqdm(
72
+ native_predictions(model, records),
73
+ total=len(records),
74
+ desc="Validation threshold calibration",
75
+ ):
76
+ index = np.minimum((p * bins).astype(np.int32), bins)
77
+ hist[r["dataset"]][1] += np.bincount(index[y], minlength=bins + 1)
78
+ hist[r["dataset"]][0] += np.bincount(index[~y], minlength=bins + 1)
79
+ curves = []
80
+ flat = []
81
+ tails = {d: h[:, ::-1].cumsum(axis=1)[:, ::-1] for d, h in hist.items()}
82
+ for j in range(bins + 1):
83
+ domains = {}
84
+ for d, h in hist.items():
85
+ tp = int(tails[d][1, j])
86
+ fp = int(tails[d][0, j])
87
+ fn = int(h[1].sum() - tp)
88
+ tn = int(h[0].sum() - fp)
89
+ domains[d] = metrics_from_counts(tp, fp, fn, tn)
90
+ flat.append({"dataset": d, "threshold": j / bins, **domains[d]})
91
+ curves.append({"threshold": j / bins, "domains": domains})
92
+ candidates = [row for row in curves if 0 < row["threshold"] < 1]
93
+ best_iou = max(
94
+ candidates,
95
+ key=lambda row: (
96
+ np.mean([v["iou"] or 0 for v in row["domains"].values()]),
97
+ -abs(row["threshold"] - 0.5),
98
+ ),
99
+ )
100
+ constrained = choose_operating_point(
101
+ curves, CFG["target_recall"], CFG["maximum_background_fpr"]
102
+ )
103
+ thresholds = {"fixed_0.5": 0.5, "validation_best_iou": best_iou["threshold"]}
104
+ if constrained is not None:
105
+ thresholds["recall_constrained"] = constrained["threshold"]
106
+ else:
107
+ print(
108
+ "INFEASIBLE: no validation threshold meets both the recall target "
109
+ "and FPR cap in every domain. No recall-constrained test result will be claimed."
110
+ )
111
+ report = {
112
+ "thresholds": thresholds,
113
+ "deployment_operating_point": "validation_best_iou",
114
+ "validation_best_iou": best_iou,
115
+ "recall_constraint_feasible": constrained is not None,
116
+ "recall_constrained": constrained,
117
+ "target_recall": CFG["target_recall"],
118
+ "maximum_background_fpr": CFG["maximum_background_fpr"],
119
+ "selection_data": "validation only; equal-domain pixel metrics",
120
+ "histogram_resolution": 1 / bins,
121
+ }
122
+ write_json(out / "calibration.json", report)
123
+ pd.DataFrame(flat).to_csv(out / "validation_threshold_curve.csv", index=False)
124
+ return thresholds
125
+
126
+
127
+ def group_bootstrap(frame):
128
+ grouped = (
129
+ frame.groupby("group")[["tp", "fp", "fn", "tn"]].sum().to_numpy(dtype=np.int64)
130
+ )
131
+ rng = np.random.default_rng(CFG["seed"])
132
+ sampled = defaultdict(list)
133
+ for _ in range(CFG["bootstrap_samples"]):
134
+ totals = grouped[rng.integers(0, len(grouped), len(grouped))].sum(axis=0)
135
+ for name, value in metrics_from_counts(*totals).items():
136
+ if value is not None:
137
+ sampled[name].append(value)
138
+ return {
139
+ name: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))]
140
+ for name, v in sampled.items()
141
+ }
142
+
143
+
144
+ def write_overlay(r, probability, truth, threshold, path):
145
+ base = np.asarray(Image.open(PREP / r["image"]).convert("RGB"))[
146
+ : r["nh"], : r["nw"]
147
+ ]
148
+ size = (r["nw"], r["nh"])
149
+ gt = np.asarray(
150
+ Image.fromarray(truth.astype("uint8")).resize(size, Image.Resampling.NEAREST)
151
+ ).astype(bool)
152
+ pred = np.asarray(
153
+ Image.fromarray((probability >= threshold).astype("uint8")).resize(
154
+ size, Image.Resampling.NEAREST
155
+ )
156
+ ).astype(bool)
157
+
158
+ def overlay(mask):
159
+ result = base.astype(np.float32).copy()
160
+ result[mask] = 0.5 * result[mask] + 0.5 * np.array([255, 0, 0])
161
+ return result.astype("uint8")
162
+
163
+ fig, axes = plt.subplots(1, 3, figsize=(12, 4))
164
+ for axis, image, title in zip(
165
+ axes,
166
+ [base, overlay(gt), overlay(pred)],
167
+ ["Image", "Annotated sensitivity", "Predicted sensitivity"],
168
+ ):
169
+ axis.imshow(image)
170
+ axis.set_title(title)
171
+ axis.axis("off")
172
+ fig.suptitle(r["id"])
173
+ fig.tight_layout()
174
+ fig.savefig(path, dpi=130)
175
+ plt.close(fig)
176
+
177
+
178
+ def evaluate_test(model, records, thresholds, out):
179
+ threshold = thresholds["validation_best_iou"]
180
+ out.mkdir(parents=True, exist_ok=True)
181
+ (out / "overlays").mkdir(exist_ok=True)
182
+ selected = set()
183
+ for domain in {r["dataset"] for r in records}:
184
+ rr = sorted(
185
+ [r for r in records if r["dataset"] == domain], key=lambda r: r["id"]
186
+ )
187
+ selected.update(
188
+ rr[i]["id"]
189
+ for i in np.linspace(
190
+ 0,
191
+ len(rr) - 1,
192
+ min(len(rr), CFG["overlay_count_per_dataset"]),
193
+ dtype=int,
194
+ )
195
+ )
196
+ result = []
197
+ with zipfile.ZipFile(
198
+ out / "test_binary_masks.zip", "w", compression=zipfile.ZIP_DEFLATED
199
+ ) as masks:
200
+ probability_zip = (
201
+ zipfile.ZipFile(
202
+ out / "test_probabilities.zip", "w", compression=zipfile.ZIP_DEFLATED
203
+ )
204
+ if CFG["save_probability_maps"]
205
+ else None
206
+ )
207
+ try:
208
+ for r, p, y in tqdm(
209
+ native_predictions(model, records),
210
+ total=len(records),
211
+ desc="Held-out test evaluation",
212
+ ):
213
+ for label, t in thresholds.items():
214
+ pred = p >= t
215
+ tp = int(np.count_nonzero(pred & y))
216
+ fp = int(np.count_nonzero(pred & ~y))
217
+ fn = int(np.count_nonzero(~pred & y))
218
+ tn = int(np.count_nonzero(~pred & ~y))
219
+ result.append(
220
+ {
221
+ "id": r["id"],
222
+ "group": r["group"],
223
+ "dataset": r["dataset"],
224
+ "operating_point": label,
225
+ "threshold": t,
226
+ "tp": tp,
227
+ "fp": fp,
228
+ "fn": fn,
229
+ "tn": tn,
230
+ "categories": "|".join(r["categories"]),
231
+ **metrics_from_counts(tp, fp, fn, tn),
232
+ }
233
+ )
234
+ buffer = io.BytesIO()
235
+ Image.fromarray((p >= threshold).astype("uint8")).save(
236
+ buffer, format="PNG"
237
+ )
238
+ masks.writestr(f"{r['dataset']}/{r['id']}.png", buffer.getvalue())
239
+ if probability_zip:
240
+ buffer = io.BytesIO()
241
+ np.save(buffer, p.astype(np.float16), allow_pickle=False)
242
+ probability_zip.writestr(
243
+ f"{r['dataset']}/{r['id']}.npy", buffer.getvalue()
244
+ )
245
+ if r["id"] in selected:
246
+ write_overlay(
247
+ r, p, y, threshold, out / "overlays" / f"{r['id']}.png"
248
+ )
249
+ finally:
250
+ if probability_zip:
251
+ probability_zip.close()
252
+ frame = pd.DataFrame(result)
253
+ frame.to_csv(out / "per_image_test_metrics.csv", index=False)
254
+ summaries = []
255
+ for (domain, point), part in frame.groupby(["dataset", "operating_point"]):
256
+ values = metrics_from_counts(*part[["tp", "fp", "fn", "tn"]].sum().to_numpy())
257
+ summaries.append(
258
+ {
259
+ "dataset": domain,
260
+ "operating_point": point,
261
+ "images": len(part),
262
+ "groups": part.group.nunique(),
263
+ "threshold": float(part.threshold.iloc[0]),
264
+ "pixel_micro": values,
265
+ "image_macro": {
266
+ k: float(part[k].mean()) if part[k].notna().any() else None
267
+ for k in values
268
+ },
269
+ "group_bootstrap_95ci": group_bootstrap(part),
270
+ }
271
+ )
272
+ write_json(out / "test_summary.json", summaries)
273
+ # Category-conditional image scores are not per-category pixel recall.
274
+ category_rows = []
275
+ for (domain, point), part in frame.groupby(["dataset", "operating_point"]):
276
+ for category in sorted(
277
+ {c for labels in part.categories for c in labels.split("|")}
278
+ ):
279
+ subset = part[part.categories.map(lambda s: category in s.split("|"))]
280
+ category_rows.append(
281
+ {
282
+ "dataset": domain,
283
+ "operating_point": point,
284
+ "category": category,
285
+ "images": len(subset),
286
+ "mean_binary_iou_on_images_with_category": float(subset.iou.mean()),
287
+ "mean_binary_recall_on_images_with_category": float(
288
+ subset.recall.mean()
289
+ ),
290
+ }
291
+ )
292
+ pd.DataFrame(category_rows).to_csv(
293
+ out / "category_conditional_image_metrics.csv", index=False
294
+ )
295
+ return summaries
296
+
297
+
298
+ @torch.no_grad()
299
+ def measure_runtime(model):
300
+ model.eval()
301
+ x = torch.zeros((1, 3, CFG["image_size"], CFG["image_size"]), device=DEVICE)
302
+ for _ in range(10):
303
+ with torch.autocast("cuda", dtype=AMP_DTYPE):
304
+ model(x)
305
+ torch.cuda.synchronize()
306
+ torch.cuda.reset_peak_memory_stats()
307
+ times = []
308
+ for _ in range(30):
309
+ start = torch.cuda.Event(enable_timing=True)
310
+ end = torch.cuda.Event(enable_timing=True)
311
+ start.record()
312
+ with torch.autocast("cuda", dtype=AMP_DTYPE):
313
+ model(x)
314
+ end.record()
315
+ torch.cuda.synchronize()
316
+ times.append(start.elapsed_time(end))
317
+ return {
318
+ "gpu": GPU,
319
+ "batch_size": 1,
320
+ "input_size": CFG["image_size"],
321
+ "dtype": str(AMP_DTYPE),
322
+ "model_forward_ms_mean": float(np.mean(times)),
323
+ "model_forward_ms_p95": float(np.percentile(times, 95)),
324
+ "peak_allocated_vram_bytes": torch.cuda.max_memory_allocated(),
325
+ "parameters": sum(p.numel() for p in model.parameters()),
326
+ "timing_scope": "Model forward only; excludes image decoding, resizing, host transfer and mask restoration",
327
+ }
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_20.txt ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 20
2
+ def save_state(model, path):
3
+ save_file(
4
+ {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()},
5
+ str(path),
6
+ )
7
+
8
+
9
+ def remote_optional(repo, path, kind, revision):
10
+ if revision is None:
11
+ return None
12
+ try:
13
+ return fetch(repo, path, kind, revision)
14
+ except EntryNotFoundError:
15
+ return None
16
+
17
+
18
+ def update_early_stopping(state, score, completed_epochs, config):
19
+ """Track meaningful validation improvement independently of best-weight saving.
20
+
21
+ The first min_epochs establish a reference. Patience starts afterward.
22
+ Small improvements can accumulate until they exceed min_delta.
23
+ """
24
+ if not math.isfinite(score):
25
+ raise ValueError("Early stopping requires a finite validation score.")
26
+ reference = state["reference_score"]
27
+ if completed_epochs <= config["early_stopping_min_epochs"]:
28
+ state["reference_score"] = score if reference is None else max(reference, score)
29
+ state["bad_epochs"] = 0
30
+ elif reference is None or score > reference + config["early_stopping_min_delta"]:
31
+ state["reference_score"] = score
32
+ state["bad_epochs"] = 0
33
+ else:
34
+ state["bad_epochs"] += 1
35
+ return (
36
+ completed_epochs > config["early_stopping_min_epochs"]
37
+ and state["bad_epochs"] >= config["early_stopping_patience"]
38
+ )
39
+
40
+
41
+ def train_student(experiment):
42
+ if experiment not in ["direct", "distilled"]:
43
+ raise ValueError(experiment)
44
+ folder = RUN_ROOT / experiment
45
+ folder.mkdir(exist_ok=True)
46
+ checkpoint = folder / "checkpoint"
47
+ checkpoint.mkdir(exist_ok=True)
48
+ prefix = f"{RUN_ID}/{experiment}/checkpoint"
49
+ seed_all(CFG["seed"])
50
+ model = SensitivityStudent(CFG["decoder_channels"]).to(DEVICE)
51
+ model.load_state_dict(load_file(str(shared / "initial.safetensors")), strict=True)
52
+ decoder = [p for n, p in model.named_parameters() if not n.startswith("encoder.")]
53
+ optimizer = torch.optim.AdamW(
54
+ [
55
+ {"params": model.encoder.parameters(), "lr": CFG["encoder_lr"]},
56
+ {"params": decoder, "lr": CFG["decoder_lr"]},
57
+ ],
58
+ weight_decay=CFG["weight_decay"],
59
+ )
60
+ scaler = torch.amp.GradScaler("cuda", enabled=AMP_DTYPE == torch.float16)
61
+ history = []
62
+ best = -1.0
63
+ start_epoch = 0
64
+ best_epoch = None
65
+ training_complete = False
66
+ early_stopping = {"reference_score": None, "bad_epochs": 0}
67
+ if CFG["early_stopping_patience"] < 1 or CFG["early_stopping_min_epochs"] < 0:
68
+ raise ValueError("Patience must be positive and minimum epochs nonnegative.")
69
+ if not math.isfinite(CFG["early_stopping_min_delta"]) or CFG["early_stopping_min_delta"] < 0:
70
+ raise ValueError("Minimum improvement must be finite and nonnegative.")
71
+ revision = api.repo_info(MODEL_REPO, repo_type="model").sha
72
+ manifest_path = remote_optional(
73
+ MODEL_REPO, f"{prefix}/checkpoint.json", "model", revision
74
+ )
75
+ if manifest_path:
76
+ meta = json.loads(manifest_path.read_text())
77
+ if meta["plan_sha256"] != PLAN_SHA:
78
+ raise ValueError("Checkpoint plan differs.")
79
+ for name, sha in meta["files"].items():
80
+ src = fetch(MODEL_REPO, f"{prefix}/{name}", "model", revision)
81
+ if digest_file(src) != sha:
82
+ raise ValueError("Checkpoint checksum mismatch.")
83
+ shutil.copy2(src, checkpoint / name)
84
+ model.load_state_dict(
85
+ load_file(str(checkpoint / "latest.safetensors")), strict=True
86
+ )
87
+ # Only tensor/basic-container checkpoint state is accepted, never arbitrary pickle objects.
88
+ state = torch.load(
89
+ checkpoint / "optimizer.pt", map_location=DEVICE, weights_only=True
90
+ )
91
+ optimizer.load_state_dict(state["optimizer"])
92
+ scaler.load_state_dict(state["scaler"])
93
+ del state
94
+ history = meta["history"]
95
+ best = meta["best_score"]
96
+ start_epoch = meta["next_epoch"]
97
+ best_epoch = meta.get("best_epoch") or max(history, key=lambda row: row["validation_iou"])["epoch"]
98
+ training_complete = meta.get("training_complete", False) or start_epoch >= CFG["epochs"]
99
+ policy_changed = meta.get("execution_policy_sha256") != POLICY_SHA
100
+ early_stopping = {"reference_score": None, "bad_epochs": 0}
101
+ for row in history:
102
+ update_early_stopping(early_stopping, row["validation_iou"], row["epoch"], CFG)
103
+ # Do not pretend the new policy stopped the past run at an earlier epoch.
104
+ # If an unfinished run is already on a plateau, finish now at its saved epoch.
105
+ plateau_at_resume = (
106
+ not training_complete
107
+ and start_epoch > CFG["early_stopping_min_epochs"]
108
+ and early_stopping["bad_epochs"] >= CFG["early_stopping_patience"]
109
+ )
110
+ if plateau_at_resume:
111
+ training_complete = True
112
+ reason = meta.get("stop_reason")
113
+ if reason is None and training_complete:
114
+ reason = "max_epochs" if start_epoch >= CFG["epochs"] else "early_stopping"
115
+ meta.update(
116
+ best_epoch=best_epoch, early_stopping=dict(early_stopping),
117
+ training_complete=training_complete, stop_reason=reason,
118
+ execution_policy_sha256=POLICY_SHA, execution_policy=EXECUTION_POLICY,
119
+ policy_applied_at_completed_epoch=start_epoch,
120
+ )
121
+ write_json(checkpoint / "checkpoint.json", meta)
122
+ if policy_changed:
123
+ upload(checkpoint, MODEL_REPO, "model", prefix)
124
+ if training_complete:
125
+ print(experiment, "training already finished:", meta["stop_reason"],
126
+ "after", start_epoch, "epochs. Export/evaluation will continue.")
127
+ else:
128
+ print(experiment, "resuming from epoch", start_epoch + 1,
129
+ "with patience counter", early_stopping["bad_epochs"])
130
+ teacher = (
131
+ load_teacher()
132
+ if experiment == "distilled" and not training_complete and start_epoch < CFG["epochs"]
133
+ else None
134
+ )
135
+ accumulation = max(1, math.ceil(CFG["effective_batch_size"] / CFG["batch_size"]))
136
+ first_epoch = CFG["epochs"] if training_complete else start_epoch
137
+ for epoch in range(first_epoch, CFG["epochs"]):
138
+ seed_all(CFG["seed"] + epoch)
139
+ model.train()
140
+ train_loader = loader(
141
+ SPLITS["train"], training=True, balanced=True, epoch=epoch
142
+ )
143
+ warmup = CFG["lr_warmup_epochs"]
144
+ lr_factor = (
145
+ (epoch + 1) / warmup
146
+ if epoch < warmup
147
+ else 0.5
148
+ * (
149
+ 1
150
+ + math.cos(math.pi * (epoch - warmup) / max(1, CFG["epochs"] - warmup))
151
+ )
152
+ )
153
+ kd_factor = CFG["kd_weight"] * min(
154
+ 1.0, max(0.0, (epoch - CFG["kd_warmup_epochs"] + 1) / CFG["kd_ramp_epochs"])
155
+ )
156
+ for group, base in zip(
157
+ optimizer.param_groups, [CFG["encoder_lr"], CFG["decoder_lr"]]
158
+ ):
159
+ group["lr"] = base * lr_factor
160
+ optimizer.zero_grad(set_to_none=True)
161
+ totals = np.zeros(3)
162
+ samples = 0
163
+ t0 = time.time()
164
+ steps = 0
165
+ for step, (x, y, v, _) in enumerate(
166
+ tqdm(train_loader, desc=f'{experiment} epoch {epoch+1}/{CFG["epochs"]}')
167
+ ):
168
+ x = x.to(DEVICE)
169
+ y = y.to(DEVICE)
170
+ v = v.to(DEVICE)
171
+ with torch.autocast("cuda", dtype=AMP_DTYPE):
172
+ logits, auxiliary, boundary = model.forward_train(x)
173
+ if teacher is not None and kd_factor > 0:
174
+ with torch.no_grad():
175
+ teacher_logits = teacher(x)
176
+ supervised = supervised_objective(logits, auxiliary, boundary, y, v)
177
+ kd = (
178
+ distillation_loss(logits, teacher_logits, y, v)
179
+ if teacher is not None and kd_factor > 0
180
+ else supervised.new_zeros(())
181
+ )
182
+ loss = supervised + kd_factor * kd
183
+ if not torch.isfinite(loss):
184
+ raise FloatingPointError(
185
+ "Non-finite loss. No checkpoint was overwritten."
186
+ )
187
+ # Weight by actual images, including the final short accumulation window.
188
+ window_start = (step // accumulation) * accumulation
189
+ window_samples = min(
190
+ accumulation * CFG["batch_size"],
191
+ len(train_loader.dataset) - window_start * CFG["batch_size"],
192
+ )
193
+ scaler.scale(loss * x.size(0) / window_samples).backward()
194
+ if (step + 1) % accumulation == 0 or step + 1 == len(train_loader):
195
+ scaler.unscale_(optimizer)
196
+ nn.utils.clip_grad_norm_(model.parameters(), 1.0)
197
+ scaler.step(optimizer)
198
+ scaler.update()
199
+ optimizer.zero_grad(set_to_none=True)
200
+ steps += 1
201
+ totals += np.array([loss.item(), supervised.item(), kd.item()]) * x.size(0)
202
+ samples += x.size(0)
203
+ score, domain = validation_score(model, SPLITS["validation"])
204
+ if not np.isfinite(score):
205
+ raise FloatingPointError("Non-finite validation score.")
206
+ if score > best:
207
+ best = score
208
+ best_epoch = epoch + 1
209
+ save_state(model, checkpoint / "best.safetensors")
210
+ stopped_early = update_early_stopping(early_stopping, score, epoch + 1, CFG)
211
+ training_complete = stopped_early or epoch + 1 == CFG["epochs"]
212
+ stop_reason = "early_stopping" if stopped_early else (
213
+ "max_epochs" if training_complete else None
214
+ )
215
+ history.append(
216
+ dict(
217
+ epoch=epoch + 1,
218
+ loss=float(totals[0] / samples),
219
+ supervised_loss=float(totals[1] / samples),
220
+ kd_loss=float(totals[2] / samples),
221
+ validation_iou=score,
222
+ validation_domains=domain,
223
+ early_stopping_bad_epochs=early_stopping["bad_epochs"],
224
+ early_stopping_reference=early_stopping["reference_score"],
225
+ kd_weight=kd_factor if experiment == "distilled" else 0.0,
226
+ optimizer_steps=steps,
227
+ seconds=time.time() - t0,
228
+ encoder_lr=optimizer.param_groups[0]["lr"],
229
+ )
230
+ )
231
+ save_state(model, checkpoint / "latest.safetensors")
232
+ torch.save(
233
+ {"optimizer": optimizer.state_dict(), "scaler": scaler.state_dict()},
234
+ checkpoint / "optimizer.pt",
235
+ )
236
+ names = ["latest.safetensors", "best.safetensors", "optimizer.pt"]
237
+ write_json(
238
+ checkpoint / "checkpoint.json",
239
+ dict(
240
+ plan_sha256=PLAN_SHA,
241
+ next_epoch=epoch + 1,
242
+ best_score=best,
243
+ best_epoch=best_epoch,
244
+ early_stopping=dict(early_stopping),
245
+ execution_policy_sha256=POLICY_SHA,
246
+ execution_policy=EXECUTION_POLICY,
247
+ training_complete=training_complete,
248
+ stop_reason=stop_reason,
249
+ history=history,
250
+ files={name: digest_file(checkpoint / name) for name in names},
251
+ ),
252
+ )
253
+ # One atomic Hub commit per epoch. A failed upload stops instead of silently losing progress.
254
+ upload(checkpoint, MODEL_REPO, "model", prefix)
255
+ print(
256
+ f"Validation mean IoU: {score:.5f}; best: {best:.5f}; saved to Hugging Face"
257
+ )
258
+ if stopped_early:
259
+ print(f"Early stopping after {epoch + 1} epochs. "
260
+ f"Best validation IoU: {best:.5f} at epoch {best_epoch}.")
261
+ break
262
+ completed = json.loads((checkpoint / "checkpoint.json").read_text())
263
+ write_json(folder / "training_summary.json", {
264
+ "experiment": experiment,
265
+ "plan_sha256": PLAN_SHA,
266
+ "epochs_completed": completed["next_epoch"],
267
+ "maximum_epochs": CFG["epochs"],
268
+ "best_epoch": completed["best_epoch"],
269
+ "best_validation_iou": completed["best_score"],
270
+ "training_complete": completed["training_complete"],
271
+ "stop_reason": completed["stop_reason"],
272
+ "early_stopping": completed["early_stopping"],
273
+ "execution_policy": EXECUTION_POLICY,
274
+ "execution_policy_sha256": POLICY_SHA,
275
+ "policy_applied_at_completed_epoch": start_epoch,
276
+ "monitor": "equal-domain validation pixel IoU at threshold 0.5",
277
+ })
278
+ pd.DataFrame(history).to_csv(folder / "training_history.csv", index=False)
279
+ del optimizer, scaler, teacher, model
280
+ gc.collect()
281
+ torch.cuda.empty_cache()
282
+ return folder
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_22.txt ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 22
2
+ def finish_student(experiment):
3
+ folder = RUN_ROOT / experiment
4
+ out = folder / "results"
5
+ out.mkdir(exist_ok=True)
6
+ export = folder / "export"
7
+ export.mkdir(exist_ok=True)
8
+ model = SensitivityStudent(CFG["decoder_channels"]).to(DEVICE)
9
+ model.load_state_dict(
10
+ load_file(str(folder / "checkpoint" / "best.safetensors")), strict=True
11
+ )
12
+ model.eval()
13
+ thresholds = calibrate(model, SPLITS["validation"], out)
14
+ threshold = thresholds["validation_best_iou"]
15
+ summaries = evaluate_test(model, SPLITS["test"], thresholds, out)
16
+ runtime = measure_runtime(model)
17
+ save_state(model, export / "student.safetensors")
18
+ runtime["weights_bytes"] = (export / "student.safetensors").stat().st_size
19
+ runtime["plan_sha256"] = PLAN_SHA
20
+ write_json(out / "runtime.json", runtime)
21
+ config = dict(
22
+ architecture="SensiContextNet",
23
+ decoder_channels=CFG["decoder_channels"],
24
+ image_size=CFG["image_size"],
25
+ normalization_mean=CFG["normalization_mean"],
26
+ normalization_std=CFG["normalization_std"],
27
+ threshold=threshold,
28
+ experiment=experiment,
29
+ parameters=PARAMETERS,
30
+ plan_sha256=PLAN_SHA,
31
+ amp=str(AMP_DTYPE),
32
+ mask_definition="1 = sensitive, 0 = background",
33
+ coordinates="EXIF-upright input image",
34
+ teacher_used_at_inference=False,
35
+ )
36
+ write_json(export / "student_config.json", config)
37
+ shutil.copy2("student_model.py", export / "student_model.py")
38
+ shutil.copy2("inference.py", export / "inference.py")
39
+ shutil.copy2(out / "calibration.json", export / "calibration.json")
40
+ requirements = f'torch=={torch.__version__.split("+")[0]}\ntimm==1.0.22\nsafetensors>=0.5\nPillow>=10\nnumpy>=1.26\n'
41
+ (export / "requirements.txt").write_text(requirements)
42
+ (export / "README.md").write_text(f"""# SensiContextNet: {experiment}
43
+
44
+ Custom binary sensitivity segmenter with an ImageNet-pretrained MobileViTv2-075
45
+ encoder, top-down weighted fusion and a narrow image-detail path. MobileViTv2
46
+ is an existing architecture, not our invention. Total parameters: {PARAMETERS:,}.
47
+ Training-only auxiliary and boundary heads are included in that count.
48
+
49
+ Both arms start from identical weights. Distillation adds teacher-agreement-weighted
50
+ Bernoulli KL after warmup. No teacher is needed at inference. Performance gains
51
+ are experimental, not guaranteed.
52
+
53
+ Input: RGB image. Output: original-size probability and binary sensitivity mask.
54
+ Deployment threshold {threshold} maximizes mean domain validation IoU.
55
+ This is NOT a recall guarantee. See calibration.json for the separately evaluated
56
+ recall/FPR constraint and its feasibility. No test data selects thresholds.
57
+
58
+ Data: {PREPARED_REPO}, revision {PREP_REVISION}, release {PREP_ID}.
59
+ Results: {RESULTS_REPO}/{RUN_ID}/{experiment}.
60
+ Download this export folder, then use load_student and predict_image in inference.py.
61
+ Stored normalization buffers adapt the saved teacher input convention to the
62
+ pretrained encoder's RGB [0, 1] convention. Background means unannotated, not safe.
63
+
64
+ Encoder and its applicable terms: https://huggingface.co/timm/mobilevitv2_075.cvnets_in1k
65
+ Teacher terms: https://huggingface.co/{TEACHER_CONFIG['recipe']['backbone']}
66
+ Existing dataset/checkpoint restrictions continue to apply.
67
+ """)
68
+ shutil.copy2(folder / "training_summary.json", export / "training_summary.json")
69
+ model_rev = upload(export, MODEL_REPO, "model", f"{RUN_ID}/{experiment}/export")
70
+ model_receipt = dict(
71
+ repo=MODEL_REPO,
72
+ revision=model_rev,
73
+ prefix=f"{RUN_ID}/{experiment}/export",
74
+ weights_sha256=digest_file(export / "student.safetensors"),
75
+ plan_sha256=PLAN_SHA,
76
+ )
77
+ # Verify that the exact exported weights can be retrieved from the committed revision.
78
+ remote = fetch(
79
+ MODEL_REPO, f'{model_receipt["prefix"]}/student.safetensors', "model", model_rev
80
+ )
81
+ if digest_file(remote) != model_receipt["weights_sha256"]:
82
+ raise ValueError("Student upload verification failed.")
83
+ write_json(out / "model_receipt.json", model_receipt)
84
+ for name in ["split_ids.json", "source_provenance.json", "run_plan.json", "active_execution_policy.json"]:
85
+ shutil.copy2(RUN_ROOT / name, out / name)
86
+ shutil.copy2(folder / "training_history.csv", out / "training_history.csv")
87
+ shutil.copy2(folder / "training_summary.json", out / "training_summary.json")
88
+ history = pd.read_csv(out / "training_history.csv")
89
+ fig, axes = plt.subplots(1, 2, figsize=(10, 4))
90
+ axes[0].plot(history.epoch, history.supervised_loss, label="Supervised")
91
+ axes[0].plot(history.epoch, history.kd_loss, label="Unweighted KD")
92
+ axes[0].legend()
93
+ axes[0].set(xlabel="Epoch", ylabel="Loss")
94
+ axes[1].plot(history.epoch, history.validation_iou)
95
+ axes[1].set(xlabel="Epoch", ylabel="Mean domain validation IoU")
96
+ fig.tight_layout()
97
+ fig.savefig(out / "training_curves.png", dpi=140)
98
+ plt.close(fig)
99
+ shutil.copytree(CODE_DIRECTORY, out / "code", dirs_exist_ok=True)
100
+ write_json(
101
+ out / "DONE.json",
102
+ dict(
103
+ plan_sha256=PLAN_SHA,
104
+ experiment=experiment,
105
+ files={
106
+ str(p.relative_to(out)): digest_file(p)
107
+ for p in out.rglob("*")
108
+ if p.is_file() and p.name != "DONE.json"
109
+ },
110
+ ),
111
+ )
112
+ result_rev = upload(out, RESULTS_REPO, "dataset", f"{RUN_ID}/{experiment}")
113
+ saved = read_remote(
114
+ RESULTS_REPO, f"{RUN_ID}/{experiment}/DONE.json", "dataset", result_rev
115
+ )
116
+ if saved["plan_sha256"] != PLAN_SHA:
117
+ raise ValueError("Result upload verification failed.")
118
+ del model
119
+ gc.collect()
120
+ torch.cuda.empty_cache()
121
+ print(experiment, "model and metrics saved:", model_rev, result_rev)
122
+ return summaries
123
+
124
+
125
+ def run_experiment(experiment):
126
+ rev = api.repo_info(RESULTS_REPO, repo_type="dataset").sha
127
+ done = remote_optional(
128
+ RESULTS_REPO, f"{RUN_ID}/{experiment}/DONE.json", "dataset", rev
129
+ )
130
+ if done:
131
+ meta = json.loads(done.read_text())
132
+ if meta["plan_sha256"] != PLAN_SHA:
133
+ raise ValueError("Saved result configuration differs.")
134
+ model_receipt = read_remote(
135
+ RESULTS_REPO, f"{RUN_ID}/{experiment}/model_receipt.json", "dataset", rev
136
+ )
137
+ weights = fetch(
138
+ MODEL_REPO,
139
+ f'{model_receipt["prefix"]}/student.safetensors',
140
+ "model",
141
+ model_receipt["revision"],
142
+ )
143
+ if digest_file(weights) != model_receipt["weights_sha256"]:
144
+ raise ValueError("Saved model checksum differs.")
145
+ print(experiment, "already complete. Reusing committed results.")
146
+ return read_remote(
147
+ RESULTS_REPO, f"{RUN_ID}/{experiment}/test_summary.json", "dataset", rev
148
+ )
149
+ train_student(experiment)
150
+ return finish_student(experiment)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/cell_24.txt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 24
2
+ import re
3
+
4
+
5
+ def save_readable_code(directory):
6
+ """Archive only this notebook's marked code cells, never execute archived text."""
7
+ directory.mkdir(parents=True, exist_ok=True)
8
+ shutil.copy2("student_model.py", directory / "student_model.py")
9
+ shutil.copy2("inference.py", directory / "inference.py")
10
+ # Keep the latest execution of each cell if a cell was rerun interactively.
11
+ history = get_ipython().history_manager.input_hist_raw
12
+ current_marker = re.search(
13
+ r"^# MODULE04_CELL: (\d+)$", history[-1], flags=re.MULTILINE
14
+ )
15
+ if current_marker is None:
16
+ raise RuntimeError("Run the complete provenance cell, including its marker.")
17
+ cutoff = int(current_marker.group(1))
18
+ executed_cells = {}
19
+ for cell in history:
20
+ marker = re.search(r"^# MODULE04_CELL: (\d+)$", cell, flags=re.MULTILINE)
21
+ if marker and int(marker.group(1)) <= cutoff:
22
+ executed_cells[marker.group(1)] = cell
23
+ if not executed_cells:
24
+ raise RuntimeError(
25
+ "No notebook cells found. Run this notebook in Colab/IPython."
26
+ )
27
+ for cell_id, cell in executed_cells.items():
28
+ (directory / f"cell_{cell_id}.txt").write_text(cell)
29
+ paths = list(directory.glob("*.py")) + list(directory.glob("*.txt"))
30
+ checksums = {path.name: digest_file(path) for path in paths}
31
+ write_json(directory / "code_checksums.json", checksums)
32
+ return hashlib.sha256(json.dumps(checksums, sort_keys=True).encode()).hexdigest()
33
+
34
+
35
+ CODE_DIRECTORY = RUN_ROOT / "code"
36
+ CODE_SHA = save_readable_code(CODE_DIRECTORY)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/code_checksums.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "inference.py": "ab031d9431591bfb6f274124919bc05a1845988c498ae200ce7e8007662c12ad",
3
+ "student_model.py": "c6da9d62d019e1f70815e895f91f026024ebb690ac5147af5d18e34de0f99128",
4
+ "cell_10.txt": "663e86f6c5ae15f817381ff34cb4d1e101afd52b5a69df2cf1b41dfaa88b18d8",
5
+ "cell_16.txt": "cbfb6bb5bfe0eaf011aa0dc8ad3d5b254089d08f91e40f3ec5c8152f2b16af98",
6
+ "cell_02.txt": "5ed1ebd3c38c817de50a59f2ecfe42a82c419ae0ecd9ad8d3b27d37ae9ce8546",
7
+ "cell_07.txt": "766ca55346af7776a60ef2e4df9b55bacc88332a0cf24f3da42721dcf684964b",
8
+ "cell_18.txt": "6e57820bd78cd7cb6bb8b84f99818051d5c09d1174ac7f1dda346933812595ca",
9
+ "cell_24.txt": "ae28cf2d75812ea3ded980ec1b9876b052a38c58e14ca3383d836a01c8d07341",
10
+ "cell_14.txt": "6efb48c643c6ab92eb07737e09dc0c314e9ddafe0bf421853c02ca4e6e244b37",
11
+ "cell_06.txt": "99532b99114cc3d33ea3b7f74282c55b895889585047e1272f77231af5a57f41",
12
+ "cell_20.txt": "eb6a50a4652e7b31e7877971bd17672c696302ecc2581c0149090cc0aa3bdf8e",
13
+ "cell_22.txt": "8c8c3dbbdeac001871e3e9eff0a1c1fb141bfaacfe884f000f1eb73760596fa2",
14
+ "cell_04.txt": "e21d1af32b6f40610aa48243f8bb3b89d6817e895f14d4f2f19d33c9cfa8dc88",
15
+ "cell_09.txt": "87882676774095ea4d229541baaf3d0bc655cd88b7b3febb9c6975f711ea16a2",
16
+ "cell_12.txt": "ca9671b52b5069c4150aafaaa740b5c2dea33d0a304c11d8c5dfb9781b4484f7"
17
+ }
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/inference.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 12
2
+ from pathlib import Path
3
+ import json
4
+ import numpy as np
5
+ import torch
6
+ from torch.nn import functional as F
7
+ from PIL import Image, ImageOps
8
+ from safetensors.torch import load_file
9
+ from student_model import SensitivityStudent
10
+
11
+
12
+ def load_student(directory, device="cpu"):
13
+ directory = Path(directory)
14
+ config = json.loads((directory / "student_config.json").read_text())
15
+ model = SensitivityStudent(config["decoder_channels"])
16
+ model.load_state_dict(
17
+ load_file(str(directory / "student.safetensors")), strict=True
18
+ )
19
+ return model.to(device).eval(), config
20
+
21
+
22
+ @torch.inference_mode()
23
+ def predict_image(model, config, image, threshold=None):
24
+ if not isinstance(image, Image.Image):
25
+ image = Image.open(image)
26
+ image = ImageOps.exif_transpose(image).convert("RGB")
27
+ w, h = image.size
28
+ size = config["image_size"]
29
+ ratio = min(size / w, size / h)
30
+ nw = max(1, round(w * ratio))
31
+ nh = max(1, round(h * ratio))
32
+ canvas = Image.new("RGB", (size, size), (124, 116, 104))
33
+ canvas.paste(image.resize((nw, nh), Image.Resampling.BILINEAR), (0, 0))
34
+ a = np.asarray(canvas, dtype=np.float32) / 255.0
35
+ mean = np.asarray(config["normalization_mean"], dtype=np.float32)
36
+ std = np.asarray(config["normalization_std"], dtype=np.float32)
37
+ x = torch.from_numpy(((a - mean) / std).transpose(2, 0, 1).copy())[None].to(
38
+ next(model.parameters()).device
39
+ )
40
+ dtype = torch.bfloat16 if config.get("amp") == "torch.bfloat16" else torch.float16
41
+ with torch.autocast(x.device.type, dtype=dtype, enabled=x.device.type == "cuda"):
42
+ logits = model(x)
43
+ p = logits.float().sigmoid()[:, :, :nh, :nw]
44
+ p = (
45
+ F.interpolate(p, size=(h, w), mode="bilinear", align_corners=False)[0, 0]
46
+ .cpu()
47
+ .numpy()
48
+ )
49
+ t = config["threshold"] if threshold is None else threshold
50
+ return {"probability": p, "mask": (p >= t).astype(np.uint8), "threshold": t}
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/code/student_model.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MODULE04_CELL: 09
2
+ """SensiContextNet: pretrained context encoder and custom lightweight decoder."""
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ import timm
8
+
9
+
10
+ class DecoderConv(nn.Sequential):
11
+ """Batch-size-independent decoder convolution."""
12
+
13
+ def __init__(self, in_channels, out_channels, kernel_size=1, groups=1):
14
+ super().__init__(
15
+ nn.Conv2d(
16
+ in_channels,
17
+ out_channels,
18
+ kernel_size,
19
+ padding=kernel_size // 2,
20
+ groups=groups,
21
+ bias=False,
22
+ ),
23
+ nn.GroupNorm(8, out_channels),
24
+ nn.SiLU(inplace=True),
25
+ )
26
+
27
+
28
+ class SpatialRefinement(nn.Module):
29
+ def __init__(self, channels):
30
+ super().__init__()
31
+ self.depthwise = DecoderConv(channels, channels, 3, groups=channels)
32
+ self.pointwise = DecoderConv(channels, channels)
33
+
34
+ def forward(self, features):
35
+ return features + self.pointwise(self.depthwise(features))
36
+
37
+
38
+ class ContextFusion(nn.Module):
39
+ """Cheap top-down fusion with normalized, learned nonnegative weights."""
40
+
41
+ def __init__(self, skip_channels, channels):
42
+ super().__init__()
43
+ self.lateral = DecoderConv(skip_channels, channels)
44
+ self.weights = nn.Parameter(torch.zeros(2))
45
+ self.refine = SpatialRefinement(channels)
46
+
47
+ def forward(self, coarse, skip):
48
+ coarse = F.interpolate(
49
+ coarse, size=skip.shape[-2:], mode="bilinear", align_corners=False
50
+ )
51
+ weights = self.weights.softmax(dim=0)
52
+ fused = weights[0] * coarse + weights[1] * self.lateral(skip)
53
+ return self.refine(fused)
54
+
55
+
56
+ class SensitivityStudent(nn.Module):
57
+ """Custom binary segmenter. The MobileViTv2 encoder is an existing architecture.
58
+
59
+ Input uses the saved teacher's normalization. Buffers reverse it for the
60
+ pretrained encoder, which expects RGB values in [0, 1]. No teacher is needed
61
+ at inference. The auxiliary heads are executed only by forward_train().
62
+ """
63
+
64
+ def __init__(self, channels=96, pretrained=False, encoder_checkpoint=None):
65
+ super().__init__()
66
+ if pretrained and encoder_checkpoint is None:
67
+ raise ValueError(
68
+ "Provide the pinned local encoder checkpoint for initialization."
69
+ )
70
+ options = {}
71
+ if pretrained:
72
+ options["pretrained_cfg_overlay"] = {
73
+ "file": str(encoder_checkpoint),
74
+ "hf_hub_id": "",
75
+ }
76
+ self.encoder = timm.create_model(
77
+ "mobilevitv2_075.cvnets_in1k",
78
+ pretrained=pretrained,
79
+ features_only=True,
80
+ out_indices=(1, 2, 3, 4),
81
+ **options
82
+ )
83
+ feature_channels = self.encoder.feature_info.channels()
84
+ if self.encoder.feature_info.reduction() != [4, 8, 16, 32]:
85
+ raise RuntimeError("Unexpected encoder feature strides.")
86
+ self.register_buffer(
87
+ "input_mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
88
+ )
89
+ self.register_buffer(
90
+ "input_std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
91
+ )
92
+ self.coarse = DecoderConv(feature_channels[-1], channels)
93
+ self.context = DecoderConv(channels, channels, 7, groups=channels)
94
+ self.global_gate = nn.Sequential(
95
+ nn.AdaptiveAvgPool2d(1), nn.Conv2d(channels, channels, 1), nn.Sigmoid()
96
+ )
97
+ self.fusions = nn.ModuleList(
98
+ [ContextFusion(skip, channels) for skip in reversed(feature_channels[:-1])]
99
+ )
100
+ # A narrow image-detail path supplies edges without a wide stride-2 decoder.
101
+ self.detail = nn.Sequential(
102
+ nn.Conv2d(3, 16, 3, stride=2, padding=1, bias=False),
103
+ nn.GroupNorm(8, 16),
104
+ nn.SiLU(),
105
+ nn.Conv2d(16, 32, 3, stride=2, padding=1, bias=False),
106
+ nn.GroupNorm(8, 32),
107
+ nn.SiLU(),
108
+ )
109
+ self.detail_fuse = nn.Sequential(
110
+ DecoderConv(channels + 32, channels + 32, 3, groups=channels + 32),
111
+ DecoderConv(channels + 32, 64),
112
+ SpatialRefinement(64),
113
+ )
114
+ self.head = nn.Conv2d(64, 1, 1)
115
+ self.aux_heads = nn.ModuleList([nn.Conv2d(channels, 1, 1) for _ in range(2)])
116
+ self.boundary_head = nn.Conv2d(64, 1, 1)
117
+
118
+ def train(self, mode=True):
119
+ super().train(mode)
120
+ # Pretrained BN running statistics remain stable even with a T4 microbatch of 2.
121
+ # Affine BN parameters still receive gradients.
122
+ for layer in self.encoder.modules():
123
+ if isinstance(layer, nn.BatchNorm2d):
124
+ layer.eval()
125
+ return self
126
+
127
+ def _decode(self, inputs):
128
+ rgb = inputs * self.input_std + self.input_mean
129
+ features = self.encoder(rgb)
130
+ coarse = self.coarse(features[-1])
131
+ coarse = coarse + self.context(coarse) * self.global_gate(coarse)
132
+ decoded = []
133
+ for fusion, skip in zip(self.fusions, reversed(features[:-1])):
134
+ coarse = fusion(coarse, skip)
135
+ decoded.append(coarse)
136
+ detail = self.detail(rgb)
137
+ detail = F.interpolate(
138
+ detail, size=coarse.shape[-2:], mode="bilinear", align_corners=False
139
+ )
140
+ fine = self.detail_fuse(torch.cat([coarse, detail], dim=1))
141
+ return fine, decoded
142
+
143
+ def forward(self, inputs):
144
+ fine, _ = self._decode(inputs)
145
+ return F.interpolate(
146
+ self.head(fine),
147
+ size=inputs.shape[-2:],
148
+ mode="bilinear",
149
+ align_corners=False,
150
+ )
151
+
152
+ def forward_train(self, inputs):
153
+ fine, decoded = self._decode(inputs)
154
+ logits = F.interpolate(
155
+ self.head(fine),
156
+ size=inputs.shape[-2:],
157
+ mode="bilinear",
158
+ align_corners=False,
159
+ )
160
+ auxiliary = [
161
+ head(feature) for head, feature in zip(self.aux_heads, decoded[:2])
162
+ ]
163
+ return logits, auxiliary, self.boundary_head(fine)
sensicontext-mobilevit075-v2-seed42/shared/continuations/5b22a344a4fd28b1430cdc67508173706ac4dd6bc89f1dcaabc30ccbba2034fc/execution_policy.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_plan_sha256": "30027f57d9734a6538715ba6302502eb501e3ab4ae0cf1c0e1a7b4a5039fc99a",
3
+ "implementation_sha256": "517cb0b83f88c1122d3f081b73d08f56a45b0cd66dd103c9811fedd442b26116",
4
+ "early_stopping_patience": 3,
5
+ "early_stopping_min_delta": 0.0001,
6
+ "early_stopping_min_epochs": 15,
7
+ "scope": "Unfinished training only; completed results are reused unchanged"
8
+ }