TorchScript1DProfileFunctorMaterial

Overview

TorchScript1DProfileFunctorMaterial evaluates a TorchScript model and converts its output into one or more spatially varying functor material properties. It is intended for models that predict a discrete one-dimensional profile, such as a friction coefficient, heat-transfer coefficient, or closure correction along a channel. The predicted values are linearly interpolated in profile coordinates and may be consumed by finite-element and finite-volume objects through the MOOSE functor interface.

The TorchScript module is loaded and evaluated through a TorchScriptUserObject. Unlike TorchScriptMaterial, which creates conventional quadrature-point material properties, this object creates Real functors that can be evaluated using the spatial arguments supplied by a consuming MOOSE object.

Model inputs and outputs

Model inputs are supplied using exactly one of the following parameters:

  • "input_names", which obtains the model inputs from scalar postprocessors; or

  • "input_values", which supplies constant model inputs directly in the input file.

For inputs, the material constructs a tensor of shape [1, M]. The tensor scalar type is selected with "tensor_dtype", which defaults to float32.

The TorchScript model may return any of the following shapes:

  • [N] for one profile containing stations along a line;

  • [C, N] for profiles containing stations along the line each; or

  • [1, C, N] with a leading unit batch dimension.

The number of output profiles must equal the number of entries in "profile_names", and the number of stations must equal the number of entries in "profile_coordinates". The coordinates must be finite and strictly increasing. Each row of the normalized [C, N] output tensor is paired with "profile_coordinates" to construct one linearly interpolated functor.

Update schedule

The TorchScript model is evaluated according to "execute_on", which accepts two flags:

  • INITIAL (default) evaluates the model once during initial setup, so the generated profiles remain fixed for the entire simulation.

  • TIMESTEP_BEGIN additionally re-runs inference at the start of every time step, so the profiles can follow time-varying inputs.

Only these two flags are offered because the model consumes solely the scalar values supplied through "input_names" or "input_values". "execute_on" therefore controls when inference re-runs. Between updates, the generated profiles remain fixed.

If an entry in "input_names" is a postprocessor that depends on the solution, the material reads only that postprocessor's most recently stored scalar value:

  • In a steady simulation, inference occurs before the nonlinear solve. The default INITIAL evaluation can occur before the input postprocessor has performed its normal INITIAL execution. Including TIMESTEP_BEGIN causes one additional profile update immediately before the steady solve, after INITIAL postprocessors have executed. This update can therefore use postprocessor values computed from the initialized solution, but the resulting profiles remain fixed throughout the nonlinear iterations.

  • In a transient simulation with TIMESTEP_BEGIN, the material rebuilds its profiles before postprocessors scheduled on TIMESTEP_BEGIN are recomputed. It therefore uses the value stored by the input postprocessor at its preceding execution, normally a value computed from the previous accepted solution. The profiles then remain fixed throughout the current time-step solve. A postprocessor that also executes on TIMESTEP_BEGIN is consequently seen with a one-step lag.

warningwarning:Profile availability and automatic differentiation

Values referenced by "input_names" must be available when each profile update occurs. The published functors do not reevaluate the model when the solution changes or distinguish current and old solution states. They have type Real, and TorchScript inference is performed outside the MOOSE automatic-differentiation graph. Consequently, a solution-dependent input is treated as a lagged explicit coupling: its dependence on the current nonlinear solution is not represented in the Jacobian.

Spatial coordinate mapping

At a physical point , the scalar coordinate used to evaluate the profile is

(1)

where is "profile_origin", is the normalized "profile_direction", and is "coordinate_scale". The supplied direction therefore does not need to have unit length, but it must be finite and nonzero. "coordinate_scale" converts mesh distance along the selected direction into the coordinate system used by "profile_coordinates".

The "out_of_range_behavior" parameter determines how values outside the tabulated coordinate range are handled:

  • error (default) reports an error;

  • clamp returns the value at the nearest endpoint; and

  • extrapolate linearly extrapolates using the nearest two profile stations.

Example

The following TorchScript model maps the two inputs [a, b] to two profiles at coordinates [0, 1, 2] and can be saved to two_profiles.pt for use with this material:


import torch
from torch import nn


class TwoProfileModel(nn.Module):
    def forward(self, x):
        # x is expected to have shape [1, 2] containing [a, b]
        a = x[0, 0]
        b = x[0, 1]

        stations = torch.tensor([0.0, 1.0, 2.0], dtype=x.dtype, device=x.device)

        # Given inputs [a, b], produce
        # [[a, a + 2, a + 4],
        #  [b, b - 1, b - 2]].
        profile_a = a + 2.0 * stations
        profile_b = b - 1.0 * stations

        return torch.stack((profile_a, profile_b), dim=0)


model = TwoProfileModel()
scripted_model = torch.jit.script(model)
scripted_model.save("two_profiles.pt")

