https://mooseframework.inl.gov
Loading...
Searching...
No Matches
GaussianProcessTrainer.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#ifdef MOOSE_LIBTORCH_ENABLED
10
12#include "Sampler.h"
13#include "CartesianProduct.h"
14
15#include <petsctao.h>
16#include <petscdmda.h>
17
18#include "libmesh/petsc_vector.h"
19#include "libmesh/petsc_matrix.h"
20
21#include <cmath>
22
24
27{
29 params.addClassDescription("Provides data preperation and training for a single- or multi-output "
30 "Gaussian Process surrogate model.");
31
32 params.addRequiredParam<UserObjectName>("covariance_function", "Name of covariance function.");
33 params.addParam<bool>(
34 "standardize_params", true, "Standardize (center and scale) training parameters (x values)");
35 params.addParam<bool>(
36 "standardize_data", true, "Standardize (center and scale) training data (y values)");
37 // Already preparing to use Adam here
38 params.addParam<unsigned int>("num_iters", 1000, "Tolerance value for Adam optimization");
39 params.addParam<unsigned int>("batch_size", 0, "The batch size for Adam optimization");
40 params.addParam<Real>("learning_rate", 0.001, "The learning rate for Adam optimization");
41 params.addParam<MooseEnum>(
42 "optimizer",
43 MooseEnum("adam=0 legacy_adam=1", "adam"),
44 "The Adam optimizer semantics to use for Gaussian process hyperparameter tuning.");
45 params.addParam<unsigned int>(
46 "show_every_nth_iteration",
47 0,
48 "Switch to show Adam optimization loss values at every nth step. If 0, nothing is showed.");
49 params.addParam<std::vector<std::string>>("tune_parameters",
50 "Select hyperparameters to be tuned");
51 params.addParam<std::vector<Real>>("tuning_min", "Minimum allowable tuning value");
52 params.addParam<std::vector<Real>>("tuning_max", "Maximum allowable tuning value");
53 return params;
54}
55
57 : SurrogateTrainer(parameters),
58 CovarianceInterface(parameters),
59 _predictor_row(getPredictorData()),
60 _gp(declareModelData<StochasticTools::GaussianProcess>("_gp")),
61 _training_params(declareModelData<torch::Tensor>("_training_params")),
62 _standardize_params(getParam<bool>("standardize_params")),
63 _standardize_data(getParam<bool>("standardize_data")),
64 _do_tuning(isParamValid("tune_parameters")),
65 _optimization_opts(StochasticTools::GaussianProcess::GPOptimizerOptions(
66 getParam<unsigned int>("show_every_nth_iteration"),
67 getParam<unsigned int>("num_iters"),
68 getParam<unsigned int>("batch_size"),
69 getParam<Real>("learning_rate"),
70 0.9,
71 0.999,
72 1e-7,
73 1e-4,
74 getParam<MooseEnum>("optimizer")
75 .getEnum<StochasticTools::GaussianProcess::OptimizerType>())),
76 _sampler_row(getSamplerData())
77{
78 // Error Checking
79 if (parameters.isParamSetByUser("batch_size"))
81 paramError("batch_size", "Batch size cannot be greater than the training data set size.");
82
83 std::vector<std::string> tune_parameters(
84 _do_tuning ? getParam<std::vector<std::string>>("tune_parameters")
85 : std::vector<std::string>{});
86
87 if (isParamValid("tuning_min") &&
88 (getParam<std::vector<Real>>("tuning_min").size() != tune_parameters.size()))
89 mooseError("tuning_min size does not match tune_parameters");
90 if (isParamValid("tuning_max") &&
91 (getParam<std::vector<Real>>("tuning_max").size() != tune_parameters.size()))
92 mooseError("tuning_max size does not match tune_parameters");
93
94 std::vector<Real> lower_bounds, upper_bounds;
95 if (isParamValid("tuning_min"))
96 lower_bounds = getParam<std::vector<Real>>("tuning_min");
97 if (isParamValid("tuning_max"))
98 upper_bounds = getParam<std::vector<Real>>("tuning_max");
99
100 _gp.initialize(getCovarianceFunctionByName(parameters.get<UserObjectName>("covariance_function")),
101 tune_parameters,
102 lower_bounds,
103 upper_bounds);
104
106}
107
108void
116
117void
119{
121
122 if (_rvecval && _rvecval->size() != _n_outputs)
123 mooseError("The size of the provided response (",
124 _rvecval->size(),
125 ") does not match the number of expected outputs from the covariance (",
127 ")!");
128
129 _data_buffer.push_back(_rvecval ? (*_rvecval) : std::vector<Real>(1, *_rval));
130}
131
132void
134{
135 // Instead of gatherSum, we have to allgather.
138
139 _training_params = torch::empty({long(_params_buffer.size()), _n_dims}, at::kDouble);
140 _training_data = torch::empty({long(_data_buffer.size()), _n_outputs}, at::kDouble);
141
142 auto params_accessor = _training_params.accessor<Real, 2>();
143 auto data_accessor = _training_data.accessor<Real, 2>();
144
145 for (auto ii : make_range(_training_params.sizes()[0]))
146 {
147 for (auto jj : make_range(_n_dims))
148 params_accessor[ii][jj] = _params_buffer[ii][jj];
149 for (auto jj : make_range(_n_outputs))
150 data_accessor[ii][jj] = _data_buffer[ii][jj];
151 }
152
155
156 // Standardize (center and scale) training params
159 // if not standardizing data set mean=0, std=1 for use in surrogate
160 else
162 // Standardize (center and scale) training data
165 // if not standardizing data set mean=0, std=1 for use in surrogate
166 else
168
169 // Setup the covariance
171}
172
173#endif
registerMooseObject("StochasticToolsApp", GaussianProcessTrainer)
void ErrorVector unsigned int
unsigned int numOutputs() const
Return the number of outputs assumed for this covariance function.
CovarianceFunctionBase * getCovarianceFunctionByName(const UserObjectName &name) const
Lookup a CovarianceFunction object by name and return pointer.
virtual void postTrain() override
virtual void preTrain() override
StochasticTools::GaussianProcess & _gp
Gaussian process handler responsible for managing training related tasks.
std::vector< std::vector< Real > > _data_buffer
Data (y) used for training.
bool _do_tuning
Flag to toggle hyperparameter tuning/optimization.
torch::Tensor _training_data
Data (y) used for training.
bool _standardize_data
Switch for training data(y) standardization.
const std::vector< Real > & _predictor_row
Data from the current predictor row.
std::vector< std::vector< Real > > _params_buffer
Parameters (x) used for training – we'll allgather these in postTrain().
GaussianProcessTrainer(const InputParameters &parameters)
const StochasticTools::GaussianProcess::GPOptimizerOptions _optimization_opts
Struct holding parameters necessary for parameter tuning.
static InputParameters validParams()
torch::Tensor & _training_params
Paramaters (x) used for training, along with statistics.
virtual void train() override
bool _standardize_params
Switch for training param (x) standardization.
bool isParamSetByUser(const std::string &name) const
void addRequiredParam(const std::string &name, const std::string &doc_string)
void addParam(const std::string &name, const std::initializer_list< typename T::value_type > &value, const std::string &doc_string)
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
void addClassDescription(const std::string &doc_string)
torch::DeviceType getLibtorchDevice() const
const InputParameters & parameters() const
void paramError(const std::string &param, Args... args) const
void mooseError(Args &&... args) const
const T & getParam(const std::string &name) const
bool isParamValid(const std::string &name) const
dof_id_type getNumberOfRows() const
void standardizeParameters(torch::Tensor &parameters, bool keep_moments=false)
Standardizes the vector of input parameters (x values).
void initialize(CovarianceFunctionBase *covariance_function, const std::vector< std::string > &params_to_tune, const std::vector< Real > &min=std::vector< Real >(), const std::vector< Real > &max=std::vector< Real >())
Initializes the most important structures in the Gaussian Process: the covariance function and a tuni...
const CovarianceFunctionBase & getCovarFunction() const
StochasticTools::Standardizer & paramStandardizer()
Get non-constant reference to the contained structures (if they need to be modified from the utside)
StochasticTools::Standardizer & dataStandardizer()
void standardizeData(torch::Tensor &data, bool keep_moments=false)
Standardizes the vector of responses (y values).
void setupCovarianceMatrix(const torch::Tensor &training_params, const torch::Tensor &training_data, const GPOptimizerOptions &opts)
Sets up the covariance matrix given data and optimization options.
void set(const Real &n)
Methods for setting mean and standard deviation directly Sets mean=0, std=1 for n variables.
This is the main trainer base class.
unsigned int getLocalSampleSize() const
const std::vector< Real > * _rvecval
Vector response value.
unsigned int & _n_outputs
The number of outputs.
const Real * _rval
Response value.
static InputParameters validParams()
unsigned int _n_dims
Dimension of predictor data - either _sampler.getNumberOfCols() or _pvals.size() + _pcols....
void allgather(const T &send_data, std::vector< T, A > &recv_data) const
const Parallel::Communicator & _communicator
void moveToLibtorchDevice(torch::Tensor &tensor, const torch::DeviceType device_type)
Enum for batch type in stochastic tools MultiApp.
const unsigned int batch_size
The batch size for Adam optimizer.