10#include "bitrl/base/bitrl_config.h"
26#include <torch/torch.h>
58template <
typename EnvType,
typename PolicyType>
74 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer);
125 std::unique_ptr<torch::optim::Optimizer> policy_optimizer_;
162template <
typename EnvType,
typename PolicyType>
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_()
172template <
typename EnvType,
typename PolicyType>
176 monitor_.policy_loss_values.reserve(config_.n_episodes);
177 monitor_.rewards.reserve(config_.n_episodes);
178 monitor_.episode_duration.reserve(config_.n_episodes);
181 policy_ptr_->train();
184template <
typename EnvType,
typename PolicyType>
185uint_t ReinforceSolver<EnvType, PolicyType>::create_episode_batch_(
env_type &env,
193 experience_tuple_type;
196 auto old_timestep = env.reset();
204 for (; itr < config_.max_itrs_per_episode; ++itr)
209 auto [action, log_prob] = policy_ptr_->act(old_timestep.observation());
212 auto new_timestep = env.step(action);
213 auto reward = new_timestep.reward();
215 experience_tuple_type exp = {old_timestep.observation(), action, reward,
216 new_timestep.done(), log_prob};
221 if (new_timestep.done())
226 old_timestep = new_timestep;
233template <
typename EnvType,
typename PolicyType>
239 auto start = std::chrono::steady_clock::now();
246 auto itrs = create_episode_batch_(env, buffer);
252 auto [episode_reward, total_episode_loss] = train_without_baseline_(buffer);
253 info.episode_reward = episode_reward;
258 auto [episode_reward, total_episode_loss] = train_with_baseline_(buffer);
259 info.episode_reward = episode_reward;
261 monitor_.episode_duration.push_back(itrs);
263 auto end = std::chrono::steady_clock::now();
264 std::chrono::duration<real_t> elapsed_seconds = end - start;
267 info.episode_index = episode_idx;
268 info.episode_iterations = itrs;
269 info.total_time = elapsed_seconds;
273template <
typename EnvType,
typename PolicyType>
274std::tuple<real_t, real_t>
279 experience_tuple_type;
281 typedef std::vector<experience_tuple_type> batch_type;
284 auto batch = buffer.template get<batch_type>();
287 auto reward_batch = monitor_.template get<real_t, 2>(batch);
288 auto log_probs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
291 auto discounted_returns =
294 if (config_.normalize_rewards)
299 std::vector<torch_tensor_t> loss_vals =
compute_loss_item(discounted_returns, log_probs_batch);
303 policy_optimizer_->zero_grad();
305 policy_optimizer_->step();
307 auto total_episode_loss = loss.item().to<
real_t>();
312 return std::make_tuple(R, total_episode_loss);
315template <
typename EnvType,
typename PolicyType>
316std::tuple<real_t, real_t>
317ReinforceSolver<EnvType, PolicyType>::train_sequential_(experience_buffer_type &buffer)
320 typedef typename ReinforceMonitor<action_type, state_type>::experience_tuple_type
321 experience_tuple_type;
323 typedef std::vector<experience_tuple_type> batch_type;
326 auto batch = buffer.template get<batch_type>();
329 auto reward_batch = monitor_.template get<real_t, 2>(batch);
330 auto log_probs_batch = monitor_.template get<torch_tensor_t, 4>(batch);
333 auto discounted_returns =
336 if (config_.normalize_rewards)
341 std::vector<torch_tensor_t> loss_vals =
compute_loss_item(discounted_returns, log_probs_batch);
345 auto total_episode_loss = 0.0;
346 for (
uint_t l = 0; l < loss_vals.size(); ++l)
349 auto loss = loss_vals[l];
350 policy_optimizer_->zero_grad();
352 policy_optimizer_->step();
354 total_episode_loss += loss.item().to<
real_t>();
358 return std::make_tuple(R, total_episode_loss / loss_vals.size());
361template <
typename EnvType,
typename PolicyType>
362std::tuple<real_t, real_t>
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);
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);
384template <
typename EnvType,
typename PolicyType>
385std::tuple<real_t, real_t>
391 typedef std::vector<experience_tuple_type> batch_type;
394 auto batch = buffer.template get<batch_type>();
395 auto reward_batch = monitor_.template get<real_t, 2>(batch);
398 auto discounted_returns =
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);
419 policy_optimizer_->zero_grad();
421 policy_optimizer_->step();
423 auto total_episode_loss = loss.item().to<
real_t>();
429 monitor_.policy_loss_values.push_back(total_episode_loss);
430 monitor_.rewards.push_back(R);
432 return std::make_tuple(R, total_episode_loss);
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
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)