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

#include <LibtorchArtificialNeuralNet.h>

Inheritance diagram for Moose::LibtorchArtificialNeuralNet:
[legend]

Public Member Functions

 LibtorchArtificialNeuralNet (const std::string name, const unsigned int num_inputs, const unsigned int num_outputs, const std::vector< unsigned int > &num_neurons_per_layer, const std::vector< std::string > &activation_function={"relu"}, const torch::DeviceType device_type=torch::kCPU, const torch::ScalarType scalar_type=torch::kDouble)
 Construct using input parameters.
 
 LibtorchArtificialNeuralNet (const Moose::LibtorchArtificialNeuralNet &nn)
 Copy construct an artificial neural network.
 
virtual void addLayer (const std::string &layer_name, const std::unordered_map< std::string, unsigned int > &parameters)
 Add layers to the neural network.
 
virtual torch::Tensor forward (const torch::Tensor &x) override
 Overriding the forward substitution function for the neural network, unfortunately this cannot be const since it creates a graph in the background.
 
const std::string & name () const
 Return the name of the neural network.
 
unsigned int numInputs () const
 Return the number of neurons on the input layer.
 
unsigned int numOutputs () const
 Return the number of neurons on the output layer.
 
unsigned int numHiddenLayers () const
 Return the number of hidden layers.
 
const std::vector< unsigned int > & numNeuronsPerLayer () const
 Return the hidden layer architecture.
 
const MultiMooseEnumactivationFunctions () const
 Return the multi enum containing the activation functions.
 
torch::DeviceType deviceType () const
 Return the device which is used by this neural network.
 
torch::ScalarType dataType () const
 Return the data type which is used by this neural network.
 
void constructNeuralNetwork ()
 Construct the neural network.
 
void store (nlohmann::json &json) const
 Store the network architecture in a json file (for debugging, visualization)
 

Protected Attributes

const std::string _name
 Name of the neural network.
 
std::vector< torch::nn::Linear > _weights
 Submodules that hold linear operations and the corresponding weights and biases (y = W * x + b)
 
const unsigned int _num_inputs
 
const unsigned int _num_outputs
 Number of neurons on the output layer.
 
const std::vector< unsigned int_num_neurons_per_layer
 Hidden layer architecture.
 
MultiMooseEnum _activation_function
 Activation functions (either one for all hidden layers or one for every layer separately)
 
const torch::DeviceType _device_type
 The device type used for this neural network.
 
const torch::ScalarType _data_type
 The data type used in this neural network.
 

Detailed Description

Definition at line 26 of file LibtorchArtificialNeuralNet.h.

Constructor & Destructor Documentation

◆ LibtorchArtificialNeuralNet() [1/2]

Moose::LibtorchArtificialNeuralNet::LibtorchArtificialNeuralNet ( const std::string  name,
const unsigned int  num_inputs,
const unsigned int  num_outputs,
const std::vector< unsigned int > &  num_neurons_per_layer,
const std::vector< std::string > &  activation_function = {"relu"},
const torch::DeviceType  device_type = torch::kCPU,
const torch::ScalarType  scalar_type = torch::kDouble 
)

Construct using input parameters.

Parameters
nameName of the neural network
num_inputsThe number of input neurons/parameters
num_neurons_per_layerNumber of neurons per hidden layer
num_outputsThe number of output neurons

Definition at line 18 of file LibtorchArtificialNeuralNet.C.

26 : _name(name),
27 _num_inputs(num_inputs),
28 _num_outputs(num_outputs),
29 _num_neurons_per_layer(num_neurons_per_layer),
30 _activation_function(MultiMooseEnum("relu sigmoid elu gelu linear", "relu")),
31 _device_type(device_type),
32 _data_type(data_type)
33{
34 _activation_function = activation_function;
35
36 // Check if the number of activation functions matches the number of hidden layers
37 if ((_activation_function.size() != 1) &&
39 mooseError("The number of activation functions should be either one or the same as the number "
40 "of hidden layers");
42}
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
const torch::ScalarType _data_type
The data type used in this neural network.
MultiMooseEnum _activation_function
Activation functions (either one for all hidden layers or one for every layer separately)
const std::string & name() const
Return the name of the neural network.
const unsigned int _num_outputs
Number of neurons on the output layer.
const std::string _name
Name of the neural network.
const torch::DeviceType _device_type
The device type used for this neural network.
const std::vector< unsigned int > _num_neurons_per_layer
Hidden layer architecture.
void constructNeuralNetwork()
Construct the neural network.
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type.
unsigned int size() const
Return the number of active items in the MultiMooseEnum.

◆ LibtorchArtificialNeuralNet() [2/2]

Moose::LibtorchArtificialNeuralNet::LibtorchArtificialNeuralNet ( const Moose::LibtorchArtificialNeuralNet nn)

Copy construct an artificial neural network.

Parameters
nnThe neural network which needs to be copied

Definition at line 44 of file LibtorchArtificialNeuralNet.C.

46 : torch::nn::Module(),
47 _name(nn.name()),
54{
55
56 // We construct the NN architecture
58 // We fill it up with the current parameter values
59 const auto & from_params = nn.named_parameters();
60 auto to_params = this->named_parameters();
61 for (unsigned int param_i : make_range(from_params.size()))
62 to_params[param_i].value().data() = from_params[param_i].value().data().clone();
63}
torch::ScalarType dataType() const
Return the data type which is used by this neural network.
torch::DeviceType deviceType() const
Return the device which is used by this neural network.
unsigned int numOutputs() const
Return the number of neurons on the output layer.
const std::vector< unsigned int > & numNeuronsPerLayer() const
Return the hidden layer architecture.
unsigned int numInputs() const
Return the number of neurons on the input layer.
const MultiMooseEnum & activationFunctions() const
Return the multi enum containing the activation functions.
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)
IntRange< T > make_range(T beg, T end)

