https://mooseframework.inl.gov
Loading...
Searching...
No Matches
LibtorchRLValueEstimator.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#ifdef MOOSE_LIBTORCH_ENABLED
11
13
14#include "LibtorchUtils.h"
15
16#include "libmesh/utility.h"
17
18namespace
19{
20
21torch::Tensor
22valueEstimatorMatrixToTensor(const std::vector<std::vector<Real>> & rows)
23{
24 if (rows.empty())
25 return {};
26
27 const auto num_columns = rows.front().size();
28 auto tensor = torch::zeros({static_cast<long>(rows.size()), static_cast<long>(num_columns)},
29 torch::TensorOptions().dtype(torch::kDouble));
30 auto accessor = tensor.accessor<Real, 2>();
31
32 for (const auto row_i : make_range(rows.size()))
33 for (const auto column_i : make_range(num_columns))
34 accessor[row_i][column_i] = rows[row_i][column_i];
35
36 return tensor;
37}
38
39} // namespace
40
42 const Real lambda_factor)
43 : _discount_factor(discount_factor), _lambda_factor(lambda_factor)
44{
45}
46
47void
50{
51 for (auto & trajectory : buffer.trajectories())
52 {
53 const auto targets = estimate(trajectory, value_network);
54 trajectory.advantages = targets.advantages;
55 trajectory.value_targets = targets.value_targets;
56 }
57}
58
61 Moose::LibtorchArtificialNeuralNet & value_network) const
62{
63 Targets targets;
64
65 const auto values = evaluate(trajectory.observations, value_network);
66 const auto next_values = evaluate(trajectory.next_observations, value_network);
67
68 const auto num_steps = trajectory.rewards.size();
69 targets.advantages.resize(num_steps, 0.0);
70 targets.value_targets.resize(num_steps, 0.0);
71
72 Real gae = 0.0;
73 for (const auto reverse_step : make_range(num_steps))
74 {
75 const auto step = num_steps - reverse_step - 1;
76 const Real continuation =
77 trajectory.terminals.empty() || !trajectory.terminals[step] ? 1.0 : 0.0;
78 const auto delta = trajectory.rewards[step] +
79 _discount_factor * continuation * next_values[step] - values[step];
80 gae = delta + _discount_factor * _lambda_factor * continuation * gae;
81 targets.advantages[step] = gae;
82 targets.value_targets[step] = gae + values[step];
83 }
84
85 return targets;
86}
87
88std::vector<Real>
89LibtorchRLValueEstimator::evaluate(const std::vector<std::vector<Real>> & observations,
90 Moose::LibtorchArtificialNeuralNet & value_network) const
91{
92 if (observations.empty())
93 return {};
94
95 torch::NoGradGuard no_grad;
96
97 auto tensor = valueEstimatorMatrixToTensor(observations);
98 auto value_tensor = value_network.forward(tensor);
99 auto flattened_value_tensor = value_tensor.reshape({-1});
100
101 std::vector<Real> values;
102 LibtorchUtils::tensorToVector(flattened_value_tensor, values);
103 return values;
104}
105
106#endif
std::array< Real, 2 > values
for(PetscInt i=0;i< nvars;++i)
On-policy trajectory storage for fixed-horizon RL training.
std::vector< Trajectory > & trajectories()
Return mutable access to the stored trajectories.
Targets estimate(const LibtorchRLTrajectoryBuffer::Trajectory &trajectory, Moose::LibtorchArtificialNeuralNet &value_network) const
Compute value targets and advantages for one trajectory.
const Real _discount_factor
Reward discount factor used in the temporal-difference recursion.
std::vector< Real > evaluate(const std::vector< std::vector< Real > > &observations, Moose::LibtorchArtificialNeuralNet &value_network) const
Evaluate the critic on a batch of observations.
void computeValueTargets(LibtorchRLTrajectoryBuffer &buffer, Moose::LibtorchArtificialNeuralNet &value_network) const
Fill every trajectory in the buffer with value targets and advantages.
LibtorchRLValueEstimator(Real discount_factor, Real lambda_factor)
Build the GAE helper.
const Real _lambda_factor
GAE lambda factor used in the reverse-time advantage recursion.
virtual torch::Tensor forward(const torch::Tensor &x) override
void tensorToVector(torch::Tensor &tensor, std::vector< DataType > &vector)
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
IntRange< T > make_range(T beg, T end)
Vector data for one on-policy trajectory.
std::vector< Real > rewards
Scalar rewards for each transition.
std::vector< std::vector< Real > > observations
Observations for each transition.
std::vector< std::vector< Real > > next_observations
Next observations for each transition.
std::vector< bool > terminals
Terminal flags for each transition. A true value cuts value bootstrapping at that step.
Generalized-advantage estimates and critic targets for one trajectory.
std::vector< Real > value_targets
Critic regression targets.
std::vector< Real > advantages
Generalized-advantage estimates.