- active__all__ If specified only the blocks named will be visited and made active
Default:__all__
C++ Type:std::vector<std::string>
Controllable:No
Description:If specified only the blocks named will be visited and made active
- auto_outputTrueWhether to automatically retrieve all NEML2 output variables as MOOSE material properties.
Default:True
C++ Type:bool
Controllable:No
Description:Whether to automatically retrieve all NEML2 output variables as MOOSE material properties.
- cli_argsAdditional command line arguments to use when parsing the NEML2 input file.
C++ Type:std::vector<std::string>
Controllable:No
Description:Additional command line arguments to use when parsing the NEML2 input file.
- derivativesList of NEML2 derivatives to retrieve. Each entry is (output, input) -- the derivative of 'output' w.r.t. 'input' -- with an optional third element aliasing it to a custom MOOSE material property name (default d(output)/d(input)).
C++ Type:std::vector<std::vector<std::string>>
Controllable:No
Description:List of NEML2 derivatives to retrieve. Each entry is (output, input) -- the derivative of 'output' w.r.t. 'input' -- with an optional third element aliasing it to a custom MOOSE material property name (default d(output)/d(input)).
- deviceCompute device(s) for the NEML2 model, each following the schema (cpu|cuda)[:
] (e.g. 'cpu', 'cuda:1'). cpp-eager pins the model to the first device. cpp-aoti dispatches over the list: a CUDA list is round-robined over the MPI ranks on each node (one device per rank when counts match, sharing when there are more ranks than devices, an error when there are fewer); a single 'cpu' runs each rank's local batch on CPU. If not specified, defaults to the compute device from the --compute-device command line argument. C++ Type:std::vector<std::string>
Controllable:No
Description:Compute device(s) for the NEML2 model, each following the schema (cpu|cuda)[:
] (e.g. 'cpu', 'cuda:1'). cpp-eager pins the model to the first device. cpp-aoti dispatches over the list: a CUDA list is round-robined over the MPI ranks on each node (one device per rank when counts match, sharing when there are more ranks than devices, an error when there are fewer); a single 'cpu' runs each rank's local batch on CPU. If not specified, defaults to the compute device from the --compute-device command line argument. - device_batchPer-device chunk size along the leading batch axis (0 = run the whole local batch at once). Must have length 1 (broadcast to all devices) or match the length of 'device'. Defaults to 0.
C++ Type:std::vector<unsigned int>
Controllable:No
Description:Per-device chunk size along the leading batch axis (0 = run the whole local batch at once). Must have length 1 (broadcast to all devices) or match the length of 'device'. Defaults to 0.
- dump_inputs_on_failureFalseWhen a NEML2 constitutive solve fails (recoverable convergence failure), serialize the input tensors to a per-rank TorchScript file '
_count _rank .pt' (c is a persistent failure counter). The file can be loaded offline with torch.jit.load to re-evaluate the model on the failing batch, independently of MOOSE. Default:False
C++ Type:bool
Controllable:No
Description:When a NEML2 constitutive solve fails (recoverable convergence failure), serialize the input tensors to a per-rank TorchScript file '
_count _rank .pt' (c is a persistent failure counter). The file can be loaded offline with torch.jit.load to re-evaluate the model on the failing batch, independently of MOOSE. - eagerFalseUse the cpp-eager NEML2 runtime, which embeds a Python interpreter and loads the model from the source 'input' file at runtime. Default false -- use the cpp-aoti runtime, which loads an ahead-of-time-compiled artifact (no Python at runtime) from the artifact folder given by 'input'. The 'load' parameter is only valid with eager=true.
Default:False
C++ Type:bool
Controllable:No
Description:Use the cpp-eager NEML2 runtime, which embeds a Python interpreter and loads the model from the source 'input' file at runtime. Default false -- use the cpp-aoti runtime, which loads an ahead-of-time-compiled artifact (no Python at runtime) from the artifact folder given by 'input'. The 'load' parameter is only valid with eager=true.
- export_output_targetsThe export targets corresponding to each MOOSE material property specified in export_outputs.
C++ Type:std::vector<std::vector<OutputName>>
Controllable:No
Description:The export targets corresponding to each MOOSE material property specified in export_outputs.
- export_outputsList of MOOSE material properties to export which correspond to NEML2 output variables or output derivatives. Each material property's export targets can be specified by export_output_targets. The default export target is 'none'.
C++ Type:std::vector<MaterialPropertyName>
Unit:(no unit assumed)
Controllable:No
Description:List of MOOSE material properties to export which correspond to NEML2 output variables or output derivatives. Each material property's export targets can be specified by export_output_targets. The default export target is 'none'.
- inactiveIf specified blocks matching these identifiers will be skipped.
C++ Type:std::vector<std::string>
Controllable:No
Description:If specified blocks matching these identifiers will be skipped.
- initialize_output_valuesList of MOOSE material properties whose initial values (evaluated at the 0th time step) will be used to initialize stateful properties. See the description of initialize_outputs for more details.
C++ Type:std::vector<MaterialPropertyName>
Unit:(no unit assumed)
Controllable:No
Description:List of MOOSE material properties whose initial values (evaluated at the 0th time step) will be used to initialize stateful properties. See the description of initialize_outputs for more details.
- initialize_outputsList of MOOSE material properties to be initialized. Each these properties must correspond to a stateful NEML2 variable (which appears on both the input old state sub-axis and the output state sub-axis). These MOOSE material properties will be initialized with the values of properties specified in the initialize_output_values list.
C++ Type:std::vector<MaterialPropertyName>
Unit:(no unit assumed)
Controllable:No
Description:List of MOOSE material properties to be initialized. Each these properties must correspond to a stateful NEML2 variable (which appears on both the input old state sub-axis and the output state sub-axis). These MOOSE material properties will be initialized with the values of properties specified in the initialize_output_values list.
- inputFor the cpp-eager runtime, the path to the source NEML2 '.i' model file. For the cpp-aoti runtime, any of: the artifact folder produced by neml2-compile (a self-describing directory holding metadata.json plus per-
/ '.pt2' binaries), the metadata.json inside it, or the neml2-compile stub '.i'. Prefer the artifact folder -- it is self-contained and relocatable as a unit, and needs no 'model' name. The stub '.i' is accepted for compatibility but points at its artifact folder by path, so the two must stay together. C++ Type:DataFileName
Controllable:No
Description:For the cpp-eager runtime, the path to the source NEML2 '.i' model file. For the cpp-aoti runtime, any of: the artifact folder produced by neml2-compile (a self-describing directory holding metadata.json plus per-
/ '.pt2' binaries), the metadata.json inside it, or the neml2-compile stub '.i'. Prefer the artifact folder -- it is self-contained and relocatable as a unit, and needs no 'model' name. The stub '.i' is accepted for compatibility but points at its artifact folder by path, so the two must stay together. - input_kernelsNEML2 kernels defined in MOOSE that provides input data. The object name must match the input variable name.
C++ Type:std::vector<std::string>
Controllable:No
Description:NEML2 kernels defined in MOOSE that provides input data. The object name must match the input variable name.
- input_typesType of each MOOSE data to be used as NEML2 input variable
C++ Type:MultiMooseEnum
Controllable:No
Description:Type of each MOOSE data to be used as NEML2 input variable
- inputsList of NEML2 input variables corresponding to each MOOSE data.
C++ Type:std::vector<std::string>
Controllable:No
Description:List of NEML2 input variables corresponding to each MOOSE data.
- loadExternal Python extension files (paths to .py files or package directories, resolved relative to the input file and the application's data search path) imported into the embedded interpreter before the NEML2 model is built. Importing them registers any @register_neml2_object types they define -- e.g. NEML2 models hosted inside a MOOSE app -- so the NEML2 input file can reference them. Mirrors the neml2 CLI --load flag. Only valid with the cpp-eager runtime (eager=true).
C++ Type:std::vector<DataFileName>
Controllable:No
Description:External Python extension files (paths to .py files or package directories, resolved relative to the input file and the application's data search path) imported into the embedded interpreter before the NEML2 model is built. Importing them registers any @register_neml2_object types they define -- e.g. NEML2 models hosted inside a MOOSE app -- so the NEML2 input file can reference them. Mirrors the neml2 CLI --load flag. Only valid with the cpp-eager runtime (eager=true).
- manage_state_advanceFalseKeep state and forces on the device and advance it to old state and old forces without a roundtrip through MOOSE materials. This is only recommended for explicit time integration or when absolutely no restepping occurs (e.g. failed timesteps).
Default:False
C++ Type:bool
Controllable:No
Description:Keep state and forces on the device and advance it to old state and old forces without a roundtrip through MOOSE materials. This is only recommended for explicit time integration or when absolutely no restepping occurs (e.g. failed timesteps).
- modelName of the NEML2 model, i.e., the string inside the brackets [] in the NEML2 input file that corresponds to the model you want to use. Required for the cpp-eager runtime, and for cpp-aoti only when 'input' is a stub '.i'; the cpp-aoti folder and metadata.json forms use the single model recorded in the artifact metadata and ignore it.
C++ Type:std::string
Controllable:No
Description:Name of the NEML2 model, i.e., the string inside the brackets [] in the NEML2 input file that corresponds to the model you want to use. Required for the cpp-eager runtime, and for cpp-aoti only when 'input' is a stub '.i'; the cpp-aoti folder and metadata.json forms use the single model recorded in the artifact metadata and ignore it.
- num_threadsNumber of threads to use when evaluating the NEML2 model. Defaults to the number of threads MOOSE is run with (the --n-threads command-line value). Some models evaluate fastest with a single thread regardless of --n-threads; set this to 1 in that case.
C++ Type:unsigned int
Controllable:No
Description:Number of threads to use when evaluating the NEML2 model. Defaults to the number of threads MOOSE is run with (the --n-threads command-line value). Some models evaluate fastest with a single thread regardless of --n-threads; set this to 1 in that case.
- output_deviceDevice on which to store the model outputs, following the same schema as a single 'device' entry. Defaults to cpu, where MOOSE consumes them. Set this only if a downstream object needs the outputs on a specific device.
C++ Type:std::string
Controllable:No
Description:Device on which to store the model outputs, following the same schema as a single 'device' entry. Defaults to cpu, where MOOSE consumes them. Set this only if a downstream object needs the outputs on a specific device.
- parameter_derivativesList of NEML2 parameter derivatives to retrieve. Each entry is (output, parameter) -- the derivative of 'output' w.r.t. model 'parameter' -- with an optional third element aliasing it to a custom MOOSE material property name (default d(output)/d(parameter)).
C++ Type:std::vector<std::vector<std::string>>
Controllable:No
Description:List of NEML2 parameter derivatives to retrieve. Each entry is (output, parameter) -- the derivative of 'output' w.r.t. model 'parameter' -- with an optional third element aliasing it to a custom MOOSE material property name (default d(output)/d(parameter)).
- parameter_typesType of each MOOSE data to be used as NEML2 model parameter
C++ Type:MultiMooseEnum
Controllable:No
Description:Type of each MOOSE data to be used as NEML2 model parameter
- parametersList of NEML2 model parameters corresponding to each MOOSE data.
C++ Type:std::vector<std::string>
Controllable:No
Description:List of NEML2 model parameters corresponding to each MOOSE data.
- skip_input_variablesList of NEML2 variables to skip when setting up the model input. If an input variable is skipped, its value will stay zero. If a required input variable is skipped, an error will be raised.
C++ Type:std::vector<std::string>
Controllable:No
Description:List of NEML2 variables to skip when setting up the model input. If an input variable is skipped, its value will stay zero. If a required input variable is skipped, an error will be raised.
NEML2Action
Set up the NEML2 material model
This page is developer-facing. Users please refer to the NEML2 syntax documentation.
Overview
This is the primary action responsible for constructing objects for transferring data back and forth between MOOSE and NEML2, as well as for executing the NEML2 model.
Four types of objects are constructed by this action:
Gatherer: Object responsible for gathering MOOSE data.
Retriever: Object responsible for retrieving NEML2 data and assigning it back to MOOSE data structures.
Index generator: Object responsible for generating the element-to-batch-index map.
Executor: Object responsible for sending data gathered by gatherers to NEML2, execute the NEML2 model, and have the outputs ready for retrieval by retrievers.
Currently supported objects are summarized below.
| Type | MOOSE object(s) |
|---|---|
| Gatherer | MOOSEQuantityToNEML2 |
| Retriever | NEML2ToMOOSEMaterialProperty |
| Index generator | NEML2BatchIndexGenerator |
| Executor | NEML2ModelExecutor |
Multiple gatherers and retrievers may be created by this action, but each instance of the action creates one and only one index generator and executor. Each step performed by this action is explained in one of the following sections, in the order of execution.
Applying common parameters
Recall that input file parameters in the common area under the [NEML2] block defined by the NEML2ActionCommon are shared by all sub-blocks. The first step is to retrieve the common parameters and apply them to this sub-block. This happens in the constructor of the action. Note that parameters defined in the sub-block overrides the parameters defined in the common area.
Creating the NEML2 model
By the time this action "acts", the NEML2 input file must have already been parsed and loaded by NEML2ActionCommon. Therefore, the NEML2 model associated with this action can be directly created using the name given by "model".
NEML2 model introspection
A high-level summary of the NEML2 model is printed to the console, including model name, evaluation device, as well as a table summarizing the model's variables, parameters, and buffers.
NEML2 model allows introspection, i.e., variable and parameter names, tensor types, and storage sizes can be inferred after the model is loaded. Five maps are set up upon introspection of the NEML2 model:
A map between MOOSE data structures and NEML2 input variables.
A map between MOOSE data structures and NEML2 model parameters.
A map between MOOSE data structures and NEML2 output variables.
A map between MOOSE data structures and NEML2 output derivatives.
A map between MOOSE data structures and NEML2 parameter derivatives.
These maps are used later to create objects for transferring data between MOOSE and NEML2.
Creating MOOSEToNEML2 gatherers
This step involves the creation of MOOSEToNEML2 gatherers for NEML2 input variables and model parameters. The first two maps mentioned in the previous section are used. The maps are looped through to create objects one-by-one.
Note that the correct type of object is selected/created relying on NEML2 model introspection. For example, if a NEML2 input variable is of type SR2, we can infer that the corresponding MOOSE data structure should be SymmetricRankTwoTensor.
Creating the NEML2 index generator and model executor
Next, a NEML2BatchIndexGenerator and a NEML2ModelExecutor excutor are created. The list of "gatherers" and "param_gatherers" are automatically filled out by this action.
Creating NEML2ToMOOSE retrievers
The last step is creating the NEML2ToMOOSE retrievers to retrieve NEML2 model outputs (and their derivatives) back to MOOSE. This step is similar to creating MOOSEToNEML2 gatherers.
Debugging a failed constitutive update
A NEML2 constitutive update can fail to converge for some elements – a recoverable return-map failure (a Newton divergence or max-iterations in the material solve). MOOSE then cuts the time step and retries, so the exact inputs that triggered the failure are normally lost by the time the run ends. Set "dump_inputs_on_failure" to true to capture them: on each failed update the executor serializes the whole local batch of NEML2 input tensors (strains, temperature, old state, model parameters, ...) to a per-rank TorchScript file <model>_count<c>_rank<r>.pt.
The counter <c> is advanced collectively, so it is identical on every rank for a given failed update; since MOOSE streams only rank 0 to the console, the reported message names the <model>_count<c>_rank_*.pt glob (one file per failing rank) along with the time step, execute_on flag, and nonlinear iteration for context.
Each file can be loaded offline with torch.jit.load – its buffers are the model's input variables (characters that are invalid in identifiers, such as the ~ in old-state lag names, are replaced by _) – so the model can be re-evaluated on exactly the failing batch and the divergence diagnosed independently of MOOSE. This is a debugging aid; leave it off (the default) for production runs.
To make that diagnosis near-zero-boilerplate, NEML2 can attach a failure context to the recoverable ConvergenceError a non-converged constitutive update raises. Set the NEML2_CAPTURE_SOLVE_FAILURE environment variable before the failing solve and the exception carries two extra attributes:
converged_mask– a per-batch-entry boolean tensor,Truewhere that quadrature point converged. Isolating which points diverged is then a single(~e.converged_mask).nonzero(), rather than re-running each entry as its own size-1 batch.unknowns– a{unknown-variable name -> best-effort iterate}map: the state the Newton solve got stuck at, ready to inspect. Each value is a NEML2-typed tensor when replaying an eager model, or a plaintorch.Tensorfor a compiled one; both carry the dynamic-batch leading dim.
The capture is identical whether you load the eager model .i or the <model>_aoti.i compiled stub, and identical to what MOOSE sees at runtime. It is off by default because it costs an extra masked re-solve on each failure; the boilerplate below turns it on at import time.
The following boilerplate (1) loads a dumped file and maps its buffers back onto the model's inputs, and (2) re-runs the model on the whole failing batch to reproduce the failure and read the failing entries + stuck state off the exception (export NEML2_LOGS="newton=info" to additionally print the per-iteration residual history):
Re-evaluate a NEML2 model on a dumped failing batch and read the failure context (from "dump_inputs_on_failure" with NEML2_CAPTURE_SOLVE_FAILURE).
import os
# Ask NEML2 to attach a failure context to the recoverable ConvergenceError a
# non-converged constitutive update raises. Must be set before the failing solve
# (both the compiled and Python runtimes read it live). Off by default because it
# costs an extra masked re-solve on failure.
os.environ["NEML2_CAPTURE_SOLVE_FAILURE"] = "1"
import glob
import unittest
import torch
import neml2
from neml2.solvers import ConvergenceError
def load_dumped_inputs(dump_glob, model_input, model_name):
"""Load a ``dump_inputs_on_failure`` TorchScript file and map its buffers back
onto a freshly-loaded NEML2 model -- no MOOSE required.
dump_glob : glob for the per-rank dump(s) MOOSE named in its error message,
e.g. ``"mymodel_count0_rank*.pt"``
model_input : the model ``.i`` (eager) or the ``<model>_aoti.i`` stub (compiled)
model_name : the ``[Models]`` block name
Returns ``(model, inputs)`` where ``inputs`` maps each model input name to its
NEML2-typed tensor from the dump.
"""
# dump_inputs_on_failure stores each input tensor as a TorchScript buffer,
# replacing characters that are invalid in identifiers -- the ``~`` of
# old-state lag names, the ``/`` of nested names -- with ``_``. Re-apply the
# same sanitization to match a model input name to its buffer.
def sanitize(name):
return "".join(c if (c.isalnum() or c == "_") else "_" for c in name)
dump_file = sorted(glob.glob(dump_glob))[0] # one file per failing rank
buffers = dict(torch.jit.load(dump_file).named_buffers())
model = neml2.load_model(model_input, model_name)
inputs = {name: T(buffers[sanitize(name)]) for name, T in model.input_spec.items()}
return model, inputs
def diagnose_failure(model, inputs):
"""Re-run the model on the whole failing batch and read the failure context.
With ``NEML2_CAPTURE_SOLVE_FAILURE`` set (see top of file), the recoverable
``ConvergenceError`` carries, as attributes:
``converged_mask`` -- a per-batch-entry bool tensor (``True`` where that
quadrature point converged),
``unknowns`` -- ``{unknown-variable name -> best-effort iterate}``,
the state the Newton solve got stuck at. Each value is
a NEML2-typed tensor when replaying an eager model or a
plain ``torch.Tensor`` for a compiled one; both carry
the dynamic-batch leading dim, so index them the same.
Returns ``(failing_indices, unknowns)`` -- the batch entries (quadrature
points) that diverged and the stuck state -- or ``None`` if the batch
actually converged on replay (the MOOSE-context failure did not reproduce
standalone). Export ``NEML2_LOGS="newton=info"`` to also print the
per-iteration residual history of the replay.
"""
try:
model(*[inputs[name] for name in model.input_spec])
return None # converged on replay -- nothing to diagnose
except ConvergenceError as e:
failing = (~e.converged_mask).nonzero().flatten().tolist()
return failing, e.unknowns
(test/tests/neml2/debug_dumped_inputs.py)Input Parameters
- control_tagsAdds user-defined labels for accessing object parameters via control logic.
C++ Type:std::vector<std::string>
Controllable:No
Description:Adds user-defined labels for accessing object parameters via control logic.
These input parameters correspond to the sub-blocks under the [NEML2] block. The usage of the [NEML2] block is explained in details in the NEML2 syntax documentation.
The detailed documentation of this object/syntax is only available when MOOSE is compiled with NEML2. To enable NEML2, please follow the NEML2 installation guide.