NEML2 1.4.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/base/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/solvers/NonlinearSystem.h"
34
35#include "neml2/tensors/LabeledVector.h"
36#include "neml2/tensors/LabeledMatrix.h"
37#include "neml2/tensors/LabeledTensor3D.h"
38
39namespace neml2
40{
48class Model : public std::enable_shared_from_this<Model>,
49 public Data,
50 public ParameterStore,
51 public VariableStore,
52 public NonlinearSystem,
53 public DependencyDefinition<VariableName>,
55{
56public:
58
64 Model(const OptionSet & options);
65
66 virtual void diagnose(std::vector<Diagnosis> &) const override;
67
69 void diagnose_nl_sys(std::vector<Diagnosis> & diagnoses) const;
70
72 virtual bool is_nonlinear_system() const { return _nonlinear_system; }
73
75 std::tuple<const Tensor &, const Tensor &, const Tensor &, const Tensor &, const Tensor &>
76 get_system_matrices() const;
77
82 virtual void reinit(const Tensor & tensor, int deriv_order);
83
99 virtual void reinit(TensorShapeRef batch_shape = {},
100 int deriv_order = 0,
101 const torch::Device & device = default_device(),
102 const torch::Dtype & dtype = default_dtype());
103
107 Size batch_dim() const { return _batch_sizes.size(); }
109 TensorShapeRef batch_sizes() const { return _batch_sizes; }
111 const torch::TensorOptions & options() const { return _options; }
113 torch::Dtype scalar_type() const { return _options.dtype().toScalarType(); }
115 torch::Device device() const { return _options.device(); }
117
119 const std::vector<Model *> & registered_models() const { return _registered_models; }
121 Model * registered_model(const std::string & name) const;
122
124 virtual std::set<VariableName> consumed_items() const override;
126 virtual std::set<VariableName> provided_items() const override;
127
129 virtual bool is_AD_enabled() const override { return _enable_AD; }
131 bool using_AD_1st_derivative() const { return _AD_1st_deriv; }
133 bool using_AD_2nd_derivative() const { return _AD_2nd_deriv; }
135 void use_AD_derivatives(bool first = true, bool second = true);
136
138 void prepare();
140 virtual void value();
142 virtual void value_and_dvalue();
144 virtual void dvalue();
146 virtual void value_and_dvalue_and_d2value();
148 virtual void d2value();
150 virtual void dvalue_and_d2value();
152 virtual LabeledVector value(const LabeledVector & in);
154 virtual std::tuple<LabeledVector, LabeledMatrix> value_and_dvalue(const LabeledVector & in);
156 virtual LabeledMatrix dvalue(const LabeledVector & in);
158 virtual std::tuple<LabeledVector, LabeledMatrix, LabeledTensor3D>
161 virtual LabeledTensor3D d2value(const LabeledVector & in);
163 virtual std::tuple<LabeledMatrix, LabeledTensor3D> dvalue_and_d2value(const LabeledVector & in);
164
166 friend class ParameterStore;
167
169 friend class ComposedModel;
170
171protected:
177 virtual void setup() override;
178
189 virtual void check_AD_limitation() const;
191 void check_inplace_dbg();
193 virtual void check_input(const LabeledVector & in) const;
194
197
201 virtual void reinit(bool in, bool out);
203 virtual void cache(TensorShapeRef batch_shape,
204 int deriv_order,
205 const torch::Device & device,
206 const torch::Dtype & dtype);
208 bool requires_grad() const { return _deriv_order >= 1; }
210 bool requires_2nd_grad() const { return _deriv_order >= 2; }
213 virtual void allocate_variables(bool in, bool out);
215 virtual void setup_input_views(VariableStore * host = nullptr) override;
219 virtual void setup_output_views();
220 virtual void setup_submodel_output_views();
221 virtual void setup_nonlinear_system();
223
228 virtual void zero();
230 virtual void set_input(const LabeledVector & in);
232 virtual void set_solution(const Tensor & x) override;
234 virtual void set_value(bool out, bool dout_din, bool d2out_din2) = 0;
235 virtual void assemble(bool residual, bool Jacobian) override;
237
239 virtual LabeledVector get_output();
244
257 template <typename T, typename = typename std::enable_if_t<std::is_base_of_v<Model, T>>>
258 T & register_model(const std::string & name,
259 int extra_deriv_order = 0,
260 bool nonlinear = false,
261 bool merge_input = true)
262 {
264 extra_opts.set<NEML2Object *>("_host") = host();
265 extra_opts.set<int>("_extra_derivative_order") = extra_deriv_order;
266 extra_opts.set<bool>("_nonlinear_system") = nonlinear;
267 extra_opts.set<bool>("_enable_AD") = input_options().get<bool>("_enable_AD");
268
269 auto model = Factory::get_object_ptr<Model>("Models", name, extra_opts);
270
271 if (merge_input)
272 for (auto && [name, var] : model->input_variables())
273 declare_input_variable(var.base_storage(), var.type(), name);
274
275 _registered_models.push_back(model.get());
276 return *(std::dynamic_pointer_cast<T>(model));
277 }
278
280 std::vector<Model *> _registered_models;
281
282private:
286 void input_requires_grad_(bool req = true);
288 void extract_derivatives(bool retain_graph, bool create_graph, bool allow_unused);
290 void extract_second_derivatives(bool retain_graph, bool create_graph, bool allow_unused);
292
294 TensorShape _batch_sizes;
295
297 torch::TensorOptions _options;
298
300 bool _nonlinear_system;
301
312 int _deriv_order;
313
321 const int _extra_deriv_order;
322
324 const bool _enable_AD;
325
327 bool _AD_1st_deriv;
328
330 bool _AD_2nd_deriv;
331
333 Tensor _dr_ds, _dr_dsn, _dr_df, _dr_dfn, _dr_dp;
334
335#ifndef NDEBUG
337 bool _evaluated_once;
338#endif
339};
340} // namespace neml2
Definition ComposedModel.h:35
The wrapper (decorator) for cross-referencing unresolved values at parse time.
Definition CrossRef.h:56
Definition Data.h:36
Definition DependencyDefinition.h:40
Interface for object making diagnostics about common setup errors.
Definition DiagnosticsInterface.h:47
A single-batched, logically 2D LabeledTensor.
Definition LabeledMatrix.h:38
A single-batched, logically 3D LabeledTensor.
Definition LabeledTensor3D.h:38
A single-batched, logically 1D LabeledTensor.
Definition LabeledVector.h:38
The base class for all constitutive models.
Definition Model.h:55
virtual LabeledMatrix get_doutput_dinput()
Definition Model.cxx:374
virtual void setup_submodel_output_views()
Definition Model.cxx:251
virtual void assemble(bool residual, bool Jacobian) override
Compute the residual and Jacobian.
Definition Model.cxx:638
virtual void zero()
Definition Model.cxx:272
virtual void check_input(const LabeledVector &in) const
Check if the input has valid shape.
Definition Model.cxx:338
std::tuple< const Tensor &, const Tensor &, const Tensor &, const Tensor &, const Tensor & > get_system_matrices() const
Get assembled system.
Definition Model.cxx:133
void prepare()
Prepare for evaluation.
Definition Model.cxx:177
void check_inplace_dbg()
Check for potential in-place operation.
Definition Model.cxx:601
virtual void dvalue()
Evalute the derivative.
Definition Model.cxx:484
virtual void diagnose(std::vector< Diagnosis > &) const override
Check for common problems.
Definition Model.cxx:75
void use_AD_derivatives(bool first=true, bool second=true)
Tell this model to use AD to get derivatives.
Definition Model.cxx:330
virtual LabeledVector get_output()
Definition Model.cxx:368
bool requires_grad() const
Whether derivative has been requested for this model.
Definition Model.h:208
virtual LabeledTensor3D get_d2output_dinput2()
Definition Model.cxx:380
virtual bool is_AD_enabled() const override
Whether AD is enabled.
Definition Model.h:129
virtual void dvalue_and_d2value()
Evalute the first and second derivatives.
Definition Model.cxx:538
virtual void value_and_dvalue_and_d2value()
Evalute the model and compute its first and second derivatives.
Definition Model.cxx:506
torch::Dtype scalar_type() const
Storage scalar type.
Definition Model.h:113
const std::vector< Model * > & registered_models() const
The models that may be used during the evaluation of this model.
Definition Model.h:119
std::vector< Model * > _registered_models
Models this model may use during its evaluation.
Definition Model.h:280
Size batch_dim() const
Definition Model.h:107
bool using_AD_1st_derivative() const
Whether this model is using AD to get 1st derivatives.
Definition Model.h:131
virtual void d2value()
Evalute the second derivatives.
Definition Model.cxx:570
virtual void setup_nonlinear_system()
Definition Model.cxx:258
virtual void setup_input_views(VariableStore *host=nullptr) override
Call VariableStore::setup_input_views recursively on all submodels.
Definition Model.cxx:212
virtual void set_solution(const Tensor &x) override
Set x as the current solution of the nonlinear system.
Definition Model.cxx:281
bool requires_2nd_grad() const
Whether 2nd derivative has been requested for this model.
Definition Model.h:210
TensorShapeRef batch_sizes() const
Storage batch shape.
Definition Model.h:109
virtual void set_value(bool out, bool dout_din, bool d2out_din2)=0
The map between input -> output, and optionally its derivatives.
virtual std::set< VariableName > provided_items() const override
The variables that this model defines as part of its output.
Definition Model.cxx:632
torch::Device device() const
Storage device.
Definition Model.h:115
const torch::TensorOptions & options() const
Storage tensor options.
Definition Model.h:111
virtual void setup_output_views()
Definition Model.cxx:230
virtual bool is_nonlinear_system() const
Whether this model defines one or more nonlinear equations to be solved.
Definition Model.h:72
T & register_model(const std::string &name, int extra_deriv_order=0, bool nonlinear=false, bool merge_input=true)
Register a model that the current model may use during its evaluation.
Definition Model.h:258
virtual void check_AD_limitation() const
Definition Model.cxx:314
virtual void set_input(const LabeledVector &in)
Set in to be the input of this model.
Definition Model.cxx:357
virtual void setup() override
Setup this model.
Definition Model.cxx:126
virtual void value()
Evalute the model.
Definition Model.cxx:452
virtual void allocate_variables(bool in, bool out)
Call VariableStore::allocate_variables recursively on all submodels.
Definition Model.cxx:186
static OptionSet expected_options()
Definition Model.cxx:31
virtual void value_and_dvalue()
Evalute the model and compute its derivative.
Definition Model.cxx:462
void diagnose_nl_sys(std::vector< Diagnosis > &diagnoses) const
Additional diagnostics for a nonlinear system.
Definition Model.cxx:101
virtual void reinit(const Tensor &tensor, int deriv_order)
Allocate storage and setup views for all the variables of this model and recursively all of the sub-m...
Definition Model.cxx:140
virtual void setup_submodel_input_views(VariableStore *host)
Definition Model.cxx:219
bool using_AD_2nd_derivative() const
Whether this model is using AD to get 2nd derivatives.
Definition Model.h:133
virtual void cache(TensorShapeRef batch_shape, int deriv_order, const torch::Device &device, const torch::Dtype &dtype)
Definition Model.cxx:291
Model(const OptionSet &options)
Construct a new Model object.
Definition Model.cxx:54
Model * registered_model(const std::string &name) const
Get a registered model by its name.
Definition Model.cxx:615
virtual std::set< VariableName > consumed_items() const override
The variables that this model depends on.
Definition Model.cxx:626
The base class of all "manufacturable" objects in the NEML2 library.
Definition NEML2Object.h:38
const std::string & name() const
A readonly reference to the object's name.
Definition NEML2Object.h:65
const T * host() const
Get a readonly pointer to the host.
Definition NEML2Object.h:90
const OptionSet & input_options() const
Definition NEML2Object.h:51
Definition of a nonlinear system of equations.
Definition NonlinearSystem.h:37
void residual()
Convenient shortcut to assemble and return the system residual.
Definition NonlinearSystem.cxx:174
void Jacobian()
Convenient shortcut to assemble and return the system Jacobian.
Definition NonlinearSystem.cxx:190
A custom map-like data structure. The keys are strings, and the values can be nonhomogeneously typed.
Definition OptionSet.h:100
Interface for object which can store parameters.
Definition ParameterStore.h:45
Definition Tensor.h:32
Definition VariableStore.h:40
virtual void setup_output_views(bool out, bool dout_din, bool d2out_din2)
Tell each output variable view which tensor storage(s) to view into.
Definition VariableStore.cxx:134
const Variable< T > & declare_input_variable(S &&... name)
Declare an input variable.
Definition VariableStore.h:182
virtual void allocate_variables(TensorShapeRef batch_shape, const torch::TensorOptions &options, bool in, bool out, bool dout_din, bool d2out_din2)
Allocate variable storages given the batch shape and tensor options.
Definition VariableStore.cxx:95
virtual void zero(bool dout_din, bool d2out_din2)
Zero out derivative and second derivative storage.
Definition VariableStore.cxx:143
virtual void cache(TensorShapeRef batch_shape)
Cache the variable's batch shape.
Definition VariableStore.cxx:86
Definition CrossRef.cxx:30
torch::Device & default_device()
Default device.
Definition types.cxx:60
torch::Dtype & default_dtype()
Default floating point type.
Definition types.cxx:46
torch::SmallVector< Size > TensorShape
Definition types.h:34
torch::IntArrayRef TensorShapeRef
Definition types.h:35