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:
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]
\]
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.
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:
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.
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
{
struct Run
{
};
{
env.make(
"v1", {{
"observation",
observation}, {
"shared_reward",
true}}, {});
}
{
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());
}
auto greedy = learner.greedy();
run.solved = result.all_done;
run.greedy_steps = result.n_steps;
run.greedy_collisions = result.n_collisions;
}
{
k < n_seeds ? GridObservation::OWN_POSITION : GridObservation::JOINT_POSITIONS;
}
void summarise(
const std::string &name,
const std::vector<Run> &runs)
{
uint_t solved = 0, steps = 0, collisions = 0;
for (
const auto &
run : runs)
{
{
++solved;
steps +=
run.greedy_steps;
}
collisions +=
run.greedy_collisions;
const auto tail = std::max<std::size_t>(1,
run.team_returns.size() / 10);
for (
auto i =
run.team_returns.size() - tail; i <
run.team_returns.size(); ++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)
{
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";
}
}
{
std::ofstream(
"layout.txt") <<
env.render();
std::ofstream out("episode.csv");
out << "step,agent,row,col,done\n";
auto greedy =
run.learner.greedy();
{
{
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;
});
}
{
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";
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 =
const std::chrono::duration<real_t> parallel = std::chrono::steady_clock::now() -
start;
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());
std::cout << " observation solved mean steps collisions final return\n";
std::cout << "\n The mean return per episode is in returns.csv\n\n";
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";
}
}
int main(
int argc,
char **argv)
{
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);
}
}
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
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