File size: 3,514 Bytes
0a2c21d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch


def main():
    parser = argparse.ArgumentParser(description="Visualize matched token change-rate curves.")
    parser.add_argument("input", help="Path to token_dynamics_*.pt artifact.")
    parser.add_argument("--output-dir", default=None)
    parser.add_argument("--stride", type=int, default=16, help="Plot every N-th noise token.")
    parser.add_argument("--max-pairs", type=int, default=32, help="Maximum number of pair plots.")
    args = parser.parse_args()

    artifact = torch.load(args.input, map_location="cpu")
    output_dir = Path(args.output_dir or Path(args.input).parent)
    output_dir.mkdir(parents=True, exist_ok=True)
    stem = Path(args.input).stem

    match_indices = artifact["match_indices"].long()
    history_rates = artifact["history_change_rates"].float()
    noise_rates = artifact["noise_change_rates"].float()
    grid_h, grid_w = artifact["grid"]
    step_indices = artifact.get("step_indices", list(range(history_rates.shape[0])))
    timesteps = artifact.get("timesteps", step_indices)

    if history_rates.numel() == 0 or noise_rates.numel() == 0:
        raise RuntimeError("Artifact has no change-rate records.")

    x = list(timesteps)
    plotted = 0
    for noise_idx in range(match_indices.numel()):
        if noise_idx % args.stride != 0:
            continue
        if plotted >= args.max_pairs:
            break

        hist_idx = int(match_indices[noise_idx].item())
        noise_y = noise_idx // grid_w
        noise_x = noise_idx % grid_w
        hist_y = hist_idx // grid_w
        hist_x = hist_idx % grid_w

        fig, ax = plt.subplots(figsize=(8, 4.5), dpi=160)
        ax.plot(x, history_rates[:, hist_idx].numpy(), label=f"history ({hist_y},{hist_x})", linewidth=2)
        ax.plot(x, noise_rates[:, noise_idx].numpy(), label=f"noise ({noise_y},{noise_x})", linewidth=2)
        ax.set_xlabel("denoise step / timestep")
        ax.set_ylabel("token change rate")
        hist_src = artifact.get("history_source_chunk")
        hist_src_frame = artifact.get("history_source_frame")
        src_note = ""
        if hist_src is not None and hist_src_frame is not None:
            src_note = f"\nhistory rates: chunk {hist_src} frame {hist_src_frame}"
        ax.set_title(
            f"matched pair: noise ({noise_y},{noise_x}) -> history ({hist_y},{hist_x}){src_note}"
        )
        ax.grid(True, alpha=0.3)
        ax.legend()
        fig.tight_layout()
        out = output_dir / f"{stem}_pair_noise{noise_y}_{noise_x}_hist{hist_y}_{hist_x}.png"
        fig.savefig(out)
        plt.close(fig)
        plotted += 1

    summary_fig, ax = plt.subplots(figsize=(9, 5), dpi=160)
    mean_history = history_rates.mean(dim=1).numpy()
    mean_noise = noise_rates.mean(dim=1).numpy()
    ax.plot(x, mean_history, label="history mean", linewidth=2)
    ax.plot(x, mean_noise, label="noise mean", linewidth=2)
    ax.set_xlabel("denoise step / timestep")
    ax.set_ylabel("mean token change rate")
    ax.set_title("mean change rate over all tokens")
    ax.grid(True, alpha=0.3)
    ax.legend()
    summary_fig.tight_layout()
    summary_path = output_dir / f"{stem}_mean_summary.png"
    summary_fig.savefig(summary_path)
    plt.close(summary_fig)

    print(f"Saved {plotted} pair plots to {output_dir}")
    print(f"Saved summary: {summary_path}")


if __name__ == "__main__":
    main()