bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
REINFORCE algorithm on CartPole

The DQN algorithm we used in examples Example 12: DQN algorithm on Gridworld and Example 15: DQN algorithm on Gridworld with experience replay approximate a value function and in particular the state-action value function i.e. \(Q(s, \alpha)\). However, in reinforcement learning we are more interested in policies rather than value functions This is because a policy dictates how an agent behaves in a given state. Indeed one way to derive a policy from a state-action value function is to use a greedy approach i.e.

\[\pi(s) = max_{\alpha} Q(s, \alpha)\]

In this example, we will implement a policy-based method. In particular, we will use one of the earliest policy-based methods namely the REINFORCE algorithm. Policy-based methods, as their name probably suggests, approximate policies directly. In particular, we will use a neural network to represent the policy \(\pi\) and use variants of the gradient descent algorithm in order to estimate the weights of the network.

The REINFORCE algorithm samples trajectories from the environment using the policy on hand and estimate the gradient using these samples. The true gradient can be then estimated using:

\[ \nabla J(\boldsymbol{\theta}_{t}) = E_{\pi} \left[ G_t \nabla log \pi(\alpha | S_t, \boldsymbol{\theta}) \right] \]

where \(G_t\) is the discounted cumulative reward at time step \(t\). After the gradient calculation, we update the policy parameters using the following formula

\[\boldsymbol{\theta} = \boldsymbol{\theta} + \eta \nabla_{\boldsymbol{\theta}} J( \pi_{\boldsymbol{\theta}})\]

or by substituting the expected value of the gradient:

\[\boldsymbol{\theta} = \boldsymbol{\theta} + \eta G_t\nabla_{\boldsymbol{\theta}} log \pi(\alpha | S_t, \boldsymbol{\theta})\]

In this example we will use the gymnasium.CartPole environment. Specifically, we will use the class CartPole. This is a simple class that allows us to sent HTTP requests to a server that actually runs the environment. We need this as gymnasium.CartPole is written in Python and we want to avoid the complexity of directly executing Python code from the C++ driver.

We will use the policy network from PyTorch examples: reinforce.py. However, feel free to experiment with this. Note that the PyTorch implementation uses a baseline in the implementation. We will use this approach in REINFORCE with baseline algorithm on CartPole

The REINFORCE algorithm is implemented in the class ReinforceSolver The solver is passed to the RLSerialAgentTrainer class that manages the loop over the specified number of episodes. The ReinforceSolver is derived from the RLSolverBase class and overrides some virtual methods. The class ReinforceSolver accepts two template parameters:

  • The environment type
  • The policy type

The environment type is a standard argument for all RL solvers in bitrl. The policy type represents the PyTorch model that we will use. Specifically, it should expose an act function that has the following signature

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

The PolicyNetImpl class

Below is the code for the network that implements the policy we want to use. The network specification is taken from reinforce.py. However, feel free to expeiment with this.

const uint_t L1 = 4;
const uint_t L2 = 128;
const uint_t L3 = 2;
const real_t LEARNING_RATE = 0.01;
// The class that models the Policy network to train
class PolicyNetImpl: public torch::nn::Module
{
public:
PolicyNetImpl();
// To execute the network in C++,
// we simply call the forward() method
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_;
bool is_playing_{false};
};
PolicyNetImpl::PolicyNetImpl()
:
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_);
}
PolicyNetImpl::forward(torch_tensor_t x){
x = fc1_->forward(x);
if(!is_playing_){
x = dp_ -> forward(x);
}
x = F::relu(x);
x = fc2_->forward(x);
return F::softmax(x, F::SoftmaxFuncOptions(0));
}
template<typename StateTp>
std::tuple<uint_t, torch_tensor_t>
PolicyNetImpl::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_MODULE(PolicyNet);
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
TORCH_MODULE(LogisticRegressionModel)
dict action
Definition play.py:46
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

The ReinforceSolver expects a policy type that exposes an act function that returns the action type and the log probability of taking this action.

Note also that the network above uses torch::nn::Dropout. Dropout is some form of regularization that we should only use during training.

Driver code

The learned policy

The greedy policy REINFORCE learned: 126 steps.

