bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Independent Q-learning in a corridor

Two agents start in opposite rooms of a grid and each has to reach the far corner of the other room. The rooms are joined by a corridor one cell wide, so the shortest paths of the two meet in it, and one agent has to let the other through:

#########
#A.###.B#
#.......#
#b.###.a#
#########

A goes to a and B to b. This is bitrl::envs::multi_agent::MultiAgentGridWorld, bitrl's first multi-agent environment. Every step both agents move at once: up, right, down, left or stay. Moves that would put the two in one cell, or make them swap cells, are cancelled, and the agents that tried to move get a penalty. Every step costs -0.05, and reaching the goal is worth 1. The example shares the reward: each agent gets the sum of both rewards, so they win or lose together.

Multi-agent environments in bitrl

A multi-agent environment derives from MultiAgentEnvBase. Its step() takes a joint action, one action per agent, and returns a MultiAgentTimeStep with an observation, a reward and a done flag for every agent. An agent that is done waits for the others; the episode ends when all are done, or at the step limit. This is the "parallel" form that PettingZoo also uses; a turn-based game fits it as well, by ignoring the agents whose turn it is not.

Independent Q-learning

The simplest way to learn with several agents is to let every agent learn on its own, as if the others were part of the environment. IndependentQLearning gives every agent its own Q-table and its own epsilon-greedy policy, and each agent updates its table from its own observation, action and reward:

