diff --git a/README.md b/README.md index d1802c0aabb16ab46cefe510c277332308d4f93d..329e861dfc819107785af595e2a972a79fa051b6 100644 --- a/README.md +++ b/README.md @@ -4,103 +4,11 @@ MSO 3.4 Apprentissage Automatique # -In this hands-on project, we will first implement a simple RL algorithm and apply it to solve the CartPole-v1 environment. Once we become familiar with the basic workflow, we will learn to use various tools for machine learning model training, monitoring, and sharing, by applying these tools to train a robotic arm. - -## To be handed in - -This work must be done individually. The expected output is a repository named `hands-on-rl` on https://gitlab.ec-lyon.fr. - -We assume that `git` is installed, and that you are familiar with the basic `git` commands. (Optionnaly, you can use GitHub Desktop.) -We also assume that you have access to the [ECL GitLab](https://gitlab.ec-lyon.fr/). If necessary, please consult [this tutorial](https://gitlab.ec-lyon.fr/edelland/inf_tc2/-/blob/main/Tutoriel_gitlab/tutoriel_gitlab.md). - -Your repository must contain a `README.md` file that explains **briefly** the successive steps of the project. It must be private, so you need to add your teacher as "developer" member. - -Throughout the subject, you will find a 🛠 symbol indicating that a specific production is expected. - -The last commit is due before 11:59 pm on March 17, 2025. Subsequent commits will not be considered. - -> ⚠️ **Warning** -> Ensure that you only commit the files that are requested. For example, your directory should not contain the generated `.zip` files, nor the `runs` folder... At the end, your repository must contain one `README.md`, three python scripts, and optionally image files for the plots. - -## Before you start - -Make sure you know the basics of Reinforcement Learning. In case of need, you can refer to the [introduction of the Hugging Face RL course](https://huggingface.co/blog/deep-rl-intro). - -## Introduction to Gym - -[Gym](https://gymnasium.farama.org/) is a framework for developing and evaluating reinforcement learning environments. It offers various environments, including classic control and toy text scenarios, to test RL algorithms. - -### Installation - -We recommend to use Python virtual environnements to install the required modules : https://docs.python.org/3/library/venv.html or https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html if you are using conda. - -First, install Pytorch : https://pytorch.org/get-started/locally. - -Then install the following modules : - - -```sh -pip install gymnasium -``` - -```sh -pip install "gymnasium[classic-control]" -``` - - -### Usage - -Here is an example of how to use Gym to solve the `CartPole-v1` environment [Documentation](https://gymnasium.farama.org/environments/classic_control/cart_pole/): - -```python -import gymnasium as gym - -# Create the environment -env = gym.make("CartPole-v1", render_mode="human") - -# Reset the environment and get the initial observation -observation = env.reset() - -for _ in range(100): - # Select a random action from the action space - action = env.action_space.sample() - # Apply the action to the environment - # Returns next observation, reward, done signal (indicating - # if the episode has ended), and an additional info dictionary - observation, reward, terminated, truncated, info = env.step(action) - # Render the environment to visualize the agent's behavior - env.render() - if terminated: - # Terminated before max step - break - -env.close() -``` ## REINFORCE The REINFORCE algorithm (also known as Vanilla Policy Gradient) is a policy gradient method that optimizes the policy directly using gradient descent. The following is the pseudocode of the REINFORCE algorithm: -```txt -Setup the CartPole environment -Setup the agent as a simple neural network with: - - One fully connected layer with 128 units and ReLU activation followed by a dropout layer - - One fully connected layer followed by softmax activation -Repeat 500 times: - Reset the environment - Reset the buffer - Repeat until the end of the episode: - Compute action probabilities - Sample the action based on the probabilities and store its probability in the buffer - Step the environment with the action - Compute and store in the buffer the return using gamma=0.99 - Normalize the return - Compute the policy loss as -sum(log(prob) * return) - Update the policy using an Adam optimizer and a learning rate of 5e-3 -Save the model weights -``` - -To learn more about REINFORCE, you can refer to [this unit](https://huggingface.co/learn/deep-rl-course/unit4/policy-gradient). > 🛠 **To be handed in** > Use PyTorch to implement REINFORCE and solve the CartPole environement. Share the code in `reinforce_cartpole.py`, and share a plot showing the total reward accross episodes in the `README.md`. Also, share a file `reinforce_cartpole.pth` containing the learned weights. For saving and loading PyTorch models, check [this tutorial](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference) @@ -112,70 +20,21 @@ Now that you have trained your model, it is time to evaluate its performance. Ru > 🛠 **To be handed in** > Implement a script which loads your saved model and use it to solve the cartpole enviroment. Run 100 evaluations and share the final success rate across all evaluations in the `README.md`. Share the code in `evaluate_reinforce_cartpole.py`. +From the openai gym wiki we know that the environment counts as solved when the average reward is greater or equal to 195 for over 100 consecutuve trials. +From the evaluation script i used the success rate is 1.0 when we allow the maximum number of steps the environment offers. ## Familiarization with a complete RL pipeline: Application to training a robotic arm -In this section, you will use the Stable-Baselines3 package to train a robotic arm using RL. You'll get familiar with several widely-used tools for training, monitoring and sharing machine learning models. - -### Get familiar with Stable-Baselines3 - Stable-Baselines3 (SB3) is a high-level RL library that provides various algorithms and integrated tools to easily train and test reinforcement learning models. -#### Installation - -```sh -pip install stable-baselines3 -pip install "stable-baselines3[extra]" -pip install moviepy -``` - -#### Usage - -Use the [Stable-Baselines3 documentation](https://stable-baselines3.readthedocs.io/en/master/) to implement the code to solve the CartPole environment with the Advantage Actor-Critic (A2C) algorithm. - - > 🛠 **To be handed in** > Store the code in `a2c_sb3_cartpole.py`. Unless otherwise stated, you'll work upon this file for the next sections. -### Get familiar with Hugging Face Hub - -Hugging Face Hub is a platform for easy sharing and versioning of trained machine learning models. With Hugging Face Hub, you can quickly and easily share your models with others and make them usable through the API. For example, see the trained A2C agent for CartPole: https://huggingface.co/sb3/a2c-CartPole-v1. Hugging Face Hub provides an API to download and upload SB3 models. - -#### Installation of `huggingface_sb3` - -```sh -pip install huggingface-sb3 -``` - -#### Upload the model on the Hub - -Follow the [Hugging Face Hub documentation](https://huggingface.co/docs/hub/stable-baselines3) to upload the previously learned model to the Hub. - > 🛠 **To be handed in** > Link the trained model in the `README.md` file. -> 📝 **Note** -> [RL-Zoo3](https://stable-baselines3.readthedocs.io/en/master/guide/rl_zoo.html) provides more advanced features to save hyperparameters, generate renderings and metrics. Feel free to try them. - -### Get familiar with Weights & Biases - -Weights & Biases (W&B) is a tool for machine learning experiment management. With W&B, you can track and compare your experiments, visualize your model training and performance. - -#### Installation - -You'll need to install `wand`. - -```shell -pip install wandb -``` - -Use the documentation of [Stable-Baselines3](https://stable-baselines3.readthedocs.io/en/master/) and [Weights & Biases](https://docs.wandb.ai/guides/integrations/stable-baselines-3) to track the CartPole training. Make the run public. - 🛠 Share the link of the wandb run in the `README.md` file. -> ⚠️ **Warning** -> Make sure to make the run public! If it is not possible (due to the restrictions on your account), you can create a WandB [report](https://docs.wandb.ai/guides/reports/create-a-report/), add all relevant graphs and any textual descriptions or explanations you find pertinent, then download a PDF file (landscape format) and upload it along with the code to GitLab. Make sure to arrange the plots in a way that makes them understandable in the PDF (e.g., one graph per row, correct axes, etc.). Specify which report corresponds to which experiment. - wandb: https://wandb.ai/lennartecl-centrale-lyon/sb3?nw=nwuserlennartecl hugging: https://huggingface.co/lennartoe/Cartpole-v1/tree/main @@ -183,32 +42,9 @@ hugging: https://huggingface.co/lennartoe/Cartpole-v1/tree/main [Panda-gym](https://github.com/qgallouedec/panda-gym) is a collection of environments for robotic simulation and control. It provides a range of challenges for training robotic agents in a simulated environment. In this section, you will get familiar with one of the environments provided by panda-gym, the `PandaReachJointsDense-v3`. The objective is to learn how to reach any point in 3D space by directly controlling the robot's articulations. -#### Installation - -```shell -pip install panda-gym==3.0.7 -``` - -#### Train, track, and share - -Use the Stable-Baselines3 package to train A2C model on the `PandaReachJointsDense-v3` environment. 500k timesteps should be enough. Track the environment with Weights & Biases. Once the training is over, upload the trained model on the Hub. - > 🛠 **To be handed in** > Share all the code in `a2c_sb3_panda_reach.py`. Share the link of the wandb run and the trained model in the `README.md` file. wandb: https://wandb.ai/lennartecl-centrale-lyon/pandasgym_sb3?nw=nwuserlennartecl hugging: https://huggingface.co/lennartoe/PandaReachJointsDense-v3/tree/main -## Contribute - -This tutorial may contain errors, inaccuracies, typos or areas for improvement. Feel free to contribute to its improvement by opening an issue. - -## Author - -Quentin Gallouédec - -Updates by Bruno Machado, Léo Schneider, Emmanuel Dellandréa - -## License - -MIT diff --git a/a2c_sb3_cartpole.py b/a2c_sb3_cartpole.py index ee1087d0bd9f61ca3a469f271ca00453a3f42ad0..f32222078c69166ff8434803641a1bd7b5dff925 100644 --- a/a2c_sb3_cartpole.py +++ b/a2c_sb3_cartpole.py @@ -32,9 +32,6 @@ for i in range(1000): action, _state = model.predict(obs, deterministic=True) obs, reward, done, info = vec_env.step(action) vec_env.render("human") - # VecEnv resets automatically - # if done: - # obs = vec_env.reset() run.finish() diff --git a/a2c_sb3_panda_reach.py b/a2c_sb3_panda_reach.py new file mode 100644 index 0000000000000000000000000000000000000000..b33f309674b3876692c93361f51a5bfe4d5e9db8 --- /dev/null +++ b/a2c_sb3_panda_reach.py @@ -0,0 +1,48 @@ +import panda_gym +import gymnasium as gym + +from stable_baselines3 import A2C +import wandb +from wandb.integration.sb3 import WandbCallback +from huggingface_sb3 import package_to_hub + + +# from documentation of wandb +config = { + "policy_type": "MultiInputPolicy", + "total_timesteps": 50000, + "env_name": "PandaReachJointsDense-v3", +} +run = wandb.init( + project="pandasgym_sb3", + config=config, + sync_tensorboard=True, + monitor_gym=True, + save_code=True, +) + +env = gym.make("PandaReachJointsDense-v3", render_mode="rgb_array") + +model = A2C("MultiInputPolicy", env, verbose=1, tensorboard_log=f"runs/{run.id}") +#model = A2C("MlpPolicy", env, ) +model.learn(total_timesteps=500_000, callback=WandbCallback(gradient_save_freq=100,model_save_path=f"models/{run.id}",verbose=2,),) +#model.learn(total_timesteps=10_000) +vec_env = model.get_env() +obs = vec_env.reset() +for i in range(1000): + action, _state = model.predict(obs, deterministic=True) + obs, reward, done, info = vec_env.step(action) + vec_env.render("human") + # VecEnv resets automatically + # if done: + # obs = vec_env.reset() + +run.finish() + +package_to_hub(model=model, + model_name="PandaReachJointsDense-v3", + model_architecture="A2C", + env_id="PandaReachJointsDense-v3", + eval_env=env, + repo_id="lennartoe/PandaReachJointsDense-v3", + commit_message="First commit") \ No newline at end of file diff --git a/evaluate_reinforce_cartpole.py b/evaluate_reinforce_cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..1021baf702d003289c61a334d91e7d3d87d02e2a --- /dev/null +++ b/evaluate_reinforce_cartpole.py @@ -0,0 +1,41 @@ +import gymnasium as gym +import torch +from reinforce_cartpole import Policy + +def eval_policy(eval_length, policy, env): + # Reset the environment and get the initial observation + observation = env.reset()[0] + rewards = [] + + for step in range(eval_length): + # sample action from policy + action_probs = policy(torch.from_numpy(observation).float()) + action = torch.distributions.Categorical(action_probs).sample() + observation, reward, terminated, truncated, info = env.step(action.numpy()) + rewards.append(reward) + # visualize agent behavio + #env.render() + if terminated or truncated: + break + return sum(rewards) +# Create the environment +env = gym.make("CartPole-v1") + +policy = Policy() +# load learned policy +policy.load_state_dict(torch.load('reinforce_cartpole.pth', weights_only=True)) +policy.eval() + +eval_length = env.spec.max_episode_steps +num_evals = 100 +number_of_solves = 0 +for eval in range(num_evals): + sum_reward = eval_policy(eval_length, policy, env) + print(f"Average reward: {sum_reward}") + if sum_reward >= 195: + number_of_solves += 1 + +success_rate = number_of_solves / num_evals +print(f"Success rate: {success_rate}") + +env.close() diff --git a/evaluate_reinforce_cartpole.py.py b/evaluate_reinforce_cartpole.py.py deleted file mode 100644 index 01479f7b7a18bf02be0ba4a09f0d5bb078e093fc..0000000000000000000000000000000000000000 --- a/evaluate_reinforce_cartpole.py.py +++ /dev/null @@ -1,32 +0,0 @@ -import gymnasium as gym -import torch -from reinforce_cartpole import Policy -# Create the environment -env = gym.make("CartPole-v1", render_mode="human") - -# Reset the environment and get the initial observation -observation = env.reset()[0] - -policy = Policy() -# load learned policy -policy.load_state_dict(torch.load('policy.pth', weights_only=True)) -policy.eval() - -for _ in range(200): - # sample action from policy - print(observation) - print(torch.from_numpy(observation).float()) - action_probs = policy(torch.from_numpy(observation).float()) - action = torch.distributions.Categorical(action_probs).sample() - # Apply the action to the environment - # Returns next observation, reward, done signal (indicating - # if the episode has ended), and an additional info dictionary - observation, reward, terminated, truncated, info = env.step(action.numpy()) - # Render the environment to visualize the agent's behavior - env.render() - print(terminated or truncated) - if terminated or truncated: - # Terminated before max step - break - -env.close() diff --git a/policy.pth b/policy.pth deleted file mode 100644 index 970f5c065a6275f6d9a5038936d3e7bff9adc6ac..0000000000000000000000000000000000000000 Binary files a/policy.pth and /dev/null differ diff --git a/reinforce_cartpole.pth b/reinforce_cartpole.pth new file mode 100644 index 0000000000000000000000000000000000000000..8f0468d676b0a0ab9441b9269ec62d27ca79ea83 Binary files /dev/null and b/reinforce_cartpole.pth differ diff --git a/reinforce_cartpole.py b/reinforce_cartpole.py index 50be37c67a30fb2a5c723903fc7cf67482403427..dc01fd7bc5aad5c71bf1a8115c311dc94b5095e5 100644 --- a/reinforce_cartpole.py +++ b/reinforce_cartpole.py @@ -1,13 +1,16 @@ import gymnasium as gym import torch import numpy as np +import matplotlib.pyplot as plt + +DROPOUT_RATE = 0.5 class Policy(torch.nn.Module): def __init__(self, input_size=4, output_size=2): super(Policy, self).__init__() self.fc1 = torch.nn.Linear(input_size, 128) self.relu = torch.nn.ReLU() - self.dropout = torch.nn.Dropout(0.2) + self.dropout = torch.nn.Dropout(DROPOUT_RATE) self.fc2 = torch.nn.Linear(128, output_size) self.softmax = torch.nn.Softmax(dim=0) @@ -38,60 +41,39 @@ def main(): max_steps = env.spec.max_episode_steps - for _ in range(epochs): - print(_) - # Reset the environment + + for ep in range(epochs): + print(ep) observation = env.reset()[0] - # Reset buffer # rewards = torch.zeros(max_steps) # log_probs = torch.zeros(max_steps) - rewards = [] - log_probs = [] + rewards = torch.zeros(max_steps) + log_probs = torch.zeros(max_steps) for step in range(max_steps): - # Select a random action from the action space - #print(observation) + action_probs = policy(torch.from_numpy(observation).float()) - # Sample an action from the action probabilities action = torch.distributions.Categorical(action_probs).sample() - #print("Action") - #print(action) - # Apply the action to the environment observation, reward, terminated, truncated, info = env.step(action.numpy()) - #print(observation) - # env.render() - # does this come before adding to the rewards or after - - # rewards[step] = reward - # log_probs[step] = torch.log(action_probs[action]) - rewards.append(torch.tensor(reward)) - log_probs.append(torch.log(action_probs[action])) + rewards[step] = reward + log_probs[step] = torch.log(action_probs[action]) if terminated or truncated: break - - # apply gamma - # transform rewards and log_probs into tensors - rewards = torch.stack(rewards) - log_probs = torch.stack(log_probs) - rewards_length = len(rewards) - rewards_tensor = torch.zeros(rewards_length, rewards_length) - for i in range(rewards_length): - for j in range(rewards_length-i): - rewards_tensor[i,j] = rewards[i+j] - #print(rewards_tensor) - for i in range(rewards_length): - for j in range(rewards_length): - rewards_tensor[i,j] = rewards_tensor[i,j] * np.pow(gamma,j) - #print(rewards_tensor) - normalized_rewards = torch.sum(rewards_tensor, dim=1) - #print(normalized_rewards) - normalized_rewards = normalized_rewards- torch.mean(normalized_rewards) - normalized_rewards /= torch.std(normalized_rewards) - - loss = -torch.sum(log_probs * normalized_rewards) - total_reward.append(sum(rewards)) + # calculate discounted rewards in reverse + R = 0 + returns = [] + for r in reversed(rewards[:step+1]): + R = r + gamma * R + returns.insert(0, R) + returns_tensor = torch.tensor(returns) + eps = 1e-10 + # normalize the returns + normalized_rewards = (returns_tensor - returns_tensor.mean()) / (returns_tensor.std() + eps) + log_probs_truncated = log_probs[:step+1] + loss = torch.sum(-log_probs_truncated * normalized_rewards) + total_reward.append(sum(rewards[:step+1])) # optimize optimizer.zero_grad() loss.backward() @@ -101,19 +83,18 @@ def main(): #env.render() # save the model weights - torch.save(policy.state_dict(), "policy.pth") - + torch.save(policy.state_dict(), "reinforce_cartpole.pth") - print(total_reward) - print(total_loss) env.close() # plot the rewards and the loss side by side - import matplotlib.pyplot as plt fig, ax = plt.subplots(1,2) ax[0].plot(total_reward) ax[1].plot(total_loss) - plt.show() + ax[0].set_title("Rewards") + ax[1].set_title("Loss") + plt.savefig(f"reinforce_cartpole_dr_{DROPOUT_RATE}.png") +