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

REINFORCE algorithm on CartPole used the REINFORCE algorithm to build an agent that can control the CartPole environment. The REINFORCE algorithm is very sensitive to gradient variance which in turn can affect training.

In this example, we will extend the REINFORCE algorithm using a baseline. This is a generalisation of the REINFORCE algorithm to include a comparison of the action value to an arbitrary baseline \(b(s)\) [1]. Hence, the gradient of the cost function is now proportional to

\[\nabla J(\boldsymbol{\theta}_{t}) \propto \sum_{s} \mu(s) \sum_{\alpha}\left(q_{\pi}(s,\alpha) - b(s)\right )\nabla \pi(\alpha | s, \boldsymbol{\theta}) \]

Note that the baseline can be any function, even a random variable, as long as it does not vary with \(\alpha\). The update rule in this version of REINFORCE is [1].

\[\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_{t} + \alpha \left(G_t - b(S_t)\right )\frac{\nabla \pi(A_t | S_t, \boldsymbol{\theta}_t)}{\pi(A_t | S_t, \boldsymbol{\theta}_t)}\]

The baseline function, as mentioned above, can be any function even a unformly zero. Thus, the update rule above is a generalization of the REINFORCE algorithm [1]. Although the baseline does not affect the expected value of the update, it can have a, large, effect on its variance [1]. A choice for the baseline is an estimate of the state value i.e. \(\hat{v}(S_t, \mathbf{w})\) where \(\mathbf{w} \in \mathbb{R}^m\) is a weight vector.

We will again 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 we used in REINFORCE algorithm on CartPole The configuation of the REINFORCE solver supports three types of baseline values

  • A user specified constant
  • Mean value
  • Standardization

In this example we will use standardization or whitening as a baseline. In this case the baseline term is given by


Remark

The Medium article https://medium.com/@fork.tree.ai/understanding-baseline-techniques-for-reinforce-53a1e2279b57 provides a nice overview of baseline techniques.


\[b(S_t) = \frac{G_t - \bar{G}}{\sigma_{G}}\]

Recall that \(G_t\) is the total, discounted, reward over the episode i.e.

\[G_t = \sum_{i} \gamma^ir_i\]

where \(i\) denotes the iteration index within the episode.

Other than that this example is similar to the aforementioned example. Feel free to experiment with the various baseline types. The dirver code is shown below.

Driver code

The learned policy

The greedy policy REINFORCE with a baseline learned: all 500 steps.

REINFORCE with a baseline trained for 2000 episodes of at most 200 steps. The mean length of its training episodes, 250 at a time, went 145, 194, 184, 193, 175, 198, 178, 191, against the cap of 200.

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, more than the 200 steps of the episodes it was trained on. 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_baseline.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.max_itrs_per_episode = 200; // the max we can get according to docs
opts.device_type = DeviceType::CPU;
opts.baseline_type = BaselineEnumType::STANDARDIZE;
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
BaselineEnumType
Enumeration of the baseline types supported.
Definition reinforce_config.h:24
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
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
TORCH_MODULE(LogisticRegressionModel)
dict action
Definition play.py:46
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
BaselineEnumType baseline_type
The baseline to use.
Definition reinforce_config.h:48
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 extended REINFORCE algorithm on CartPole by using a baseline term. Specifically, it used standarization or whitening as a baseline.