Download evaluate_fixed_line_learned.py from iteratehack/himalaya-fixed-line-training: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/iteratehack/himalaya-fixed-line-training/resolve/main/evaluate_fixed_line_learned.py
- Command line
-
hf download hf://datasets/iteratehack/himalaya-fixed-line-training/evaluate_fixed_line_learned.py
-
curl -L -o evaluate_fixed_line_learned.py https://huggingface.co/datasets/iteratehack/himalaya-fixed-line-training/resolve/main/evaluate_fixed_line_learned.py
12.1 kB
| """Evaluate the direct-joint PPO policy and non-learning baselines.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import Callable | |
| import numpy as np | |
| from stable_baselines3 import PPO | |
| from fixed_line_learned_env import G1LearnedFixedLineEnv | |
| def resolve_model(requested: str | None = None) -> Path: | |
| if requested is not None: | |
| requested_path = Path(requested) | |
| if requested_path.exists(): | |
| return requested_path.resolve() | |
| raise FileNotFoundError(f"Requested checkpoint not found: {requested_path}") | |
| candidates = [ | |
| Path("models/ppo_fixed_line_learned/g1_fixed_line_direct_final.zip"), | |
| Path("models/ppo_fixed_line_learned/best/best_model.zip"), | |
| Path("models/ppo_fixed_line_learned/g1_fixed_line_direct_last.zip"), | |
| ] | |
| for candidate in candidates: | |
| if candidate is not None and candidate.exists(): | |
| return candidate.resolve() | |
| raise FileNotFoundError( | |
| "No direct-joint checkpoint found. Run train_fixed_line_learned.py " | |
| "or pass --model." | |
| ) | |
| def rollout_policy( | |
| action_fn: Callable[[np.ndarray, G1LearnedFixedLineEnv], np.ndarray], | |
| seed: int, | |
| randomize: bool, | |
| curriculum_stage: str = "full", | |
| ) -> dict[str, float | bool | int]: | |
| env = G1LearnedFixedLineEnv( | |
| randomize_reset=randomize, | |
| curriculum_stage=curriculum_stage, | |
| ) | |
| observation, info = env.reset(seed=seed, options={"randomize": randomize}) | |
| total_reward = 0.0 | |
| line_load_peak = 0.0 | |
| lanyard_load_peak = 0.0 | |
| line_support_sum = 0.0 | |
| ground_load_peak = 0.0 | |
| minimum_rope_snow_contacts = np.inf | |
| rope_leg_contact_steps = 0 | |
| minimum_rope_leg_center_clearance = np.inf | |
| peak_rope_strain = 0.0 | |
| peak_rope_lift = 0.0 | |
| rope_cam_contact_steps = 0 | |
| peak_lateral_offset = 0.0 | |
| minimum_heading_alignment = np.inf | |
| minimum_pelvis_normal_height = np.inf | |
| minimum_backward_lean = np.inf | |
| maximum_backward_lean = -np.inf | |
| nonfoot_snow_contact_steps = 0 | |
| contacts = {"left": 0, "right": 0, "any": 0, "double": 0} | |
| for step in range(env.max_episode_steps): | |
| action = action_fn(observation, env) | |
| observation, reward, terminated, truncated, info = env.step(action) | |
| total_reward += reward | |
| line_load_peak = max(line_load_peak, float(info["ascender_load_n"])) | |
| lanyard_load_peak = max( | |
| lanyard_load_peak, float(info["lanyard_load_n"]) | |
| ) | |
| line_support_sum += float(info["line_support_fraction"]) | |
| ground_load_peak = max(ground_load_peak, float(info["ground_load_n"])) | |
| left = bool(info["left_boot_contact"]) | |
| right = bool(info["right_boot_contact"]) | |
| contacts["left"] += int(left) | |
| contacts["right"] += int(right) | |
| contacts["any"] += int(left or right) | |
| contacts["double"] += int(left and right) | |
| rope_snow_contacts, rope_touches_leg = env.rope_contact_audit() | |
| minimum_rope_snow_contacts = min( | |
| minimum_rope_snow_contacts, rope_snow_contacts | |
| ) | |
| rope_leg_contact_steps += int(rope_touches_leg) | |
| minimum_rope_leg_center_clearance = min( | |
| minimum_rope_leg_center_clearance, | |
| float(info["rope_leg_center_clearance_m"]), | |
| ) | |
| peak_rope_strain = max( | |
| peak_rope_strain, float(info["rope_strain"]) | |
| ) | |
| peak_rope_lift = max( | |
| peak_rope_lift, float(info["rope_max_lift_m"]) | |
| ) | |
| rope_cam_contact_steps += int(info["rope_cam_contacts"] > 0) | |
| peak_lateral_offset = max( | |
| peak_lateral_offset, float(info["lateral_offset"]) | |
| ) | |
| minimum_heading_alignment = min( | |
| minimum_heading_alignment, float(info["line_heading_alignment"]) | |
| ) | |
| minimum_pelvis_normal_height = min( | |
| minimum_pelvis_normal_height, | |
| float(info["pelvis_normal_height"]), | |
| ) | |
| minimum_backward_lean = min( | |
| minimum_backward_lean, float(info["backward_lean"]) | |
| ) | |
| maximum_backward_lean = max( | |
| maximum_backward_lean, float(info["backward_lean"]) | |
| ) | |
| nonfoot_snow_contact_steps += int(info["nonfoot_snow_contact"]) | |
| if terminated or truncated: | |
| break | |
| elapsed = step + 1 | |
| result: dict[str, float | bool | int] = { | |
| "seed": seed, | |
| "success": bool(info["success"]), | |
| "failure": bool(info["failure"]), | |
| "policy_steps": elapsed, | |
| "return": total_reward, | |
| "ascent_m": float(info["ascent"]), | |
| "ascender_advance_m": float(info["ascender_advance"]), | |
| "physical_landings": int(info["physical_landings"]), | |
| "alternating_landings": int(info["alternating_landings"]), | |
| "current_boot_anchor_loss_m": float( | |
| info["current_boot_anchor_loss_m"] | |
| ), | |
| "maximum_boot_anchor_loss_m": float( | |
| info["maximum_boot_anchor_loss_m"] | |
| ), | |
| "maximum_single_support_steps": int( | |
| info["maximum_single_support_steps"] | |
| ), | |
| "maximum_supported_single_support_steps": int( | |
| info["maximum_supported_single_support_steps"] | |
| ), | |
| "maximum_swing_advance_m": float( | |
| info["maximum_swing_advance_m"] | |
| ), | |
| "maximum_supported_swing_advance_m": float( | |
| info["maximum_supported_swing_advance_m"] | |
| ), | |
| "maximum_shaped_supported_swing_advance_m": float( | |
| info["maximum_shaped_supported_swing_advance_m"] | |
| ), | |
| "technique_cycles": int(info["technique_cycles"]), | |
| "right_elbow_peak_rad": float(info["right_elbow_peak_rad"]), | |
| "right_elbow_excursion_rad": float(info["right_elbow_excursion_rad"]), | |
| "descent_from_high_water_m": float(info["descent_from_high_water"]), | |
| "upright_score": float(info["upright_score"]), | |
| "minimum_heading_alignment": minimum_heading_alignment, | |
| "minimum_backward_lean": minimum_backward_lean, | |
| "maximum_backward_lean": maximum_backward_lean, | |
| "pelvis_normal_height_m": float(info["pelvis_normal_height"]), | |
| "minimum_pelvis_normal_height_m": minimum_pelvis_normal_height, | |
| "final_lateral_offset_m": float(info["lateral_offset"]), | |
| "peak_lateral_offset_m": peak_lateral_offset, | |
| "grip_constraint_error_m": float(info["grip_constraint_error_m"]), | |
| "peak_ascender_load_n": line_load_peak, | |
| "peak_lanyard_load_n": lanyard_load_peak, | |
| "mean_lanyard_load_n": float(info["mean_lanyard_load_n"]), | |
| "mean_active_lanyard_load_n": float( | |
| info["mean_active_lanyard_load_n"] | |
| ), | |
| "mean_line_support_fraction": line_support_sum / elapsed, | |
| "line_loaded_fraction": float(info["line_loaded_fraction"]), | |
| "maximum_target_lanyard_support_streak": int( | |
| info["maximum_target_lanyard_support_streak"] | |
| ), | |
| "target_lanyard_support_duration_s": float( | |
| info["maximum_target_lanyard_support_streak"] * env.policy_dt | |
| ), | |
| "peak_ground_load_n": ground_load_peak, | |
| "left_contact_fraction": contacts["left"] / elapsed, | |
| "right_contact_fraction": contacts["right"] / elapsed, | |
| "grounded_fraction": contacts["any"] / elapsed, | |
| "double_support_fraction": contacts["double"] / elapsed, | |
| "maximum_airborne_streak": int(info["maximum_airborne_streak"]), | |
| "maximum_rope_cam_lost_streak": int( | |
| info["maximum_rope_cam_lost_streak"] | |
| ), | |
| "nonfoot_snow_contact_steps": nonfoot_snow_contact_steps, | |
| "minimum_rope_snow_contacts": int(minimum_rope_snow_contacts), | |
| "rope_leg_contact_steps": rope_leg_contact_steps, | |
| "rope_leg_contact_fraction": rope_leg_contact_steps / elapsed, | |
| "minimum_rope_leg_center_clearance_m": ( | |
| minimum_rope_leg_center_clearance | |
| ), | |
| "peak_rope_strain": peak_rope_strain, | |
| "peak_rope_lift_m": peak_rope_lift, | |
| "rope_cam_contact_fraction": rope_cam_contact_steps / elapsed, | |
| } | |
| env.close() | |
| return result | |
| def _summary(episodes: list[dict[str, float | bool | int]]) -> dict: | |
| numeric_keys = [ | |
| key | |
| for key, value in episodes[0].items() | |
| if key not in ("seed", "success", "failure") | |
| and isinstance(value, (int, float)) | |
| ] | |
| return { | |
| "episodes": len(episodes), | |
| "successes": sum(bool(episode["success"]) for episode in episodes), | |
| "failures": sum(bool(episode["failure"]) for episode in episodes), | |
| "success_rate": float( | |
| np.mean([bool(episode["success"]) for episode in episodes]) | |
| ), | |
| "mean": { | |
| key: float(np.mean([float(episode[key]) for episode in episodes])) | |
| for key in numeric_keys | |
| }, | |
| "minimum": { | |
| key: float(np.min([float(episode[key]) for episode in episodes])) | |
| for key in numeric_keys | |
| }, | |
| "maximum": { | |
| key: float(np.max([float(episode[key]) for episode in episodes])) | |
| for key in numeric_keys | |
| }, | |
| "rollouts": episodes, | |
| } | |
| def evaluate( | |
| model_path: str | None = None, | |
| episodes: int = 10, | |
| output: str = "models/ppo_fixed_line_learned/evaluation_report.json", | |
| seed: int = 2100, | |
| ) -> dict: | |
| checkpoint = resolve_model(model_path) | |
| policy = PPO.load(checkpoint, device="cpu") | |
| if policy.action_space.shape != (len(G1LearnedFixedLineEnv.POLICY_JOINTS),): | |
| raise ValueError( | |
| f"Checkpoint has action shape {policy.action_space.shape}; expected " | |
| f"{(len(G1LearnedFixedLineEnv.POLICY_JOINTS),)} direct joint actions" | |
| ) | |
| def learned(observation: np.ndarray, _env: G1LearnedFixedLineEnv) -> np.ndarray: | |
| action, _state = policy.predict(observation, deterministic=True) | |
| return np.asarray(action, dtype=np.float32) | |
| rng = np.random.default_rng(seed + 50_000) | |
| conditions = { | |
| "learned_direct_joint_policy": [ | |
| rollout_policy(learned, seed + index, True) | |
| for index in range(episodes) | |
| ], | |
| "neutral_joint_residual": [ | |
| rollout_policy( | |
| lambda _observation, env: np.zeros( | |
| env.action_dim, dtype=np.float32 | |
| ), | |
| seed + 10_000 + index, | |
| True, | |
| ) | |
| for index in range(max(3, episodes // 2)) | |
| ], | |
| "uniform_random_joint_residual": [ | |
| rollout_policy( | |
| lambda _observation, env: rng.uniform( | |
| -1.0, 1.0, env.action_dim | |
| ).astype(np.float32), | |
| seed + 20_000 + index, | |
| True, | |
| ) | |
| for index in range(max(3, episodes // 2)) | |
| ], | |
| } | |
| report = { | |
| "checkpoint": str(checkpoint), | |
| "controller_contract": { | |
| "observation_dim": int(policy.observation_space.shape[0]), | |
| "action_dim": int(policy.action_space.shape[0]), | |
| "actions": list(G1LearnedFixedLineEnv.POLICY_JOINTS), | |
| "scripted_motion": False, | |
| "runtime_inverse_kinematics": False, | |
| "external_robot_forces": False, | |
| }, | |
| "conditions": { | |
| name: _summary(rollouts) for name, rollouts in conditions.items() | |
| }, | |
| } | |
| destination = Path(output) | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| destination.write_text(json.dumps(report, indent=2) + "\n") | |
| print(json.dumps(report, indent=2)) | |
| return report | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--model") | |
| parser.add_argument("--episodes", type=int, default=10) | |
| parser.add_argument( | |
| "--output", | |
| default="models/ppo_fixed_line_learned/evaluation_report.json", | |
| ) | |
| parser.add_argument("--seed", type=int, default=2100) | |
| arguments = parser.parse_args() | |
| evaluate(arguments.model, arguments.episodes, arguments.output, arguments.seed) | |