File size: 5,193 Bytes
37a82b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3

import argparse
import json
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple

import matplotlib

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


def parse_int_list(value: Optional[str]) -> Optional[Set[int]]:
    if not value:
        return None
    return {int(item.strip()) for item in value.split(",") if item.strip()}


def load_l1_rel_records(json_path: Path) -> List[dict]:
    with json_path.open("r") as f:
        payload = json.load(f)
    if isinstance(payload, list):
        return payload
    if isinstance(payload, dict) and isinstance(payload.get("records"), list):
        return payload["records"]
    raise ValueError(f"Cannot find records in {json_path}")


def collect_by_chunk(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]:
    chunks = defaultdict(list)
    for record in records:
        chunk_idx = int(record["chunk_idx"])
        if chunk_ids is not None and chunk_idx not in chunk_ids:
            continue
        chunks[chunk_idx].append(record)

    chunks = dict(sorted(chunks.items()))
    if max_chunks is not None:
        chunks = dict(list(chunks.items())[:max_chunks])
    return chunks


def plot_l1_rel(
    chunks: Dict[int, List[dict]],
    output_path: Path,
    x_field: str,
    y_field: str,
    reverse_x: bool,
    title: Optional[str],
    figsize: Tuple[float, float],
    dpi: int,
) -> None:
    fig, ax = plt.subplots(figsize=figsize)

    for chunk_idx, records in chunks.items():
        points = []
        for record in records:
            if x_field not in record or y_field not in record:
                continue
            if record[x_field] is None or record[y_field] is None:
                continue
            points.append((float(record[x_field]), float(record[y_field])))
        if not points:
            continue

        points.sort(key=lambda item: item[0])
        xs, ys = zip(*points)
        ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}")

    ax.set_xlabel(x_field)
    ax.set_ylabel(y_field)
    ax.set_title(title or f"{y_field} by timestep")
    ax.grid(True, alpha=0.3)
    if reverse_x:
        ax.invert_xaxis()
    ax.legend(loc="best", fontsize="small", ncols=2)
    fig.tight_layout()

    output_path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(output_path, dpi=dpi)
    plt.close(fig)


def parse_arguments():
    parser = argparse.ArgumentParser(description="Plot per-chunk MAGI relative L1 change curves.")
    parser.add_argument("json_path", type=Path, help="Path to L1 relative change JSON saved by --l1_rel_stats_path.")
    parser.add_argument("-o", "--output", type=Path, help="Output image path. Defaults to <json stem>_plot.png.")
    parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.")
    parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.")
    parser.add_argument(
        "--x-field",
        choices=["timestep", "next_timestep", "cur_denoise_step", "denoise_idx"],
        default="next_timestep",
        help="Record field used for the x axis. next_timestep is the cleaner MAGI step.",
    )
    parser.add_argument(
        "--y-field",
        choices=[
            "l1_rel",
            "l1_rel_ratio",
            "delta_l1_norm",
            "x_l1_norm",
            "x_embedder_l1_rel",
            "x_embedder_l1_rel_ratio",
            "x_embedder_delta_l1_norm",
            "x_embedder_x_l1_norm",
            "flowcache_rel_l1",
            "flowcache_rel_l1_ratio",
            "flowcache_delta_l1_norm",
            "flowcache_prev_feat_l1_norm",
            "flowcache_accumulated_rel_l1",
            "rel_l1_thresh",
        ],
        default="l1_rel",
        help="Record field used for the y axis.",
    )
    parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.")
    parser.add_argument("--title", type=str, help="Figure title.")
    parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.")
    parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.")
    return parser.parse_args()


def main():
    args = parse_arguments()
    output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_plot.png")
    figsize = [float(part.strip()) for part in args.figsize.split(",")]
    if len(figsize) != 2:
        raise ValueError("--figsize must be formatted as width,height")

    records = load_l1_rel_records(args.json_path)
    chunks = collect_by_chunk(records, parse_int_list(args.chunks), args.max_chunks)
    if not chunks:
        raise ValueError("No records matched the requested chunks.")

    plot_l1_rel(
        chunks=chunks,
        output_path=output_path,
        x_field=args.x_field,
        y_field=args.y_field,
        reverse_x=args.reverse_x,
        title=args.title,
        figsize=(figsize[0], figsize[1]),
        dpi=args.dpi,
    )
    print(f"Saved plot to {output_path}")


if __name__ == "__main__":
    main()