Skip to content
pockermanPublic

About

Reinforcement learning algorithms with c++ for bitsim

Topics

Resources

Contributing

Stars

8 stars

Watchers

1 watching

Forks

Repository files navigation

bitrl

bitrl is a C++20 library for reinforcement learning. It has environments, among them grid worlds, Connect2, multi-armed bandits, robots simulated in Chrono, and Gymnasium's environments over a REST API, and the algorithms that learn in them, from dynamic programming to proximal policy optimization. Its deep reinforcement learning uses libtorch, the C++ API of PyTorch. bitrl is built on bitsim, a library for robots, and the documentation of both is here.

Monte Carlo tree search weighing the commands of a robot A robot planning its way around a track with Monte Carlo tree search
Monte Carlo tree search drives bitsim's Chrono robot along a line and around boxes. Every 0.2 s it runs 400 simulations, 5 s ahead, in a fast model of the track. Each line is where one of the five commands leads; the robot takes the green one, and the wider an orange line, the more simulations tried its command. Example With nothing but those plans the robot goes once around the track in 47.7 s, without touching a box, faster than bitsim's hand written controller; each decision takes about 4 ms. Example

What is in it

Area What bitrl has
Environments grid worlds, Connect2, CartPole and a cart-pole swing-up without a server, multi-agent grid worlds and differential drive robots, multi-armed bandits, GymWalk, bitsim robots in Chrono, and Gymnasium's FrozenLake, CliffWalking, Taxi, Blackjack, CartPole, MountainCar, Pendulum, Acrobot and LunarLander over the bitrl-rest-api server
Dynamic programming iterative policy evaluation, policy iteration, value iteration
Monte Carlo first visit Monte Carlo, Monte Carlo tree search
Temporal difference SARSA, Q-learning, expected SARSA, double Q-learning
Multi-agent environments where agents act at once, a trainer, and independent Q-learning; every agent in a process or machine of its own, over MQTT
Policy gradients REINFORCE, with and without a baseline, A2C, PPO, PPO from several episodes at once, played by copies of the environment on threads, and PPO over several processes or machines that average their gradients
Evolution strategies the evolution strategy of Salimans et al., with antithetic pairs, rank shaping and Adam, its episodes on threads or over processes and machines that exchange only the returns; a small network that needs no libtorch
Policies epsilon-greedy with decay, soft-max, greedy and uniform tabular policies
Tools experience replay buffers, trainers, parallel runs on bitsim's thread pool, policies saved to and loaded from files, Tensorboard logging, PyTorch distributions and optimizers

Examples

The examples build on each other, from the basic ideas to deep reinforcement learning, and each has a page that explains it. They are listed in examples/examples.md. The Gymnasium environments run on the bitrl-rest-api server.

The basics

The PyTorch C++ API

Experiments

Environments

Algorithms

The algorithms at work

Every algorithm example ends by showing what it learned. Each GIF links to its example.

Thompson sampling and epsilon-greedy finding the best of five arms
Thompson sampling and epsilon-greedy finding the best of five arms
A soft-max policy on ten arms
A soft-max policy on ten arms
Iterative policy evaluation of the random policy on the slippery lake
Iterative policy evaluation of the random policy on the slippery lake
Policy iteration: the optimal policy in 4 iterations
Policy iteration: the optimal policy in 4 iterations
Value iteration: the values spread back from the goal in 7 sweeps
Value iteration: the values spread back from the goal in 7 sweeps
First visit Monte Carlo estimates of the same values from sampled episodes
First visit Monte Carlo estimates of the same values from sampled episodes
Q-learning, double Q-learning, expected SARSA and SARSA on CliffWalking
Q-learning, double Q-learning, expected SARSA and SARSA on CliffWalking
DQN: the shortest way around the wall and the pit
DQN: the shortest way around the wall and the pit
DQN with experience replay on random boards: 85 of 100 solved
DQN with experience replay on random boards: 85 of 100 solved
REINFORCE on CartPole: 126 steps
REINFORCE on CartPole: 126 steps
REINFORCE with a baseline: all 500 steps
REINFORCE with a baseline: all 500 steps
A2C: all 500 steps
A2C: all 500 steps
PPO: 339 steps
PPO: 339 steps
PPO on LunarLander: 9 of 10 landings
PPO on LunarLander: 9 of 10 landings

