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.
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 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:
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.
#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 F = torch::nn::functional;
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_);
}
{
x = F::relu(fc1_->forward(x));
x = F::relu(fc2_->forward(x));
return fc3_->forward(x);
}
{
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;
}
}
{
try
{
std::filesystem::create_directories(
"experiments/" +
EXPERIMENT_ID);
torch::manual_seed(
SEED);
std::unordered_map<std::string, std::any> options;
std::unordered_map<std::string, std::any> reset_options;
env.make(
"v1", options, reset_options);
QNet qnet;
auto optimizer_ptr = std::make_unique<torch::optim::Adam>(
auto loss_fn = torch::nn::MSELoss();
std::vector<real_t> losses;
std::vector<real_t> rewards;
{
auto time_step =
env.reset();
std::vector<real_t> epoch_loss;
std::vector<real_t> epoch_rewards;
std::vector<float_t> rand_vec(64, 0.0);
while (!done)
{
auto torch_state =
auto qvals = qnet(torch_state);
time_step =
env.step(action_idx);
torch_state =
qnet->eval();
auto new_q_vals = qnet(torch_state);
qnet->train();
auto max_q = torch::max(new_q_vals);
auto reward = time_step.reward();
auto y = torch::tensor({
reward});
if (reward == -1.0)
{
}
y = y.detach();
auto X = qvals.squeeze()[action_idx].unsqueeze(0);
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;
if (done)
{
}
}
auto eps =
policy.eps_value();
if (eps > 0.1)
{
}
}
{
qnet->eval();
torch::NoGradGuard no_grad;
std::ofstream episode_file("episode.csv");
episode_file << "# episode,action,reward,board\n";
for (
uint_t episode = 0; episode < 1; ++episode)
{
auto time_step =
env.reset();
{
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;
}
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;
}
filename +=
"/dqn_grid_world_policy_rewards.csv";
rewards_csv_writer.open();
rewards_csv_writer.write_column_vector(rewards);
rewards_csv_writer.close();
filename +=
"/dqn_grid_world_policy_losses.csv";
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>
{
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
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
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)