bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
parallel_ppo.h
Go to the documentation of this file.
1#ifndef PARALLEL_PPO_H
2#define PARALLEL_PPO_H
3
4#include "bitrl/base/bitrl_config.h"
5
6#ifdef USE_PYTORCH
7
14
15#include <torch/torch.h>
16
17#include <chrono>
18#include <memory>
19#include <tuple>
20#include <type_traits>
21#include <vector>
22
23namespace bitrl
24{
25namespace rl::algos::pg
26{
27
54template <typename EnvType, typename PolicyType, typename CriticType>
56 : public ACSolverBase<envs::ParallelEnvs<EnvType>, PolicyType, CriticType,
57 A2CMonitor<typename EnvType::action_type, typename EnvType::state_type>,
58 PPOConfig>
59{
60 public:
62 typedef PolicyType policy_type;
63 typedef CriticType critic_type;
64 typedef typename EnvType::state_type state_type;
65 typedef typename EnvType::action_type action_type;
69
70 ParallelPPOSolver(const PPOConfig &config, policy_type &policy, critic_type &critic,
71 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
72 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer)
73 : base_type(config, policy, critic, policy_optimizer, critic_optimizer)
74 {
75 }
76
82
86 const std::vector<real_t> &last_returns() const noexcept { return last_returns_; }
87
88 protected:
93 virtual void on_gradients_() {}
94
95 private:
96 // what one copy played
97 struct Episode
98 {
99 std::vector<std::vector<float_t>> states;
100 std::vector<std::vector<float_t>> actions;
101 std::vector<real_t> rewards;
102 std::vector<float_t> log_probs;
103 std::vector<float_t> values;
104 };
105
106 template <typename T> static std::vector<float_t> as_floats_(const T &value);
107
108 static action_type action_from_(const torch::Tensor &actions, int64_t row);
109
110 real_t learn_(const std::vector<Episode> &episodes);
111
112 std::vector<real_t> last_returns_;
113};
114
115template <typename EnvType, typename PolicyType, typename CriticType>
116template <typename T>
117std::vector<float_t> ParallelPPOSolver<EnvType, PolicyType, CriticType>::as_floats_(const T &value)
118{
119 if constexpr (std::is_arithmetic_v<T>)
120 {
121 return {static_cast<float_t>(value)};
122 }
123 else
124 {
125 return std::vector<float_t>(value.begin(), value.end());
126 }
127}
128
129template <typename EnvType, typename PolicyType, typename CriticType>
131ParallelPPOSolver<EnvType, PolicyType, CriticType>::action_from_(const torch::Tensor &actions,
132 int64_t row)
133{
134 const auto a = actions[row].to(torch::kDouble).contiguous();
135 if constexpr (std::is_arithmetic_v<action_type>)
136 {
137 return static_cast<action_type>(a.template item<double>());
138 }
139 else
140 {
141 const auto flat = a.view({-1});
142 action_type out(static_cast<std::size_t>(flat.numel()));
143 for (int64_t k = 0; k < flat.numel(); ++k)
144 {
145 out[k] = static_cast<typename action_type::value_type>(flat[k].template item<double>());
146 }
147 return out;
148 }
149}
150
151template <typename EnvType, typename PolicyType, typename CriticType>
153 uint_t round)
154{
155 const auto start = std::chrono::steady_clock::now();
156 const uint_t n = envs.size();
157 std::vector<Episode> episodes(n);
158 uint_t n_steps = 0;
159
160 {
161 torch::NoGradGuard no_grad;
162 envs.reset();
163 std::vector<action_type> actions(n, action_type{});
164 for (uint_t t = 0; t < this->config_.max_itrs_per_episode && !envs.all_done(); ++t)
165 {
166 // the copies still playing, and their states, in one batch
167 std::vector<uint_t> active;
168 std::vector<std::vector<float_t>> rows;
169 for (uint_t i = 0; i < n; ++i)
170 {
171 if (!envs.done(i))
172 {
173 active.push_back(i);
174 rows.push_back(as_floats_(envs.time_steps()[i].observation()));
175 }
176 }
177 const auto width = static_cast<int64_t>(rows.front().size());
178 std::vector<float_t> flat;
179 flat.reserve(rows.size() * rows.front().size());
180 for (const auto &row : rows)
181 {
182 flat.insert(flat.end(), row.begin(), row.end());
183 }
184 const auto states =
185 torch::from_blob(flat.data(), {static_cast<int64_t>(rows.size()), width},
186 torch::TensorOptions().dtype(torch::kFloat32))
187 .clone();
188
189 auto [batch_actions, log_probs] = this->policy_->act_batch(states);
190 const auto values = this->critic_->forward(states).view({-1});
191 const auto lp = log_probs.view({-1}).to(torch::kFloat32).contiguous();
192 const auto v = values.to(torch::kFloat32).contiguous();
193
194 for (std::size_t r = 0; r < active.size(); ++r)
195 {
196 actions[active[r]] = action_from_(batch_actions, static_cast<int64_t>(r));
197 }
198 const auto &next = envs.step(actions);
199 for (std::size_t r = 0; r < active.size(); ++r)
200 {
201 auto &e = episodes[active[r]];
202 e.states.push_back(rows[r]);
203 e.actions.push_back(as_floats_(actions[active[r]]));
204 e.rewards.push_back(next[active[r]].reward());
205 e.log_probs.push_back(lp[static_cast<int64_t>(r)].template item<float_t>());
206 e.values.push_back(v[static_cast<int64_t>(r)].template item<float_t>());
207 }
208 n_steps += static_cast<uint_t>(active.size());
209 }
210 }
211
212 last_returns_.assign(n, 0.0);
213 real_t mean_return = 0.0;
214 for (uint_t i = 0; i < n; ++i)
215 {
216 for (const real_t r : episodes[i].rewards)
217 {
218 last_returns_[i] += r;
219 }
220 mean_return += last_returns_[i] / n;
221 }
222
223 const real_t loss = learn_(episodes);
224 this->monitor_.rewards.push_back(mean_return);
225 this->monitor_.policy_loss_values.push_back(loss);
226 this->monitor_.episode_duration.push_back(n_steps);
227
228 EpisodeInfo info;
229 info.episode_index = round;
230 info.episode_reward = mean_return;
231 info.episode_iterations = n_steps;
232 info.total_time = std::chrono::steady_clock::now() - start;
233 return info;
234}
235
236template <typename EnvType, typename PolicyType, typename CriticType>
237real_t
238ParallelPPOSolver<EnvType, PolicyType, CriticType>::learn_(const std::vector<Episode> &episodes)
239{
240 // the discounted return of every step, within its own episode
241 std::vector<float_t> returns, old_values, old_log_probs, state_data, action_data;
242 int64_t n_rows = 0, state_width = 0, action_width = 0;
243 for (const auto &e : episodes)
244 {
245 std::vector<float_t> g(e.rewards.size());
246 real_t running = 0.0;
247 for (std::size_t k = e.rewards.size(); k-- > 0;)
248 {
249 running = e.rewards[k] + this->config_.gamma * running;
250 g[k] = static_cast<float_t>(running);
251 }
252 returns.insert(returns.end(), g.begin(), g.end());
253 old_values.insert(old_values.end(), e.values.begin(), e.values.end());
254 old_log_probs.insert(old_log_probs.end(), e.log_probs.begin(), e.log_probs.end());
255 for (std::size_t k = 0; k < e.states.size(); ++k)
256 {
257 state_width = static_cast<int64_t>(e.states[k].size());
258 action_width = static_cast<int64_t>(e.actions[k].size());
259 state_data.insert(state_data.end(), e.states[k].begin(), e.states[k].end());
260 action_data.insert(action_data.end(), e.actions[k].begin(), e.actions[k].end());
261 ++n_rows;
262 }
263 }
264 if (n_rows == 0)
265 {
266 return 0.0;
267 }
268
269 const auto f32 = torch::TensorOptions().dtype(torch::kFloat32);
270 const auto states = torch::from_blob(state_data.data(), {n_rows, state_width}, f32).clone();
271 const auto actions = torch::from_blob(action_data.data(), {n_rows, action_width}, f32).clone();
272 const auto g = torch::from_blob(returns.data(), {n_rows}, f32).clone();
273 const auto values = torch::from_blob(old_values.data(), {n_rows}, f32).clone();
274 const auto old_lp = torch::from_blob(old_log_probs.data(), {n_rows}, f32).clone();
275
276 auto advantages = g - values;
277 if (this->config_.normalize_advantages && n_rows > 1)
278 {
279 advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8);
280 }
281
282 real_t total = 0.0;
283 for (uint_t p = 0; p < this->config_.max_passes_over_batch; ++p)
284 {
285 auto [new_log_probs, entropy, _] = this->policy_->evaluate(states, actions);
286 const auto ratio = (new_log_probs.view({-1}) - old_lp).exp();
287 const auto surr1 = ratio * advantages;
288 const auto surr2 =
289 torch::clamp(ratio, 1 - this->config_.clip_epsilon, 1 + this->config_.clip_epsilon) *
290 advantages;
291 const auto actor_loss = -torch::min(surr1, surr2).mean();
292 const auto critic_loss =
293 torch::nn::functional::mse_loss(this->critic_->forward(states).view({-1}), g);
294 const auto loss = actor_loss + 0.5 * critic_loss - 0.01 * entropy;
295
296 this->policy_optimizer_->zero_grad();
297 this->critic_optimizer_->zero_grad();
298 loss.backward();
299 on_gradients_();
300 total += loss.template item<real_t>();
301 this->policy_optimizer_->step();
302 this->critic_optimizer_->step();
303 }
304 return this->config_.max_passes_over_batch ? total / this->config_.max_passes_over_batch : 0.0;
305}
306
307} // namespace rl::algos::pg
308} // namespace bitrl
309
310#endif // USE_PYTORCH
311#endif // PARALLEL_PPO_H
Several copies of an environment, stepped at the same time on the threads of a bitsim::utils::concurr...
Definition parallel_envs.h:36
ACSolverBase(const config_type &config, policy_type &policy, critic_type &critic, std::unique_ptr< torch::optim::Optimizer > &policy_optimizer, std::unique_ptr< torch::optim::Optimizer > &critic_optimizer)
Definition actor_critic_solver_base.h:193
PolicyType policy_type
Definition parallel_ppo.h:62
ParallelPPOSolver(const PPOConfig &config, policy_type &policy, critic_type &critic, std::unique_ptr< torch::optim::Optimizer > &policy_optimizer, std::unique_ptr< torch::optim::Optimizer > &critic_optimizer)
Definition parallel_ppo.h:70
EnvType::action_type action_type
Definition parallel_ppo.h:65
envs::ParallelEnvs< EnvType > env_type
Definition parallel_ppo.h:61
CriticType critic_type
Definition parallel_ppo.h:63
virtual void on_gradients_()
Called after every backward pass, before the optimisers step, with the gradients of both networks in ...
Definition parallel_ppo.h:93
EnvType::state_type state_type
Definition parallel_ppo.h:64
EpisodeInfo on_training_episode(env_type &envs, uint_t round) override
Play an episode in every copy and learn from all of them; the reward of the EpisodeInfo is the mean r...
Definition parallel_ppo.h:152
const std::vector< real_t > & last_returns() const noexcept
The return of every episode of the last round.
Definition parallel_ppo.h:86
ACSolverBase< env_type, PolicyType, CriticType, A2CMonitor< action_type, state_type >, PPOConfig > base_type
Definition parallel_ppo.h:68
Definition a2c.h:37
Definition with_dynamics_mixin.h:14
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
float float_t
float
Definition bitsim_types.h:25
double real_t
real_t
Definition bitsim_types.h:20
std::array< real_t, 2 > action_type
Definition multi_robot_navigation.cpp:40
_
Definition play.py:39
The EpisodeInfo struct.
Definition episode_info.h:21
The PPOConfig struct. Configuration for PPOSolver class.
Definition ppo_config.h:26