Robotics

These need bitsim built with Chrono.

Multi-agent

Two independent Q-learners share a corridor one cell wide
Independent Q-learning: one agent waits while the other crosses the corridor
Six decentralised robots cross a circle
Six decentralised robots cross a circle without touching

Evolution strategies

An evolution strategy swings a pole up and balances it
An evolution strategy learns to swing the pole up and balance it, with a continuous force

Installation

bitrl needs

  • a compiler that supports C++20, for example g++ 11
  • CMake 3.20 or later
  • Boost and Eigen
  • spdlog, which bitsim logs with
  • GoogleTest, if it is built with the tests

HTTPRequest and nlohmann/json come with bitsim.

bitsim and libtorch

bitrl is built on bitsim 5, which has to be installed first, see its install page. bitsim installs as the CMake package bitsim. bitrl also needs libtorch, built with the C++11 ABI, and TBB (sudo apt-get install libtbb-dev). Tell CMake where bitsim and libtorch are:

cmake -B build -DCMAKE_PREFIX_PATH="/path/to/bitsim/prefix;/path/to/libtorch"
cmake --build build --parallel 3

Give --parallel a number. Files that include libtorch take a lot of memory to compile, and an unlimited build runs out of memory on a 16 GB machine.

Add the Chrono prefix to CMAKE_PREFIX_PATH too if bitsim was built with Chrono and Chrono is not in a system prefix. ci/install_bitsim.sh and ci/install_libtorch.sh do both installs the way CI does.

Logging

bitrl logs with bitsim's logger, which writes with spdlog to standard error. bitrl's messages go to the logger named bitrl, and are written with the stream operator:

#include "bitrl/base/bitrl_log.h"

BITRL_LOG_INFO << "Episode " << episode << " reward " << reward;

Every logger writes info and above. To change that, call

bitrl::log::set_level("bitrl", bitrl::log::Level::warn);  // only warnings and above from bitrl
bitrl::log::set_level(bitrl::log::Level::debug);          // everything, from every logger
bitrl::log::add_file_sink("training.log");                // to a file as well

or set the SPDLOG_LEVEL environment variable, SPDLOG_LEVEL=bitrl=warn ./ppo_cartpole, without changing the code. bitsim's own messages go to the logger bitsim; its install page has the details.

Install

cmake -B build -DCMAKE_PREFIX_PATH="..." -DCMAKE_INSTALL_PREFIX=$HOME/opt/bitrl
cmake --build build --parallel 3
cmake --install build

installs lib/libbitrllib.so, the headers in include/bitrl/ and the CMake package in lib/cmake/bitrl/. Another project then uses bitrl with

find_package(bitrl 5 REQUIRED)
target_link_libraries(my_target PRIVATE bitrl::bitrl)

and -DCMAKE_PREFIX_PATH with the prefixes of bitrl, bitsim and libtorch. The package finds bitsim, libtorch and TBB itself. ci/check_install.sh checks that an installed bitrl works this way.

The options are ENABLE_EXAMPLES (ON), ENABLE_TESTS (OFF), USE_CUDA (OFF; libtorch must be built with CUDA too), BITRL_LOG (ON) and BITRL_WERROR (OFF), for example

cmake -B build -DCMAKE_PREFIX_PATH="..." -DENABLE_TESTS=ON
cmake --build build --parallel 3
ctest --test-dir build --output-on-failure

About

Reinforcement learning algorithms with c++ for bitsim

Topics

Resources

Contributing

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages