10#ifdef MOOSE_LIBTORCH_ENABLED
20#include "libmesh/utility.h"
32setActionScalingFactors(
const std::vector<Real> & factors,
const unsigned int expected_size)
34 const auto normalized = factors.empty() ? std::vector<Real>(expected_size, 1.0) : factors;
36 if (normalized.size() != expected_size)
37 mooseError(
"The number of output_scaling_factors entries must match the number of action "
40 for (
const auto factor : normalized)
42 mooseError(
"The output_scaling_factors entries must be non-zero.");
53 const std::string &
name,
54 const unsigned int num_inputs,
55 const unsigned int num_outputs,
56 const torch::DeviceType device_type,
57 const torch::ScalarType data_type,
58 const std::vector<Real> & output_scaling_factors)
60 _num_inputs(num_inputs),
61 _num_outputs(num_outputs),
62 _device_type(device_type),
63 _data_type(data_type),
64 _output_scaling_factors(setActionScalingFactors(output_scaling_factors, num_outputs))
83 auto features = input;
94 auto scaled_action = action;
103 const std::string &
name,
104 const unsigned int num_inputs,
105 const unsigned int num_outputs,
106 const torch::DeviceType device_type,
107 const torch::ScalarType data_type,
108 const bool build_on_construct,
109 const std::vector<Real> & output_scaling_factors,
110 const bool state_independent_std)
112 name, num_inputs, num_outputs, device_type, data_type, output_scaling_factors),
113 _state_independent_std(state_independent_std)
115 if (build_on_construct)
163 if (
_mean.dim() <= 1)
194 constexpr Real pi = 3.14159265358979323846;
197 0.5 * std::log(2.0 * pi) - log_action_scale;
204 constexpr Real pi = 3.14159265358979323846;
205 return 0.5 * std::log(2.0 * pi) +
_log_std_tensor + 0.5 + log_action_scale;
209 const std::string &
name,
210 const unsigned int num_inputs,
211 const unsigned int num_outputs,
212 const std::vector<Real> & minimum_values,
213 const std::vector<Real> & maximum_values,
214 const torch::DeviceType device_type,
215 const torch::ScalarType data_type,
216 const bool build_on_construct,
217 const std::vector<Real> & output_scaling_factors)
219 name, num_inputs, num_outputs, device_type, data_type, output_scaling_factors),
220 _minimum_values(minimum_values),
221 _maximum_values(maximum_values)
224 mooseError(
"The number of minimum_values and maximum_values entries must match the number "
225 "of action outputs.");
229 mooseError(
"maximum_values entries must be strictly greater than minimum_values entries.");
238 if (build_on_construct)
281 const auto alpha_sample = at::_standard_gamma(
_alpha_tensor, generator);
282 const auto beta_sample = at::_standard_gamma(
_beta_tensor, generator);
283 const auto sampled = alpha_sample / (alpha_sample + beta_sample);
301 const auto clipped = torch::clamp(normalized, 1e-8, 1.0 - 1e-8);
302 auto log_prob = (
_alpha_tensor - 1.0) * torch::log(clipped) +
306 const auto out_of_bounds = (normalized < 0.0) | (normalized > 1.0);
307 if (out_of_bounds.any().item<
bool>())
308 log_prob = torch::where(out_of_bounds,
309 torch::full_like(log_prob, -std::numeric_limits<Real>::infinity()),
void mooseError(Args &&... args)
Reusable continuous-action distribution interface for actor policies.
const torch::DeviceType _device_type
Torch device used by this distribution.
torch::Tensor _action_scale_tensor
Registered libtorch buffer holding the per-action scaling factors.
torch::Tensor prepareAction(const torch::Tensor &action) const
Convert actions to the configured device and scalar type.
void synchronizeScalingFactorsFromBuffer()
Sync cached scaling metadata from the registered buffers after loading state.
std::vector< Real > _output_scaling_factors
Cached per-action scaling factors applied in physical units.
torch::Tensor prepareFeatures(const torch::Tensor &input) const
Convert actor features to the configured device and scalar type.
const torch::Tensor & actionScaleTensor() const
Return the registered tensor that stores per-action scaling factors.
const unsigned int _num_outputs
Number of action dimensions produced by this distribution.
const unsigned int _num_inputs
Number of actor features feeding this distribution.
const torch::ScalarType _data_type
Torch scalar type used by this distribution.
LibtorchActionDistribution(const std::string &name, unsigned int num_inputs, unsigned int num_outputs, torch::DeviceType device_type=torch::kCPU, torch::ScalarType scalar_type=torch::kDouble, const std::vector< Real > &output_scaling_factors={})
Build an action-distribution module for an actor network.
virtual void reset(const torch::Tensor &input) override
Refresh the Beta distribution parameters from the latest actor features.
torch::Tensor _min_tensor
Tensor form of the lower action bounds.
torch::nn::Linear _beta_module
Linear head that produces the Beta beta parameters.
torch::nn::Linear _alpha_module
Linear head that produces the Beta alpha parameters.
const std::vector< Real > _maximum_values
Upper action bounds in physical units.
torch::Tensor _max_tensor
Tensor form of the upper action bounds.
virtual void initialize(c10::optional< at::Generator > generator=c10::nullopt) override
Initialize the trainable Beta distribution parameters.
const std::vector< Real > _minimum_values
Lower action bounds in physical units.
torch::Tensor _alpha_tensor
Cached Beta alpha parameters from the latest reset.
torch::Tensor _mean
Cached normalized Beta mean from the latest reset.
LibtorchBetaActionDistribution(const std::string &name, unsigned int num_inputs, unsigned int num_outputs, const std::vector< Real > &minimum_values, const std::vector< Real > &maximum_values, torch::DeviceType device_type=torch::kCPU, torch::ScalarType scalar_type=torch::kDouble, bool build_on_construct=true, const std::vector< Real > &output_scaling_factors={})
Build the Beta action distribution used for bounded controls.
torch::Tensor _log_norm
Cached log normalization factor for the latest Beta distribution state.
torch::Tensor _beta_tensor
Cached Beta beta parameters from the latest reset.
torch::Tensor _alpha_beta_tensor
Cached sum of the alpha and beta parameters.
void constructDistribution()
Build and register the Beta distribution heads.
virtual torch::Tensor deterministicAction() const override
Return the Beta mean action used for deterministic evaluation.
virtual torch::Tensor entropy() const override
Compute the entropy of the current Beta distribution.
virtual torch::Tensor sample(c10::optional< at::Generator > generator=c10::nullopt) const override
Draw a stochastic Beta action sample in physical units.
virtual torch::Tensor logProbability(const torch::Tensor &action) const override
Evaluate the log-probability of an action under the current Beta distribution.
void constructDistribution()
Build and register the Gaussian distribution heads.
torch::Tensor _std_tensor
Cached Gaussian action standard deviation from the latest reset.
torch::nn::Linear _std_module
Linear head that produces state-dependent Gaussian log-std inputs.
torch::Tensor _mean
Cached Gaussian action mean from the latest reset.
virtual torch::Tensor entropy() const override
Compute the entropy of the current Gaussian distribution.
torch::nn::Linear _mean_module
Linear head that produces the Gaussian action mean.
virtual torch::Tensor deterministicAction() const override
Return the Gaussian mean action used for deterministic evaluation.
virtual torch::Tensor sample(c10::optional< at::Generator > generator=c10::nullopt) const override
Draw a stochastic Gaussian action sample in physical units.
torch::Tensor _log_std_tensor
Cached Gaussian action log standard deviation from the latest reset.
torch::Tensor _log_std_parameter
Trainable state-independent Gaussian log-std.
virtual void initialize(c10::optional< at::Generator > generator=c10::nullopt) override
Initialize the trainable Gaussian distribution parameters.
virtual torch::Tensor logProbability(const torch::Tensor &action) const override
Evaluate the log-probability of an action under the current Gaussian distribution.
virtual void reset(const torch::Tensor &input) override
Refresh the Gaussian distribution parameters from the latest actor features.
const bool _state_independent_std
Whether the Gaussian std ignores the current actor features.
LibtorchGaussianActionDistribution(const std::string &name, unsigned int num_inputs, unsigned int num_outputs, torch::DeviceType device_type=torch::kCPU, torch::ScalarType scalar_type=torch::kDouble, bool build_on_construct=true, const std::vector< Real > &output_scaling_factors={}, bool state_independent_std=true)
Build the Gaussian action distribution used for unbounded controls.
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
void vectorToTensor(const std::vector< DataType > &vector, torch::Tensor &tensor, const bool detach=false)
void tensorToVector(torch::Tensor &tensor, std::vector< DataType > &vector)
void orthogonalInitializeTensor(torch::Tensor &tensor, Real gain=1.0, c10::optional< at::Generator > generator=c10::nullopt)