File size: 4,362 Bytes
5b2e6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
import argparse
import csv
import re
from pathlib import Path

import matplotlib.pyplot as plt


EPOCH_RE = re.compile(r"\[epoch\s+(\d+)\s+md\]\s+(.*)")


def _parse_value(raw):
    raw = raw.strip().rstrip(",")
    try:
        return float(raw)
    except ValueError:
        return None


def parse_epoch_log(path):
    rows = []
    for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines():
        match = EPOCH_RE.search(line)
        if not match:
            continue
        row = {"epoch": int(match.group(1))}
        for item in match.group(2).split(","):
            if "=" not in item:
                continue
            key, value = item.split("=", 1)
            parsed = _parse_value(value)
            if parsed is not None:
                row[key.strip()] = parsed
        rows.append(row)
    return rows


def parse_csv(path):
    rows = []
    with Path(path).open("r", encoding="utf-8", errors="replace", newline="") as handle:
        for raw in csv.DictReader(handle):
            row = {}
            for key, value in raw.items():
                if key is None:
                    continue
                if key == "epoch":
                    row[key] = int(float(value))
                else:
                    parsed = _parse_value(value)
                    if parsed is not None:
                        row[key] = parsed
            if "epoch" in row:
                rows.append(row)
    return rows


def plot_group(rows, metrics, title, output_path):
    epochs = [row["epoch"] for row in rows]
    fig, axes = plt.subplots(len(metrics), 1, figsize=(10, 2.4 * len(metrics)), sharex=True)
    if len(metrics) == 1:
        axes = [axes]
    for axis, metric in zip(axes, metrics):
        values = [row.get(metric) for row in rows]
        valid = [(epoch, value) for epoch, value in zip(epochs, values) if value is not None]
        if valid:
            axis.plot([x for x, _ in valid], [y for _, y in valid], marker="o", linewidth=1.5)
        axis.set_ylabel(metric)
        axis.grid(True, alpha=0.25)
    axes[-1].set_xlabel("epoch")
    fig.suptitle(title)
    fig.tight_layout()
    fig.savefig(output_path, dpi=180)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description="Plot BBFlow per-epoch latent/training metrics.")
    parser.add_argument("input", help="train.log or latent_train_epoch_metrics.csv")
    parser.add_argument("--out-dir", default="metric_plots")
    args = parser.parse_args()

    input_path = Path(args.input)
    rows = parse_csv(input_path) if input_path.suffix.lower() == ".csv" else parse_epoch_log(input_path)
    if not rows:
        raise SystemExit(f"No epoch metric rows found in {input_path}")
    rows = sorted(rows, key=lambda row: row["epoch"])

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    groups = {
        "losses": [
            "train_loss",
            "official_loss",
            "motion_loss",
            "q_nll_per_dim",
            "mode_orth_loss",
        ],
        "mode_health": [
            "mode_coeff_abs",
            "mode_coeff_std",
            "mode_recon_centered_rel_error",
            "mode_gram_condition",
            "mode_max_cosine_abs",
            "latent_effective_modes",
        ],
        "covariance": [
            "local_cov_loss",
            "cross_cov_loss",
            "cross_cov_far_loss",
            "cross_cov_far_corr",
            "cross_cov_far_top10_sign_agree",
            "rmsf_loss",
        ],
        "condition": [
            "condition_scaled_pred_trans_delta_rel",
            "condition_pred_trans_delta_rel",
            "condition_delta_rel",
            "cross_cov_far_corr",
            "q_nll_per_dim",
        ],
    }

    written = []
    available = set().union(*(row.keys() for row in rows))
    for name, metrics in groups.items():
        present = [metric for metric in metrics if metric in available]
        if not present:
            continue
        output_path = out_dir / f"{name}.png"
        plot_group(rows, present, f"{name} ({input_path.name})", output_path)
        written.append(output_path)

    print(f"Parsed {len(rows)} epoch rows: {rows[0]['epoch']}..{rows[-1]['epoch']}")
    for path in written:
        print(path)


if __name__ == "__main__":
    main()