bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
A policy network

The policy gradient methods of bitrl, REINFORCE, A2C and PPO, all rest on the same few steps with libtorch: a network whose outputs define a distribution over the actions, an action sampled from it, and a change to the network that raises the log probability of the actions that did well. This example does those steps on their own, on a problem that needs no environment server, before the examples that use them on real environments.

The problem

A contextual bandit: the agent is in one of two situations, chosen at random, and pulls one of three arms. Each arm pays a reward with noise around a mean that depends on the situation:

Situation Arm 0 Arm 1 Arm 2
0 0.2 0.5 1.0
1 1.0 0.3 0.1

The best arm is different in the two situations, so the policy has to depend on the situation, which is what a network is for.

The network and the distribution

Policy takes the situation, one-hot, and gives a logit for every arm, through a hidden layer of 16 units. TorchCategorical, built from the logits, is the distribution over the arms, \(\pi_\theta(\alpha | s)\), the soft-max of the logits. It samples the arms and gives their log probabilities and its entropy. The optimizer, Adam with a learning rate of 0.01, comes from bitrl's build_pytorch_optimizer, which builds a libtorch optimizer from its type and options.

Learning

Every update samples 64 situations, an arm for each from the policy, and the rewards of the arms. The loss is the REINFORCE loss,

\[L(\theta) = - \frac{1}{64} \sum_i \log \pi_\theta(\alpha_i | s_i) \left( r_i - \bar{r} \right), \]

where \(\bar{r}\) is the mean reward of the batch. Its gradient raises the log probability of the arms that paid more than the mean and lowers it for the others; subtracting the mean, a baseline, makes the gradient vary less without changing its expected direction. The arms are sampled, so the loss does not differentiate through the sampling, only through the log probabilities.

The results

The policy starts close to uniform and after 300 updates picks the best arm of each situation almost always:

Before training
situation 0: arm 0 0.472 arm 1 0.340 arm 2 0.188
situation 1: arm 0 0.501 arm 1 0.263 arm 2 0.236
update 100: mean reward 0.976, entropy 0.019
update 200: mean reward 1.000, entropy 0.008
update 300: mean reward 1.020, entropy 0.006
After training
situation 0: arm 0 0.000 arm 1 0.000 arm 2 0.999
situation 1: arm 0 0.999 arm 1 0.000 arm 2 0.001
The policy found the best arm of both situations

The entropy of the policy falls as it stops exploring. Here that is what we want, but on harder problems a policy that stops exploring this early can settle on a poor action, which is why A2C and PPO can add the entropy to the loss to keep it up. The example exits with an error if the best arms are not found, so it runs as a test too.

The driver code

