bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
An A2C Solver for CartPole

REINFORCE algorithm on CartPole introduced the vanilla REINFORCE algorithm in order to solve the pole balancing problem. The REINFORCE algorithm is a simple algorithm and easy to use however it exhibits a large variance in the reward signal.

In this exampel, we will introduce actor-critic methods and specifically the A2C algorithm. The main objective of actor-critic methods is to further reduce the high gradient variance. One way towards this direction is to use the so-called reward-to-go term for a trajectory \(T\).

\[G = \sum_{k = t}^T R(s_{k}, \alpha_{k})\]

The environment runs on the bitrl-rest-api server, so start it first.

The workings of the A2C algorithm are handled by the A2CSolver class. The class accepts three template parameters

  • The environment type
  • The policy type or the actor type
  • The critic type

The role of the actor is to select an action for the agent to take. The role of the critic is to tell us whether that action was good or bad. We could use of course the raw reward signal to have an assessment on this but for enviroments where the reward is sparse this may not work or for enviroments where the reward signal is the same for most actions.

Given this approach, the critic will be a term in the actor’s loss function, whilst the critic will learn directly from the provided reward signals.

In the code below, the critic and action networks do not share any details. This need not be the case however. You can come up with an implementation where the two networks share most of the layers and only differentiate at the output layer.

The Actor network class

Just like in REINFORCE algorithm on CartPole, the actor class has to expose an act function with the following signature:

template<typename StateTp>
std::tuple<uint_t, torch_tensor_t> act(const StateTp& state)

Below is the class that implements the actor model. It is identical to the one from the REINFORCE example.

class ActorNetImpl: public torch::nn::Module
{
public:
ActorNetImpl();
torch_tensor_t forward(torch_tensor_t state);
template<typename StateTp>
std::tuple<uint_t, torch_tensor_t> act(const StateTp& state);
private:
torch::nn::Linear fc1_;
torch::nn::Dropout dp_;
torch::nn::Linear fc2_;
};
ActorNetImpl::ActorNetImpl()
:
torch::nn::Module(),
fc1_(torch::nn::Linear(L1, L2)),
dp_(torch::nn::Dropout(0.6)),
fc2_(torch::nn::Linear(L2, L3))
{
register_module("fc1_", fc1_);
register_module("dp_", dp_);
register_module("fc2_", fc2_);
}
template<typename StateTp>
std::tuple<uint_t, torch_tensor_t>
ActorNetImpl::act(const StateTp& state){
auto torch_state = torch::tensor(state);
auto probs = forward(torch_state);
auto m = TorchCategorical(probs, false);
auto action = m.sample();
return std::make_tuple(action.item().toLong(),
m.log_prob(action));
}
ActorNetImpl::forward(torch_tensor_t state){
state = fc1_->forward(state);
state = dp_ -> forward(state);
state = F::relu(state);
state = fc2_->forward(state);
return F::softmax(state, F::SoftmaxFuncOptions(0));
}
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
dict action
Definition play.py:46
state
Definition play.py:39

The Critic network class

We also need to provide a critic network. The class has to expose an evaluate function with the following signature:

template<typename StateTp>
torch_tensor_t evaluate(const StateTp& state);
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(4, 128)),
fc2_(torch::nn::Linear(128, 256)),
fc3_(torch::nn::Linear(256, 1))
{
register_module("fc1_", fc1_);
register_module("fc2_", fc2_);
register_module("fc3_", fc3_);
}
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>
CriticNetImpl::evaluate(const StateTp& state){
auto torch_state = torch::tensor(state);
return forward(torch_state);
}

The learned policy

The greedy policy A2C learned: 500 steps.

A2C trained for 1000 episodes of at most 500 steps, about 400,000 steps in all, which took 393 s, most of it in the HTTP requests to the server. The mean length of its training episodes, 250 at a time, went 337, 465, 376, 486: by the second 250 episodes it keeps the pole up most of the time.

After training the example plays one episode with the greedy policy, the action of the larger probability, from the next seed, and writes its actions and the seed to episode.csv. It kept the pole up for all 500 steps. examples/tools/episode_gif.py replays the actions in Gymnasium to make the GIF:

python examples/tools/episode_gif.py --env CartPole-v1 --actions episode.csv --fps 50 --out a2c.gif

The driver code

The driver code for this tutorial is shown below.

#include "bitrl/base/bitrl_config.h"
#ifdef USE_PYTORCH
#include <torch/torch.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <unordered_map>
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 = 4;
const uint_t L2 = 128;
const uint_t L3 = 2;
const real_t LEARNING_RATE = 0.01;
const auto N_EPISODES = 1000;
// create the Action network
class ActorNetImpl : public torch::nn::Module
{
public:
template <typename StateTp> std::tuple<uint_t, torch_tensor_t> act(const StateTp &state);
private:
torch::nn::Linear fc1_;
torch::nn::Dropout dp_;
torch::nn::Linear fc2_;
};
: torch::nn::Module(), fc1_(torch::nn::Linear(L1, L2)), dp_(torch::nn::Dropout(0.6)),
fc2_(torch::nn::Linear(L2, L3))
{
register_module("fc1_", fc1_);
register_module("dp_", dp_);
register_module("fc2_", fc2_);
}
template <typename StateTp>
std::tuple<uint_t, torch_tensor_t> ActorNetImpl::act(const StateTp &state)
{
auto torch_state = torch::tensor(state);
auto probs = forward(torch_state);
auto m = TorchCategorical(probs, false);
auto action = m.sample();
return std::make_tuple(action.item().toLong(), m.log_prob(action));
}
torch_tensor_t ActorNetImpl::forward(torch_tensor_t state)
{
state = fc1_->forward(state);
state = dp_->forward(state);
state = F::relu(state);
state = fc2_->forward(state);
return F::softmax(state, F::SoftmaxFuncOptions(0));
}
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(4, 128)), fc2_(torch::nn::Linear(128, 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("v1", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Done...";
BITRL_LOG_INFO << "Number of actions=" << env.n_actions();
A2CConfig a2c_config;
a2c_config.max_itrs_per_episode = 500;
a2c_config.n_episodes = N_EPISODES;
a2c_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(a2c_config, policy, critic, policy_optimizer, critic_optimizer);
config.output_msg_frequency = 20;
auto info = trainer.train(env);
// one episode with the greedy policy, the action of the largest
// probability, from the seed the environment resets with; its actions
// are for examples/tools/episode_gif.py
{
torch::NoGradGuard no_grad;
policy->eval();
std::ofstream episode("episode.csv");
auto time_step = env.reset();
// the seed the episode started from, for the GIF to start from it too
episode << "# seed " << env.last_reset_seed() << "\n";
bitrl::real_t total = 0.0;
for (bitrl::uint_t step = 0; step < 500 && !time_step.done(); ++step)
{
const auto state = torch::tensor(time_step.observation(), torch::kFloat32);
const auto action =
static_cast<bitrl::uint_t>(policy->forward(state).argmax().item<int64_t>());
episode << action << "\n";
time_step = env.step(action);
total += time_step.reward();
}
std::cout << "The greedy policy kept the pole up for " << total << " steps"
<< std::endl;
}
BITRL_LOG_INFO << "Training info...";
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
The CartPole class Interface for CartPole environment.
Definition cart_pole_env.h:70
Definition torch_categorical.h:23
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
A2C solver assuming separate networks for the actor and the critic. Similar to the Reinforce algorith...
Definition a2c.h:54
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
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
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)
info
Definition play.py:49
env
Definition play.py:33
dict policy
Definition play.py:28
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
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 A2CConfig struct. Configuration for A2CSolver class.
Definition a2c_config.h:26
uint_t n_episodes
Number of training episodes.
Definition a2c_config.h:77
DeviceType device_type
Definition a2c_config.h:97
uint_t max_itrs_per_episode
Number of iterations per episode.
Definition a2c_config.h:82

Running the driver above produces the following plots.

Figure 1: Undiscounted total reward for A2C over training.

Figure 2: Actor loss for A2C over training.

Figure 3: Critic loss for A2C over training.

Figure 4: Episode duration for A2C over training.