Add runnable PPO training example
Browse files- examples/ppo.py +102 -0
examples/ppo.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train and evaluate a single-encounter RGB PPO baseline."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from contextlib import closing
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from statistics import mean
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
import gymnasium as gym
|
| 10 |
+
import numpy as np
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from stable_baselines3 import PPO
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "environments/games/prototype"))
|
| 15 |
+
import bossbench
|
| 16 |
+
from bossbench.scope import BENCH_CASES
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FixedTier(gym.Wrapper):
|
| 20 |
+
"""Apply the requested difficulty to every episode reset."""
|
| 21 |
+
|
| 22 |
+
def __init__(self, env, tier):
|
| 23 |
+
super().__init__(env)
|
| 24 |
+
self.tier = tier
|
| 25 |
+
|
| 26 |
+
def reset(self, *, seed=None, options=None):
|
| 27 |
+
options = dict(options or {})
|
| 28 |
+
if "tier" not in options and "difficulty" not in options:
|
| 29 |
+
options["tier"] = self.tier
|
| 30 |
+
return super().reset(seed=seed, options=options)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def make_env(case, tier):
|
| 34 |
+
env = bossbench.make_training_env(case, action_format="compact", time_mode="paused")
|
| 35 |
+
width, height = 160, 96
|
| 36 |
+
|
| 37 |
+
def resize(frame):
|
| 38 |
+
return np.array(Image.fromarray(frame).resize((width, height), Image.Resampling.BILINEAR))
|
| 39 |
+
|
| 40 |
+
space = gym.spaces.Box(0, 255, shape=(height, width, 3), dtype=np.uint8)
|
| 41 |
+
return gym.wrappers.TransformObservation(FixedTier(env, tier), resize, space)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def evaluate(model, env, episodes, seed):
|
| 45 |
+
results = []
|
| 46 |
+
for episode_seed in range(seed, seed + episodes):
|
| 47 |
+
obs, _ = env.reset(seed=episode_seed)
|
| 48 |
+
while True:
|
| 49 |
+
action, _ = model.predict(obs, deterministic=True)
|
| 50 |
+
obs, _, terminated, truncated, _ = env.step(action)
|
| 51 |
+
if terminated or truncated:
|
| 52 |
+
break
|
| 53 |
+
result = env.unwrapped.verifier()
|
| 54 |
+
results.append({
|
| 55 |
+
"seed": episode_seed,
|
| 56 |
+
"win": result["win"],
|
| 57 |
+
"progress": result["boss_damage"],
|
| 58 |
+
"outcome": result["outcome"],
|
| 59 |
+
})
|
| 60 |
+
return {"win_rate": mean(r["win"] for r in results),
|
| 61 |
+
"mean_progress": mean(r["progress"] for r in results), "episodes": results}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def main():
|
| 65 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 66 |
+
parser.add_argument("--case", choices=sorted(BENCH_CASES), default="doom/cyberdemon")
|
| 67 |
+
parser.add_argument("--tier", choices=("easy", "normal", "hard"), default="easy")
|
| 68 |
+
parser.add_argument("--device", default="auto")
|
| 69 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 70 |
+
train = commands.add_parser("train")
|
| 71 |
+
train.add_argument("--steps", type=int, default=10_000)
|
| 72 |
+
train.add_argument("--rollout-steps", type=int, default=128)
|
| 73 |
+
train.add_argument("--seed", type=int, default=1)
|
| 74 |
+
train.add_argument("--output", type=Path, default=Path("runs/ppo.zip"))
|
| 75 |
+
test = commands.add_parser("eval")
|
| 76 |
+
test.add_argument("--checkpoint", type=Path, required=True)
|
| 77 |
+
test.add_argument("--episodes", type=int, default=3)
|
| 78 |
+
test.add_argument("--seed", type=int, default=1001)
|
| 79 |
+
args = parser.parse_args()
|
| 80 |
+
if args.seed < 0:
|
| 81 |
+
parser.error("--seed must be nonnegative")
|
| 82 |
+
if args.command == "train" and (args.steps < 2 or args.rollout_steps < 2):
|
| 83 |
+
parser.error("--steps and --rollout-steps must be at least 2")
|
| 84 |
+
if args.command == "eval" and args.episodes < 1:
|
| 85 |
+
parser.error("--episodes must be at least 1")
|
| 86 |
+
|
| 87 |
+
with closing(make_env(args.case, args.tier)) as env:
|
| 88 |
+
if args.command == "train":
|
| 89 |
+
batch = min(args.rollout_steps, 64)
|
| 90 |
+
model = PPO("CnnPolicy", env, n_steps=args.rollout_steps, batch_size=batch,
|
| 91 |
+
seed=args.seed, device=args.device, verbose=1)
|
| 92 |
+
model.learn(total_timesteps=args.steps)
|
| 93 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
model.save(args.output)
|
| 95 |
+
else:
|
| 96 |
+
model = PPO.load(args.checkpoint, env=env, device=args.device)
|
| 97 |
+
results = evaluate(model, env, args.episodes, args.seed)
|
| 98 |
+
print(json.dumps({"case": args.case, "tier": args.tier, **results}, indent=2))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
main()
|