NEML2 2.1.0
Loading...
Searching...
No Matches
Model.h
1// Copyright 2024, UChicago Argonne, LLC
2// All Rights Reserved
3// Software Name: NEML2 -- the New Engineering material Model Library, version 2
4// By: Argonne National Laboratory
5// OPEN SOURCE LICENSE (MIT)
6//
7// Permission is hereby granted, free of charge, to any person obtaining a copy
8// of this software and associated documentation files (the "Software"), to deal
9// in the Software without restriction, including without limitation the rights
10// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11// copies of the Software, and to permit persons to whom the Software is
12// furnished to do so, subject to the following conditions:
13//
14// The above copyright notice and this permission notice shall be included in
15// all copies or substantial portions of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23// THE SOFTWARE.
24
25#pragma once
26
27#include "neml2/models/DependencyDefinition.h"
28#include "neml2/base/DiagnosticsInterface.h"
29
30#include "neml2/models/Data.h"
31#include "neml2/models/ParameterStore.h"
32#include "neml2/models/VariableStore.h"
33#include "neml2/models/NonlinearParameter.h"
34#include "neml2/tensors/jit.h"
35
36// These headers are not directly used by Model, but are included here so that derived classes do
37// not have to include them separately. This is a convenience for the user, and is a reasonable
38// choice since these headers are light and bring in little dependency.
39#include "neml2/base/LabeledAxis.h"
40#include "neml2/models/Variable.h"
41#include "neml2/tensors/Derivative.h"
42
43namespace neml2
44{
45class Model;
46
53
54// Guard a region where implicit solve is being performed
67
77class Model : public std::enable_shared_from_this<Model>,
78 public Data,
79 public ParameterStore,
80 public VariableStore,
81 public DependencyDefinition<VariableName>,
83{
84public:
91 {
92 std::vector<Size> dynamic_dims;
93 std::vector<TensorShape> intmd_shapes;
94 at::DispatchKey dispatch_key;
95 bool operator==(const EvaluationSchema & other) const;
96 bool operator!=(const EvaluationSchema & other) const;
97 bool operator<(const EvaluationSchema & other) const;
98 };
99
101
107 Model(const OptionSet & options);
108
109 void setup() override;
110
111 void diagnose() const override;
112
114 virtual bool defines_values() const { return _defines_value; }
115
117 virtual bool defines_derivatives() const { return _defines_dvalue; }
118
120 virtual bool defines_second_derivatives() const { return _defines_d2value; }
121
123 virtual bool is_jit_enabled() const { return _jit; }
124
126 virtual void to(const TensorOptions & options);
127
129 const std::vector<std::shared_ptr<Model>> & registered_models() const
130 {
131 return _registered_models;
132 }
133
134 std::shared_ptr<Model> registered_model(const std::string & name) const;
135
137 void register_nonlinear_parameter(const std::string & pname, const NonlinearParameter & param);
138
140 bool has_nl_param(bool recursive = false) const;
141
148 const VariableBase * nl_param(const std::string &) const;
149
151 virtual std::map<std::string, NonlinearParameter>
152 named_nonlinear_parameters(bool recursive = false) const;
153
155 std::set<VariableName> consumed_items() const override;
157 std::set<VariableName> provided_items() const override;
158
161
163 void request_AD(VariableBase & y, const VariableBase & u1, const VariableBase & u2);
164
165 void clear_input() override;
166 void clear_output() override;
167 void zero_undefined_input() override;
168
177 void forward_maybe_jit(bool out, bool dout, bool d2out);
178
180 std::string variable_name_lookup(const ATensor & var) const;
181
183 virtual ValueMap value(const ValueMap & in);
184
186 virtual std::tuple<ValueMap, DerivMap> value_and_dvalue(const ValueMap & in);
187
189 virtual DerivMap dvalue(const ValueMap & in);
190
192 virtual std::tuple<ValueMap, DerivMap, SecDerivMap>
194
196 virtual SecDerivMap d2value(const ValueMap & in);
197
199 virtual std::tuple<DerivMap, SecDerivMap> dvalue_and_d2value(const ValueMap & in);
200
202 friend class ParameterStore;
203
205 friend class ComposedModel;
206
209
210protected:
218
219 virtual void link_input_variables();
220 virtual void link_input_variables(Model * submodel);
221 virtual void link_output_variables();
222 virtual void link_output_variables(Model * submodel);
223
225 void check_precision() const;
226
228 virtual std::string failed_graph_execution_hint() const;
229
243 virtual void request_AD() {}
244
246 void forward(bool out, bool dout, bool d2out);
247
249 virtual void set_value(bool out, bool dout_din, bool d2out_din2) = 0;
250
262 template <typename T = Model, typename = typename std::enable_if_t<std::is_base_of_v<Model, T>>>
263 T & register_model(const std::string & name, bool merge_input = true)
264 {
265 auto model_name =
266 input_options().contains(name) ? input_options().get<std::string>(name) : name;
267 if (model_name == this->name())
268 throw SetupException("Model named '" + this->name() +
269 "' is trying to register itself as a sub-model. This is not allowed.");
270
271 OptionSet extra_opts;
272 extra_opts.set<NEML2Object *>("_host") = host();
273
274 if (!host()->factory())
275 throw SetupException("Internal error: Host object '" + host()->name() +
276 "' does not have a factory set.");
277 auto model = host()->factory()->get_object<T>("Models", model_name, extra_opts);
278
279 register_model(model, merge_input);
280 return *model;
281 }
282
294 template <typename T = Model, typename = typename std::enable_if_t<std::is_base_of_v<Model, T>>>
295 void register_model(const std::shared_ptr<T> & model, bool merge_input = true)
296 {
297 if (std::find(_registered_models.begin(), _registered_models.end(), model) !=
298 _registered_models.end())
299 throw SetupException("Model named '" + model->name() + "' has already been registered.");
300
301 if (merge_input)
302 for (auto && [name, var] : model->input_variables())
304
305 _registered_models.push_back(model);
306 }
307
308 void assign_input_stack(jit::Stack & stack);
309
310 jit::Stack collect_input_stack() const;
311
313 std::vector<std::shared_ptr<Model>> _registered_models;
314
315private:
316 template <typename T>
317 void forward_helper(T && in, bool out, bool dout, bool d2out)
318 {
320 assign_input(std::forward<T>(in));
322 forward_maybe_jit(out, dout, d2out);
323 }
324
326 void enable_AD();
327
329 void extract_AD_derivatives(bool dout, bool d2out);
330
332 std::size_t forward_operator_index(bool out, bool dout, bool d2out) const;
333
335 EvaluationSchema calculate_eval_schema() const;
336
339 bool _defines_value;
340 bool _defines_dvalue;
341 bool _defines_d2value;
343
345 std::map<std::string, NonlinearParameter> _nl_params;
346
349 std::map<VariableBase *, std::set<const VariableBase *>> _ad_derivs;
350 std::map<VariableBase *, std::map<const VariableBase *, std::set<const VariableBase *>>>
351 _ad_secderivs;
352 std::set<VariableBase *> _ad_args;
354
356 const bool _jit;
357
359 const bool _production;
360
377 std::array<std::map<EvaluationSchema, std::unique_ptr<jit::GraphFunction>>, 8> _traced_functions;
378
380 std::array<std::map<EvaluationSchema, std::unique_ptr<jit::GraphFunction>>, 8>
381 _traced_functions_nl_sys;
382
384 bool _currently_assembling_nonlinear_system = false;
385};
386
387std::ostream & operator<<(std::ostream & os, const Model & model);
388} // namespace neml2
Data(const OptionSet &options)
Construct a new Data object.
The base class for all constitutive models.
Definition Model.h:83
void request_AD(VariableBase &y, const VariableBase &u)
Request to use AD to compute the first derivative of a variable.
virtual std::string failed_graph_execution_hint() const
Additional hint to include in the error message when an exception is encountered during execution of ...
friend class ComposedModel
ComposedModel's set_value need to call submodel's set_value.
Definition Model.h:205
void register_model(const std::shared_ptr< T > &model, bool merge_input=true)
Register a model that the current model may use during its evaluation.
Definition Model.h:295
virtual void link_output_variables()
void clear_input() override
std::vector< std::shared_ptr< Model > > _registered_models
Models this model may use during its evaluation.
Definition Model.h:313
virtual void link_output_variables(Model *submodel)
virtual void to(const TensorOptions &options)
Send model to a different device or dtype.
virtual std::tuple< ValueMap, DerivMap > value_and_dvalue(const ValueMap &in)
Convenient shortcut to construct and return the model value and its derivative.
void check_precision() const
Check the current default precision and warn if it's not double precision.
void diagnostic_assert_force(const VariableBase &v) const
void zero_undefined_input() override
Fill undefined input variables with zeros.
virtual std::tuple< ValueMap, DerivMap, SecDerivMap > value_and_dvalue_and_d2value(const ValueMap &in)
Convenient shortcut to construct and return the model's value, first and second derivative.
void register_nonlinear_parameter(const std::string &pname, const NonlinearParameter &param)
Register a nonlinear parameter.
virtual bool defines_derivatives() const
Whether this model defines first derivatives.
Definition Model.h:117
friend class ModelNonlinearSystem
ModelNonlinearSystem needs access to some setup methods.
Definition Model.h:208
bool has_nl_param(bool recursive=false) const
Whether this parameter store has any nonlinear parameter.
void diagnostic_check_output_variable(const VariableBase &v) const
virtual bool defines_values() const
Whether this model defines output values.
Definition Model.h:114
const std::vector< std::shared_ptr< Model > > & registered_models() const
The models that may be used during the evaluation of this model.
Definition Model.h:129
void forward_maybe_jit(bool out, bool dout, bool d2out)
Forward operator with jit.
virtual ValueMap value(const ValueMap &in)
Convenient shortcut to construct and return the model value.
virtual void set_value(bool out, bool dout_din, bool d2out_din2)=0
The map between input -> output, and optionally its derivatives.
std::set< VariableName > provided_items() const override
The variables that this model defines as part of its output.
virtual DerivMap dvalue(const ValueMap &in)
Convenient shortcut to construct and return the derivative.
friend class ParameterStore
Declaration of nonlinear parameters may require manipulation of input.
Definition Model.h:202
virtual bool defines_second_derivatives() const
Whether this model defines second derivatives.
Definition Model.h:120
virtual void link_input_variables()
void diagnostic_assert_state(const VariableBase &v) const
void request_AD(VariableBase &y, const VariableBase &u1, const VariableBase &u2)
Request to use AD to compute the second derivative of a variable.
void forward(bool out, bool dout, bool d2out)
Forward operator without jit.
void diagnostic_check_input_variable(const VariableBase &v) const
virtual std::map< std::string, NonlinearParameter > named_nonlinear_parameters(bool recursive=false) const
Get all nonlinear parameters.
std::string variable_name_lookup(const ATensor &var) const
Look up the name of a variable in the traced graph.
std::shared_ptr< Model > registered_model(const std::string &name) const
Get a registered model by its name.
void diagnostic_assert_old_state(const VariableBase &v) const
jit::Stack collect_input_stack() const
void diagnostic_assert_old_force(const VariableBase &v) const
void setup() override
Setup this object.
void diagnose() const override
Check for common problems.
void clear_output() override
virtual SecDerivMap d2value(const ValueMap &in)
Convenient shortcut to construct and return the model's second derivative.
static OptionSet expected_options()
void assign_input_stack(jit::Stack &stack)
void diagnostic_assert_residual(const VariableBase &v) const
virtual void request_AD()
Definition Model.h:243
Model(const OptionSet &options)
Construct a new Model object.
virtual void link_input_variables(Model *submodel)
T & register_model(const std::string &name, bool merge_input=true)
Register a model that the current model may use during its evaluation.
Definition Model.h:263
virtual bool is_jit_enabled() const
Whether JIT is enabled.
Definition Model.h:123
virtual std::tuple< DerivMap, SecDerivMap > dvalue_and_d2value(const ValueMap &in)
Convenient shortcut to construct and return the model's first and second derivative.
const VariableBase * nl_param(const std::string &) const
Query the existence of a nonlinear parameter.
std::set< VariableName > consumed_items() const override
The variables that this model depends on.
The base class of all "manufacturable" objects in the NEML2 library.
Definition NEML2Object.h:52
const std::string & name() const
A readonly reference to the object's name.
Definition NEML2Object.h:84
const T * host() const
Get a readonly pointer to the host.
Definition NEML2Object.h:154
Factory * factory() const
Get the factory that created this object.
Definition NEML2Object.h:93
const OptionSet & input_options() const
Definition NEML2Object.h:70
A custom map-like data structure. The keys are strings, and the values can be nonhomogeneously typed.
Definition OptionSet.h:52
T get(const std::string &) const
Definition OptionSet.h:261
bool contains(const std::string &) const
T & set(const std::string &)
Definition OptionSet.h:298
Definition errors.h:50
Base class of variable.
Definition VariableBase.h:53
VariableStore(Model *object)
void assign_input(const ValueMap &vals)
const VariableBase * clone_input_variable(const VariableBase &var, const VariableName &new_name={})
Clone a variable and put it on the input axis.
Definition DiagnosticsInterface.h:31
std::map< LabeledAxisAccessor, Tensor > ValueMap
Definition map_types_fwd.h:33
std::ostream & operator<<(std::ostream &, const EnumSelection &)
at::Tensor ATensor
Definition types.h:42
std::map< LabeledAxisAccessor, ValueMap > DerivMap
Definition map_types_fwd.h:34
std::map< LabeledAxisAccessor, DerivMap > SecDerivMap
Definition map_types_fwd.h:35
bool & currently_assembling_nonlinear_system()
c10::TensorOptions TensorOptions
Definition types.h:66
AssemblyingNonlinearSystem & operator=(const AssemblyingNonlinearSystem &)=delete
AssemblyingNonlinearSystem(AssemblyingNonlinearSystem &&)=delete
AssemblyingNonlinearSystem & operator=(AssemblyingNonlinearSystem &&)=delete
AssemblyingNonlinearSystem(const AssemblyingNonlinearSystem &)=delete
AssemblyingNonlinearSystem(bool assembling=true)
const bool prev_bool
Definition Model.h:65
Schema for the traced forward operators.
Definition Model.h:91
bool operator==(const EvaluationSchema &other) const
at::DispatchKey dispatch_key
Definition Model.h:94
bool operator!=(const EvaluationSchema &other) const
std::vector< Size > dynamic_dims
Definition Model.h:92
bool operator<(const EvaluationSchema &other) const
std::vector< TensorShape > intmd_shapes
Definition Model.h:93
Nonlinear parameter.
Definition NonlinearParameter.h:51