bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
ppo.h
Go to the documentation of this file.
1#ifndef PPO_H
2#define PPO_H
3
10
11#include "bitrl/base/bitrl_config.h"
12
13#ifdef USE_PYTORCH
14
23
24#include <torch/torch.h>
25
26#ifdef BITRL_DEBUG
27#include <cassert>
28#endif
29
30#include <chrono>
31#include <type_traits>
32#include <vector>
33
34namespace bitrl
35{
36namespace rl::algos::pg
37{
38
39template <typename EnvType, typename PolicyType, typename CriticType>
40class PPOSolver final
41 : public ACSolverBase<EnvType, PolicyType, CriticType,
42 A2CMonitor<typename EnvType::action_type, typename EnvType::state_type>,
43 PPOConfig>
44{
45 public:
49 typedef EnvType env_type;
50
54 typedef PolicyType policy_type;
55
59 typedef CriticType critic_type;
60
64 typedef typename env_type::state_type state_type;
65
69 typedef typename env_type::action_type action_type;
70
71 typedef
73
77 PPOSolver(const PPOConfig &config, policy_type &policy, critic_type &critic,
78 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
79 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer);
80
84 virtual EpisodeInfo on_training_episode(env_type &, uint_t /*episode_idx*/) override final;
85
86 private:
87 std::tuple<real_t, real_t> train_with_batch_(experience_buffer_type &buffer);
88};
89
90template <typename EnvType, typename PolicyType, typename CriticType>
92 const PPOConfig &config, policy_type &policy, critic_type &critic,
93 std::unique_ptr<torch::optim::Optimizer> &policy_optimizer,
94 std::unique_ptr<torch::optim::Optimizer> &critic_optimizer)
95 : ACSolverBase<EnvType, PolicyType, CriticType,
96 A2CMonitor<typename EnvType::action_type, typename EnvType::state_type>,
97 PPOConfig>(config, policy, critic, policy_optimizer, critic_optimizer)
98{
99}
100
101template <typename EnvType, typename PolicyType, typename CriticType>
103 uint_t episode_idx)
104{
105 auto start = std::chrono::steady_clock::now();
106
107 // the buffer to use
108 experience_buffer_type buffer(this->config_.max_itrs_per_episode);
109
110 // collect the buffer
111 auto eps_itrs = this->create_episode_batch_(env, episode_idx, buffer);
112
113 // train the networks with from the
114 // collected buffer
115 auto [episode_reward, total_episode_loss] = train_with_batch_(buffer);
116
117 auto end = std::chrono::steady_clock::now();
118 std::chrono::duration<real_t> elapsed_seconds = end - start;
119
120 this->monitor_.episode_duration.push_back(eps_itrs);
121
122 EpisodeInfo info;
123 info.episode_index = episode_idx;
124 info.episode_reward = episode_reward;
125 info.episode_iterations = eps_itrs;
126 info.total_time = elapsed_seconds;
127 return info;
128}
129
130template <typename EnvType, typename PolicyType, typename CriticType>
131std::tuple<real_t, real_t>
132PPOSolver<EnvType, PolicyType, CriticType>::train_with_batch_(experience_buffer_type &buffer)
133{
134
135#ifdef BITRL_DEBUG
136 BITRL_LOG_INFO << "PPO: Training with batch...: ";
137#endif
138
139 // because of the way we treat the values
140 // we loose the requires_grad so we need to set it
141 using namespace bitrl::utils::pytorch;
142 using namespace bitrl::rl::algos;
143 typedef
145 typedef std::vector<experience_tuple_type> batch_type;
146
147 // the batch for this episode
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);
151
152 // a state or an action is a vector, or a single number such as the index
153 // of a discrete action; either way a row of floats
154 auto as_floats = [](const auto &value)
155 {
156 using value_type = std::decay_t<decltype(value)>;
157 if constexpr (std::is_arithmetic_v<value_type>)
158 {
159 return std::vector<float_t>{static_cast<float_t>(value)};
160 }
161 else
162 {
163 return std::vector<float_t>(value.begin(), value.end());
164 }
165 };
166 std::vector<std::vector<float_t>> states_f(states.size());
167 for (uint_t i = 0; i < states.size(); ++i)
168 {
169 states_f[i] = as_floats(states[i]);
170 }
171 std::vector<std::vector<float_t>> actions_f(actions.size());
172 for (uint_t i = 0; i < actions.size(); ++i)
173 {
174 actions_f[i] = as_floats(actions[i]);
175 }
176
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);
180
181 // compute the discounted rewards for this batch
182 auto discounted_returns =
183 calculate_step_discounted_return(rewards_batch, static_cast<float_t>(this->config_.gamma));
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();
188 // one value per step: the critic and the policy give tensors of one
189 // element, which stack into a column, and a column minus a row would
190 // broadcast into a matrix
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();
196
197 // form the advantage: how much better the return was than the critic said
198 auto advantages = (torch_rewards_batch - torch_values_batch).detach();
199 if (this->config_.normalize_advantages && advantages.numel() > 1)
200 {
201 advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8);
202 }
203
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)
206 {
207 auto [new_log_probs, entropy, _] =
208 this->policy_->evaluate(torch_states_batch, torch_actions_batch);
209
210 auto ratio = (new_log_probs.view({-1}) - old_torch_logprobs_batch).exp();
211 auto surr1 = ratio * advantages;
212 auto surr2 =
213 torch::clamp(ratio, 1 - this->config_.clip_epsilon, 1 + this->config_.clip_epsilon) *
214 advantages;
215 auto actor_loss = -torch::min(surr1, surr2).mean();
216
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);
219
220 auto total_loss = actor_loss + 0.5 * critic_loss - 0.01 * entropy;
221
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();
228 }
229
230 // compute the undiscounted reward as the reward for this episode
231 auto R = bitrl::maths::sum(rewards_batch);
232 auto avg_loss = bitrl::maths::mean(loss_vals);
233 this->monitor_.policy_loss_values.push_back(avg_loss);
234 this->monitor_.rewards.push_back(R);
235#ifdef BITRL_DEBUG
236 BITRL_LOG_INFO << "PPO: Done...: ";
237#endif
238 return std::make_tuple(R, avg_loss);
239}
240
241} // namespace rl::algos::pg
242} // namespace bitrl
243#endif
244#endif
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
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
A2CMonitor< action_type, state_type >::experience_buffer_type experience_buffer_type
Definition ppo.h:72
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 a2c.h:37
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
_
Definition play.py:39
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