-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgym.h
More file actions
368 lines (326 loc) · 14.1 KB
/
gym.h
File metadata and controls
368 lines (326 loc) · 14.1 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#ifndef GYM_H
#define GYM_H
#include <memory>
#include <tuple>
#include <vector>
#include <future>
#include <optional>
#include <unordered_map>
#include <string>
#include <torch/torch.h>
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio.hpp>
using namespace std;
using namespace torch;
struct env_info
{
float r; // return
int l; // length of episode
float t; // Episode time length in seconds.
};
class Environment {
public:
virtual tuple<Tensor, float, bool, bool> step(const Tensor& action) = 0;
virtual Tensor reset(int seed) = 0;
[[nodiscard]] virtual int get_observation_space() const = 0;
[[nodiscard]] virtual int get_action_space() const = 0;
[[nodiscard]] virtual float get_action_space_min() const = 0;
[[nodiscard]] virtual float get_action_space_max() const = 0;
virtual ~Environment() = default;
};
class EnvironmentWrapper {
public:
virtual tuple<Tensor, float, bool, bool, optional<env_info>> step(const Tensor& action) = 0;
virtual Tensor reset(int seed) = 0;
[[nodiscard]] virtual int get_observation_space() const = 0;
[[nodiscard]] virtual int get_action_space() const = 0;
[[nodiscard]] virtual float get_action_space_min() const = 0;
[[nodiscard]] virtual float get_action_space_max() const = 0;
virtual ~EnvironmentWrapper() = default;
};
class EnvironmentCarla {
public:
virtual tuple<unordered_map<string, Tensor>, float, bool, bool> step(const Tensor& action) = 0;
virtual unordered_map<string, Tensor> reset(int seed) = 0;
[[nodiscard]] virtual vector<int> get_observation_space() const = 0;
[[nodiscard]] virtual int get_action_space() const = 0;
[[nodiscard]] virtual float get_action_space_min() const = 0;
[[nodiscard]] virtual float get_action_space_max() const = 0;
virtual ~EnvironmentCarla() = default;
};
class EnvironmentWrapperCarla {
public:
virtual tuple<unordered_map<string, Tensor>, float, bool, bool, optional<env_info>> step(const Tensor& action) = 0;
virtual unordered_map<string, Tensor> reset(int seed) = 0;
[[nodiscard]] virtual vector<int> get_observation_space() const = 0;
[[nodiscard]] virtual int get_action_space() const = 0;
[[nodiscard]] virtual float get_action_space_min() const = 0;
[[nodiscard]] virtual float get_action_space_max() const = 0;
virtual ~EnvironmentWrapperCarla() = default;
};
// Comparable to gymnasiums SyncVectorEnv.
class SeqVectorEnv {
private:
std::vector<shared_ptr<EnvironmentWrapper>> env_array_;
Tensor obs_;
Tensor rewards_;
Tensor terminations_;
Tensor truncations_;
vector<optional<env_info>> infos_;
vector<bool> autoreset_envs_;
const bool clip_actions_;
public:
const unsigned int num_envs_;
SeqVectorEnv(const std::vector<shared_ptr<EnvironmentWrapper>>& env_array, const bool clip_actions):
env_array_(env_array), clip_actions_(clip_actions), num_envs_(env_array.size())
{
for (int i = 0; i < num_envs_; ++i) {
autoreset_envs_.push_back(false);
infos_.emplace_back();
}
obs_ = torch::zeros({num_envs_, env_array_[0]->get_observation_space()});
rewards_ = torch::zeros({num_envs_});
terminations_ = torch::zeros({num_envs_});
truncations_ = torch::zeros({num_envs_});
}
~SeqVectorEnv() = default;
Tensor reset(const int seed) {
torch::NoGradGuard no_grad;
for (int i = 0; i < env_array_.size(); ++i) {
const auto next_obs = env_array_[i]->reset(seed+i);
obs_.index({i}) = next_obs;
autoreset_envs_[i] = false;
}
return obs_;
}
[[nodiscard]] unsigned int get_num_envs() const {
return num_envs_;
}
[[nodiscard]] int get_observation_space() const {
return env_array_[0]->get_observation_space();
}
[[nodiscard]] int get_action_space() const {
return env_array_[0]->get_action_space();
}
[[nodiscard]] float get_action_space_min() const {
return env_array_[0]->get_action_space_min();
}
[[nodiscard]] float get_action_space_max() const {
return env_array_[0]->get_action_space_max();
}
tuple<Tensor, Tensor, Tensor, Tensor, vector<optional<env_info>>> step(const Tensor& actions) {
torch::NoGradGuard no_grad;
Tensor clipped_actions;
if (clip_actions_) {
clipped_actions = torch::clamp(actions, env_array_[0]->get_action_space_min(), env_array_[0]->get_action_space_max());
}
else {
clipped_actions = actions;
}
for (int i = 0; i < env_array_.size(); ++i) {
if (autoreset_envs_.at(i)) {
// -1 == do not reseed the environment
const auto next_obs = env_array_[i]->reset(-1);
obs_.slice(0, i,i+1) = next_obs;
rewards_.accessor<float,1>()[i] = 0.0f;
terminations_.accessor<float,1>()[i] = static_cast<float>(false);
truncations_.accessor<float,1>()[i] = static_cast<float>(false);
infos_[i] = nullopt;
autoreset_envs_.at(i) = false;
}
else {
auto [next_obs, reward, termination, truncation, info] = env_array_[i]->step(clipped_actions.index({i}));
obs_.slice(0, i,i+1) = next_obs;
rewards_.accessor<float,1>()[i] = reward;
terminations_.accessor<float,1>()[i] = static_cast<float>(termination);
truncations_.accessor<float,1>()[i] = static_cast<float>(truncation);
infos_[i] = info;
autoreset_envs_.at(i) = (termination or truncation);
}
}
return make_tuple(obs_, rewards_, terminations_, truncations_, infos_);
}
};
// Comparable to gymnasiums SyncVectorEnv.
class SeqVectorEnvCarla {
private:
std::vector<shared_ptr<EnvironmentWrapperCarla>> env_array_;
unordered_map<string, Tensor> obs_;
Tensor rewards_;
Tensor terminations_;
Tensor truncations_;
vector<optional<env_info>> infos_;
vector<bool> autoreset_envs_;
const bool clip_actions_;
public:
const unsigned int num_envs_;
SeqVectorEnvCarla(const std::vector<shared_ptr<EnvironmentWrapperCarla>>& env_array, const bool clip_actions):
env_array_(env_array), clip_actions_(clip_actions), num_envs_(env_array.size())
{
for (int i = 0; i < num_envs_; ++i) {
autoreset_envs_.push_back(false);
infos_.emplace_back();
}
auto obs_space = env_array_[0]->get_observation_space();
obs_["bev_semantics"] = torch::zeros({num_envs_, obs_space[0], obs_space[1], obs_space[2]}, torch::kUInt8);
obs_["measurements"] = torch::zeros({num_envs_, obs_space[3]});
obs_["value_measurements"] = torch::zeros({num_envs_, obs_space[4]});
rewards_ = torch::zeros({num_envs_});
terminations_ = torch::zeros({num_envs_});
truncations_ = torch::zeros({num_envs_});
}
~SeqVectorEnvCarla() = default;
unordered_map<string, Tensor> reset(const int seed) {
torch::NoGradGuard no_grad;
for (int i = 0; i < env_array_.size(); ++i) {
auto next_obs = env_array_[i]->reset(seed+i);
obs_["bev_semantics"].index_put_({i}, next_obs["bev_semantics"]);
obs_["measurements"].index_put_({i}, next_obs["measurements"]);
obs_["value_measurements"].index_put_({i}, next_obs["value_measurements"]);
autoreset_envs_[i] = false;
}
return obs_;
}
[[nodiscard]] unsigned int get_num_envs() const {
return num_envs_;
}
[[nodiscard]] vector<int> get_observation_space() const {
return env_array_[0]->get_observation_space();
}
[[nodiscard]] int get_action_space() const {
return env_array_[0]->get_action_space();
}
[[nodiscard]] float get_action_space_min() const {
return env_array_[0]->get_action_space_min();
}
[[nodiscard]] float get_action_space_max() const {
return env_array_[0]->get_action_space_max();
}
tuple<unordered_map<string, Tensor>, Tensor, Tensor, Tensor, vector<optional<env_info>>> step(const Tensor& actions) {
torch::NoGradGuard no_grad;
Tensor clipped_actions;
if (clip_actions_) {
clipped_actions = torch::clamp(actions, env_array_[0]->get_action_space_min(), env_array_[0]->get_action_space_max());
}
else {
clipped_actions = actions;
}
for (int i = 0; i < env_array_.size(); ++i) {
if (autoreset_envs_.at(i)) {
// -1 == do not reseed the environment
auto next_obs = env_array_[i]->reset(-1);
obs_["bev_semantics"].index_put_({i}, next_obs["bev_semantics"]);
obs_["measurements"].index_put_({i},next_obs["measurements"]);
obs_["value_measurements"].index_put_({i}, next_obs["value_measurements"]);
rewards_.accessor<float,1>()[i] = 0.0f;
terminations_.accessor<float,1>()[i] = static_cast<float>(false);
truncations_.accessor<float,1>()[i] = static_cast<float>(false);
infos_[i] = nullopt;
autoreset_envs_.at(i) = false;
}
else {
auto [next_obs, reward, termination, truncation, info] = env_array_[i]->step(clipped_actions.index({i}));
obs_["bev_semantics"].index_put_({i}, next_obs["bev_semantics"]);
obs_["measurements"].index_put_({i}, next_obs["measurements"]);
obs_["value_measurements"].index_put_({i}, next_obs["value_measurements"]);
rewards_.accessor<float,1>()[i] = reward;
terminations_.accessor<float,1>()[i] = static_cast<float>(termination);
truncations_.accessor<float,1>()[i] = static_cast<float>(truncation);
infos_[i] = info;
autoreset_envs_.at(i) = (termination or truncation);
}
}
unordered_map<string, Tensor> obs_copy;
obs_copy["bev_semantics"] = obs_["bev_semantics"].detach().clone();
obs_copy["measurements"] = obs_["measurements"].detach().clone();
obs_copy["value_measurements"] = obs_["value_measurements"].detach().clone();
return make_tuple(obs_copy, rewards_.detach().clone(), terminations_.detach().clone(), truncations_.detach().clone(), infos_);
}
};
// Comparable to gymnasiums AsyncVectorEnv but implemented with threads instead of mutli-processes.
class ParVectorEnv {
private:
std::vector<shared_ptr<EnvironmentWrapper>> env_array_;
Tensor obs_;
Tensor rewards_;
Tensor terminations_;
Tensor truncations_;
// NOTE: All vectors can be written to in parallel except for vector<bool>, so I use int here.
vector<int> autoreset_envs_;
vector<optional<env_info>> infos_;
const bool clip_actions_;
std::unique_ptr<boost::asio::thread_pool> pool_;
std::vector<std::future<void>> results_;
public:
const unsigned int num_envs_;
ParVectorEnv(const std::vector<shared_ptr<EnvironmentWrapper>>& env_array, const bool clip_actions):
env_array_(env_array), clip_actions_(clip_actions), num_envs_(env_array.size())
{
for (int i = 0; i < num_envs_; ++i) {
autoreset_envs_.push_back(false);
results_.emplace_back();
infos_.emplace_back();
}
obs_ = torch::zeros({num_envs_, env_array_[0]->get_observation_space()});
rewards_ = torch::zeros({num_envs_});
terminations_ = torch::zeros({num_envs_});
truncations_ = torch::zeros({num_envs_});
pool_ = make_unique<boost::asio::thread_pool>(num_envs_);
}
~ParVectorEnv() = default;
Tensor reset(const int seed) {
torch::NoGradGuard no_grad;
for (int i = 0; i < env_array_.size(); ++i) {
const auto next_obs = env_array_[i]->reset(seed+i);
obs_.index({i}) = next_obs;
autoreset_envs_[i] = false;
}
return obs_;
}
[[nodiscard]] unsigned int get_num_envs() const {
return num_envs_;
}
tuple<Tensor, Tensor, Tensor, Tensor, vector<optional<env_info>>> step(const Tensor& actions) {
torch::NoGradGuard no_grad;
Tensor clipped_actions;
if (clip_actions_) {
clipped_actions = torch::clamp(actions, env_array_[0]->get_action_space_min(), env_array_[0]->get_action_space_max());
}
else {
clipped_actions = actions;
}
for (int i = 0; i < env_array_.size(); ++i) {
// Important to copy i by value since it will change during the loop
auto forward_env_i = [this, &clipped_actions, i]
{
if (autoreset_envs_[i]) {
// -1 == do not reseed the environment
const auto next_obs = env_array_[i]->reset(-1);
obs_.slice(0, i,i+1) = next_obs;
rewards_.accessor<float,1>()[i] = 0.0f;
terminations_.accessor<float,1>()[i] = static_cast<float>(false);
truncations_.accessor<float,1>()[i] = static_cast<float>(false);
infos_[i] = nullopt;
autoreset_envs_[i] = false;
}
else {
auto [next_obs, reward, termination, truncation, info] = env_array_[i]->step(clipped_actions.index({i}));
obs_.slice(0, i,i+1) = next_obs;
rewards_.accessor<float,1>()[i] = reward;
terminations_.accessor<float,1>()[i] = static_cast<float>(termination);
truncations_.accessor<float,1>()[i] = static_cast<float>(truncation);
infos_[i] = info;
autoreset_envs_[i] = (termination or truncation);
}
};
results_.at(i) = boost::asio::post(pool_->get_executor(), boost::asio::use_future(forward_env_i));
}
// Wait until all environments are finished.
for (int i = 0; i < env_array_.size(); ++i) {
results_.at(i).get();
}
return make_tuple(obs_, rewards_, terminations_, truncations_, infos_);
}
};
#endif //GYM_H