cp500 commited on
Commit
e461eb3
·
verified ·
1 Parent(s): c2d9eb5

Upload folder using huggingface_hub

Browse files
harness/README.md CHANGED
@@ -41,3 +41,11 @@ only the naming head, not the segmenter.
41
 
42
  `DATASET_SPEC.md` records the sufficiency analysis and the label-QC audit
43
  trail (including the snow-on-clouds failure and its fix).
 
 
 
 
 
 
 
 
 
41
 
42
  `DATASET_SPEC.md` records the sufficiency analysis and the label-QC audit
43
  trail (including the snow-on-clouds failure and its fix).
44
+
45
+ ## 4. Name (query-time captioning head)
46
+ - `concept_head.py tag1 [tag2 ...]` — 22-dim deterministic token features
47
+ (log-area, roundness, solidity, eccentricity, log-Hu, per-band mean/std,
48
+ NDVI) -> 2-layer MLP over taxonomy concepts, trained on the SAM 3.1 labels,
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.
harness/concept_head.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 3 prototype: the naming head. Deterministic token features ->
2
+ taxonomy concept, trained on the SAM 3.1 INFERRED labels in cp500/hyperkd-rs.
3
+
4
+ Features per sample (all computable at query time without any big model):
5
+ shape (log-area, perimeter^2/area roundness, solidity, eccentricity, 7 log-Hu)
6
+ + spectral (mean/std of r,g,b,nir inside the mask + NDVI mean) = 22 dims.
7
+ Head: 2-layer MLP, single-label over the concepts seen in training spots
8
+ (each sample's highest-score label wins; nuisance and domain concepts mix).
9
+
10
+ Temporal holdout: last 2 scenes of each spot are val.
11
+ Usage: python concept_head.py tag1 tag2 ...
12
+ """
13
+ import pathlib, sys, collections
14
+ import numpy as np
15
+ import cv2
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from huggingface_hub import hf_hub_download
19
+
20
+ torch.manual_seed(0); np.random.seed(0)
21
+ HERE = pathlib.Path(__file__).parent
22
+ TAGS = [a for a in sys.argv[1:] if not a.startswith("--")]
23
+
24
+ def feats(mask, ms):
25
+ m8 = (mask > 0).astype(np.uint8)
26
+ a = m8.sum()
27
+ cs, _ = cv2.findContours(m8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
28
+ big = max(cs, key=cv2.contourArea)
29
+ per = cv2.arcLength(big, True)
30
+ hull = cv2.convexHull(big)
31
+ sol = cv2.contourArea(big) / max(cv2.contourArea(hull), 1)
32
+ rnd = 4 * np.pi * a / max(per * per, 1)
33
+ if len(big) >= 5:
34
+ (_, _), (MA, ma), _ = cv2.fitEllipse(big)
35
+ ecc = ma / max(MA, 1e-3)
36
+ else:
37
+ ecc = 1.0
38
+ hu = cv2.HuMoments(cv2.moments(m8)).flatten()
39
+ hu = np.sign(hu) * np.log1p(np.abs(hu) * 1e7)
40
+ # spectral: mask is 256-grid, multispec is 160-grid
41
+ m160 = cv2.resize(m8, (160, 160), interpolation=cv2.INTER_NEAREST) > 0
42
+ px = ms[m160]
43
+ if len(px) == 0: px = ms.reshape(-1, 4)
44
+ mu, sd = px.mean(0), px.std(0)
45
+ ndvi = ((px[:, 3] - px[:, 0]) / np.clip(px[:, 3] + px[:, 0], 1e-3, None)).mean()
46
+ return np.concatenate([[np.log1p(a), rnd, sol, ecc], hu, mu, sd, [ndvi]]).astype(np.float32)
47
+
48
+ X_tr, y_tr, X_va, y_va, names = [], [], [], [], {}
49
+ for tag in TAGS:
50
+ sh = np.load(HERE / f"shard_{tag}.npz")
51
+ lf = hf_hub_download("cp500/hyperkd-rs", f"labels/labels_{tag}.npz", repo_type="dataset")
52
+ lb = np.load(lf)
53
+ sl, cn = lb["sample_labels"], lb["concepts"]
54
+ best = {}
55
+ for i, ci, sc, iou in sl:
56
+ i = int(i)
57
+ if i not in best or sc > best[i][1]: best[i] = (str(cn[int(ci)]), sc)
58
+ cut = len(sh["images"]) - 2
59
+ for i, (cname, _) in best.items():
60
+ r = sh["samples"][i]; si = int(r[0]); ch = int(r[6]); mi = int(r[3 + ch])
61
+ if mi < 0: continue
62
+ ci = names.setdefault(cname, len(names))
63
+ f = feats(sh["masks"][mi], sh["multispec"][si].astype(np.float32))
64
+ (X_tr if si < cut else X_va).append(f)
65
+ (y_tr if si < cut else y_va).append(ci)
66
+ print(f"{tag}: {len(best)} labelled samples")
67
+ X_tr, X_va = np.stack(X_tr), np.stack(X_va)
68
+ mu, sd = X_tr.mean(0), X_tr.std(0) + 1e-6
69
+ X_tr, X_va = (X_tr - mu) / sd, (X_va - mu) / sd
70
+ y_tr, y_va = np.array(y_tr), np.array(y_va)
71
+ K = len(names)
72
+ print(f"{len(X_tr)} train / {len(X_va)} val, {K} concepts")
73
+
74
+ m = torch.nn.Sequential(torch.nn.Linear(X_tr.shape[1], 128), torch.nn.ReLU(),
75
+ torch.nn.Linear(128, 128), torch.nn.ReLU(),
76
+ torch.nn.Linear(128, K))
77
+ opt = torch.optim.Adam(m.parameters(), 1e-3)
78
+ Xt, yt = torch.tensor(X_tr), torch.tensor(y_tr)
79
+ Xv, yv = torch.tensor(X_va), torch.tensor(y_va)
80
+ for ep in range(300):
81
+ idx = torch.randperm(len(Xt))[:512]
82
+ loss = F.cross_entropy(m(Xt[idx]), yt[idx])
83
+ opt.zero_grad(); loss.backward(); opt.step()
84
+ with torch.no_grad():
85
+ pr = m(Xv).argmax(1)
86
+ acc = (pr == yv).float().mean().item()
87
+ # majority-class baseline
88
+ base = collections.Counter(y_tr.tolist()).most_common(1)[0][1] / len(y_tr)
89
+ maj = (yv == collections.Counter(y_tr.tolist()).most_common(1)[0][0]).float().mean().item()
90
+ print(f"val top-1 {acc:.3f} vs majority-class {maj:.3f} ({K} classes)")
91
+ inv = {v: k for k, v in names.items()}
92
+ with torch.no_grad():
93
+ for ci in range(K):
94
+ sel = yv == ci
95
+ if sel.sum() < 5: continue
96
+ a = (pr[sel] == ci).float().mean().item()
97
+ print(f" {inv[ci].split('/')[-1][:34]:36s} n={int(sel.sum()):4d} recall {a:.2f}")
98
+ torch.save(dict(state=m.state_dict(), mu=mu, sd=sd, names=names), HERE / "concept_head.pt")
99
+ print("-> concept_head.pt")
harness/label_shards.py CHANGED
@@ -49,7 +49,8 @@ def label_tag(tag):
49
  sh = np.load(fp)
50
  images, samples, masks = sh["images"], sh["samples"], sh["masks"]
51
  months = [int(str(d)[5:7]) for d in sh["dates"]]
52
- cons = concepts_for(MAN[tag])
 
53
  names = [c[0] for c in cons]
54
  sample_labels = [] # (sample_idx, concept_idx, score, iou)
55
  clouds = np.zeros((len(images), 256, 256), np.uint8)
@@ -62,7 +63,7 @@ def label_tag(tag):
62
  # one processor per threshold value used in this domain
63
  states = {}
64
  for ci, (name, vis, thr) in enumerate(cons):
65
- if name.endswith("/snow cover") and not snow_possible(LAT[tag], months[si]):
66
  continue
67
  proc = states.get(thr)
68
  if proc is None:
 
49
  sh = np.load(fp)
50
  images, samples, masks = sh["images"], sh["samples"], sh["masks"]
51
  months = [int(str(d)[5:7]) for d in sh["dates"]]
52
+ base = tag[:-3] if tag.endswith("_ev") else tag # event shards share the spot
53
+ cons = concepts_for(MAN[base])
54
  names = [c[0] for c in cons]
55
  sample_labels = [] # (sample_idx, concept_idx, score, iou)
56
  clouds = np.zeros((len(images), 256, 256), np.uint8)
 
63
  # one processor per threshold value used in this domain
64
  states = {}
65
  for ci, (name, vis, thr) in enumerate(cons):
66
+ if name.endswith("/snow cover") and not snow_possible(LAT[base], months[si]):
67
  continue
68
  proc = states.get(thr)
69
  if proc is None: