The mean length of the training episodes, 1000 at a time, went 13.3, 8.0, 5.9, 5.5, 5.7. After training the example plays the greedy policy on 100 new random boards, at most 20 steps each, and writes every board to episode.csv. It reached the goal on 85 of them, in 2.9 steps on average, and never fell into the pit; on the other 15 it got stuck, as on the last board of the GIF, where it keeps walking into the edge of the grid. More training episodes, or an \(\epsilon\) that decays, would help. The GIF shows boards 1, 2, 3, 6, 7 and 0:
#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 <tuple>
#include <unordered_map>
#include <vector>
{
namespace F = torch::nn::functional;
class QNetImpl : 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;
}
template <typename T, uint_t index>
std::vector<T>
get(
const std::vector<experience_tuple_type> &experience)
{
std::vector<T> result;
result.reserve(experience.size());
auto b = experience.begin();
auto e = experience.end();
for (; b != e; ++b)
{
auto item = *b;
result.push_back(std::get<index>(item));
}
return result;
}
}
{
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(
"v0", 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<float_t> rand_vec(64, 0.0);
{
auto time_step =
env.reset();
std::vector<real_t> epoch_loss;
while (!done)
{
auto torch_state_1 =
auto qvals = qnet(torch_state_1);
time_step =
env.step(action_idx);
auto reward = time_step.reward();
auto step_finished =
time_step.done() ?
static_cast<uint_t>(1) : static_cast<
uint_t>(0);
auto torch_state_2 =
experience_buffer.append(exp);
{
std::vector<experience_tuple_type> batch_sample;
state_1_batch, bitrl::DeviceType::CPU);
auto q1 = qnet(state_1_batch_t);
qnet->eval();
state_2_batch, bitrl::DeviceType::CPU);
auto q2 = qnet(state_2_batch_t);
qnet->train();
reward_batch, bitrl::DeviceType::CPU);
done_batch, bitrl::DeviceType::CPU);
action_batch, bitrl::DeviceType::CPU);
auto state_max = torch::max(q2, 1);
auto state_max_val = std::get<0>(state_max);
auto Y = reward_batch_t +
GAMMA * ((1 - done_batch_t) * state_max_val);
auto X = q1.gather(1, action_batch_t.unsqueeze(1)).squeeze();
auto loss = loss_fn(X, Y.detach());
optimizer_ptr->zero_grad();
loss.backward();
optimizer_ptr->step();
epoch_loss.push_back(loss.item<
real_t>());
}
step_counter += 1;
{
step_counter = 0;
}
}
}
{
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 < 100; ++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 " << 100
<< " episodes" << std::endl;
}
filename +=
"/dqn_grid_world_policy_loss.csv";
csv_writer.open();
csv_writer.write_column_vector(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 ExperienceBuffer class. A buffer based on boost::circular_buffer to accumulate items of type Expe...
Definition experience_buffer.h:28
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
@ RANDOM
Definition grid_world_env.h:41
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
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
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
int int_t
integer type
Definition bitsim_types.h:30
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 EXPERIENCE_BUFFER_SIZE
Definition dqn_experience_replay.cpp:60
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
std::tuple< std::vector< float_t >, uint_t, float_t, std::vector< float_t >, uint_t > experience_tuple_type
Definition dqn_experience_replay.cpp:106
constexpr uint_t BATCH_SIZE
Definition dqn_experience_replay.cpp:59
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< T > get(const std::vector< experience_tuple_type > &experience)
Definition dqn_experience_replay.cpp:132
env_type::time_step_type time_step_type
Definition dqn_experience_replay.cpp:103
std::vector< float_t > flattened_observation(const state_type &state)
Definition dqn.cpp:96
bitrl::utils::ExperienceBuffer< experience_tuple_type > experience_buffer_type
Definition dqn_experience_replay.cpp:108
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)
static value_type stack(const std::vector< T > &values, DeviceType type=DeviceType::CPU, bool requires_grad=false)