bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
PPO on LunarLander

This example trains an agent to land the lander of LunarLander from Gymnasium with proximal policy optimization (PPO). It uses the continuous version of the environment, LunarLanderContinuous in its v3 form: the agent sets the throttle of the main engine and of the side engines, two numbers between -1 and 1, instead of picking one of four discrete actions. The observation has 8 numbers: the position, velocity, angle and angular velocity of the lander, and whether each of its legs touches the ground.

The environment runs on the bitrl-rest-api server, which the example talks to over HTTP at http://0.0.0.0:8001/api, so start the server first.

PPO

PPO is an actor-critic method, like A2C in An A2C Solver for CartPole. The actor is the policy, and the critic estimates the value of a state, which gives the advantage of an action: how much better its return was than the critic expected. A plain policy gradient step can change the policy so much that it gets worse and does not recover. PPO limits the step. With the ratio \(\rho = \pi_{\theta}(\alpha | s) / \pi_{\theta_{old}}(\alpha | s)\) of the new and the old probability of an action and its advantage \(A\), it maximises

\[\min\left( \rho A, \; \mathrm{clip}(\rho, 1 - \epsilon, 1 + \epsilon) A \right) , \]

so moving \(\rho\) further than \(\epsilon\) from 1 brings no more gain. Because of that it can make several passes over the same batch of experience.

The networks

The actor, ActorNet, has two hidden layers of 128 and 64 units with \(\tanh\), and gives the mean of a normal distribution for each of the two actions. The log of its standard deviation is a learned parameter of its own, the same in every state, that starts at -0.5, a standard deviation of 0.6, and stays between -5 and 0.5. The actor samples an action from that distribution and squashes it into \([-1, 1]\) with \(\tanh\); the log probability of the action is corrected for the squashing. A standard deviation that the network can raise in every state, as an earlier version of this example had, grows until \(\tanh\) squashes almost every action to -1 or 1, and the lander only learns to fire its engines at full throttle. The critic, CriticNet, has hidden layers of 128 and 256 units and one output, the value of the state.

PPOSolver trains both with Adam and a learning rate of \(3 \cdot 10^{-4}\), on the CPU, with \(\gamma = 0.99\), a clip \(\epsilon\) of 0.2, 4 passes over each episode and normalised advantages. The example trains for 2000 episodes of at most 1000 steps, the limit of Gymnasium's LunarLander; every episode starts from the next seed, so from a different terrain and push.

The learned policy

One of the greedy landings: on its legs at the edge of the pad, a return of 190.

The mean return of the training episodes, 200 at a time, went -232, -62, 1, 82, 119, 128, 85, 131, 138, 136. The training took about 22 minutes, almost all of it in the HTTP requests to the server. After training the example lands 10 times with the greedy policy, \(\tanh\) of the mean, each from the next seed, prints the returns, and writes the actions of every landing to episode_<k>.csv, at full precision: a landing is chaotic, and a replay from rounded actions drifts away from it.

Landing 0 1 2 3 4 5 6 7 8 9
Return 190 162 156 191 233 176 218 -45 185 147

Nine of the ten land, and one crashes; the mean return is 161. LunarLander counts as solved at a mean of 200, so the policy lands but not yet precisely, often away from the middle of the pad: more episodes, or updates from batches of several episodes rather than one, would be expected to get it there. The GIF is landing 0:

python examples/tools/episode_gif.py --env LunarLanderContinuous-v3 --actions episode_0.csv --max-steps 1000 --fps 50 --out ppo_lunar_lander.gif

What it writes

After training, the example writes what the solver recorded to four files in experiments/1/, in the directory it runs from. Each has an index and a value per row:

File What
policy_loss.csv the loss of the actor
critic_loss.csv the loss of the critic
rewards.csv the rewards
episode_duration.csv how many steps the episodes lasted

The driver code

