Download code/scripts/evaluate_baseline.py from mcocheteux/KITTI-C2L-Dataset: direct link, hf CLI and curl.
- Browser
- Download file 5.34 kB
-
https://huggingface.co/datasets/mcocheteux/KITTI-C2L-Dataset/resolve/main/code/scripts/evaluate_baseline.py
- Command line
-
hf download hf://datasets/mcocheteux/KITTI-C2L-Dataset/code/scripts/evaluate_baseline.py
-
curl -L -o evaluate_baseline.py https://huggingface.co/datasets/mcocheteux/KITTI-C2L-Dataset/resolve/main/code/scripts/evaluate_baseline.py
5.34 kB
| """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() | |