https://mooseframework.inl.gov
NEML2ModelInterface.h
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://mooseframework.inl.gov
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #pragma once
11 
12 #include <thread>
13 #include <utility>
14 #include <tuple>
15 #include "NEML2Utils.h"
16 #include "InputParameters.h"
17 
18 #ifdef NEML2_ENABLED
19 #include <ATen/Parallel.h>
20 #include "neml2/models/Model.h"
21 #include "neml2/dispatchers/WorkScheduler.h"
22 #include "neml2/dispatchers/WorkDispatcher.h"
23 #include "neml2/dispatchers/valuemap_helpers.h"
24 #include "neml2/dispatchers/derivmap_helpers.h"
25 #endif
26 
31 template <class T>
32 class NEML2ModelInterface : public T
33 {
34 public:
36 
37  template <typename... P>
38  NEML2ModelInterface(const InputParameters & params, P &&... args);
39 
40 #ifdef NEML2_ENABLED
41 
42 protected:
47  virtual void validateModel() const;
48 
50  neml2::Model & model() const { return *_model; }
51 
53  const neml2::Device & device() const { return _device; }
54 
55  using RJType = std::tuple<neml2::ValueMap, neml2::DerivMap>;
56  using DispatcherType =
57  neml2::WorkDispatcher<neml2::ValueMap, RJType, RJType, neml2::ValueMap, RJType>;
58 
60  neml2::WorkScheduler * scheduler() { return _scheduler.get(); }
62  const std::unique_ptr<DispatcherType> & dispatcher() const { return _dispatcher; }
63 
64 private:
66  const neml2::Device _device;
68  std::unique_ptr<neml2::Factory> _factory;
70  std::shared_ptr<neml2::Model> _model;
71 
73  std::shared_ptr<neml2::WorkScheduler> _scheduler;
75  std::unique_ptr<DispatcherType> _dispatcher;
77  const bool _async_dispatch;
79  std::unordered_map<std::thread::id, std::shared_ptr<neml2::Model>> _model_pool;
80 
81 #endif // NEML2_ENABLED
82 };
83 
84 template <class T>
87 {
89  params.addParam<DataFileName>(
90  "input",
91  NEML2Utils::docstring("Path to the NEML2 input file containing the NEML2 model(s)."));
92  params.addParam<std::vector<std::string>>(
93  "cli_args",
94  {},
96  "Additional command line arguments to use when parsing the NEML2 input file."));
97  params.addParam<std::string>(
98  "model",
99  "",
100  NEML2Utils::docstring("Name of the NEML2 model, i.e., the string inside the brackets [] in "
101  "the NEML2 input file that corresponds to the model you want to use."));
102  params.addParam<std::string>(
103  "device",
104  "cpu",
106  "Device on which to evaluate the NEML2 model. The string supplied must follow the "
107  "following schema: (cpu|cuda)[:<device-index>] where cpu or cuda specifies the device "
108  "type, and :<device-index> optionally specifies a device index. For example, "
109  "device='cpu' sets the target compute device to be CPU, and device='cuda:1' sets the "
110  "target compute device to be CUDA with device ID 1."));
111 
112  params.addParam<std::string>(
113  "scheduler",
115  "NEML2 scheduler to use to run the model. If not specified no scheduler is used and "
116  "MOOSE will pass all the constitutive updates to the provided device at once."));
117 
118  params.addParam<bool>(
119  "async_dispatch", true, NEML2Utils::docstring("Whether to use asynchronous dispatch."));
120 
121  return params;
122 }
123 
124 #ifndef NEML2_ENABLED
125 
126 template <class T>
127 template <typename... P>
129  : T(params, args...)
130 {
131 }
132 
133 #else
134 
135 template <class T>
136 template <typename... P>
138  : T(params, args...),
139  _device(params.get<std::string>("device")),
140  _scheduler(nullptr),
141  _async_dispatch(params.get<bool>("async_dispatch"))
142 {
143  // Load model
144  const auto & fname = params.get<DataFileName>("input");
145  const auto & cli_args = params.get<std::vector<std::string>>("cli_args");
146  _factory = neml2::load_input(std::string(fname), neml2::utils::join(cli_args, " "));
147  _model = NEML2Utils::getModel(*_factory, params.get<std::string>("model"));
148  _model->to(_device);
149 
150  // Load scheduler if specified
151  if (params.isParamValid("scheduler"))
152  _scheduler = _factory->get_scheduler(params.get<std::string>("scheduler"));
153 
154  if (_scheduler)
155  {
156  auto red = [](std::vector<RJType> && results) -> RJType
157  {
158  // Split into two separate vectors
159  std::vector<neml2::ValueMap> vms;
160  std::vector<neml2::DerivMap> dms;
161  for (auto && [vm, dm] : results)
162  {
163  vms.push_back(std::move(vm));
164  dms.push_back(std::move(dm));
165  }
166  return std::make_tuple(neml2::valuemap_cat_reduce(std::move(vms), 0),
167  neml2::derivmap_cat_reduce(std::move(dms), 0));
168  };
169 
170  auto post = [this](RJType && x) -> RJType
171  {
172  return std::make_tuple(neml2::valuemap_move_device(std::move(std::get<0>(x)), _device),
173  neml2::derivmap_move_device(std::move(std::get<1>(x)), _device));
174  };
175 
176  auto thread_init = [this](neml2::Device device) -> void
177  {
178  at::set_num_threads(libMesh::n_threads());
179  at::set_num_interop_threads(libMesh::n_threads());
180  auto model = NEML2Utils::getModel(*_factory, _model->name());
181  model->to(device);
182  _model_pool[std::this_thread::get_id()] = std::move(model);
183  };
184 
185  _dispatcher = std::make_unique<DispatcherType>(
186  *_scheduler,
188  [&](neml2::ValueMap && x, neml2::Device device) -> RJType
189  {
190  auto & model =
191  _async_dispatch ? libmesh_map_find(_model_pool, std::this_thread::get_id()) : _model;
192 
193  // If this is not an async dispatch, we need to move the model to the target device
194  // _every_ time before evaluation
195  if (!_async_dispatch)
196  model->to(device);
197 
198  return model->value_and_dvalue(std::move(x));
199  },
200  red,
201  &neml2::valuemap_move_device,
202  post,
203  _async_dispatch ? thread_init : std::function<void(neml2::Device)>());
204  }
205 }
206 
207 template <class T>
208 void
210 {
211  mooseAssert(_model != nullptr, "_model must be initialized");
212  neml2::diagnose(*_model);
213 }
214 
215 #endif // NEML2_ENABLED
std::shared_ptr< neml2::WorkScheduler > _scheduler
The work scheduler to use.
neml2::WorkScheduler * scheduler()
Get the work scheduler.
std::string join(Iterator begin, Iterator end, const std::string &delimiter)
Python-like join function for strings over an iterator range.
Definition: MooseUtils.h:142
unsigned int n_threads()
static InputParameters validParams()
std::unordered_map< std::thread::id, std::shared_ptr< neml2::Model > > _model_pool
Models for each thread.
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
Combine two vector parameters into a single vector of pairs.
T * get(const std::unique_ptr< T > &u)
The MooseUtils::get() specializations are used to support making forwards-compatible code changes fro...
Definition: MooseUtils.h:1155
Interface class to provide common input parameters, members, and methods for MOOSEObjects that use NE...
PetscErrorCode PetscOptionItems *PetscErrorCode DM dm
neml2::Model & model() const
Get the NEML2 model.
std::unique_ptr< DispatcherType > _dispatcher
Work dispatcher.
const neml2::Device & device() const
Get the target compute device.
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
const std::unique_ptr< DispatcherType > & dispatcher() const
Get the work dispatcher.
std::tuple< neml2::ValueMap, neml2::DerivMap > RJType
InputParameters validParams()
std::shared_ptr< neml2::Model > _model
The NEML2 material model.
NEML2ModelInterface(const InputParameters &params, P &&... args)
std::string docstring(const std::string &desc)
Augment docstring if NEML2 is not enabled.
Definition: NEML2Utils.C:77
std::shared_ptr< neml2::Model > getModel(neml2::Factory &factory, const std::string &name, neml2::Dtype dtype=neml2::kFloat64)
Get the NEML2 Model.
Definition: NEML2Utils.C:18
neml2::WorkDispatcher< neml2::ValueMap, RJType, RJType, neml2::ValueMap, RJType > DispatcherType
std::unique_ptr< neml2::Factory > _factory
The NEML2 factory.
void addParam(const std::string &name, const S &value, const std::string &doc_string)
These methods add an optional parameter and a documentation string to the InputParameters object...
const bool _async_dispatch
Whether to dispatch work asynchronously.
virtual void validateModel() const
Validate the NEML2 material model.
const neml2::Device _device
The device on which to evaluate the NEML2 model.
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another, i.e.