bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
reinforce.h
Go to the documentation of this file.
1#ifndef REINFORCE_H
2#define REINFORCE_H
3
9
10#include "bitrl/base/bitrl_config.h"
11
12#ifdef USE_PYTORCH
13
22//#include "bitrl/data_structs/experience_buffer.h"
25
26#include <torch/torch.h>
27
28#include <vector>
29
30#include <chrono>
31#include <iostream>
32#include <iterator>
33#include <memory>
34#include <numeric>
35#include <string>
36#include <tuple>
37
38namespace bitrl
39{
40namespace rl
41{
42namespace algos
43{
44namespace pg
45{
46
58template <typename EnvType, typename PolicyType>
59class ReinforceSolver final : public RLSolverBase<EnvType>
60{
61 public:
62 typedef EnvType env_type;
63 typedef PolicyType policy_type;
64
65 typedef typename env_type::state_type state_type;
66 typedef typename env_type::action_type action_type;
69
74 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer);
75
81
87
91 virtual void actions_before_episode_begins(env_type &, uint_t /*episode_idx*/) {}
92
96 virtual void actions_after_episode_ends(env_type &, uint_t /*episode_idx*/,
97 const EpisodeInfo & /*einfo*/)
98 {
99 }
100
104 virtual EpisodeInfo on_training_episode(env_type &, uint_t /*episode_idx*/);
105
110
111 private:
115 ReinforceConfig config_;
116
120 policy_type policy_ptr_;
121
125 std::unique_ptr<torch::optim::Optimizer> policy_optimizer_;
126
131
137 uint_t create_episode_batch_(env_type &env, experience_buffer_type &buffer);
138
143 std::tuple<real_t, real_t> train_batch_(experience_buffer_type &buffer);
144
149 std::tuple<real_t, real_t> train_sequential_(experience_buffer_type &buffer);
150
154 std::tuple<real_t, real_t> train_without_baseline_(experience_buffer_type &buffer);
155
159 std::tuple<real_t, real_t> train_with_baseline_(experience_buffer_type &buffer);
160};
161
162template <typename EnvType, typename PolicyType>
164 ReinforceConfig config, policy_type &policy,
165 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer)
166 : RLSolverBase<EnvType>(), config_(config), policy_ptr_(policy),
167 policy_optimizer_(std::move(policy_optimizer)), monitor_()
168
169{
170}
171
172template <typename EnvType, typename PolicyType>
174{
175
176 monitor_.policy_loss_values.reserve(config_.n_episodes);
177 monitor_.rewards.reserve(config_.n_episodes);
178 monitor_.episode_duration.reserve(config_.n_episodes);
179
180 // set the policy to train mode
181 policy_ptr_->train();
182}
183
184template <typename EnvType, typename PolicyType>
185uint_t ReinforceSolver<EnvType, PolicyType>::create_episode_batch_(env_type &env,
187{
188
191
193 experience_tuple_type;
194
195 // for every episode reset the environment
196 auto old_timestep = env.reset();
197
198 // iterate over the given number
199 // of iterations for the episode and create
200 // the trajectory. The trajectory may be less
201 // than config_.max_itrs_per_episode
202
203 uint_t itr = 0;
204 for (; itr < config_.max_itrs_per_episode; ++itr)
205 {
206
207 // from the policy get the action to do based
208 // on the seen state.
209 auto [action, log_prob] = policy_ptr_->act(old_timestep.observation());
210
211 // execute the selected action on the environment
212 auto new_timestep = env.step(action);
213 auto reward = new_timestep.reward();
214
215 experience_tuple_type exp = {old_timestep.observation(), action, reward,
216 new_timestep.done(), log_prob};
217
218 // put the observation into the buffer
219 buffer.append(exp);
220
221 if (new_timestep.done())
222 {
223 break;
224 }
225
226 old_timestep = new_timestep;
227 }
228
229 // because we start from zero
230 return itr + 1;
231}
232
233template <typename EnvType, typename PolicyType>
235 uint_t episode_idx)
236{
237
238 // start the time for the episode
239 auto start = std::chrono::steady_clock::now();
240
241 // the buffer to use
242 experience_buffer_type buffer(config_.max_itrs_per_episode);
243
244 // Accummulate the data i.e. create the
245 // batch data we need to train the parameters
246 auto itrs = create_episode_batch_(env, buffer);
247
248 EpisodeInfo info;
249 if (config_.baseline_type == bitrl::rl::algos::pg::BaselineEnumType::NONE)
250 {
251
252 auto [episode_reward, total_episode_loss] = train_without_baseline_(buffer);
253 info.episode_reward = episode_reward;
254 }
255 else
256 {
257
258 auto [episode_reward, total_episode_loss] = train_with_baseline_(buffer);
259 info.episode_reward = episode_reward;
260 }
261 monitor_.episode_duration.push_back(itrs);
262
263 auto end = std::chrono::steady_clock::now();
264 std::chrono::duration<real_t> elapsed_seconds = end - start;
265
266 // the info class to return for the episode
267 info.episode_index = episode_idx;
268 info.episode_iterations = itrs;
269 info.total_time = elapsed_seconds;
270 return info;
271}
272
273template <typename EnvType, typename PolicyType>
274std::tuple<real_t, real_t>
275ReinforceSolver<EnvType, PolicyType>::train_batch_(experience_buffer_type &buffer)
276{
277
279 experience_tuple_type;
280
281 typedef std::vector<experience_tuple_type> batch_type;
282
283 // the batch for this episode
284 auto batch = buffer.template get<batch_type>();
285
286 // create the batches
287 auto reward_batch = monitor_.template get<real_t, 2>(batch);
288 auto log_probs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
289
290 // compute the discounted rewards for this batch
291 auto discounted_returns =
292 bitrl::rl::algos::calculate_step_discounted_return(reward_batch, config_.gamma);
293
294 if (config_.normalize_rewards)
295 {
296 discounted_returns = bitrl::maths::normalize_max(discounted_returns);
297 }
298
299 std::vector<torch_tensor_t> loss_vals = compute_loss_item(discounted_returns, log_probs_batch);
300
301 auto loss =
302 bitrl::utils::pytorch::TorchAdaptor::stack(loss_vals, config_.device_type, true).sum();
303 policy_optimizer_->zero_grad();
304 loss.backward();
305 policy_optimizer_->step();
306
307 auto total_episode_loss = loss.item().to<real_t>();
308
309 // compute the undiscounted reward as the reward
310 // for this episode
311 auto R = bitrl::maths::sum(reward_batch);
312 return std::make_tuple(R, total_episode_loss);
313}
314
315template <typename EnvType, typename PolicyType>
316std::tuple<real_t, real_t>
317ReinforceSolver<EnvType, PolicyType>::train_sequential_(experience_buffer_type &buffer)
318{
319
320 typedef typename ReinforceMonitor<action_type, state_type>::experience_tuple_type
321 experience_tuple_type;
322
323 typedef std::vector<experience_tuple_type> batch_type;
324
325 // the batch for this episode
326 auto batch = buffer.template get<batch_type>();
327
328 // create the batches
329 auto reward_batch = monitor_.template get<real_t, 2>(batch);
330 auto log_probs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
331
332 // compute the discounted rewards for this batch
333 auto discounted_returns =
334 bitrl::rl::algos::calculate_step_discounted_return(reward_batch, config_.gamma);
335
336 if (config_.normalize_rewards)
337 {
338 discounted_returns = bitrl::maths::normalize_max(discounted_returns);
339 }
340
341 std::vector<torch_tensor_t> loss_vals = compute_loss_item(discounted_returns, log_probs_batch);
342
343 // auto device = config_.device_type != DeviceType::CPU ? torch::kCUDA : torch::kCPU;
344
345 auto total_episode_loss = 0.0;
346 for (uint_t l = 0; l < loss_vals.size(); ++l)
347 {
348
349 auto loss = loss_vals[l];
350 policy_optimizer_->zero_grad();
351 loss.backward();
352 policy_optimizer_->step();
353
354 total_episode_loss += loss.item().to<real_t>();
355 }
356
357 auto R = bitrl::maths::sum(reward_batch);
358 return std::make_tuple(R, total_episode_loss / loss_vals.size());
359}
360
361template <typename EnvType, typename PolicyType>
362std::tuple<real_t, real_t>
363ReinforceSolver<EnvType, PolicyType>::train_without_baseline_(experience_buffer_type &buffer)
364{
365
366 if (config_.train_type == bitrl::utils::TrainEnumType::BATCH)
367 {
368
369 auto [episode_reward, total_episode_loss] = train_batch_(buffer);
370 monitor_.policy_loss_values.push_back(total_episode_loss);
371 monitor_.rewards.push_back(episode_reward);
372 return std::make_tuple(episode_reward, total_episode_loss);
373 }
374 else
375 {
376
377 auto [episode_reward, total_episode_loss] = train_sequential_(buffer);
378 monitor_.policy_loss_values.push_back(total_episode_loss);
379 monitor_.rewards.push_back(episode_reward);
380 return std::make_tuple(episode_reward, total_episode_loss);
381 }
382}
383
384template <typename EnvType, typename PolicyType>
385std::tuple<real_t, real_t>
386ReinforceSolver<EnvType, PolicyType>::train_with_baseline_(experience_buffer_type &buffer)
387{
388
391 typedef std::vector<experience_tuple_type> batch_type;
392
393 // the batch for this episode
394 auto batch = buffer.template get<batch_type>();
395 auto reward_batch = monitor_.template get<real_t, 2>(batch);
396
397 // compute the discounted rewards for this batch
398 auto discounted_returns =
399 bitrl::rl::algos::calculate_step_discounted_return(reward_batch, config_.gamma);
400 if (config_.baseline_type == BaselineEnumType::CONSTANT)
401 {
402 discounted_returns =
403 compute_baseline_with_constant(discounted_returns, config_.baseline_constant);
404 }
405 else if (config_.baseline_type == BaselineEnumType::MEAN)
406 {
407 discounted_returns = compute_baseline_with_mean(discounted_returns);
408 }
409 else
410 {
411 discounted_returns = compute_baseline_with_standardization(discounted_returns, config_.eps);
412 }
413
414 auto log_probs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
415 std::vector<torch_tensor_t> loss_vals = compute_loss_item(discounted_returns, log_probs_batch);
416
417 auto loss =
418 bitrl::utils::pytorch::TorchAdaptor::stack(loss_vals, config_.device_type, true).sum();
419 policy_optimizer_->zero_grad();
420 loss.backward();
421 policy_optimizer_->step();
422
423 auto total_episode_loss = loss.item().to<real_t>();
424
425 // compute the undiscounted reward as the reward
426 // for this episode
427 auto R = bitrl::maths::sum(reward_batch);
428
429 monitor_.policy_loss_values.push_back(total_episode_loss);
430 monitor_.rewards.push_back(R);
431
432 return std::make_tuple(R, total_episode_loss);
433}
434
435} // namespace pg
436} // namespace algos
437} // namespace rl
438} // namespace bitrl
439#endif
440#endif // VANILLA_REINFORCE_H
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
RLSolverBase()=default
Constructor.
virtual void actions_after_episode_ends(env_type &, uint_t, const EpisodeInfo &)
actions_after_training_episode
Definition reinforce.h:96
ReinforceMonitor< action_type, state_type >::experience_buffer_type experience_buffer_type
Definition reinforce.h:68
env_type::action_type action_type
Definition reinforce.h:66
ReinforceSolver(ReinforceConfig opts, policy_type &policy, std::unique_ptr< torch::optim::Optimizer > &policy_optimizer)
ReinforceSolver. Constructor.
Definition reinforce.h:163
virtual EpisodeInfo on_training_episode(env_type &, uint_t)
on_episode Do one on_episode of the algorithm
Definition reinforce.h:234
virtual void actions_before_episode_begins(env_type &, uint_t)
actions_before_training_episode
Definition reinforce.h:91
PolicyType policy_type
Definition reinforce.h:63
EnvType env_type
Definition reinforce.h:62
virtual void actions_after_training_ends(env_type &)
actions_after_training_ends. Actions to execute after the training iterations have finisehd
Definition reinforce.h:86
ReinforceMonitor< action_type, state_type > & get_monitor()
Read-write access to the monitor object.
Definition reinforce.h:109
env_type::state_type state_type
Definition reinforce.h:65
virtual void actions_before_training_begins(env_type &)
actions_before_training_begins. Execute any actions the algorithm needs before starting the iteration...
Definition reinforce.h:173
std::vector< T > normalize_max(const std::vector< T > &vec)
Definition vector_math.h:532
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< real_t > compute_baseline_with_mean(const std::vector< real_t > &rewards)
Compute the baseline using the mean value of the provided rewards.
std::vector< real_t > compute_baseline_with_standardization(const std::vector< real_t > &rewards, real_t eps=bitsim::consts::TOLERANCE)
Compute the baseline using standarization also known as whitening.
std::vector< torch_tensor_t > compute_loss_item(const std::vector< real_t > &rewards, const std::vector< torch_tensor_t > &log_probs)
compute_loss_item. Compute the product -rewards[i] * log_probs[i]
std::vector< real_t > compute_baseline_with_constant(const std::vector< real_t > &rewards, real_t constant)
Compute the baseline using a user-defined constant value from the given rewards.
@ MEAN
Definition reinforce_config.h:27
@ CONSTANT
Definition reinforce_config.h:26
@ NONE
Definition reinforce_config.h:25
Definition dp_algo_base.h:15
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 dummy_agent.h:9
@ BATCH
Definition train_enum_type.h:19
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
double real_t
real_t
Definition bitsim_types.h:20
std::tuple< std::vector< float_t >, uint_t, float_t, std::vector< float_t >, uint_t > experience_tuple_type
Definition dqn_experience_replay.cpp:106
The EpisodeInfo struct.
Definition episode_info.h:21
The ReinforceOpts struct. Holds various configuration options for the Reinforce algorithm.
Definition reinforce_config.h:37
Definition reinforce_monitor.h:24
bitrl::utils::ExperienceBuffer< experience_tuple_type > experience_buffer_type
Definition reinforce_monitor.h:36
std::tuple< state_type, action_type, real_t, bool, torch_tensor_t > experience_tuple_type
Definition reinforce_monitor.h:34
static value_type stack(const std::vector< T > &values, DeviceType type=DeviceType::CPU, bool requires_grad=false)