Python
feat: SA-1B support (folder index, 2D visibility masking)
mohamdevbe0463719671
diff --git a/datasets_pipeline/README.md b/datasets_pipeline/README.mdindex dc5f556..7d55bc1 100644--- a/datasets_pipeline/README.md+++ b/datasets_pipeline/README.md@@ -62,14 +62,14 @@ Everything is resume-safe: re-running skips crops already on disk.| dataset | images | route | undistort ||---|---|---|---|-| coco | 13.5 GB | `wget` train2014.zip — **only train2014 is referenced** | no |+| coco | 13.5 GB (often mirrored) | `wget` train2014.zip — **only train2014 is referenced** | no || mpii | 12.1 GB | `wget` mpii_human_pose_v1.tar.gz | no || aic | 36.4 GB | OpenDataLab CLI (login) — where this corpus came from before | no || 3dpw | 4.6 GB | licence form → imageFiles.zip | no || harmony4d | 352 GB | HF `Jyun-Ting/Harmony4D`, ungated, per-scene zips | **yes** || egohumans | 107 GB referenced (550 GB advertised) | Google Drive, per-take tar.gz → `gdown --folder` | **yes** || egoexo4d | ~8 GB (procedure) | `egoexo -o $DEST --parts sam_3d_body` (signed licence) | no |-| sa1b | ~11 TB | terms → `links.txt` → `--links-file` | no |+| sa1b | ~11 TB (often mirrored) | terms → `links.txt` → `--links-file` | no |`fetch_images.py` handles the first two and harmony4d directly. For the rest itprints the exact commands and exits 2 rather than pretending.@@ -173,8 +173,15 @@ corpus.## SA-1B-Accept the terms at <https://ai.meta.com/datasets/segment-anything-downloads/>-to get `links.txt` (one `sa_NNNNNN.tar <signed-url>` per line), then:+**Check your cluster's shared dataset mirror first** — SA-1B is commonly+mirrored, and if it is, everything below is moot. A mirror that unpacked the+1000 tars in place stores `sa_000000/`, `sa_000001/`, ... while the parquet asks+for a flat `sa_<id>.jpg`; `index_sa1b.py` walks it once and+`build_split.py --image-index` resolves against that index.++Otherwise, accept the terms at+<https://ai.meta.com/datasets/segment-anything-downloads/> to get `links.txt`+(one `sa_NNNNNN.tar <signed-url>` per line), then:```bashpython datasets_pipeline/stream_archives.py --dataset sa1b \@@ -184,8 +191,8 @@ python datasets_pipeline/stream_archives.py --dataset sa1b \-- --originals none --crop-format jpg```-Any prefix of the tar list is a valid dataset, so you can stop whenever. But-the measured economics are poor, and I would not start here:+Any prefix of the tar list is a valid dataset, so you can stop whenever. If you+are paying for the bandwidth, the economics are poor:- References are spread **uniformly over all 1000 tars** — 994 of 1000 idblocks are hit by just 3% of the annotations — so there is no dense subset to@@ -193,17 +200,36 @@ the measured economics are poor, and I would not start here:- Only **11.4%** of SA-1B is referenced. Each ~10 GB tar yields ~1,270 usefulframes ≈ 3,400 crops, i.e. **~2.3 MB of download per crop** against AIC's0.13 MB. The full 3.4M crops cost ~11 TB.-- It is the one split with real visibility flags: a mean of **44 of 70**- keypoints are literal `(0, 0)` placeholders, and only **0.3%** of hands are- fully visible.--That last point is a trap for any converter. `tools/parquet_to_npz.py` drops the-visibility column (`joints_2d = kp2[:, :2]`), so a naive SA-1B build writes-those placeholders as if they were observations at the image corner — poisoning-the 2D loss and blowing every hand box out to the frame edge. `build_split.py`-stores `joints_2d_vis` / `joints_3d_conf` and refuses to cut a hand crop unless-all 21 of its keypoints are visible. Every other split is 100% visible, so this-only bites on SA-1B.++### The SA-1B label trap++SA-1B is the one split whose keypoint arrays are not fully populated, and the+two arrays differ:++| | populated |+|---|---|+| `keypoints_3d` + `model_params` + `shape_params` | **100%** |+| `keypoints_2d`, body (0–14) | 100% |+| `keypoints_2d`, feet (15–20) | 97% |+| `keypoints_2d`, hands (21–62) | **8%** |++So the 3D supervision is complete and the split is fully usable — but the 2D+array stores unobserved keypoints as literal `(0, 0)` with a graded confidence+in the third column. `tools/parquet_to_npz.py` drops that column+(`joints_2d = kp2[:, :2]`), so a naive build writes ~45 of 70 keypoints per+person as observations at the image corner. Left unmasked that would drag every+predicted hand keypoint to the top-left of the frame.++`build_split.py` stores `joints_2d_vis` and `joints_3d_conf`, and refuses to cut+a hand crop unless all 21 of that hand's keypoints are visible (true for 0.3% of+SA-1B hands and 100% of every other split).++`train_distill_mhr_only.py` consumes the mask: `loss_2d_native`,+`loss_2d_simcc` and `loss_reproj` are weighted by `joints_2d_vis`, which+defaults to all-ones when a folder does not carry it — so every existing+`data/sam3d_gt_*` folder trains exactly as before (verified to float32+rounding, 6e-8). On SA-1B, `vis > 0` is an exact gate for "this coordinate is+real": zero exceptions in 183k keypoints measured.## Datasets that do not fit: `stream_archives.py`@@ -260,7 +286,7 @@ fingertips — an upper bound on what a hand branch could learn from them.| **egoexo4d_procedure** | ~350k | **16.1 mm** | **85.5%** | licence + CLI || egoexo4d_physical | ~700k | 14.5 mm | 19.3% | licence + CLI || harmony4d | 496k | 12.6 mm | 3.4% | 352 GB |-| sa1b | 3.4M | 8.5 mm | 0.3% visible at all | ~11 TB |+| sa1b | 3.4M | 8.5 mm | 0.3% visible at all | ~11 TB, or free if mirrored || 3dpw | 22k | 7.5 mm | 71.4% | 4.6 GB || mpii | 7k | 7.4 mm | 11.5% | 12.1 GB || aic | 287k | 6.9 mm | 16.6% | 36.4 GB |diff --git a/datasets_pipeline/build_split.py b/datasets_pipeline/build_split.pyindex e359360..6a908a2 100755--- a/datasets_pipeline/build_split.py+++ b/datasets_pipeline/build_split.py@@ -47,6 +47,7 @@ from __future__ import annotationsimport argparseimport os+import reimport shutilimport sysfrom pathlib import Path@@ -71,6 +72,41 @@ from tools.parquet_to_npz import ( # noqa: E402RIGHT_HAND_KPS = list(range(21, 42))LEFT_HAND_KPS = list(range(42, 63))+ID_RE = re.compile(r"^sa_(\d+)\.jpe?g$", re.I)+++class ImageIndex:+ """Resolve a flat `sa_<id>.jpg` to its per-tar subfolder.++ Only needed when a mirror unpacked SA-1B's 1000 distribution tars in place+ rather than flattening them. Built by index_sa1b.py.+ """++ def __init__(self, path: Path):+ z = np.load(path, allow_pickle=True)+ self.dirs = [str(d) for d in z["dirs"]]+ self.mode = str(z["mode"])+ if self.mode == "ranges":+ self.lo, self.hi, self.folder = z["lo"], z["hi"], z["folder"]+ else:+ self.ids, self.folder = z["ids"], z["folder"]++ def resolve(self, image: str) -> str | None:+ m = ID_RE.match(os.path.basename(image))+ if not m:+ return None+ n = int(m.group(1))+ if self.mode == "ranges":+ k = int(np.searchsorted(self.lo, n, side="right")) - 1+ if k < 0 or n > self.hi[k]:+ return None+ return f"{self.dirs[self.folder[k]]}/{image}"+ k = int(np.searchsorted(self.ids, n))+ if k >= self.ids.size or self.ids[k] != n:+ return None+ return f"{self.dirs[self.folder[k]]}/{image}"++def hand_boxes(joints_2d: np.ndarray,vis: np.ndarray | None = None) -> dict[str, np.ndarray | None]:@@ -165,6 +201,13 @@ def parse_args() -> argparse.Namespace:help="copy: self-contained, prunes unreferenced source images. ""link/hardlink: free, but the source root must survive.")+ p.add_argument("--image-index", type=Path, default=None,+ help="npz from index_sa1b.py, for a SA-1B mirror that kept "+ "the per-tar sa_NNNNNN/ folders instead of a flat tree")+ p.add_argument("--shard-slice", default=None, metavar="I/N",+ help="process only shard I of N (0-based) — for a Slurm job "+ "array. Resume-safety makes overlap harmless, but a "+ "clean split avoids duplicated decoding.")p.add_argument("--image-prefix", default=None,help="only rows whose `image` starts with this — the hook ""stream_archives.py uses to build one archive at a time")@@ -194,11 +237,24 @@ def main() -> None:# Let the unmodified training script discover this folder.compat = out_dir / "images"if not compat.exists():- os.symlink("body_crops", compat)+ try:+ os.symlink("body_crops", compat)+ except FileExistsError:+ pass # another array task won the raceparquets = sorted(args.annotation_dir.glob("*.parquet"))if not parquets:sys.exit(f"no parquet files in {args.annotation_dir}")+ if args.shard_slice:+ i, n = (int(x) for x in args.shard_slice.split("/"))+ if not 0 <= i < n:+ sys.exit(f"--shard-slice {args.shard_slice}: need 0 <= I < N")+ parquets = parquets[i::n]+ print(f"shard slice {i}/{n}: {len(parquets)} parquet file(s)")++ index = ImageIndex(args.image_index) if args.image_index else None+ if index:+ print(f"image index: {len(index.dirs)} folders, mode={index.mode}")ext = args.crop_formatimwrite_params = ([int(cv2.IMWRITE_JPEG_QUALITY), args.jpg_quality]@@ -232,6 +288,12 @@ def main() -> None:continuerelpath = image_relpath(dataset, image)+ if index is not None:+ resolved = index.resolve(image)+ if resolved is None:+ st["missing_image"] += 1+ continue+ relpath = resolvedif image not in img_cache:bgr = cv2.imread(str(args.image_dir / relpath))img_cache[image] = (cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)diff --git a/datasets_pipeline/index_sa1b.py b/datasets_pipeline/index_sa1b.pynew file mode 100755index 0000000..82e5ac0--- /dev/null+++ b/datasets_pipeline/index_sa1b.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Index SA-1B when it is stored as per-tar folders instead of a flat tree.++The parquet asks for a flat `sa_4409715.jpg`, but a mirror that unpacked the+1000 distribution tars in place holds `sa_000000/`, `sa_000001/`, ... instead —+which is what most cluster-wide mirrors look like. This walks the tree once and+writes an index that `build_split.py --image-index` uses to resolve names.++ python datasets_pipeline/index_sa1b.py \+ --image-dir /path/to/SegmentAnything_1B \+ --out sa1b_index.npz++SA-1B assigns ids to tars in blocks, so the index is usually just 1000+(min_id, max_id, folder) rows — a few KB. If the ranges turn out to overlap the+full id->folder table is written instead (~110 MB for 11M images). Either way+lookup is an O(log n) searchsorted.++Walking ~11M directory entries takes minutes and is single-threaded — run it as+a batch job, not on a shared login node.+"""++from __future__ import annotations++import argparse+import os+import re+import sys+import time+from pathlib import Path++import numpy as np++ID_RE = re.compile(r"^sa_(\d+)\.jpe?g$", re.I)+++def find_jpeg_dir(folder: Path, max_depth: int = 3) -> Path | None:+ """The directory inside `folder` that actually holds the jpgs.++ Mirrors differ: some put the images straight in sa_NNNNNN/, others add an+ images/ level. Probe rather than assume.+ """+ stack = [(folder, 0)]+ while stack:+ d, depth = stack.pop()+ try:+ subdirs = []+ for e in os.scandir(d):+ if e.is_file() and ID_RE.match(e.name):+ return d+ if e.is_dir() and depth < max_depth:+ subdirs.append((Path(e.path), depth + 1))+ stack.extend(subdirs)+ except OSError:+ continue+ return None+++def main() -> None:+ p = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ p.add_argument("--image-dir", type=Path, required=True)+ p.add_argument("--out", type=Path, required=True)+ p.add_argument("--pattern", default="sa_*",+ help="glob for the per-tar folders (default sa_*)")+ args = p.parse_args()++ folders = sorted(d for d in args.image_dir.glob(args.pattern) if d.is_dir())+ if not folders:+ sys.exit(f"no {args.pattern} folders under {args.image_dir} — is it "+ f"already flat? Then you do not need an index.")+ print(f"{len(folders)} folders under {args.image_dir}")++ rel_dirs: list[str] = []+ ids_all: list[np.ndarray] = []+ fidx_all: list[np.ndarray] = []+ t0 = time.time()++ for i, folder in enumerate(folders):+ jdir = find_jpeg_dir(folder)+ if jdir is None:+ print(f" [skip] {folder.name}: no sa_*.jpg found")+ continue+ ids = np.fromiter(+ (int(m.group(1)) for m in+ (ID_RE.match(e.name) for e in os.scandir(jdir)) if m),+ dtype=np.int64)+ if ids.size == 0:+ continue+ rel_dirs.append(str(jdir.relative_to(args.image_dir)))+ ids_all.append(ids)+ fidx_all.append(np.full(ids.size, len(rel_dirs) - 1, dtype=np.int32))+ if i % 50 == 0 or i == len(folders) - 1:+ n = sum(a.size for a in ids_all)+ print(f" [{i + 1}/{len(folders)}] {n:,} images, "+ f"{time.time() - t0:.0f}s", flush=True)++ ids = np.concatenate(ids_all)+ fidx = np.concatenate(fidx_all)+ order = np.argsort(ids, kind="stable")+ ids, fidx = ids[order], fidx[order]+ print(f"\n{ids.size:,} images across {len(rel_dirs)} folders "+ f"in {time.time() - t0:.0f}s")++ # Are the folders contiguous, disjoint id blocks? Then 1000 rows suffice.+ lo = np.array([ids[fidx == k].min() for k in range(len(rel_dirs))])+ hi = np.array([ids[fidx == k].max() for k in range(len(rel_dirs))])+ o = np.argsort(lo)+ disjoint = bool(np.all(hi[o][:-1] < lo[o][1:]))++ payload = {"dirs": np.array(rel_dirs, dtype=object)}+ if disjoint:+ payload.update(mode=np.array("ranges"), lo=lo[o], hi=hi[o],+ folder=np.arange(len(rel_dirs))[o])+ print("folders hold disjoint id ranges -> compact range index")+ else:+ payload.update(mode=np.array("full"), ids=ids, folder=fidx)+ print("id ranges overlap -> full index")++ args.out.parent.mkdir(parents=True, exist_ok=True)+ np.savez_compressed(args.out, **payload)+ print(f"wrote {args.out} ({args.out.stat().st_size / 1e6:.1f} MB)")+ print(f"\nuse it with:\n"+ f" build_split.py --split sa1b_train --image-dir {args.image_dir} \\\n"+ f" --image-index {args.out} --originals link ...")+++if __name__ == "__main__":+ main()diff --git a/datasets_pipeline/probe_split.py b/datasets_pipeline/probe_split.pyindex 6eb5be3..6a15012 100755--- a/datasets_pipeline/probe_split.py+++ b/datasets_pipeline/probe_split.py@@ -7,10 +7,13 @@ reads only the annotations and answers, before you spend the bandwidth:size persons, unique frames, and how many GB of frames that implies.Totals extrapolate over the shards ON DISK, so fetch the wholesplit's annotations first if you want the true count.- labels keypoint visibility health. NOT cosmetic: SA-1B stores invisible+ labels keypoint visibility, reported separately for 2D and 3D because+ they differ. NOT cosmetic: SA-1B's 2D array stores unobservedkeypoints as literal (0, 0) with a visibility column that- parquet_to_npz.py discards, so a naive build writes 44 of 70+ parquet_to_npz.py discards, so a naive build writes ~45 of 70keypoints per person as fake observations at the image corner.+ Its 3D array and MHR params are complete, so the split is+ perfectly usable once the 2D losses are masked.hands how many hands are fully visible and how big their crop would besignal how far the finger poses sit from ONE constant hand pose, in mm atthe fingertips — an upper bound on what a hand branch could learn@@ -83,25 +86,31 @@ def probe(d: Path, shards: int, hand_expand: float, args) -> None:rows = 0frames: set[str] = set()all_vis = 0- zero_kps = []+ vis3d = []+ vis_body = []+ vis_hand = []params: list[np.ndarray] = []spans: list[float] = []hands_seen = hands_full = 0for f in used:t = pq.read_table(f, columns=["image", "mhr_valid", "keypoints_2d",- "model_params"])- for im, mv, k, mp in zip(t.column("image").to_pylist(),- t.column("mhr_valid").to_pylist(),- t.column("keypoints_2d").to_pylist(),- t.column("model_params").to_pylist()):+ "keypoints_3d", "model_params"])+ for im, mv, k, k3, mp in zip(t.column("image").to_pylist(),+ t.column("mhr_valid").to_pylist(),+ t.column("keypoints_2d").to_pylist(),+ t.column("keypoints_3d").to_pylist(),+ t.column("model_params").to_pylist()):if not mv:continuerows += 1frames.add(im)k = np.asarray(k, dtype=np.float32).reshape(70, 3)all_vis += bool((k[:, 2] > 0).all())- zero_kps.append(int(((k[:, 0] == 0) & (k[:, 1] == 0)).sum()))+ vis_body.append(float((k[:15, 2] > 0).mean()))+ vis_hand.append(float((k[21:63, 2] > 0).mean()))+ vis3d.append(float(+ (np.asarray(k3, dtype=np.float32).reshape(70, 4)[:, 3] > 0).mean()))params.append(np.asarray(mp, dtype=np.float32))for idx in (RIGHT_HAND_KPS, LEFT_HAND_KPS):hands_seen += 1@@ -125,9 +134,12 @@ def probe(d: Path, shards: int, hand_expand: float, args) -> None:f"({gb * 1000 / max(rows * scale, 1):.2f} MB per person crop){note}")pct = 100.0 * all_vis / max(rows, 1)- flag = "" if pct > 99 else " <-- gate hand boxes on joints_2d_vis"- print(f" all 70 kps visible : {pct:5.1f}% "- f"mean (0,0) placeholders {np.mean(zero_kps):.1f}/70{flag}")+ print(f" 2D kps visible : {pct:5.1f}% of rows have all 70 "+ f"(body {100 * np.mean(vis_body):.0f}%, hands {100 * np.mean(vis_hand):.0f}%)")+ print(f" 3D kps valid : {100 * np.mean(vis3d):5.1f}% of keypoints")+ if pct <= 99:+ print(" ^ mask the 2D losses with joints_2d_vis and gate hand "+ "boxes on it; the 3D labels above are unaffected")if spans:s = np.array(spans)diff --git a/datasets_pipeline/registry.py b/datasets_pipeline/registry.pyindex fd90f4a..201d6f6 100755--- a/datasets_pipeline/registry.py+++ b/datasets_pipeline/registry.py@@ -50,6 +50,11 @@ class Dataset:image_root_suffix: str = ""needs_undistort: bool = Falseapprox_gb: float = 0.0 # download size+ # Many HPC sites mirror the big public datasets into a read-only shared+ # space. Set SHARED_DATASET_DIR and check there before downloading —+ # presence of a directory is not enough, the referenced SUBSET has to be+ # there in the layout image_relpath() expects.+ shared_mirror: str = ""notes: str = ""# Per-scene/shard archives, for streaming one at a time. Empty means the# dataset arrives as one blob.@@ -77,8 +82,12 @@ DATASETS: dict[str, Dataset] = {method="direct",urls=("http://images.cocodataset.org/zips/train2014.zip",),approx_gb=13.5,+ shared_mirror="COCO",notes="Only train2014 is referenced by coco_train — val2014/test2014 are "- "a waste of 9 GB. Verified over every image string in shard 0.",+ "a waste of 9 GB. Verified over every image string in shard 0.\n"+ "If your site mirrors COCO, confirm the mirror carries train2014 "+ "and not just 2017 before trusting it, then build with "+ "--originals link instead of downloading.",),"mpii": Dataset(name="mpii",@@ -168,6 +177,7 @@ DATASETS: dict[str, Dataset] = {splits=("sa1b_train",),method="links_file",approx_gb=0.0,+ shared_mirror="SegmentAnything_1B",notes="1,850 annotation shards ~= 3.4M person crops — bigger than every ""other split combined. Accept the terms at ""https://ai.meta.com/datasets/segment-anything-downloads/ to get "@@ -184,8 +194,16 @@ DATASETS: dict[str, Dataset] = {"only 0.3% of hands are fully visible.\n""Any prefix of the tar list is a valid subset — each tar is ""self-contained and the builder skips rows whose image is absent "- "— so stream it and stop whenever. But spend the bandwidth on "- "egoexo4d first.",+ "— so stream it and stop whenever.\n"+ "If your site already mirrors SA-1B the download cost is zero and "+ "it becomes the largest body corpus here by far (3.4M persons, 4x "+ "everything else combined). A mirror that unpacked the 1000 tars "+ "in place needs index_sa1b.py + build_split.py --image-index, "+ "because the parquet asks for a flat sa_<id>.jpg. Its 3D "+ "keypoints and MHR params are 100% complete; only the 2D array is "+ "sparse (body 100%, feet 97%, hands 8%) — see the label trap in "+ "README.md. Near-useless for hand CROPS either way: 0.3% of hands "+ "have all 21 2D keypoints.",),}diff --git a/instanthmr_distill_train/train_distill_mhr_only.py b/instanthmr_distill_train/train_distill_mhr_only.pyindex 341f64f..2df05d2 100644--- a/instanthmr_distill_train/train_distill_mhr_only.py+++ b/instanthmr_distill_train/train_distill_mhr_only.py@@ -368,6 +368,22 @@ class SAM3DStudentDataset(Dataset):joints_2d[:, 0] = (joints_2d[:, 0] / self.image_size) * 2.0 - 1.0joints_2d[:, 1] = (joints_2d[:, 1] / self.image_size) * 2.0 - 1.0+ # Per-keypoint 2D visibility. Present only on folders built by+ # datasets_pipeline/build_split.py; older folders (and every split+ # except SA-1B) are fully observed, so the all-ones default reproduces+ # the previous behaviour bit for bit.+ #+ # SA-1B is the one split that needs this: its keypoints_2d stores+ # unobserved points as literal (0, 0) with a graded confidence in the+ # third column — body 100% observed, feet 97%, hands 8%. Training on it+ # without the mask drags every predicted hand keypoint to the top-left+ # of the frame. The 3D keypoints and the MHR params are complete, so+ # only the 2D losses need it.+ if "joints_2d_vis" in ann:+ joints_2d_vis = ann["joints_2d_vis"].astype(np.float32).copy()+ else:+ joints_2d_vis = np.ones(joints_2d.shape[0], dtype=np.float32)+joints_3d = ann["joints_3d"].astype(np.float32).copy()cam_trans = ann["cam_trans"].astype(np.float32).copy()@@ -422,6 +438,7 @@ class SAM3DStudentDataset(Dataset):# Without this the 2D head gets contradictory left/right supervision# and collapses symmetric joints toward the body midline.joints_2d = joints_2d[FLIP_PERM]+ joints_2d_vis = joints_2d_vis[FLIP_PERM]cam_trans[0] = -cam_trans[0]cx = orig_w - cxrad = math.radians(angle)@@ -448,6 +465,7 @@ class SAM3DStudentDataset(Dataset):"cam_trans": torch.from_numpy(cam_trans).float(),"cam_focal": torch.from_numpy(ann["cam_focal_length"]).float(),"joints_2d": torch.from_numpy(joints_2d).float(),+ "joints_2d_vis": torch.from_numpy(joints_2d_vis).float(),"joints_3d": torch.from_numpy(joints_3d).float(),"orig_shape": torch.tensor([orig_h, orig_w], dtype=torch.float32),"bbox_square": sq_bbox,@@ -720,7 +738,18 @@ class DistillationLoss(nn.Module):e = (pred - tgt).abs().flatten(1).mean(1)return self._mmean(e, mask)- def _simcc_ce(self, logits, tgt_2d):+ @staticmethod+ def _kp_weighted(per_kp, w_kp, m_sample=None):+ """Mean of a (B, K) error under per-keypoint weights and a sample mask.++ With w_kp all ones and no sample mask this is exactly `.mean()`, so the+ masked 2D losses below are numerically identical to the unmasked ones+ on every split that is fully observed.+ """+ w = w_kp if m_sample is None else w_kp * m_sample.view(-1, 1)+ return (per_kp * w).sum() / w.sum().clamp_min(1e-6)++ def _simcc_ce(self, logits, tgt_2d, w_kp=None):bins = torch.linspace(-self.cfg.kp2d_range, self.cfg.kp2d_range,self.cfg.kp2d_bins, device=logits.device)tgt = tgt_2d.clamp(-self.cfg.kp2d_range, self.cfg.kp2d_range)@@ -728,7 +757,10 @@ class DistillationLoss(nn.Module):label = torch.exp(-(d ** 2) / (2.0 * self.simcc_sigma ** 2))label = label / label.sum(dim=-1, keepdim=True).clamp_min(1e-8)logp = F.log_softmax(logits, dim=-1)- return -(label * logp).sum(dim=-1).mean()+ per_kp = -(label * logp).sum(dim=-1).mean(dim=-1) # (B, K), mean over x/y+ if w_kp is None:+ return per_kp.mean()+ return self._kp_weighted(per_kp, w_kp)def _project_3d_to_norm_2d(self, j3d, pred_cam_trans, targets):j3d_cam = j3d + pred_cam_trans.unsqueeze(1)@@ -809,12 +841,26 @@ class DistillationLoss(nn.Module):tgt_2d = targets["joints_2d"]tgt_3d = targets["joints_3d"]+ # Per-keypoint 2D observation weight. All-ones unless the dataset+ # supplies `joints_2d_vis` (only SA-1B does), in which case the three+ # 2D terms below skip the keypoints whose target is a (0, 0)+ # placeholder. Measured on SA-1B: vis > 0 <=> the coordinate is real,+ # with zero exceptions in 183k keypoints, so this gate is exact; the+ # graded values (0.25 / 0.5 / 1.0) additionally down-weight the+ # uncertain observations.+ w_kp = targets.get("joints_2d_vis")+ if w_kp is None:+ w_kp = torch.ones_like(tgt_2d[..., 0])+# 2D head — training-only auxiliary task, and the ONLY supervision that# survives a horizontal flip in full (targets["joints_2d"] is mirrored- # AND FLIP_PERM-permuted by the dataset, so it stays self-consistent).- losses['loss_2d_native'] = self.l1(pred_2d[..., :2], tgt_2d) * self.cfg.w_keypoints2d+ # AND FLIP_PERM-permuted by the dataset, so it stays self-consistent —+ # and so is joints_2d_vis).+ e2d = F.smooth_l1_loss(pred_2d[..., :2], tgt_2d, reduction='none').mean(-1)+ losses['loss_2d_native'] = self._kp_weighted(e2d, w_kp) * self.cfg.w_keypoints2dif "joints_2d_logits" in preds:- losses['loss_2d_simcc'] = self._simcc_ce(preds["joints_2d_logits"], tgt_2d) * self.cfg.w_simcc+ losses['loss_2d_simcc'] = self._simcc_ce(+ preds["joints_2d_logits"], tgt_2d, w_kp) * self.cfg.w_simcc# Main 3D loss, now on the MHR-derived keypoints. Deliberately UNMASKED:# targets["joints_3d"] is mirrored + permuted under flip, and the MHR rest@@ -842,7 +888,9 @@ class DistillationLoss(nn.Module):# need an extra FLIP_PERM + cx mirror that is not worth the complexity# for a 0.01-weight auxiliary term.pred_reproj = self._project_3d_to_norm_2d(_counter_rot_pts(pred_kp3d), cam_cr, targets)- losses['loss_reproj'] = self.m_l1(pred_reproj, tgt_2d, m_noflip) * self.cfg.w_reproj * self.fk_scale+ e_reproj = (pred_reproj - tgt_2d).abs().mean(-1)+ losses['loss_reproj'] = self._kp_weighted(+ e_reproj, w_kp, m_noflip) * self.cfg.w_reproj * self.fk_scalelosses['total_loss'] = sum(losses.values())return losses