https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Public Member Functions | Protected Member Functions | Protected Attributes | Private Member Functions | Private Attributes | List of all members
Moose::LibtorchBetaActionDistribution Class Reference

Beta action distribution for bounded action spaces. More...

#include <LibtorchActionDistribution.h>

Inheritance diagram for Moose::LibtorchBetaActionDistribution:
[legend]

Public Member Functions

 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.
 
virtual void initialize (c10::optional< at::Generator > generator=c10::nullopt) override
 Initialize the trainable Beta distribution parameters.
 
virtual void reset (const torch::Tensor &input) override
 Refresh the Beta distribution parameters from the latest actor features.
 
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 deterministicAction () const override
 Return the Beta mean action used for deterministic evaluation.
 
virtual torch::Tensor logProbability (const torch::Tensor &action) const override
 Evaluate the log-probability of an action under the current Beta distribution.
 
virtual torch::Tensor entropy () const override
 Compute the entropy of the current Beta distribution.
 
virtual bool isBounded () const override
 Return true because the Beta distribution enforces action bounds.
 
torch::nn::Linear & alphaModule ()
 Return the Beta alpha head.
 
const torch::nn::Linear & alphaModule () const
 Return the Beta alpha head.
 
torch::nn::Linear & betaModule ()
 Return the Beta beta head.
 
const torch::nn::Linear & betaModule () const
 Return the Beta beta head.
 
const torch::Tensor & alphaTensor () const
 Return the cached Beta alpha tensor.
 
const torch::Tensor & betaTensor () const
 Return the cached Beta beta tensor.
 
void synchronizeScalingFactorsFromBuffer ()
 Sync cached scaling metadata from the registered buffers after loading state.
 

Protected Member Functions

torch::Tensor prepareFeatures (const torch::Tensor &input) const
 Convert actor features to the configured device and scalar type.
 
torch::Tensor prepareAction (const torch::Tensor &action) const
 Convert actions to the configured device and scalar type.
 
const torch::Tensor & actionScaleTensor () const
 Return the registered tensor that stores per-action scaling factors.
 

Protected Attributes

const std::string _name
 Module name used for registration and serialization.
 
const unsigned int _num_inputs
 Number of actor features feeding this distribution.
 
const unsigned int _num_outputs
 Number of action dimensions produced by this distribution.
 
const torch::DeviceType _device_type
 Torch device used by this distribution.
 
const torch::ScalarType _data_type
 Torch scalar type used by this distribution.
 
std::vector< Real > _output_scaling_factors
 Cached per-action scaling factors applied in physical units.
 
torch::Tensor _action_scale_tensor
 Registered libtorch buffer holding the per-action scaling factors.
 

Private Member Functions

void constructDistribution ()
 Build and register the Beta distribution heads.
 

Private Attributes

const std::vector< Real > _minimum_values
 Lower action bounds in physical units.
 
const std::vector< Real > _maximum_values
 Upper action bounds in physical units.
 
torch::nn::Linear _alpha_module {nullptr}
 Linear head that produces the Beta alpha parameters.
 
torch::nn::Linear _beta_module {nullptr}
 Linear head that produces the Beta beta parameters.
 
torch::Tensor _min_tensor
 Tensor form of the lower action bounds.
 
torch::Tensor _max_tensor
 Tensor form of the upper action bounds.
 
torch::Tensor _alpha_tensor
 Cached Beta alpha parameters from the latest reset.
 
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.
 
torch::Tensor _log_norm
 Cached log normalization factor for the latest Beta distribution state.
 
torch::Tensor _mean
 Cached normalized Beta mean from the latest reset.
 

Detailed Description

Beta action distribution for bounded action spaces.

Definition at line 254 of file LibtorchActionDistribution.h.

Constructor & Destructor Documentation

◆ LibtorchBetaActionDistribution()

Moose::LibtorchBetaActionDistribution::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.

Parameters
nameModule name used for registration and serialization.
num_inputsNumber of actor features feeding the distribution.
num_outputsNumber of action dimensions produced by the distribution.
minimum_valuesLower action bounds in physical units.
maximum_valuesUpper action bounds in physical units.
device_typeTorch device used by the module.
scalar_typeTorch scalar type used by the module.
build_on_constructWhether to build the torch modules right away.
output_scaling_factorsOptional extra per-action scaling in physical units.

