import gymnasium as gym
import optuna
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.vec_env import DummyVecEnv
from huggingface_sb3 import load_from_hub, package_to_hub
from huggingface_hub import notebook_login
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
--- Monkey patch for Hugging Face + SB3 compatibility ---
from stable_baselines3.common.vec_env import VecVideoRecorder
def _patched_getattr(self, name):
if name == "video_recorder": # Hugging Face expects this
return self
if name == "path": # sometimes it asks for .path
return getattr(self, "video_path", None)
raise AttributeError(name)
VecVideoRecorder.getattr = _patched_getattr
print("✅ Patched VecVideoRecorder to provide .video_recorder and .path")
!pip install "gymnasium[box2d]"
Create a multivector environment
env = make_vec_env('LunarLander-v3', n_envs=16)
Training the PPO Model with 1m steps using the environment defined above
"""## Train a simple paramaterized model and save to disk"""
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy
study = optuna.create_study(direction="maximize", study_name="ppo_ll_v3_tuning")
study.optimize(objective, n_trials=N_TRIALS, show_progress_bar=True)
print("Best value (mean reward):", study.best_value)
print("Best params:", study.best_params)
--- Final training with best params (scale up steps/envs if you want) ---
best = study.best_params
def make_training_env():
return Monitor(gym.make(ENV_ID))
final_env = DummyVecEnv([make_training_env for _ in range(16)]) # more envs for final run
PLACE the package_to_hub function you've just filled here
package_to_hub(model=model, # Our trained model
model_name=modelname, # The name of our trained model
model_architecture=model_architecture, # The model architecture we used: in our case PPO
env_id=env_id, # Name of the environment
eval_env=eval_env, # Evaluation Environment
repo_id=repo_id, # id of the model repository from the Hugging Face Hub (repo_id = {organization}/{repo_name} for instance ThomasSimonini/ppo-LunarLander-v2
commit_message=commit_message, token=token)
"""Congrats 🥳 you've just trained and uploaded your first Deep Reinforcement Learning agent. The script above should have displayed a link to a model repository such as https://huggingface.co/osanseviero/test_sb3. When you go to this link, you can:
See a video preview of your agent at the right.
Click "Files and versions" to see all the files in the repository.
Click "Use in stable-baselines3" to get a code snippet that shows how to load the model.
A model card (README.md file) which gives a description of the model
Under the hood, the Hub uses git-based repositories (don't worry if you don't know what git is), which means you can update the model with new versions as you experiment and improve your agent.
The filename: the saved model inside the repo and its extension (*.zip)
Because the model I download from the Hub was trained with Gym (the former version of Gymnasium) we need to install shimmy a API conversion tool that will help us to run the environment correctly.
from huggingface_sb3 import load_from_hub
repo_id = "Classroom-workshop/assignment2-omar" # The repo_id
filename = "ppo-LunarLander-v2.zip" # The model filename.zip
When the model was trained on Python 3.8 the pickle protocol is 5
But Python 3.6, 3.7 use protocol 4
In order to get compatibility we need to:
1. Install pickle5 (we done it at the beginning of the colab)
2. Create a custom empty object we pass as parameter to PPO.load()