https://mooseframework.inl.gov
Loading...
Searching...
No Matches
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 class  OptimizerType { Adam , 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.
 
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 setupStoredMatrices (const torch::Tensor &input)
 Sets up the Cholesky decomposition and inverse action of the covariance matrix.
 
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.
 
void standardizeParameters (torch::Tensor &parameters, bool keep_moments=false)
 Standardizes the vector of input parameters (x values).
 
void standardizeData (torch::Tensor &data, bool keep_moments=false)
 Standardizes the vector of responses (y values).
 
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< Real > getGradient (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.
 
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.
 
const StochasticTools::StandardizergetParamStandardizer () const
 Get constant reference to the contained structures.
 
const StochasticTools::StandardizergetDataStandardizer () const
 
const torch::Tensor & getK () const
 
const torch::Tensor & getKResultsSolve () const
 
const torch::Tensor & getKCholeskyDecomp () 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)
 
StochasticTools::StandardizerdataStandardizer ()
 
torch::Tensor & K ()
 
torch::Tensor & KResultsSolve ()
 
torch::Tensor & KCholeskyDecomp ()
 
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.
 
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 _num_tunable = 0
 Number of tunable hyperparameters.
 
std::string _covar_type
 Type of covariance function used for this GP.
 
std::string _covar_name
 The name of the covariance function used in this GP.
 
std::vector< UserObjectName > _dependent_covar_names
 The names of the covariance functions the used covariance function depends on.
 
std::map< UserObjectName, std::string > _dependent_covar_types
 The types of the covariance functions the used covariance function depends on.
 
unsigned int _num_outputs = 0
 The number of outputs of the GP.
 
HyperParameterMap _hyperparam_map
 Hyperparameters. Stored as tensors for use in surrogate reload/reporting.
 
StochasticTools::Standardizer _param_standardizer
 Standardizer for use with params (x)
 
StochasticTools::Standardizer _data_standardizer
 Standardizer for use with data (y)
 
torch::Tensor _K
 An _n_sample by _n_sample covariance matrix constructed from the selected kernel function.
 
torch::Tensor _K_results_solve
 A solve of Ax=b via Cholesky.
 
torch::Tensor _K_cho_decomp
 Cholesky decomposition libtorch tensor object.
 
unsigned int _batch_size = 0
 The batch size for Adam optimization.
 
std::vector< Real > _length_scales
 To return the GP length scales for active learning.
 

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.

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; }

◆ covarName()

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

Definition at line 218 of file GaussianProcess.h.

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

Referenced by dataLoad(), and dataStore().

◆ covarNumOutputs()

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

Definition at line 221 of file GaussianProcess.h.

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

Referenced by dataLoad(), and dataStore().

◆ covarType()

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

Definition at line 217 of file GaussianProcess.h.

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

Referenced by dataLoad(), and dataStore().

◆ dataStandardizer()

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

Definition at line 211 of file GaussianProcess.h.

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

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

◆ dependentCovarNames()

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

Definition at line 220 of file GaussianProcess.h.

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

Referenced by dataLoad(), and dataStore().

◆ dependentCovarTypes()

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

Definition at line 219 of file GaussianProcess.h.

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.

Referenced by dataLoad(), and dataStore().

◆ 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.

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}
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.
virtual bool isTunable(const std::string &name) const
Check if a given parameter is tunable.
unsigned int _num_tunable
Number of tunable hyperparameters.
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.
auto max(const L &left, const R &right)
auto min(const L &left, const R &right)
auto index_range(const T &sizable)
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real

Referenced by initialize().

◆ getCovarFunction()

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

◆ getCovarFunctionPtr()

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

Definition at line 188 of file GaussianProcess.h.

188{ return _covariance_function; }

Referenced by GaussianProcessSurrogate::setupCovariance().

◆ getCovarName()

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

Definition at line 190 of file GaussianProcess.h.

190{ return _covar_name; }

◆ getCovarNumOutputs()

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

Definition at line 199 of file GaussianProcess.h.

199{ return _num_outputs; }

◆ getCovarType()

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

Definition at line 189 of file GaussianProcess.h.

189{ return _covar_type; }

◆ getDataStandardizer()

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

◆ getDependentCovarNames()

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

Definition at line 191 of file GaussianProcess.h.

192 {
194 }

◆ getDependentCovarTypes()

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

Definition at line 195 of file GaussianProcess.h.

196 {
198 }

◆ getGradient()

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