Definition at line 208 of file LibtorchActionDistribution.C.

219 name, num_inputs, num_outputs, device_type, data_type, output_scaling_factors),
220 _minimum_values(minimum_values),
221 _maximum_values(maximum_values)
222{
223 if (_minimum_values.size() != _num_outputs || _maximum_values.size() != _num_outputs)
224 mooseError("The number of minimum_values and maximum_values entries must match the number "
225 "of action outputs.");
226
227 for (const auto i : make_range(_minimum_values.size()))
229 mooseError("maximum_values entries must be strictly greater than minimum_values entries.");
230
231 auto min_value = _minimum_values;
233 _min_tensor = _min_tensor.transpose(0, 1).to(_data_type).to(_device_type);
234 auto max_value = _maximum_values;
236 _max_tensor = _max_tensor.transpose(0, 1).to(_data_type).to(_device_type);
237
238 if (build_on_construct)
240}
void mooseError(Args &&... args)
const std::string name
Definition Setup.h:21
const torch::DeviceType _device_type
Torch device used by this distribution.
const unsigned int _num_outputs
Number of action dimensions produced by 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.
torch::Tensor _min_tensor
Tensor form of the lower action bounds.
const std::vector< Real > _maximum_values
Upper action bounds in physical units.
torch::Tensor _max_tensor
Tensor form of the upper action bounds.
const std::vector< Real > _minimum_values
Lower action bounds in physical units.
void constructDistribution()
Build and register the Beta distribution heads.
void vectorToTensor(const std::vector< DataType > &vector, torch::Tensor &tensor, const bool detach=false)
if(subdm)
IntRange< T > make_range(T beg, T end)

Member Function Documentation

◆ actionScaleTensor()

const torch::Tensor & Moose::LibtorchActionDistribution::actionScaleTensor ( ) const
inlineprotectedinherited

◆ alphaModule() [1/2]

torch::nn::Linear & Moose::LibtorchBetaActionDistribution::alphaModule ( )
inline

Return the Beta alpha head.

Definition at line 322 of file LibtorchActionDistribution.h.

322{ return _alpha_module; }
torch::nn::Linear _alpha_module
Linear head that produces the Beta alpha parameters.

◆ alphaModule() [2/2]

const torch::nn::Linear & Moose::LibtorchBetaActionDistribution::alphaModule ( ) const
inline

Return the Beta alpha head.

Definition at line 327 of file LibtorchActionDistribution.h.

327{ return _alpha_module; }

◆ alphaTensor()

const torch::Tensor & Moose::LibtorchBetaActionDistribution::alphaTensor ( ) const
inline

Return the cached Beta alpha tensor.

Definition at line 342 of file LibtorchActionDistribution.h.

342{ return _alpha_tensor; }
torch::Tensor _alpha_tensor
Cached Beta alpha parameters from the latest reset.

◆ betaModule() [1/2]

torch::nn::Linear & Moose::LibtorchBetaActionDistribution::betaModule ( )
inline

Return the Beta beta head.

Definition at line 332 of file LibtorchActionDistribution.h.

332{ return _beta_module; }
torch::nn::Linear _beta_module
Linear head that produces the Beta beta parameters.

◆ betaModule() [2/2]

const torch::nn::Linear & Moose::LibtorchBetaActionDistribution::betaModule ( ) const
inline

Return the Beta beta head.

Definition at line 337 of file LibtorchActionDistribution.h.

337{ return _beta_module; }

◆ betaTensor()

const torch::Tensor & Moose::LibtorchBetaActionDistribution::betaTensor ( ) const
inline

Return the cached Beta beta tensor.

Definition at line 347 of file LibtorchActionDistribution.h.

347{ return _beta_tensor; }
torch::Tensor _beta_tensor
Cached Beta beta parameters from the latest reset.

◆ constructDistribution()

void Moose::LibtorchBetaActionDistribution::constructDistribution ( )
private

Build and register the Beta distribution heads.

Definition at line 243 of file LibtorchActionDistribution.C.

244{
245 _alpha_module = register_module(
246 "alpha", torch::nn::Linear(torch::nn::LinearOptions(_num_inputs, _num_outputs).bias(true)));
247 _beta_module = register_module(
248 "beta", torch::nn::Linear(torch::nn::LinearOptions(_num_inputs, _num_outputs).bias(true)));
249
252}
const unsigned int _num_inputs
Number of actor features feeding this distribution.

