https://mooseframework.inl.gov
Classes | Public Types | Public Member Functions | Protected Attributes | List of all members
StochasticTools::GaussianProcess Class Reference

Utility class dedicated to hold structures and functions commont to Gaussian Processes. More...

#include <GaussianProcess.h>

Classes

struct  GPOptimizerOptions
 Structure containing the optimization options for hyperparameter-tuning. More...
 

Public Types

enum  OptimizerType { OptimizerType::Adam, OptimizerType::LegacyAdam }
 
using HyperParameterMap = CovarianceFunctionBase::HyperParameterMap
 

Public Member Functions

 GaussianProcess ()
 
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 tuning map which is used if the user requires parameter tuning. More...
 
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. More...
 
void setupStoredMatrices (const torch::Tensor &input)
 Sets up the Cholesky decomposition and inverse action of the covariance matrix. More...
 
void linkCovarianceFunction (CovarianceFunctionBase *covariance_function)
 Finds and links the covariance function to this object. More...
 
void generateTuningMap (const std::vector< std::string > &params_to_tune, const std::vector< Real > &min=std::vector< Real >(), const std::vector< Real > &max=std::vector< Real >())
 Sets up the tuning map which is used if the user requires parameter tuning. More...
 
void standardizeParameters (torch::Tensor &parameters, bool keep_moments=false)
 Standardizes the vector of input parameters (x values). More...
 
void standardizeData (torch::Tensor &data, bool keep_moments=false)
 Standardizes the vector of responses (y values). More...
 
void tuneHyperParamsAdam (const torch::Tensor &training_params, const torch::Tensor &training_data, const GPOptimizerOptions &opts)
 
Real getLoss (torch::Tensor &inputs, torch::Tensor &outputs)
 
std::vector< RealgetGradient (torch::Tensor &inputs) const
 
void mapToVec (const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &tuning_data, const HyperParameterMap &hyperparam_map, std::vector< Real > &vec) const
 Function used to convert the hyperparameter map in this object to a flat vector. More...
 
void vecToMap (const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &tuning_data, HyperParameterMap &hyperparam_map, const std::vector< Real > &vec) const
 Function used to convert the vector back to the hyperparameter map. More...
 
const StochasticTools::StandardizergetParamStandardizer () const
 Get constant reference to the contained structures. More...
 
const StochasticTools::StandardizergetDataStandardizer () const
 
const torch::TensorgetK () const
 
const torch::TensorgetKResultsSolve () const
 
const torch::TensorgetKCholeskyDecomp () const
 
const CovarianceFunctionBasegetCovarFunction () const
 
const CovarianceFunctionBasegetCovarFunctionPtr () const
 
const std::string & getCovarType () const
 
const std::string & getCovarName () const
 
const std::vector< UserObjectName > & getDependentCovarNames () const
 
const std::map< UserObjectName, std::string > & getDependentCovarTypes () const
 
const unsigned intgetCovarNumOutputs () const
 
const unsigned intgetNumTunableParams () const
 
const HyperParameterMapgetHyperParamMap () const
 
const std::vector< Real > & getLengthScales () const
 
StochasticTools::StandardizerparamStandardizer ()
 Get non-constant reference to the contained structures (if they need to be modified from the utside) More...
 
StochasticTools::StandardizerdataStandardizer ()
 
torch::TensorK ()
 
torch::TensorKResultsSolve ()
 
torch::TensorKCholeskyDecomp ()
 
CovarianceFunctionBasecovarFunctionPtr ()
 
CovarianceFunctionBasecovarFunction ()
 
std::string & covarType ()
 
std::string & covarName ()
 
std::map< UserObjectName, std::string > & dependentCovarTypes ()
 
std::vector< UserObjectName > & dependentCovarNames ()
 
unsigned intcovarNumOutputs ()
 
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > & tuningData ()
 
HyperParameterMaphyperparamMap ()
 
std::vector< Real > & lengthScales ()
 

Protected Attributes

CovarianceFunctionBase_covariance_function = nullptr
 Covariance function object. More...
 
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
 Contains tuning inforation. Index of hyperparam, size, and min/max bounds. More...
 
unsigned int _num_tunable = 0
 Number of tunable hyperparameters. More...
 
std::string _covar_type
 Type of covariance function used for this GP. More...
 
std::string _covar_name
 The name of the covariance function used in this GP. More...
 
std::vector< UserObjectName > _dependent_covar_names
 The names of the covariance functions the used covariance function depends on. More...
 
std::map< UserObjectName, std::string > _dependent_covar_types
 The types of the covariance functions the used covariance function depends on. More...
 
unsigned int _num_outputs = 0
 The number of outputs of the GP. More...
 
HyperParameterMap _hyperparam_map
 Hyperparameters. Stored as tensors for use in surrogate reload/reporting. More...
 
StochasticTools::Standardizer _param_standardizer
 Standardizer for use with params (x) More...
 
StochasticTools::Standardizer _data_standardizer
 Standardizer for use with data (y) More...
 
torch::Tensor _K
 An _n_sample by _n_sample covariance matrix constructed from the selected kernel function. More...
 
torch::Tensor _K_results_solve
 A solve of Ax=b via Cholesky. More...
 
torch::Tensor _K_cho_decomp
 Cholesky decomposition libtorch tensor object. More...
 