Member Function Documentation

◆ activationFunctions()

const MultiMooseEnum & Moose::LibtorchArtificialNeuralNet::activationFunctions ( ) const
inline

Return the multi enum containing the activation functions.

Definition at line 77 of file LibtorchArtificialNeuralNet.h.

77{ return _activation_function; }

◆ addLayer()

void Moose::LibtorchArtificialNeuralNet::addLayer ( const std::string &  layer_name,
const std::unordered_map< std::string, unsigned int > &  parameters 
)
virtual

Add layers to the neural network.

Parameters
layer_nameThe name of the layer to be added
parametersA map of parameter names and the corresponding values which describe the neural net layer architecture

Definition at line 118 of file LibtorchArtificialNeuralNet.C.

121{
122 auto it = parameters.find("inp_neurons");
123 if (it == parameters.end())
124 ::mooseError("Number of input neurons not found during the construction of "
125 "LibtorchArtificialNeuralNet!");
126 unsigned int inp_neurons = it->second;
127
128 it = parameters.find("out_neurons");
129 if (it == parameters.end())
130 ::mooseError("Number of output neurons not found during the construction of "
131 "LibtorchArtificialNeuralNet!");
132 unsigned int out_neurons = it->second;
133
134 _weights.push_back(register_module(layer_name, torch::nn::Linear(inp_neurons, out_neurons)));
135}
std::vector< torch::nn::Linear > _weights
Submodules that hold linear operations and the corresponding weights and biases (y = W * x + b)

Referenced by constructNeuralNetwork().

◆ constructNeuralNetwork()

void Moose::LibtorchArtificialNeuralNet::constructNeuralNetwork ( )

Construct the neural network.

Definition at line 66 of file LibtorchArtificialNeuralNet.C.

67{
68 // Adding hidden layers
69 unsigned int inp_neurons = _num_inputs;
70 for (unsigned int i = 0; i < numHiddenLayers(); ++i)
71 {
72 std::unordered_map<std::string, unsigned int> parameters = {
73 {"inp_neurons", inp_neurons}, {"out_neurons", _num_neurons_per_layer[i]}};
74 addLayer("hidden_layer_" + std::to_string(i + 1), parameters);
75
76 // Necessary to retain double precision (and error-free runs)
78 inp_neurons = _num_neurons_per_layer[i];
79 }
80 // Adding output layer
81 std::unordered_map<std::string, unsigned int> parameters = {{"inp_neurons", inp_neurons},
82 {"out_neurons", _num_outputs}};
83 addLayer("output_layer_", parameters);
84 _weights.back()->to(_device_type, _data_type);
85}
virtual void addLayer(const std::string &layer_name, const std::unordered_map< std::string, unsigned int > &parameters)
Add layers to the neural network.
unsigned int numHiddenLayers() const
Return the number of hidden layers.

Referenced by LibtorchArtificialNeuralNet(), and LibtorchArtificialNeuralNet().

◆ dataType()

torch::ScalarType Moose::LibtorchArtificialNeuralNet::dataType ( ) const
inline

Return the data type which is used by this neural network.

Definition at line 81 of file LibtorchArtificialNeuralNet.h.

81{ return _data_type; }

◆ deviceType()

torch::DeviceType Moose::LibtorchArtificialNeuralNet::deviceType ( ) const
inline

Return the device which is used by this neural network.

Definition at line 79 of file LibtorchArtificialNeuralNet.h.

79{ return _device_type; }

◆ forward()

torch::Tensor Moose::LibtorchArtificialNeuralNet::forward ( const torch::Tensor &  x)
overridevirtual

Overriding the forward substitution function for the neural network, unfortunately this cannot be const since it creates a graph in the background.

Parameters
xInput tensor for the evaluation

Implements Moose::LibtorchNeuralNetBase.

Definition at line 88 of file LibtorchArtificialNeuralNet.C.

