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
#include <torch/torch.h>
#include <any>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
{
{
out(register_module(
"out", torch::nn::Linear(16,
N_ARMS)))
{
}
{
return out->forward(torch::relu(
hidden->forward(situation)));
}
};
{
torch::NoGradGuard no_grad;
const auto probs = torch::softmax(
policy->forward(situations), -1);
std::cout << when << "\n";
{
std::cout << " situation " << s << ":";
{
std::cout << " arm " << a << " " << std::fixed << std::setprecision(3)
<< probs[s][a].item<
real_t>();
}
std::cout << "\n";
}
}
}
{
torch::manual_seed(42);
std::map<std::string, std::any> options{{
"lr", std::any(
LEARNING_RATE)}};
const auto optimizer_options =
optim::build_pytorch_optimizer_options(OptimizerType::ADAM, options);
auto optimizer =
optim::build_pytorch_optimizer(OptimizerType::ADAM, *policy, *optimizer_options);
torch::kFloat64)
{
const auto situations = torch::one_hot(situation_index,
N_SITUATIONS).to(torch::kFloat32);
const auto arms = policy_distribution.sample().detach();
const auto rewards = (means.index({situation_index, arms}) +
.to(torch::kFloat32);
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";
}
}
torch::NoGradGuard no_grad;
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