bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Independent learners in processes of their own

The two agents of Independent Q-learning in a corridor learn to share a corridor one cell wide with independent Q-learning. Here every agent learns in a participant of its own: a thread, a process, or a machine. Nothing else changes: the agents learn exactly the Q-tables they learn in one process, to the last bit.

What you need

Nothing beyond bitrl for the threads of one process. For processes, bitsim built with MQTT and a broker such as mosquitto; see bitsim's install page.

A copy of the world in every participant

There are two ways to split a multi-agent simulation. bitsim's distributed simulation gives every participant its own robots, and the participants send each other where their robots are. That suits a world that is expensive, or not repeatable, such as a Chrono simulation. In RL the environment is often cheap next to the agents, and repeatable. Then every participant can hold a copy of the whole environment, and only the actions need to travel.

DistributedAgentEnv does that. It wraps the participant's copy, made with the same options and seed as every other copy, and is the environment of one agent:

auto copy = make_env(); // the same options and seed everywhere
QLearningAgent learner(agent, copy.n_states(), copy.n_actions(), config);
DistributedAgentEnv<MultiAgentGridWorld> env(copy, agent, transport);
AgentTrainer<DistributedAgentEnv<MultiAgentGridWorld>, QLearningAgent> trainer({n_episodes}, learner);
trainer.train(env);

env.step(action) sends this agent's action, waits for the actions of the others at the same step, with bitsim's Synchroniser in lockstep, and steps the copy with the joint action. Every copy gets the same joint actions, so the copies stay alike. To make sure, every action comes with a checksum of the observation it was chosen from. If it is not the observation of that agent in this participant's copy, step() throws. That catches a copy made with other options, reset with another seed, or one that is not deterministic.

The learner is a QLearningAgent: one agent's Q-table and epsilon-greedy policy, whose generator is seeded from the seed and the index of the agent. IndependentQLearning is a team of them, so a QLearningAgent on its own learns what the same agent learns in the team. AgentTrainer is the training loop of MultiAgentTrainer for one agent.

Running the example

./distributed_independent_learners # in one process, then a thread per agent
./distributed_independent_learners --transport mqtt --agent 1 &
./distributed_independent_learners --transport mqtt --agent 0

The second and third lines run every agent in a process of its own, meeting on the broker at tcp://localhost:1883 (--broker for another). Each process also trains the team in one process, to tell whether it learned the same.

Output

1. The team in one process
4000 episodes, 90324 steps, in 0.02 s
the greedy team crossed in 15 steps, team return 1.70
2. A participant per agent
2 threads, one per agent, in 7.52 s: 83.2 microseconds per step for the exchange
the greedy team crossed in 15 steps, team return 1.70
every agent learned the same Q-table, and every episode had the same returns, as in one process: true

Over MQTT, with a broker that has set_tcp_nodelay true, the two processes took 11.7 s, 129 microseconds a step, and learned the same Q-tables. With mosquitto's default settings a step waits a few milliseconds for the broker to bundle small packets; see the note on brokers in bitsim's distributed simulation example.

The distributed training is much slower than the one in one process. Every step waits for a message from the other agent, and a step of a tabular Q-learner takes well under a microsecond. Splitting pays off when an agent is the expensive part, such as a neural network policy, or when it has to run somewhere else, on a robot's computer for one. The time per step is the price of the exchange, and it does not grow with what the agents compute.

Things to try

  1. Make one participant's copy with GridObservation::OWN_POSITION, and run the two processes. What does the first step say? Why does a different "seed" change nothing here?
  2. Start the two processes ten seconds apart. What does the first one do in the meantime?
  3. Give DistributedAgentConfig::timeout 1 s and stop one process half-way. What do you see in the other?

The code

