File size: 4,342 Bytes
1521ce5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert a5_user_data.json -> per-user txt, then plot token length distribution.

Usage:
    python /mnt/train-gui-agent/zhangxinyuan/data_mem/output/export_and_plot_lengths.py
"""

import json
import os
import glob
import statistics

# ====== Config ======
A5_PATH = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/a5_user_data.json"
USER_TEXT_DIR = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/user_text"
MODEL_PATH = "/mnt/train-gui-agent/zhangzeyu/models/Qwen3-8B"
OUT_DIR = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/eval"


def format_session(session):
    """Format a single session as plain text."""
    lines = [f"[Session: {session.get('timestamp', 'unknown')}]"]
    for turn in session.get("turns", []):
        content = turn.get("content")
        if not content:
            continue
        role = turn.get("role", "unknown")
        # Fix corrupted roles (e.g. "assistantWinvalid" -> "Assistant")
        if role.startswith("assistant"):
            role = "Assistant"
        elif role.startswith("user"):
            role = "User"
        else:
            role = role.capitalize()
        lines.append(f"{role}: {content}")
    return "\n".join(lines)


def step1_export_txt():
    """a5_user_data.json -> user_text/{user_id}.txt"""
    print(f"[Step 1] Loading {A5_PATH}")
    with open(A5_PATH, "r", encoding="utf-8") as f:
        data = json.load(f)
    print(f"  {len(data)} users")

    os.makedirs(USER_TEXT_DIR, exist_ok=True)
    count = 0
    for user in data:
        user_id = user["user_id"]
        sessions = user.get("all_sessions", [])
        if not sessions:
            continue

        sessions_sorted = sorted(sessions, key=lambda s: s.get("timestamp", ""))
        full_text = "\n\n".join(format_session(s) for s in sessions_sorted)

        out_path = os.path.join(USER_TEXT_DIR, f"{user_id}.txt")
        with open(out_path, "w", encoding="utf-8") as f:
            f.write(full_text)
        count += 1

    print(f"  Exported {count} user txt files -> {USER_TEXT_DIR}/")
    return count


def step2_token_stats():
    """Tokenize all txt files and plot distribution."""
    from transformers import AutoTokenizer
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    print(f"\n[Step 2] Loading tokenizer from {MODEL_PATH}")
    tok = AutoTokenizer.from_pretrained(MODEL_PATH)

    files = sorted(glob.glob(os.path.join(USER_TEXT_DIR, "*.txt")))
    print(f"  Tokenizing {len(files)} files...")

    counts = []
    for f in files:
        txt = open(f, encoding="utf-8").read()
        counts.append(len(tok.encode(txt, add_special_tokens=False)))

    # Stats
    s = sorted(counts)
    n = len(s)
    def pct(p):
        return s[min(n - 1, int(p / 100 * n))]

    stats = {
        "n": n,
        "min": s[0],
        "max": s[-1],
        "mean": round(statistics.mean(s), 1),
        "median": s[n // 2],
        "p10": pct(10),
        "p25": pct(25),
        "p75": pct(75),
        "p90": pct(90),
        "p95": pct(95),
        "std": round(statistics.pstdev(s), 1),
    }

    print(f"\n  === Token Length Stats ===")
    for k, v in stats.items():
        print(f"    {k}: {v:,}" if isinstance(v, int) else f"    {k}: {v}")

    # Plot
    os.makedirs(OUT_DIR, exist_ok=True)

    fig, ax = plt.subplots(figsize=(10, 5))
    ax.hist(counts, bins=40, color="#4C72B0", edgecolor="white", alpha=0.85)
    ax.axvline(stats["median"], color="black", ls="--", lw=1.5,
               label=f"median={stats['median']:,}")
    ax.axvline(stats["mean"], color="dimgray", ls=":", lw=1.5,
               label=f"mean={stats['mean']:,.0f}")
    ax.set_title(f"User history token length (n={n}, Qwen3-8B tokens)\n"
                 f"zhangxinyuan a5_user_data")
    ax.set_xlabel("tokens per user")
    ax.set_ylabel("number of users")
    ax.legend()
    fig.tight_layout()

    out_png = os.path.join(OUT_DIR, "user_history_tokens.png")
    fig.savefig(out_png, dpi=130)
    plt.close(fig)
    print(f"\n  Plot saved -> {out_png}")

    # Save JSON
    out_json = os.path.join(OUT_DIR, "user_history_tokens.json")
    with open(out_json, "w") as f:
        json.dump({"stats": stats, "raw_counts": counts}, f, indent=2)
    print(f"  Stats saved -> {out_json}")


if __name__ == "__main__":
    step1_export_txt()
    step2_token_stats()