For the input [10, 5], this model returns

The first row defines profile_a, and the second row defines profile_b.

The material is configured in the test input as follows:

[UserObjects<<<{"href": "../../syntax/UserObjects/index.html"}>>>]
  [profile_network]
    type = TorchScriptUserObject<<<{"description": "User-facing object which loads a torch script module.", "href": "../libtorch/userobjects/TorchScriptUserObject.html"}>>>
    filename<<<{"description": "The file name which contains the torch script module."}>>> = two_profiles.pt
    load_during_construction<<<{"description": "If we want to load this neural network while we are constructing this object."}>>> = true
    execute_on<<<{"description": "The list of flag(s) indicating when this object should be executed. For a description of each flag, see https://mooseframework.inl.gov/source/interfaces/SetupInterface.html."}>>> = NONE
  []
[]
(modules/navier_stokes/test/tests/functormaterials/torchscript_profile_functor_material/profile.i)
[FunctorMaterials<<<{"href": "../../syntax/FunctorMaterials/index.html"}>>>]
  [profiles]
    type = TorchScript1DProfileFunctorMaterial<<<{"description": "Evaluates a TorchScript model that returns sampled one-dimensional profiles and exposes those profiles as interpolated Real functors.", "href": "TorchScript1DProfileFunctorMaterial.html"}>>>
    torch_script_userobject<<<{"description": "TorchScriptUserObject containing the deployed TorchScript model."}>>> = profile_network

    input_values<<<{"description": "Ordered constant values passed directly to the model. Specify either input_names or input_values, but not both."}>>> = '10 5'

    profile_names<<<{"description": "Names assigned to model output channels. The number of names must equal the model output channel count. A functor is any of the following: a variable, a functor material property, a function, a postprocessor or a number."}>>> = 'profile_a profile_b'
    profile_coordinates<<<{"description": "Strictly increasing coordinates corresponding to the model output stations."}>>> = '0 1 2'

    profile_origin<<<{"description": "Physical point corresponding to profile coordinate zero."}>>> = '2 0 0'
    profile_direction<<<{"description": "Physical direction of increasing profile coordinate. The direction is normalized internally."}>>> = '2 0 0'

    coordinate_scale<<<{"description": "Physical distance corresponding to one model-coordinate unit."}>>> = 2
    out_of_range_behavior<<<{"description": "Behavior when a MOOSE evaluation point lies outside the supplied profile coordinate range."}>>> = error
  []
[]
(modules/navier_stokes/test/tests/functormaterials/torchscript_profile_functor_material/profile.i)

With profile_origin = '2 0 0', profile_direction = '2 0 0', and coordinate_scale = 2, a point at has profile coordinate . Linear interpolation therefore gives profile_a = 11 and profile_b = 4.5 at that point.

Usage notes

  • The order of profile_names defines the correspondence between tensor rows and generated functors.

  • The same units must be used for profile_coordinates and the mapped coordinate .

  • Use load_during_construction = true on the TorchScriptUserObject so that the module is available when this material performs initial setup.

  • The saved TorchScript model should be generated with a PyTorch version compatible with the LibTorch version linked into MOOSE.

Input Parameters

  • profile_coordinatesStrictly increasing coordinates corresponding to the model output stations.

    C++ Type:std::vector<Real>

    Unit:(no unit assumed)

    Controllable:No

    Description:Strictly increasing coordinates corresponding to the model output stations.

  • profile_directionPhysical direction of increasing profile coordinate. The direction is normalized internally.

    C++ Type:libMesh::VectorValue<Real>

    Unit:(no unit assumed)

    Controllable:No

    Description:Physical direction of increasing profile coordinate. The direction is normalized internally.

  • profile_namesNames assigned to model output channels. The number of names must equal the model output channel count. A functor is any of the following: a variable, a functor material property, a function, a postprocessor or a number.

    C++ Type:std::vector<MooseFunctorName>

    Unit:(no unit assumed)

    Controllable:No

    Description:Names assigned to model output channels. The number of names must equal the model output channel count. A functor is any of the following: a variable, a functor material property, a function, a postprocessor or a number.

  • profile_originPhysical point corresponding to profile coordinate zero.

    C++ Type:libMesh::Point

    Controllable:No

    Description:Physical point corresponding to profile coordinate zero.

  • torch_script_userobjectTorchScriptUserObject containing the deployed TorchScript model.

    C++ Type:UserObjectName

    Controllable:No

    Description:TorchScriptUserObject containing the deployed TorchScript model.