// Two agents learn to cross a corridor with independent Q-learning, each in a participant of its
// own: a thread, a process or a machine. Every participant holds a copy of the grid world and
// learns only its own agent's Q-table; at every step the participants send each other their
// actions, and step their copies with the joint action. The copies stay alike, so the agents
// learn exactly what they learn in one process.
//
// Usage: distributed_independent_learners [--episodes N]
// distributed_independent_learners --transport mqtt --agent 0|1 [--episodes N] [--broker
// URL]
//
// In-process (the default) the example trains the team in one process, then with a thread per
// agent, and compares. With --transport mqtt every agent is a process of its own; start one with
// --agent 0 and one with --agent 1, on the same broker. Each also trains the team in one process,
// to tell whether it learned the same.
#include "bitsim/bitsim_config.h"
#ifdef BITSIM_MQTT
#endif
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
{
using namespace bitrl::envs::multi_agent;
using namespace bitrl::rl::multi_agent;
using steady = std::chrono::steady_clock;
// every participant makes its copy with the same options, and the same seed
{
env.make("v1", {{"observation", GridObservation::JOINT_POSITIONS}, {"shared_reward", true}},
{{"seed", uint_t(1)}});
return env;
}
{
config.eta = 0.2;
config.eps_decay = 5.0 / n_episodes;
return config;
}
real_t seconds(steady::duration d) { return std::chrono::duration<real_t>(d).count(); }
// What one participant learned, and how its greedy agent did with the others
struct Outcome
{
MultiAgentTrainingResult training;
MultiAgentEpisodeResult greedy;
};
// The participant of one agent: train it, then play a greedy episode with the others
Outcome participant(uint_t agent, Transport &transport, uint_t n_episodes)
{
auto copy = make_env();
QLearningAgent learner(agent, copy.n_states(), copy.n_actions(), learning(n_episodes));
agent_env_type env(copy, agent, transport);
AgentTrainer<agent_env_type, QLearningAgent> trainer({n_episodes}, learner);
Outcome outcome;
outcome.training = trainer.train(env);
auto greedy = learner.greedy();
outcome.greedy = run_agent_episode(env, greedy);
outcome.q_table = learner.q_table();
outcome.n_resent = env.synchroniser().n_resent();
env.leave();
return outcome;
}
// The same team in one process
struct Team
{
MultiAgentTrainingResult training;
MultiAgentEpisodeResult greedy;
std::vector<DynMat<real_t>> q_tables;
};
Team one_process(uint_t n_episodes)
{
auto env = make_env();
IndependentQLearning team(env.n_agents(), env.n_states(), env.n_actions(),
learning(n_episodes));
Team result;
result.training = trainer.train(env);
auto greedy = team.greedy();
result.greedy = run_episode(env, greedy);
for (uint_t a = 0; a < env.n_agents(); ++a)
{
result.q_tables.push_back(team.q_table(a));
}
return result;
}
{
uint_t n = 0;
for (const auto &e : training.episodes)
{
n += e.n_steps;
}
return n;
}
{
if (a.episodes.size() != b.episodes.size())
{
return false;
}
for (std::size_t e = 0; e < a.episodes.size(); ++e)
{
if (a.episodes[e].returns != b.episodes[e].returns)
{
return false;
}
}
return true;
}
{
std::cout << " the greedy team " << (greedy.all_done ? "crossed" : "did not cross") << " in "
<< greedy.n_steps << " steps, team return " << std::fixed << std::setprecision(2)
<< greedy.team_return() << "\n";
}
int run_in_process(uint_t n_episodes)
{
bitsim::utils::io::print_title("1. The team in one process");
auto start = steady::now();
const auto team = one_process(n_episodes);
const real_t t_one = seconds(steady::now() - start);
const uint_t n_steps = total_steps(team.training);
std::cout << " " << n_episodes << " episodes, " << n_steps << " steps, in " << std::fixed
<< std::setprecision(2) << t_one << " s\n";
report_greedy(team.greedy);
std::cout << "\n";
bitsim::utils::io::print_title("2. A participant per agent");
const uint_t n = make_env().n_agents();
std::vector<std::unique_ptr<Transport>> transports;
for (uint_t a = 0; a < n; ++a)
{
transports.push_back(bus.connect());
}
std::vector<Outcome> outcomes(n);
start = steady::now();
std::vector<std::thread> threads;
for (uint_t a = 0; a < n; ++a)
{
threads.emplace_back([&, a] { outcomes[a] = participant(a, *transports[a], n_episodes); });
}
for (auto &t : threads)
{
t.join();
}
const real_t t_distributed = seconds(steady::now() - start);
std::cout << " " << n << " threads, one per agent, in " << std::setprecision(2)
<< t_distributed << " s: " << std::setprecision(1) << 1e6 * t_distributed / n_steps
<< " microseconds per step for the exchange\n";
report_greedy(outcomes.front().greedy);
bool same = true;
for (uint_t a = 0; a < n; ++a)
{
same = same && outcomes[a].q_table == team.q_tables[a] &&
same_returns(outcomes[a].training, team.training);
}
std::cout << " every agent learned the same Q-table, and every episode had the same "
<< "returns, as in one process: " << std::boolalpha << same << "\n";
return same ? 0 : 1;
}
int run_mqtt(uint_t agent, uint_t n_episodes, const std::string &broker)
{
#ifdef BITSIM_MQTT
if (agent >= make_env().n_agents())
{
std::cerr << "--agent must be 0 or 1\n";
return 1;
}
bitsim::distributed::MQTT_Transport transport(broker, "distributed_independent_learners");
std::cout << " agent " << make_env().agent_name(agent) << ": waiting for the others on "
<< broker << "\n";
const auto start = steady::now();
const auto outcome = participant(agent, transport, n_episodes);
const real_t t = seconds(steady::now() - start);
std::cout << " " << n_episodes << " episodes in " << std::fixed << std::setprecision(2) << t
<< " s, " << std::setprecision(1) << 1e6 * t / total_steps(outcome.training)
<< " microseconds per step; sent its last steps again " << outcome.n_resent
<< " times\n";
report_greedy(outcome.greedy);
const auto team = one_process(n_episodes);
std::cout << " learned the same Q-table as the team in one process: " << std::boolalpha
<< (outcome.q_table == team.q_tables[agent]) << "\n";
return 0;
#else
(void)agent;
(void)n_episodes;
(void)broker;
std::cerr << "bitsim was built without MQTT\n";
return 1;
#endif
}
} // namespace distributed_independent_learners
int main(int argc, char **argv)
{
bitrl::uint_t n_episodes = 4000;
bitrl::uint_t agent = 0;
std::string transport = "inprocess", broker = "tcp://localhost:1883";
for (int i = 1; i + 1 < argc; i += 2)
{
const std::string flag = argv[i], value = argv[i + 1];
if (flag == "--episodes")
n_episodes = std::strtoul(value.c_str(), nullptr, 10);
else if (flag == "--transport")
transport = value;
else if (flag == "--agent")
agent = std::strtoul(value.c_str(), nullptr, 10);
else if (flag == "--broker")
broker = value;
else
{
std::cerr << "unknown option " << flag << "\n";
return 1;
}
}
if (transport == "mqtt")
{
return distributed_independent_learners::run_mqtt(agent, n_episodes, broker);
}
}
One agent of a multi-agent environment, in a process of its own.
Definition distributed_agent_env.h:151
uint_t n_agents() const noexcept
Definition multi_agent_env_base.h:79
const std::string & agent_name(uint_t agent) const
The name of an agent, for printing.
Definition multi_agent_env_base.h:84
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
Train one agent of a multi-agent environment, an episode at a time.
Definition agent_trainer.h:97
MultiAgentTrainingResult train(EnvType &env)
Run config.n_episodes episodes of training.
Definition agent_trainer.h:107
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
One agent of a multi-agent environment that learns its own Q-table with Q-learning,...
Definition q_learning_agent.h:40
Participants that are threads of one process, joined by queues.
Definition transport.h:57
How the participants of a distributed simulation reach each other: everything one publishes,...
Definition transport.h:34
int main()
Definition discounted_returns.cpp:19
Definition distributed_agent_env.h:19
@ JOINT_POSITIONS
its own cell and the cells of the others
Definition multi_agent_grid_world.h:36
Definition agent_trainer.h:14
MultiAgentEpisodeResult run_agent_episode(EnvType &env, ActorType &actor, const std::function< void(const typename EnvType::time_step_type &)> &on_step={})
Play one episode of env with the action of one agent chosen by actor.
Definition agent_trainer.h:63
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
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
Eigen::MatrixX< T > DynMat
Dynamically sized matrix to use around the library.
Definition bitsim_types.h:51
double real_t
real_t
Definition bitsim_types.h:20
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
Definition distributed_independent_learners.cpp:42
bool same_returns(const MultiAgentTrainingResult &a, const MultiAgentTrainingResult &b)
Definition distributed_independent_learners.cpp:137
Outcome participant(uint_t agent, Transport &transport, uint_t n_episodes)
Definition distributed_independent_learners.cpp:85
DistributedAgentEnv< MultiAgentGridWorld > agent_env_type
Definition distributed_independent_learners.cpp:53
int run_mqtt(uint_t agent, uint_t n_episodes, const std::string &broker)
Definition distributed_independent_learners.cpp:208
void report_greedy(const MultiAgentEpisodeResult &greedy)
Definition distributed_independent_learners.cpp:153
int run_in_process(uint_t n_episodes)
Definition distributed_independent_learners.cpp:160
uint_t total_steps(const MultiAgentTrainingResult &training)
Definition distributed_independent_learners.cpp:127
std::chrono::steady_clock steady
Definition distributed_independent_learners.cpp:51
real_t seconds(steady::duration d)
Definition distributed_independent_learners.cpp:73
MultiAgentGridWorld make_env()
Definition distributed_independent_learners.cpp:56
Team one_process(uint_t n_episodes)
Definition distributed_independent_learners.cpp:110
IndependentQLearningConfig learning(uint_t n_episodes)
Definition distributed_independent_learners.cpp:64
env
Definition play.py:33
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
What one episode of a multi-agent environment gave.
Definition multi_agent_trainer.h:48
uint_t n_steps
the joint steps of the episode
Definition multi_agent_trainer.h:50
real_t team_return() const noexcept
The sum of the returns of the agents.
Definition multi_agent_trainer.h:119
bool all_done
whether every agent finished, rather than the step limit
Definition multi_agent_trainer.h:52
What MultiAgentTrainer::train() gave: an entry per episode.
Definition multi_agent_trainer.h:84
std::vector< MultiAgentEpisodeResult > episodes
Definition multi_agent_trainer.h:85
Definition distributed_independent_learners.cpp:77
uint_t n_resent
Definition distributed_independent_learners.cpp:81
MultiAgentTrainingResult training
Definition distributed_independent_learners.cpp:78
MultiAgentEpisodeResult greedy
Definition distributed_independent_learners.cpp:79
DynMat< real_t > q_table
Definition distributed_independent_learners.cpp:80
Definition distributed_independent_learners.cpp:104
std::vector< DynMat< real_t > > q_tables
Definition distributed_independent_learners.cpp:107
MultiAgentEpisodeResult greedy
Definition distributed_independent_learners.cpp:106
MultiAgentTrainingResult training
Definition distributed_independent_learners.cpp:105