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

Training is usually done once, and what it learned used later: by another program, on another machine, in a robot. This example trains Q-learning and keeps the policy it found in two forms, a table of actions in a CSV file and a network saved with libtorch, and loads each back into a new policy that then plays an episode.

It trains on the cliff walk of Sutton and Barto, example 6.6, a 4 x 12 grid written in C++ in examples/03_experiments/common/cliff_walk.h, so it needs no environment server. The agent starts in the bottom left corner and the episode ends in the bottom right one; every step costs 1, and the cells between them along the bottom are a cliff that costs 100 and ends the episode.

A table of actions

QLearningSolver trains with an \(\epsilon\)-greedy policy, \(\epsilon = 0.1\), for 500 episodes, through RLSerialAgentTrainer. build_policy() then gives the greedy policy of its table, a MaxTabularPolicy, which saves itself as a CSV file of states and actions:

const auto trained = solver.build_policy();
trained.save("policy.csv");
MaxTabularPolicy loaded;
loaded.load("policy.csv");
auto action = loaded.on_state(state);

load reads the file back, and throws if it cannot be read or a row is not a state and an action. The example checks that the loaded policy gives the same action in every state, and plays an episode with it.

A network

A table works when there are few states. With more, a policy is a network, and libtorch saves and loads it with torch::save and torch::load. To have a network to save, the example trains one to give the action of the table in every state: the state, one-hot, in, a score for every action out, with a hidden layer of 64 units, trained with the cross entropy between its scores and the table's actions. Then

torch::save(network, "policy_network.pt");
PolicyNetwork loaded_network;
torch::load(loaded_network, "policy_network.pt");

The loaded network has to be the same type as the saved one: the file holds its parameters, not its layers. The example checks that the loaded network takes the table's action in every state, and plays an episode with it.

The results

Q-learning's greedy policy, saved to policy.csv:
............
............
************
SCCCCCCCCCCG
Loaded 48 states from policy.csv, 0 different from the trained policy; it scores -13
The network saved to policy_network.pt and loaded again differs from the table in 0 states; it scores -13

Q-learning learns the shortest path, along the edge of the cliff, 13 steps, and both loaded policies take it. The example exits with an error if either loaded policy differs from the trained one, so it runs as a test too.

The driver code

// Exporting a policy after training
//
// Training is often done once, and the policy it found used later, by another
// program, on another machine or in a robot. This example trains Q-learning
// on the cliff walk and keeps what it learned in two forms:
//
// - the greedy policy of the table, as a CSV file of states and actions, which
// MaxTabularPolicy saves and loads;
// - a small network trained to give the same actions, saved with libtorch's
// torch::save, the form a policy takes when there are too many states for a
// table.
//
// Each file is loaded back into a new policy, which then plays an episode.
#include "cliff_walk.h"
#include <torch/torch.h>
#include <iostream>
#include <string>
namespace export_policy
{
const std::string POLICY_FILE = "policy.csv";
const std::string NETWORK_FILE = "policy_network.pt";
// The network: the state, one-hot, in; a score for every action out
struct PolicyNetworkImpl : torch::nn::Module
{
: hidden(register_module("hidden", torch::nn::Linear(CliffWalk().n_states(), 64))),
out(register_module("out", torch::nn::Linear(64, CliffWalk().n_actions())))
{
}
{
return out->forward(torch::relu(hidden->forward(states)));
}
// the action with the highest score in the given state
uint_t act(uint_t state)
{
torch::NoGradGuard no_grad;
const auto one_hot =
torch::one_hot(torch::tensor({static_cast<int64_t>(state)}), CliffWalk().n_states())
.to(torch::kFloat32);
return forward(one_hot).argmax(-1).item<int64_t>();
}
torch::nn::Linear hidden;
torch::nn::Linear out;
};
TORCH_MODULE(PolicyNetwork);
// The return of one episode with the given policy, at most 100 steps
template <typename Policy> real_t play(Policy &&policy)
{
auto time_step = env.reset();
real_t total = 0.0;
for (uint_t i = 0; i < 100 && !time_step.done(); ++i)
{
time_step = env.step(policy(time_step.observation()));
total += time_step.reward();
}
return total;
}
{
bitrl::rl::algos::td::QLearningConfig config;
config.n_episodes = 500;
config.tolerance = 1.0e-8;
config.gamma = 1.0;
config.eta = 0.5;
typedef bitrl::rl::algos::td::QLearningSolver<CliffWalk, EpsilonGreedyPolicy> solver_type;
solver_type solver(config, EpsilonGreedyPolicy(0.1, 42));
// report every 1000 episodes, so not while these 500 run
bitrl::rl::RLSerialTrainerConfig trainer_config{1000, config.n_episodes, 1.0e-8};
bitrl::rl::RLSerialAgentTrainer<CliffWalk, solver_type> trainer(trainer_config, solver);
trainer.train(env);
return solver.build_policy();
}
// Train the network to give the action of the table in every state
void imitate(PolicyNetwork &network, const MaxTabularPolicy &policy)
{
const auto n_states = static_cast<int64_t>(policy.n_states());
const auto states = torch::eye(n_states);
std::vector<int64_t> actions(n_states);
for (int64_t s = 0; s < n_states; ++s)
{
actions[s] = policy.on_state(s);
}
const auto targets = torch::tensor(actions);
torch::optim::Adam optimizer(network->parameters(), torch::optim::AdamOptions(0.01));
for (uint_t epoch = 0; epoch < 500; ++epoch)
{
const auto loss = torch::nn::functional::cross_entropy(network->forward(states), targets);
optimizer.zero_grad();
loss.backward();
optimizer.step();
}
}
} // namespace export_policy
int main()
{
using namespace export_policy;
torch::manual_seed(42);
// Train, and save the greedy policy of the table
const auto trained = train_q_learning();
trained.save(POLICY_FILE);
std::cout << "Q-learning's greedy policy, saved to " << POLICY_FILE << ":\n"
<< CliffWalk::draw([&](uint_t s) { return trained.on_state(s); });
// Load it into a new policy, as another program would
loaded.load(POLICY_FILE);
uint_t differences = 0;
for (uint_t s = 0; s < loaded.n_states(); ++s)
{
differences += loaded.on_state(s) != trained.on_state(s);
}
const real_t table_return = play([&](uint_t s) { return loaded.on_state(s); });
std::cout << "Loaded " << loaded.n_states() << " states from " << POLICY_FILE << ", "
<< differences << " different from the trained policy; it scores " << table_return
<< "\n\n";
// A network that gives the same actions, saved with torch::save
PolicyNetwork network;
imitate(network, loaded);
torch::save(network, NETWORK_FILE);
// Load it into a new network and play with it
PolicyNetwork loaded_network;
torch::load(loaded_network, NETWORK_FILE);
uint_t network_differences = 0;
for (uint_t s = 0; s < loaded.n_states(); ++s)
{
network_differences += loaded_network->act(s) != loaded.on_state(s);
}
const real_t network_return = play([&](uint_t s) { return loaded_network->act(s); });
std::cout << "The network saved to " << NETWORK_FILE << " and loaded again differs from the "
<< "table in " << network_differences << " states; it scores " << network_return
<< "\n";
const bool same = differences == 0 && network_differences == 0;
return same ? 0 : 1;
}
The EpsilonGreedyPolicy class.
Definition epsilon_greedy_policy.h:38
class MaxTabularPolicy
Definition max_tabular_policy.h:33
void load(const std::string &filename)
Load the state -> action map from a CSV file that save() wrote: a state and its action per row,...
Definition cliff_walk.h:26
static std::string draw(const Policy &policy)
Definition cliff_walk.h:81
int main()
Definition discounted_returns.cpp:19
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
ValueIteration< env_type > solver_type
Definition value_iteration.cpp:36
Definition export_policy.cpp:29
const std::string POLICY_FILE
Definition export_policy.cpp:38
void imitate(PolicyNetwork &network, const MaxTabularPolicy &policy)
Definition export_policy.cpp:104
real_t play(Policy &&policy)
Definition export_policy.cpp:71
MaxTabularPolicy train_q_learning()
Definition export_policy.cpp:84
TORCH_MODULE(PolicyNetwork)
const std::string NETWORK_FILE
Definition export_policy.cpp:39
Definition play.py:1
state
Definition play.py:39
env
Definition play.py:33
dict policy
Definition play.py:28
real_t tolerance
Definition q_learning.h:33
uint_t n_episodes
Definition q_learning.h:31
real_t gamma
Definition q_learning.h:34
real_t eta
Definition q_learning.h:35
uint_t max_num_iterations_per_episode
Definition q_learning.h:32
PolicyNetworkImpl()
Definition export_policy.cpp:44
torch::nn::Linear hidden
Definition export_policy.cpp:65
torch_tensor_t forward(torch_tensor_t states)
Definition export_policy.cpp:50
torch::nn::Linear out
Definition export_policy.cpp:66
uint_t act(uint_t state)
Definition export_policy.cpp:56