REINFORCE trained for 2000 episodes of at most 500 steps. The mean length of its training episodes, 250 at a time, went 27, 176, 218, 439, 339, 415, 484, 224: it learns, but its returns vary a lot from episode to episode, and it can lose much of what it learned, as in the last 250 episodes, which is what the baseline of REINFORCE with baseline algorithm on CartPole is for.

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 126 steps: the greedy policy is not the policy that was trained, which samples its actions, the training ended on a bad stretch, and a single episode from a single seed says little. 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 reinforce.gif
#include "bitrl/base/bitrl_config.h"
#ifdef USE_PYTORCH
#include <torch/torch.h>
#include <any>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
namespace rl_example_13
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const std::string EXPERIMENT_ID = "2";
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;
// The class that models the Policy network to train
class PolicyNetImpl : public torch::nn::Module
{
public:
// To execute the network in C++,
// we simply call the forward() method
template <typename StateTp> std::tuple<uint_t, torch_tensor_t> act(const StateTp &state);
void make_play() { is_playing_ = true; }
private:
torch::nn::Linear fc1_;
torch::nn::Dropout dp_;
torch::nn::Linear fc2_;
bool is_playing_{false};
};
: 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_);
}
torch_tensor_t PolicyNetImpl::forward(torch_tensor_t x)
{
x = fc1_->forward(x);
if (!is_playing_)
{
x = dp_->forward(x);
}
x = F::relu(x);
x = fc2_->forward(x);
return F::softmax(x, F::SoftmaxFuncOptions(0));
}
template <typename StateTp>
std::tuple<uint_t, torch_tensor_t> PolicyNetImpl::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_MODULE(PolicyNet);
typedef CartPole env_type;
typedef PolicyNet policy_type;
typedef ReinforceSolver<env_type, PolicyNet> solver_type;
} // namespace rl_example_13
int main()
{
BITRL_LOG_INFO << "Starting agent training";
using namespace rl_example_13;
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);
BITRL_LOG_INFO << "Creating environment...";
RESTRLEnvClient server(SERVER_URL, true);
auto env = CartPole(server);
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
// with Gymnasium v0 is not working
env.make("v1", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Done...";
BITRL_LOG_INFO << "Number of actions=" << env.n_actions();
PolicyNet policy;
// configuration for the REINFORCE solver
const auto N_EPISODES = 2000;
opts.gamma = 0.999;
opts.normalize_rewards = false;
opts.device_type = DeviceType::CPU;
std::map<std::string, std::any> opt_options;
opt_options.insert(std::make_pair("lr", LEARNING_RATE));
using namespace bitrl::maths;
*policy, pytorch_ops);
solver_type solver(opts, policy, policy_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...";
// save the rewards per episode for visualization
// purposes
auto experiment_path = std::string("experiments/") + EXPERIMENT_ID;
// save the policy also so that we can load it and check
// use it
auto policy_model_filename =
experiment_path + std::string("/reinforce_cartpole_policy.pth");
torch::save(policy, policy_model_filename + std::string("policy.pth"));
// or we can use serialize
torch::serialize::OutputArchive archive;
policy->save(archive);
archive.save_to(policy_model_filename);
// write the loss values
auto &loss_vals = solver.get_monitor().policy_loss_values;
BITRL_LOG_INFO << "Loss values size: " << loss_vals.size();
experiment_path + "/" + "loss.csv", bitsim::utils::io::CSVWriter::default_delimiter());
loss_csv_writer.open();
auto episode_counter = 0;
for (uint_t i = 0; i < loss_vals.size(); ++i)
{
std::tuple<uint_t, real_t> row = {episode_counter++, loss_vals[i]};
loss_csv_writer.write_row(row);
}
loss_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 0;
}
#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
The ReinforceSolver class. The ReinforceSolver trains a policy represented by the PolicyTp template p...
Definition reinforce.h:60
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
void make_play()
Definition reinforce.cpp:80
std::tuple< uint_t, torch_tensor_t > act(const StateTp &state)
act Every policy network should expose an act function that takes a StateTp and returns an std::tuple...
Definition reinforce.cpp:112
PolicyNetImpl()
Constructor.
Definition reinforce.cpp:89
torch_tensor_t forward(torch_tensor_t state)
Definition reinforce.cpp:97
int main()
Definition discounted_returns.cpp:19
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
@ ADAM
Definition optimizer_type.h:24
Definition lp_metric.h:10
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
float float_t
float
Definition bitsim_types.h:25
double real_t
real_t
Definition bitsim_types.h:20
DeviceType
Enumeration of various device types.
Definition bitsim_types.h:186
int int_t
integer type
Definition bitsim_types.h:30
EpsilonDoubleQTableGreedyPolicy< DynMat< real_t > > policy_type
Definition double_q_learning.cpp:38
FrozenLake< 4 > env_type
Definition iterative_policy_evaluation.cpp:28
ValueIteration< env_type > solver_type
Definition value_iteration.cpp:36
state
Definition play.py:39
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 reinforce.cpp:33
const uint_t L3
Definition reinforce.cpp:57
ReinforceSolver< env_type, PolicyNet > solver_type
Definition reinforce.cpp:128
const real_t LEARNING_RATE
Definition reinforce.cpp:58
const std::string SERVER_URL
Definition reinforce.cpp:35
const std::string EXPERIMENT_ID
Definition reinforce.cpp:36
const std::string POLICY
Definition reinforce.cpp:37
const uint_t L1
Definition reinforce.cpp:55
const uint_t L2
Definition reinforce.cpp:56
uint_t N_EPISODES
Definition multi_armed_bandits.cpp:34
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 ReinforceOpts struct. Holds various configuration options for the Reinforce algorithm.
Definition reinforce_config.h:37
real_t gamma
The discount factor.
Definition reinforce_config.h:69
bool normalize_rewards
Definition reinforce_config.h:38
DeviceType device_type
The device type that PyTorch calculations take place.
Definition reinforce_config.h:53
uint_t n_episodes
The number of episodes.
Definition reinforce_config.h:58
uint_t max_itrs_per_episode
Max number of iterations per episode.
Definition reinforce_config.h:64

Running the driver above produces the following plots.

Figure 1: Undiscounted total reward for REINFORCE over training.

Figure 2: Loss for REINFORCE over training.

Figure 3: Episode duration for REINFORCE over training.

Summary

This example introduced the ReinforceSolver class that models the REINFORCE algorithm.

The RINFORCE algorithm, just like all policy gradient methods, suffers from high variance in the gradient estimation. There are several reasons behind this high variance; e.g. sparse rewards or environment randomness. Regardless of reasons behind the high variance in the gradient, this effect can be detrimental during learning as it destabilizes it. Hence, reducing the high variance is important for feasible training. Using a baseline is one approach we can use in order to reduce the variance in the gradient approximation. We will use this in REINFORCE with baseline algorithm on CartPole.