unsigned int _batch_size = 0
 The batch size for Adam optimization. More...
 
std::vector< Real_length_scales
 To return the GP length scales for active learning. More...
 

Detailed Description

Utility class dedicated to hold structures and functions commont to Gaussian Processes.

It can be used to standardize parameters, manipulate covariance data and compute additional stored matrices.

Definition at line 27 of file GaussianProcess.h.

Member Typedef Documentation

◆ HyperParameterMap

Definition at line 30 of file GaussianProcess.h.

Member Enumeration Documentation

◆ OptimizerType

Enumerator
Adam 
LegacyAdam 

Definition at line 34 of file GaussianProcess.h.

35  {
36  Adam,
37  LegacyAdam
38  };

Constructor & Destructor Documentation

◆ GaussianProcess()

StochasticTools::GaussianProcess::GaussianProcess ( )

Definition at line 129 of file GaussianProcess.C.

129 {}

Member Function Documentation

◆ covarFunction()

CovarianceFunctionBase& StochasticTools::GaussianProcess::covarFunction ( )
inline

Definition at line 216 of file GaussianProcess.h.

216 { return *_covariance_function; }
CovarianceFunctionBase * _covariance_function
Covariance function object.

◆ covarFunctionPtr()

CovarianceFunctionBase* StochasticTools::GaussianProcess::covarFunctionPtr ( )
inline

Definition at line 215 of file GaussianProcess.h.

215 { return _covariance_function; }
CovarianceFunctionBase * _covariance_function
Covariance function object.

◆ covarName()

std::string& StochasticTools::GaussianProcess::covarName ( )
inline

Definition at line 218 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

218 { return _covar_name; }
std::string _covar_name
The name of the covariance function used in this GP.

◆ covarNumOutputs()

unsigned int& StochasticTools::GaussianProcess::covarNumOutputs ( )
inline

Definition at line 221 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

221 { return _num_outputs; }
unsigned int _num_outputs
The number of outputs of the GP.

◆ covarType()

std::string& StochasticTools::GaussianProcess::covarType ( )
inline

Definition at line 217 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

217 { return _covar_type; }
std::string _covar_type
Type of covariance function used for this GP.

◆ dataStandardizer()

StochasticTools::Standardizer& StochasticTools::GaussianProcess::dataStandardizer ( )
inline

Definition at line 211 of file GaussianProcess.h.

Referenced by dataLoad(), dataStore(), GaussianProcessTrainer::postTrain(), and ActiveLearningGaussianProcess::reTrain().

211 { return _data_standardizer; }
StochasticTools::Standardizer _data_standardizer
Standardizer for use with data (y)

◆ dependentCovarNames()

std::vector<UserObjectName>& StochasticTools::GaussianProcess::dependentCovarNames ( )
inline

Definition at line 220 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

220 { return _dependent_covar_names; }
std::vector< UserObjectName > _dependent_covar_names
The names of the covariance functions the used covariance function depends on.

◆ dependentCovarTypes()

std::map<UserObjectName, std::string>& StochasticTools::GaussianProcess::dependentCovarTypes ( )
inline

Definition at line 219 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

219 { return _dependent_covar_types; }
std::map< UserObjectName, std::string > _dependent_covar_types
The types of the covariance functions the used covariance function depends on.

◆ generateTuningMap()

void StochasticTools::GaussianProcess::generateTuningMap ( const std::vector< std::string > &  params_to_tune,
const std::vector< Real > &  min = std::vector<Real>(),
const std::vector< Real > &  max = std::vector<Real>() 
)

Sets up the tuning map which is used if the user requires parameter tuning.

Parameters
params_to_tuneList of parameters which need to be tuned.
minList of lower bounds for the parameter tuning.
maxList of upper bounds for parameter tuning.

Definition at line 196 of file GaussianProcess.C.

Referenced by initialize().

199 {
200  _num_tunable = 0;
201 
202  const bool upper_bounds_specified = min_vector.size();
203  const bool lower_bounds_specified = max_vector.size();
204 
205  for (const auto param_i : index_range(params_to_tune))
206  {
207  const auto & hp = params_to_tune[param_i];
209  {
210  unsigned int size;
211  Real min;
212  Real max;
213  // Get size and default min/max
214  const bool found = _covariance_function->getTuningData(hp, size, min, max);
215 
216  if (!found)
217  ::mooseError("The covariance parameter ", hp, " could not be found!");
218 
219  // Check for overridden min/max
220  min = lower_bounds_specified ? min_vector[param_i] : min;
221  max = upper_bounds_specified ? max_vector[param_i] : max;
222  // Save data in tuple
223  _tuning_data[hp] = std::make_tuple(_num_tunable, size, min, max);
224  _num_tunable += size;
225  }
226  }
227 }
unsigned int _num_tunable
Number of tunable hyperparameters.
CovarianceFunctionBase * _covariance_function
Covariance function object.
auto max(const L &left, const R &right)
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
Contains tuning inforation. Index of hyperparam, size, and min/max bounds.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
auto min(const L &left, const R &right)
virtual bool getTuningData(const std::string &name, unsigned int &size, Real &min, Real &max) const
Get the default minimum and maximum and size of a hyperparameter.
auto index_range(const T &sizable)
virtual bool isTunable(const std::string &name) const
Check if a given parameter is tunable.

