File size: 3,113 Bytes
67ba414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Analyze rollout pkl: check whether successful episodes are all solved in turn=1.

Usage:
    python scripts/test.py --path results/sft_data/sokoban_14B_10K/val_rollouts_20260410_215230.pkl
"""

import argparse
import os
import sys
import pickle
from collections import Counter

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_success_flags(data):
    """
    Use rm_scores from the verifier directly.
    rm_scores shape: [n_episodes, seq_len] — reward is placed at the last
    valid token, all other positions are 0. Success = final nonzero reward > 0.
    Falls back to message-based heuristic if rm_scores is absent.
    """
    import torch
    if data.batch is not None and "rm_scores" in data.batch:
        rm = data.batch["rm_scores"]  # [N, T]
        # last nonzero reward per episode
        final_rewards = []
        for i in range(rm.shape[0]):
            nonzero = rm[i].nonzero(as_tuple=False)
            if len(nonzero) > 0:
                final_rewards.append(rm[i, nonzero[-1]].item())
            else:
                final_rewards.append(0.0)
        return [r > 0 for r in final_rewards]
    # fallback
    return [_is_success_from_msgs(msgs) for msgs in data.non_tensor_batch["messages_list"]]


def _is_success_from_msgs(msgs):
    for m in reversed(msgs):
        if m["role"] == "user" and "Reward:" in m["content"]:
            for line in m["content"].splitlines():
                if line.startswith("Reward:"):
                    try:
                        return float(line.replace("Reward:", "").strip()) > 0
                    except ValueError:
                        pass
            break
    return False


def count_turns(msgs):
    """Number of assistant turns in the episode."""
    return sum(1 for m in msgs if m["role"] == "assistant")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--path", required=True)
    args = parser.parse_args()

    data = load_pkl(args.path)
    msgs_list = data.non_tensor_batch["messages_list"]
    success_flags = get_success_flags(data)

    success_turn_dist = Counter()
    fail_turn_dist = Counter()

    for msgs, suc in zip(msgs_list, success_flags):
        n_turns = count_turns(msgs)
        if suc:
            success_turn_dist[n_turns] += 1
        else:
            fail_turn_dist[n_turns] += 1

    total = len(msgs_list)
    total_success = sum(success_turn_dist.values())
    print(f"Total episodes : {total}")
    print(f"Total success  : {total_success} ({100*total_success/total:.1f}%)")
    print()

    print("Turn distribution of SUCCESSFUL episodes:")
    for t in sorted(success_turn_dist):
        print(f"  turns={t}: {success_turn_dist[t]} ({100*success_turn_dist[t]/total_success:.1f}%)")

    print()
    print("Turn distribution of FAILED episodes:")
    for t in sorted(fail_turn_dist):
        print(f"  turns={t}: {fail_turn_dist[t]}")


if __name__ == "__main__":
    main()