Add frozen ARCTIC V006 MANO adaptation source snapshot
Browse files- releases/20261105_arctic_render_v006_refit/source_snapshot/docs/ARCTIC_V006_MANO_ADAPTATION_20261104_ZH.md +109 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/__init__.py +1 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/data.py +95 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/prepare.py +209 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/verify.py +116 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/src/foundation_hand/data/egorender_arctic_mano.py +220 -0
- releases/20261105_arctic_render_v006_refit/source_snapshot/tests/test_egorender_arctic_v006.py +228 -0
releases/20261105_arctic_render_v006_refit/source_snapshot/docs/ARCTIC_V006_MANO_ADAPTATION_20261104_ZH.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ARCTIC V006 MANO 适配结果
|
| 2 |
+
|
| 3 |
+
2026-11-04 已完成 301 条序列、218,273 帧的独立标签适配与检查。可用数据入口:
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
/data5/yifanwu/EgoNet_Data/egorender_arctic_v006_mano_20261104_r2/
|
| 7 |
+
```
|
| 8 |
+
|
| 9 |
+
`manifest.json` 与 `verification.json` 均为 PASS。标签缓存约 367 MiB。
|
| 10 |
+
保留下载包 `part_001`、`part_002` 的原目录和两份 INDEX,没有拼接视频。
|
| 11 |
+
当前 RGB-clean SFT 的冻结数据清单、训练代码快照、采样计划与权重均未更改。
|
| 12 |
+
|
| 13 |
+
## 解码与监督约定
|
| 14 |
+
|
| 15 |
+
1. 原参数使用官方 ARCTIC 的 non-flat mean、原生 left shapedirs。先以
|
| 16 |
+
non-flat manopth 解码毫米,再转米并加原始 `left/right_trans`。
|
| 17 |
+
2. 使用 metadata 的 `mano_reconstruction.composed_original_to_world`,
|
| 18 |
+
然后乘逐帧 `world_to_camera`。原始 translation 不是 wrist;监督 wrist
|
| 19 |
+
是解码和变换后的 joint 0。
|
| 20 |
+
3. 目标 full local axis-angle 只加一次官方 mean。相机 global orientation
|
| 21 |
+
由相机、source-to-world 和原 global orientation 按顺序相乘,不对局部姿态
|
| 22 |
+
重复变换。
|
| 23 |
+
4. 原始双手 joints 始终保存在 `joints_native`,独立于 corrected 标签是否存在。
|
| 24 |
+
hand presence 按原生 mesh 是否进入画面判断,不因物体遮挡或 wrist 出画而
|
| 25 |
+
单独丢弃整只手;没有用场景语义分割替代左右手标签。
|
| 26 |
+
5. 右手与模型基底兼容,原参数经过重建门限后直接监督。左手优先复用已有
|
| 27 |
+
同源 ARCTIC corrected-left 标签,检查原始 MANO 文件 SHA256,再按原始帧号
|
| 28 |
+
匹配,经原 ego camera 的逆变换回到原始坐标,最后转入新 render camera。
|
| 29 |
+
6. 左手没有兼容标签的帧保留 native 几何监督,只关闭不兼容的 pose/shape
|
| 30 |
+
监督。原参数若自身通过 1 mm 顶点基底兼容门限也可作为参数目标。
|
| 31 |
+
拟合标签继续标明 refit 来源,不能称为原始参数 GT。
|
| 32 |
+
7. 旧真实 RGB 标签缺少的 7 个原始帧仍保留在新包中,不做索引偏移或用邻帧
|
| 33 |
+
补标签。缺失 corrected 标签不会改变 native 几何分母。
|
| 34 |
+
|
| 35 |
+
## 全量验证
|
| 36 |
+
|
| 37 |
+
| 项目 | 结果 |
|
| 38 |
+
| --- | ---: |
|
| 39 |
+
| train / val 序列 | 267 / 34 |
|
| 40 |
+
| train / val 帧 | 192,390 / 25,883 |
|
| 41 |
+
| 双深度序列 | 299,其中 train 265、val 34 |
|
| 42 |
+
| 原生有效手帧,左 / 右 | 174,521 / 180,901 |
|
| 43 |
+
| 兼容参数有效手帧,左 / 右 | 133,962 / 180,901 |
|
| 44 |
+
| 匹配复用的 corrected-left 帧,含新视角出画帧 | 144,564 |
|
| 45 |
+
| 原生几何与旧标签经坐标变换后的最大差异 | 0.000257 mm |
|
| 46 |
+
| 有效参数重建其目标 joints 最大差异,左 / 右 | 0.000185 / 0.000223 mm |
|
| 47 |
+
| 有效参数目标相对原生 joints 平均差异,左 / 右 | 0.5344 / 0.000047 mm |
|
| 48 |
+
| 同上,每手帧关节平均差异的 P95,左 / 右 | 0.7647 / 0.000068 mm |
|
| 49 |
+
|
| 50 |
+
上面的重建差异检查解码约定是否一致;0.5344 mm 则是左手兼容参数标签相对
|
| 51 |
+
原始关节几何的平均拟合差异,两者均不是网络预测精度。全量 native 几何的
|
| 52 |
+
评估 mask 不按拟合可用性缩小。验证集没有导入训练用 corrected-left 标签;
|
| 53 |
+
验证集左手仍可评估原生关节几何。
|
| 54 |
+
|
| 55 |
+
对所有标签检查 SHA256、帧覆盖、参数重建门限和 train/val 隔离。实际解码
|
| 56 |
+
7 个 T8 case,覆盖两包的 train/val、无干净 GT 的样本和末尾 padding;
|
| 57 |
+
经过 `adapt_inputs`、`adapt_targets` 和 camera motion 的 `relative_targets`
|
| 58 |
+
后检查通过。这里的 projection roundtrip 检查的是同一 K/resize 下的标签一致性,
|
| 59 |
+
不代替逐帧图像人工标注审查。
|
| 60 |
+
|
| 61 |
+
25 项测试通过,覆盖非平 mean、非交换旋转次序、raw translation/wrist 区别、
|
| 62 |
+
左右基底、corrected 标签转相机、缺帧精确匹配、错误标签拒收、米制深度、
|
| 63 |
+
sensor 空洞、padding 与 GT 不进入模型 inputs。
|
| 64 |
+
|
| 65 |
+
## 使用入口
|
| 66 |
+
|
| 67 |
+
源码:
|
| 68 |
+
|
| 69 |
+
- `src/foundation_hand/data/egorender_arctic_mano.py`:MANO 几何与标签适配。
|
| 70 |
+
- `experiments/egorender_arctic_v006/prepare.py`:双索引、split、哈希、缓存与来源冻结。
|
| 71 |
+
- `experiments/egorender_arctic_v006/data.py`:新包 T8 读取器。
|
| 72 |
+
- `experiments/egorender_arctic_v006/verify.py`:全量检查和实际 reader smoke。
|
| 73 |
+
- `tests/test_egorender_arctic_v006.py`:针对本适配的回归测试。
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
from experiments.egorender_arctic_v006.data import V006Dataset
|
| 77 |
+
|
| 78 |
+
dataset = V006Dataset(
|
| 79 |
+
"/data5/yifanwu/EgoNet_Data/egorender_arctic_v006_mano_20261104_r2",
|
| 80 |
+
split="train", sensor_input=True, paired_only=False,
|
| 81 |
+
)
|
| 82 |
+
sample = dataset[0] # inputs / targets / meta,与现有 SFT batch adapter 对接
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
`sensor_input=False` 用于无深度输入;`paired_only=True` 筛选双深度完整样本。
|
| 86 |
+
网络 depth 输入只读取 sensor,米制数值直接使用;不以干净 GT 填洞。
|
| 87 |
+
干净 GT 路径独立登记在 record 的 `clean_depth`,默认不作为模型输入。
|
| 88 |
+
所有 native 参数明确标为 `native_corrected_basis=False`,避免旧接口将所有
|
| 89 |
+
EgoRenderer 样本一律视为 corrected 标签。
|
| 90 |
+
|
| 91 |
+
复现命��,在项目根目录并使用安装了 NumPy、PyTorch、manopth 的环境运行:
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
export PYTHONPATH="$PWD/src:$PWD:$PWD/runtime/code/manopth"
|
| 95 |
+
runtime/venv/bin/python -m experiments.egorender_arctic_v006.prepare \
|
| 96 |
+
--output /path/to/new/output
|
| 97 |
+
runtime/venv/bin/python -m experiments.egorender_arctic_v006.verify \
|
| 98 |
+
--root /path/to/new/output
|
| 99 |
+
runtime/venv/bin/python -m pytest -q \
|
| 100 |
+
tests/test_egorender_arctic_v006.py tests/test_phase7_arctic_adapter.py \
|
| 101 |
+
tests/test_mano_translation.py tests/test_local_sft_data.py
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
输出合同冻结两份索引、随包读取器、MANO 资产、适配源码和已有 ARCTIC 标签
|
| 105 |
+
清单的 SHA256;每个 record 另绑定相机、MANO、metadata、reference labels
|
| 106 |
+
及生成标签哈希。恢复时拒绝不同合同或被改写的缓存。
|
| 107 |
+
|
| 108 |
+
这批新数据已具备单独读取的 MANO 标签和 batch 接口。把它加入正式 SFT
|
| 109 |
+
仍需登记新的数据/采样合同,并完成该新训练池的 RGB 质量资格检查。
|
releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""ARCTIC V006 rendered packages; independent of frozen historical SFT runs."""
|
releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/data.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""T8 reader for adapted V006 MANO labels and optional simulated sensor depth."""
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from foundation_hand.data.h2o_dataset import _resize_pad
|
| 13 |
+
from experiments.local_sft.data import PreparedSFTDataset
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class V006Dataset(PreparedSFTDataset):
|
| 17 |
+
def __init__(self, root, split="train", target_hw=(512, 896),
|
| 18 |
+
sensor_input=True, paired_only=False):
|
| 19 |
+
root = Path(root)
|
| 20 |
+
manifest = json.loads((root / "manifest.json").read_text())
|
| 21 |
+
if manifest["status"] != "PASS" or manifest["schema"] != "egonet.arctic_v006_mano.v1":
|
| 22 |
+
raise ValueError("Expected verified V006 MANO manifest")
|
| 23 |
+
def sha(path):
|
| 24 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 25 |
+
if (sha(root / "contract.json") != manifest["contract_sha256"]
|
| 26 |
+
or sha(manifest["records"]) != manifest["records_sha256"]
|
| 27 |
+
or sha(manifest["clips"][split]) != manifest["clips_sha256"][split]):
|
| 28 |
+
raise ValueError("Prepared manifest assets changed")
|
| 29 |
+
self.contract = json.loads((root / "contract.json").read_text())
|
| 30 |
+
super().__init__(root, split=split, target_hw=target_hw)
|
| 31 |
+
self.sensor_input = sensor_input
|
| 32 |
+
if paired_only:
|
| 33 |
+
self.clips = [c for c in self.clips if not self.records[c["record_id"]]["missing_channels"]]
|
| 34 |
+
for row in self.records.values():
|
| 35 |
+
if row["native_corrected_basis"] or row["depth_input_available"]:
|
| 36 |
+
raise ValueError("V006 native basis/depth routing contract differs")
|
| 37 |
+
|
| 38 |
+
@lru_cache(maxsize=4)
|
| 39 |
+
def labels(self, record_id):
|
| 40 |
+
row = self.records[record_id]
|
| 41 |
+
if hashlib.sha256(Path(row["labels"]).read_bytes()).hexdigest() != row["labels_sha256"]:
|
| 42 |
+
raise ValueError("Adapted MANO labels changed")
|
| 43 |
+
with np.load(row["labels"], allow_pickle=False) as archive:
|
| 44 |
+
return {key: archive[key] for key in archive.files}
|
| 45 |
+
|
| 46 |
+
@lru_cache(maxsize=2)
|
| 47 |
+
def reader_class(self, part):
|
| 48 |
+
path = Path(self.contract["dataset"]) / part / "egorender_reader.py"
|
| 49 |
+
if hashlib.sha256(path.read_bytes()).hexdigest() != self.contract["readers"][part]:
|
| 50 |
+
raise ValueError("Bundled depth reader changed")
|
| 51 |
+
spec = importlib.util.spec_from_file_location("egorender_v006_" + part, path)
|
| 52 |
+
module = importlib.util.module_from_spec(spec)
|
| 53 |
+
spec.loader.exec_module(module)
|
| 54 |
+
return module.DepthReader
|
| 55 |
+
|
| 56 |
+
@lru_cache(maxsize=4)
|
| 57 |
+
def depth_reader(self, record_id):
|
| 58 |
+
row = self.records[record_id]
|
| 59 |
+
return self.reader_class(row["part"])(row["sensor_depth"])
|
| 60 |
+
|
| 61 |
+
def __getitem__(self, index):
|
| 62 |
+
sample = super().__getitem__(index)
|
| 63 |
+
clip = self.clips[index]
|
| 64 |
+
row = self.records[clip["record_id"]]
|
| 65 |
+
labels = self.labels(row["id"])
|
| 66 |
+
ids = np.asarray(clip["indices"])
|
| 67 |
+
safe = np.maximum(ids, 0)
|
| 68 |
+
valid = ids >= 0
|
| 69 |
+
# Provenance must override historical assumptions that every render is corrected.
|
| 70 |
+
sample["targets"]["native_corrected_basis"] = torch.tensor(False)
|
| 71 |
+
sample["targets"]["has_3d_gt"] = torch.from_numpy(labels["has_3d_gt"][safe] & valid)
|
| 72 |
+
for key in ("native_pose", "native_beta", "native_wrist"):
|
| 73 |
+
sample["targets"][key] = torch.from_numpy(labels[key][safe].copy())
|
| 74 |
+
sample["inputs"]["depth_available"][:] = False
|
| 75 |
+
if self.sensor_input:
|
| 76 |
+
reader = self.depth_reader(row["id"])
|
| 77 |
+
for t, frame in enumerate(ids):
|
| 78 |
+
if frame < 0:
|
| 79 |
+
continue
|
| 80 |
+
depth_m, depth_valid, source_frame = reader.frame(int(frame))
|
| 81 |
+
if source_frame != int(labels["source_frame_ids"][frame]):
|
| 82 |
+
raise ValueError("Sensor/MANO frame mapping differs")
|
| 83 |
+
if depth_m.shape != tuple(row["image_hw"]) or depth_valid.shape != depth_m.shape:
|
| 84 |
+
raise ValueError("Sensor/RGB image shape differs")
|
| 85 |
+
depth, _, _ = _resize_pad(depth_m, self.target_hw, cv2.INTER_NEAREST)
|
| 86 |
+
mask, _, _ = _resize_pad(depth_valid.astype(np.uint8), self.target_hw, cv2.INTER_NEAREST)
|
| 87 |
+
mask = (mask.astype(bool) & np.isfinite(depth) & (depth > 0)
|
| 88 |
+
& sample["inputs"]["pixel_valid"][t, 0].numpy())
|
| 89 |
+
depth = np.where(mask, depth, 0).astype(np.float32)
|
| 90 |
+
sample["inputs"]["depth_m"][t, 0] = torch.from_numpy(depth)
|
| 91 |
+
sample["inputs"]["depth_valid"][t, 0] = torch.from_numpy(mask)
|
| 92 |
+
sample["inputs"]["depth_available"][t] = True
|
| 93 |
+
sample["meta"].update(clip_index=index, label_type=row["label_type"],
|
| 94 |
+
part=row["part"], sequence=row["sequence"])
|
| 95 |
+
return sample
|
releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/prepare.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Freeze native geometry and compatible MANO targets for both V006 parts."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from foundation_hand.data.egorender_arctic_mano import ArcticRenderMANO
|
| 13 |
+
from experiments.local_sft.common import windows
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def sha(path):
|
| 19 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def save(path, value):
|
| 23 |
+
path = Path(path)
|
| 24 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 25 |
+
temporary = path.with_name(path.name + ".tmp")
|
| 26 |
+
temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
|
| 27 |
+
temporary.replace(path)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def jsonl(path, values):
|
| 31 |
+
path = Path(path)
|
| 32 |
+
temporary = path.with_name(path.name + ".tmp")
|
| 33 |
+
with temporary.open("w") as f:
|
| 34 |
+
for value in values:
|
| 35 |
+
f.write(json.dumps(value, ensure_ascii=False, allow_nan=False) + "\n")
|
| 36 |
+
temporary.replace(path)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def catalog(root, references):
|
| 40 |
+
sources, seen = [], set()
|
| 41 |
+
for part in ("part_001", "part_002"):
|
| 42 |
+
index_path = root / part / "INDEX.json"
|
| 43 |
+
index = json.loads(index_path.read_text())
|
| 44 |
+
if index["part"] != part or index["dataset"] != "ARCTIC":
|
| 45 |
+
raise ValueError("Unexpected part identity")
|
| 46 |
+
for source in index["sources"]:
|
| 47 |
+
name = source["sequence"]
|
| 48 |
+
if name in seen or not name.startswith("arctic_") or "/" in name or ".." in name:
|
| 49 |
+
raise ValueError("Duplicate or unsafe sequence name")
|
| 50 |
+
seen.add(name)
|
| 51 |
+
subject, action = name[len("arctic_"):].split("_", 1)
|
| 52 |
+
recording = subject + "/" + action
|
| 53 |
+
reference = references[recording]
|
| 54 |
+
if reference["split"] not in ("train", "val"):
|
| 55 |
+
raise ValueError("No registered train/val split for source")
|
| 56 |
+
sources.append(dict(source, part=part, recording=recording,
|
| 57 |
+
split=reference["split"], package=str(root / part / "samples" / name),
|
| 58 |
+
index_path=str(index_path), index_sha256=sha(index_path)))
|
| 59 |
+
return sources
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def prepare_one(source, reference, output, adapter):
|
| 63 |
+
package = Path(source["package"])
|
| 64 |
+
record_id = hashlib.sha256((source["index_sha256"] + source["sequence"]).encode()).hexdigest()[:24]
|
| 65 |
+
receipt_path = output / "records" / (record_id + ".json")
|
| 66 |
+
if receipt_path.exists():
|
| 67 |
+
row = json.loads(receipt_path.read_text())
|
| 68 |
+
if (sha(row["labels"]) != row["labels_sha256"]
|
| 69 |
+
or sha(package / "metadata.json") != row["metadata_sha256"]
|
| 70 |
+
or sha(reference["labels"]) != row["reference_labels_sha256"]
|
| 71 |
+
or any(sha(package / name) != expected for name, expected in row["input_sha256"].items())):
|
| 72 |
+
raise ValueError("Prepared label cache changed")
|
| 73 |
+
return row
|
| 74 |
+
meta_path = package / "metadata.json"
|
| 75 |
+
metadata = json.loads(meta_path.read_text())
|
| 76 |
+
if metadata["sequence_index"] != source["sequence"] or metadata["frames"] != source["frames"]:
|
| 77 |
+
raise ValueError("Metadata and index disagree")
|
| 78 |
+
original_hash = metadata["mano_reconstruction"]["original_dataset_parameters"]["sha256"]
|
| 79 |
+
original_refs = [v for k, v in reference["annotation_inputs"].items() if k.endswith(".mano.npy")]
|
| 80 |
+
if original_refs != [original_hash]:
|
| 81 |
+
raise ValueError("Corrected reference is not from the same original MANO file")
|
| 82 |
+
inputs = {}
|
| 83 |
+
for filename in ("mano_parameters.npz", "camera_parameters.npz"):
|
| 84 |
+
path = package / filename
|
| 85 |
+
actual = sha(path)
|
| 86 |
+
if actual != source["files"][filename]["sha256"]:
|
| 87 |
+
raise ValueError("Input SHA256 differs from preserved INDEX: " + filename)
|
| 88 |
+
inputs[filename] = actual
|
| 89 |
+
if inputs["mano_parameters.npz"] != metadata["mano_reconstruction"]["original_params_sha256"]:
|
| 90 |
+
raise ValueError("MANO reconstruction metadata binding differs")
|
| 91 |
+
reference_path = Path(reference["labels"])
|
| 92 |
+
if sha(reference_path) != reference["labels_sha256"]:
|
| 93 |
+
raise ValueError("Original ARCTIC reference labels changed")
|
| 94 |
+
with np.load(reference_path, allow_pickle=False) as archive:
|
| 95 |
+
ref = {key: archive[key] for key in archive.files}
|
| 96 |
+
if reference["split"] != "train" and ref["canonical_available"].any():
|
| 97 |
+
raise ValueError("Unexpected fitted parameter targets in held-out reference")
|
| 98 |
+
with np.load(package / "mano_parameters.npz", allow_pickle=False) as parameters, np.load(
|
| 99 |
+
package / "camera_parameters.npz", allow_pickle=False
|
| 100 |
+
) as camera:
|
| 101 |
+
arrays, verification = adapter.adapt(parameters, camera, metadata, ref)
|
| 102 |
+
hw = list(map(int, camera["image_size"][::-1]))
|
| 103 |
+
if verification["rejected_refit_regeneration_frames"]:
|
| 104 |
+
raise ValueError("Corrected-left refit failed the 1 mm reconstruction gate")
|
| 105 |
+
label_path = output / "labels" / (record_id + ".npz")
|
| 106 |
+
label_path.parent.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
temporary = label_path.with_name(record_id + ".tmp.npz")
|
| 108 |
+
np.savez_compressed(temporary, **arrays)
|
| 109 |
+
temporary.replace(label_path)
|
| 110 |
+
row = dict(id=record_id, source="EgoRenderer", recording=source["recording"],
|
| 111 |
+
physical_recording="ARCTIC/" + source["recording"], split=source["split"],
|
| 112 |
+
dataset="ARCTIC", release="V006", part=source["part"], sequence=source["sequence"],
|
| 113 |
+
package=str(package), video=str(package / "rgb.mp4"),
|
| 114 |
+
rgb_sha256=source["files"]["rgb.mp4"]["sha256"], frames=source["frames"],
|
| 115 |
+
fps=metadata["fps"], image_hw=hw, labels=str(label_path), labels_sha256=sha(label_path),
|
| 116 |
+
camera_calibrated=True, camera_pose_valid=True, rectify_rgb=False,
|
| 117 |
+
# RGB is read by the prepared reader; sensor NPZ is added by V006Dataset.
|
| 118 |
+
depth_input_available=False, sensor_depth=str(package / "depth_sensor_u16.npz"),
|
| 119 |
+
clean_depth=str(package / "depth_gt_mm.npz") if "gt" not in source["missing_channels"] else None,
|
| 120 |
+
missing_channels=source["missing_channels"], depth_unit="reader_returns_meters_z_depth",
|
| 121 |
+
native_corrected_basis=False, label_type="ARCTIC_native_geometry_separate_corrected_parameter_targets",
|
| 122 |
+
index_path=source["index_path"], index_sha256=source["index_sha256"],
|
| 123 |
+
input_sha256=inputs, metadata_sha256=sha(meta_path), original_arctic_mano_sha256=original_hash,
|
| 124 |
+
reference_labels=str(reference_path), reference_labels_sha256=reference["labels_sha256"],
|
| 125 |
+
corrected_reference=reference.get("canonical"), verification=verification)
|
| 126 |
+
save(receipt_path, row)
|
| 127 |
+
return row
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main():
|
| 131 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 132 |
+
parser.add_argument("--dataset", type=Path, default=ROOT / "SFT_data/incoming_baidu_20261104/egorenderer-v006-arctic")
|
| 133 |
+
parser.add_argument("--references", type=Path, default=ROOT / "SFT_data/processed_20261029/real_ARCTIC_records.jsonl")
|
| 134 |
+
parser.add_argument("--mano-root", type=Path, default=ROOT / "runtime/assets/mano")
|
| 135 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 136 |
+
parser.add_argument("--limit", type=int, help="Small independent smoke output only")
|
| 137 |
+
parser.add_argument("--threads", type=int, default=2)
|
| 138 |
+
args = parser.parse_args()
|
| 139 |
+
torch.set_num_threads(args.threads)
|
| 140 |
+
os.nice(10)
|
| 141 |
+
output = args.output.resolve()
|
| 142 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 143 |
+
references = {r["recording"]: r for line in args.references.read_text().splitlines() for r in [json.loads(line)]}
|
| 144 |
+
sources = catalog(args.dataset.resolve(), references)
|
| 145 |
+
if args.limit is not None:
|
| 146 |
+
if args.limit <= 0:
|
| 147 |
+
raise ValueError("Smoke limit must be positive")
|
| 148 |
+
sources = sources[:args.limit]
|
| 149 |
+
import foundation_hand.data.egorender_arctic_mano as adapter_module
|
| 150 |
+
contract = dict(schema="egonet.arctic_v006_mano.v1", dataset=str(args.dataset.resolve()),
|
| 151 |
+
indices={s["part"]: s["index_sha256"] for s in sources},
|
| 152 |
+
readers={part: sha(args.dataset / part / "egorender_reader.py") for part in ("part_001", "part_002")},
|
| 153 |
+
source_sha256={"adapter": sha(adapter_module.__file__), "prepare": sha(__file__),
|
| 154 |
+
"data": sha(Path(__file__).with_name("data.py"))},
|
| 155 |
+
reference_index=str(args.references.resolve()), reference_index_sha256=sha(args.references),
|
| 156 |
+
mano_assets={s: sha(args.mano_root / ("MANO_" + s.upper() + ".pkl")) for s in ("left", "right")},
|
| 157 |
+
limit=args.limit, parameter_reconstruction_gate_mm=1.,
|
| 158 |
+
native_geometry="official_nonflat_uncorrected_left", model_geometry="full_pose_corrected_left",
|
| 159 |
+
split_policy="inherit_original_ARCTIC_recording", training_registered=False)
|
| 160 |
+
contract_path = output / "contract.json"
|
| 161 |
+
if contract_path.exists() and json.loads(contract_path.read_text()) != contract:
|
| 162 |
+
raise ValueError("Resume contract differs; use a new output directory")
|
| 163 |
+
save(contract_path, contract)
|
| 164 |
+
adapter = ArcticRenderMANO(args.mano_root)
|
| 165 |
+
records, clips = [], []
|
| 166 |
+
begin = time.time()
|
| 167 |
+
for i, source in enumerate(sources):
|
| 168 |
+
row = prepare_one(source, references[source["recording"]], output, adapter)
|
| 169 |
+
records.append(row)
|
| 170 |
+
with np.load(row["labels"], allow_pickle=False) as labels:
|
| 171 |
+
for indices in windows(labels["source_frame_ids"]):
|
| 172 |
+
clips.append(dict(record_id=row["id"], source=row["source"], split=row["split"], indices=indices))
|
| 173 |
+
state = dict(stage="preparing", sequences=i + 1, total=len(sources),
|
| 174 |
+
frames=sum(r["frames"] for r in records), seconds=round(time.time() - begin, 1),
|
| 175 |
+
last_sequence=row["sequence"])
|
| 176 |
+
save(output / "status.json", state)
|
| 177 |
+
if i % 10 == 0 or i + 1 == len(sources):
|
| 178 |
+
print(json.dumps(state), flush=True)
|
| 179 |
+
jsonl(output / "records.jsonl", records)
|
| 180 |
+
by_id = {r["id"]: r for r in records}
|
| 181 |
+
index_paths = {}
|
| 182 |
+
for split in ("train", "val"):
|
| 183 |
+
index_paths[split] = str(output / ("clips_" + split + "_t8.jsonl"))
|
| 184 |
+
selected = [c for c in clips if c["split"] == split]
|
| 185 |
+
jsonl(index_paths[split], selected)
|
| 186 |
+
jsonl(output / ("clips_" + split + "_paired_t8.jsonl"),
|
| 187 |
+
[c for c in selected if not by_id[c["record_id"]]["missing_channels"]])
|
| 188 |
+
manifest = dict(status="PASS", schema=contract["schema"], records=str(output / "records.jsonl"),
|
| 189 |
+
records_sha256=sha(output / "records.jsonl"), clips=index_paths,
|
| 190 |
+
clips_sha256={k: sha(v) for k, v in index_paths.items()}, contract_sha256=sha(contract_path),
|
| 191 |
+
sequences=len(records), frames=sum(r["frames"] for r in records),
|
| 192 |
+
split_sequences={s: sum(r["split"] == s for r in records) for s in index_paths},
|
| 193 |
+
paired_sequences=sum(not r["missing_channels"] for r in records),
|
| 194 |
+
geometry_valid=np.sum([r["verification"]["geometry_valid"] for r in records], axis=0).tolist(),
|
| 195 |
+
parameter_valid=np.sum([r["verification"]["parameter_valid"] for r in records], axis=0).tolist(),
|
| 196 |
+
corrected_left_reused_frames=sum(r["verification"]["corrected_left_reused_frames"] for r in records),
|
| 197 |
+
reference_frames_absent=sum(r["verification"]["reference_frames_absent"] for r in records),
|
| 198 |
+
reference_native_max_mm=max(r["verification"]["reference_native_max_mm"] for r in records),
|
| 199 |
+
valid_parameter_regen_max_mm=[max((r["verification"]["valid_parameter_regen_max_mm"][h]
|
| 200 |
+
or 0) for r in records) for h in range(2)],
|
| 201 |
+
training_registered=False, visibility_provenance="native_mesh_in_frame_any_vertex_no_occlusion_rejection",
|
| 202 |
+
notes="Native GT denominators do not depend on corrected-fit availability. No historical training assets changed.")
|
| 203 |
+
save(output / "manifest.json", manifest)
|
| 204 |
+
save(output / "status.json", dict(stage="complete", **manifest, seconds=round(time.time() - begin, 1)))
|
| 205 |
+
print(json.dumps(manifest), flush=True)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
+
main()
|
releases/20261105_arctic_render_v006_refit/source_snapshot/experiments/egorender_arctic_v006/verify.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit the complete adapted pool and exercise real T8 training dictionaries."""
|
| 2 |
+
import argparse
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from torch.utils.data._utils.collate import default_collate
|
| 10 |
+
|
| 11 |
+
from experiments.camera_motion_sft.geometry import relative_targets
|
| 12 |
+
from experiments.egorender_arctic_v006.data import V006Dataset
|
| 13 |
+
from experiments.egorender_arctic_v006.prepare import save, sha
|
| 14 |
+
from experiments.local_sft.batch import adapt_inputs, adapt_targets
|
| 15 |
+
from experiments.local_sft.data import read_jsonl
|
| 16 |
+
from foundation_hand.geometry.camera import project_points
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 21 |
+
parser.add_argument("--root", type=Path, required=True)
|
| 22 |
+
args = parser.parse_args()
|
| 23 |
+
torch.set_num_threads(2)
|
| 24 |
+
root = args.root.resolve()
|
| 25 |
+
manifest = json.loads((root / "manifest.json").read_text())
|
| 26 |
+
records = read_jsonl(manifest["records"])
|
| 27 |
+
errors, split_counts, geometry, parameters = [], {}, np.zeros(2, int), np.zeros(2, int)
|
| 28 |
+
candidate, frame_maps, fit_errors = {}, {}, [[], []]
|
| 29 |
+
for row in records:
|
| 30 |
+
if sha(row["labels"]) != row["labels_sha256"]:
|
| 31 |
+
errors.append("label_sha:" + row["sequence"])
|
| 32 |
+
with np.load(row["labels"], allow_pickle=False) as z:
|
| 33 |
+
n = row["frames"]
|
| 34 |
+
frame_maps[row["id"]] = n
|
| 35 |
+
split_counts[row["split"]] = split_counts.get(row["split"], 0) + n
|
| 36 |
+
geometry += z["geometry_valid"].sum(0)
|
| 37 |
+
parameters += z["parameter_valid"].sum(0)
|
| 38 |
+
if not np.array_equal(z["frame_ids"], np.arange(n)):
|
| 39 |
+
errors.append("frame_ids:" + row["sequence"])
|
| 40 |
+
if not np.array_equal(z["native_joint_valid"], np.broadcast_to(z["geometry_valid"][..., None], (n, 2, 21))):
|
| 41 |
+
errors.append("geometry_denominator:" + row["sequence"])
|
| 42 |
+
if row["split"] == "val" and z["canonical_available"].any():
|
| 43 |
+
errors.append("val_refit_leakage:" + row["sequence"])
|
| 44 |
+
for h in range(2):
|
| 45 |
+
valid = z["parameter_valid"][:, h]
|
| 46 |
+
if valid.any() and z["parameter_regen_error_mm"][:, h][valid].max() > 1:
|
| 47 |
+
errors.append("regen:" + row["sequence"])
|
| 48 |
+
fit_errors[h].extend(z["fitted_vs_native_joint_error_mm"][:, h][valid].tolist())
|
| 49 |
+
candidate.setdefault((row["split"], row["part"]), row)
|
| 50 |
+
if row["missing_channels"]:
|
| 51 |
+
candidate[(row["split"], "missing_gt")] = row
|
| 52 |
+
if n % 8:
|
| 53 |
+
candidate.setdefault((row["split"], "tail"), row)
|
| 54 |
+
for split, path in manifest["clips"].items():
|
| 55 |
+
coverage = defaultdict(list)
|
| 56 |
+
for clip in read_jsonl(path):
|
| 57 |
+
coverage[clip["record_id"]].extend(i for i in clip["indices"] if i >= 0)
|
| 58 |
+
for row in records:
|
| 59 |
+
if row["split"] == split and coverage[row["id"]] != list(range(row["frames"])):
|
| 60 |
+
errors.append("clip_coverage:" + row["sequence"])
|
| 61 |
+
observations = []
|
| 62 |
+
for (split, kind), row in candidate.items():
|
| 63 |
+
dataset = V006Dataset(root, split=split)
|
| 64 |
+
possible = [(i, c) for i, c in enumerate(dataset.clips) if c["record_id"] == row["id"]]
|
| 65 |
+
if kind == "tail":
|
| 66 |
+
index, clip = possible[-1]
|
| 67 |
+
else:
|
| 68 |
+
with np.load(row["labels"], allow_pickle=False) as z:
|
| 69 |
+
_, (index, clip) = max(
|
| 70 |
+
(int(z["geometry_valid"][[k for k in c["indices"] if k >= 0]].sum()), (i, c))
|
| 71 |
+
for i, c in possible)
|
| 72 |
+
sample = dataset[index]
|
| 73 |
+
batch = default_collate([sample])
|
| 74 |
+
inputs = adapt_inputs(batch["inputs"])
|
| 75 |
+
targets = adapt_targets(inputs, batch["targets"])
|
| 76 |
+
frame_valid = sample["inputs"]["frame_valid"]
|
| 77 |
+
depth = sample["inputs"]["depth_m"]
|
| 78 |
+
valid = sample["inputs"]["depth_valid"]
|
| 79 |
+
if not torch.isfinite(depth).all() or (depth[~valid] != 0).any():
|
| 80 |
+
errors.append("sensor_invalid_values:" + row["sequence"])
|
| 81 |
+
if (sample["targets"]["native_joint_valid"][~frame_valid].any()
|
| 82 |
+
or sample["inputs"]["depth_available"][~frame_valid].any()):
|
| 83 |
+
errors.append("padding:" + row["sequence"])
|
| 84 |
+
relative, relative_valid = relative_targets(batch["targets"]["world_to_camera"], batch["targets"]["camera_pose_valid"])
|
| 85 |
+
if not torch.equal(relative[0, 0], torch.eye(4)) or not torch.equal(relative_valid[0], frame_valid):
|
| 86 |
+
errors.append("cam0:" + row["sequence"])
|
| 87 |
+
camera_joints = targets["joint3d_camera"]
|
| 88 |
+
uv, _ = project_points(camera_joints, inputs["K"])
|
| 89 |
+
mask = targets["joint2d_valid"]
|
| 90 |
+
projection_error = float((uv - targets["joint2d"]).norm(dim=-1)[mask].max()) if mask.any() else None
|
| 91 |
+
if projection_error is not None and projection_error > .001:
|
| 92 |
+
errors.append("projection:" + row["sequence"])
|
| 93 |
+
observations.append(dict(sequence=row["sequence"], split=split, kind=kind,
|
| 94 |
+
indices=clip["indices"], depth_median_m=float(depth[valid].median()) if valid.any() else None,
|
| 95 |
+
depth_valid_fraction=float(valid[frame_valid].float().mean()),
|
| 96 |
+
native_valid=sample["targets"]["geometry_valid"].sum(0).tolist(),
|
| 97 |
+
parameter_valid=sample["targets"]["parameter_valid"].sum(0).tolist(),
|
| 98 |
+
native_corrected_basis=bool(sample["targets"]["native_corrected_basis"]),
|
| 99 |
+
projection_roundtrip_max_px=projection_error))
|
| 100 |
+
print(json.dumps(observations[-1]), flush=True)
|
| 101 |
+
dataset.depth_reader.cache_clear()
|
| 102 |
+
dataset.labels.cache_clear()
|
| 103 |
+
result = dict(status="PASS" if not errors else "FAIL", source="verify.py",
|
| 104 |
+
records=len(records), frames=sum(frame_maps.values()), split_frames=split_counts,
|
| 105 |
+
geometry_valid=geometry.tolist(), parameter_valid=parameters.tolist(),
|
| 106 |
+
parameter_target_vs_native_joint_mean_mm=[float(np.mean(a)) if a else None for a in fit_errors],
|
| 107 |
+
parameter_target_vs_native_joint_p95_mm=[float(np.percentile(a, 95)) if a else None for a in fit_errors],
|
| 108 |
+
actual_reader_cases=observations, errors=errors)
|
| 109 |
+
save(root / "verification.json", result)
|
| 110 |
+
print(json.dumps({k: v for k, v in result.items() if k != "actual_reader_cases"}), flush=True)
|
| 111 |
+
if errors:
|
| 112 |
+
raise SystemExit(1)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
main()
|
releases/20261105_arctic_render_v006_refit/source_snapshot/src/foundation_hand/data/egorender_arctic_mano.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Native ARCTIC MANO -> rendered-camera labels, with explicit basis provenance.
|
| 2 |
+
|
| 3 |
+
Source parameters use the official non-flat mean and uncorrected left shapedirs.
|
| 4 |
+
The model uses flat full axis-angle and corrected left shapedirs. Native geometry
|
| 5 |
+
is always retained; a corrected parameter target requires a reconstruction gate.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from scipy.spatial.transform import Rotation
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading
|
| 14 |
+
from foundation_hand.models.mano import ManoCameraLayer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def frame_lookup(requested, available):
|
| 18 |
+
requested = np.asarray(requested, dtype=np.int64)
|
| 19 |
+
available = np.asarray(available, dtype=np.int64)
|
| 20 |
+
if (requested.ndim != 1 or available.ndim != 1
|
| 21 |
+
or len(np.unique(available)) != len(available)
|
| 22 |
+
or len(np.unique(requested)) != len(requested)):
|
| 23 |
+
raise ValueError("Frame mappings must be unique one-dimensional indices")
|
| 24 |
+
lookup = {int(frame): i for i, frame in enumerate(available)}
|
| 25 |
+
if any(int(frame) not in lookup for frame in requested):
|
| 26 |
+
raise ValueError("Missing source frame in the reference labels")
|
| 27 |
+
return np.asarray([lookup[int(frame)] for frame in requested], dtype=np.int64)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def rigid(matrix):
|
| 31 |
+
matrix = np.asarray(matrix, dtype=np.float64)
|
| 32 |
+
if matrix.shape[-2:] != (4, 4) or not np.isfinite(matrix).all():
|
| 33 |
+
raise ValueError("Expected finite rigid 4x4 transforms")
|
| 34 |
+
r = matrix[..., :3, :3]
|
| 35 |
+
if (not np.allclose(matrix[..., 3, :], [0, 0, 0, 1], atol=2e-5, rtol=0)
|
| 36 |
+
or not np.allclose(r.swapaxes(-1, -2) @ r, np.eye(3), atol=2e-5, rtol=0)
|
| 37 |
+
or not np.allclose(np.linalg.det(r), 1, atol=2e-5, rtol=0)):
|
| 38 |
+
raise ValueError("Transform is not a proper rigid transform")
|
| 39 |
+
return matrix
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def source_to_world(metadata):
|
| 43 |
+
contract = metadata["mano_reconstruction"]
|
| 44 |
+
if contract["units"] != "meters" or contract["original_mean"] != "nonflat":
|
| 45 |
+
raise ValueError("Expected native ARCTIC non-flat MANO in meters")
|
| 46 |
+
value = contract["composed_original_to_world"]
|
| 47 |
+
matrix = np.eye(4)
|
| 48 |
+
matrix[:3, :3] = value["rotation_3x3"]
|
| 49 |
+
matrix[:3, 3] = value["translation_m_3"]
|
| 50 |
+
return rigid(matrix)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def transform_points(points, matrix):
|
| 54 |
+
return np.einsum("fij,f...j->f...i", matrix[:, :3, :3], points) + matrix[
|
| 55 |
+
(slice(None),) + (None,) * (points.ndim - 2) + (slice(0, 3), 3)
|
| 56 |
+
]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def camera_pose(pose, matrix):
|
| 60 |
+
result = np.array(pose, dtype=np.float32, copy=True)
|
| 61 |
+
result[..., :3] = Rotation.from_matrix(
|
| 62 |
+
matrix[:, :3, :3] @ Rotation.from_rotvec(pose[..., :3]).as_matrix()
|
| 63 |
+
).as_rotvec()
|
| 64 |
+
return result
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def projected_presence(vertices, K, image_hw):
|
| 68 |
+
projected = np.einsum("fij,fvj->fvi", K, vertices)
|
| 69 |
+
positive = vertices[..., 2] > 0
|
| 70 |
+
uv = projected[..., :2] / np.where(positive, projected[..., 2], 1)[..., None]
|
| 71 |
+
h, w = image_hw
|
| 72 |
+
inside = (positive & np.isfinite(uv).all(-1) & (uv[..., 0] >= 0)
|
| 73 |
+
& (uv[..., 0] < w) & (uv[..., 1] >= 0) & (uv[..., 1] < h))
|
| 74 |
+
return inside.any(-1)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class ArcticRenderMANO:
|
| 78 |
+
def __init__(self, mano_root, batch_size=128, reconstruction_tolerance_mm=1.):
|
| 79 |
+
enable_legacy_mano_loading()
|
| 80 |
+
from manopth.manolayer import ManoLayer
|
| 81 |
+
|
| 82 |
+
if batch_size < 1 or not 0 < reconstruction_tolerance_mm <= 1:
|
| 83 |
+
raise ValueError("Positive batch size and at most 1 mm reconstruction gate required")
|
| 84 |
+
self.native = [ManoLayer(mano_root=str(mano_root), side=side, use_pca=False,
|
| 85 |
+
ncomps=45, flat_hand_mean=False).eval()
|
| 86 |
+
for side in ("left", "right")]
|
| 87 |
+
self.corrected = ManoCameraLayer(mano_root, fix_left_shapedirs=True).eval().layers
|
| 88 |
+
self.batch_size = batch_size
|
| 89 |
+
self.tolerance = reconstruction_tolerance_mm
|
| 90 |
+
|
| 91 |
+
def decode(self, layer, pose, beta):
|
| 92 |
+
vertices, joints = [], []
|
| 93 |
+
for first in range(0, len(pose), self.batch_size):
|
| 94 |
+
stop = first + self.batch_size
|
| 95 |
+
with torch.inference_mode():
|
| 96 |
+
v, j = layer(torch.from_numpy(np.array(pose[first:stop], dtype=np.float32)),
|
| 97 |
+
torch.from_numpy(np.array(beta[first:stop], dtype=np.float32)))
|
| 98 |
+
vertices.append(v.numpy() / 1000)
|
| 99 |
+
joints.append(j.numpy() / 1000)
|
| 100 |
+
return np.concatenate(vertices), np.concatenate(joints)
|
| 101 |
+
|
| 102 |
+
def adapt(self, parameters, camera, metadata, reference=None):
|
| 103 |
+
ids = np.asarray(camera["source_frame_index"])
|
| 104 |
+
n = len(ids)
|
| 105 |
+
if not n or not np.array_equal(camera["frame_index"], np.arange(n)):
|
| 106 |
+
raise ValueError("Rendered frame_index must be contiguous and nonempty")
|
| 107 |
+
if (not np.array_equal(ids, parameters["source_frames"])
|
| 108 |
+
or not np.array_equal(ids, metadata["source_frame_indices"])):
|
| 109 |
+
raise ValueError("Camera/MANO/metadata source frame mappings differ")
|
| 110 |
+
frame_lookup(ids, ids)
|
| 111 |
+
if (str(camera["camera_coordinates"]) != "opencv_x_right_y_down_z_forward"
|
| 112 |
+
or str(camera["world_coordinates"]) != "right_handed_z_up_meters"):
|
| 113 |
+
raise ValueError("Unexpected render camera/world coordinates")
|
| 114 |
+
w2c = rigid(camera["world_to_camera"])
|
| 115 |
+
if not np.allclose(w2c @ rigid(camera["camera_to_world"]), np.eye(4), atol=2e-5):
|
| 116 |
+
raise ValueError("Camera inverse mismatch")
|
| 117 |
+
original_to_camera = w2c @ source_to_world(metadata)
|
| 118 |
+
K = np.asarray(camera["K"], dtype=np.float32)
|
| 119 |
+
if K.shape != (n, 3, 3) or not np.isfinite(K).all() or not (K[:, (0, 1), (0, 1)] > 0).all():
|
| 120 |
+
raise ValueError("Invalid per-frame K")
|
| 121 |
+
hw = tuple(map(int, camera["image_size"][::-1]))
|
| 122 |
+
native_pose = np.empty((n, 2, 48), np.float32)
|
| 123 |
+
native_beta = np.empty((n, 2, 10), np.float32)
|
| 124 |
+
native_joints = np.empty((n, 2, 21, 3), np.float32)
|
| 125 |
+
native_vertices = []
|
| 126 |
+
presence = np.empty((n, 2), bool)
|
| 127 |
+
for h, side in enumerate(("left", "right")):
|
| 128 |
+
raw = np.concatenate((parameters[side + "_rot"], parameters[side + "_pose"]), -1)
|
| 129 |
+
beta = np.broadcast_to(parameters[side + "_shape"], (n, 10)).copy()
|
| 130 |
+
trans = np.asarray(parameters[side + "_trans"])
|
| 131 |
+
if (raw.shape != (n, 48) or trans.shape != (n, 3)
|
| 132 |
+
or not all(np.isfinite(a).all() for a in (raw, beta, trans))):
|
| 133 |
+
raise ValueError("Invalid native MANO parameters")
|
| 134 |
+
vertices, joints = self.decode(self.native[h], raw, beta)
|
| 135 |
+
vertices = transform_points(vertices + trans[:, None], original_to_camera)
|
| 136 |
+
joints = transform_points(joints + trans[:, None], original_to_camera)
|
| 137 |
+
full_pose = raw.copy()
|
| 138 |
+
# This is the manopth axis-angle mean addition, once, before SO(3).
|
| 139 |
+
full_pose[:, 3:] += self.native[h].th_hands_mean.numpy()
|
| 140 |
+
native_pose[:, h] = camera_pose(full_pose, original_to_camera)
|
| 141 |
+
native_beta[:, h] = beta
|
| 142 |
+
native_joints[:, h] = joints
|
| 143 |
+
native_vertices.append(vertices)
|
| 144 |
+
presence[:, h] = projected_presence(vertices, K, hw)
|
| 145 |
+
native_wrist = native_joints[:, :, 0].copy()
|
| 146 |
+
pose, beta, wrist = native_pose.copy(), native_beta.copy(), native_wrist.copy()
|
| 147 |
+
model_joints = native_joints.copy()
|
| 148 |
+
reused = np.zeros((n, 2), bool)
|
| 149 |
+
reference_native_error_mm = 0.
|
| 150 |
+
matched_count = 0
|
| 151 |
+
if reference is not None:
|
| 152 |
+
available = reference["annotation_indices"]
|
| 153 |
+
frame_lookup(available, available)
|
| 154 |
+
destination = np.flatnonzero(np.isin(ids, available))
|
| 155 |
+
matched = frame_lookup(ids[destination], available)
|
| 156 |
+
matched_count = len(matched)
|
| 157 |
+
ref_w2c = rigid(reference["world_to_camera"][matched])
|
| 158 |
+
reference_to_camera = original_to_camera[destination] @ np.linalg.inv(ref_w2c)
|
| 159 |
+
ref_native = transform_points(reference["joints_native"][matched], reference_to_camera)
|
| 160 |
+
if matched_count:
|
| 161 |
+
reference_native_error_mm = float(np.linalg.norm(
|
| 162 |
+
ref_native - native_joints[destination], axis=-1).max() * 1000)
|
| 163 |
+
if reference_native_error_mm > .1:
|
| 164 |
+
raise ValueError("Reference native geometry differs by more than 0.1 mm")
|
| 165 |
+
# Only a documented corrected-left refit is reused; right native is exact.
|
| 166 |
+
good = reference["canonical_available"][matched, 0].astype(bool)
|
| 167 |
+
finite = (np.isfinite(reference["pose"][matched, 0]).all(-1)
|
| 168 |
+
& np.isfinite(reference["beta"][matched, 0]).all(-1)
|
| 169 |
+
& np.isfinite(reference["wrist"][matched, 0]).all(-1))
|
| 170 |
+
if (good & ~finite).any():
|
| 171 |
+
raise ValueError("Nonfinite valid corrected-left reference")
|
| 172 |
+
selected = destination[good]
|
| 173 |
+
if len(selected):
|
| 174 |
+
origin = matched[good]
|
| 175 |
+
motion = reference_to_camera[good]
|
| 176 |
+
pose[selected, 0] = camera_pose(reference["pose"][origin, 0], motion)
|
| 177 |
+
beta[selected, 0] = reference["beta"][origin, 0]
|
| 178 |
+
wrist[selected, 0] = transform_points(reference["wrist"][origin, 0, None], motion)[:, 0]
|
| 179 |
+
model_joints[selected, 0] = transform_points(reference["joints_model"][origin, 0], motion)
|
| 180 |
+
reused[selected, 0] = True
|
| 181 |
+
basis_error = np.empty((n, 2), np.float32)
|
| 182 |
+
regen_error = np.empty((n, 2), np.float32)
|
| 183 |
+
fit_native_error = np.empty((n, 2), np.float32)
|
| 184 |
+
for h in range(2):
|
| 185 |
+
# Diagnose direct native parameters against the model's corrected basis.
|
| 186 |
+
v, j = self.decode(self.corrected[h], native_pose[:, h], native_beta[:, h])
|
| 187 |
+
placed = v - j[:, :1] + native_wrist[:, h, None]
|
| 188 |
+
basis_error[:, h] = np.linalg.norm(placed - native_vertices[h], axis=-1).max(-1) * 1000
|
| 189 |
+
if h == 0 and reused[:, h].any():
|
| 190 |
+
_, j = self.decode(self.corrected[h], pose[:, h], beta[:, h])
|
| 191 |
+
placed_joints = j - j[:, :1] + wrist[:, h, None]
|
| 192 |
+
regen_error[:, h] = np.linalg.norm(placed_joints - model_joints[:, h], axis=-1).max(-1) * 1000
|
| 193 |
+
fit_native_error[:, h] = np.linalg.norm(placed_joints - native_joints[:, h], axis=-1).mean(-1) * 1000
|
| 194 |
+
compatible = (basis_error <= self.tolerance) | reused
|
| 195 |
+
compatible &= regen_error <= self.tolerance
|
| 196 |
+
geometry = presence.copy() # All native fields have already passed finite checks.
|
| 197 |
+
parameter_valid = compatible & geometry
|
| 198 |
+
# Refit validity never changes native GT denominators or scene presence.
|
| 199 |
+
arrays = dict(frame_ids=np.asarray(camera["frame_index"], np.int64),
|
| 200 |
+
source_frame_ids=np.asarray(ids, np.int64), K=K,
|
| 201 |
+
world_to_camera=w2c.astype(np.float32), pose=pose, beta=beta, wrist=wrist,
|
| 202 |
+
native_pose=native_pose, native_beta=native_beta, native_wrist=native_wrist,
|
| 203 |
+
joints_native=native_joints, joints_model=model_joints,
|
| 204 |
+
geometry_valid=geometry, native_joint_valid=np.broadcast_to(geometry[..., None], (n, 2, 21)).copy(),
|
| 205 |
+
model_joint_valid=np.broadcast_to(parameter_valid[..., None], (n, 2, 21)).copy(),
|
| 206 |
+
parameter_valid=parameter_valid, shape_valid=parameter_valid.copy(),
|
| 207 |
+
presence=presence, presence_valid=np.ones((n, 2), bool),
|
| 208 |
+
canonical_available=reused, has_3d_gt=np.ones(n, bool),
|
| 209 |
+
depth_available=np.full(n, "sensor" not in metadata["missing_channels"], bool),
|
| 210 |
+
native_basis_vertex_error_mm=basis_error, parameter_regen_error_mm=regen_error,
|
| 211 |
+
fitted_vs_native_joint_error_mm=fit_native_error)
|
| 212 |
+
report = dict(frames=n, native_basis_vertex_max_mm=basis_error.max(0).tolist(),
|
| 213 |
+
parameter_valid=parameter_valid.sum(0).tolist(), geometry_valid=geometry.sum(0).tolist(),
|
| 214 |
+
corrected_left_reused_frames=int(reused[:, 0].sum()),
|
| 215 |
+
reference_frames_matched=matched_count, reference_frames_absent=n-matched_count,
|
| 216 |
+
reference_native_max_mm=reference_native_error_mm,
|
| 217 |
+
valid_parameter_regen_max_mm=[float(regen_error[:, h][parameter_valid[:, h]].max())
|
| 218 |
+
if parameter_valid[:, h].any() else None for h in range(2)],
|
| 219 |
+
rejected_refit_regeneration_frames=int((reused & (regen_error > self.tolerance)).sum()))
|
| 220 |
+
return arrays, report
|
releases/20261105_arctic_render_v006_refit/source_snapshot/tests/test_egorender_arctic_v006.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Catch MANO mean/basis, reference-frame and GT/input routing regressions."""
|
| 2 |
+
import copy
|
| 3 |
+
import importlib.util
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
from scipy.spatial.transform import Rotation
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from foundation_hand.data.egorender_arctic_mano import (
|
| 12 |
+
ArcticRenderMANO, camera_pose, frame_lookup, source_to_world, transform_points,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
MANO = Path(__file__).resolve().parents[1] / "runtime/assets/mano"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.fixture(scope="module")
|
| 19 |
+
def adapter():
|
| 20 |
+
if not (MANO / "MANO_LEFT.pkl").is_file() or importlib.util.find_spec("manopth") is None:
|
| 21 |
+
pytest.skip("licensed MANO/manopth unavailable")
|
| 22 |
+
torch.set_num_threads(2)
|
| 23 |
+
return ArcticRenderMANO(MANO)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def package():
|
| 27 |
+
ids = np.array([4, 7, 11])
|
| 28 |
+
params = {"source_frames": ids}
|
| 29 |
+
for h, side in enumerate(("left", "right")):
|
| 30 |
+
params[side + "_rot"] = np.tile([.15, -.25, .2], (3, 1)).astype(np.float32)
|
| 31 |
+
params[side + "_pose"] = np.linspace(-.1, .15, 135).reshape(3, 45).astype(np.float32)
|
| 32 |
+
params[side + "_shape"] = np.linspace(-1, 1, 10).astype(np.float32)
|
| 33 |
+
params[side + "_trans"] = np.tile([h * .15, .02, .7], (3, 1)).astype(np.float32)
|
| 34 |
+
transform = np.eye(4)
|
| 35 |
+
transform[:3, :3] = Rotation.from_euler("xy", [.25, -.15]).as_matrix()
|
| 36 |
+
transform[:3, 3] = [.1, -.1, 1]
|
| 37 |
+
w2c = np.broadcast_to(transform, (3, 4, 4)).copy()
|
| 38 |
+
camera = dict(source_frame_index=ids, frame_index=np.arange(3),
|
| 39 |
+
world_to_camera=w2c, camera_to_world=np.linalg.inv(w2c),
|
| 40 |
+
camera_coordinates="opencv_x_right_y_down_z_forward",
|
| 41 |
+
world_coordinates="right_handed_z_up_meters",
|
| 42 |
+
image_size=np.array([320, 240]),
|
| 43 |
+
K=np.tile([[200, 0, 160], [0, 200, 120], [0, 0, 1]], (3, 1, 1)))
|
| 44 |
+
source_R = Rotation.from_euler("zy", [.1, -.05]).as_matrix()
|
| 45 |
+
meta = dict(source_frame_indices=ids.tolist(), missing_channels=[],
|
| 46 |
+
mano_reconstruction=dict(units="meters", original_mean="nonflat",
|
| 47 |
+
composed_original_to_world=dict(rotation_3x3=source_R.tolist(), translation_m_3=[.02, .01, .2])))
|
| 48 |
+
return params, camera, meta
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_frame_lookup_uses_source_ids_and_rejects_missing_or_duplicate():
|
| 52 |
+
np.testing.assert_array_equal(frame_lookup([7, 4], [4, 7, 11]), [1, 0])
|
| 53 |
+
with pytest.raises(ValueError, match="Missing"):
|
| 54 |
+
frame_lookup([0], [1, 2])
|
| 55 |
+
with pytest.raises(ValueError, match="unique"):
|
| 56 |
+
frame_lookup([1], [1, 1])
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_native_mean_translation_and_left_basis_are_separate(adapter):
|
| 60 |
+
params, camera, meta = package()
|
| 61 |
+
labels, report = adapter.adapt(params, camera, meta)
|
| 62 |
+
matrix = camera["world_to_camera"] @ source_to_world(meta)
|
| 63 |
+
for h, side in enumerate(("left", "right")):
|
| 64 |
+
raw = np.concatenate([params[side + "_rot"], params[side + "_pose"]], -1)
|
| 65 |
+
beta = labels["native_beta"][:, h]
|
| 66 |
+
v, j = adapter.decode(adapter.native[h], raw, beta)
|
| 67 |
+
expected_j = transform_points(j + params[side + "_trans"][:, None], matrix)
|
| 68 |
+
np.testing.assert_allclose(labels["joints_native"][:, h], expected_j, atol=2e-7)
|
| 69 |
+
np.testing.assert_allclose(labels["native_pose"][:, h, 3:],
|
| 70 |
+
raw[:, 3:] + adapter.native[h].th_hands_mean.numpy(), atol=1e-7)
|
| 71 |
+
expected_rotation = matrix[:, :3, :3] @ Rotation.from_rotvec(raw[:, :3]).as_matrix()
|
| 72 |
+
np.testing.assert_allclose(Rotation.from_rotvec(labels["native_pose"][:, h, :3]).as_matrix(),
|
| 73 |
+
expected_rotation, atol=1e-7)
|
| 74 |
+
assert labels["geometry_valid"].all()
|
| 75 |
+
assert not labels["parameter_valid"][:, 0].any()
|
| 76 |
+
assert labels["parameter_valid"][:, 1].all()
|
| 77 |
+
assert not np.allclose(labels["native_wrist"][:, 0], params["left_trans"])
|
| 78 |
+
assert report["native_basis_vertex_max_mm"][0] > 1
|
| 79 |
+
assert report["valid_parameter_regen_max_mm"][1] < .01
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def corrected_reference(adapter):
|
| 83 |
+
params, camera, meta = package()
|
| 84 |
+
original_meta = copy.deepcopy(meta)
|
| 85 |
+
original_meta["mano_reconstruction"]["composed_original_to_world"] = dict(
|
| 86 |
+
rotation_3x3=np.eye(3).tolist(), translation_m_3=[0, 0, 0])
|
| 87 |
+
labels, _ = adapter.adapt(params, camera, original_meta)
|
| 88 |
+
labels["annotation_indices"] = params["source_frames"]
|
| 89 |
+
labels["canonical_available"][:, 0] = True
|
| 90 |
+
# A synthetic compatible corrected-left target, independent of native geometry.
|
| 91 |
+
labels["beta"][:, 0] = 0
|
| 92 |
+
_, joints = adapter.decode(adapter.corrected[0], labels["pose"][:, 0], labels["beta"][:, 0])
|
| 93 |
+
labels["joints_model"][:, 0] = joints - joints[:, :1] + labels["wrist"][:, 0, None]
|
| 94 |
+
return labels
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_refit_transplants_through_world_and_keeps_native_gt(adapter):
|
| 98 |
+
params, camera, meta = package()
|
| 99 |
+
ref = corrected_reference(adapter)
|
| 100 |
+
native, _ = adapter.adapt(params, camera, meta)
|
| 101 |
+
result, report = adapter.adapt(params, camera, meta, ref)
|
| 102 |
+
matrix = camera["world_to_camera"] @ source_to_world(meta) @ np.linalg.inv(ref["world_to_camera"])
|
| 103 |
+
expected = camera_pose(ref["pose"][:, 0], matrix)
|
| 104 |
+
np.testing.assert_allclose(result["pose"][:, 0], expected, atol=1e-7)
|
| 105 |
+
np.testing.assert_array_equal(result["native_joint_valid"], native["native_joint_valid"])
|
| 106 |
+
np.testing.assert_array_equal(result["joints_native"], native["joints_native"])
|
| 107 |
+
assert result["parameter_valid"].all()
|
| 108 |
+
assert report["corrected_left_reused_frames"] == 3
|
| 109 |
+
assert report["valid_parameter_regen_max_mm"][0] < .01
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_corrupt_refit_is_masked_without_discarding_native_geometry(adapter):
|
| 113 |
+
params, camera, meta = package()
|
| 114 |
+
ref = corrected_reference(adapter)
|
| 115 |
+
ref["joints_model"][:, 0, 4, 0] += .005
|
| 116 |
+
labels, report = adapter.adapt(params, camera, meta, ref)
|
| 117 |
+
assert not labels["parameter_valid"][:, 0].any()
|
| 118 |
+
assert labels["geometry_valid"][:, 0].all()
|
| 119 |
+
assert labels["native_joint_valid"][:, 0].all()
|
| 120 |
+
assert report["rejected_refit_regeneration_frames"] == 3
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_missing_reference_frames_keep_native_gt_without_index_shifts(adapter):
|
| 124 |
+
params, camera, meta = package()
|
| 125 |
+
ref = corrected_reference(adapter)
|
| 126 |
+
# The real RGB-derived reference can omit a source frame that the render retains.
|
| 127 |
+
ref = {key: value[[2, 0]] for key, value in ref.items()}
|
| 128 |
+
labels, report = adapter.adapt(params, camera, meta, ref)
|
| 129 |
+
np.testing.assert_array_equal(labels["canonical_available"][:, 0], [True, False, True])
|
| 130 |
+
np.testing.assert_array_equal(labels["parameter_valid"][:, 0], [True, False, True])
|
| 131 |
+
assert labels["native_joint_valid"].all()
|
| 132 |
+
assert report["reference_frames_absent"] == 1
|
| 133 |
+
assert report["valid_parameter_regen_max_mm"][0] < .01
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_wrong_native_reference_and_double_units_fail(adapter):
|
| 137 |
+
params, camera, meta = package()
|
| 138 |
+
ref = corrected_reference(adapter)
|
| 139 |
+
ref["joints_native"][0, 0, 9, 0] += .01
|
| 140 |
+
with pytest.raises(ValueError, match="Reference native geometry"):
|
| 141 |
+
adapter.adapt(params, camera, meta, ref)
|
| 142 |
+
meta["mano_reconstruction"]["units"] = "millimeters"
|
| 143 |
+
with pytest.raises(ValueError, match="meters"):
|
| 144 |
+
adapter.adapt(params, camera, meta)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_coordinate_and_frame_mapping_mistakes_fail(adapter):
|
| 148 |
+
params, camera, meta = package()
|
| 149 |
+
camera["source_frame_index"] = camera["source_frame_index"] + 1
|
| 150 |
+
with pytest.raises(ValueError, match="frame mappings"):
|
| 151 |
+
adapter.adapt(params, camera, meta)
|
| 152 |
+
params, camera, meta = package()
|
| 153 |
+
camera["world_to_camera"][0, :3, :3] *= 2
|
| 154 |
+
with pytest.raises(ValueError, match="rigid"):
|
| 155 |
+
adapter.adapt(params, camera, meta)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def dataset_fixture(tmp_path, adapter):
|
| 159 |
+
import cv2
|
| 160 |
+
from experiments.egorender_arctic_v006.prepare import jsonl, save, sha
|
| 161 |
+
params, camera, meta = package()
|
| 162 |
+
labels, _ = adapter.adapt(params, camera, meta)
|
| 163 |
+
labels["K"][:] = [[4, 0, 3], [0, 4, 1], [0, 0, 1]]
|
| 164 |
+
np.savez(tmp_path / "labels.npz", **labels)
|
| 165 |
+
reader_dir = tmp_path / "raw/part_001"
|
| 166 |
+
reader_dir.mkdir(parents=True)
|
| 167 |
+
reader_path = reader_dir / "egorender_reader.py"
|
| 168 |
+
reader_path.write_text('''import numpy as np
|
| 169 |
+
class DepthReader:
|
| 170 |
+
def __init__(self, path): pass
|
| 171 |
+
def frame(self, index):
|
| 172 |
+
d = np.full((4, 8), 1.25, np.float32)
|
| 173 |
+
valid = np.ones((4, 8), bool)
|
| 174 |
+
valid[:, 0] = False
|
| 175 |
+
d[:, 0] = 0
|
| 176 |
+
return d, valid, [4, 7, 11][index]
|
| 177 |
+
''')
|
| 178 |
+
video = tmp_path / "rgb.mp4"
|
| 179 |
+
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"mp4v"), 30, (8, 4))
|
| 180 |
+
assert writer.isOpened()
|
| 181 |
+
for i in range(3):
|
| 182 |
+
writer.write(np.full((4, 8, 3), 80 + i * 20, np.uint8))
|
| 183 |
+
writer.release()
|
| 184 |
+
row = dict(id="sample", source="EgoRenderer", recording="s01/example", sequence="arctic_s01_example",
|
| 185 |
+
split="train", part="part_001", video=str(video), labels=str(tmp_path / "labels.npz"),
|
| 186 |
+
labels_sha256=sha(tmp_path / "labels.npz"), depth_input_available=False, camera_calibrated=True,
|
| 187 |
+
camera_pose_valid=True, native_corrected_basis=False, sensor_depth="unused_sensor.npz",
|
| 188 |
+
image_hw=[4, 8], missing_channels=[], label_type="test")
|
| 189 |
+
jsonl(tmp_path / "records.jsonl", [row])
|
| 190 |
+
jsonl(tmp_path / "clips.jsonl", [dict(record_id="sample", indices=[0, 1, 2, -1, -1, -1, -1, -1])])
|
| 191 |
+
save(tmp_path / "contract.json", dict(dataset=str(tmp_path / "raw"), readers={"part_001": sha(reader_path)}))
|
| 192 |
+
save(tmp_path / "manifest.json", dict(status="PASS", schema="egonet.arctic_v006_mano.v1",
|
| 193 |
+
contract_sha256=sha(tmp_path / "contract.json"), records=str(tmp_path / "records.jsonl"),
|
| 194 |
+
records_sha256=sha(tmp_path / "records.jsonl"), clips=dict(train=str(tmp_path / "clips.jsonl")),
|
| 195 |
+
clips_sha256=dict(train=sha(tmp_path / "clips.jsonl"))))
|
| 196 |
+
return labels
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_reader_keeps_meter_depth_holes_padding_and_gt_input_isolation(tmp_path, adapter):
|
| 200 |
+
from experiments.egorender_arctic_v006.data import V006Dataset
|
| 201 |
+
labels = dataset_fixture(tmp_path, adapter)
|
| 202 |
+
dataset = V006Dataset(tmp_path, target_hw=(8, 16))
|
| 203 |
+
before = dataset[0]
|
| 204 |
+
valid = before["inputs"]["depth_valid"]
|
| 205 |
+
torch.testing.assert_close(before["inputs"]["depth_m"][valid], torch.full_like(before["inputs"]["depth_m"][valid], 1.25))
|
| 206 |
+
assert not valid[:, :, :, :2].any()
|
| 207 |
+
assert not before["inputs"]["depth_available"][3:].any()
|
| 208 |
+
assert not before["targets"]["native_joint_valid"][3:].any()
|
| 209 |
+
assert not bool(before["targets"]["native_corrected_basis"])
|
| 210 |
+
changed = {key: value.copy() for key, value in labels.items()}
|
| 211 |
+
changed["pose"][:] = 42
|
| 212 |
+
changed["joints_native"][:] = 17
|
| 213 |
+
dataset.labels = lambda record_id: changed
|
| 214 |
+
after = dataset[0]
|
| 215 |
+
for key in before["inputs"]:
|
| 216 |
+
assert torch.equal(before["inputs"][key], after["inputs"][key]), key
|
| 217 |
+
no_depth = V006Dataset(tmp_path, target_hw=(8, 16), sensor_input=False)[0]
|
| 218 |
+
assert not no_depth["inputs"]["depth_available"].any()
|
| 219 |
+
assert not no_depth["inputs"]["depth_valid"].any()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def test_reader_refuses_modified_label_cache(tmp_path, adapter):
|
| 223 |
+
from experiments.egorender_arctic_v006.data import V006Dataset
|
| 224 |
+
labels = dataset_fixture(tmp_path, adapter)
|
| 225 |
+
labels["pose"][:] = 42
|
| 226 |
+
np.savez(tmp_path / "labels.npz", **labels)
|
| 227 |
+
with pytest.raises(ValueError, match="labels changed"):
|
| 228 |
+
V006Dataset(tmp_path, target_hw=(8, 16))[0]
|