89{
90 torch::Tensor output(x);
91 if (_data_type != output.scalar_type())
92 output.to(_data_type);
93 if (_device_type != output.device().type())
94 output.to(_device_type);
95
96 for (unsigned int i = 0; i < _weights.size() - 1; ++i)
97 {
98 std::string activation =
100 if (activation == "relu")
101 output = torch::relu(_weights[i]->forward(output));
102 else if (activation == "sigmoid")
103 output = torch::sigmoid(_weights[i]->forward(output));
104 else if (activation == "elu")
105 output = torch::elu(_weights[i]->forward(output));
106 else if (activation == "gelu")
107 output = torch::gelu(_weights[i]->forward(output));
108 else if (activation == "linear")
109 output = _weights[i]->forward(output);
110 }
111
112 output = _weights[_weights.size() - 1]->forward(output);
113
114 return output;
115}
virtual torch::Tensor forward(const torch::Tensor &x) override
Overriding the forward substitution function for the neural network, unfortunately this cannot be con...

Referenced by forward().

◆ name()

const std::string & Moose::LibtorchArtificialNeuralNet::name ( ) const
inline

Return the name of the neural network.

Definition at line 67 of file LibtorchArtificialNeuralNet.h.

67{ return _name; }

◆ numHiddenLayers()

unsigned int Moose::LibtorchArtificialNeuralNet::numHiddenLayers ( ) const
inline

Return the number of hidden layers.

Definition at line 73 of file LibtorchArtificialNeuralNet.h.

73{ return _num_neurons_per_layer.size(); }

Referenced by constructNeuralNetwork().

◆ numInputs()

unsigned int Moose::LibtorchArtificialNeuralNet::numInputs ( ) const
inline

Return the number of neurons on the input layer.

Definition at line 69 of file LibtorchArtificialNeuralNet.h.

69{ return _num_inputs; }

◆ numNeuronsPerLayer()

const std::vector< unsigned int > & Moose::LibtorchArtificialNeuralNet::numNeuronsPerLayer ( ) const
inline

Return the hidden layer architecture.

Definition at line 75 of file LibtorchArtificialNeuralNet.h.

75{ return _num_neurons_per_layer; }

◆ numOutputs()

unsigned int Moose::LibtorchArtificialNeuralNet::numOutputs ( ) const
inline

Return the number of neurons on the output layer.

Definition at line 71 of file LibtorchArtificialNeuralNet.h.

71{ return _num_outputs; }

◆ store()

void Moose::LibtorchArtificialNeuralNet::store ( nlohmann::json &  json) const

Store the network architecture in a json file (for debugging, visualization)

Definition at line 138 of file LibtorchArtificialNeuralNet.C.

139{
140 const auto & named_params = this->named_parameters();
141 for (const auto & param_i : make_range(named_params.size()))
142 {
143 // We cast the parameters into a 1D vector
144 json[named_params[param_i].key()] = std::vector<Real>(
145 named_params[param_i].value().data_ptr<Real>(),
146 named_params[param_i].value().data_ptr<Real>() + named_params[param_i].value().numel());
147 }
148}

Referenced by Moose::to_json().

Member Data Documentation

◆ _activation_function

MultiMooseEnum Moose::LibtorchArtificialNeuralNet::_activation_function
protected

Activation functions (either one for all hidden layers or one for every layer separately)

Definition at line 102 of file LibtorchArtificialNeuralNet.h.

Referenced by activationFunctions(), forward(), and LibtorchArtificialNeuralNet().

◆ _data_type

const torch::ScalarType Moose::LibtorchArtificialNeuralNet::_data_type
protected

The data type used in this neural network.

Definition at line 106 of file LibtorchArtificialNeuralNet.h.

Referenced by constructNeuralNetwork(), dataType(), and forward().

◆ _device_type

const torch::DeviceType Moose::LibtorchArtificialNeuralNet::_device_type
protected

The device type used for this neural network.

Definition at line 104 of file LibtorchArtificialNeuralNet.h.

Referenced by constructNeuralNetwork(), deviceType(), and forward().

◆ _name

const std::string Moose::LibtorchArtificialNeuralNet::_name
protected

Name of the neural network.

Definition at line 90 of file LibtorchArtificialNeuralNet.h.

Referenced by name().

◆ _num_inputs

const unsigned int Moose::LibtorchArtificialNeuralNet::_num_inputs
protected

Definition at line 95 of file LibtorchArtificialNeuralNet.h.

Referenced by constructNeuralNetwork(), and numInputs().

◆ _num_neurons_per_layer

const std::vector<unsigned int> Moose::LibtorchArtificialNeuralNet::_num_neurons_per_layer
protected

Hidden layer architecture.

Definition at line 99 of file LibtorchArtificialNeuralNet.h.

Referenced by constructNeuralNetwork(), LibtorchArtificialNeuralNet(), numHiddenLayers(), and numNeuronsPerLayer().

◆ _num_outputs

const unsigned int Moose::LibtorchArtificialNeuralNet::_num_outputs
protected

Number of neurons on the output layer.

Definition at line 97 of file LibtorchArtificialNeuralNet.h.

Referenced by constructNeuralNetwork(), and numOutputs().

◆ _weights

std::vector<torch::nn::Linear> Moose::LibtorchArtificialNeuralNet::_weights
protected

Submodules that hold linear operations and the corresponding weights and biases (y = W * x + b)

Definition at line 93 of file LibtorchArtificialNeuralNet.h.

Referenced by addLayer(), constructNeuralNetwork(), and forward().


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