◆ getCovarFunction()

const CovarianceFunctionBase& StochasticTools::GaussianProcess::getCovarFunction ( ) const
inline

Definition at line 187 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::evaluate(), and GaussianProcessTrainer::GaussianProcessTrainer().

187 { return *_covariance_function; }
CovarianceFunctionBase * _covariance_function
Covariance function object.

◆ getCovarFunctionPtr()

const CovarianceFunctionBase* StochasticTools::GaussianProcess::getCovarFunctionPtr ( ) const
inline

Definition at line 188 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::setupCovariance().

188 { return _covariance_function; }
CovarianceFunctionBase * _covariance_function
Covariance function object.

◆ getCovarName()

const std::string& StochasticTools::GaussianProcess::getCovarName ( ) const
inline

Definition at line 190 of file GaussianProcess.h.

190 { return _covar_name; }
std::string _covar_name
The name of the covariance function used in this GP.

◆ getCovarNumOutputs()

const unsigned int& StochasticTools::GaussianProcess::getCovarNumOutputs ( ) const
inline

Definition at line 199 of file GaussianProcess.h.

199 { return _num_outputs; }
unsigned int _num_outputs
The number of outputs of the GP.

◆ getCovarType()

const std::string& StochasticTools::GaussianProcess::getCovarType ( ) const
inline

Definition at line 189 of file GaussianProcess.h.

189 { return _covar_type; }
std::string _covar_type
Type of covariance function used for this GP.

◆ getDataStandardizer()

const StochasticTools::Standardizer& StochasticTools::GaussianProcess::getDataStandardizer ( ) const
inline

Definition at line 183 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::evaluate(), and ActiveLearningGaussianProcess::getTrainingStandardizer().

183 { return _data_standardizer; }
StochasticTools::Standardizer _data_standardizer
Standardizer for use with data (y)

◆ getDependentCovarNames()

const std::vector<UserObjectName>& StochasticTools::GaussianProcess::getDependentCovarNames ( ) const
inline

Definition at line 191 of file GaussianProcess.h.

192  {
193  return _dependent_covar_names;
194  }
std::vector< UserObjectName > _dependent_covar_names
The names of the covariance functions the used covariance function depends on.

◆ getDependentCovarTypes()

const std::map<UserObjectName, std::string>& StochasticTools::GaussianProcess::getDependentCovarTypes ( ) const
inline

Definition at line 195 of file GaussianProcess.h.

196  {
197  return _dependent_covar_types;
198  }
std::map< UserObjectName, std::string > _dependent_covar_types
The types of the covariance functions the used covariance function depends on.

◆ getGradient()

std::vector< Real > StochasticTools::GaussianProcess::getGradient ( torch::Tensor inputs) const

Definition at line 379 of file GaussianProcess.C.

Referenced by tuneHyperParamsAdam().

380 {
381  torch::Tensor dKdhp = torch::empty({_num_outputs * _batch_size, _num_outputs * _batch_size},
382  doubleOptionsLike(inputs));
383  std::vector<Real> grad_vec;
384  grad_vec.resize(_num_tunable);
385  for (auto iter = _tuning_data.begin(); iter != _tuning_data.end(); ++iter)
386  {
387  std::string hyper_param_name = iter->first;
388  const auto first_index = std::get<0>(iter->second);
389  const auto num_entries = std::get<1>(iter->second);
390  for (unsigned int ii = 0; ii < num_entries; ++ii)
391  {
392  const auto global_index = first_index + ii;
393  _covariance_function->computedKdhyper(dKdhp, inputs, hyper_param_name, ii);
394  const auto quadratic_form =
395  torch::mm(torch::transpose(_K_results_solve, 0, 1), torch::mm(dKdhp, _K_results_solve))
396  .item<Real>();
397  const auto inverse_trace =
398  torch::trace(torch::cholesky_solve(dKdhp, _K_cho_decomp)).item<Real>();
399  grad_vec[global_index] = (inverse_trace - quadratic_form) / 2.0;
400  }
401  }
402  return grad_vec;
403 }
unsigned int _num_tunable
Number of tunable hyperparameters.
CovarianceFunctionBase * _covariance_function
Covariance function object.
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.
unsigned int _num_outputs
The number of outputs of the GP.
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
Contains tuning inforation. Index of hyperparam, size, and min/max bounds.
unsigned int _batch_size
The batch size for Adam optimization.
virtual bool computedKdhyper(torch::Tensor &dKdhp, const torch::Tensor &x, const std::string &hyper_param_name, unsigned int ind) const
Redirect dK/dhp for hyperparameter "hp".
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real

◆ getHyperParamMap()

const HyperParameterMap& StochasticTools::GaussianProcess::getHyperParamMap ( ) const
inline

Definition at line 201 of file GaussianProcess.h.

Referenced by GaussianProcessData::initialize().

201 { return _hyperparam_map; }
HyperParameterMap _hyperparam_map
Hyperparameters. Stored as tensors for use in surrogate reload/reporting.

◆ getK()

const torch::Tensor& StochasticTools::GaussianProcess::getK ( ) const
inline

Definition at line 184 of file GaussianProcess.h.

184 { return _K; }
torch::Tensor _K
An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.

◆ getKCholeskyDecomp()

const torch::Tensor& StochasticTools::GaussianProcess::getKCholeskyDecomp ( ) const
inline