\[Q_i(o_i, a_i) \leftarrow Q_i(o_i, a_i) + \eta \left[r_i + \gamma \max_{a} Q_i(o'_i, a) - Q_i(o_i, a_i)\right] \]

MultiAgentTrainer runs the episodes: the team chooses a joint action, the environment applies it, and the team learns from the transition.

What an agent observes decides what it can learn. With GridObservation::OWN_POSITION an agent knows only its own cell: it cannot tell whether the corridor is free, so whatever path it learns it takes whether the other agent is in the way or not. With GridObservation::JOINT_POSITIONS its observation is both cells, \(45 \times 45 = 2025\) states, and it can learn to wait.

Training in parallel

Each training has its own environment and learner, so trainings with different seeds share nothing, and the example runs all of them at once with bitsim::utils::concurrency::parallel_map:

const auto runs = parallel_map(2 * n_seeds, [=](std::size_t k) {
return train_one(k, n_seeds, n_episodes); // seed task_seed(1, k % n_seeds)
});

The results come back in the order of k, whatever order the threads finish in, so the output is the same on any number of threads; the example also trains every team in a plain loop, to time one thread, and checks that both learned the same. Every agent explores with its own random generator, seeded with task_seed(); a generator shared between threads would be a data race.

Results

32 trainings of 4000 episodes in a plain loop: 1.34 s; on the 8 threads of the pool and this one: 0.43 s, a speed-up of 3.09
every training learned the same in both: true
observation solved mean steps collisions final return
own position 0/16 0.0 11.2 -2.53
joint positions 16/16 15.2 0.0 0.76

Over 16 seeds, no team that sees only its own position learned to cross: their greedy agents walk into each other in the corridor and stay stuck there until the step limit. Every team that sees both positions solved it in about 15 steps without a collision: one agent waits in its room while the other comes through. The speed-up, about 3 over several runs, is smaller than the number of threads: the laptop has four cores with two threads each, each training takes only about 40 ms, and parallel_map hands each thread a chunk of consecutive trainings, so the chunks of the first half, the teams that see only their own position and often play to the step limit, take longer than the others.

The greedy team of the first seed that sees both agents. A crosses first while B steps aside and waits; then B follows.

The example writes returns.csv, the mean team return per episode of both kinds of team, and layout.txt and episode.csv, the greedy episode above. examples/tools/multi_agent_gif.py makes the GIF:

./multi_agent_grid_world [--episodes 4000] [--seeds 16]
python examples/tools/multi_agent_gif.py grid layout.txt episode.csv --out multi_agent_grid_world.gif

Things to try

  1. Turn off shared_reward. Does the agent that waits still learn to wait, when waiting costs it and helps only the other?
  2. Add a third agent with a layout of your own. How many states does a joint observation need now, and how much longer does training take?
  3. Give the agents a cheaper observation: their own cell and whether the corridor is free.

The driver code

// Two agents learn to cross a corridor one cell wide from opposite ends, with independent
// Q-learning. Each agent learns its own Q-table; one team sees only its own position, the other
// also sees where the other agent is. Every team is trained with many seeds, all of them at the
// same time on the threads of bitsim's thread pool.
//
// Usage: multi_agent_grid_world [--episodes N] [--seeds N]
//
// Writes returns.csv (the mean return of the team per episode, for both observations), and
// layout.txt and episode.csv (the map, and the greedy episode of a team that sees both agents) to
// the working directory.
// examples/tools/multi_agent_gif.py turns episode.csv into a GIF.
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
{
using namespace bitrl::envs::multi_agent;
using namespace bitrl::rl::multi_agent;
// What one training gave
struct Run
{
std::vector<real_t> team_returns; // per episode
bool solved{false}; // the greedy team reached both goals
IndependentQLearning learner;
};
{
env.make("v1", {{"observation", observation}, {"shared_reward", true}}, {});
return env;
}
// Train one team from scratch; every call has its own environment and learner, so that many
// can run at once
Run train(GridObservation observation, uint_t seed, uint_t n_episodes)
{
auto env = make_env(observation);
config.seed = seed;
config.eta = 0.2;
config.eps_decay = 5.0 / n_episodes;
IndependentQLearning learner(env.n_agents(), env.n_states(), env.n_actions(), config);
const auto training = trainer.train(env);
Run run{{}, false, 0, 0, learner};
for (const auto &episode : training.episodes)
{
run.team_returns.push_back(episode.returns.front()); // shared: every agent has the same
}
auto greedy = learner.greedy();
const auto result = run_episode(env, greedy);
run.solved = result.all_done;
run.greedy_steps = result.n_steps;
run.greedy_collisions = result.n_collisions;
return run;
}
// Training k of 2 n_seeds: the first n_seeds teams see their own position, the others both;
// training k has seed task_seed(1, k % n_seeds)
Run train_one(std::size_t k, uint_t n_seeds, uint_t n_episodes)
{
const auto observation =
k < n_seeds ? GridObservation::OWN_POSITION : GridObservation::JOINT_POSITIONS;
return train(observation, bitsim::utils::concurrency::task_seed(1, k % n_seeds), n_episodes);
}
void summarise(const std::string &name, const std::vector<Run> &runs)
{
uint_t solved = 0, steps = 0, collisions = 0;
real_t final_return = 0.0;
for (const auto &run : runs)
{
if (run.solved)
{
++solved;
steps += run.greedy_steps;
}
collisions += run.greedy_collisions;
// the mean return of the last tenth of the episodes
const auto tail = std::max<std::size_t>(1, run.team_returns.size() / 10);
real_t sum = 0.0;
for (auto i = run.team_returns.size() - tail; i < run.team_returns.size(); ++i)
{
sum += run.team_returns[i];
}
final_return += sum / tail;
}
std::cout << std::setw(18) << name << std::setw(10) << solved << "/" << runs.size()
<< std::setw(14) << std::fixed << std::setprecision(1)
<< (solved ? static_cast<real_t>(steps) / solved : 0.0) << std::setw(16)
<< static_cast<real_t>(collisions) / runs.size() << std::setw(16)
<< std::setprecision(2) << final_return / runs.size() << "\n";
}
void write_returns(const std::vector<Run> &own, const std::vector<Run> &joint)
{
std::ofstream out("returns.csv");
out << "episode,own_position,joint_positions\n";
for (uint_t e = 0; e < own.front().team_returns.size(); ++e)
{
real_t a = 0.0, b = 0.0;
for (const auto &run : own)
{
a += run.team_returns[e];
}
for (const auto &run : joint)
{
b += run.team_returns[e];
}
out << e << "," << a / own.size() << "," << b / joint.size() << "\n";
}
}
// Play the greedy team of run and print and record its steps
void show(const Run &run, GridObservation observation)
{
auto env = make_env(observation);
env.reset();
std::ofstream("layout.txt") << env.render();
std::ofstream out("episode.csv");
out << "step,agent,row,col,done\n";
uint_t k = 0;
auto greedy = run.learner.greedy();
run_episode(env, greedy,
{
for (uint_t a = 0; a < env.n_agents(); ++a)
{
out << k << "," << env.agent_name(a) << "," << env.positions()[a].first
<< "," << env.positions()[a].second << "," << step.done(a) << "\n";
}
if (k % 2 == 0 || step.last())
{
std::cout << " step " << k << (step.last() ? ", the last" : "") << "\n";
std::cout << env.render() << "\n";
}
++k;
});
}
void run(uint_t n_episodes, uint_t n_seeds)
{
bitsim::utils::io::print_title("1. The corridor");
MultiAgentGridWorld env = make_env(GridObservation::OWN_POSITION);
env.reset();
std::cout << env.render()
<< "\nA goes to a, B to b. The shortest paths meet in the corridor, so "
<< "one agent has to wait.\n\n";
bitsim::utils::io::print_title("2. Training, in parallel");
// the same trainings, once in a plain loop on this thread and once on all the threads
auto start = std::chrono::steady_clock::now();
std::vector<Run> serial_runs;
for (std::size_t k = 0; k < 2 * n_seeds; ++k)
{
serial_runs.push_back(train_one(k, n_seeds, n_episodes));
}
const std::chrono::duration<real_t> serial = std::chrono::steady_clock::now() - start;
start = std::chrono::steady_clock::now();
const auto runs =
parallel_map(2 * n_seeds, [=](std::size_t k) { return train_one(k, n_seeds, n_episodes); });
const std::chrono::duration<real_t> parallel = std::chrono::steady_clock::now() - start;
// every training has its own generators, so the threads change nothing
bool same = true;
for (std::size_t k = 0; k < runs.size(); ++k)
{
same = same && runs[k].team_returns == serial_runs[k].team_returns;
}
std::cout << " " << 2 * n_seeds << " trainings of " << n_episodes
<< " episodes in a plain loop: " << std::fixed << std::setprecision(2)
<< serial.count() << " s; on the "
<< " threads of the pool and this one: " << parallel.count() << " s, a speed-up of "
<< serial.count() / parallel.count() << "\n"
<< " every training learned the same in both: " << std::boolalpha << same << "\n\n";
const std::vector<Run> own(runs.begin(), runs.begin() + n_seeds);
const std::vector<Run> joint(runs.begin() + n_seeds, runs.end());
bitsim::utils::io::print_title("3. What the greedy teams do");
std::cout << " observation solved mean steps collisions final return\n";
summarise("own position", own);
summarise("joint positions", joint);
write_returns(own, joint);
std::cout << "\n The mean return per episode is in returns.csv\n\n";
bitsim::utils::io::print_title("4. A team that sees both agents");
const auto best =
std::find_if(joint.begin(), joint.end(), [](const Run &r) { return r.solved; });
if (best == joint.end())
{
std::cout << " no team solved the corridor; train for more episodes\n";
return;
}
show(*best, GridObservation::JOINT_POSITIONS);
std::cout << " The episode is in episode.csv\n";
}
} // namespace multi_agent_grid_world
int main(int argc, char **argv)
{
bitrl::uint_t n_episodes = 4000;
bitrl::uint_t n_seeds = 16;
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i];
if (flag == "--episodes")
{
n_episodes = std::strtoul(argv[i + 1], nullptr, 10);
}
else if (flag == "--seeds")
{
n_seeds = std::strtoul(argv[i + 1], nullptr, 10);
}
}
multi_agent_grid_world::run(n_episodes, n_seeds);
return 0;
}
Agents that walk a grid at the same time, each to its own goal, without bumping into each other.
Definition multi_agent_grid_world.h:65
base_type::time_step_type time_step_type
Definition multi_agent_grid_world.h:68
Every agent learns its own Q-table with Q-learning, as if the others were part of the environment.
Definition independent_q_learning.h:40
Train a team of learners on a multi-agent environment, an episode at a time.
Definition multi_agent_trainer.h:99
MultiAgentTrainingResult train(env_type &env)
Run config.n_episodes episodes of training.
Definition multi_agent_trainer.h:185
uint_t size() const noexcept
The number of threads.
Definition thread_pool.h:54
int main()
Definition discounted_returns.cpp:19
Definition distributed_agent_env.h:19
GridObservation
What an agent of MultiAgentGridWorld observes.
Definition multi_agent_grid_world.h:34
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
Definition agent_trainer.h:14
MultiAgentEpisodeResult run_episode(EnvType &env, ActorType &actor, const std::function< void(const typename EnvType::time_step_type &)> &on_step={})
Play one episode: reset env, then let actor choose the joint actions until the episode is over.
Definition multi_agent_trainer.h:160
uint_t task_seed(uint_t base_seed, uint_t task) noexcept
A seed for task task, made from base_seed.
Definition parallel.h:148
auto parallel_map(std::size_t n, F &&f, ThreadPool &pool=default_thread_pool()) -> std::vector< std::invoke_result_t< F &, std::size_t > >
Compute f(0), f(1), ..., f(n - 1) on the threads of pool.
Definition parallel.h:119
ThreadPool & default_thread_pool()
The pool that parallel_for() and parallel_map() use when given none. It starts ThreadPool::default_n_...
Definition thread_pool.cpp:77
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
Definition multi_agent_grid_world.cpp:30
void show(const Run &run, GridObservation observation)
Definition multi_agent_grid_world.cpp:138
void summarise(const std::string &name, const std::vector< Run > &runs)
Definition multi_agent_grid_world.cpp:90
auto parallel_map(std::size_t n, F &&f, ThreadPool &pool=default_thread_pool()) -> std::vector< std::invoke_result_t< F &, std::size_t > >
Compute f(0), f(1), ..., f(n - 1) on the threads of pool.
Definition parallel.h:119
void write_returns(const std::vector< Run > &own, const std::vector< Run > &joint)
Definition multi_agent_grid_world.cpp:118
MultiAgentGridWorld make_env(GridObservation observation)
Definition multi_agent_grid_world.cpp:48
Run train_one(std::size_t k, uint_t n_seeds, uint_t n_episodes)
Definition multi_agent_grid_world.cpp:83
Run train(GridObservation observation, uint_t seed, uint_t n_episodes)
Definition multi_agent_grid_world.cpp:57
void run(uint_t n_episodes, uint_t n_seeds)
Definition multi_agent_grid_world.cpp:164
observation
Definition play.py:49
env
Definition play.py:33
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
The settings of a Q-learning agent among others, and of IndependentQLearning.
Definition q_learning_agent.h:19
real_t eta
the learning rate
Definition q_learning_agent.h:21
real_t eps_decay
eps = eps_min + (eps_max - eps_min) exp(-eps_decay * episode)
Definition q_learning_agent.h:24
uint_t seed
every agent explores with its own generator, seeded from this
Definition q_learning_agent.h:25
Definition multi_agent_grid_world.cpp:40
uint_t greedy_steps
Definition multi_agent_grid_world.cpp:43
uint_t greedy_collisions
Definition multi_agent_grid_world.cpp:44
std::vector< real_t > team_returns
Definition multi_agent_grid_world.cpp:41
bool solved
Definition multi_agent_grid_world.cpp:42
IndependentQLearning learner
Definition multi_agent_grid_world.cpp:45