bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
DQN on Gridworld

This example trains a deep Q-network, DQN, to walk an agent to the goal of a 4 x 4 grid. The environment is Gridworld, from the book Deep Reinforcement Learning in Action, and runs in the library itself, so it needs no server. The board has the player, a goal, a pit and a wall. Every step pays -1, the goal 10 and the pit -10, and either ends the episode. The board is static here: every episode starts with the pieces in the same cells. DQN with experience replay on Gridworld trains on random boards.

DQN

The network takes the board, a one-hot 4 x 4 plane for each of the four pieces, 64 values with a little noise added, and gives a Q value for each of the four moves through two hidden layers of 150 and 100 units with ReLU. The output layer has no ReLU: the Q values are mostly negative, since every step pays -1. Every step moves the Q value of the action taken towards \(r + \gamma \max_{\alpha'} Q(s', \alpha')\), with \(\gamma = 0.9\), or towards \(r\) alone on the step that ends the episode, by one step of Adam on the squared error. The agent acts \(\epsilon\)-greedily, with \(\epsilon\) going from 1 down to 0.1 over the 1000 training episodes.

The learned policy

The greedy policy DQN learned: 7 steps to the goal, a return of 4.

The mean length of the training episodes, 100 at a time, went 34, 29, 22, 19, 16, 13, 11, 10, 8, 7.6, as \(\epsilon\) fell and the agent learned the way. After training the example plays the greedy policy once and writes every board to episode.csv. It takes the shortest way around the wall and the pit, 7 steps. examples/tools/grid_world_gif.py draws the file:

python examples/tools/grid_world_gif.py episode.csv --title DQN --out dqn.gif

The example also writes the mean loss and the mean reward of every training episode to experiments/3/dqn_grid_world_policy_losses.csv and experiments/3/dqn_grid_world_policy_rewards.csv.

The driver code

#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>
#include <vector>
namespace rl_example_12
{
const std::string EXPERIMENT_ID = "3";
namespace F = torch::nn::functional;
constexpr uint_t l1 = 64;
constexpr uint_t l2 = 150;
constexpr uint_t l3 = 100;
constexpr uint_t l4 = 4;
constexpr uint_t SEED = 42;
constexpr uint_t TOTAL_EPOCHS = 1000;
constexpr real_t GAMMA = 0.9;
constexpr real_t EPSILON = 1.0;
constexpr real_t LEARNING_RATE = 1.0e-3;
// The class that models the Policy network to train
class QNetImpl final : public torch::nn::Module
{
public:
private:
torch::nn::Linear fc1_;
torch::nn::Linear fc2_;
torch::nn::Linear fc3_;
};
: fc1_(torch::nn::Linear(l1, l2)), fc2_(torch::nn::Linear(l2, l3)),
fc3_(torch::nn::Linear(l3, l4))
{
register_module("fc1", fc1_);
register_module("fc2", fc2_);
register_module("fc3", fc3_);
}
torch_tensor_t QNetImpl::forward(torch_tensor_t x)
{
// ReLU after the hidden layers only: the Q values are negative, every step
// pays -1, and a ReLU on the output could not give them
x = F::relu(fc1_->forward(x));
x = F::relu(fc2_->forward(x));
return fc3_->forward(x);
}
// create the model
// 4x4 grid
typedef Gridworld<4> env_type;
typedef env_type::state_type state_type;
std::vector<float_t> flattened_observation(const state_type &state)
{
std::vector<float_t> data;
data.reserve(64);
for (uint_t i = 0; i < state.size(); ++i)
{
for (uint_t j = 0; j < state[i].size(); ++j)
{
for (uint_t k = 0; k < state[i][j].size(); ++k)
{
data.push_back(state[i][j][k]);
}
}
}
return data;
}
} // namespace rl_example_12
int main()
{
using namespace rl_example_12;
try
{
BITRL_LOG_INFO << "Starting agent training...";
BITRL_LOG_INFO << "Number of episodes to train: " << TOTAL_EPOCHS;
// let's create a directory where we want to
// store all the results from running a simulation
std::filesystem::create_directories("experiments/" + EXPERIMENT_ID);
// set the seed for PyTorch
torch::manual_seed(SEED);
BITRL_LOG_INFO << "Creating the environment...";
// create a 4x4 grid
auto env = env_type();
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
env.make("v1", options, reset_options);
BITRL_LOG_INFO << "Done...";
BITRL_LOG_INFO << "Environment name: " << env.name;
BITRL_LOG_INFO << "Number of actions available: " << env.n_actions();
BITRL_LOG_INFO << "Number of states available: " << env.n_states();
// the network to train for the q values
QNet qnet;
auto optimizer_ptr = std::make_unique<torch::optim::Adam>(
qnet->parameters(), torch::optim::AdamOptions(LEARNING_RATE));
// we will use an epsilon-greedy policy
// the loss function to use
auto loss_fn = torch::nn::MSELoss();
std::vector<real_t> losses;
std::vector<real_t> rewards;
losses.reserve(TOTAL_EPOCHS);
rewards.reserve(TOTAL_EPOCHS);
// loop over the epochs
for (uint_t epoch = 0; epoch < TOTAL_EPOCHS; ++epoch)
{
BITRL_LOG_INFO << "Starting epoch: " << epoch;
// for every new epoch we reset the environment
auto time_step = env.reset();
auto done = false;
uint_t step_counter = 0;
std::vector<real_t> epoch_loss;
std::vector<real_t> epoch_rewards;
std::vector<float_t> rand_vec(64, 0.0);
epoch_loss.reserve(TOTAL_ITRS_PER_EPOCH);
while (!done)
{
auto obs = flattened_observation(time_step.observation());
float_t a = 0.0;
float_t b = 1.0;
rand_vec = bitrl::maths::randomize(rand_vec, a, b, 64);
rand_vec = bitrl::maths::divide(rand_vec, 10.0);
// randomize the flattened observation
obs = bitrl::maths::add(obs, rand_vec);
auto torch_state =
bitrl::utils::pytorch::TorchAdaptor::to_torch(obs, bitrl::DeviceType::CPU);
// get the qvals
auto qvals = qnet(torch_state);
auto action_idx = policy(qvals, bitrl::torch_tensor_value_type<float_t>());
BITRL_LOG_INFO << "\tAction selected: " << action_idx << std::endl;
// step in the environment
time_step = env.step(action_idx);
obs = flattened_observation(time_step.observation());
// randomize the flattened observation
obs = bitrl::maths::add(obs, rand_vec);
torch_state =
bitrl::utils::pytorch::TorchAdaptor::to_torch(obs, bitrl::DeviceType::CPU);
// tell the model that we don't use grad here
qnet->eval();
auto new_q_vals = qnet(torch_state);
// we are training again
qnet->train();
// find the maximum
auto max_q = torch::max(new_q_vals);
auto reward = time_step.reward();
BITRL_LOG_INFO << "\tReward: " << reward;
auto y = torch::tensor({reward});
if (reward == -1.0)
{
y += max_q * GAMMA;
}
// in the code below to break the computation graph
// and prevent gradients from flowing backward through
// parts of the model that shouldn't be updated during backpropagation.
y = y.detach();
auto X = qvals.squeeze()[action_idx].unsqueeze(0);
// calculate the loss
auto loss = loss_fn(X, y);
optimizer_ptr->zero_grad();
loss.backward();
optimizer_ptr->step();
epoch_loss.push_back(loss.item<real_t>());
epoch_rewards.push_back(reward);
step_counter += 1;
BITRL_LOG_INFO << "\tLoss at epoch: " << loss.item<real_t>();
// update done
done = time_step.done();
if (done)
{
BITRL_LOG_INFO << "\tFinishing epoch at step: " << step_counter;
}
}
BITRL_LOG_INFO << "Epoch finished...";
// get the epsilon
auto eps = policy.eps_value();
if (eps > 0.1)
{
eps -= 1 / static_cast<real_t>(TOTAL_EPOCHS);
policy.set_eps_value(eps);
}
losses.push_back(bitrl::maths::mean(epoch_loss.begin(), epoch_loss.end()));
rewards.push_back(bitrl::maths::mean(epoch_rewards.begin(), epoch_rewards.end()));
}
// play the greedy policy, the action of the largest Q value, for one episode on the static
// board, at most 20 steps each, and write every board to episode.csv for
// examples/tools/grid_world_gif.py: a row per step, the episode, the
// action that led to the board (-1 for the first), the reward and the 64
// values of the board
{
qnet->eval();
torch::NoGradGuard no_grad;
std::ofstream episode_file("episode.csv");
episode_file << "# episode,action,reward,board\n";
uint_t won = 0;
for (uint_t episode = 0; episode < 1; ++episode)
{
auto time_step = env.reset();
int action = -1;
for (uint_t step = 0; step <= 20; ++step)
{
const auto obs = flattened_observation(time_step.observation());
episode_file << episode << "," << action << "," << time_step.reward();
for (auto v : obs)
{
episode_file << "," << v;
}
episode_file << "\n";
if (time_step.done() || step == 20)
{
won += time_step.reward() > 0.0 ? 1 : 0;
break;
}
auto state =
bitrl::utils::pytorch::TorchAdaptor::to_torch(obs, bitrl::DeviceType::CPU);
action = static_cast<int>(torch::argmax(qnet(state)).item<int64_t>());
time_step = env.step(static_cast<uint_t>(action));
}
}
std::cout << "The greedy policy reached the goal in " << won << " of " << 1
<< " episodes" << std::endl;
}
// save the rewards per episode for visualization
// purposes
auto filename = std::string("experiments/") + EXPERIMENT_ID;
filename += "/dqn_grid_world_policy_rewards.csv";
CSVWriter rewards_csv_writer(filename, CSVWriter::default_delimiter());
rewards_csv_writer.open();
rewards_csv_writer.write_column_vector(rewards);
rewards_csv_writer.close();
filename = std::string("experiments/") + EXPERIMENT_ID;
filename += "/dqn_grid_world_policy_losses.csv";
CSVWriter losses_csv_writer(filename, CSVWriter::default_delimiter());
losses_csv_writer.open();
losses_csv_writer.write_column_vector(losses);
losses_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>
int main()
{
std::cout << "This example requires PyTorch" << std::endl;
std::cout << "Reconfigure bitrl with USE_PYTORCH flag 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
Definition grid_world_env.h:253
Definition rl_serial_agent_trainer.h:41
The EpsilonGreedyPolicy class.
Definition epsilon_greedy_policy.h:38
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
torch_tensor_t forward(torch_tensor_t)
Definition dqn.cpp:79
QNetImpl()
Definition dqn.cpp:70
int main()
Definition discounted_returns.cpp:19
Vec & add(Vec &v1, const Vec &v2)
Definition vector_math.h:248
std::vector< T > & randomize(std::vector< T > &vec, T a, T b, uint_t seed=42)
Fill in the given vector with random values.
Definition vector_math.h:230
real_t mean(IteratorType begin, IteratorType end, bool parallel=true)
mean Compute the mean value of the values in the provided iterator range
Definition vector_math.h:119
Vec & divide(Vec &v1, typename Vec::value_type val)
Definition vector_math.h:237
@ NONE
Definition epsilon_greedy_policy.h:28
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
constexpr int X
Definition cart_pole_dynamics.h:34
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
FrozenLake< 4 > env_type
Definition iterative_policy_evaluation.cpp:28
TORCH_MODULE(LogisticRegressionModel)
dict action
Definition play.py:46
reward
Definition play.py:49
state
Definition play.py:39
bool done
Definition play.py:40
env
Definition play.py:33
dict policy
Definition play.py:28
filename
Definition plot_losses.py:8
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Definition dqn.cpp:30
const std::string EXPERIMENT_ID
Definition dqn.cpp:32
constexpr uint_t TOTAL_EPOCHS
Definition dqn.cpp:51
constexpr uint_t l1
Definition dqn.cpp:46
Gridworld< 4 > env_type
Definition dqn.cpp:93
constexpr real_t LEARNING_RATE
Definition dqn.cpp:55
constexpr real_t EPSILON
Definition dqn.cpp:54
constexpr uint_t TOTAL_ITRS_PER_EPOCH
Definition dqn.cpp:52
constexpr uint_t l3
Definition dqn.cpp:48
constexpr real_t GAMMA
Definition dqn.cpp:53
constexpr uint_t SEED
Definition dqn.cpp:50
constexpr uint_t l2
Definition dqn.cpp:47
env_type::state_type state_type
Definition dqn.cpp:94
constexpr uint_t l4
Definition dqn.cpp:49
std::vector< float_t > flattened_observation(const state_type &state)
Definition dqn.cpp:96
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
Definition bitrl_types.h:98
static value_type to_torch(const std::vector< real_t > &data, DeviceType dtype=DeviceType::CPU, bool requires_grad=false)