| import json
|
| import numpy as np
|
| import matplotlib.pyplot as plt
|
| import seaborn as sns
|
| import argparse
|
| from pathlib import Path
|
|
|
|
|
| months = [2407, 2408, 2409, 2410, 2411, 2412,
|
| 2501, 2502, 2503, 2504, 2505, 2506]
|
|
|
|
|
| def load_results(path: Path):
|
| results = []
|
| if path.is_file():
|
| files = [path]
|
| elif path.is_dir():
|
| files = sorted(path.rglob("ppl_metrics.jsonl"))
|
| if not files:
|
| raise FileNotFoundError(f"目录 {path} 下没有找到 ppl_metrics.jsonl")
|
| else:
|
| raise FileNotFoundError(f"{path} 不存在")
|
|
|
| for file in files:
|
|
|
| ckpt_str = ''.join(filter(str.isdigit, file.parent.name[:4]))
|
|
|
| with open(file, "r", encoding="utf-8") as f:
|
| for line in f:
|
| if line.strip():
|
| row = json.loads(line)
|
|
|
| row["ckpt_month"] = ckpt_str
|
|
|
| row["val_month"] = str(row["month"])
|
| results.append(row)
|
| return results
|
|
|
|
|
|
|
| def build_matrix(results, metric="val_ppl"):
|
| n = len(months)
|
| mat = np.full((n, n), np.nan)
|
|
|
|
|
| data = {}
|
| for row in results:
|
| ckpt = str(row["ckpt_month"])
|
| val = str(row["val_month"])
|
| value = row.get(metric, None)
|
| if value is None:
|
| continue
|
| data.setdefault(ckpt, {}).setdefault(val, []).append(value)
|
|
|
|
|
| for i, ckpt in enumerate(months):
|
| for j, val in enumerate(months):
|
| if str(ckpt) in data and str(val) in data[str(ckpt)]:
|
| mat[i, j] = np.mean(data[str(ckpt)][str(val)])
|
|
|
| return mat
|
|
|
|
|
|
|
| def plot_heatmap(matrix, metric="val_ppl", save_path="heatmap.png"):
|
| plt.figure(figsize=(10, 8))
|
| sns.heatmap(matrix, xticklabels=months, yticklabels=months,
|
| cmap="viridis", annot=True, fmt=".2f")
|
| plt.xlabel("Validation month (j)")
|
| plt.ylabel("Checkpoint month (i)")
|
| plt.title(f"{metric} Heatmap (12x12)")
|
| plt.tight_layout()
|
| plt.savefig(save_path, dpi=300)
|
| print(f"[Saved] {save_path}")
|
|
|
|
|
| def parse_args():
|
| parser = argparse.ArgumentParser(description="Build ppl/loss heatmap from jsonl results.")
|
| parser.add_argument("input", type=str,
|
| help="输入的 ppl_metrics.jsonl 文件 或 包含多个子文件夹的目录")
|
| parser.add_argument("--metric", type=str, default="val_ppl",
|
| choices=["val_ppl", "val_loss"],
|
| help="选择绘制的指标 (默认: val_ppl)")
|
| parser.add_argument("--out", type=str, default=None,
|
| help="输出图片路径 (默认: 输入路径下 heatmap.png)")
|
| return parser.parse_args()
|
|
|
|
|
| if __name__ == "__main__":
|
| args = parse_args()
|
| results = load_results(Path(args.input))
|
| mat = build_matrix(results, metric=args.metric)
|
|
|
| if args.out is None:
|
| out_path = Path(args.input)
|
| if out_path.is_dir():
|
| out_path = out_path / f"{args.metric}_heatmap.png"
|
| else:
|
| out_path = out_path.with_suffix(f"_{args.metric}_heatmap.png")
|
| else:
|
| out_path = Path(args.out)
|
|
|
| plot_heatmap(mat, metric=args.metric, save_path=str(out_path))
|
|
|