#include "bitrl/base/bitrl_config.h"
#ifdef USE_PYTORCH
#include <torch/torch.h>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <unordered_map>
#include <vector>
namespace rl_example_11
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const std::string EXPERIMENT_ID = "1";
const std::string POLICY = "policy.csv";
namespace F = torch::nn::functional;
const uint_t L1 = 8;
const uint_t L2 = 128;
const uint_t L3 = 64;
constexpr real_t LEARNING_RATE = 3.0e-4;
const auto N_EPISODES = 2000;
// create the Action network
class ActorNetImpl : public torch::nn::Module
{
public:
std::pair<torch::Tensor, torch::Tensor> forward(torch_tensor_t state);
template <typename StateTp>
std::tuple<std::vector<real_t>, torch_tensor_t> act(const StateTp &state);
std::tuple<torch_tensor_t, torch_tensor_t, torch_tensor_t> evaluate(torch_tensor_t states,
torch_tensor_t actions);
private:
torch::nn::Linear fc1_;
torch::nn::Linear fc2_;
torch::nn::Linear mean_layer_;
// the log of the standard deviation of every action, learned but the same
// in every state
torch_tensor_t log_std_;
};
: torch::nn::Module(), fc1_(torch::nn::Linear(L1, L2)), fc2_(torch::nn::Linear(L2, L3)),
mean_layer_(torch::nn::Linear(L3, 2))
{
register_module("fc1_", fc1_);
register_module("fc2_", fc2_);
register_module("mean_layer_", mean_layer_);
// start with a standard deviation of exp(-0.5) = 0.6: wide enough to
// explore, narrow enough that tanh does not squash most samples to -1 or 1
log_std_ = register_parameter("log_std_", torch::full({2}, -0.5));
}
template <typename StateTp>
std::tuple<std::vector<real_t>, torch_tensor_t> ActorNetImpl::act(const StateTp &state)
{
auto torch_state = torch::tensor(state, torch::dtype(torch::kFloat32));
auto [mean, log_std] = this->forward(torch_state);
auto std = torch::exp(log_std);
auto dist = TorchNormalDist(mean, std);
// sample an action
auto raw_action = dist.sample();
auto action = torch::tanh(raw_action);
auto log_prob =
-0.5 * (((raw_action - mean) / (std + 1e-8)).pow(2) + 2 * log_std + std::log(2 * M_PI));
log_prob = log_prob.sum(-1); // sum over action dims
auto log_det_jacobian = torch::log(1 - action.pow(2) + 1e-6).sum(-1);
auto corrected_log_prob = log_prob - log_det_jacobian;
auto clamped_action = TorchAdaptor::to_vector<real_t>(action.to(torch::kDouble));
return {clamped_action, corrected_log_prob};
}
std::pair<torch_tensor_t, torch_tensor_t> ActorNetImpl::forward(torch_tensor_t state)
{
state = torch::tanh(fc1_->forward(state));
state = torch::tanh(fc2_->forward(state));
auto mean = mean_layer_->forward(state);
// a standard deviation between exp(-5) and exp(0.5), the same shape as the
// mean so that it works for one state and for a batch
auto log_std = torch::clamp(log_std_, -5.0, 0.5).expand_as(mean);
return {mean, log_std};
}
std::tuple<torch_tensor_t, torch_tensor_t, torch_tensor_t>
ActorNetImpl::evaluate(torch_tensor_t states, torch_tensor_t actions)
{
// forward gives the log of the standard deviation
auto [mean, log_std] = this->forward(states);
auto dist = TorchNormalDist(mean, torch::exp(log_std));
// act squashed the sampled action into [-1, 1] with tanh, and corrected its
// log probability for that; do the same for the stored actions: undo the
// tanh to get the sample, and correct its log probability the same way
const auto squashed = actions.clamp(-1.0 + 1e-6, 1.0 - 1e-6);
const auto raw = torch::atanh(squashed);
auto log_probs = dist.log_prob(raw).sum(-1) - torch::log(1 - squashed.pow(2) + 1e-6).sum(-1);
auto entropy = dist.entropy().sum(-1).mean();
return {log_probs, entropy, mean};
}
class CriticNetImpl : public torch::nn::Module
{
public:
CriticNetImpl();
torch_tensor_t forward(torch_tensor_t state);
template <typename StateTp> torch_tensor_t evaluate(const StateTp &state);
private:
torch::nn::Linear fc1_;
torch::nn::Linear fc2_;
torch::nn::Linear fc3_;
};
CriticNetImpl::CriticNetImpl()
: torch::nn::Module(), fc1_(torch::nn::Linear(L1, L2)), fc2_(torch::nn::Linear(L2, 256)),
fc3_(torch::nn::Linear(256, 1))
{
register_module("fc1_", fc1_);
register_module("fc2_", fc2_);
register_module("fc3_", fc3_);
}
torch_tensor_t CriticNetImpl::forward(torch_tensor_t state)
{
auto output = F::relu(fc1_->forward(state));
output = F::relu(fc2_->forward(output));
output = fc3_->forward(output);
return output;
}
template <typename StateTp> torch_tensor_t CriticNetImpl::evaluate(const StateTp &state)
{
auto torch_state = torch::tensor(state);
return forward(torch_state);
}
TORCH_MODULE(ActorNet);
TORCH_MODULE(CriticNet);
} // namespace rl_example_11
int main()
{
BITRL_LOG_INFO << "Starting agent training";
using namespace rl_example_11;
try
{
// let's create a directory where we want to
// store all the results from running a simualtion
std::filesystem::create_directories("experiments/" + EXPERIMENT_ID);
torch::manual_seed(42);
RESTRLEnvClient server(SERVER_URL, true);
// create the environment
env_type env(server);
BITRL_LOG_INFO << "Creating environment...";
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
env.make("v3", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Done...";
BITRL_LOG_INFO << "Number of actions=" << env.n_actions();
// Gymnasium ends LunarLander after 1000 steps
ppo_config.max_itrs_per_episode = 1000;
ppo_config.clip_epsilon = 0.2;
ppo_config.gamma = 0.99;
ppo_config.n_episodes = N_EPISODES;
ppo_config.device_type = DeviceType::CPU;
ActorNet policy;
CriticNet critic;
std::map<std::string, std::any> opt_options;
opt_options.insert(std::make_pair("lr", LEARNING_RATE));
using namespace bitrl::maths::optim;
auto pytorch_ops = build_pytorch_optimizer_options(OptimizerType::ADAM, opt_options);
auto policy_optimizer = build_pytorch_optimizer(OptimizerType::ADAM, *policy, pytorch_ops);
auto critic_optimizer = build_pytorch_optimizer(OptimizerType::ADAM, *critic, pytorch_ops);
solver_type solver(ppo_config, policy, critic, policy_optimizer, critic_optimizer);
config.output_msg_frequency = 20;
auto info = trainer.train(env);
BITRL_LOG_INFO << "Training info...";
// land 10 times with the greedy policy, tanh of the mean, each from the
// next seed, and write the actions of every landing to episode_<k>.csv
// for examples/tools/episode_gif.py
{
policy->eval();
torch::NoGradGuard no_grad;
real_t sum = 0.0;
uint_t landed = 0;
for (uint_t k = 0; k < 10; ++k)
{
std::ofstream episode_file("episode_" + std::to_string(k) + ".csv");
// all the digits: a landing is chaotic, and a replay from rounded
// actions drifts away from it
episode_file << std::setprecision(17);
auto time_step = env.reset();
episode_file << "# seed " << env.last_reset_seed() << "\n";
uint_t steps = 0;
while (!time_step.done() && steps < 1000)
{
auto state =
torch::tensor(time_step.observation(), torch::dtype(torch::kFloat32));
auto [mean, log_std] = policy->forward(state);
const auto action =
TorchAdaptor::to_vector<real_t>(torch::tanh(mean).to(torch::kDouble));
episode_file << action[0] << "," << action[1] << "\n";
time_step = env.step(action);
total_reward += time_step.reward();
steps += 1;
}
landed += total_reward >= 200.0 ? 1 : 0;
std::cout << "Greedy landing " << k << " from seed " << env.last_reset_seed()
<< ": return " << total_reward << " in " << steps << " steps"
<< std::endl;
}
std::cout << "The greedy policy scored 200 or more in " << landed
<< " of 10 landings, with a mean return of " << sum / 10.0 << std::endl;
}
auto experiment_path = std::string("experiments/") + EXPERIMENT_ID;
// write the loss values
auto &policy_loss_vals = solver.get_monitor().policy_loss_values;
experiment_path + "/" + "policy_loss.csv",
loss_csv_writer.open();
auto episode_counter = 0;
for (uint_t i = 0; i < policy_loss_vals.size(); ++i)
{
std::tuple<uint_t, real_t> row = {episode_counter++, policy_loss_vals[i]};
loss_csv_writer.write_row(row);
}
loss_csv_writer.close();
// write the loss values
auto &critic_loss_vals = solver.get_monitor().critic_loss_values;
bitsim::utils::io::CSVWriter critic_csv_writer(
experiment_path + "/" + "critic_loss.csv",
critic_csv_writer.open();
episode_counter = 0;
for (uint_t i = 0; i < policy_loss_vals.size(); ++i)
{
std::tuple<uint_t, real_t> row = {episode_counter++, critic_loss_vals[i]};
critic_csv_writer.write_row(row);
}
critic_csv_writer.close();
auto &rewards = solver.get_monitor().rewards;
bitsim::utils::io::CSVWriter rewards_csv_writer(
experiment_path + "/" + "rewards.csv",
rewards_csv_writer.open();
episode_counter = 0;
for (uint_t i = 0; i < rewards.size(); ++i)
{
std::tuple<uint_t, real_t> row = {episode_counter++, rewards[i]};
rewards_csv_writer.write_row(row);
}
rewards_csv_writer.close();
auto &episode_duration = solver.get_monitor().episode_duration;
bitsim::utils::io::CSVWriter episode_duration_csv_writer(
experiment_path + "/" + "episode_duration.csv",
episode_duration_csv_writer.open();
episode_counter = 0;
for (uint_t i = 0; i < episode_duration.size(); ++i)
{
std::tuple<uint_t, real_t> row = {episode_counter++, episode_duration[i]};
episode_duration_csv_writer.write_row(row);
}
episode_duration_csv_writer.close();
BITRL_LOG_INFO << "Finished agent training";
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "Unknown exception occured" << std::endl;
}
return 0;
}
#else
#include <iostream>
int main()
{
std::cout << "This example requires PyTorch. Reconfigure bitrl with USE_PYTORCH fag turned ON."
<< std::endl;
return 1;
}
#endif
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_INFO
Definition bitrl_log.h:36
Definition lunar_lander_env.h:271
Normal distribution to be used with torchlib.
Definition torch_normal.h:25
Utility class to facilitate HTTP requests between the environments REST API and C++ drivers.
Definition rest_rl_env_client.h:28
Definition rl_serial_agent_trainer.h:41
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
static char default_delimiter()
The default column delimiter.
Definition csv_file_writer.h:28
std::tuple< uint_t, torch_tensor_t > act(const StateTp &state)
Definition a2c.cpp:78
std::tuple< torch_tensor_t, torch_tensor_t, torch_tensor_t > evaluate(torch_tensor_t states, torch_tensor_t actions)
Definition ppo_lunar_lander.cpp:138
ActorNetImpl()
Definition a2c.cpp:68
torch_tensor_t forward(torch_tensor_t state)
Definition a2c.cpp:90
int main()
Definition discounted_returns.cpp:19
Definition pytorch_optimizer_factory.h:26
std::unique_ptr< torch::optim::OptimizerOptions > build_pytorch_optimizer_options(OptimizerType type, const std::map< std::string, std::any > &options)
std::unique_ptr< torch::optim::Optimizer > build_pytorch_optimizer(OptimizerType type, torch::nn::Module &model, const torch::optim::OptimizerOptions &options)
build_pytorch_optimizer
Definition optimizer_type.h:12
@ ADAM
Definition optimizer_type.h:24
real_t mean(IteratorType begin, IteratorType end, bool parallel=true)
mean Compute the mean value of the values in the provided iterator range
Definition vector_math.h:119
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
DeviceType
Enumeration of various device types.
Definition bitsim_types.h:186
ValueIteration< env_type > solver_type
Definition value_iteration.cpp:36
TORCH_MODULE(LogisticRegressionModel)
dict action
Definition play.py:46
state
Definition play.py:39
info
Definition play.py:49
int total_reward
Definition play.py:41
env
Definition play.py:33
dict policy
Definition play.py:28
pg::PPOConfig ppo_config(uint_t n_rounds)
Definition ppo_distributed.cpp:134
Definition a2c.cpp:26
const std::string EXPERIMENT_ID
Definition a2c.cpp:29
const uint_t L1
Layer sizes for Actor.
Definition a2c.cpp:48
const uint_t L2
Definition a2c.cpp:49
const uint_t L3
Definition a2c.cpp:50
const auto N_EPISODES
Definition a2c.cpp:52
const std::string POLICY
Definition a2c.cpp:30
const real_t LEARNING_RATE
Definition a2c.cpp:51
bitrl::envs::gymnasium::CartPole env_type
Definition a2c.cpp:45
const std::string SERVER_URL
Definition a2c.cpp:28
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
uint_t n_episodes
Definition rl_serial_agent_trainer.h:31
uint_t output_msg_frequency
Definition rl_serial_agent_trainer.h:30
The PPOConfig struct. Configuration for PPOSolver class.
Definition ppo_config.h:26
The TorchStateAdaptor struct.
Definition torch_adaptor.h:24
static std::vector< T > to_vector(torch_tensor_t tensor)