Definition at line 186 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::evaluate().

186 { return _K_cho_decomp; }
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.

◆ getKResultsSolve()

const torch::Tensor& StochasticTools::GaussianProcess::getKResultsSolve ( ) const
inline

Definition at line 185 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::evaluate().

185 { return _K_results_solve; }
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.

◆ getLengthScales()

const std::vector<Real>& StochasticTools::GaussianProcess::getLengthScales ( ) const
inline

Definition at line 202 of file GaussianProcess.h.

Referenced by ActiveLearningGaussianProcess::getLengthScales().

202 { return _length_scales; }
std::vector< Real > _length_scales
To return the GP length scales for active learning.

◆ getLoss()

Real StochasticTools::GaussianProcess::getLoss ( torch::Tensor inputs,
torch::Tensor outputs 
)

Definition at line 362 of file GaussianProcess.C.

Referenced by tuneHyperParamsAdam().

363 {
364  _covariance_function->computeCovarianceMatrix(_K, inputs, inputs, true);
365  const auto flattened_data = flattenOutputData(outputs);
366 
367  setupStoredMatrices(flattened_data);
368 
369  Real log_likelihood = 0;
370  log_likelihood +=
371  -1 * torch::mm(torch::transpose(flattened_data, 0, 1), _K_results_solve).item<Real>();
372  log_likelihood += -2.0 * torch::sum(torch::log(torch::diagonal(_K_cho_decomp))).item<Real>();
373  log_likelihood -= flattened_data.size(0) * std::log(2 * M_PI);
374  log_likelihood = -log_likelihood / 2;
375  return log_likelihood;
376 }
CovarianceFunctionBase * _covariance_function
Covariance function object.
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.
void setupStoredMatrices(const torch::Tensor &input)
Sets up the Cholesky decomposition and inverse action of the covariance matrix.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
torch::Tensor _K
An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.
virtual void computeCovarianceMatrix(torch::Tensor &K, const torch::Tensor &x, const torch::Tensor &xp, const bool is_self_covariance) const =0
Generates the Covariance Matrix given two sets of points in the parameter space.

◆ getNumTunableParams()

const unsigned int& StochasticTools::GaussianProcess::getNumTunableParams ( ) const
inline

Definition at line 200 of file GaussianProcess.h.

200 { return _num_tunable; }
unsigned int _num_tunable
Number of tunable hyperparameters.

◆ getParamStandardizer()

const StochasticTools::Standardizer& StochasticTools::GaussianProcess::getParamStandardizer ( ) const
inline

Get constant reference to the contained structures.

Definition at line 182 of file GaussianProcess.h.

Referenced by GaussianProcessSurrogate::evaluate().

182 { return _param_standardizer; }
StochasticTools::Standardizer _param_standardizer
Standardizer for use with params (x)

◆ hyperparamMap()

HyperParameterMap& StochasticTools::GaussianProcess::hyperparamMap ( )
inline

Definition at line 226 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

226 { return _hyperparam_map; }
HyperParameterMap _hyperparam_map
Hyperparameters. Stored as tensors for use in surrogate reload/reporting.

◆ initialize()

void StochasticTools::GaussianProcess::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 tuning map which is used if the user requires parameter tuning.

Parameters
covariance_functionPointer to the covariance function that needs to be used for the Gaussian Process.
params_to_tuneList of parameters which need to be tuned.
minList of lower bounds for the parameter tuning.
maxList of upper bounds for parameter tuning.

Definition at line 132 of file GaussianProcess.C.

Referenced by ActiveLearningGaussianProcess::ActiveLearningGaussianProcess(), and GaussianProcessTrainer::GaussianProcessTrainer().

136 {
137  linkCovarianceFunction(covariance_function);
138  generateTuningMap(params_to_tune, min, max);
139 }
void linkCovarianceFunction(CovarianceFunctionBase *covariance_function)
Finds and links the covariance function to this object.
void generateTuningMap(const std::vector< std::string > &params_to_tune, const std::vector< Real > &min=std::vector< Real >(), const std::vector< Real > &max=std::vector< Real >())
Sets up the tuning map which is used if the user requires parameter tuning.

◆ K()

torch::Tensor& StochasticTools::GaussianProcess::K ( )
inline

Definition at line 212 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

212 { return _K; }
torch::Tensor _K
An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.

◆ KCholeskyDecomp()

torch::Tensor& StochasticTools::GaussianProcess::KCholeskyDecomp ( )
inline

Definition at line 214 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

214 { return _K_cho_decomp; }
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.

◆ KResultsSolve()

torch::Tensor& StochasticTools::GaussianProcess::KResultsSolve ( )
inline

Definition at line 213 of file GaussianProcess.h.

Referenced by dataLoad(), and dataStore().

213 { return _K_results_solve; }
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.

◆ lengthScales()

std::vector<Real>& StochasticTools::GaussianProcess::lengthScales ( )
inline

Definition at line 227 of file GaussianProcess.h.

227 { return _length_scales; }
std::vector< Real > _length_scales
To return the GP length scales for active learning.

◆ linkCovarianceFunction()

void StochasticTools::GaussianProcess::linkCovarianceFunction ( CovarianceFunctionBase covariance_function)

Finds and links the covariance function to this object.

Used mainly in the covariance data action.

