File size: 9,808 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | """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()
|