Required Parameters

  • blockThe list of blocks (ids or names) that this object will be applied

    C++ Type:std::vector<SubdomainName>

    Controllable:No

    Description:The list of blocks (ids or names) that this object will be applied

  • coordinate_scale1Physical distance corresponding to one model-coordinate unit.

    Default:1

    C++ Type:Real

    Unit:(no unit assumed)

    Controllable:No

    Description:Physical distance corresponding to one model-coordinate unit.

  • declare_suffixAn optional suffix parameter that can be appended to any declared properties. The suffix will be prepended with a '_' character.

    C++ Type:MaterialPropertyName

    Unit:(no unit assumed)

    Controllable:No

    Description:An optional suffix parameter that can be appended to any declared properties. The suffix will be prepended with a '_' character.

  • execute_onINITIALWhen the TorchScript model is (re-)evaluated to rebuild the profiles. The list of flag(s) indicating when this object should be executed. For a description of each flag, see https://mooseframework.inl.gov/source/interfaces/SetupInterface.html.

    Default:INITIAL

    C++ Type:ExecFlagEnum

    Options:INITIAL, TIMESTEP_BEGIN

    Controllable:No

    Description:When the TorchScript model is (re-)evaluated to rebuild the profiles. The list of flag(s) indicating when this object should be executed. For a description of each flag, see https://mooseframework.inl.gov/source/interfaces/SetupInterface.html.

  • input_namesOrdered postprocessor values passed to the model. Specify either input_names or input_values, but not both.

    C++ Type:std::vector<PostprocessorName>

    Unit:(no unit assumed)

    Controllable:No

    Description:Ordered postprocessor values passed to the model. Specify either input_names or input_values, but not both.

  • input_valuesOrdered constant values passed directly to the model. Specify either input_names or input_values, but not both.

    C++ Type:std::vector<Real>

    Unit:(no unit assumed)

    Controllable:No

    Description:Ordered constant values passed directly to the model. Specify either input_names or input_values, but not both.

  • out_of_range_behaviorerrorBehavior when a MOOSE evaluation point lies outside the supplied profile coordinate range.

    Default:error

    C++ Type:MooseEnum

    Options:error, clamp, extrapolate

    Controllable:No

    Description:Behavior when a MOOSE evaluation point lies outside the supplied profile coordinate range.

  • tensor_dtypefloat32Floating-point type expected by the TorchScript model.

    Default:float32

    C++ Type:MooseEnum

    Options:float32, float64

    Controllable:No

    Description:Floating-point type expected by the TorchScript model.

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

  • enableTrueSet the enabled status of the MooseObject.

    Default:True

    C++ Type:bool

    Controllable:Yes

    Description:Set the enabled status of the MooseObject.

  • implicitTrueDetermines whether this object is calculated using an implicit or explicit form

    Default:True

    C++ Type:bool

    Controllable:No

    Description:Determines whether this object is calculated using an implicit or explicit form

  • search_methodnearest_node_connected_sidesChoice of search algorithm. All options begin by finding the nearest node in the primary boundary to a query point in the secondary boundary. In the default nearest_node_connected_sides algorithm, primary boundary elements are searched iff that nearest node is one of their nodes. This is fast to determine via a pregenerated node-to-elem map and is robust on conforming meshes. In the optional all_proximate_sides algorithm, primary boundary elements are searched iff they touch that nearest node, even if they are not topologically connected to it. This is more CPU-intensive but is necessary for robustness on any boundary surfaces which has disconnections (such as Flex IGA meshes) or non-conformity (such as hanging nodes in adaptively h-refined meshes).

    Default:nearest_node_connected_sides

    C++ Type:MooseEnum

    Options:nearest_node_connected_sides, all_proximate_sides

    Controllable:No

    Description:Choice of search algorithm. All options begin by finding the nearest node in the primary boundary to a query point in the secondary boundary. In the default nearest_node_connected_sides algorithm, primary boundary elements are searched iff that nearest node is one of their nodes. This is fast to determine via a pregenerated node-to-elem map and is robust on conforming meshes. In the optional all_proximate_sides algorithm, primary boundary elements are searched iff they touch that nearest node, even if they are not topologically connected to it. This is more CPU-intensive but is necessary for robustness on any boundary surfaces which has disconnections (such as Flex IGA meshes) or non-conformity (such as hanging nodes in adaptively h-refined meshes).

  • seed0The seed for the master random number generator

    Default:0

    C++ Type:unsigned int

    Controllable:No

    Description:The seed for the master random number generator

Advanced Parameters

  • output_propertiesList of material properties, from this material, to output (outputs must also be defined to an output type)

    C++ Type:std::vector<std::string>

    Controllable:No

    Description:List of material properties, from this material, to output (outputs must also be defined to an output type)

  • outputsnone Vector of output names where you would like to restrict the output of variables(s) associated with this object

    Default:none

    C++ Type:std::vector<OutputName>

    Controllable:No

    Description:Vector of output names where you would like to restrict the output of variables(s) associated with this object

Outputs Parameters

Input Files

warningwarning

The detailed documentation of this object is only available when Moose is compiled with Libtorch. For instructions on how to compile Moose with Libtorch, visit the general installation webpage or click here.