Parameters
covariance_functionPointer to the covariance function that needs to be used for the Gaussian Process.

Definition at line 142 of file GaussianProcess.C.

Referenced by initialize(), and GaussianProcessSurrogate::setupCovariance().

143 {
144  _covariance_function = covariance_function;
150 }
CovarianceFunctionBase * _covariance_function
Covariance function object.
std::string _covar_name
The name of the covariance function used in this GP.
std::map< UserObjectName, std::string > _dependent_covar_types
The types of the covariance functions the used covariance function depends on.
const std::string & name() const
unsigned int _num_outputs
The number of outputs of the GP.
std::vector< UserObjectName > _dependent_covar_names
The names of the covariance functions the used covariance function depends on.
const std::string & type() const
const std::vector< UserObjectName > & dependentCovarianceNames() const
Get the names of the dependent covariances.
void dependentCovarianceTypes(std::map< UserObjectName, std::string > &name_type_map) const
Populate a map with the names and types of the dependent covariance functions.
std::string _covar_type
Type of covariance function used for this GP.
unsigned int numOutputs() const
Return the number of outputs assumed for this covariance function.

◆ mapToVec()

void StochasticTools::GaussianProcess::mapToVec ( const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &  tuning_data,
const HyperParameterMap hyperparam_map,
std::vector< Real > &  vec 
) const

Function used to convert the hyperparameter map in this object to a flat vector.

Definition at line 406 of file GaussianProcess.C.

Referenced by tuneHyperParamsAdam().

411 {
412  for (auto iter : tuning_data)
413  {
414  const std::string & param_name = iter.first;
415  const auto tensor_it = hyperparam_map.find(param_name);
416  if (tensor_it == hyperparam_map.end())
417  mooseError("The covariance parameter ", param_name, " could not be found!");
418 
419  const auto values = exportHyperParameter(tensor_it->second);
420  const auto num_entries = std::get<1>(iter.second);
421  mooseAssert(values.size() == num_entries,
422  "Hyperparameter size does not match tuning metadata.");
423  for (unsigned int ii = 0; ii < num_entries; ++ii)
424  vec[std::get<0>(iter.second) + ii] = values[ii];
425  }
426 }
void mooseError(Args &&... args)

◆ paramStandardizer()

StochasticTools::Standardizer& StochasticTools::GaussianProcess::paramStandardizer ( )
inline

Get non-constant reference to the contained structures (if they need to be modified from the utside)

Definition at line 210 of file GaussianProcess.h.

Referenced by dataLoad(), dataStore(), GaussianProcessTrainer::postTrain(), and ActiveLearningGaussianProcess::reTrain().

210 { return _param_standardizer; }
StochasticTools::Standardizer _param_standardizer
Standardizer for use with params (x)

◆ setupCovarianceMatrix()

void StochasticTools::GaussianProcess::setupCovarianceMatrix ( const torch::Tensor training_params,
const torch::Tensor training_data,
const GPOptimizerOptions opts 
)

Sets up the covariance matrix given data and optimization options.

Parameters
training_paramsThe training parameter values (x values) for the covariance matrix.
training_dataThe training data (y values) for the inversion of the covariance matrix.
optsThe optimizer options.

Definition at line 153 of file GaussianProcess.C.

Referenced by GaussianProcessTrainer::postTrain(), and ActiveLearningGaussianProcess::reTrain().

156 {
157  const auto options = doubleOptionsLike(training_params);
158  const auto params = toOptions(training_params, options);
159  const auto data = toOptions(training_data, options);
160 
161  mooseAssert(params.dim() == 2, "GaussianProcess training parameters must be rank-2.");
162  mooseAssert(data.dim() == 2, "GaussianProcess training responses must be rank-2.");
163 
164  const auto num_samples = params.size(0);
165  mooseAssert(data.size(0) == num_samples,
166  "Training parameter and response sample counts must match.");
167  mooseAssert(data.size(1) == _num_outputs,
168  "Training response dimension does not match the covariance output dimension.");
169 
170  const bool batch_decision = opts.batch_size > 0 && (opts.batch_size <= num_samples);
171  _batch_size = batch_decision ? opts.batch_size : num_samples;
172 
173  _hyperparam_map.clear();
175  moveHyperParameters(_hyperparam_map, options);
177 
178  if (_tuning_data.size())
179  tuneHyperParamsAdam(params, data, opts);
180 
181  _covariance_function->computeCovarianceMatrix(_K, params, params, true);
182  const auto flattened_tensor = flattenOutputData(data);
183 
184  // Compute the Cholesky decomposition and inverse action of the covariance matrix.
185  setupStoredMatrices(flattened_tensor);
186 }
CovarianceFunctionBase * _covariance_function
Covariance function object.
void tuneHyperParamsAdam(const torch::Tensor &training_params, const torch::Tensor &training_data, const GPOptimizerOptions &opts)
void buildHyperParamMap(HyperParameterMap &map) const
Populates the input maps with the owned hyperparameters.
HyperParameterMap _hyperparam_map
Hyperparameters. Stored as tensors for use in surrogate reload/reporting.
unsigned int _num_outputs
The number of outputs of the GP.
void loadHyperParamMap(const HyperParameterMap &map)
Load some hyperparameters into the local map contained in this object.
void setupStoredMatrices(const torch::Tensor &input)
Sets up the Cholesky decomposition and inverse action of the covariance matrix.
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
Contains tuning inforation. Index of hyperparam, size, and min/max bounds.
unsigned int _batch_size
The batch size for Adam optimization.
torch::Tensor _K
An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.
virtual void computeCovarianceMatrix(torch::Tensor &K, const torch::Tensor &x, const torch::Tensor &xp, const bool is_self_covariance) const =0
Generates the Covariance Matrix given two sets of points in the parameter space.

