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.
In this example we will use standardization or whitening as a baseline. In this case the baseline term is given by
Recall that \(G_t\) is the total, discounted, reward over the episode i.e.
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.
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:
#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>
{
const std::string
SERVER_URL =
"http://0.0.0.0:8001/api";
const std::string
POLICY =
"policy.csv";
namespace F = torch::nn::functional;
class PolicyNetImpl : 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_;
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_);
}
{
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);
return std::make_tuple(
action.item().toLong(), m.log_prob(action));
}
typedef ReinforceSolver<env_type, PolicyNet>
solver_type;
}
{
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(
"v1", options, reset_options);
std::map<std::string, std::any> opt_options;
*policy, pytorch_ops);
auto info = trainer.train(env);
{
torch::NoGradGuard no_grad;
std::ofstream episode("episode.csv");
auto time_step =
env.reset();
episode <<
"# seed " <<
env.last_reset_seed() <<
"\n";
{
const auto state = torch::tensor(time_step.observation(), torch::kFloat32);
time_step =
env.step(action);
total += time_step.reward();
}
std::cout << "The greedy policy kept the pole up for " << total << " steps"
<< std::endl;
}
auto experiment_path = std::string(
"experiments/") +
EXPERIMENT_ID;
auto policy_model_filename =
experiment_path + std::string("/reinforce_cartpole_policy.pth");
torch::save(policy, policy_model_filename + std::string("policy.pth"));
torch::serialize::OutputArchive archive;
archive.save_to(policy_model_filename);
auto &loss_vals = solver.get_monitor().policy_loss_values;
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;
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 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
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.