Referenced by LibtorchBetaActionDistribution().

◆ deterministicAction()

torch::Tensor Moose::LibtorchBetaActionDistribution::deterministicAction ( ) const
overridevirtual

Return the Beta mean action used for deterministic evaluation.

Implements Moose::LibtorchActionDistribution.

Definition at line 288 of file LibtorchActionDistribution.C.

289{
291}
const torch::Tensor & actionScaleTensor() const
Return the registered tensor that stores per-action scaling factors.
torch::Tensor _mean
Cached normalized Beta mean from the latest reset.

◆ entropy()

torch::Tensor Moose::LibtorchBetaActionDistribution::entropy ( ) const
overridevirtual

Compute the entropy of the current Beta distribution.

Implements Moose::LibtorchActionDistribution.

Definition at line 316 of file LibtorchActionDistribution.C.

317{
318 const auto log_action_scale = torch::log(torch::abs(actionScaleTensor()));
319 const auto scale = torch::clamp_min(_max_tensor - _min_tensor, 1e-8);
320 return _log_norm - (_beta_tensor - 1.0) * torch::digamma(_beta_tensor) -
321 (_alpha_tensor - 1.0) * torch::digamma(_alpha_tensor) +
322 (_alpha_beta_tensor - 2.0) * torch::digamma(_alpha_beta_tensor) + torch::log(scale) +
323 log_action_scale;
324}
Real scale
torch::Tensor _log_norm
Cached log normalization factor for the latest Beta distribution state.
torch::Tensor _alpha_beta_tensor
Cached sum of the alpha and beta parameters.

◆ initialize()

void Moose::LibtorchBetaActionDistribution::initialize ( c10::optional< at::Generator >  generator = c10::nullopt)
overridevirtual

Initialize the trainable Beta distribution parameters.

Parameters
generatorOptional random-number generator used for reproducible initialization.

Implements Moose::LibtorchActionDistribution.

Definition at line 255 of file LibtorchActionDistribution.C.

256{
257 Moose::orthogonalInitializeTensor(_alpha_module->weight, 1.0, generator);
258 torch::nn::init::zeros_(_alpha_module->bias);
259
260 Moose::orthogonalInitializeTensor(_beta_module->weight, 1.0, generator);
261 torch::nn::init::zeros_(_beta_module->bias);
262}
void orthogonalInitializeTensor(torch::Tensor &tensor, Real gain=1.0, c10::optional< at::Generator > generator=c10::nullopt)

◆ isBounded()

virtual bool Moose::LibtorchBetaActionDistribution::isBounded ( ) const
inlineoverridevirtual

Return true because the Beta distribution enforces action bounds.

Implements Moose::LibtorchActionDistribution.

Definition at line 317 of file LibtorchActionDistribution.h.

317{ return true; }

◆ logProbability()

torch::Tensor Moose::LibtorchBetaActionDistribution::logProbability ( const torch::Tensor &  action) const
overridevirtual

Evaluate the log-probability of an action under the current Beta distribution.

Parameters
actionAction tensor in physical units.

Implements Moose::LibtorchActionDistribution.

Definition at line 294 of file LibtorchActionDistribution.C.

295{
296 const auto scaled_action = prepareAction(action);
297 const auto log_action_scale = torch::log(torch::abs(actionScaleTensor()));
298 const auto unscaled_action = scaled_action / actionScaleTensor();
299 const auto scale = torch::clamp_min(_max_tensor - _min_tensor, 1e-8);
300 const auto normalized = (unscaled_action - _min_tensor) / scale;
301 const auto clipped = torch::clamp(normalized, 1e-8, 1.0 - 1e-8);
302 auto log_prob = (_alpha_tensor - 1.0) * torch::log(clipped) +
303 (_beta_tensor - 1.0) * torch::log1p(-clipped) - _log_norm - torch::log(scale) -
304 log_action_scale;
305
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()),
310 log_prob);
311
312 return log_prob;
313}
torch::Tensor prepareAction(const torch::Tensor &action) const
Convert actions to the configured device and scalar type.

◆ prepareAction()

torch::Tensor Moose::LibtorchActionDistribution::prepareAction ( const torch::Tensor &  action) const
protectedinherited