◆ setupStoredMatrices()

void StochasticTools::GaussianProcess::setupStoredMatrices ( const torch::Tensor input)

Sets up the Cholesky decomposition and inverse action of the covariance matrix.

Parameters
inputThe vector/matrix which right multiples the inverse of the covariance matrix.

Definition at line 189 of file GaussianProcess.C.

Referenced by getLoss(), and setupCovarianceMatrix().

190 {
191  _K_cho_decomp = torch::linalg_cholesky(_K);
192  _K_results_solve = torch::cholesky_solve(input, _K_cho_decomp);
193 }
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.
torch::Tensor _K
An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.

◆ standardizeData()

void StochasticTools::GaussianProcess::standardizeData ( torch::Tensor data,
bool  keep_moments = false 
)

Standardizes the vector of responses (y values).

Parameters
dataThe vector/matrix of input data.
keep_momentsIf previously computed or new moments are to be used.

Definition at line 238 of file GaussianProcess.C.

Referenced by GaussianProcessTrainer::postTrain(), and ActiveLearningGaussianProcess::reTrain().

239 {
240  if (!keep_moments)
243 }
StochasticTools::Standardizer _data_standardizer
Standardizer for use with data (y)
void getStandardized(torch::Tensor &input) const
Returns the standardized (centered and scaled) of the provided input.
Definition: Standardizer.C:89
void computeSet(const torch::Tensor &input)
Methods for computing and setting mean and standard deviation.
Definition: Standardizer.C:79

◆ standardizeParameters()

void StochasticTools::GaussianProcess::standardizeParameters ( torch::Tensor parameters,
bool  keep_moments = false 
)

Standardizes the vector of input parameters (x values).

Parameters
parametersThe vector/matrix of input data.
keep_momentsIf previously computed or new moments are to be used.

Definition at line 230 of file GaussianProcess.C.

Referenced by GaussianProcessTrainer::postTrain(), and ActiveLearningGaussianProcess::reTrain().

231 {
232  if (!keep_moments)
235 }
StochasticTools::Standardizer _param_standardizer
Standardizer for use with params (x)
void getStandardized(torch::Tensor &input) const
Returns the standardized (centered and scaled) of the provided input.
Definition: Standardizer.C:89
void computeSet(const torch::Tensor &input)
Methods for computing and setting mean and standard deviation.
Definition: Standardizer.C:79

◆ tuneHyperParamsAdam()

void StochasticTools::GaussianProcess::tuneHyperParamsAdam ( const torch::Tensor training_params,
const torch::Tensor training_data,
const GPOptimizerOptions opts 
)

Definition at line 246 of file GaussianProcess.C.

Referenced by setupCovarianceMatrix().