// A policy network with the PyTorch C++ API
//
// The policy gradient methods of bitrl, REINFORCE, A2C and PPO, all have a
// network whose outputs define a distribution over the actions. They sample
// an action from it, and change the network so that the log probability of
// the actions that did well goes up. This example does that on its own, on a
// contextual bandit that needs no environment server: in each of two
// situations one of three arms pays best, and the network learns which.
#include <torch/torch.h>
#include <any>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
{
const uint_t N_SITUATIONS = 2;
const uint_t N_ARMS = 3;
const uint_t BATCH_SIZE = 64;
const uint_t N_UPDATES = 300;
const real_t LEARNING_RATE = 0.01;
const real_t REWARD_NOISE = 0.5;
// The mean reward of each arm in each situation: arm 2 is best in the first,
// arm 0 in the second
const real_t MEAN_REWARD[N_SITUATIONS][N_ARMS] = {{0.2, 0.5, 1.0}, {1.0, 0.3, 0.1}};
// The policy: the situation, one-hot, in; a logit for every arm out
struct PolicyImpl : torch::nn::Module
{
: hidden(register_module("hidden", torch::nn::Linear(N_SITUATIONS, 16))),
out(register_module("out", torch::nn::Linear(16, N_ARMS)))
{
}
{
return out->forward(torch::relu(hidden->forward(situation)));
}
torch::nn::Linear hidden;
torch::nn::Linear out;
};
TORCH_MODULE(Policy);
// The probability the policy gives every arm in every situation
void print_probabilities(Policy &policy, const std::string &when)
{
torch::NoGradGuard no_grad;
const auto situations = torch::eye(N_SITUATIONS);
const auto probs = torch::softmax(policy->forward(situations), -1);
std::cout << when << "\n";
for (uint_t s = 0; s < N_SITUATIONS; ++s)
{
std::cout << " situation " << s << ":";
for (uint_t a = 0; a < N_ARMS; ++a)
{
std::cout << " arm " << a << " " << std::fixed << std::setprecision(3)
<< probs[s][a].item<real_t>();
}
std::cout << "\n";
}
}
} // namespace pytorch_policy_network
int main()
{
using namespace pytorch_policy_network;
torch::manual_seed(42);
Policy policy;
print_probabilities(policy, "Before training");
// bitrl builds the optimizer from its type and options
std::map<std::string, std::any> options{{"lr", std::any(LEARNING_RATE)}};
namespace optim = bitrl::maths::optim::pytorch;
const auto optimizer_options =
optim::build_pytorch_optimizer_options(OptimizerType::ADAM, options);
auto optimizer =
optim::build_pytorch_optimizer(OptimizerType::ADAM, *policy, *optimizer_options);
const auto means = torch::tensor({MEAN_REWARD[0][0], MEAN_REWARD[0][1], MEAN_REWARD[0][2],
MEAN_REWARD[1][0], MEAN_REWARD[1][1], MEAN_REWARD[1][2]},
torch::kFloat64)
.view({N_SITUATIONS, N_ARMS});
for (uint_t update = 0; update < N_UPDATES; ++update)
{
// a batch of situations, and an arm for each, sampled from the policy
const auto situation_index = torch::randint(N_SITUATIONS, {BATCH_SIZE}, torch::kLong);
const auto situations = torch::one_hot(situation_index, N_SITUATIONS).to(torch::kFloat32);
TorchCategorical policy_distribution(policy->forward(situations), /*from logits*/ true);
const auto arms = policy_distribution.sample().detach();
// the bandit pays a noisy reward
const auto rewards = (means.index({situation_index, arms}) +
REWARD_NOISE * torch::randn({BATCH_SIZE}, torch::kFloat64))
.to(torch::kFloat32);
// REINFORCE: raise the log probability of the arms that paid more than
// the mean of the batch, lower it for the others
const auto advantage = rewards - rewards.mean();
const auto loss = -(policy_distribution.log_prob(arms) * advantage).mean();
optimizer->zero_grad();
loss.backward();
optimizer->step();
if ((update + 1) % 100 == 0)
{
std::cout << "update " << update + 1 << ": mean reward " << std::fixed
<< std::setprecision(3) << rewards.mean().item<real_t>() << ", entropy "
<< policy_distribution.entropy().mean().item<real_t>() << "\n";
}
}
print_probabilities(policy, "After training");
// the policy should have found the best arm of each situation
torch::NoGradGuard no_grad;
const auto probs = torch::softmax(policy->forward(torch::eye(N_SITUATIONS)), -1);
const bool learned = probs[0][2].item<real_t>() > 0.9 && probs[1][0].item<real_t>() > 0.9;
std::cout << (learned ? "The policy found the best arm of both situations"
: "The policy did not find the best arms")
<< std::endl;
return learned ? 0 : 1;
}
Definition torch_categorical.h:23
int main()
Definition discounted_returns.cpp:19
Definition pytorch_optimizer_factory.h:26
OptimizerType
The RenderModeType enum.
Definition optimizer_type.h:20
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
dict policy
Definition play.py:28
Definition pytorch_policy_network.cpp:24
const real_t MEAN_REWARD[N_SITUATIONS][N_ARMS]
Definition pytorch_policy_network.cpp:41
const real_t REWARD_NOISE
Definition pytorch_policy_network.cpp:37
const uint_t N_ARMS
Definition pytorch_policy_network.cpp:33
const real_t LEARNING_RATE
Definition pytorch_policy_network.cpp:36
const uint_t BATCH_SIZE
Definition pytorch_policy_network.cpp:34
void print_probabilities(Policy &policy, const std::string &when)
Definition pytorch_policy_network.cpp:63
const uint_t N_UPDATES
Definition pytorch_policy_network.cpp:35
const uint_t N_SITUATIONS
Definition pytorch_policy_network.cpp:32
Definition pytorch_policy_network.cpp:45
torch_tensor_t forward(torch_tensor_t situation)
Definition pytorch_policy_network.cpp:52
torch::nn::Linear out
Definition pytorch_policy_network.cpp:58
PolicyImpl()
Definition pytorch_policy_network.cpp:46
torch::nn::Linear hidden
Definition pytorch_policy_network.cpp:57