File size: 4,862 Bytes
68442cd | 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 | #!/usr/bin/env python
"""
Evaluate DoVLA-Transformer checkpoint (same protocol as Enhanced evaluation).
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
import torch
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from dovla_cil.data.datasets import CILDataset
from dovla_cil.models.dovla_transformer import DoVLATransformer
from dovla_cil.utils.io import write_json
def evaluate_transformer_checkpoint(
checkpoint_path: str | Path,
dataset_dir: str | Path,
output_path: str | Path | None = None,
device: str = "auto",
) -> dict:
"""Evaluate Transformer using same protocol as baseline."""
resolved_device = (
"cuda" if device == "auto" and torch.cuda.is_available() else "cpu"
if device == "auto"
else device
)
checkpoint = torch.load(checkpoint_path, map_location=resolved_device, weights_only=False)
args = checkpoint["args"]
# Recreate model
model = DoVLATransformer(
obs_dim=70,
action_dim=32,
lang_dim=0, # Baseline has no language
d_model=args["d_model"],
n_heads=args["n_heads"],
n_layers=args["n_layers"],
d_ff=args["d_ff"],
dropout=0.1
).to(resolved_device)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
dataset = CILDataset(dataset_dir)
val_group_ids = list(dataset.group_ids)
selected_success = 0
oracle_success = 0
top1_correct = 0
def pad(vec, target):
if len(vec) >= target:
return vec[:target]
return vec + [0.0] * (target - len(vec))
with torch.no_grad():
for group_id in val_group_ids:
records = dataset.get_group(group_id)
if not records:
continue
# Prepare observations (pad to 70)
obs_list = []
for r in records:
obs_data = r.observation_inline
if "state" in obs_data:
obs = list(obs_data["state"])
else:
obs = []
for v in obs_data.values():
if isinstance(v, list):
obs.extend(v)
elif isinstance(v, (int, float)):
obs.append(v)
obs = pad([float(x) for x in obs], 70)
obs_list.append(obs)
obs = torch.tensor([obs_list[0]], dtype=torch.float32, device=resolved_device)
# Prepare actions (pad to 32)
actions = torch.tensor(
[pad(r.action_chunk.flat_values, 32) for r in records],
dtype=torch.float32,
device=resolved_device
).unsqueeze(0)
# Forward (no language)
scores_matrix = model(obs, actions, lang=None)
# Aggregate to per-action scores
scores = scores_matrix[0].sum(dim=1).cpu().tolist()
# Select best
selected = max(range(len(records)), key=lambda i: (scores[i], -i))
# Check success
utilities = [r.reward.score for r in records]
best_utility = max(utilities)
is_selected_success = int(records[selected].reward.terminal_success)
has_oracle_success = int(any(r.reward.terminal_success for r in records))
is_top1 = int(abs(utilities[selected] - best_utility) < 1e-6)
selected_success += is_selected_success
oracle_success += has_oracle_success
top1_correct += is_top1
group_count = len(val_group_ids)
result = {
"checkpoint": str(checkpoint_path),
"dataset": str(dataset_dir),
"num_groups": group_count,
"selected_success_rate": selected_success / group_count,
"oracle_success_rate": oracle_success / group_count,
"top1_action_selection": top1_correct / group_count,
}
if output_path:
write_json(result, output_path)
return result
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--dataset", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--device", default="auto")
args = parser.parse_args(argv)
result = evaluate_transformer_checkpoint(
args.checkpoint, args.dataset, args.out, args.device
)
print(f"Selected success rate: {result['selected_success_rate']:.4f}")
print(f"Top-1 selection: {result['top1_action_selection']:.4f}")
print(f"Oracle success: {result['oracle_success_rate']:.4f}")
return 0
if __name__ == "__main__":
sys.exit(main())
|