bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
a2c.h
Go to the documentation of this file.
1#ifndef A2C_H
2#define A2C_H
3
10
11#include "bitrl/base/bitrl_config.h"
12
13#ifdef USE_PYTORCH
14
22//#include "bitrl/utils/experience_buffer.h"
23
24#include <torch/torch.h>
25
26#ifdef BITRL_DEBUG
27#include <cassert>
28#endif
29
30#include <chrono>
31#include <memory>
32#include <tuple>
33
34namespace bitrl
35{
37{
38
52template <typename EnvType, typename PolicyType, typename CriticType>
53class A2CSolver final : public RLSolverBase<EnvType>
54{
55 public:
59 typedef EnvType env_type;
60
64 typedef PolicyType policy_type;
65
69 typedef CriticType critic_type;
70
71 typedef typename env_type::state_type state_type;
72 typedef typename env_type::action_type action_type;
73
74 typedef
76
82 A2CSolver(const A2CConfig &config, policy_type &policy, critic_type &critic,
83 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
84 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer);
85
91
96 virtual void actions_after_training_ends(env_type &) override final {}
97
101 virtual void actions_before_episode_begins(env_type &, uint_t /*episode_idx*/) override final {}
102
106 virtual void actions_after_episode_ends(env_type &, uint_t /*episode_idx*/,
107 const EpisodeInfo &) override final
108 {
109 }
110
114 virtual EpisodeInfo on_training_episode(env_type &, uint_t /*episode_idx*/);
115
119 void set_train_mode() noexcept;
120
124 void set_evaluation_mode() noexcept;
125
130
131 private:
135 A2CConfig config_;
136
140 policy_type &policy_;
141
145 critic_type &critic_;
146
151
155 std::unique_ptr<torch::optim::Optimizer> policy_optimizer_;
156
160 std::unique_ptr<torch::optim::Optimizer> critic_optimizer_;
161
166 uint_t create_episode_batch_(env_type &, uint_t /*episode_idx*/,
167 experience_buffer_type &buffer);
168
169 std::tuple<real_t, real_t> train_with_batch_(experience_buffer_type &buffer);
170};
171
172template <typename EnvType, typename PolicyType, typename CriticType>
174 const A2CConfig &config, policy_type &policy, critic_type &critic,
175 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
176 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer)
177 : config_(config), policy_(policy), critic_(critic), monitor_(),
178 policy_optimizer_(std::move(policy_optimizer)), critic_optimizer_(std::move(critic_optimizer))
179{
180}
181
182template <typename EnvType, typename PolicyType, typename CriticType>
184{
185 policy_->train();
186 critic_->train();
187}
188
189template <typename EnvType, typename PolicyType, typename CriticType>
191{
192 policy_->eval();
193 critic_->eval();
194}
195
196template <typename EnvType, typename PolicyType, typename CriticType>
198{
199
200 monitor_.reset();
201 monitor_.policy_loss_values.reserve(config_.n_episodes);
202 monitor_.critic_loss_values.reserve(config_.n_episodes);
203 monitor_.rewards.reserve(config_.n_episodes);
204 monitor_.episode_duration.reserve(config_.n_episodes);
206}
207
208template <typename EnvType, typename PolicyType, typename CriticType>
210 uint_t episode_idx)
211{
212
213 auto start = std::chrono::steady_clock::now();
214
215 // the buffer to use
216 experience_buffer_type buffer(config_.max_itrs_per_episode);
217
218 // collect the buffer
219 auto eps_itrs = create_episode_batch_(env, episode_idx, buffer);
220
221 // train the networks with from the
222 // collected buffer
223 auto [episode_reward, total_episode_loss] = train_with_batch_(buffer);
224
225 auto end = std::chrono::steady_clock::now();
226 std::chrono::duration<real_t> elapsed_seconds = end - start;
227
228 monitor_.episode_duration.push_back(eps_itrs);
229
230 EpisodeInfo info;
231 info.episode_index = episode_idx;
232 info.episode_reward = episode_reward;
233 info.episode_iterations = eps_itrs;
234 info.total_time = elapsed_seconds;
235 return info;
236}
237
238template <typename EnvType, typename PolicyType, typename CriticType>
239uint_t A2CSolver<EnvType, PolicyType, CriticType>::create_episode_batch_(
240 env_type &env, uint_t /*episode_idx*/, experience_buffer_type &buffer)
241{
244 typedef
246
247 // reset the environment
248 // for every episode reset the environment
249 auto old_timestep = env.reset();
250
251 // loop over the iterations
252 uint_t itrs = 0;
253 for (; itrs < config_.max_itrs_per_episode; ++itrs)
254 {
255
256 auto [action, log_prob] = policy_->act(old_timestep.observation());
257 auto values = critic_->evaluate(old_timestep.observation());
258
259 // step into the environment
260 auto next_time_step = env.step(action);
261
262 auto next_state = next_time_step.observation();
263 auto reward = next_time_step.reward();
264
265 experience_tuple_type exp = {old_timestep.observation(), action, reward,
266 next_time_step.done(), log_prob, values};
267
268 // put the observation into the buffer
269 buffer.append(exp);
270
271 if (next_time_step.done())
272 {
273 break;
274 }
275
276 old_timestep = next_time_step;
277 }
278
279 return itrs + 1;
280}
281
282template <typename EnvType, typename PolicyType, typename CriticType>
283std::tuple<real_t, real_t>
284A2CSolver<EnvType, PolicyType, CriticType>::train_with_batch_(experience_buffer_type &buffer)
285{
286
287 // because of the way we treat the values
288 // we loose the requires_grad so we need to set it
289 using namespace bitrl::utils::pytorch;
290
291 typedef
292 typename A2CMonitor<action_type, state_type>::experience_tuple_type experience_tuple_type;
293 typedef std::vector<experience_tuple_type> batch_type;
294
295 // the batch for this episode
296 auto batch = buffer.template get<batch_type>();
297 auto rewards_batch = monitor_.template get<real_t, 2>(batch);
298 auto values_batch = monitor_.template get<torch_tensor_t, 5>(batch);
299 auto logprobs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
300
301 // compute the discounted rewards for this batch
302 auto discounted_returns =
303 bitrl::rl::algos::calculate_step_discounted_return(rewards_batch, config_.gamma);
304
305 auto torch_rewards_batch =
306 TorchAdaptor::to_torch(discounted_returns, config_.device_type, false);
307
308 auto torch_values_batch = TorchAdaptor::stack(values_batch, config_.device_type);
309
310 auto torch_logprobs_batch = TorchAdaptor::stack(logprobs_batch, config_.device_type);
311
312 // form the advantage
313 auto advantage = torch_rewards_batch - torch_values_batch;
314
315 // take the mean because we collect batches
316 auto actor_loss = -(torch_logprobs_batch * advantage.detach()).mean();
317 auto critic_loss = advantage.pow(2).mean();
318
319 if (config_.clip_policy_grad)
320 {
321
322 // clip the grad if needed
323 torch::nn::utils::clip_grad_norm_(policy_->parameters(), config_.max_grad_norm_policy);
324 }
325
326 if (config_.clip_critic_grad)
327 {
328 torch::nn::utils::clip_grad_norm_(critic_->parameters(), config_.max_grad_norm_critic);
329 }
330
331 // Backward pass and optimize
332 policy_optimizer_->zero_grad();
333 critic_optimizer_->zero_grad();
334
335 actor_loss.backward();
336 critic_loss.backward();
337
338 policy_optimizer_->step();
339 critic_optimizer_->step();
340
341 auto total_episode_policy_loss = actor_loss.item().template to<real_t>();
342 auto total_episode_critic_loss = critic_loss.item().template to<real_t>();
343
344 // compute the undiscounted reward as the reward
345 // for this episode
346 auto R = bitrl::maths::sum(rewards_batch);
347
348 monitor_.policy_loss_values.push_back(total_episode_policy_loss);
349 monitor_.critic_loss_values.push_back(total_episode_critic_loss);
350 monitor_.rewards.push_back(R);
351
352 return std::make_tuple(R, total_episode_policy_loss + total_episode_critic_loss);
353}
354
355} // namespace rl::algos::pg
356} // namespace bitrl
357#endif
358#endif // A2C_H
RLSolverBase()=default
Constructor.
EnvType env_type
The environment type.
Definition a2c.h:59
void set_evaluation_mode() noexcept
set_evaluation_mode for both the Actor and the Critic
Definition a2c.h:190
CriticType critic_type
The critic type.
Definition a2c.h:69
virtual void actions_after_episode_ends(env_type &, uint_t, const EpisodeInfo &) override final
actions_after_training_episode
Definition a2c.h:106
PolicyType policy_type
The policy or action type.
Definition a2c.h:64
virtual void actions_before_episode_begins(env_type &, uint_t) override final
actions_before_training_episode
Definition a2c.h:101
void set_train_mode() noexcept
set_train_mode for both the Actor and the Critic
Definition a2c.h:183
A2CMonitor< action_type, state_type >::experience_buffer_type experience_buffer_type
Definition a2c.h:75
env_type::action_type action_type
Definition a2c.h:72
A2CSolver(const A2CConfig &config, policy_type &policy, critic_type &critic, std::unique_ptr< torch::optim::Optimizer > &policy_optimizer, std::unique_ptr< torch::optim::Optimizer > &critic_optimizer)
A2C.
Definition a2c.h:173
A2CMonitor< action_type, state_type > & get_monitor()
Read-write access to the monitor object.
Definition a2c.h:129
virtual EpisodeInfo on_training_episode(env_type &, uint_t)
on_episode Do one on_episode of the algorithm
Definition a2c.h:209
virtual void actions_before_training_begins(env_type &)
actions_before_training_begins. Execute any actions the algorithm needs before starting the iteration...
Definition a2c.h:197
virtual void actions_after_training_ends(env_type &) override final
actions_after_training_ends. Actions to execute after the training iterations have finisehd
Definition a2c.h:96
env_type::state_type state_type
Definition a2c.h:71
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
Definition a2c.h:37
std::vector< T > calculate_step_discounted_return(const std::vector< T > &rewards, T gamma)
Given an array of rewards, for each entry calculate the following: $$G = \sum_{k=t+1}...
Definition utils.h:151
Definition torch_adaptor.h:18
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
@ R
Definition fixed_wing_dynamics.h:39
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
The EpisodeInfo struct.
Definition episode_info.h:21
The A2CConfig struct. Configuration for A2CSolver class.
Definition a2c_config.h:26
Definition a2c_monitor.h:24
std::tuple< state_type, action_type, real_t, bool, torch_tensor_t, torch_tensor_t > experience_tuple_type
Definition a2c_monitor.h:35
bitrl::utils::ExperienceBuffer< experience_tuple_type > experience_buffer_type
Definition a2c_monitor.h:37
static value_type to_torch(const std::vector< real_t > &data, DeviceType dtype=DeviceType::CPU, bool requires_grad=false)
static value_type stack(const std::vector< T > &values, DeviceType type=DeviceType::CPU, bool requires_grad=false)