-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathLaunchParallelCartPole.cpp
266 lines (216 loc) · 7.24 KB
/
LaunchParallelCartPole.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* Copyright (C) 2019 Istituto Italiano di Tecnologia (IIT)
* All rights reserved.
*
* This software may be modified and distributed under the terms of the
* GNU Lesser General Public License v2.1 or any later version.
*/
#include "gympp/Environment.h"
#include "gympp/GymFactory.h"
#include "gympp/Log.h"
#include "gympp/PluginDatabase.h"
#include "gympp/Random.h"
#include "gympp/Space.h"
#include "clara.hpp"
#include <ignition/common/SignalHandler.hh>
#include <atomic>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <utility>
#include <vector>
using namespace gympp;
using namespace clara;
class Worker
{
private:
size_t m_id;
size_t m_maxEpisodes;
std::string m_environmentName;
EnvironmentPtr m_env;
static std::mutex m_mutex;
public:
// Global variable shared by worker threads
static std::atomic<size_t> BestScore;
static std::atomic<size_t> InstanceCounter;
static std::atomic<size_t> NumberOfEpisodes;
static std::atomic<double> MovingAverageReward;
using EnvironmentName = std::string;
Worker(const EnvironmentName& name, size_t maxEpisodes)
: m_id(Worker::InstanceCounter++)
, m_maxEpisodes(maxEpisodes)
, m_environmentName(name)
{
gymppDebug << "Constructing worker #" << m_id;
}
bool initialize()
{
m_env = GymFactory::Instance()->make(m_environmentName);
if (!m_env) {
gymppError << "Failed to create environment '" << m_environmentName << "'" << std::endl;
return false;
}
return true;
}
void run()
{
// This check the number of episodes of all workers
while (Worker::NumberOfEpisodes <= (m_maxEpisodes - std::thread::hardware_concurrency())) {
// Reset the environment
assert(m_env);
auto reward = Environment::Reward(0);
auto observation = m_env->reset();
assert(observation);
// Create the initial state object
Environment::State oldState;
oldState.done = false;
oldState.observation = observation.value();
size_t episodeStep = 0;
while (!oldState.done) {
// Process oldState to obtain the action.
// Here we use a random action to bypass it.
auto actionSample = m_env->action_space->sample();
// Simulate the system with the given action
auto state = m_env->step(actionSample);
assert(state && state->observation.getBuffer<double>());
// Cumulate the reward
reward += state->reward;
// Save the old state
oldState = std::move(state.value());
// Increase the episode steps counter
episodeStep++;
// Handle termination
if (state->done) {
std::unique_lock lock(Worker::m_mutex);
// Increase the episodes counter
Worker::NumberOfEpisodes++;
record(NumberOfEpisodes, reward, m_id, episodeStep);
// Handle this episode if it is the best achieved until now
if (reward > Worker::BestScore) {
// CartPole rewards are integers
Worker::BestScore = static_cast<size_t>(reward);
gymppMessage << "New best score: " << reward << std::endl;
}
}
}
}
}
static void record(const size_t episode,
const Reward reward,
const size_t worker_id,
const size_t numOfSteps)
{
if (Worker::MovingAverageReward == 0.0) {
Worker::MovingAverageReward = reward;
}
else {
Worker::MovingAverageReward = Worker::MovingAverageReward * 0.99 + reward * 0.01;
}
std::cout << "Episode: " << episode
<< " | Moving Average Reward: " << Worker::MovingAverageReward
<< " | Episode reward: " << reward << " | Steps: " << numOfSteps
<< " | Worker: " << worker_id << std::endl;
}
};
// Define static attributes
std::mutex Worker::m_mutex;
std::atomic<size_t> Worker::BestScore = 0;
std::atomic<size_t> Worker::InstanceCounter = 0;
std::atomic<size_t> Worker::NumberOfEpisodes = 0;
std::atomic<double> Worker::MovingAverageReward = 0;
class MasterAgent
{
private:
size_t m_maxEpisodes;
std::vector<std::unique_ptr<Worker>> m_workers;
std::vector<std::thread> m_pool;
const gympp::EnvironmentName EnvName = "CartPole";
public:
MasterAgent(const size_t maxEpisodes)
: m_maxEpisodes(maxEpisodes)
{}
bool train()
{
unsigned threadAffinity = std::thread::hardware_concurrency();
gymppMessage << "Machine supports " << threadAffinity << " concurrent threads" << std::endl;
for (size_t i = 0; i < threadAffinity; ++i) {
// Create the worker
m_workers.emplace_back(std::make_unique<Worker>(EnvName, m_maxEpisodes));
auto& worker = m_workers.back();
if (!worker->initialize()) {
return false;
}
// Add its run method in the thread pool
m_pool.emplace_back(&Worker::run, &*m_workers.back());
}
for (auto& thread : m_pool) {
thread.join();
}
return true;
}
void reset()
{
for (auto& worker : m_workers) {
worker.reset();
}
}
};
struct Config
{
bool help = false;
bool train = false;
size_t maxEpisodes = 100;
std::optional<size_t> seed;
};
int main(int argc, char* argv[])
{
// ==================
// PARSE COMMAND LINE
// ==================
Config config;
// Create the command line parser
auto cli =
Help(config.help) //
| Opt(config.maxEpisodes, "n")["-m"]["--max-episodes"]("Maximum number of episodes to run")
| Opt(config.train)["-t"]["--train"]("Train the model")
| Opt([&](unsigned value) { config.seed = value; },
"seed")["-s"]["--seed"]("use a specific seed for randomness");
// Parse the command line
if (auto result = cli.parse(Args(argc, argv)); !result) {
gymppError << "Error in command line: " << result.errorMessage() << std::endl;
exit(EXIT_FAILURE);
}
if (config.help) {
std::cout << cli;
exit(EXIT_SUCCESS);
}
// ====================
// INITIALIZE THE AGENT
// ====================
if (config.seed) {
Random::setSeed(config.seed.value());
}
// Create the master agent
MasterAgent agent(config.maxEpisodes);
// Terminate the agent gracefully
ignition::common::SignalHandler sigHandler;
assert(sigHandler.Initialized());
sigHandler.AddCallback([&](const int /*_sig*/) {
gymppDebug << "Shutting down gracefully" << std::endl;
agent.reset();
exit(EXIT_FAILURE);
});
// =====
// TRAIN
// =====
bool ok = agent.train();
if (!ok) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}