Spaces:
Paused

dqa-openenv / train /train_ppo.py
neelshingavi's picture
fix: switch create_app to create_fastapi_app β€” remove Gradio root mount causing 404
da7445d
Raw History Blame Contribute Delete
8.73 kB
"""
PPO training script for DQA-OpenEnv.
Trains a separate PPO agent on each of the 3 core tasks (easy, medium, hard)
using stable-baselines3 MLP policy. Runs entirely in-process on CPU β€”
no server required. Generates results/learning_curves.png on completion.
Usage:
uv run python3 train/train_ppo.py
Expected runtime: ~15-20 min per task on CPU, ~50-60 min total.
"""
import os
import sys
import numpy as np
import matplotlib
matplotlib.use("Agg") # non-interactive backend β€” no display required
import matplotlib.pyplot as plt
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.callbacks import BaseCallback
from train.dqa_gym_env import DQAGymEnv
# ── Config ────────────────────────────────────────────────────────────────────
TASKS_TO_TRAIN = ["easy", "medium", "hard"]
TOTAL_TIMESTEPS = 30_000 # per task β€” ~15 min CPU
EVAL_EPISODES = 20 # episodes for post-training policy analysis
RESULTS_DIR = "results"
MODELS_DIR = "models"
CURVE_PATH = os.path.join(RESULTS_DIR, "learning_curves.png")
os.makedirs(RESULTS_DIR, exist_ok=True)
os.makedirs(MODELS_DIR, exist_ok=True)
# ── Reward tracking callback ───────────────────────────────────────────────────
class RewardTracker(BaseCallback):
"""
Records episode rewards during training for plotting.
Stores (timestep, mean_reward_over_last_10_episodes) pairs.
"""
def __init__(self, verbose: int = 0):
super().__init__(verbose)
self.episode_rewards: list = []
self.curve_x: list = [] # timesteps
self.curve_y: list = [] # smoothed reward
def _on_step(self) -> bool:
infos = self.locals.get("infos", [])
for info in infos:
if "episode" in info:
ep_reward = float(info["episode"]["r"])
self.episode_rewards.append(ep_reward)
if len(self.episode_rewards) >= 5:
smoothed = float(np.mean(self.episode_rewards[-10:]))
self.curve_x.append(self.num_timesteps)
self.curve_y.append(smoothed)
return True
# ── Training ───────────────────────────────────────────────────────────────────
def train_task(task_id: str) -> RewardTracker:
"""
Train a PPO agent on one DQA task.
Args:
task_id: One of "easy", "medium", "hard".
Returns:
RewardTracker with training curve data.
"""
print(f"\n{'='*60}")
print(f" Training PPO on task: {task_id.upper()}")
print(f" Timesteps: {TOTAL_TIMESTEPS:,} | Policy: MlpPolicy | Device: CPU")
print(f"{'='*60}")
task_results_dir = os.path.join(RESULTS_DIR, task_id)
os.makedirs(task_results_dir, exist_ok=True)
env = DQAGymEnv(task_id=task_id)
env = Monitor(env, filename=os.path.join(task_results_dir, "monitor"))
tracker = RewardTracker()
model = PPO(
policy = "MlpPolicy",
env = env,
verbose = 1,
n_steps = 256,
batch_size = 32,
n_epochs = 5,
learning_rate = 3e-4,
ent_coef = 0.01,
device = "cpu",
)
model.learn(total_timesteps=TOTAL_TIMESTEPS, callback=tracker)
model.save(os.path.join(MODELS_DIR, f"ppo_{task_id}"))
env.close()
print(f"\n Saved model β†’ models/ppo_{task_id}.zip")
print(f" Saved monitor β†’ results/{task_id}/monitor.monitor.csv")
if tracker.curve_y:
first = tracker.curve_y[0]
last = tracker.curve_y[-1]
change = last - first
trend = "↑ improving" if change > 0.02 else ("↓ declining" if change < -0.02 else "β†’ stable")
print(f" Reward trend: {first:.4f} β†’ {last:.4f} {trend}")
return tracker
# ── Plot ───────────────────────────────────────────────────────────────────────
def plot_learning_curves(trackers: dict) -> None:
"""
Generates and saves a 3-panel learning curve figure.
Args:
trackers: Dict mapping task_id β†’ RewardTracker.
"""
fig, axes = plt.subplots(1, 3, figsize=(15, 4), facecolor="#0f1117")
fig.suptitle(
"DQA-OpenEnv: PPO Agent Learning Curves",
fontsize=14, fontweight="bold", color="white", y=1.02
)
PRIMARY_COLOR = "#2563EB"
BAND_COLOR = "#2563EB"
TASK_LABELS = {"easy": "Easy (Customer Surveys)", "medium": "Medium (HR Records)", "hard": "Hard (Financial Transactions)"}
for ax, task_id in zip(axes, TASKS_TO_TRAIN):
tracker = trackers[task_id]
ax.set_facecolor("#1a1d27")
if len(tracker.curve_x) >= 3:
x = np.array(tracker.curve_x)
y = np.array(tracker.curve_y)
# Wider smoothing for cleaner curve on noisy RL data
window = max(3, len(y) // 8)
if len(y) >= window:
kernel = np.ones(window) / window
y_smooth = np.convolve(y, kernel, mode="valid")
x_smooth = x[window - 1:]
else:
y_smooth, x_smooth = y, x
# Confidence band: rolling std of raw rewards
y_std = np.array([
np.std(tracker.curve_y[max(0, i - 10): i + 1])
for i in range(len(tracker.curve_y))
])
if len(y_std) >= window:
y_std_smooth = np.convolve(y_std, kernel, mode="valid")
else:
y_std_smooth = y_std[: len(x_smooth)]
ax.plot(x_smooth, y_smooth, color=PRIMARY_COLOR, linewidth=2, label="Mean reward (smoothed)")
ax.fill_between(
x_smooth,
y_smooth - y_std_smooth,
y_smooth + y_std_smooth,
alpha=0.25, color=BAND_COLOR, label="Β±1 std"
)
ax.axhline(y=0, color="#555", linewidth=0.8, linestyle="--")
else:
ax.text(
0.5, 0.5, "Insufficient data",
transform=ax.transAxes, ha="center", va="center",
color="white", fontsize=11
)
ax.set_title(TASK_LABELS.get(task_id, task_id), color="white", fontsize=10, pad=8)
ax.set_xlabel("Timesteps", color="#aaa", fontsize=9)
ax.set_ylabel("Episode Reward", color="#aaa", fontsize=9)
ax.tick_params(colors="#aaa", labelsize=8)
for spine in ax.spines.values():
spine.set_edgecolor("#333")
ax.legend(fontsize=7, labelcolor="white",
facecolor="#1a1d27", edgecolor="#333")
plt.tight_layout()
plt.savefig(CURVE_PATH, dpi=150, bbox_inches="tight",
facecolor="#0f1117", edgecolor="none")
plt.close()
print(f"\n Learning curves saved β†’ {CURVE_PATH}")
# ── Main ───────────────────────────────────────────────────────────────────────
def main() -> None:
print("\nDQA-OpenEnv PPO Training")
print(f"Tasks: {TASKS_TO_TRAIN}")
print(f"Timesteps per task: {TOTAL_TIMESTEPS:,}")
print(f"Total estimated time: ~50-60 min on CPU\n")
trackers: dict = {}
for task_id in TASKS_TO_TRAIN:
trackers[task_id] = train_task(task_id)
print(f"\n{'='*60}")
print(" All tasks trained. Generating learning curves...")
print(f"{'='*60}")
plot_learning_curves(trackers)
print("\n── TRAINING SUMMARY ──────────────────────────────────────")
for task_id in TASKS_TO_TRAIN:
t = trackers[task_id]
if t.curve_y:
print(f" {task_id:8s} episodes={len(t.episode_rewards):4d} "
f"first_reward={t.curve_y[0]:+.4f} "
f"final_reward={t.curve_y[-1]:+.4f}")
else:
print(f" {task_id:8s} no reward data recorded")
print("\nTraining complete. See results/learning_curves.png")
if __name__ == "__main__":
main()