\[\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 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.
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:
#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>
{
const std::string
SERVER_URL =
"http://0.0.0.0:8001/api";
const std::string
POLICY =
"policy.csv";
namespace F = torch::nn::functional;
class ActorNetImpl : public torch::nn::Module
{
public:
template <typename StateTp>
private:
torch::nn::Linear fc1_;
torch::nn::Linear fc2_;
torch::nn::Linear mean_layer_;
};
: 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_);
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);
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);
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);
auto log_std = torch::clamp(log_std_, -5.0, 0.5).expand_as(mean);
}
std::tuple<torch_tensor_t, torch_tensor_t, torch_tensor_t>
ActorNetImpl::evaluate(torch_tensor_t states, torch_tensor_t actions)
{
auto [
mean, log_std] = this->forward(states);
auto dist = TorchNormalDist(mean, torch::exp(log_std));
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();
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_);
}
{
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);
}
}
{
try
{
std::filesystem::create_directories(
"experiments/" +
EXPERIMENT_ID);
torch::manual_seed(42);
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
env.make(
"v3", options, reset_options);
CriticNet critic;
std::map<std::string, std::any> opt_options;
solver_type solver(ppo_config, policy, critic, policy_optimizer, critic_optimizer);
auto info = trainer.train(env);
{
torch::NoGradGuard no_grad;
for (
uint_t k = 0; k < 10; ++k)
{
std::ofstream episode_file("episode_" + std::to_string(k) + ".csv");
episode_file << std::setprecision(17);
auto time_step =
env.reset();
episode_file <<
"# seed " <<
env.last_reset_seed() <<
"\n";
while (!time_step.done() && steps < 1000)
{
torch::tensor(time_step.observation(), torch::dtype(torch::kFloat32));
time_step =
env.step(action);
steps += 1;
}
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;
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();
auto &critic_loss_vals = solver.get_monitor().critic_loss_values;
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;
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;
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();
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "Unknown exception occured" << std::endl;
}
return 0;
}
#else
#include <iostream>
{
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
dict policy
Definition play.py:28
pg::PPOConfig ppo_config(uint_t n_rounds)
Definition ppo_distributed.cpp:134
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)