File size: 5,338 Bytes
db613b6 1150050 db613b6 1150050 db613b6 1150050 db613b6 | 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 | """Evaluate an exported main UniCal checkpoint on frozen C2L stage-5 test rows.
Requires the separately licensed UniCal source package; no pretrained download.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
import torch
import unical
from hydra import compose, initialize_config_dir
from hydra.utils import instantiate
from scipy.spatial.transform import Rotation
from unical.utils.transform import rotation_6d_to_matrix
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--checkpoint", required=True, type=Path)
parser.add_argument("--data-dir", required=True, type=Path)
parser.add_argument("--raw-root", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--device", choices=["cpu", "cuda"], default="cpu")
parser.add_argument("--num-workers", type=int, default=0)
parser.add_argument("--batch-size", type=int, default=2)
parser.add_argument("--max-samples", type=int)
parser.add_argument(
"--dataset-protocol",
choices=("legacy_v1", "full_projection_v1_1"),
default="legacy_v1",
help="Label convention being evaluated; checkpoints remain the original v1-trained models.",
)
args = parser.parse_args()
if args.max_samples is not None and args.max_samples < 1:
parser.error("--max-samples must be positive")
if args.output.exists():
raise FileExistsError(args.output)
root = Path(unical.__file__).resolve().parents[2]
torch.set_float32_matmul_precision("high")
overrides = [
"data=kitti_c2l",
f"data.data_dir={args.data_dir.resolve()}",
f"data.kitti_raw_root={args.raw_root.resolve()}",
"data.stages=[5]",
f"data.batch_size={args.batch_size}",
f"data.num_workers={args.num_workers}",
"data.preprocessor.cfg.width=256",
"data.preprocessor.cfg.height=256",
"model.backbone.image_size=256",
"model.backbone.pretrained=null",
]
with initialize_config_dir(config_dir=str(root / "configs"), version_base="1.3"):
cfg = compose(config_name="train", overrides=overrides)
dm = instantiate(cfg.data)
dm.setup("test")
state = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
model = instantiate(cfg.model).to(args.device).eval()
model.load_state_dict(state["state_dict"], strict=True)
records = []
with torch.inference_mode():
for batch in dm.test_dataloader():
translation, r6 = model(
batch._replace(
img=batch.img.to(args.device), lidar_map=batch.lidar_map.to(args.device)
)
)
translation = translation.float().cpu().numpy()
rotation = rotation_6d_to_matrix(r6.float()).cpu().numpy()
target_t, target_r = (value.numpy() for value in batch.target_reg)
angles = np.rad2deg(
(Rotation.from_matrix(rotation).inv() * Rotation.from_matrix(target_r)).magnitude()
)
errors = np.abs(translation - target_t).mean(axis=1) * 100
for i, meta in enumerate(batch.metadata):
records.append(
{
"sequence": meta["sequence"],
"frame_index": int(meta["frame_index"]),
"translation_mae_cm": float(errors[i]),
"rotation_degrees": float(angles[i]),
}
)
if args.max_samples is not None and len(records) >= args.max_samples:
records = records[: args.max_samples]
break
if (
not records
or not np.isfinite(
[[row["translation_mae_cm"], row["rotation_degrees"]] for row in records]
).all()
):
raise ValueError("Empty or non-finite evaluation")
def mean_metrics(rows):
return {
key: float(np.mean([row[key] for row in rows]))
for key in ("translation_mae_cm", "rotation_degrees")
}
result = {
"protocol": "native-frozen-stage5",
"dataset_protocol": args.dataset_protocol,
"checkpoint_sha256": hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(),
"test_metadata_sha256": hashlib.sha256(
(args.data_dir / "test.parquet").read_bytes()
).hexdigest(),
"checkpoint_training_protocol": "legacy_v1",
"samples": len(records),
"device": args.device,
"smoke_only": args.max_samples is not None,
"training_seed": state["training_seed"],
"epoch_zero_based": state["epoch"],
"global_step": state["global_step"],
"metrics": mean_metrics(records),
"per_sequence": {
seq: mean_metrics([row for row in records if row["sequence"] == seq])
for seq in sorted({row["sequence"] for row in records})
},
"records": records,
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps({key: value for key, value in result.items() if key != "records"}, indent=2))
if __name__ == "__main__":
main()
|