Convert actions to the configured device and scalar type.

Parameters
actionRaw action tensor.

Definition at line 92 of file LibtorchActionDistribution.C.

93{
94 auto scaled_action = action;
95 if (_data_type != scaled_action.scalar_type())
96 scaled_action = scaled_action.to(_data_type);
97 if (_device_type != scaled_action.device().type())
98 scaled_action = scaled_action.to(_device_type);
99 return scaled_action;
100}

Referenced by Moose::LibtorchGaussianActionDistribution::logProbability(), and logProbability().

◆ prepareFeatures()

torch::Tensor Moose::LibtorchActionDistribution::prepareFeatures ( const torch::Tensor &  input) const
protectedinherited

Convert actor features to the configured device and scalar type.

Parameters
inputRaw actor feature tensor.

Definition at line 81 of file LibtorchActionDistribution.C.

82{
83 auto features = input;
84 if (_data_type != features.scalar_type())
85 features = features.to(_data_type);
86 if (_device_type != features.device().type())
87 features = features.to(_device_type);
88 return features;
89}

Referenced by Moose::LibtorchGaussianActionDistribution::reset(), and reset().

◆ reset()

void Moose::LibtorchBetaActionDistribution::reset ( const torch::Tensor &  input)
overridevirtual

Refresh the Beta distribution parameters from the latest actor features.

Parameters
inputFeature tensor coming from the actor body.

Implements Moose::LibtorchActionDistribution.

Definition at line 265 of file LibtorchActionDistribution.C.

266{
267 const auto features = prepareFeatures(input);
268 // softplus(x) + 1 keeps alpha, beta > 1 so the Beta density stays unimodal. torch::softplus
269 // switches to the identity for large logits, where log(exp(x) + 1) would overflow to inf.
270 _alpha_tensor = torch::softplus(_alpha_module->forward(features)) + 1.0;
271 _beta_tensor = torch::softplus(_beta_module->forward(features)) + 1.0;
272
273 _alpha_beta_tensor = torch::clamp_min(_alpha_tensor + _beta_tensor, 1e-8);
275 _log_norm = at::lgamma(_alpha_tensor) + at::lgamma(_beta_tensor) - at::lgamma(_alpha_beta_tensor);
276}
torch::Tensor prepareFeatures(const torch::Tensor &input) const
Convert actor features to the configured device and scalar type.

◆ sample()

torch::Tensor Moose::LibtorchBetaActionDistribution::sample ( c10::optional< at::Generator >  generator = c10::nullopt) const
overridevirtual

Draw a stochastic Beta action sample in physical units.

Parameters
generatorOptional random-number generator used for sampling.

Implements Moose::LibtorchActionDistribution.

Definition at line 279 of file LibtorchActionDistribution.C.

280{
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);
284 return (_min_tensor + (_max_tensor - _min_tensor) * sampled) * actionScaleTensor();
285}

◆ synchronizeScalingFactorsFromBuffer()

void Moose::LibtorchActionDistribution::synchronizeScalingFactorsFromBuffer ( )
inherited

Sync cached scaling metadata from the registered buffers after loading state.

Definition at line 73 of file LibtorchActionDistribution.C.

74{
75 auto action_scale =
76 _action_scale_tensor.detach().reshape({-1}).to(torch::kCPU).to(torch::kDouble);
78}
std::vector< Real > _output_scaling_factors
Cached per-action scaling factors applied in physical units.
void tensorToVector(torch::Tensor &tensor, std::vector< DataType > &vector)

Referenced by Moose::loadLibtorchActorNeuralNetState().

Member Data Documentation

◆ _action_scale_tensor

torch::Tensor Moose::LibtorchActionDistribution::_action_scale_tensor
protectedinherited

◆ _alpha_beta_tensor

torch::Tensor Moose::LibtorchBetaActionDistribution::_alpha_beta_tensor
private

Cached sum of the alpha and beta parameters.

Definition at line 373 of file LibtorchActionDistribution.h.

Referenced by entropy(), and reset().

◆ _alpha_module

torch::nn::Linear Moose::LibtorchBetaActionDistribution::_alpha_module {nullptr}
private

Linear head that produces the Beta alpha parameters.

Definition at line 361 of file LibtorchActionDistribution.h.

361{nullptr};

