3d-box-trajectory-smoothing / hf_dataset_example.py
Silicon23's picture
Upload hf_dataset_example.py with huggingface_hub
bc719be verified
Raw
History Blame Contribute Delete
4.77 kB
"""Standalone example: consume the Track B HuggingFace dataset.
Self-contained — needs only ``numpy`` + ``datasets`` (no Track B package, no
torch). Shows how to:
1. load the dataset and apply the canonical by-video val split,
2. read one trajectory's three box sources (noisy / kalman / gt),
3. convert the stored 3x3 rotation to the model's ``rot_6d`` and pack the
12-d ``box_repr = [center(3), log_dims(3), rot_6d(6)]``,
4. (optional) build a tiny PyTorch input batch.
python hf_dataset_example.py --hf_dataset /path/to/track_b_hf_dataset
"""
from __future__ import annotations
import argparse
import json
import os
import numpy as np
# --- rotation convention (MUST match training; see the dataset card) ---------
def matrix_to_rot6d(R: np.ndarray) -> np.ndarray:
"""3x3 rotation (box-local -> camera) -> 6-d = first two ROWS, flattened.
[...,3,3] -> [...,6]."""
R = np.asarray(R, np.float32)
return R[..., :2, :].reshape(*R.shape[:-2], 6)
def rot6d_to_matrix(r6: np.ndarray) -> np.ndarray:
"""Inverse of ``matrix_to_rot6d``: row Gram-Schmidt. [...,6] -> [...,3,3]."""
r6 = np.asarray(r6, np.float32)
a1, a2 = r6[..., 0:3], r6[..., 3:6]
b1 = a1 / np.clip(np.linalg.norm(a1, axis=-1, keepdims=True), 1e-8, None)
a2 = a2 - np.sum(b1 * a2, axis=-1, keepdims=True) * b1
b2 = a2 / np.clip(np.linalg.norm(a2, axis=-1, keepdims=True), 1e-8, None)
b3 = np.cross(b1, b2)
return np.stack([b1, b2, b3], axis=-2)
def box_repr(center: np.ndarray, dims: np.ndarray, R: np.ndarray) -> np.ndarray:
"""(center[T,3], dims[T,3] FULL extents, R[T,3,3]) -> box_repr[T,12]."""
log_dims = np.log(np.clip(dims, 1e-4, None))
return np.concatenate([center, log_dims, matrix_to_rot6d(R)], axis=-1).astype(np.float32)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--hf_dataset", required=True)
ap.add_argument("--prior", choices=["noisy", "kalman"], default="noisy",
help="which box trajectory to feed the model as the prior input")
args = ap.parse_args()
from datasets import load_from_disk
ds = load_from_disk(args.hf_dataset).with_format("numpy")
print(f"loaded {len(ds)} trajectories")
# canonical by-video val split (shared benchmark) — shipped with the dataset
split_path = os.path.join(args.hf_dataset, "val_video_ids.json")
val_vids = set()
if os.path.exists(split_path):
val_vids = set(json.load(open(split_path))["val_video_ids"])
is_val = np.array([v in val_vids for v in ds["video_id"]])
print(f"split by video: train={int((~is_val).sum())} val={int(is_val.sum())} "
f"({len(val_vids)} val videos)")
# NOTE: split BY VIDEO, never by object — objects from one video must not
# straddle train/val (they share camera trajectory + scene).
r = ds[0]
T = int(r["num_frames"])
print(f"\nexample trajectory: video={r['video_id']} object={r['object_id']}")
print(f" category={r['category']!r} caption={r['caption']!r}")
print(f" frames={T} keyframes(measured)={int(r['num_keyframes'])}")
prior_c = r[f"{args.prior}_center"]
prior_d = r[f"{args.prior}_dims"]
prior_R = r[f"{args.prior}_R"]
prior_repr = box_repr(prior_c, prior_d, prior_R) # [T,12] model input
gt_repr = box_repr(r["gt_center"], r["gt_dims"], r["gt_R"]) # [T,12] target
ts_sec = (r["timestamps_ns"].astype(np.float64) - r["timestamps_ns"].min()) / 1e9
measured = np.asarray(r["measured_mask"], bool)
print(f" box_repr (input prior) shape={prior_repr.shape}, gt_repr shape={gt_repr.shape}")
print(f" timestamps span {ts_sec.max():.2f}s, measured frames={int(measured.sum())}/{T}")
# per-frame center error of the prior vs GT (the thing the model reduces)
err = np.linalg.norm(prior_c - r["gt_center"], axis=-1)
print(f" prior center error vs GT: mean={err.mean():.3f}m max={err.max():.3f}m")
# verify rot_6d round-trips the stored matrix
R_rt = rot6d_to_matrix(matrix_to_rot6d(r["gt_R"]))
print(f" rot_6d round-trip max err: {np.abs(R_rt - r['gt_R']).max():.2e}")
# optional: a tiny torch batch (only if torch is available)
try:
import torch
batch = {
"box_repr": torch.from_numpy(prior_repr)[None], # [1,T,12]
"timestamps": torch.from_numpy(ts_sec.astype(np.float32))[None],
"measured_mask": torch.from_numpy(measured)[None],
}
print(f"\n torch batch ready: box_repr {tuple(batch['box_repr'].shape)} "
f"-> feed to a bidirectional transformer (see trackb/model.py)")
except ImportError:
print("\n (torch not installed — skipping the tensor-batch demo)")
if __name__ == "__main__":
main()