https://mooseframework.inl.gov
Loading...
Searching...
No Matches
LibtorchArtificialNeuralNet.h
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
12#pragma once
13
14#include <torch/torch.h>
15#include <torch/script.h>
16#include <torch/serialize/archive.h>
18#include "MooseError.h"
19#include "DataIO.h"
20#include "MultiMooseEnum.h"
21#include "nlohmann/json.h"
22
23namespace Moose
24{
25
29class LibtorchArtificialNeuralNet : public torch::nn::Module, public LibtorchNeuralNetBase
30{
31public:
46 LibtorchArtificialNeuralNet(const std::string name,
47 const unsigned int num_inputs,
48 const unsigned int num_outputs,
49 const std::vector<unsigned int> & num_neurons_per_layer,
50 const std::vector<std::string> & activation_function = {"relu"},
51 const torch::DeviceType device_type = torch::kCPU,
52 const torch::ScalarType scalar_type = torch::kDouble,
53 const bool build_on_construct = true,
54 const std::vector<Real> & input_shift_factors = {},
55 const std::vector<Real> & input_scaling_factors = {},
56 const std::vector<Real> & output_scaling_factors = {});
57
64 const bool build_on_construct = true);
65
71 virtual void addLayer(const std::string & layer_name,
72 const std::unordered_map<std::string, unsigned int> & parameters);
73
78 virtual torch::Tensor forward(const torch::Tensor & x) override;
79
83 const std::string & name() const { return _name; }
87 unsigned int numInputs() const { return _num_inputs; }
91 unsigned int numOutputs() const { return _num_outputs; }
95 unsigned int numHiddenLayers() const { return _num_neurons_per_layer.size(); }
99 const std::vector<unsigned int> & numNeuronsPerLayer() const { return _num_neurons_per_layer; }
107 torch::DeviceType deviceType() const { return _device_type; }
111 torch::ScalarType dataType() const { return _data_type; }
115 const std::vector<Real> & inputShiftFactors() const { return _input_shift_factors; }
119 const std::vector<Real> & inputScalingFactors() const { return _input_scaling_factors; }
123 const std::vector<Real> & outputScalingFactors() const { return _output_scaling_factors; }
127 virtual void constructNeuralNetwork();
128
133
138 Real determineGain(const std::string & activation);
139
144 virtual void initializeNeuralNetwork(c10::optional<at::Generator> generator = c10::nullopt);
145
150 void store(nlohmann::json & json) const;
151
152protected:
160 static std::vector<Real> setAffineFactors(const std::vector<Real> & factors,
161 unsigned int expected_size,
162 Real default_value,
163 const std::string & factor_name);
164
169
174 virtual torch::Tensor preprocessInput(const torch::Tensor & x) const;
175
180 virtual torch::Tensor scaleOutput(const torch::Tensor & y) const;
181
183 const std::string _name;
186 std::vector<torch::nn::Linear> _weights;
188 const unsigned int _num_inputs;
190 const unsigned int _num_outputs;
192 const std::vector<unsigned int> _num_neurons_per_layer;
197 const torch::DeviceType _device_type;
199 const torch::ScalarType _data_type;
201 std::vector<Real> _input_shift_factors;
203 std::vector<Real> _input_scaling_factors;
205 std::vector<Real> _output_scaling_factors;
207 torch::Tensor _input_shift_tensor;
209 torch::Tensor _input_scale_tensor;
211 torch::Tensor _output_scale_tensor;
212};
213
219void to_json(nlohmann::json & json, const Moose::LibtorchArtificialNeuralNet * const & network);
220
227 const std::string & filename);
228}
229
236template <>
238 std::ostream & stream,
239 std::shared_ptr<Moose::LibtorchArtificialNeuralNet> & nn,
240 void * context);
241
248template <>
250 std::istream & stream,
251 std::shared_ptr<Moose::LibtorchArtificialNeuralNet> & nn,
252 void * context);
253
254// This is needed because the reporter which is used to ouput the neural net parameters to JSON
255// requires a dataStore/dataLoad. However, these functions will be empty due to the fact that
256// we are only interested in the JSON output and we don't want to output everything
263template <>
265 std::ostream & stream, Moose::LibtorchArtificialNeuralNet const *& nn, void * context);
266
273template <>
275 std::istream & stream, Moose::LibtorchArtificialNeuralNet const *& nn, void * context);
276
277#endif
void dataStore< Moose::LibtorchArtificialNeuralNet >(std::ostream &stream, std::shared_ptr< Moose::LibtorchArtificialNeuralNet > &nn, void *context)
Serialize the artificial-neural-network metadata needed for restart.
void dataLoad< Moose::LibtorchArtificialNeuralNet const >(std::istream &stream, Moose::LibtorchArtificialNeuralNet const *&nn, void *context)
Placeholder deserializer for reporter-only artificial-neural-network pointers.
void dataStore< Moose::LibtorchArtificialNeuralNet const >(std::ostream &stream, Moose::LibtorchArtificialNeuralNet const *&nn, void *context)
Placeholder serializer for reporter-only artificial-neural-network pointers.
void dataLoad< Moose::LibtorchArtificialNeuralNet >(std::istream &stream, std::shared_ptr< Moose::LibtorchArtificialNeuralNet > &nn, void *context)
Deserialize the artificial-neural-network metadata needed for restart.
Simple feed-forward neural net with optional affine input and output scaling.
torch::ScalarType dataType() const
Return the data type used by this neural network.
const unsigned int _num_inputs
Number of neurons on the input layer.
Real determineGain(const std::string &activation)
Map an activation name to the orthogonal-initialization gain we want to use.
virtual torch::Tensor forward(const torch::Tensor &x) override
Run a forward pass through the network.
torch::Tensor _input_shift_tensor
Registered libtorch buffer holding the affine input shifts.
const torch::ScalarType _data_type
The data type used in this neural network.
void store(nlohmann::json &json) const
Store the network architecture in a JSON object for debugging or visualization.
static std::vector< Real > setAffineFactors(const std::vector< Real > &factors, unsigned int expected_size, Real default_value, const std::string &factor_name)
Set affine metadata by either accepting the user values or filling defaults.
std::vector< Real > _input_shift_factors
Affine preprocessing applied to the flattened input.
const std::vector< Real > & outputScalingFactors() const
Return the output scaling factors applied after evaluation.
torch::DeviceType deviceType() const
Return the device used by this neural network.
void synchronizeAffineFactorsFromBuffers()
Update cached affine metadata vectors from the registered libtorch buffers.
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.
std::vector< Real > _input_scaling_factors
Multiplicative affine preprocessing applied after shifting the input.
std::vector< torch::nn::Linear > _weights
Submodules that hold linear operations and the corresponding weights and biases (y = W * x + b)
const std::vector< Real > & inputShiftFactors() const
Return the affine input shift factors used before evaluation.
unsigned int numOutputs() const
Return the number of neurons on the output layer.
void initializeAffineBuffers()
Initialize the registered affine metadata buffers used by serialization.
virtual void addLayer(const std::string &layer_name, const std::unordered_map< std::string, unsigned int > &parameters)
Add one linear layer to the network.
torch::Tensor _input_scale_tensor
Registered libtorch buffer holding the affine input scaling factors.
const unsigned int _num_outputs
Number of neurons on the output layer.
const std::vector< unsigned int > & numNeuronsPerLayer() const
Return the hidden layer architecture.
torch::Tensor _output_scale_tensor
Registered libtorch buffer holding the output scaling factors.
const std::string _name
Name of the neural network.
const torch::DeviceType _device_type
The device type used for this neural network.
virtual torch::Tensor preprocessInput(const torch::Tensor &x) const
Apply affine preprocessing to the raw input tensor.
unsigned int numHiddenLayers() const
Return the number of hidden layers.
unsigned int numInputs() const
Return the number of neurons on the input layer.
const std::vector< Real > & inputScalingFactors() const
Return the affine input scaling factors used before evaluation.
const std::vector< unsigned int > _num_neurons_per_layer
Hidden layer architecture.
virtual void initializeNeuralNetwork(c10::optional< at::Generator > generator=c10::nullopt)
Initialize the trainable weights and biases.
const MultiMooseEnum & activationFunctions() const
Return the multi enum containing the activation functions.
std::vector< Real > _output_scaling_factors
Multiplicative scaling applied after the network output is formed.
virtual torch::Tensor scaleOutput(const torch::Tensor &y) const
Apply the configured output scaling to a network output tensor.
virtual void constructNeuralNetwork()
Construct the neural network.
This base class is meant to gather the functions and members common in every neural network based on ...
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type.
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
void to_json(nlohmann::json &json, const Moose::LibtorchArtificialNeuralNet *const &network)
Dump an artificial neural network into JSON for reporter output and debugging.
void loadLibtorchArtificialNeuralNetState(Moose::LibtorchArtificialNeuralNet &nn, const std::string &filename)
Load an artificial-neural-network checkpoint written as a native libtorch state archive.