-
Notifications
You must be signed in to change notification settings - Fork 1
/
rl_example_14.cpp
executable file
·165 lines (115 loc) · 3.78 KB
/
rl_example_14.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include "cubeai/base/cubeai_config.h"
#if defined(USE_PYTORCH) && defined(USE_GYMFCPP)
#include "cubeai/base/cubeai_types.h"
#include "cubeai/rl/algorithms/pg/simple_reinforce.h"
#include "cubeai/rl/trainers/pytorch_rl_agent_trainer.h"
#include "cubeai/ml/distributions/torch_categorical.h"
#include "cubeai/optimization/optimizer_type.h"
#include "cubeai/optimization/pytorch_optimizer_factory.h"
#include "gymfcpp/gymfcpp_types.h"
#include "gymfcpp/cart_pole_env.h"
#include "gymfcpp/time_step.h"
#include <torch/torch.h>
#include <boost/python.hpp>
#include <iostream>
#include <string>
#include <any>
namespace example{
namespace F = torch::nn::functional;
using cubeai::real_t;
using cubeai::uint_t;
using cubeai::torch_tensor_t;
using cubeai::rl::algos::pg::SimpleReinforce;
using cubeai::rl::algos::pg::ReinforceConfig;
using cubeai::rl::PyTorchRLTrainer;
using cubeai::rl::PyTorchRLTrainerConfig;
using cubeai::ml::stats::TorchCategorical;
using rlenvs_cpp::gymfcpp::CartPole;
class PolicyImpl: public torch::nn::Module
{
public:
PolicyImpl();
torch_tensor_t forward(torch_tensor_t);
template<typename StateTp>
std::tuple<uint_t, real_t> act(const StateTp& state);
template<typename LossValuesTp>
void update_policy_loss(const LossValuesTp& vals);
void step_backward_policy_loss();
torch_tensor_t compute_loss(){return loss_;}
private:
torch::nn::Linear fc1_;
torch::nn::Linear fc2_;
// placeholder for the loss
torch_tensor_t loss_;
};
PolicyImpl::PolicyImpl()
:
fc1_(torch::nn::Linear(4, 16)),
fc2_(torch::nn::Linear(16, 2))
{
register_module("fc1", fc1_);
register_module("fc2", fc2_);
}
template<typename LossValuesTp>
void
PolicyImpl::update_policy_loss(const LossValuesTp& vals){
torch_tensor_t torch_vals = torch::tensor(vals);
// specify that we require the gradient
loss_ = torch::cat(torch::tensor(vals, torch::requires_grad())).sum();
}
void
PolicyImpl::step_backward_policy_loss(){
loss_.backward();
}
torch_tensor_t
PolicyImpl::forward(torch_tensor_t x){
x = F::relu(fc1_->forward(x));
x = fc2_->forward(x);
return F::softmax(x, F::SoftmaxFuncOptions(0));
}
template<typename StateTp>
std::tuple<uint_t, real_t>
PolicyImpl::act(const StateTp& state){
auto torch_state = torch::tensor(state);
auto probs = forward(torch_state);
auto m = TorchCategorical(&probs, nullptr);
auto action = m.sample();
return std::make_tuple(action.item().toLong(), m.log_prob(action).item().to<real_t>());
}
TORCH_MODULE(Policy);
}
int main(){
using namespace example;
try{
Py_Initialize();
auto gym_module = boost::python::import("__main__");
auto gym_namespace = gym_module.attr("__dict__");
auto env = CartPole("v0", gym_namespace, false);
env.make();
Policy policy;
auto optimizer_ptr = std::make_unique<torch::optim::Adam>(policy->parameters(), torch::optim::AdamOptions(1e-2));
// reinforce options
ReinforceConfig opts = {1000, 100, 100, 100, 1.0e-2, 0.1, 195.0, true};
SimpleReinforce<CartPole, Policy> algorithm(opts, policy);
PyTorchRLTrainerConfig trainer_config{1.0e-8, 1001, 50};
PyTorchRLTrainer<CartPole, SimpleReinforce<CartPole, Policy>> trainer(trainer_config, algorithm, std::move(optimizer_ptr));
trainer.train(env);
}
catch(const boost::python::error_already_set&){
PyErr_Print();
}
catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
catch(...){
std::cout<<"Unknown exception occured"<<std::endl;
}
return 0;
}
#else
#include <iostream>
int main(){
std::cout<<"This example requires PyTorch and gymfcpp. Reconfigure cubeai with PyTorch and gymfcpp support."<<std::endl;
return 0;
}
#endif