Download scripts/inspect_rollout.py from SeanWang0027/RAGEN: direct link, hf CLI and curl.
- Browser
- Download file 6.07 kB
-
https://huggingface.co/datasets/SeanWang0027/RAGEN/resolve/main/scripts/inspect_rollout.py
- Command line
-
hf download hf://datasets/SeanWang0027/RAGEN/scripts/inspect_rollout.py
-
curl -L -o inspect_rollout.py https://huggingface.co/datasets/SeanWang0027/RAGEN/resolve/main/scripts/inspect_rollout.py
6.07 kB
| """ | |
| Inspect a saved rollout pkl file from RAGEN evaluation. | |
| Usage: | |
| python scripts/inspect_rollout.py --path results/eval_multi/.../val_rollouts_*.pkl | |
| python scripts/inspect_rollout.py --path ... --n 5 # show first 5 episodes | |
| python scripts/inspect_rollout.py --path ... --idx 3 # show episode 3 | |
| python scripts/inspect_rollout.py --path ... --success_only # only show successful episodes | |
| python scripts/inspect_rollout.py --path ... --summary # summary stats only | |
| """ | |
| import argparse | |
| import pickle | |
| import sys | |
| import os | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../verl")) | |
| def load_pkl(path): | |
| with open(path, "rb") as f: | |
| return pickle.load(f) | |
| def get_episodes(data): | |
| nb = data.non_tensor_batch | |
| messages_list = nb["messages_list"] | |
| # turn_counts may not exist (e.g. stitch rollouts); derive from messages | |
| if "turn_counts" in nb: | |
| turn_counts = nb["turn_counts"] | |
| else: | |
| turn_counts = [sum(1 for m in msgs if m["role"] == "assistant") for msgs in messages_list] | |
| episodes = [] | |
| for i, (msgs, n_turns) in enumerate(zip(messages_list, turn_counts)): | |
| # collect intermediate rewards from user messages | |
| rewards = [] | |
| for msg in msgs: | |
| if msg["role"] == "user" and "Reward:" in msg["content"]: | |
| lines = msg["content"].strip().splitlines() | |
| for line in lines: | |
| if line.startswith("Reward:"): | |
| try: | |
| rewards.append(float(line.replace("Reward:", "").strip())) | |
| except ValueError: | |
| pass | |
| break | |
| # infer success from last state: look for "√" (player on goal) in last assistant or user msg | |
| success = False | |
| for msg in reversed(msgs): | |
| content = msg["content"] | |
| if "√" in content or "player_on_goal" in content.lower(): | |
| success = True | |
| break | |
| # also check last user message for final reward=1 | |
| if msg["role"] == "user" and "Reward:" in content: | |
| for line in content.splitlines(): | |
| if line.startswith("Reward:"): | |
| try: | |
| if float(line.replace("Reward:", "").strip()) > 0: | |
| success = True | |
| except ValueError: | |
| pass | |
| break | |
| episodes.append({ | |
| "idx": i, | |
| "messages": msgs, | |
| "n_turns": n_turns, | |
| "rewards": rewards, | |
| "success": success, | |
| }) | |
| return episodes | |
| def print_summary(data, episodes): | |
| n = len(episodes) | |
| n_success = sum(e["success"] for e in episodes) | |
| avg_turns = sum(e["n_turns"] for e in episodes) / n | |
| # prefer aggregate metrics from meta_info if available | |
| metrics = (data.meta_info or {}).get("metrics", {}) | |
| env_tag = next((k.split("/")[0] for k in metrics if "/success" in k), None) | |
| print(f"{'='*60}") | |
| if env_tag and f"{env_tag}/success" in metrics: | |
| print(f"[from meta_info] {env_tag}") | |
| print(f" success : {metrics[f'{env_tag}/success']:.1%}") | |
| pass_val = next((metrics[f"{env_tag}/{k}"] for k in ("pass@1", "pass@5", "pass@10") if f"{env_tag}/{k}" in metrics), "N/A") | |
| pass_key = next((k for k in ("pass@1", "pass@5", "pass@10") if f"{env_tag}/{k}" in metrics), "pass@1") | |
| print(f" {pass_key:<14}: {pass_val}") | |
| print(f" num_actions : {metrics.get(f'{env_tag}/num_actions', 'N/A'):.2f}") | |
| print(f" action_valid : {metrics.get(f'{env_tag}/action_is_valid', 'N/A'):.1%}") | |
| print(f" response_len : {metrics.get('response_length', 'N/A'):.1f}") | |
| else: | |
| print(f"Total episodes : {n}") | |
| print(f"Success (inferred): {n_success} / {n} ({100*n_success/n:.1f}%)") | |
| print(f"Avg turns : {avg_turns:.2f}") | |
| print(f"{'='*60}") | |
| def print_episode(ep, max_content_len=500): | |
| print(f"\n{'='*60}") | |
| status = "SUCCESS" if ep["success"] else "FAILED" | |
| print(f"Episode {ep['idx']} [{status}] turns={ep['n_turns']} rewards={ep['rewards']}") | |
| print(f"{'='*60}") | |
| for i, msg in enumerate(ep["messages"]): | |
| role = msg["role"].upper() | |
| content = msg["content"] | |
| if len(content) > max_content_len: | |
| content = content[:max_content_len] + f"\n... [truncated {len(msg['content'])-max_content_len} chars]" | |
| print(f"\n[{role}]") | |
| print(content) | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--path", required=True, help="Path to val_rollouts_*.pkl") | |
| parser.add_argument("--n", type=int, default=3, help="Number of episodes to show (default: 3)") | |
| parser.add_argument("--idx", type=int, default=None, help="Show a specific episode by index") | |
| parser.add_argument("--success_only", action="store_true", help="Only show successful episodes") | |
| parser.add_argument("--fail_only", action="store_true", help="Only show failed episodes") | |
| parser.add_argument("--summary", action="store_true", help="Show summary stats only") | |
| parser.add_argument("--max_len", type=int, default=500, help="Max chars per message to display") | |
| args = parser.parse_args() | |
| data = load_pkl(args.path) | |
| episodes = get_episodes(data) | |
| print_summary(data, episodes) | |
| if args.summary: | |
| return | |
| if args.idx is not None: | |
| print_episode(episodes[args.idx], args.max_len) | |
| return | |
| pool = episodes | |
| if args.success_only: | |
| pool = [e for e in episodes if e["success"]] | |
| print(f"Showing {min(args.n, len(pool))} successful episodes") | |
| elif args.fail_only: | |
| pool = [e for e in episodes if not e["success"]] | |
| print(f"Showing {min(args.n, len(pool))} failed episodes") | |
| for ep in pool[:args.n]: | |
| print_episode(ep, args.max_len) | |
| if __name__ == "__main__": | |
| main() | |