"""Generate training and evaluation charts from real GRPO/eval JSON logs.""" from __future__ import annotations import argparse import json import os from typing import Any, Dict, List, Optional def load_training_metrics(logs_path: str) -> Dict[str, List[float]]: """Load and align TRL log_history entries by training step.""" with open(logs_path, "r", encoding="utf-8") as fh: history = json.load(fh) if not isinstance(history, list): raise ValueError(f"Expected a list of log entries in {logs_path}") by_step: Dict[int, Dict[str, Any]] = {} for log in history: if isinstance(log, dict) and "step" in log: step = int(log["step"]) by_step.setdefault(step, {}).update(log) steps: List[int] = [] rewards: List[float] = [] losses: List[float] = [] reward_stds: List[float] = [] completion_lengths: List[float] = [] learning_rates: List[float] = [] for step in sorted(by_step): entry = by_step[step] reward = entry.get("reward", entry.get("rewards/mean")) loss = entry.get("loss") if reward is None and loss is None: continue steps.append(step) rewards.append(float(reward) if reward is not None else float("nan")) losses.append(float(loss) if loss is not None else float("nan")) std_val = entry.get("reward_std", entry.get("rewards/std", 0.0)) reward_stds.append(float(std_val) if std_val is not None else 0.0) comp_len = entry.get("completion_length", entry.get("completions/mean_length", 0.0)) completion_lengths.append(float(comp_len) if comp_len is not None else 0.0) lr = entry.get("learning_rate", 0.0) learning_rates.append(float(lr) if lr is not None else 0.0) return { "steps": steps, "rewards": rewards, "losses": losses, "reward_stds": reward_stds, "completion_lengths": completion_lengths, "learning_rates": learning_rates, } def _plot_series(plt, x, y, title: str, ylabel: str, label: str, color: str, out_path: str, hline: Optional[tuple] = None): plt.figure(figsize=(10, 5)) plt.plot(x, y, label=label, color=color, linewidth=2) if hline is not None: plt.axhline(y=hline[0], color=hline[1], linestyle=hline[2], label=hline[3]) plt.title(title) plt.xlabel("Training Steps") plt.ylabel(ylabel) plt.grid(True, alpha=0.3) plt.legend() plt.savefig(out_path, dpi=300, bbox_inches="tight") plt.close() def generate_graphs( logs_path: str = "results/training_logs.json", eval_path: str = "results/eval_comparison.json", out_dir: str = "images", ) -> List[str]: """Generate PNG charts from actual training logs and evaluation results.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt os.makedirs(out_dir, exist_ok=True) written: List[str] = [] if os.path.exists(logs_path): metrics = load_training_metrics(logs_path) steps = metrics["steps"] if not steps: raise ValueError(f"No step metrics found in {logs_path}") reward_pairs = [(s, r) for s, r in zip(steps, metrics["rewards"]) if r == r] if reward_pairs: p = os.path.join(out_dir, "meanfleet.PNG") _plot_series( plt, [x[0] for x in reward_pairs], [x[1] for x in reward_pairs], "Libratio Fleet: GRPO Reward Optimization", "Reward Score", "Mean Fleet Reward", "#00e676", p, hline=(0.90, "r", "--", "Target (>0.90)"), ) written.append(p) loss_pairs = [(s, l) for s, l in zip(steps, metrics["losses"]) if l == l] if loss_pairs: p = os.path.join(out_dir, "policyloss.PNG") _plot_series( plt, [x[0] for x in loss_pairs], [x[1] for x in loss_pairs], "Libratio Fleet: Model Loss Curve", "Loss", "Policy Loss", "#ff1744", p, ) written.append(p) if any(v > 0 for v in metrics["reward_stds"]): p = os.path.join(out_dir, "RewardVariance.PNG") _plot_series( plt, steps, metrics["reward_stds"], "Libratio Fleet: Reward Variance Over Time", "Standard Deviation", "Reward Std Dev", "#ff9100", p, ) written.append(p) if any(v > 0 for v in metrics["completion_lengths"]): p = os.path.join(out_dir, "outputconvergence.PNG") _plot_series( plt, steps, metrics["completion_lengths"], "Libratio Fleet: JSON Output Stability", "Generated Tokens per Action", "Action Token Length", "#00e5ff", p, ) written.append(p) if os.path.exists(eval_path): with open(eval_path, "r", encoding="utf-8") as fh: eval_data = json.load(fh) summary = eval_data.get("overall", {}) if summary: labels = list(summary.keys()) scores = [float(summary[k]["mean_score"]) for k in labels] colors = ["#ff1744", "#f59e0b", "#00e676", "#38bdf8"][: len(labels)] fig, ax = plt.subplots(figsize=(8, 5)) bars = ax.bar(labels, scores, color=colors, width=0.5, edgecolor="#0d1117", linewidth=2) for bar, score in zip(bars, scores): ax.text( bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.02, f"{score:.3f}", ha="center", va="bottom", fontsize=13, fontweight="bold", color="white", ) ax.set_ylim(0, 1.1) ax.set_ylabel("Mean Reward Score", fontsize=12, color="white") ax.set_title("Libratio Fleet: Baseline vs Trained Agent", fontsize=14, fontweight="bold", color="white") ax.set_facecolor("#0d1117") fig.patch.set_facecolor("#0d1117") ax.tick_params(colors="white") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) p = os.path.join(out_dir, "baseline_vs_trained.PNG") plt.savefig(p, dpi=300, bbox_inches="tight", facecolor="#0d1117") plt.close() written.append(p) if not written: raise FileNotFoundError( f"No real log or eval files found at '{logs_path}' or '{eval_path}'. " "Run GRPO training or 'python fleet_inference.py --eval --baselines-only' first." ) return written def main() -> int: parser = argparse.ArgumentParser(description="Generate graphs from real training and eval logs.") parser.add_argument("--logs", default="results/training_logs.json", help="Path to TRL training_logs.json") parser.add_argument("--eval", default="results/eval_comparison.json", help="Path to eval_comparison.json") parser.add_argument("--out-dir", default="images", help="Output directory for PNG charts") args = parser.parse_args() paths = generate_graphs(logs_path=args.logs, eval_path=args.eval, out_dir=args.out_dir) for path in paths: print(f"Saved {path}") return 0 if __name__ == "__main__": raise SystemExit(main())