Referenced by alphaModule(), alphaModule(), constructDistribution(), initialize(), and reset().

◆ _alpha_tensor

torch::Tensor Moose::LibtorchBetaActionDistribution::_alpha_tensor
private

Cached Beta alpha parameters from the latest reset.

Definition at line 369 of file LibtorchActionDistribution.h.

Referenced by alphaTensor(), entropy(), logProbability(), reset(), and sample().

◆ _beta_module

torch::nn::Linear Moose::LibtorchBetaActionDistribution::_beta_module {nullptr}
private

Linear head that produces the Beta beta parameters.

Definition at line 363 of file LibtorchActionDistribution.h.

363{nullptr};

Referenced by betaModule(), betaModule(), constructDistribution(), initialize(), and reset().

◆ _beta_tensor

torch::Tensor Moose::LibtorchBetaActionDistribution::_beta_tensor
private

Cached Beta beta parameters from the latest reset.

Definition at line 371 of file LibtorchActionDistribution.h.

Referenced by betaTensor(), entropy(), logProbability(), reset(), and sample().

◆ _data_type

const torch::ScalarType Moose::LibtorchActionDistribution::_data_type
protectedinherited

◆ _device_type

const torch::DeviceType Moose::LibtorchActionDistribution::_device_type
protectedinherited

◆ _log_norm

torch::Tensor Moose::LibtorchBetaActionDistribution::_log_norm
private

Cached log normalization factor for the latest Beta distribution state.

Definition at line 375 of file LibtorchActionDistribution.h.

Referenced by entropy(), logProbability(), and reset().

◆ _max_tensor

torch::Tensor Moose::LibtorchBetaActionDistribution::_max_tensor
private

Tensor form of the upper action bounds.

Definition at line 367 of file LibtorchActionDistribution.h.

Referenced by deterministicAction(), entropy(), LibtorchBetaActionDistribution(), logProbability(), and sample().

◆ _maximum_values

const std::vector<Real> Moose::LibtorchBetaActionDistribution::_maximum_values
private

Upper action bounds in physical units.

Definition at line 358 of file LibtorchActionDistribution.h.

Referenced by LibtorchBetaActionDistribution().

◆ _mean

torch::Tensor Moose::LibtorchBetaActionDistribution::_mean
private

Cached normalized Beta mean from the latest reset.

Definition at line 377 of file LibtorchActionDistribution.h.

Referenced by deterministicAction(), and reset().

◆ _min_tensor

torch::Tensor Moose::LibtorchBetaActionDistribution::_min_tensor
private

Tensor form of the lower action bounds.

Definition at line 365 of file LibtorchActionDistribution.h.

Referenced by deterministicAction(), entropy(), LibtorchBetaActionDistribution(), logProbability(), and sample().

◆ _minimum_values

const std::vector<Real> Moose::LibtorchBetaActionDistribution::_minimum_values
private

Lower action bounds in physical units.

Definition at line 356 of file LibtorchActionDistribution.h.

Referenced by LibtorchBetaActionDistribution().

◆ _name

const std::string Moose::LibtorchActionDistribution::_name
protectedinherited

Module name used for registration and serialization.

Definition at line 107 of file LibtorchActionDistribution.h.

◆ _num_inputs

const unsigned int Moose::LibtorchActionDistribution::_num_inputs
protectedinherited

Number of actor features feeding this distribution.

Definition at line 109 of file LibtorchActionDistribution.h.

Referenced by Moose::LibtorchGaussianActionDistribution::constructDistribution(), and constructDistribution().

◆ _num_outputs

const unsigned int Moose::LibtorchActionDistribution::_num_outputs
protectedinherited

Number of action dimensions produced by this distribution.

Definition at line 111 of file LibtorchActionDistribution.h.

Referenced by Moose::LibtorchGaussianActionDistribution::constructDistribution(), constructDistribution(), and LibtorchBetaActionDistribution().

◆ _output_scaling_factors

std::vector<Real> Moose::LibtorchActionDistribution::_output_scaling_factors
protectedinherited

Cached per-action scaling factors applied in physical units.

Definition at line 117 of file LibtorchActionDistribution.h.

Referenced by Moose::LibtorchActionDistribution::LibtorchActionDistribution(), and Moose::LibtorchActionDistribution::synchronizeScalingFactorsFromBuffer().


The documentation for this class was generated from the following files: