11#include "bitrl/base/bitrl_config.h"
24#include <torch/torch.h>
39template <
typename EnvType,
typename PolicyType,
typename CriticType>
42 A2CMonitor<typename EnvType::action_type, typename EnvType::state_type>,
78 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
79 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer);
90template <
typename EnvType,
typename PolicyType,
typename CriticType>
93 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
94 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer)
97 PPOConfig>(config, policy, critic, policy_optimizer, critic_optimizer)
101template <
typename EnvType,
typename PolicyType,
typename CriticType>
105 auto start = std::chrono::steady_clock::now();
115 auto [episode_reward, total_episode_loss] = train_with_batch_(buffer);
117 auto end = std::chrono::steady_clock::now();
118 std::chrono::duration<real_t> elapsed_seconds = end - start;
120 this->
monitor_.episode_duration.push_back(eps_itrs);
123 info.episode_index = episode_idx;
124 info.episode_reward = episode_reward;
125 info.episode_iterations = eps_itrs;
126 info.total_time = elapsed_seconds;
130template <
typename EnvType,
typename PolicyType,
typename CriticType>
131std::tuple<real_t, real_t>
145 typedef std::vector<experience_tuple_type> batch_type;
148 auto batch = buffer.template get<batch_type>();
149 auto states = this->monitor_.template get<state_type, 0>(batch);
150 auto actions = this->monitor_.template get<action_type, 1>(batch);
154 auto as_floats = [](
const auto &value)
156 using value_type = std::decay_t<
decltype(value)>;
157 if constexpr (std::is_arithmetic_v<value_type>)
159 return std::vector<float_t>{
static_cast<float_t>(value)};
163 return std::vector<float_t>(value.begin(), value.end());
166 std::vector<std::vector<float_t>> states_f(states.size());
167 for (
uint_t i = 0; i < states.size(); ++i)
169 states_f[i] = as_floats(states[i]);
171 std::vector<std::vector<float_t>> actions_f(actions.size());
172 for (
uint_t i = 0; i < actions.size(); ++i)
174 actions_f[i] = as_floats(actions[i]);
177 auto rewards_batch = this->monitor_.template get<float_t, 2>(batch);
178 auto values_batch = this->monitor_.template get<torch_tensor_t, 5>(batch);
179 auto logprobs_batch = this->monitor_.template get<torch_tensor_t, 4>(batch);
182 auto discounted_returns =
184 auto torch_states_batch = TorchAdaptor::stack(states_f, this->config_.device_type,
true);
185 auto torch_actions_batch = TorchAdaptor::stack(actions_f, this->config_.device_type,
true);
186 auto torch_rewards_batch =
187 TorchAdaptor::to_torch(discounted_returns, this->config_.device_type,
false).detach();
191 torch_rewards_batch = torch_rewards_batch.view({-1});
192 auto torch_values_batch =
193 TorchAdaptor::stack(values_batch, this->config_.device_type).view({-1});
194 auto old_torch_logprobs_batch =
195 TorchAdaptor::stack(logprobs_batch, this->config_.device_type).view({-1}).detach();
198 auto advantages = (torch_rewards_batch - torch_values_batch).detach();
199 if (this->config_.normalize_advantages && advantages.numel() > 1)
201 advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8);
204 std::vector<real_t> loss_vals(this->config_.max_passes_over_batch, 0.0);
205 for (
uint_t p = 0; p < this->config_.max_passes_over_batch; ++p)
207 auto [new_log_probs, entropy,
_] =
208 this->policy_->evaluate(torch_states_batch, torch_actions_batch);
210 auto ratio = (new_log_probs.view({-1}) - old_torch_logprobs_batch).exp();
211 auto surr1 = ratio * advantages;
213 torch::clamp(ratio, 1 - this->config_.clip_epsilon, 1 + this->config_.clip_epsilon) *
215 auto actor_loss = -torch::min(surr1, surr2).mean();
217 auto value_estimates = this->critic_->forward(torch_states_batch).view({-1});
218 auto critic_loss = torch::nn::functional::mse_loss(value_estimates, torch_rewards_batch);
220 auto total_loss = actor_loss + 0.5 * critic_loss - 0.01 * entropy;
222 this->policy_optimizer_->zero_grad();
223 this->critic_optimizer_->zero_grad();
224 total_loss.backward();
225 loss_vals[p] = total_loss.item().template to<real_t>();
226 this->policy_optimizer_->step();
227 this->critic_optimizer_->step();
233 this->monitor_.policy_loss_values.push_back(avg_loss);
234 this->monitor_.rewards.push_back(R);
238 return std::make_tuple(R, avg_loss);
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_INFO
Definition bitrl_log.h:36
uint_t create_episode_batch_(env_type &env, uint_t, experience_buffer_type &buffer)
Definition actor_critic_solver_base.h:237
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
config_type config_
Definition actor_critic_solver_base.h:156
monitor_type monitor_
Definition actor_critic_solver_base.h:171
CriticType critic_type
The critic type.
Definition ppo.h:59
env_type::state_type state_type
The state_type.
Definition ppo.h:64
A2CMonitor< action_type, state_type >::experience_buffer_type experience_buffer_type
Definition ppo.h:72
EnvType env_type
The environment type.
Definition ppo.h:49
env_type::action_type action_type
the action type
Definition ppo.h:69
PPOSolver(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)
PPOSolver Constructor.
Definition ppo.h:91
virtual EpisodeInfo on_training_episode(env_type &, uint_t) override final
on_episode Do one on_episode of the algorithm
Definition ppo.h:102
PolicyType policy_type
The policy or action type.
Definition ppo.h:54
Critic critic_type
Definition ppo.h:59
A2CMonitor< action_type, state_type >::experience_buffer_type experience_buffer_type
Definition ppo.h:72
env_type env_type
Definition ppo.h:49
Actor policy_type
Definition ppo.h:54
real_t mean(IteratorType begin, IteratorType end, bool parallel=true)
mean Compute the mean value of the values in the provided iterator range
Definition vector_math.h:119
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
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 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
float float_t
float
Definition bitsim_types.h:25
The EpisodeInfo struct.
Definition episode_info.h:21
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
The PPOConfig struct. Configuration for PPOSolver class.
Definition ppo_config.h:26