249 {
250  const auto options = doubleOptionsLike(training_params);
251  std::vector<Real> theta_values(_num_tunable, 0.0);
252 
253  mapToVec(_tuning_data, _hyperparam_map, theta_values);
254 
255  auto theta = torch::from_blob(theta_values.data(),
256  {static_cast<long>(_num_tunable)},
257  torch::TensorOptions().dtype(at::kDouble))
258  .clone()
259  .to(options.device());
260 
261  auto adam_options = torch::optim::AdamOptions(opts.learning_rate);
262  adam_options.betas(std::make_tuple(opts.b1, opts.b2));
263  adam_options.eps(opts.eps);
264  // The legacy MOOSE shrink term is decoupled and not learning-rate-scaled, so it cannot be
265  // represented by Adam's coupled weight_decay option.
266  adam_options.weight_decay(0.0);
267  torch::optim::Adam optimizer({theta}, adam_options);
268 
269  Real store_loss = 0.0;
270  std::vector<Real> grad_values;
271  const bool use_legacy_update = opts.optimizer_type == OptimizerType::LegacyAdam;
272 
273  const bool use_full_batch = _batch_size == static_cast<unsigned int>(training_params.size(0));
274  // Preserve the existing deterministic shuffle sequence for mini-batches, but avoid rebuilding
275  // shuffled full-batch tensors when the batch already contains every training sample.
276  std::vector<unsigned int> v_sequence;
277  if (!use_full_batch)
278  {
279  v_sequence.resize(training_params.size(0));
280  std::iota(std::begin(v_sequence), std::end(v_sequence), 0);
281  }
282  if (opts.show_every_nth_iteration)
283  Moose::out << "OPTIMIZING GP HYPER-PARAMETERS USING "
284  << (use_legacy_update ? "legacy-compatible Adam" : "Adam") << std::endl;
285  for (unsigned int ss = 0; ss < opts.num_iter; ++ss)
286  {
287  torch::Tensor inputs;
288  torch::Tensor outputs;
289  if (use_full_batch)
290  {
291  inputs = training_params;
292  outputs = training_data;
293  }
294  else
295  {
296  MooseRandom generator;
297  generator.seed(0, 1980);
298  generator.saveState();
299  MooseUtils::shuffle<unsigned int>(v_sequence, generator, 0);
300 
301  std::vector<int64_t> batch_indices_vec(v_sequence.begin(), v_sequence.begin() + _batch_size);
302  auto batch_indices = torch::tensor(
303  batch_indices_vec, torch::TensorOptions().dtype(torch::kLong).device(options.device()));
304  inputs = torch::index_select(training_params, 0, batch_indices);
305  outputs = torch::index_select(training_data, 0, batch_indices);
306  }
307 
308  store_loss = getLoss(inputs, outputs);
309  if (opts.show_every_nth_iteration && ((ss + 1) % opts.show_every_nth_iteration == 0))
310  Moose::out << "Iteration: " << ss + 1 << " LOSS: " << store_loss << std::endl;
311 
312  grad_values = getGradient(inputs);
313  auto grad = torch::from_blob(grad_values.data(),
314  {static_cast<long>(_num_tunable)},
315  torch::TensorOptions().dtype(at::kDouble))
316  .clone()
317  .to(options.device());
318  optimizer.zero_grad();
319  theta.mutable_grad() = grad;
320  torch::Tensor theta_before_step;
321  if (use_legacy_update)
322  theta_before_step = theta.detach().clone();
323  optimizer.step();
324 
325  {
326  torch::NoGradGuard no_grad;
327  if (use_legacy_update)
328  theta -= opts.lambda * theta_before_step;
329  for (auto iter = _tuning_data.begin(); iter != _tuning_data.end(); ++iter)
330  {
331  const auto first_index = std::get<0>(iter->second);
332  const auto num_entries = std::get<1>(iter->second);
333  const auto min_value = std::get<2>(iter->second);
334  const auto max_value = std::get<3>(iter->second);
335  theta.slice(0, first_index, first_index + num_entries).clamp_(min_value, max_value);
336  }
337  }
338 
339  const auto theta_export = LibtorchUtils::toCPUContiguous(theta);
340  const auto * theta_data = theta_export.data_ptr<Real>();
341  theta_values.assign(theta_data, theta_data + theta_export.numel());
342  vecToMap(_tuning_data, _hyperparam_map, theta_values);
344  }
345  if (opts.show_every_nth_iteration)
346  {
347  Moose::out << "OPTIMIZED GP HYPER-PARAMETERS:" << std::endl;
348  Moose::out << Moose::stringify(theta_values) << std::endl;
349  Moose::out << "FINAL LOSS: " << store_loss << std::endl;
350  }
351 
352  if (theta_values.size() > 0)
353  {
354  unsigned int count = 1;
355  _length_scales.resize(_num_tunable - count);
356  for (unsigned int i = 0; i < _num_tunable - count; ++i)
357  _length_scales[i] = theta_values[i + 1];
358  }
359 }
unsigned int _num_tunable
Number of tunable hyperparameters.
CovarianceFunctionBase * _covariance_function
Covariance function object.
void saveState()
void seed(std::size_t i, unsigned int seed)
torch::Tensor toCPUContiguous(const torch::Tensor &tensor)
HyperParameterMap _hyperparam_map
Hyperparameters. Stored as tensors for use in surrogate reload/reporting.
void loadHyperParamMap(const HyperParameterMap &map)
Load some hyperparameters into the local map contained in this object.
std::string stringify(const T &t)
void mapToVec(const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &tuning_data, const HyperParameterMap &hyperparam_map, std::vector< Real > &vec) const
Function used to convert the hyperparameter map in this object to a flat vector.
std::string grad(const std::string &var)
Definition: NS.h:92
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
Contains tuning inforation. Index of hyperparam, size, and min/max bounds.
unsigned int _batch_size
The batch size for Adam optimization.
std::vector< Real > _length_scales
To return the GP length scales for active learning.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
std::vector< Real > getGradient(torch::Tensor &inputs) const
Real getLoss(torch::Tensor &inputs, torch::Tensor &outputs)
void vecToMap(const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &tuning_data, HyperParameterMap &hyperparam_map, const std::vector< Real > &vec) const
Function used to convert the vector back to the hyperparameter map.

◆ tuningData()

std::unordered_map<std::string, std::tuple<unsigned int, unsigned int, Real, Real> >& StochasticTools::GaussianProcess::tuningData ( )
inline

Definition at line 222 of file GaussianProcess.h.

223  {
224  return _tuning_data;
225  }
std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real > > _tuning_data
Contains tuning inforation. Index of hyperparam, size, and min/max bounds.

◆ vecToMap()

void StochasticTools::GaussianProcess::vecToMap ( const std::unordered_map< std::string, std::tuple< unsigned int, unsigned int, Real, Real >> &  tuning_data,
HyperParameterMap hyperparam_map,
const std::vector< Real > &  vec 
) const

Function used to convert the vector back to the hyperparameter map.

Definition at line 429 of file GaussianProcess.C.

Referenced by tuneHyperParamsAdam().