Definition at line 379 of file GaussianProcess.C.

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}
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".
unsigned int _batch_size
The batch size for Adam optimization.
torch::Tensor _K_results_solve
A solve of Ax=b via Cholesky.
torch::Tensor _K_cho_decomp
Cholesky decomposition libtorch tensor object.

Referenced by tuneHyperParamsAdam().

◆ getHyperParamMap()

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

Definition at line 201 of file GaussianProcess.h.

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

Referenced by GaussianProcessData::initialize().

◆ 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.

186{ return _K_cho_decomp; }

Referenced by GaussianProcessSurrogate::evaluate().

◆ getKResultsSolve()

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

Definition at line 185 of file GaussianProcess.h.

185{ return _K_results_solve; }

Referenced by GaussianProcessSurrogate::evaluate().

◆ getLengthScales()

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

Definition at line 202 of file GaussianProcess.h.

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

Referenced by ActiveLearningGaussianProcess::getLengthScales().

◆ getLoss()

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

Definition at line 362 of file GaussianProcess.C.

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}
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.
void setupStoredMatrices(const torch::Tensor &input)
Sets up the Cholesky decomposition and inverse action of the covariance matrix.

Referenced by tuneHyperParamsAdam().

◆ getNumTunableParams()

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

Definition at line 200 of file GaussianProcess.h.

200{ return _num_tunable; }

◆ getParamStandardizer()

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

Get constant reference to the contained structures.

Definition at line 182 of file GaussianProcess.h.

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

Referenced by GaussianProcessSurrogate::evaluate().

◆ hyperparamMap()

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

Definition at line 226 of file GaussianProcess.h.

226{ return _hyperparam_map; }

Referenced by dataLoad(), and dataStore().

◆ 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.

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.

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

◆ K()

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

Definition at line 212 of file GaussianProcess.h.

212{ return _K; }

Referenced by dataLoad(), and dataStore().

◆ KCholeskyDecomp()

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

Definition at line 214 of file GaussianProcess.h.

214{ return _K_cho_decomp; }

Referenced by dataLoad(), and dataStore().

◆ KResultsSolve()

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

Definition at line 213 of file GaussianProcess.h.

213{ return _K_results_solve; }

Referenced by dataLoad(), and dataStore().

◆ lengthScales()

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

Definition at line 227 of file GaussianProcess.h.

227{ return _length_scales; }

◆ 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.

143{
144 _covariance_function = covariance_function;
150}
void dependentCovarianceTypes(std::map< UserObjectName, std::string > &name_type_map) const
Populate a map with the names and types of the dependent covariance functions.
unsigned int numOutputs() const
Return the number of outputs assumed for this covariance function.
const std::vector< UserObjectName > & dependentCovarianceNames() const
Get the names of the dependent covariances.
const std::string & type() const
const std::string & name() const

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

◆ 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.

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)
std::array< Real, 2 > values

Referenced by tuneHyperParamsAdam().

◆ 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.

210{ return _param_standardizer; }

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

◆ 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.

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}
void buildHyperParamMap(HyperParameterMap &map) const
Populates the input maps with the owned hyperparameters.
void loadHyperParamMap(const HyperParameterMap &map)
Load some hyperparameters into the local map contained in this object.
void tuneHyperParamsAdam(const torch::Tensor &training_params, const torch::Tensor &training_data, const GPOptimizerOptions &opts)

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

◆ 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.

190{
191 _K_cho_decomp = torch::linalg_cholesky(_K);
192 _K_results_solve = torch::cholesky_solve(input, _K_cho_decomp);
193}

Referenced by getLoss(), and setupCovarianceMatrix().

◆ 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.

239{
240 if (!keep_moments)
243}
void getStandardized(torch::Tensor &input) const
Returns the standardized (centered and scaled) of the provided input.
void computeSet(const torch::Tensor &input)
Methods for computing and setting mean and standard deviation.

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

◆ 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.

231{
232 if (!keep_moments)
235}

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

◆ 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.

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 count
void saveState()
void seed(std::size_t i, unsigned int seed)
Real getLoss(torch::Tensor &inputs, torch::Tensor &outputs)
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::vector< Real > getGradient(torch::Tensor &inputs) const
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.
torch::Tensor toCPUContiguous(const torch::Tensor &tensor)
std::string stringify(const T &t)
std::string grad(const std::string &var)
Definition NS.h:92

Referenced by setupCovarianceMatrix().

◆ 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 }

◆ 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.

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}

Referenced by tuneHyperParamsAdam().

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: