dliu1014's picture Xuweiyi's picture meta-bot's picture
Initial data commit
9c890d3
Raw History Blame Contribute Delete
9.81 kB
"""Verify and rebuild the approved source-object camera-distillation examples."""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
import shutil
from pathlib import Path
import numpy as np
from demo.scale4d_view_count.bundle import bundle_path, validate_scene, verify_bundle
from demo.scale4d_view_count.distillation import read_npz
from demo.scale4d_view_count.source_object_codec import decode_positions
def scope_scores(gt, visible, known, predicted, visibility, mask, ids) -> dict:
valid, available = visible[:, ids] & mask[:, ids], known[:, ids] & mask[:, ids]
predicted_visible = np.isfinite(visibility[:, ids]) & (visibility[:, ids] > 0.5)
distance = np.linalg.norm(predicted[:, ids] - gt[:, ids], axis=-1)
aj, apd = [], []
for threshold in (0.05, 0.1, 0.2, 0.4):
within = distance < threshold
correct = within & valid
true_positive = correct & predicted_visible
false_positive = predicted_visible & (~valid | ~within) & available
apd.append(100 * float(correct.sum()) / int(valid.sum()))
aj.append(
100
* float(true_positive.sum())
/ (int(valid.sum()) + int(false_positive.sum()))
)
return {
"epe": 100 * float(distance[valid].mean()),
"aj": float(np.mean(aj)),
"apd": float(np.mean(apd)),
}
def _validate_groups(bundle: Path, record: dict, scene: dict) -> None:
source_ids = np.asarray(
json.loads(bundle_path(bundle, record["source_point_ids"]).read_text())
)
metadata = json.loads(bundle_path(bundle, record["source_metadata"]).read_text())
if source_ids.shape != (scene["query_count"],):
raise ValueError("Source point identities differ from benchmark queries")
expected = {"all": np.arange(len(source_ids))}
for group in metadata["point_groups"]:
expected[group["name"]] = np.flatnonzero(
(source_ids >= group["start"])
& (source_ids < group["start"] + group["count"])
)
for name, ids in expected.items():
if len(ids) and not np.array_equal(ids, scene["scopes"][name]["ids"]):
raise ValueError(f"Source point group changed: {name}")
def _validate_calibration(inputs: dict, labels: dict, scene: dict) -> None:
if labels["gt_tracks_target_camera"].shape != (
scene["frames"],
scene["query_count"],
3,
) or inputs["rgbs"].shape[:2] != (3, scene["frames"]):
raise ValueError("Inputs and GT do not match the three-view scene")
poses = inputs["cameras_to_world"]
relative = (np.linalg.inv(poses) @ poses[0:1]).astype(np.float64).round(7)
if not np.array_equal(relative, scene["relative_cameras"]) or not np.array_equal(
inputs["intrinsics"].astype(np.float64).round(6), scene["intrinsics"]
):
raise ValueError("Display calibration differs from the saved inputs")
if not np.array_equal(inputs["query_times"], scene["query_times"]):
raise ValueError("Query initialization times changed")
def _validate_tracks(inputs, labels, predictions, scene, record) -> float:
gt, visible, known = (
labels["gt_tracks_target_camera"],
labels["visibility"].astype(bool),
labels["visibility_known"].astype(bool),
)
expected = np.round(
np.nan_to_num(gt.astype(np.float64), nan=0, posinf=0, neginf=0), 5
).transpose(1, 0, 2)
maximum = float(np.abs(np.asarray(scene["gt"]["positions"]) - expected).max())
if not np.array_equal(visible.T, scene["gt"]["valid"]):
raise ValueError("GT visibility changed")
mask = np.arange(scene["frames"])[:, None] > inputs["query_times"][None]
for state in scene["states"]:
values = predictions[state["model"]]
metadata = values["metadata"]
if (
metadata["weight_role"] != "ema_teacher"
or metadata["checkpoint_step"] != record["checkpoint_step"]
or metadata["query_fingerprint"] != record["query_fingerprint"]
):
raise ValueError("Teacher role, step, or scored queries changed")
mode = values["camera_modes"].tolist().index(state["camera"])
xyz = values["positions"][mode]
rounded = np.round(
np.nan_to_num(xyz.astype(np.float64), nan=0, posinf=0, neginf=0), 5
).transpose(1, 0, 2)
maximum = max(
maximum, float(np.abs(np.asarray(state["positions"]) - rounded).max())
)
valid = (
np.isfinite(xyz).all(-1) & (xyz[..., 2] > 0) & (np.abs(xyz).max(-1) < 32)
)
if not np.array_equal(valid.T, state["valid"]):
raise ValueError("Prediction validity changed")
for scope in scene["scopes"].values():
scores = scope_scores(
gt, visible, known, xyz, values["visibility"][mode], mask, scope["ids"]
)
saved = scope["scores"][state["model"] + "_" + state["camera"]]
if any(abs(scores[key] - saved[key]) > 0.00002 for key in scores):
raise ValueError(
"Saved scope scores differ from complete raw trajectories"
)
if maximum > 0.000050001:
raise ValueError("Display coordinates exceed the 0.1-mm encoding tolerance")
return maximum
def validate_example(bundle: Path) -> dict:
verify_bundle(bundle)
record = json.loads((bundle / "sample.json").read_text())
assets = json.loads(bundle_path(bundle, record["viewer_assets"]).read_text())
paths = {asset["name"]: bundle_path(bundle, asset["path"]) for asset in assets}
rows = json.loads(paths["scenes.json"].read_text())
if len(rows) != 1 or rows[0]["id"] != record["id"]:
raise ValueError("Expected the approved single-scene collection")
packed = json.loads(gzip.decompress(paths[rows[0]["data"]].read_bytes()))
scene = decode_positions(
packed, paths[packed["position_codec"]["asset"]].read_bytes()
)
validate_scene(scene)
inputs, labels = (
read_npz(bundle_path(bundle, record["input"])),
read_npz(bundle_path(bundle, record["labels"])),
)
input_metadata = json.loads(str(inputs["metadata_json"].item()))
if input_metadata["query_fingerprint"] != record["query_fingerprint"]:
raise ValueError("Input queries differ from the approved source")
predictions = {}
for model, filename in record["predictions"].items():
values = read_npz(bundle_path(bundle, filename))
values["metadata"] = json.loads(str(values["metadata_json"].item()))
arm = {"b2_ema": "B2", "b3_ema": "B3"}[model]
receipt = json.loads(
(bundle / "model_configs" / arm / "teacher.json").read_text()
)
provenance = scene["checkpoint_provenance"][model]
if any(
values["metadata"][key] != receipt[key] or provenance[key] != receipt[key]
for key in ("teacher_state_sha256", "checkpoint_step", "weight_role")
):
raise ValueError("Prediction weights differ from the saved EMA teacher")
predictions[model] = values
_validate_groups(bundle, record, scene)
_validate_calibration(inputs, labels, scene)
maximum = _validate_tracks(inputs, labels, predictions, scene, record)
return {
"scene": scene["id"],
"frames": scene["frames"],
"all_queries": scene["query_count"],
"object_queries": len(scene["scopes"]["object"]["ids"]),
"maximum_display_rounding_m": maximum,
}
def export_bundle(bundle: Path, output: Path) -> Path:
if output.exists():
raise FileExistsError(output)
validate_example(bundle)
record = json.loads((bundle / "sample.json").read_text())
runtime = Path(__file__).with_name("source_objects.js").read_text()
if hashlib.sha256(runtime.encode()).hexdigest() != record["runtime_sha256"]:
raise ValueError("Installed viewer runtime differs from the approved source")
assets, files = (
{},
json.loads(bundle_path(bundle, record["viewer_assets"]).read_text()),
)
for asset in files:
assets[asset["name"]] = {
"type": asset["type"],
"data": list(bundle_path(bundle, asset["path"]).read_bytes()),
}
inline = json.dumps(assets, separators=(",", ":"))
html = bundle_path(bundle, record["viewer_template"]).read_text()
replacements = {
"{{ASSET_JSON}}": inline,
"{{SOURCE_ASSET_JSON}}": json.dumps(inline, ensure_ascii=False)[1:-1],
"{{RUNTIME_JS}}": runtime,
"{{SOURCE_RUNTIME_JS}}": json.dumps(runtime, ensure_ascii=False)[1:-1],
}
for placeholder, value in replacements.items():
if html.count(placeholder) != 1:
raise ValueError(f"Missing or duplicated viewer placeholder: {placeholder}")
html = html.replace(placeholder, value, 1)
if hashlib.sha256(html.encode()).hexdigest() != record["published_html_sha256"]:
raise ValueError("Rebuilt HTML differs from the approved publication")
output.mkdir(parents=True)
for asset in files:
destination = bundle_path(output, asset["name"])
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(bundle_path(bundle, asset["path"]), destination)
path = output / "index.html"
path.write_text(html)
return path
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bundle", type=Path, required=True)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.output:
print(export_bundle(args.bundle, args.output))
else:
print(json.dumps(validate_example(args.bundle), indent=2))
if __name__ == "__main__":
main()