Spaces:
Paused

File size: 8,725 Bytes
da7445d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""
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()