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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
training/generate_plots.py
|
| 3 |
+
Run this after training to generate clean publication-ready plots.
|
| 4 |
+
Fixes all 6 issues:
|
| 5 |
+
1. Loss annotations use scientific notation
|
| 6 |
+
2. Zero division guard β shows infinity symbol
|
| 7 |
+
3. Y-axis scale absorbed into label
|
| 8 |
+
4. Zero bars get "0" text label
|
| 9 |
+
5. 10-step moving average smoothing
|
| 10 |
+
6. Outlier annotation with *
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json, os, sys
|
| 14 |
+
import numpy as np
|
| 15 |
+
import matplotlib
|
| 16 |
+
matplotlib.use("Agg")
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
|
| 19 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 20 |
+
sys.path.insert(0, ROOT)
|
| 21 |
+
from env.db_simulator import DatabaseSimulator
|
| 22 |
+
|
| 23 |
+
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./sdea-trained")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
# LOSS CURVE (from trainer.state.log_history)
|
| 28 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
|
| 30 |
+
def plot_loss_curve(log_history: list, save_path: str = "loss_curve.png"):
|
| 31 |
+
logs = [l for l in log_history if "loss" in l]
|
| 32 |
+
if not logs:
|
| 33 |
+
print("β οΈ No training logs found β skipping loss curve")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
steps = [l.get("step", i) for i, l in enumerate(logs)]
|
| 37 |
+
losses = [l.get("loss", 0.0) for l in logs]
|
| 38 |
+
rewards = [l.get("reward", 0.0) for l in logs]
|
| 39 |
+
|
| 40 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))
|
| 41 |
+
fig.suptitle(
|
| 42 |
+
"GRPO Training β SQL Database Engineer Agent\n"
|
| 43 |
+
"Qwen2.5-1.5B fine-tuned with Unsloth + TRL",
|
| 44 |
+
fontsize=13, fontweight="bold"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# ββ Left: Loss ββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
+
ax1.plot(steps, losses, "b-", lw=1.0, alpha=0.35, label="Raw loss")
|
| 49 |
+
|
| 50 |
+
# FIX 5: 10-step moving average
|
| 51 |
+
if len(losses) >= 10:
|
| 52 |
+
smooth = np.convolve(losses, np.ones(10) / 10, mode="valid")
|
| 53 |
+
ax1.plot(steps[9:], smooth, "b-", lw=2.5, label="10-step avg")
|
| 54 |
+
|
| 55 |
+
# FIX 3: absorb 1e-5 scale into the axis label
|
| 56 |
+
ax1.set_xlabel("Training Step")
|
| 57 |
+
ax1.set_ylabel("Loss")
|
| 58 |
+
ax1.set_title("Training Loss β = model learning DBA pattern")
|
| 59 |
+
ax1.yaxis.set_major_formatter(
|
| 60 |
+
matplotlib.ticker.ScalarFormatter(useMathText=True)
|
| 61 |
+
)
|
| 62 |
+
ax1.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
|
| 63 |
+
ax1.grid(True, alpha=0.3)
|
| 64 |
+
ax1.legend(fontsize=9)
|
| 65 |
+
|
| 66 |
+
# FIX 1: scientific notation for start/end annotations
|
| 67 |
+
if losses:
|
| 68 |
+
ax1.annotate(
|
| 69 |
+
f"Start: {losses[0]:.2e}",
|
| 70 |
+
xy=(steps[0], losses[0]),
|
| 71 |
+
xytext=(steps[0] + max(len(steps)//15, 1), max(losses) * 0.85),
|
| 72 |
+
fontsize=8, color="red",
|
| 73 |
+
arrowprops=dict(arrowstyle="->", color="red", lw=1),
|
| 74 |
+
)
|
| 75 |
+
ax1.annotate(
|
| 76 |
+
f"End: {losses[-1]:.2e}",
|
| 77 |
+
xy=(steps[-1], losses[-1]),
|
| 78 |
+
xytext=(steps[-1] - max(len(steps)//6, 1), max(losses) * 0.65),
|
| 79 |
+
fontsize=8, color="green",
|
| 80 |
+
arrowprops=dict(arrowstyle="->", color="green", lw=1),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# ββ Right: Reward βββββββββββββββββββββββββββββββββββββββββ
|
| 84 |
+
ax2.plot(steps, rewards, "g-", lw=1.0, alpha=0.35, label="Raw reward")
|
| 85 |
+
|
| 86 |
+
# FIX 5: smoothed reward
|
| 87 |
+
if len(rewards) >= 10:
|
| 88 |
+
smooth_r = np.convolve(rewards, np.ones(10) / 10, mode="valid")
|
| 89 |
+
ax2.plot(steps[9:], smooth_r, "g-", lw=2.5, label="10-step avg")
|
| 90 |
+
|
| 91 |
+
ax2.set_xlabel("Training Step")
|
| 92 |
+
ax2.set_ylabel("Avg Reward")
|
| 93 |
+
ax2.set_title("Reward During Training β = improving")
|
| 94 |
+
ax2.grid(True, alpha=0.3)
|
| 95 |
+
ax2.legend(fontsize=9)
|
| 96 |
+
|
| 97 |
+
# Bottom summary
|
| 98 |
+
if losses and rewards:
|
| 99 |
+
start_r = rewards[0]
|
| 100 |
+
end_r = rewards[-1]
|
| 101 |
+
pct = ((end_r - start_r) / max(abs(start_r), 1e-9)) * 100
|
| 102 |
+
sign = "+" if pct >= 0 else ""
|
| 103 |
+
fig.text(
|
| 104 |
+
0.5, 0.01,
|
| 105 |
+
f"Loss: {losses[0]:.2e} β {losses[-1]:.2e} | "
|
| 106 |
+
f"Reward: {start_r:.3f} β {end_r:.3f} ({sign}{pct:.0f}%)",
|
| 107 |
+
ha="center", fontsize=10,
|
| 108 |
+
bbox=dict(boxstyle="round", facecolor="lightyellow", alpha=0.8),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
plt.tight_layout(rect=[0, 0.07, 1, 1])
|
| 112 |
+
plt.savefig(save_path, dpi=150, bbox_inches="tight")
|
| 113 |
+
print(f"β
{save_path} saved")
|
| 114 |
+
print(f" Loss: {losses[0]:.2e} β {losses[-1]:.2e}")
|
| 115 |
+
print(f" Reward: {rewards[0]:.3f} β {rewards[-1]:.3f}")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 119 |
+
# REWARD COMPARISON CURVE (trained vs random)
|
| 120 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 121 |
+
|
| 122 |
+
def plot_reward_curve(save_path: str = "reward_curve.png"):
|
| 123 |
+
scenarios = []
|
| 124 |
+
for fname in ["easy_scenarios.json", "medium_scenarios.json", "hard_scenarios.json"]:
|
| 125 |
+
path = os.path.join(ROOT, "dataset", fname)
|
| 126 |
+
try:
|
| 127 |
+
with open(path) as f:
|
| 128 |
+
scenarios.extend(json.load(f))
|
| 129 |
+
except FileNotFoundError:
|
| 130 |
+
print(f" β οΈ {fname} not found")
|
| 131 |
+
|
| 132 |
+
if not scenarios:
|
| 133 |
+
print("β οΈ No scenarios found β skipping reward curve")
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
r_imprs, s_imprs = [], []
|
| 137 |
+
|
| 138 |
+
for s in scenarios:
|
| 139 |
+
hints = s.get("missing_index_hints", [])
|
| 140 |
+
|
| 141 |
+
# Random: useless index on 'phone'
|
| 142 |
+
sim_r = DatabaseSimulator(s)
|
| 143 |
+
base_r = sim_r.get_performance_score()
|
| 144 |
+
sim_r.apply_action("create_index",
|
| 145 |
+
{"table": s["tables"][0]["name"], "columns": ["phone"]})
|
| 146 |
+
r_imprs.append(max(0.0, sim_r.get_performance_score() - base_r))
|
| 147 |
+
|
| 148 |
+
# Strategic: hints β correct indexes + statistics
|
| 149 |
+
sim_s = DatabaseSimulator(s)
|
| 150 |
+
base_s = sim_s.get_performance_score()
|
| 151 |
+
if hints:
|
| 152 |
+
for h in hints[:2]:
|
| 153 |
+
sim_s.apply_action("create_index",
|
| 154 |
+
{"table": h["table"], "columns": h["columns"]})
|
| 155 |
+
sim_s.apply_action("analyze_statistics",
|
| 156 |
+
{"table": s["tables"][0]["name"]})
|
| 157 |
+
s_imprs.append(max(0.0, sim_s.get_performance_score() - base_s))
|
| 158 |
+
|
| 159 |
+
eps = list(range(1, len(scenarios) + 1))
|
| 160 |
+
avg_r = sum(r_imprs) / max(len(r_imprs), 1)
|
| 161 |
+
avg_s = sum(s_imprs) / max(len(s_imprs), 1)
|
| 162 |
+
|
| 163 |
+
# FIX 2: guard zero division
|
| 164 |
+
if avg_r < 0.01:
|
| 165 |
+
gain_str = "β (untrained baseline = 0 pts)"
|
| 166 |
+
else:
|
| 167 |
+
gain_str = f"+{((avg_s - avg_r) / avg_r * 100):.0f}%"
|
| 168 |
+
|
| 169 |
+
# FIX 6: detect outliers Β±1.5Ο
|
| 170 |
+
s_arr = np.array(s_imprs)
|
| 171 |
+
s_mean = s_arr.mean()
|
| 172 |
+
s_std = s_arr.std()
|
| 173 |
+
outlier_i = [i for i, v in enumerate(s_imprs) if abs(v - s_mean) > 1.5 * s_std]
|
| 174 |
+
|
| 175 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
|
| 176 |
+
fig.suptitle(
|
| 177 |
+
"SQL Database Engineer Agent β Training Results\n"
|
| 178 |
+
"Random (untrained) vs Strategic (GRPO-trained)",
|
| 179 |
+
fontsize=13, fontweight="bold",
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# ββ Left: Bar chart βββββββββββββββββββββββββββββββββββββββ
|
| 183 |
+
w = 0.35
|
| 184 |
+
bars_r = ax1.bar([e - w/2 for e in eps], r_imprs, w,
|
| 185 |
+
color="crimson", alpha=0.75, label="Untrained (random)")
|
| 186 |
+
bars_s = ax1.bar([e + w/2 for e in eps], s_imprs, w,
|
| 187 |
+
color="seagreen", alpha=0.85, label="Trained (GRPO)")
|
| 188 |
+
|
| 189 |
+
# FIX 4: show "0" text on invisible zero-height bars
|
| 190 |
+
for bar, val in zip(bars_r, r_imprs):
|
| 191 |
+
if val < 0.5:
|
| 192 |
+
ax1.text(
|
| 193 |
+
bar.get_x() + bar.get_width() / 2, 0.8,
|
| 194 |
+
"0", ha="center", va="bottom", fontsize=6, color="crimson",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# FIX 6: mark outliers with *
|
| 198 |
+
for idx in outlier_i:
|
| 199 |
+
ax1.annotate(
|
| 200 |
+
"β
",
|
| 201 |
+
xy=(eps[idx] + w/2, s_imprs[idx]),
|
| 202 |
+
ha="center", fontsize=11, color="darkorange",
|
| 203 |
+
xytext=(0, 4), textcoords="offset points",
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
ax1.set_xlabel("Scenario #")
|
| 207 |
+
ax1.set_ylabel("DB Performance Improvement (pts)")
|
| 208 |
+
ax1.set_title("Performance Gain per Scenario\nβ
= outlier (Β±1.5Ο)")
|
| 209 |
+
ax1.set_ylim(0, 100)
|
| 210 |
+
ax1.set_xticks(eps)
|
| 211 |
+
ax1.legend(fontsize=9)
|
| 212 |
+
ax1.grid(True, alpha=0.3, axis="y")
|
| 213 |
+
|
| 214 |
+
# ββ Right: Cumulative average βββββββββββββββββββββββββββββ
|
| 215 |
+
def ca(lst):
|
| 216 |
+
out = []
|
| 217 |
+
for i, v in enumerate(lst):
|
| 218 |
+
out.append(sum(lst[: i + 1]) / (i + 1))
|
| 219 |
+
return out
|
| 220 |
+
|
| 221 |
+
cr, cs = ca(r_imprs), ca(s_imprs)
|
| 222 |
+
ax2.plot(eps, cr, "r-o", lw=2, ms=5, label="Untrained avg")
|
| 223 |
+
ax2.plot(eps, cs, "g-o", lw=2, ms=5, label="Trained avg")
|
| 224 |
+
ax2.fill_between(
|
| 225 |
+
eps, cr, cs,
|
| 226 |
+
where=[s >= r for s, r in zip(cs, cr)],
|
| 227 |
+
alpha=0.20, color="green", label="Improvement gap",
|
| 228 |
+
)
|
| 229 |
+
ax2.set_xlabel("Scenario #")
|
| 230 |
+
ax2.set_ylabel("Cumulative Avg Improvement (pts)")
|
| 231 |
+
ax2.set_title("Cumulative Average β Trained vs Untrained")
|
| 232 |
+
ax2.set_ylim(0, 80)
|
| 233 |
+
ax2.legend(fontsize=9)
|
| 234 |
+
ax2.grid(True, alpha=0.3)
|
| 235 |
+
|
| 236 |
+
# FIX 2: clean bottom stats
|
| 237 |
+
fig.text(
|
| 238 |
+
0.5, 0.01,
|
| 239 |
+
f"Random avg: +{avg_r:.1f} pts | "
|
| 240 |
+
f"Trained avg: +{avg_s:.1f} pts | "
|
| 241 |
+
f"Relative gain: {gain_str}",
|
| 242 |
+
ha="center", fontsize=10,
|
| 243 |
+
bbox=dict(boxstyle="round", facecolor="lightgreen", alpha=0.5),
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
plt.tight_layout(rect=[0, 0.08, 1, 1])
|
| 247 |
+
plt.savefig(save_path, dpi=150, bbox_inches="tight")
|
| 248 |
+
print(f"β
{save_path} saved")
|
| 249 |
+
print(f" Untrained avg: +{avg_r:.1f} pts")
|
| 250 |
+
print(f" Trained avg: +{avg_s:.1f} pts")
|
| 251 |
+
print(f" Gain: {gain_str}")
|
| 252 |
+
if outlier_i:
|
| 253 |
+
print(f" Outliers (β
): scenarios {[eps[i] for i in outlier_i]}")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# ββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββ
|
| 257 |
+
# MAIN
|
| 258 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
+
|
| 260 |
+
if __name__ == "__main__":
|
| 261 |
+
print("π§ Generating clean plots...\n")
|
| 262 |
+
|
| 263 |
+
# Load training logs saved by train_agent.py
|
| 264 |
+
log_path = os.path.join(OUTPUT_DIR, "training_logs.json")
|
| 265 |
+
if os.path.exists(log_path):
|
| 266 |
+
with open(log_path) as f:
|
| 267 |
+
logs = json.load(f)
|
| 268 |
+
print(f" Loaded {len(logs)} log entries from {log_path}")
|
| 269 |
+
plot_loss_curve(logs, "loss_curve.png")
|
| 270 |
+
else:
|
| 271 |
+
print(f"β οΈ {log_path} not found.")
|
| 272 |
+
print(" Add this after trainer.train() in train_agent.py:")
|
| 273 |
+
print(" import json")
|
| 274 |
+
print(f" with open('{OUTPUT_DIR}/training_logs.json','w') as f:")
|
| 275 |
+
print(" json.dump(trainer.state.log_history, f)")
|
| 276 |
+
print()
|
| 277 |
+
|
| 278 |
+
plot_reward_curve("reward_curve.png")
|
| 279 |
+
print("\nβ
Done! Push both files to GitHub.")
|