434 {
435  for (auto iter : tuning_data)
436  {
437  const std::string & param_name = iter.first;
438  const auto tensor_it = hyperparam_map.find(param_name);
439  if (tensor_it == hyperparam_map.end())
440  mooseError("The covariance parameter ", param_name, " could not be found!");
441 
442  const auto first_index = std::get<0>(iter.second);
443  const auto num_entries = std::get<1>(iter.second);
444  std::vector<Real> values(num_entries);
445  for (unsigned int ii = 0; ii < num_entries; ++ii)
446  values[ii] = vec[first_index + ii];
447 
448  updateHyperParameter(tensor_it->second, values, param_name);
449  }
450 }
void mooseError(Args &&... args)

Member Data Documentation

◆ _batch_size

unsigned int StochasticTools::GaussianProcess::_batch_size = 0
protected

The batch size for Adam optimization.

Definition at line 274 of file GaussianProcess.h.

Referenced by getGradient(), setupCovarianceMatrix(), and tuneHyperParamsAdam().

◆ _covar_name

std::string StochasticTools::GaussianProcess::_covar_name
protected

The name of the covariance function used in this GP.

Definition at line 244 of file GaussianProcess.h.

Referenced by covarName(), getCovarName(), and linkCovarianceFunction().

◆ _covar_type

std::string StochasticTools::GaussianProcess::_covar_type
protected

Type of covariance function used for this GP.

Definition at line 241 of file GaussianProcess.h.

Referenced by covarType(), getCovarType(), and linkCovarianceFunction().

◆ _covariance_function

CovarianceFunctionBase* StochasticTools::GaussianProcess::_covariance_function = nullptr
protected

◆ _data_standardizer

StochasticTools::Standardizer StochasticTools::GaussianProcess::_data_standardizer
protected

Standardizer for use with data (y)

Definition at line 262 of file GaussianProcess.h.

Referenced by dataStandardizer(), getDataStandardizer(), and standardizeData().

◆ _dependent_covar_names

std::vector<UserObjectName> StochasticTools::GaussianProcess::_dependent_covar_names
protected

The names of the covariance functions the used covariance function depends on.

Definition at line 247 of file GaussianProcess.h.

Referenced by dependentCovarNames(), getDependentCovarNames(), and linkCovarianceFunction().

◆ _dependent_covar_types

std::map<UserObjectName, std::string> StochasticTools::GaussianProcess::_dependent_covar_types
protected

The types of the covariance functions the used covariance function depends on.

Definition at line 250 of file GaussianProcess.h.

Referenced by dependentCovarTypes(), getDependentCovarTypes(), and linkCovarianceFunction().

◆ _hyperparam_map

HyperParameterMap StochasticTools::GaussianProcess::_hyperparam_map
protected

Hyperparameters. Stored as tensors for use in surrogate reload/reporting.

Definition at line 256 of file GaussianProcess.h.

Referenced by getHyperParamMap(), hyperparamMap(), setupCovarianceMatrix(), and tuneHyperParamsAdam().

◆ _K

torch::Tensor StochasticTools::GaussianProcess::_K
protected

An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.

Definition at line 265 of file GaussianProcess.h.

Referenced by getK(), getLoss(), K(), setupCovarianceMatrix(), and setupStoredMatrices().

◆ _K_cho_decomp

torch::Tensor StochasticTools::GaussianProcess::_K_cho_decomp
protected

Cholesky decomposition libtorch tensor object.

Definition at line 271 of file GaussianProcess.h.

Referenced by getGradient(), getKCholeskyDecomp(), getLoss(), KCholeskyDecomp(), and setupStoredMatrices().

◆ _K_results_solve

torch::Tensor StochasticTools::GaussianProcess::_K_results_solve
protected

A solve of Ax=b via Cholesky.

Definition at line 268 of file GaussianProcess.h.

Referenced by getGradient(), getKResultsSolve(), getLoss(), KResultsSolve(), and setupStoredMatrices().

◆ _length_scales

std::vector<Real> StochasticTools::GaussianProcess::_length_scales
protected

To return the GP length scales for active learning.

Definition at line 277 of file GaussianProcess.h.

Referenced by getLengthScales(), lengthScales(), and tuneHyperParamsAdam().

◆ _num_outputs

unsigned int StochasticTools::GaussianProcess::_num_outputs = 0
protected

The number of outputs of the GP.

Definition at line 253 of file GaussianProcess.h.

Referenced by covarNumOutputs(), getCovarNumOutputs(), getGradient(), linkCovarianceFunction(), and setupCovarianceMatrix().

◆ _num_tunable

unsigned int StochasticTools::GaussianProcess::_num_tunable = 0
protected

Number of tunable hyperparameters.

Definition at line 238 of file GaussianProcess.h.

Referenced by generateTuningMap(), getGradient(), getNumTunableParams(), and tuneHyperParamsAdam().

◆ _param_standardizer

StochasticTools::Standardizer StochasticTools::GaussianProcess::_param_standardizer
protected

Standardizer for use with params (x)

Definition at line 259 of file GaussianProcess.h.

Referenced by getParamStandardizer(), paramStandardizer(), and standardizeParameters().

◆ _tuning_data

std::unordered_map<std::string, std::tuple<unsigned int, unsigned int, Real, Real> > StochasticTools::GaussianProcess::_tuning_data
protected

Contains tuning inforation. Index of hyperparam, size, and min/max bounds.

Definition at line 235 of file GaussianProcess.h.

Referenced by generateTuningMap(), getGradient(), setupCovarianceMatrix(), tuneHyperParamsAdam(), and tuningData().


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