File size: 2,651 Bytes
0f00646
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import argparse
import json
from pathlib import Path
from typing import List

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np


def load_mean_change_rates(json_path: Path) -> List[float]:
    with json_path.open("r") as f:
        payload = json.load(f)

    if isinstance(payload, dict) and isinstance(payload.get("mean_change_rates"), list):
        rates = payload["mean_change_rates"]
    elif isinstance(payload, dict) and isinstance(payload.get("tokens"), list):
        rates = [float(item["mean_change_rate"]) for item in payload["tokens"]]
    else:
        raise ValueError(f"Cannot find per-token mean change rates in {json_path}")

    rates = [float(value) for value in rates if np.isfinite(value)]
    if not rates:
        raise ValueError(f"No valid mean change rates found in {json_path}")
    return rates


def plot_density(
    rates: List[float],
    output_path: Path,
    bins: int,
    chunk_idx: int,
) -> None:
    fig, ax = plt.subplots(figsize=(8, 5))
    ax.hist(rates, bins=bins, density=True, color="#4C78A8", alpha=0.85, edgecolor="white", linewidth=0.5)
    ax.set_xlabel("Mean L2 norm change rate")
    ax.set_ylabel("Density")
    ax.set_title(f"Chunk {chunk_idx} token heterogeneity (n={len(rates)} tokens)")
    ax.grid(True, alpha=0.25, linestyle="--", linewidth=0.5)
    fig.tight_layout()
    output_path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(output_path, dpi=160)
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Plot per-token mean L2 norm change-rate density for one chunk."
    )
    parser.add_argument(
        "json_path",
        type=Path,
        help="Path to token L2 change-rate stats JSON saved by --token_l2_change_rate_stats_path.",
    )
    parser.add_argument("-o", "--output", type=Path, required=True, help="Output image path.")
    parser.add_argument("--bins", type=int, default=50, help="Number of histogram bins.")
    parser.add_argument(
        "--chunk-idx",
        type=int,
        default=None,
        help="Chunk index for plot title. Defaults to target_generated_chunk_idx in JSON.",
    )
    args = parser.parse_args()

    with args.json_path.open("r") as f:
        payload = json.load(f)
    chunk_idx = args.chunk_idx
    if chunk_idx is None:
        chunk_idx = int(payload.get("target_generated_chunk_idx", 0))

    rates = load_mean_change_rates(args.json_path)
    plot_density(rates, args.output, bins=args.bins, chunk_idx=chunk_idx)
    print(f"Saved density plot to {args.output}")


if __name__ == "__main__":
    main()