Datasets:
Upload folder using huggingface_hub
Browse files- harness/README.md +8 -0
- harness/finetune_sam21.py +117 -0
harness/README.md
CHANGED
|
@@ -49,3 +49,11 @@ trail (including the snow-on-clouds failure and its fix).
|
|
| 49 |
temporal holdout. Prototype: 70.2% top-1 vs 38.6% majority baseline over
|
| 50 |
24 concepts. Captions are assembled from EXACT facts + this head's
|
| 51 |
INFERRED concept (scored), never generated free-form.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
temporal holdout. Prototype: 70.2% top-1 vs 38.6% majority baseline over
|
| 50 |
24 concepts. Captions are assembled from EXACT facts + this head's
|
| 51 |
INFERRED concept (scored), never generated free-form.
|
| 52 |
+
|
| 53 |
+
## 3b. Fine-tune the teacher itself (the one that won)
|
| 54 |
+
- `finetune_sam21.py tag1 ... [--steps N]` (GPU) — SAM 2.1 base-plus decoder
|
| 55 |
+
+ prompt encoder fine-tuned on point -> consensus-mask pairs, encoder frozen
|
| 56 |
+
with fp16 embedding cache. Held-out IoU 0.365 (zero-shot) -> **0.565**.
|
| 57 |
+
Checkpoint: https://huggingface.co/cp500/sam21-hyperkd-rs
|
| 58 |
+
Compare the PicoSAM3 distill (stage 3): plateaus at 0.178 — capacity, not
|
| 59 |
+
supervision, was the binding constraint at that size.
|
harness/finetune_sam21.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fine-tune SAM 2.1 hiera-base-plus mask decoder on HyperKD-RS consensus
|
| 2 |
+
targets. Encoder frozen; image embeddings precomputed once per scene and
|
| 3 |
+
cached, so training is decoder-only and fits a T4.
|
| 4 |
+
|
| 5 |
+
Point prompt -> target mask (track consensus where available), BCE+Dice on
|
| 6 |
+
the 256x256 low-res logits. Temporal holdout: last 2 scenes per shard = val.
|
| 7 |
+
|
| 8 |
+
Usage: HF_TOKEN=... python finetune_sam21.py tag1 tag2 ... [--steps N]
|
| 9 |
+
Outputs: sam21_hyperkd_decoder.pt (decoder+prompt-encoder state), metrics log.
|
| 10 |
+
"""
|
| 11 |
+
import os, sys, random, pathlib
|
| 12 |
+
import numpy as np
|
| 13 |
+
import cv2
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
|
| 18 |
+
torch.manual_seed(0); random.seed(0); np.random.seed(0)
|
| 19 |
+
DEV = "cuda"
|
| 20 |
+
STEPS = int(sys.argv[sys.argv.index("--steps") + 1]) if "--steps" in sys.argv else 4000
|
| 21 |
+
_skip = {sys.argv[sys.argv.index("--steps") + 1]} if "--steps" in sys.argv else set()
|
| 22 |
+
TAGS = [a for a in sys.argv[1:] if not a.startswith("--") and a not in _skip]
|
| 23 |
+
REPO = "cp500/hyperkd-rs"
|
| 24 |
+
|
| 25 |
+
from sam2.build_sam import build_sam2
|
| 26 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 27 |
+
sam = build_sam2("configs/sam2.1/sam2.1_hiera_b+.yaml",
|
| 28 |
+
os.path.expanduser("~/sam2/checkpoints/sam2.1_hiera_base_plus.pt"),
|
| 29 |
+
device=DEV)
|
| 30 |
+
pred = SAM2ImagePredictor(sam)
|
| 31 |
+
for p in sam.image_encoder.parameters(): p.requires_grad = False
|
| 32 |
+
trainable = list(sam.sam_mask_decoder.parameters()) + list(sam.sam_prompt_encoder.parameters())
|
| 33 |
+
opt = torch.optim.AdamW([p for p in trainable if p.requires_grad], lr=1e-5)
|
| 34 |
+
print(f"trainable params: {sum(p.numel() for p in trainable if p.requires_grad)/1e6:.2f}M")
|
| 35 |
+
|
| 36 |
+
# ---- load shards, precompute embeddings ----
|
| 37 |
+
train_pairs, val_pairs, scene_feats = [], [], []
|
| 38 |
+
for tag in TAGS:
|
| 39 |
+
fp = hf_hub_download(REPO, f"shards/shard_{tag}.npz", repo_type="dataset")
|
| 40 |
+
sh = np.load(fp)
|
| 41 |
+
IM, SAMP, MK = sh["images"], sh["samples"], sh["masks"]
|
| 42 |
+
cut = len(IM) - 2
|
| 43 |
+
local = {}
|
| 44 |
+
for si in range(len(IM)):
|
| 45 |
+
img = cv2.resize(IM[si], (1024, 1024), interpolation=cv2.INTER_CUBIC)
|
| 46 |
+
with torch.inference_mode():
|
| 47 |
+
pred.set_image(img)
|
| 48 |
+
local[si] = len(scene_feats)
|
| 49 |
+
scene_feats.append({ # fp16 cache on the A10G (~10 GB of its 24 GB)
|
| 50 |
+
"embed": pred._features["image_embed"].half().clone(),
|
| 51 |
+
"hr": [f.half().clone() for f in pred._features["high_res_feats"]]})
|
| 52 |
+
for r in SAMP:
|
| 53 |
+
si, tgt = int(r[0]), int(r[9])
|
| 54 |
+
if tgt < 0: continue
|
| 55 |
+
m = MK[tgt]
|
| 56 |
+
if m.sum() < 15: continue
|
| 57 |
+
pair = (local[si], float(r[1]), float(r[2]), tgt, fp)
|
| 58 |
+
(train_pairs if si < cut else val_pairs).append((local[si], r[1], r[2], m))
|
| 59 |
+
print(f"{tag}: cached {len(IM)} embeddings; totals {len(train_pairs)} train / {len(val_pairs)} val", flush=True)
|
| 60 |
+
|
| 61 |
+
def run_decoder(feat, cx, cy, train=True):
|
| 62 |
+
pts = torch.tensor([[[cx / 800 * 1024, cy / 800 * 1024]]], dtype=torch.float32, device=DEV)
|
| 63 |
+
lbl = torch.ones((1, 1), dtype=torch.int32, device=DEV)
|
| 64 |
+
emb = feat["embed"].to(DEV, torch.float32)
|
| 65 |
+
hr = [f.to(DEV, torch.float32) for f in feat["hr"]]
|
| 66 |
+
ctx = torch.enable_grad() if train else torch.inference_mode()
|
| 67 |
+
with ctx:
|
| 68 |
+
sparse, dense = sam.sam_prompt_encoder(points=(pts, lbl), boxes=None, masks=None)
|
| 69 |
+
lowres, iou_pred, _, _ = sam.sam_mask_decoder(
|
| 70 |
+
image_embeddings=emb,
|
| 71 |
+
image_pe=sam.sam_prompt_encoder.get_dense_pe(),
|
| 72 |
+
sparse_prompt_embeddings=sparse,
|
| 73 |
+
dense_prompt_embeddings=dense,
|
| 74 |
+
multimask_output=True,
|
| 75 |
+
repeat_image=False,
|
| 76 |
+
high_res_features=hr)
|
| 77 |
+
return lowres, iou_pred # (1,3,256,256)
|
| 78 |
+
|
| 79 |
+
def dice(p, t):
|
| 80 |
+
p = torch.sigmoid(p)
|
| 81 |
+
return 1 - (2 * (p * t).sum() + 1) / ((p + t).sum() + 1)
|
| 82 |
+
|
| 83 |
+
def val_iou(n=400):
|
| 84 |
+
ious = []
|
| 85 |
+
for fi, cx, cy, m in random.sample(val_pairs, min(n, len(val_pairs))):
|
| 86 |
+
lowres, iou_pred = run_decoder(scene_feats[fi], cx, cy, train=False)
|
| 87 |
+
bi = int(iou_pred[0].argmax())
|
| 88 |
+
pm = (lowres[0, bi] > 0).cpu().numpy()
|
| 89 |
+
t = m > 0
|
| 90 |
+
ious.append((pm & t).sum() / max((pm | t).sum(), 1))
|
| 91 |
+
return float(np.mean(ious))
|
| 92 |
+
|
| 93 |
+
print(f"zero-shot val IoU (argmax-iou head): {val_iou():.3f}", flush=True)
|
| 94 |
+
best = 0
|
| 95 |
+
for step in range(STEPS):
|
| 96 |
+
fi, cx, cy, m = random.choice(train_pairs)
|
| 97 |
+
lowres, iou_pred = run_decoder(scene_feats[fi], cx, cy, train=True)
|
| 98 |
+
T = torch.tensor(m, dtype=torch.float32, device=DEV)[None]
|
| 99 |
+
# supervise the best-matching head (SAM's multimask training rule)
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
ious = [( (lowres[0, j] > 0).float() * T ).sum() /
|
| 102 |
+
torch.clamp(((lowres[0, j] > 0).float() + T).clamp(max=1).sum(), min=1)
|
| 103 |
+
for j in range(3)]
|
| 104 |
+
bj = int(np.argmax([float(v) for v in ious]))
|
| 105 |
+
L = F.binary_cross_entropy_with_logits(lowres[0, bj][None], T) + dice(lowres[0, bj][None], T)
|
| 106 |
+
L = L + F.mse_loss(iou_pred[0, bj], ious[bj].detach())
|
| 107 |
+
opt.zero_grad(); L.backward(); opt.step()
|
| 108 |
+
if step % 500 == 499:
|
| 109 |
+
vi = val_iou()
|
| 110 |
+
print(f"step {step+1}: loss {L.item():.3f} val IoU {vi:.3f}", flush=True)
|
| 111 |
+
if vi > best:
|
| 112 |
+
best = vi
|
| 113 |
+
torch.save({"decoder": sam.sam_mask_decoder.state_dict(),
|
| 114 |
+
"prompt": sam.sam_prompt_encoder.state_dict()},
|
| 115 |
+
os.path.expanduser("~/sam21_hyperkd_decoder.pt"))
|
| 116 |
+
print(f"best val IoU {best:.3f} -> ~/sam21_hyperkd_decoder.pt", flush=True)
|
| 117 |
+
print("FINETUNE_DONE")
|