Datasets:

Modalities:
Text
ArXiv:
llmtcl / visualization /ppl_heat_map.py
Maple222's picture
Add files using upload-large-folder tool
53e0dae verified
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 月份,只取前4位数字
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)
# 加上 ckpt_month 字段(训练月)
row["ckpt_month"] = ckpt_str
# 原来的 month 就是 val_month(验证月)
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)
# ckpt_month -> val_month -> list
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)
# 对齐 months 顺序,填矩阵
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))