Manuscript Offprint
arXiv:2610.24301Torch-DPhys: A Torch-Native, MOOSE-Compatible Framework for Differentiable Physics Simulation and Hybrid Machine Learning Integration
Abstract
Gradient-based parameter inference, optimal control, and solver-in-the-loop hybrid physics–machine learning (ML) require derivatives of simulation objectives with respect to model parameters, boundary conditions, or embedded neural network weights. While existing nuclear engineering codes provide mature multiphysics forward solvers, coupling them to modern automatic differentiation (AD) and machine learning ecosystems typically requires external cross-language wrappers or code-intrusive adjoint implementations. We present Torch-DPhys, a PyTorch/LibTorch-native framework for differentiable physics simulation and hybrid physics–ML integration that implements selected modeling concepts and discretizations from the Multiphysics Object-Oriented Simulation Environment (MOOSE) Thermal Hydraulics Module (THM), the System Analysis Module (SAM), and finite-element continuum mechanics. Torch-DPhys expresses finite-element and finite-volume residuals as native tensor operations, supporting execution on central processing units (CPUs) and graphics processing units (GPUs), kernel compilation via torch.compile, and sparse direct linear solvers through SuperLU and NVIDIA's cuDSS library for direct sparse solvers. Simulation sensitivities are computed via two complementary routes: reverse-mode differentiation unrolled through executed solver iterations, and discrete residual adjoints evaluated at converged implicit states. Forward numerical verification against analytical solutions, MOOSE, and SAM-Lite demonstrates close discrete agreement across plane-strain elasticity, one-dimensional single- and two-loop thermal-hydraulic transients, and two-dimensional axisymmetric molten-salt fast reactor (MSFR) flow and heat transport, where Torch-DPhys matches SAM-Lite within a maximum normalized field discrepancy of over 200 adaptive time steps. Transient trajectory gradients are verified against tangent-linear recurrences and central finite differences. We demonstrate the framework on two gradient-driven applications: recovering pump head and heating power in a thermal-hydraulic loop within 0.06% relative error from synthetic MOOSE observations, and training a recurrent neural controller via differentiable predictive control (DPC) by backpropagating closed-loop trajectory objectives through a three-loop plant solver. Torch-DPhys connects MOOSE- and SAM-compatible physical modeling with PyTorch/LibTorch's native differentiation ecosystem, enabling gradient-based inverse modeling, optimal control, and solver-in-the-loop hybrid physics–machine learning for nuclear engineering systems.
Keywords: Differentiable simulation, inverse problems, hybrid physics–machine learning, thermal hydraulics, structural mechanics, PyTorch.
1 Introduction
Numerical simulation in nuclear science and engineering is traditionally formulated as a forward problem: given a system geometry, material properties, boundary conditions, and empirical closure relations, a solver integrates the governing conservation equations to predict thermal-hydraulic or thermomechanical states. In many engineering workflows, however, forward prediction is embedded within an outer optimization or inference loop. Modelers frequently need to infer uncertain boundary or constitutive parameters from sparse sensor measurements, optimize component geometries or operating schedules, or synthesize feedback controllers that satisfy safety constraints during transients. Addressing these tasks via partial differential equation (PDE)-constrained optimization requires sensitivities that relate trajectory-level objectives to the underlying physical parameters or control actions. Because finite-difference approximations and derivative-free search methods scale poorly as the parameter dimension grows, access to accurate simulation gradients via adjoint methods or automatic differentiation (AD) is essential.
The demand for solver gradients has grown as data assimilation and hybrid physics–machine learning (ML) have become central to nuclear system modeling and digital twin development [1–4]. Early hybrid workflows coupled ML with mechanistic solvers offline: neural networks were trained on pre-generated high-fidelity simulation databases to predict turbulent eddy viscosity or closure terms and were subsequently linked into system codes for forward deployment [1, 5]. Similarly, control-oriented studies have often trained control policies by backpropagating through learned surrogate models, such as neural ordinary differential equations (ODEs), rather than the physical plant solver itself [3, 4]. While computationally convenient, decoupling training from the numerical solver introduces distribution shift and surrogate approximation error; a closure or controller that performs well offline can degrade in accuracy or stability when deployed in closed loop with the discretized governing equations. Propagating gradients directly through the time-stepping physics solver—known as solver-in-the-loop training [6, 7]—allows neural closures and control policies to be optimized against multi-step trajectory objectives while accounting for the numerical discretization and physical coupling of the solver.
Within the nuclear engineering community, the Multiphysics Object-Oriented Simulation Environment (MOOSE) [8] and its domain applications, including the Thermal Hydraulics Module (THM) [9] and the System Analysis Module (SAM) [10–12], provide widely adopted infrastructure for reactor thermal-hydraulics and multiphysics analysis. MOOSE employs forward-mode AD to assemble local elemental and nodal residual Jacobians [13] and supports forward evaluation of trained neural networks via C++ LibTorch bindings [14]. However, because these production codes are architected in C++ around data structures distributed using the Message Passing Interface (MPI) and nonlinear solvers from the Portable, Extensible Toolkit for Scientific Computation (PETSc), they do not natively expose end-to-end reverse-mode differentiation of transient trajectory objectives directly within Python-based ML training loops.
In the broader scientific computing literature, two primary strategies have emerged to bridge numerical PDE solvers and differentiable programming. The first strategy wraps an established compiled solver with an external adjoint interface. For example, Diff-NekRS [15] retains NekRS for forward spectral-element fluid simulation, implements a manual discrete adjoint for the supported time-stepping scheme, and couples the resulting sensitivities to LibTorch for multi-step neural closure training. The second strategy implements the numerical discretizations natively within tensor-computing frameworks such as JAX, PyTorch, or TensorFlow. Representative examples include JAX-FEM [16] for differentiable finite-element mechanics and PhiFlow [17] for differentiable fluid simulation. Native tensor implementation places the physical residual evaluations, linear solvers, and neural network layers within a single execution and differentiation environment [18], avoiding cross-language serialization while supporting both unrolled computational-graph differentiation and implicit adjoint formulations.
In this work, we develop Torch-DPhys, a PyTorch-native framework for differentiable physics simulation and hybrid physics–ML integration tailored to nuclear thermal-hydraulic and continuum mechanics modeling. Rather than replacing full production codes, Torch-DPhys implements selected physical components and finite-element/finite-volume discretizations derived from MOOSE THM [9] and SAM [10, 11] alongside two-dimensional finite-element elasticity. Component topologies and mesh operators are lowered into structured tensor representations that execute on CPUs or NVIDIA GPUs, with support for kernel compilation via torch.compile and sparse direct linear algebra.
via SuperLU [19, 20] and NVIDIA cuDSS [21]. To accommodate different solver structures and memory budgets, Torch-DPhys provides two routes to trajectory gradients: (i) unrolled reverse-mode AD through executed nonlinear solver iterations, and (ii) discrete residual adjoints evaluated on the converged implicit equations at each time step.
The main contributions of this work are as follows:
• A PyTorch-native multiphysics modeling architecture. We formulate object-oriented physical models—spanning plane-strain linear elasticity, one-dimensional (1D) compressible channel and loop thermal hydraulics with conjugate heat structures and junctions, and two-dimensional (2D) axisymmetric stabilized finite-element flow and heat transport—as native PyTorch tensor operations that run in the same environment as ML optimization workflows.
• Dual differentiation routes with transient gradient verification. We implement both unrolled Newton-iteration differentiation (with step-wise checkpoint recomputation) and converged-residual discrete adjoints (including variable-step second-order backward differentiation (BDF2) history terms), and verify the resulting sensitivities against independent tangent-linear recurrences and central finite differences.
• Cross-code numerical verification against MOOSE and SAM-Lite. We verify forward simulations against archived MOOSE results across static elasticity and three 1D thermal-hydraulic loop configurations, and against SAM-Lite on a 200-step adaptive transient of an axisymmetric molten-salt fast reactor (MSFR), achieving a maximum normalized field discrepancy of while characterizing time-step stabilization sensitivities and mass-flux conservation properties.
• Evaluation of sparse compiled CPU and GPU execution. Using the 200-step MSFR transient workload, we benchmark eager and torch.compile-accelerated execution across CPU threads and GPU hardware (with graphs in NVIDIA's CUDA parallel computing platform and cuDSS sparse factorizations), analyzing component-level costs across residual evaluation, Jacobian assembly, sparse factorization, and adjoint dependency discovery.
• Demonstrations of inverse parameter estimation and solver-in-the-loop control. We apply Torch-DPhys to recover pump head and heating power in a thermal-hydraulic loop from sparse transient MOOSE observations (within 0.06% relative error), and to train a gated recurrent unit (GRU) control policy via differentiable predictive control (DPC) through a three-loop thermal-hydraulic plant model.
The remainder of this paper is organized as follows. Section 2 describes the Torch-DPhys software architecture and the two routes for computing simulation gradients. Section 3 summarizes the governing equations and discretizations for the structural mechanics, 1D channel thermal-hydraulics, and 2D axisymmetric MSFR models. Section 4 presents forward verification against MOOSE and SAM-Lite, transient sensitivity verification, and time-step refinement diagnostics. Section 5 analyzes CPU and GPU execution performance on the MSFR workload. Section 6 demonstrates PDE-constrained parameter identification, solver-in-the-loop DPC policy training, and extensions to uncertainty quantification. Section 7 discusses current limitations and concludes the paper.
2.1 Physical Models as Torch Computations
Torch-DPhys organizes materials, boundary conditions, and domain-specific physical components as Python objects while evaluating their local constitutive relations and global residual assembly through PyTorch tensor operations. Across the supported physics modules—two-dimensional finite-element mechanics, one-dimensional system thermal hydraulics, the reduced three-loop control plant, and two-dimensional axisymmetric finite-element flow and heat transport—this design separates high-level model specification from vectorized numerical execution.
For the structural mechanics module, mesh generation and finite-element basis preprocessing are performed offline using the MFEM modular finite-element library [22]. MFEM reads or generates the computational mesh, constructs first-order triangular finite-element spaces, and exports nodal coordinates, element connectivity, physical basis-function gradients, quadrature weights, and boundary node indices. Torch-DPhys loads these static arrays at initialization and executes stiffness operator evaluations and conjugate-gradient solves natively in PyTorch without runtime calls to MFEM.
For the one-dimensional thermal-hydraulic models, a lowering stage translates the object-oriented component network into contiguous tensor index tables representing channel connectivity, junction topology, heat-structure coupling, and physical parameters. This lowering step reformulates the component equations for batched tensor evaluation without altering the underlying physical conservation laws. Residual evaluations, automatic differentiation, and linear algebra execute on either CPU or NVIDIA CUDA devices, and computationally intensive residual and Jacobian kernels can be compiled using torch.compile. Figure 1 illustrates the overall execution and differentiation workflow.

Figure 1: Torch-DPhys workflow. Solid arrows show forward evaluation and parameter updates. Dashed arrows show the two differentiation routes: unrolled differentiation through executed solver operations and discrete adjoints of the converged residual equations.
2.2 Two Routes to Simulation Gradients
Torch-DPhys computes gradients of a scalar objective J with respect to model parameters via two distinct mathematical routes, which can be exposed either through PyTorch's native autograd engine or through an explicit sensitivity interface (as in the MSFR module):
-
Unrolled differentiation of executed operations. This route applies reverse-mode AD directly to the sequence of numerical operations executed during the forward solve, such as a fixed number of conjugate-gradient steps or damped Newton iterations. Because the computational graph traces the actual solver updates, the resulting derivative represents the exact sensitivity of the finite-iteration algorithm, including dependence on the initial guess, for the executed sequence of solver updates. However, retaining intermediate solver states across long transients increases memory consumption unless step-wise checkpointing and recomputation are used, and gradients from partially converged iterations need not match the sensitivity of the exact implicit root.
-
Discrete adjoint of the converged residual equations. Rather than differentiating through the nonlinear solver path, the residual-adjoint route applies the implicit function theorem to the converged discrete equations at each time step . Assuming a differentiable residual and a nonsingular state Jacobian , the discrete adjoint satisfies the linear system
where combines the direct objective derivative with history contributions propagated backward from step (and for two-step schemes). Explicit dependence of on is added separately. The residual adjoint requires solving only one transposed linear system per accepted time step and avoids storing intermediate Newton iterates, though its accuracy depends on how tightly both the forward residual and adjoint linear system are converged.
Section 6.1 compares both routes directly on a transient thermal-hydraulic inverse problem, while Section 6.2 uses adjoint-based trajectory sensitivities to train a closed-loop neural control policy. Detailed mathematical formulations of both differentiation targets are provided in Appendix A.
3 Representative Physical Models
To demonstrate the framework across distinct spatial discretizations and physics regimes, we implement three representative model families in PyTorch: two-dimensional finite-element linear elasticity, one-dimensional finite-volume system thermal hydraulics, and two-dimensional axisymmetric stabilized finite-element flow and heat transport.
3.1 Structural Mechanics
The structural mechanics module solves two-dimensional isotropic, small-strain linear elasticity under plane-strain conditions:
where u is the displacement vector, b is the body force per unit volume, is the infinitesimal strain tensor, is the Cauchy stress tensor, and and are the Lamé parameters. Using precomputed MFEM basis gradients on linear triangular elements, tensor operators gather nodal displacements, evaluate element strains and stresses at quadrature points, and scatter-add internal nodal forces. This matrix-free operator evaluation computes the action of the global stiffness matrix directly within a preconditioned conjugate-gradient solver while symmetric boundary projections enforce Dirichlet constraints.
3.2 THM-Derived Channel Thermal Hydraulics
The one-dimensional thermal-hydraulic module implements single-phase compressible flow and conjugate heat transfer following the formulation of the MOOSE Thermal Hydraulics Module [9]. Within a flow channel of cross-sectional area A, conservation of mass, axial momentum, and total energy is governed by
where , , and denote fluid density, axial velocity, and static pressure, is the specific total energy, and collects body-force, wall-friction, and wall heat-transfer source terms. Thermodynamic properties are closed via fluid equations of state. Inter-cell numerical fluxes are evaluated using the Harten–Lax–van Leer–contact (HLLC) approximate Riemann solver [23] with linear interface reconstruction.
Flow channels are coupled into system networks through volume junctions, parallel-channel junctions, and pump components. Conjugate heat structures solve radial or transverse solid heat conduction and exchange thermal power with adjacent fluid cells via the convective flux relation , where is the convective heat-transfer coefficient, is the heated perimeter, and and are the solid surface and bulk fluid temperatures. Assembling the fluid, junction, solid conduction, and controller states into a global state vector yields the semi-discrete system , which is integrated in time using the implicit backward Euler scheme:
Equation (4) defines both the forward Newton residual and the implicit state constraint differentiated in Eq. (1).
3.3 SAM-Derived Axisymmetric Flow and Heat Transport
To evaluate Torch-DPhys on multidimensional finite-element fluid and thermal transport, we implement the two-dimensional axisymmetric porous-medium incompressible Navier–Stokes and energy equations from SAM [10, 12]. We apply this model to the Molten Salt Fast Reactor (MSFR) configuration studied within the EURATOM EVOL project [24, 25], following the axisymmetric SAM setup introduced by Liu et al. [5]. In the present verification study, we model an open-cavity core with unit porosity, zero porous resistance, and a standard Prandtl mixing-length algebraic turbulence closure during a heated startup transient with a fixed inlet velocity profile.

Figure 2: Coarse mesh of the axisymmetric MSFR computational domain, with enlarged detail. The axial direction is vertical and the symmetry axis is on the left.
Figure 2 shows the axisymmetric computational domain and coarse mesh.
The axisymmetric domain is discretized into 1,296 curved nine-node isoparametric quadrilateral elements ('QUAD9'), with bilinear ('Q1') solution spaces defined on the 1,399 corner vertices for axial velocity , radial velocity , pressure , and temperature (5,596 total degrees of freedom). Time integration uses a backward-Euler startup step followed by variable-step second-order backward differentiation (BDF2). Table 1 summarizes the thermophysical properties, mixing-length profile, and boundary conditions.
Table 1: Physical settings of the MSFR initialization benchmark. Coordinates and denote the axial and radial directions.
| Quantity | Configuration |
|---|---|
| Fluid properties | Constant , , and . Molecular conductivity varies linearly from 0.9952 at 800 K to 1.0288 W/(m K) at 1200 K. |
| Mixing length | 0.07 m for m, decreasing linearly to 0.018 m at m, and 0.018 m beyond. Turbulent Prandtl number . |
| Inlet | Recorded normalized Nek5000 velocity profile, multiplied by -1.25 m/s and the coarse-boundary flux correction 1.02705297222. Radial velocity is zero and temperature is 900 K. |
| Outlet, walls and axis | Outlet pressure 161 kPa. Walls are no-slip and adiabatic. The symmetry axis has zero radial velocity and zero normal gradients of axial velocity and temperature. |
| Initial fields | Both velocity components , pressure 110 kPa and temperature 900 K, subject to the prescribed boundary values. |
| Body force and heating | Gravity is +9.81 m/s in the mesh axial direction. The fixed volumetric heat source is given by Eq. (5). |
The volumetric fission heat source is sampled at the finite-element nodes and interpolated across quadrature points using the clipped cosine profile
where , , , , and .
Because equal-order bilinear interpolation is used for velocity and pressure in a convection-dominated regime, the weak form incorporates Pressure-Stabilizing/Petrov–Galerkin (PSPG) stabilization in the continuity equation and Streamline-Upwind/Petrov–Galerkin (SUPG) stabilization in the momentum and energy equations [10]. For an element e with minimum characteristic length and quadrature-averaged velocity , the stabilization parameters are defined as
where and are evaluated at quadrature points from the eddy viscosity and molecular conductivity , while the diffusive energy flux uses the element-averaged total conductivity . Because enters directly in Eq. (6), changing the time step modifies the spatial stabilization weights , , and even as the flow approaches steady state; we analyze the consequences of this coupling in Section 4.6.
4 Numerical Verification
We verify the forward discretizations and sensitivity calculations in Torch-DPhys against analytical solutions, archived MOOSE simulations, and SAM-Lite reference runs, followed by tangent-linear and finite-difference gradient checks. Note that agreement between Torch-DPhys and a reference code under matched meshes and time steps verifies the equivalence of the discrete implementations, whereas spatial and temporal continuum convergence must be assessed separately (Section 4.6).
4.1 Structural Mechanics Verification
We first verify the plane-strain elasticity module on two static benchmark problems using linear triangular elements with Young's modulus and Poisson's ratio (in consistent dimensionless units): an 81-node unit-square patch test with prescribed affine boundary displacements, and an 85-node cantilever beam clamped at its left boundary and subjected to a uniform downward body force .
On the patch test, Torch-DPhys recovers the exact analytical linear displacement field and matches the archived MOOSE solution with a maximum componentwise relative discrepancy of . On the cantilever beam (Figure 3), the deformed mesh and upper-boundary vertical displacement profile match MOOSE with a maximum relative discrepancy of .

(a)
(b)
Figure 3: Plane-strain cantilever verification. (a) Deformed mesh colored by displacement magnitude (unmagnified). (b) Upper-boundary vertical displacement profile compared against archived MOOSE results.
4.2 Thermal Hydraulics: Heated Inlet-Driven Circuit
Figure 4 illustrates the three MOOSE THM test configurations used to verify the one-dimensional thermal-hydraulic module: (a) an open inlet-driven helium heating and cooling chain (03_upper_loop.i), (b) a closed recirculating primary loop driven by a constant-head pump (04_loop.i variant), and (c) a coupled primary–secondary heat-exchanger system with proportional-integral-derivative (PID) pump control (05_secondary_side.i).

Figure 4: Schematics of the one-dimensional thermal-hydraulic verification cases: (a) Case 03 open helium chain, (b) Case 04 closed loop with constant pump head, and (c) Case 05 coupled primary–secondary system with PID control. Arrows indicate nominal flow direction and dots mark output sensor locations.
Case 03_upper_loop.i (Figure 4a) tests conjugate fluid–solid heat transfer and parallel-channel junction coupling (JunctionParallelChannels1Phase) across seven connected helium flow channels with gravity disabled. Helium enters at 0.01 kg/s and 300 K against a 1 MPa outlet pressure, passes through a cylindrical core structure heated at 2000 W, and exits through a downstream cooler with walls maintained at 300 K. Starting from an initial velocity of m/s, Torch-DPhys advances the transient using backward Euler and a dense Newton solver with backtracking line search across the nine archived MOOSE time steps up to 500 s (as well as an eight-step reduced heated-section variant up to 250 s), converging on every interval without time-step cutbacks.
Figures 5 and 6 compare the Torch-DPhys and MOOSE trajectories and plot their signed differences across all nine positive time steps ( s). Across the full circuit, the maximum absolute discrepancies between Torch-DPhys and MOOSE are 0.0153 K in core outlet temperature, 0.0958 K in cooler outlet temperature, 0.791 W in solid-to-coolant heat transfer rate, and 0.278 Pa and 0.264 Pa in core inlet and outlet pressures (relative to the 1 MPa baseline). On the reduced eight-step heated-section problem, the corresponding maximum differences are 0.0135 K, 0.699 W, 0.180 Pa, and 0.173 Pa.
4.3 Thermal Hydraulics: Primary and Coupled Two-Loop Systems
Figure 7 compares Torch-DPhys against MOOSE on the closed primary loop (04_loop.i variant, panels a–b) and the PID-controlled coupled primary–secondary loop (05_secondary_side.i, panels c–d).
In the 04_loop.i configuration (Figure 4b), a constant-head pump circulates fluid through a heated core and pipe network connected by volume junctions, with gravity and feedback control disabled. Both codes step through the same 122 prescribed non-uniform time steps over 500 s. Despite minor discretization differences—Torch-DPhys uses unlimited monotonic upstream-centered scheme for conservation laws (MUSCL) interface reconstruction whereas the MOOSE reference uses a minmod limiter, along with minor differences in radial solid meshing and junction momentum initialization—the trajectories agree closely across the transient, with maximum absolute differences

(a)
(b)

(c)

(d)
Figure 5: Comparison between Torch-DPhys and MOOSE for the 03_upper_loop.i configuration: (a) core outlet fluid temperature, (b) heat transfer rate from the solid core to the coolant, (c) cooler outlet temperature, and (d) core inlet and outlet pressures relative to 1 MPa.

(a)
(b)

(c)

(d)
Figure 6: Signed differences (Torch-DPhys minus MOOSE) corresponding to the four observables in Figure 5.
of kg/s in core outlet mass flow rate (Figure 7a) and 0.041 K in core outlet fluid temperature (Figure 7b).
In the 05_secondary_side.i configuration (Figure 4c), the primary loop transfers heat through a counterflow heat exchanger (HX) to a once-through secondary channel while a PID controller regulates the primary pump head to maintain a target primary mass flow rate of 0.01 kg/s. Over the 12 prescribed time steps up to 50 s, the maximum differences between Torch-DPhys and MOOSE at the primary and secondary HX outlets are 0.00687 K and K, respectively (Figure 7c), and remain below 0.017 K across all four monitored temperature locations. The primary mass flow rate (Figure 7d) captures the initial overshoot and settling toward the 0.01 kg/s setpoint with a maximum discrepancy of kg/s (0.133% of the peak flow rate, reflecting the comparison between a channel-cell flow estimate in Torch-DPhys and a junction-flux postprocessor in MOOSE), while the core pressure drop agrees within 0.00144 Pa.

(a)
(b)

(c)
(d)
Figure 7: Comparisons between Torch-DPhys and MOOSE for the closed primary loop (04_loop.i with constant pump head): (a) core outlet mass flow and (b) core outlet temperature; and for the coupled two-loop system (05_secondary_side.i): (c) primary and secondary heat-exchanger outlet temperatures and (d) PID-controlled primary-loop mass flow rate.
4.4 MSFR Forward Verification Against SAM-Lite
We verify the two-dimensional axisymmetric MSFR implementation against SAM-Lite at both the residual evaluation level and across full transient trajectories. At eight archived reference states, the assembled Torch-DPhys residual vector matches SAM-Lite bit-for-bit at every degree of freedom except at four inlet boundary nodes in four states, where floating-point multiplication order in the inlet velocity expression introduces a one-unit-in-the-last-place (1 ULP) difference. Component-level finite-difference checks of the automatic state Jacobian, BDF2 history derivatives, and parameter Jacobians are documented in Appendix B.
For transient forward verification under the baseline input deck tolerances ( relative and absolute scaled residual norms), Torch-DPhys forms the exact residual Jacobian via AD and solves each Newton step using a direct lower–upper (LU) factorization with cubic backtracking, whereas SAM-Lite uses preconditioned Jacobian-free Newton–Krylov (PJFNK). Starting from the same initial state, both solvers independently select identical 200-step adaptive time grids reaching s without step rejections, typically requiring 1–3 nonlinear iterations per step.
Figure 8 and Table 2 summarize the field-level agreement over the 200-step transient. To compare all four solution fields on a common dimensionless scale in Figure 8(d), we define the step-wise normalized discrepancy for field at step as
where indexes the mesh vertices. Across all 200 steps, the maximum normalized discrepancy is (corresponding to maximum physical differences of K in temperature at step 31 and Pa in pressure at step 4), and drops below from step 60 onward. At the final state ( s), the nodal temperature fields agree to within K, with 1,016 of 1,399 vertices matching bit-for-bit. Across the eager and compiled CPU and GPU backends evaluated in Section 5.2, eager and compiled CPU states are bitwise identical at every step, and GPU trajectories differ from CPU by at most under Eq. (8).

(a)

(b)

(c)

(d)
Figure 8: MSFR forward verification over the 200-step adaptive transient. (a,b) Reference SAM-Lite temperature and velocity magnitude fields at s. (c) Nodal absolute temperature difference at s in units of K (gray indicates exact bitwise zero). (d) Evolution of the normalized field discrepancies defined in Eq. (8) over all 200 steps.
4.5 MSFR Transient-Gradient Verification
For a sequence of accepted implicit states satisfying the two-step BDF2 residual on a fixed time-step schedule, let . Given a scalar
Table 2: Maximum absolute nodal discrepancies between Torch-DPhys and SAM-Lite across all 1,399 vertices and steps 1–200 of the MSFR initialization transient.
| Field | Unit | Maximum absolute difference | Step |
|---|---|---|---|
| Temperature | K | ||
| Axial velocity | m/s | ||
| Radial velocity | m/s | ||
| Pressure | Pa |
trajectory objective and fixed initial conditions, the discrete residual adjoint backward recurrence is
where boundary terms with indices or vanish, and backward-Euler steps omit the second-history term. When a trajectory contains rejected time-step attempts, the BDF2 history metadata (dt_old) from the retry sequence are held fixed while the adjoint recurrence steps backward across the accepted states.
To verify that every state variable and time step contributes accurately to without masking errors behind sparse sensor locations, we define a dense verification functional over all accepted states:
where stacks the nodal velocity, pressure, and temperature fields at step , and is a fixed array of seeded standard-normal weights.
We verify the discrete adjoint (9) against an independently implemented forward tangent-linear sensitivity recurrence (Eq. (25) in Appendix B.6) and central finite differences. Figure 9 shows the relative directional discrepancy between the adjoint and forward-sensitivity directional derivatives across 39 parameter directions on five trajectory windows ranging from 1 to 40 accepted steps (including a 10-step window that replays a recorded step-9 rejection and retry). Across all 39 directions and five windows, the maximum relative discrepancy is .
Extending the gradient verification to the full 200-step transient on the compiled CPU trajectory, the discrete adjoint agrees with the tangent-linear recurrence to within across four tested directions (inlet temperature, inlet velocity scale, volumetric heat-source amplitude, and a random direction spanning all 34 registered parameter blocks). Across the four execution backends (eager and compiled CPU and GPU), the 200-step adjoint gradients agree within a maximum blockwise relative infinity-norm difference of . Furthermore, central finite-difference checks performed on a tightly converged 200-step trajectory (relative tolerance ) match the adjoint derivatives to within at a relative perturbation size of (see Appendix B.6 for conditioning and tolerance-polishing diagnostics).
4.6 Time-Step Sensitivity and Conservation Diagnostics
Although Torch-DPhys and SAM-Lite agree to within on the 200-step adaptive schedule, uniform time-step refinement of the production MSFR formulation reveals a notable sensitivity. Refining a constant integration step from s to s over s shifts the endpoint mean outlet temperature by K, maximum core temperature by K, and mean inlet pressure by kPa (5.8% of the total inlet–outlet pressure drop), while the global mass-flux imbalance between the integrated inlet and outlet velocity profiles increases from to (Table 7 in Appendix B.4).
This behavior stems from the explicit appearance of in the SUPG/PSPG stabilization coefficient in Eqs. (6)–(7): reducing decreases , and , which alters the

Figure 9: Relative discrepancy between the MSFR discrete residual adjoint and forward tangent-linear sensitivities across 39 parameter directions on trajectory windows of 1 to 40 accepted steps. Triangles in the lower band indicate exact bitwise zero discrepancy; “+ retry” denotes the 10-step window containing a rejected step attempt.
stabilized spatial weak form even at steady state. When inside the stabilization coefficients is held fixed at 0.25 s while the BDF2 time-integration step is refined from 0.25 s to 0.03125 s, the solutions converge monotonically toward a common endpoint state with an observed temporal order of 1.90–2.15 for temperature. This diagnostic confirms that the time-step shift and coarse-mesh mass-flux imbalance are inherent properties of the stabilized finite-element formulation shared by SAM-Lite and Torch-DPhys rather than discrepancies in the Torch implementation.
5 Execution and Computational Performance
We use the 200-step axisymmetric MSFR transient and its 200-step discrete adjoint to evaluate the computational performance of eager and compiled CPU and GPU execution in Torch-DPhys alongside serial and MPI-parallelized SAM-Lite.
5.1 Sparse Linear Algebra, Compilation, and GPU Execution
At each Newton iteration and adjoint step, the 5,596-degree-of-freedom MSFR problem requires solving a sparse linear system whose Jacobian contains 182,809 nonzeros (0.58% fill). To handle the wide dynamic range of the unscaled matrix entries (condition number ), Torch-DPhys applies row equilibration followed by sparse direct LU factorization and one step of iterative refinement (Appendix B.5). On the CPU, sparse factorizations use SciPy's SuperLU backend [19, 20] with column approximate minimum degree (COLAMD) ordering; on the GPU, factorizations use NVIDIA cuDSS [21] invoked through a custom C++ PyTorch operator. Topology-dependent sparsity maps are precomputed once and reused across all steps.
In compiled execution, torch.compile generates fused kernels for the finite-element residual, vector–Jacobian products (VJPs), and element-Jacobian assembly, while Python retains outer Newton and time-stepping control. On the GPU, compiled kernels are captured within CUDA graphs to reduce host launch overhead, and all state vectors, sparse matrix values, and adjoint history records remain resident in device memory throughout the transient. Moreover, an auxiliary-variable reuse pass evaluates intermediate constitutive and stabilization quantities once per accepted adjoint step rather than repeating them across dependency checks and Jacobian preparation, preserving bitwise-identical gradients while reducing adjoint overhead.
5.2 200-Step CPU/GPU Performance Benchmark
Table 3 summarizes the hardware and software environment for the 200-step MSFR performance benchmark. Across all Torch-DPhys configurations (eager and compiled, CPU and GPU), the adaptive solver executes the exact same 200 time steps, 266 Newton iterations, 467 residual evaluations, 280 Jacobian assemblies, and 266 sparse LU factorizations.
Table 3: Hardware and software configuration for the 200-step MSFR performance benchmark.
| Item | Setting |
|---|---|
| Workload | 200 adaptive forward steps to at baseline tolerances (266 Newton iterations), followed by a 200-step discrete residual adjoint. |
| Hardware and precision | Intel Core Ultra 7 265K CPU, NVIDIA RTX 2000 Ada GPU (16 GB), float64 arithmetic under Windows Subsystem for Linux 2 (WSL2). |
| Software stack | Python 3.12.3, PyTorch 2.13.0+cu129, Triton 3.7.1, CUDA 12.9, cuDSS 0.8.0.10, NumPy 2.1.2, SciPy 1.16.1, Intel oneAPI Math Kernel Library (MKL) 2024.2. |
| Thread and rank settings | Torch-DPhys: 4, 8, or 16 Torch/OpenMP/MKL threads (with MKL_CBWR=AUTO, STRICT and 1 OpenBLAS thread). SAM-Lite: 1 rank with 1 or 4 MOOSE threads, or 4, 8, and 16 MPI ranks with 1 thread per rank. |
| Measurement protocol | Medians and min-max ranges over three warm repetitions for Torch-DPhys; single runs for cold compilation and SAM-Lite. Forward timings measure Transient.execute() (Torch-DPhys) and cumulative PicardSolve (SAM-Lite). |
Figure 10(a) compares median wall-clock times for the 200-step forward transient and 200-step discrete adjoint using four CPU threads against GPU execution and four-rank MPI SAM-Lite. On the CPU, the compiled configuration reduces median forward runtime from 49.50 s to 29.30 s (1.69× speedup). Both eager and compiled GPU execution use CUDA. The optimized GPU configuration combines compiled numerical kernels with CUDA graph replay, reducing median forward runtime from 114.22 s to 22.65 s. This improvement reflects the combined execution optimizations. For the discrete adjoint, compilation combined with auxiliary-variable reuse reduces median runtime from 38.72 s to 24.05 s on the CPU and from 100.22 s to 33.09 s on the GPU. While GPU execution achieves the fastest warm forward time (22.65 s), four-thread CPU execution achieves the fastest warm adjoint time among the configurations in panel (a) (24.05 s). First-execution forward totals, including compilation and execution, are 847.1 s on the GPU and 1767.6 s on the CPU. Separate compiler-time measurements for the backward-Euler and BDF2 graph specializations appear in Appendix ??.
Compiled warm measurements pass background-load screening. Earlier eager medians include some load-flagged samples, whereas SAM-Lite timings are single observations with uncertain load accounting. Timing boundaries and sessions differ between codes, and GPU timings remain provisional under WSL2. Warm compiled adjoints use auxiliary reuse, while the earlier eager and cold compiled adjoints were measured without reuse.
Figure 10(b) shows forward wall-clock scaling across CPU worker counts (4, 8, and 16 threads for Torch-DPhys; 1, 4, 8, and 16 MPI ranks for SAM-Lite). SAM-Lite forward runtime decreases from 612.1 s (1 rank) to 223.5 s (4 ranks), 151.2 s (8 ranks), and 117.7 s (16 ranks). Torch-DPhys compiled CPU forward runtime reaches a minimum of 27.73 s at 8 threads (29.30 s at 4 threads and 35.22 s at 16 threads). Note that Torch-DPhys uses exact AD Jacobians with direct sparse LU solves (266 total linear solves), whereas SAM-Lite uses PJFNK with finite-difference matrix-vector products (46,659 residual evaluations in the 1-rank run), so the two curves reflect both algorithmic and parallel-implementation differences.
5.3 Component-Level Cost Breakdown
To explain the performance trends observed in Figure 10, Figure 11 allocates the per-step forward and adjoint execution times to constituent numerical operations. In panels (a,b), synchronized profiling shares are scaled to the corresponding uninstrumented timing medians. These are estimated allocations of measured totals, rather than separately measured uninstrumented component costs. Panel (c) reconstructs the post-reuse component breakdown by subtracting separately profiled costs

(a) Phase costs with four Torch CPU threads

(b) Forward execution versus configured worker count
Figure 10: Wall-clock execution costs on the 200-step MSFR benchmark. (a) Forward and discrete-adjoint runtimes across 4-thread CPU and GPU configurations in Torch-DPhys (showing warm medians, min–max ranges, and cold first-call totals) alongside 4-rank MPI SAM-Lite. (b) Forward runtime versus configured CPU threads (Torch-DPhys) or MPI ranks (SAM-Lite).
of removed auxiliary work while holding the remaining allocations fixed. Its diamond markers show independently measured totals from the later interleaved reuse comparison.
In the compiled CPU forward pass (Figure 11a), single-threaded SuperLU sparse factorization accounts for 72.3 ms per step (49% of total forward time), compared with only 3.8 ms per step for cuDSS factorization on the GPU (11.9 ms including triangular solves and checks). This serial factorization limits the work that can benefit from additional Torch threads, but the baseline profile does not establish the cause of the slowdown at 16 threads on this 1,399-node mesh.
Conversely, in the compiled GPU adjoint pass (Figure 11b,c), the compiled VJP kernel itself requires only 15.9 ms per step (down from 145.5 ms in eager GPU execution), and the transposed sparse solve requires 10.2 ms per step. However, the GPU adjoint is bottlenecked by an uncompiled primal residual evaluation used for dynamic auxiliary-variable dependency discovery. Reusing auxiliary evaluations across the adjoint step removes two of the three redundant evaluations, reducing the GPU adjoint time from 40.70 s (203.5 ms/step) to 33.09 s (165.4 ms/step, an 18.7% reduction), as shown in Figure 11(c). The separately profiled uncompiled primal residual used for dependency discovery costs approximately 91.5 ms per step, equivalent to about 57% of the reconstructed post-reuse allocation. Reducing this work while retaining the dependency checks is a target for further GPU adjoint acceleration.
6 Applications Enabled by Differentiability
6.1 Inferring Physical Parameters from Transient Observations
We first demonstrate PDE-constrained inverse parameter estimation on the closed primary thermal-hydraulic loop (04_loop.i variant verified in Figure 7a,b). The objective is to simultaneously recover the constant pump head H and core heating power Q from sparse transient measurements of core outlet mass flow rate and outlet fluid temperature recorded at observation times over the 500 s transient:
We minimize the scaled least-squares objective
where kg/s and K normalize the flow and temperature residuals to comparable magnitudes. Optimization is performed in dimensionless logarithmic coordinates using the limited-memory Broyden–Fletcher–Goldfarb–Shanno algorithm with bound constraints (L-BFGS-B) [26, 27] with box bounds (see Appendix A.5).
We compare both differentiation routes from Section 2.2: the discrete residual adjoint of the converged backward-Euler steps, and unrolled reverse-mode AD through Newton iterations per time step (using step-wise checkpoint recomputation to bound memory). Central finite differences at the initial guesses confirm that both routes match their respective forward evaluations to within relative error (Appendix A.4).
Table 4 and Figure 12 report parameter recovery from two initial guesses—Start A ( in , in ) and Start B ( in , in )—using synthetic observations generated by the same solver ( , ) as well as synthetic observations generated by MOOSE. On same-solver data, both the residual adjoint and unrolled AD converge in 7–8 L-BFGS-B updates along nearly indistinguishable optimization trajectories (differing by less than at matched iterations) and recover the exact generating parameters. When fitting the MOOSE-generated observations from Start A, the residual-adjoint optimization converges in 8 updates to ( error) and ( error), where the small residual bias reflects the minor forward discretization differences between Torch-DPhys and MOOSE noted in Section 4.
Although both differentiation routes yield identical parameter recovery on this well-converged problem, their computational costs differ substantially. Table 5 compares the wall-clock backward time and peak live CUDA memory allocation for a single 122-step trajectory evaluation at Start A

(a) Forward stepping

(b) Discrete adjoint, without auxiliary reuse

(c) Compiled GPU: estimated reuse effect; diamonds show measured totals
Figure 11: Per-step component runtime breakdown (in ms per accepted step) for (a) forward stepping and (b) the discrete adjoint prior to auxiliary reuse. (c) Compiled GPU adjoint breakdown before and after enabling auxiliary-variable reuse (hatched), with diamonds indicating the independently measured uninstrumented step totals.
Table 4: Parameter identification results for the closed thermal-hydraulic loop (, ).
| Observation source / Initial guess | Initial H (m) | Initial Q (W) | L-BFGS-B updates | Recovered (H, Q) (m, W) |
|---|---|---|---|---|
| Same solver / Start A | 0.06615 | 1300 | 8 | (0.094500, 2000.00) |
| Same solver / Start B | 0.12285 | 2700 | 7 | (0.094500, 2000.00) |
| MOOSE / Start A | 0.06615 | 1300 | 8 | (0.094516, 1998.87) |

(a)
(b)
— Pump head — Power — Residual adjoint -- Unrolled Newton ○ Start A □ Start B
Figure 12: Optimization trajectories for same-solver parameter recovery in the 04_loop. i thermal-hydraulic loop: (a) normalized parameter estimates and (b) objective value versus L-BFGS-B update. Solid and dashed curves denote the discrete residual adjoint and unrolled Newton differentiation, respectively.
(uncompiled float64 on an RTX 2000 Ada GPU; protocol in Appendix A.6). By solving a single transposed linear system per step rather than retracing and differentiating three Newton updates and Jacobian constructions per step, the residual adjoint reduces backward pass runtime by a factor of (26.9 s vs. 268 s) and peak memory allocation by (24.7 MiB vs. 201.0 MiB).
Table 5: Backward-pass runtime (median and [min, max] over three fresh processes) and peak live GPU memory allocation for a 122-step trajectory at Start A.
| Differentiation route | Backward time (s) | Peak allocation (MiB) |
|---|---|---|
| Converged-residual discrete adjoint | 26.9 [26.1, 27.0] | 24.7 |
| Unrolled Newton AD (with step recomputation) | 268 [263, 274] | 201.0 |
6.2 Solver-in-the-Loop Differentiable Predictive Control
Beyond calibrating scalar physical parameters, end-to-end differentiability enables solver-in-the-loop training of neural network components embedded in a dynamical system. We demonstrate this capability using differentiable predictive control (DPC) [28] to train a closed-loop neural feedback controller for the three-loop electrically heated thermal-fluid test facility whose computer-aided design (CAD) representation is shown in Figure 13. In previous work on this facility [3, 4], control-oriented forecasting and policy training relied on learned Graph Neural ODE surrogates, which can introduce surrogate prediction error when the trained policy is deployed on the mechanistic plant model. Here, we eliminate the intermediate dynamics surrogate by backpropagating closed-loop control objectives directly through a PyTorch reimplementation of the facility's SAM thermal-hydraulic plant model [10].
As illustrated in Figure 14(a), the neural policy is parameterized as a single-layer Gated Recurrent Unit (GRU) with 128 hidden units. At each 1 Hz control interval, the GRU receives 12 simulated plant sensor measurements along with conditioning inputs (upcoming power demand setpoint, secondary inlet temperature, and integrated tracking error) and outputs four actuator commands regulating the

2.0 m
Figure 13: CAD representation of the three-loop thermal-fluid facility modeled in the differentiable predictive control demonstration (HX: heat exchanger).
core heater power, primary and intermediate pump heads, and tertiary loop mass flow rate. The differentiable plant solver advances the coupled thermal-hydraulic state over five 0.2 s substeps per control interval across a 60 s horizon (300 plant steps total). A composite trajectory loss penalizing thermal power tracking error, outlet temperature deviation, actuator slew rate, and heater-rod temperature exceedance above a 97°C soft barrier (below the 100°C safety limit) is then differentiated backward through all 300 plant steps to update the GRU weights via gradient descent.
To balance the competing terms in the control objective, an outer Bayesian optimization loop (Figure 14b), initialized with 20 Sobol trials followed by 20 Gaussian-process-guided trials across four independent chains (160 trained policies total, following the ensemble tuning strategy of Abulawi et al. [2]), selects the loss weights and temporal discount factor. Because all plant rollouts and backpropagation occur offline during training, online deployment requires only a single forward pass of the 128-unit GRU at each 1 Hz control step.
Figure 15 shows the closed-loop responses of the four best-performing policies (one selected from each Bayesian optimization chain) across four representative power-demand profiles. Across the four trajectories, the policies achieve full-window mean absolute power-tracking errors between 99 W and 157 W while constraining the maximum heater-rod surface temperature to 94.5 °C, below both the 97 °C soft penalty barrier and the 100 °C limit.
6.3 Prospective Extensions to Uncertainty Quantification and Bayesian Calibration
Combining batched tensor execution with verified solver sensitivities also provides the mathematical building blocks for forward uncertainty propagation and Bayesian inverse calibration [29–32]. Let denote simulated quantities of interest as a function of uncertain model parameters and operating inputs . Alongside Monte Carlo ensemble propagation, the exact solver Jacobian with respect to the combined input vector provides a first-order local covariance approximation:

(a) Inner loop: solver-in-the-loop policy training via trajectory backpropagation

propose next objective hyperparameters
(b) Outer loop: Bayesian optimization of objective hyperparameters
Figure 14: Two-level hybrid physics–ML training architecture for differentiable predictive control: (a) inner loop backpropagating trajectory losses through the mechanistic plant solver to update GRU policy weights, and (b) outer Bayesian optimization loop tuning objective weights and temporal discount factors.

Figure 15: Closed-loop DPC tracking performance across four power-demand profiles. Top row: delivered versus demanded thermal power. Bottom row: peak heater-rod temperature relative to the 97°C soft penalty barrier and 100°C operating limit. Solid curves and shaded bands indicate the mean and ±1 standard deviation across the four selected policies.
as well as derivative-based global sensitivity measures [33].
Similarly, the deterministic point estimation in Section 6.1 can be extended to full Bayesian posterior inference under the statistical observation model [34, 35]
where is the observation operator, represents structural model discrepancy, and represents measurement noise. In this setting, the verified residual-adjoint gradients enable gradient-based Markov chain Monte Carlo (such as Hamiltonian Monte Carlo) or variational inference over high-dimensional closure parameters and embedded neural network weights.
7 Discussion and Conclusions
We have presented Torch-DPhys, a PyTorch/LibTorch-native framework that unifies selected finite-element and finite-volume physical models from MOOSE THM, SAM, and continuum mechanics with automatic differentiation and machine learning workflows. By lowering object-oriented component definitions and finite-element spaces into tensor operators, Torch-DPhys evaluates physical residuals, assembles sparse Jacobians, and propagates trajectory sensitivities within the same computational environment used to train neural networks and run gradient-based optimizers. The framework supports both unrolled differentiation through executed solver steps and discrete adjoints of converged implicit residuals, allowing users to trade off implementation simplicity against backward-pass memory and compute cost.
Forward numerical verification confirms that the implemented tensor operators reproduce the discrete behavior of the reference codes on the tested configurations. In two-dimensional plane-strain elasticity, Torch-DPhys matches archived MOOSE nodal displacements to within relative difference. Across three one-dimensional THM channel and loop transients—incorporating HLLC convective fluxes, volume and parallel-channel junctions, conjugate heat structures, pumps, counterflow heat exchangers, and PID control—Torch-DPhys reproduces MOOSE temperature histories within 0.096 K and mass-flow histories within 0.14%. On the two-dimensional axisymmetric MSFR initialization transient, Torch-DPhys and SAM-Lite independently select identical 200-step adaptive schedules and agree to within a maximum normalized field difference of ( K in temperature and Pa in pressure). Transient sensitivity verification confirms that the BDF2 discrete adjoint matches tangent-linear sensitivities to across 39 parameter directions on 40-step windows and to across four directions over the full 200-step trajectory.
On the 200-step MSFR benchmark, combining sparse direct linear algebra (SuperLU on CPU and cuDSS on GPU) with torch.compile reduces median forward execution time from 49.50 s to 29.30 s on a four-thread CPU configuration and from 114.22 s to 22.65 s on an NVIDIA RTX 2000 Ada GPU. Reusing auxiliary-variable evaluations across the adjoint dependency checks lowers the compiled GPU adjoint runtime by 18.7% (to 33.09 s), compared with 24.05 s on the four-thread CPU. Component-level profiling indicates that CPU forward runtime is primarily bounded by single-threaded sparse LU factorization (49% of step cost), whereas GPU adjoint runtime is bounded by uncompiled host/device dependency discovery (approximately 57% of the reconstructed post-reuse allocation).
The two application studies illustrate how these verified gradients support inverse problems and hybrid physics–ML. In the 1D thermal-hydraulic loop, L-BFGS-B optimization driven by either unrolled AD or the discrete residual adjoint recovers nominal pump head and heating power from sparse transient observations, achieving relative errors below 0.06% when fitting synthetic MOOSE data while requiring less backward time and less peak memory with the residual adjoint than with checkpointed unrolled differentiation. In the three-loop facility demonstration, differentiating a 300-step closed-loop trajectory objective directly through the SAM-derived plant solver trains a GRU feedback policy that tracks multi-step power demands while maintaining peak heater rod temperatures below the C limit, avoiding the surrogate mismatch incurred when training controllers on standalone neural ODE emulators.
Several scope boundaries qualify the reported results and define directions for future work. First, while close agreement between Torch-DPhys and MOOSE or SAM-Lite verifies that the tensor implementations reproduce the reference discrete formulations at the tested tolerances, cross-code agreement does not by itself establish spatial or temporal continuum convergence. In the axisymmetric MSFR study, because the standard SUPG/PSPG stabilization coefficients , , and depend explicitly on , refining the time step alters the stationary discrete spatial operator, shifting the endpoint inlet pressure by 5.8% and retaining a 1.65–1.90% velocity-field mass-flux imbalance on the coarse mesh. Systematic spatial mesh refinement and time-step-independent stabilization formulations are therefore needed to establish continuum accuracy. In addition, the MSFR transient adjoint differentiates trajectories conditional on a fixed time-step schedule and recorded retry history; it does not differentiate through adaptive step-size selection or discrete branch switches, nor does it currently account for parameter dependence in the initial state.
From an architectural standpoint, the structural mechanics, one-dimensional THM, reduced SAM control plant, and two-dimensional axisymmetric MSFR modules currently operate with separate data structures and solver interfaces. Unifying these interfaces and exposing the MSFR discrete adjoint as an end-to-end PyTorch autograd function will extend solver-in-the-loop training from control policies to embedded neural turbulence closures—building on offline SAM-ML workflows [1, 5]—as well as coupled fluid–structure interaction and MOOSE MultiApp integration via LibTorch. Eliminating the remaining uncompiled dependency-probing overhead in the GPU adjoint and reusing symbolic sparse factorizations will further reduce turnaround times for multi-step gradient evaluations. Finally, because the parameter-identification and DPC demonstrations reported here use noiseless synthetic observations and simulated plant rollouts, future work will evaluate these workflows on noisy measurements from instrumented test facilities and incorporate the ensemble uncertainty propagation and Bayesian calibration methods outlined in Section 6.3.
Acknowledgments and Disclosure of Funding
This research is supported by the U.S. Department of Energy (DOE) Office of Nuclear Energy's Nuclear Energy University Program (NEUP) under Award Number DE-NE0009613.
References
[1] Yang Liu, Rui Hu, Ling Zou, and Daniel Nunez. SAM-ML: Integrating data-driven closure with nuclear system code SAM for improved modeling capability. Nuclear Engineering and Design, 400:112059, 2022. doi: 10.1016/j.nucengdes.2022.112059.
[2] Zaid Abulawi, Rui Hu, Prasanna Balaprakash, and Yang Liu. Bayesian optimized deep ensemble for uncertainty quantification of deep neural networks: a system safety case study on sodium fast reactor thermal stratification modeling. Reliability Engineering & System Safety, 264(Part A):111353, 2025. ISSN 0951-8320. doi: 10.1016/j.ress.2025.111353. URL https://www.sciencedirect.com/science/article/pii/S095183202500554X.
[3] Doyeong Lim, Akzhol Almukhametov, Christian Young, and Yang Liu. Autonomous control of thermal-fluid dynamics via digital twin-enabled neural ODE models for small-scale advanced reactors. Nuclear Science and Engineering, pages 1–20, 2026. doi: 10.1080/00295639.2026.2676925.
[4] Akzhol Almukhametov, Doyeong Lim, Rui Hu, and Yang Liu. Graph neural ODE digital twins for control-oriented reactor thermal-hydraulic forecasting under partial observability. IEEE Transactions on Nuclear Science, 2026. doi: 10.1109/TNS.2026.3732134.
[5] Yang Liu, Jun Fang, Gang Yang, Ling Zou, and Rui Hu. Development of data-driven eddy viscosity closure to support MSR thermal-fluid modeling based on SAM-ML. In Proceedings of the 14th International Topical Meeting on Nuclear Reactor Thermal-Hydraulics, Operation, and Safety (NUTHOS-14), pages 2090–2101, Vancouver, British Columbia, Canada, 2024. doi:10.13182/NUTHOS14-119. URL https://doi.org/10.13182/NUTHOS14-119. August 25–28, 2024.
[6] Patrick E. Farrell, David A. Ham, Simon W. Funke, and Marie E. Rognes. Automated derivation of the adjoint of high-level transient finite element programs. SIAM Journal on Scientific Computing, 35(4):C369–C393, 2013. doi: 10.1137/120873558.
[7] Xiantao Fan and Jian-Xun Wang. Differentiable hybrid neural modeling for fluid-structure interaction. Journal of Computational Physics, 496:112584, 2024. doi: 10.1016/j.jcp.2023.112584.
[8] Logan Harbour, Guillaume Giudicelli, Alexander D. Lindsay, Peter German, Joshua Hansel, Casey Icenhour, Mengnan Li, Jason M. Miller, Roy H. Stogner, Patrick Behne, Daniel Yankura, Zachary M. Prince, Corey DeChant, Daniel Schwen, Benjamin W. Spencer, Mauricio Tano, Namjae Choi, Yaqi Wang, Max Nezdyur, Yinbin Miao, Tianchen Hu, Shikhar Kumar, Christopher Matthews, Brandon Langley, Nuno Nobre, Alexander Blair, Chris MacMackin, Henrique Bergallo Rocha, Edward Palmer, Jesse Carter, Jörg Meier, Andrew E. Slaughter, David
Andrš, Robert W. Carlsen, Fande Kong, Derek R. Gaston, and Cody J. Permann. 4.0 MOOSE: Enabling massively parallel multiphysics simulation. SoftwareX, 31:102264, 2025. doi:10.1016/j.softx.2025.102264.
[9] Joshua Hansel, David Andrs, Lise Charlot, and Guillaume Giudicelli. The MOOSE thermal hydraulics module. Journal of Open Source Software, 9(94):6146, 2024. doi: 10.21105/joss.06146.
[10] Rui Hu, Ling Zou, Guojun Hu, Daniel Nunez, Travis Mui, and Tingzhou Fei. SAM theory manual. Technical Report ANL/NE-17/4 Rev. 1, Argonne National Laboratory, 2021.
[11] Rui Hu, Ling Zou, Daniel O'Grady, Travis Mui, Zhiee Jhia Ooi, Guojun Hu, Eric Cervi, Gang Yang, David Andrs, Alex Lindsay, Cody Permann, Robert Salko, Quan Zhou, Lambert Fick, Alexander Heald, and Haihua Zhao. SAM: A modern system code for advanced non-LWR safety analysis. Nuclear Technology, 211(9):1883–1902, 2025. doi: 10.1080/00295450.2024.2409601.
[12] Rui Hu, Travis Mui, Robert Salko, Tingzhou Fei, Daniel O'Grady, Ling Zou, Huihua Yang, and Wei Ji. Development of integrated system-level analysis capabilities in SAM for molten salt reactors. Nuclear Engineering and Design, 457:115082, 2026. ISSN 0029-5493. doi: 10.1016/j.nucengdes.2026.115082. URL https://www.sciencedirect.com/science/article/pii/S0029549326003341.
[13] Alexander Lindsay, Roy Stogner, Derek Gaston, Daniel Schwen, Christopher Matthews, Wen Jiang, Larry K. Aagesen, Robert Carlsen, Fande Kong, Andrew Slaughter, Cody Permann, and Richard Martineau. Automatic differentiation in MetaPhysicL and its applications in MOOSE. Nuclear Technology, 207(7):905–922, 2021. doi: 10.1080/00295450.2020.1838877.
[14] Péter German and Dewen Yushu. Enabling scientific machine learning in MOOSE using Libtorch. SoftwareX, 23:101489, 2023. doi: 10.1016/j.softx.2023.101489.
[15] Junoh Jung, Riccardo Balin, Bethany Lusch, and Emil Constantinescu. Diff-NekRS: A scalable differentiable framework for multi-timestep solver-in-the-loop training. arXiv preprint arXiv:2609.23208, 2026. doi: 10.48550/arXiv.2609.23208. URL https://arxiv.org/abs/2609.23208.
[16] Tianju Xue, Shuheng Liao, Zhengtao Gan, Chanwook Park, Xiaoyu Xie, Wing Kam Liu, and Jian Cao. JAX-FEM: A differentiable GPU-accelerated 3D finite element solver for automatic inverse design and mechanistic data science. Computer Physics Communications, 291:108802, 2023. doi: 10.1016/j.cpc.2023.108802.
[17] Philipp Holl and Nils Thuerey. : Differentiable simulations for PyTorch, TensorFlow and Jax. In Proceedings of the 41st International Conference on Machine Learning, volume 235 of Proceedings of Machine Learning Research, pages 18515–18546. PMLR, 2024. URL https://proceedings.mlr.press/v235/holl24a.html.
[18] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, Alban Desmaison, Andreas Kopf, Edward Yang, Zachary DeVito, Martin Raison, Alykhan Tejani, Sasank Chilamkurthy, Benoit Steiner, Lu Fang, Junjie Bai, and Soumith Chintala. PyTorch: An imperative style, high-performance deep learning library. In Advances in Neural Information Processing Systems, volume 32, 2019. URL https://papers.nips.cc/paper_files/paper/2019/hash/bdbca288fee7f92f2bfa9f7012727740-Abstract.html.
[19] James W. Demmel, Stanley C. Eisenstat, John R. Gilbert, Xiaoye S. Li, and Joseph W. H. Liu. A supernodal approach to sparse partial pivoting. SIAM Journal on Matrix Analysis and Applications, 20(3):720–755, 1999. doi: 10.1137/S0895479895291765.
[20] Xiaoye S. Li, James W. Demmel, John R. Gilbert, Laura Grigori, Meiyue Shao, and Ichitaro Yamazaki. SuperLU users' guide. Technical Report LBNL-44289, Lawrence Berkeley National Laboratory, 1999. URL https://portal.nersc.gov/project/sparse/superlu/superlu_ug.pdf. Revision of August 2011.
[21] NVIDIA Corporation. NVIDIA cuDSS: A High-Performance CUDA Library for Direct Sparse Solvers. NVIDIA Corporation, 2026. URL https://docs.nvidia.com/cuda/cudss/. Version 0.8.0 documentation. Accessed October 9, 2026.
[22] R. Anderson, J. Andrej, A. Barker, J. Bramwell, J.-S. Camier, J. Cerveny, V. Dobrev, Y. Dudouit, A. Fisher, Tz. Kolev, W. Pazner, M. Stowell, V. Tomov, I. Akkerman, J. Dahm, D. Medina, and S. Zampini. MFEM: A modular finite element methods library. Computers & Mathematics with Applications, 81:42–74, 2021. doi: 10.1016/j.camwa.2020.06.009.
[23] E. F. Toro, M. Spruce, and W. Speares. Restoration of the contact surface in the HLL-riemann solver. Shock Waves, 4:25–34, 1994. doi: 10.1007/BF01414629.
[24] H. Rouch, O. Geoffroy, P. Rubiolo, A. Laureau, M. Brovchenko, D. Heuer, and E. Merle-Lucotte. Preliminary thermal-hydraulic core design of the Molten Salt Fast Reactor (MSFR). Annals of Nuclear Energy, 64:449–456, 2014. doi: 10.1016/j.anucene.2013.09.012. URL https://doi.org/10.1016/j.anucene.2013.09.012.
[25] Mariya Brovchenko, Jan-Leen Kloosterman, Lelio Luzzi, Elsa Merle, Daniel Heuer, Axel Laureau, Olga Feynberg, Victor Ignatiev, Manuele Aufero, Antonio Cammi, Carlo Fiorina, Fabio Alcaro, Sandra Dulla, Piero Ravetto, Lodewijk Frima, Danny Lathouwers, and Bruno Merk. Neutronic benchmark of the molten salt fast reactor in the frame of the EVOL and MARS collaborative projects. EPJ Nuclear Sciences & Technologies, 5:2, 2019. doi: 10.1051/epjn/2018052. URL https://doi.org/10.1051/epjn/2018052.
[26] Richard H. Byrd, Peihuang Lu, Jorge Nocedal, and Ciyou Zhu. A limited memory algorithm for bound constrained optimization. SIAM Journal on Scientific Computing, 16(5):1190–1208, 1995. doi: 10.1137/0916069.
[27] SciPy developers. SciPy 1.16.1: minimize(method=L-BFGS-B). SciPy reference manual, 2025. URL https://docs.scipy.org/doc/scipy-1.16.1/reference/optimize.minimize-lbfgsbs.html. Accessed October 12, 2026.
[28] Ján Drgoña, Karol Kiš, Aaron Tuor, Draguna Vrabie, and Martin Klaučo. Differentiable predictive control: Deep learning alternative to explicit model predictive control for unknown nonlinear systems. Journal of Process Control, 116:80–92, 2022. doi: 10.1016/j.jprocont.2022.06.001.
[29] Ralph C. Smith. Uncertainty Quantification: Theory, Implementation, and Applications. Society for Industrial and Applied Mathematics, 2013. ISBN 9781611973211. doi: 10.1137/1.9781611973228.
[30] Andrea Saltelli, Marco Ratto, Terry Andres, Francesca Campolongo, Jessica Cariboni, Debora Gatelli, Michaela Saisana, and Stefano Tarantola. Global Sensitivity Analysis: The Primer. John Wiley & Sons, 2008. ISBN 9780470059975. doi: 10.1002/9780470725184.
[31] Christopher J. Roy and William L. Oberkampf. A comprehensive framework for verification, validation, and uncertainty quantification in scientific computing. Computer Methods in Applied Mechanics and Engineering, 200(25–28):2131–2144, 2011. doi: 10.1016/j.cma.2011.03.016.
[32] Timothy G. Trucano, Laura P. Swiler, Takeru Igusa, William L. Oberkampf, and Martin Pilch. Calibration, validation, and sensitivity analysis: What's what. Reliability Engineering & System Safety, 91(10–11):1331–1357, 2006. doi: 10.1016/j.ress.2005.11.031.
[33] I. M. Sobol' and S. Kucherenko. Derivative based global sensitivity measures and their link with global sensitivity indices. Mathematics and Computers in Simulation, 79(10):3009–3017, 2009. doi: 10.1016/j.matcom.2009.01.023.
[34] Marc C. Kennedy and Anthony O'Hagan. Bayesian calibration of computer models. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 63(3):425–464, 2001. doi:10.1111/1467-9868.00294.
[35] Jenny Brynjarsdóttir and Anthony O'Hagan. Learning about physical parameters: the importance of model discrepancy. Inverse Problems, 30(11):114007, 2014. doi: 10.1088/0266-5611/30/11/114007.
A Differentiation, Optimization, and Measurement Details
While PyTorch’s autograd engine provides a unified interface for propagating derivatives across computational stages, the mathematical meaning of the resulting gradient depends on whether differentiation is applied to the finite-step numerical solver or to the implicit discrete residual equations. Below we detail both formulations as implemented in Section 2.2 and evaluated in Section 6.1.
A.1 Differentiating a Finite Numerical Calculation
Let denote the numerical update operator that advances the state at time step using nonlinear solver iterations, including its state initialization, Jacobian evaluations, and linear system solves:
Applying reverse-mode AD to Eq. (15) propagates sensitivities through the exact sequence of arithmetic and linear-algebra operations executed during those updates. Because the initial guess at step is seeded from , parameter sensitivities propagate through both the initial guess and the Newton updates, which in turn requires second-derivative information when differentiating through the AD-constructed Jacobian. When is small and the step has not fully converged, gives the exact derivative of the -step map rather than the implicit sensitivity of the root .
In the parameter-identification study (Section 6.1), the unrolled route executes Newton updates per time step. To avoid retaining the full Newton-iteration graph across all 122 time steps simultaneously in GPU memory, the implementation checkpoints the accepted step states and recomputes the forward Newton updates locally within each step during the backward pass.
A.2 Differentiating the Implicit Discrete Equations
For the residual-adjoint route, write the full transient system across all prescribed time steps as , where stacks the converged states across the time grid. For a scalar objective , assuming local differentiability and an invertible block-lower-triangular trajectory Jacobian , implicit differentiation yields
Because is block lower-bidiagonal (for backward Euler) or block lower-tridiagonal (for BDF2) in time, is solved by backward substitution one time step at a time (Eq. (1) and Eq. (9)).
Evaluating Eq. (16) depends only on the converged trajectory Y and does not retrace the forward Newton path or line-search history. Consequently, only one transposed linear solve is required per accepted time step, and no second-order derivatives of the residual are needed. However, any nonzero forward residual norm or inexactness in solving the transposed linear system introduces an approximation error relative to the exact implicit derivative.
A.3 Scope of the Parameter-Recovery Comparison
In Section 6.1, both differentiation routes are evaluated on the same 122-step time grid, physical initial state, observation times, and box bounds. The synthetic same-solver observations are generated once from a nominal converged trajectory ( , ).
Gradient accuracy is verified in the dimensionless logarithmic coordinates used by the optimizer, , where . Each differentiation route is checked against central finite differences of its own corresponding forward evaluation ( Newton updates for the unrolled route, and tolerance-converged solves for the residual-adjoint route). Because Newton iterations reduce the step residuals nearly to machine precision on this 1D loop problem, the two routes produce nearly identical gradients and optimization paths in Figure 12.
A.4 Residual-Adjoint Gradient Checks Away from the Optimum
Table 6 summarizes the central finite-difference verification of the residual-adjoint gradients at Initial Guess A ( , ) for both the same-solver and MOOSE observation datasets. For each coordinate and step size , fresh forward trajectories are solved at , yielding central finite-difference (FD) derivatives compared via the relative error .
Table 6: Comparison of residual-adjoint logarithmic derivatives against central finite differences at Initial Guess A (, ) for perturbation step sizes .
| Observations | Parameter | Adjoint derivative | |||
|---|---|---|---|---|---|
| Same solver | Pump head | ||||
| Same solver | Heating power | ||||
| MOOSE | Pump head | ||||
| MOOSE | Heating power |
At , all four derivatives agree with central finite differences to within ; at , finite-precision cancellation in the objective differences begins to limit further reduction of the heating-power discrepancy. At Initial Guess B (, ), the residual-adjoint logarithmic gradient (0.03225393, 0.02902049) matches the finite-difference-verified unrolled AD gradient to within a relative discrepancy of .
A.5 Parameter-Identification Optimizer Settings
The L-BFGS-B optimizer [26] (SciPy 1.16.1 [27]) updates the log-parameters with a maximum of 30 iterations and up to 15 line-search trials per iteration. Optimization terminates when either the projected gradient norm or relative objective reduction satisfies
All optimization runs in Table 4 converged via the projected-gradient criterion , requiring 10 total objective/gradient evaluations for Start A (8 accepted updates) and 8 evaluations for Start B (7 accepted updates).
A.6 Protocol for Differentiation-Route Cost Measurements
The backward runtime and memory comparisons in Table 5 were measured over the 122-step trajectory at Initial Guess A in float64 precision on an NVIDIA RTX 2000 Ada GPU (driver 595.95, PyTorch 2.8.0+cu128) hosted by an Intel Core Ultra 7 265K CPU (pinned to logical CPU 0 with a single intra-op and inter-op thread, compilation disabled). Following a three-step warm-up, three fresh-process repetitions were executed in alternating order for each differentiation route.
Peak memory was recorded via PyTorch's CUDA memory allocator after resetting peak statistics immediately prior to the backward sweep, and therefore includes the retained 122-step forward trajectory tensors (24.7 MiB for the residual adjoint versus 201.0 MiB for unrolled AD with step-wise recomputation). Wall-clock backward timings were bracketed by torch.cuda.synchronize() calls excluding setup and trajectory file export.
B Additional Numerical Verification
This appendix provides detailed residual, nonlinear convergence, time-step refinement, sparse linear algebra, and transient-adjoint diagnostics supporting the MSFR verification in Sections 4.4–4.6.
B.1 Residual, Derivative, and Recorded-Field Checks
At eight archived SAM-Lite reference states, the assembled Torch-DPhys residual vector matches SAM-Lite bit-for-bit at 5,592 of 5,596 entries in four states and at all 5,596 entries in the remaining four states; the four-entry differences are 1 ULP discrepancies at the inlet Dirichlet nodes resulting from floating-point evaluation order in the inlet velocity profile.
Local automatic derivatives of the MSFR residual with respect to the current state , lagged states , and 34 registered parameter blocks were verified against central finite differences across 360 sampled active state-Jacobian entries, all constrained Dirichlet identity rows, and 1,080 scalar history-derivative entries (including across a rejected step retry).
In the 200-step transient comparison (Figure 8d), the normalized field difference plateau from step 186 to step 200 occurs because the initial residual at those near-steady steps already satisfies the stopping tolerance, so both SAM-Lite and Torch-DPhys accept steps 187–200 with zero Newton updates.
B.2 Nonlinear Solution and Time Stepping
Reference nonlinear configuration and matched-step convergence. In the reference SAM-Lite configuration, each implicit time step is solved via PETSc PJFNK using matrix-free finite-difference Jacobian-vector products, a hand-coded preconditioning matrix factored via complete LU decomposition with diagonal shifting, restarted generalized minimal residual (GMRES) iteration with restart length 100 (up to 200 linear iterations), and cubic backtracking line search. Torch-DPhys instead assembles the exact residual Jacobian via AD and applies a direct LU solve with the same cubic backtracking line search.
Figure 16 compares the nonlinear residual convergence histories of SAM-Lite (PJFNK) and Torch-DPhys (exact AD Newton) across six matched single-step problems initialized from archived SAM-Lite states under unit residual scaling. Across the six steps, SAM-Lite requires 13, 7, 6, 7, 11, and 8 nonlinear iterations to reach , whereas Torch-DPhys converges in 10, 5, 4, 4, 4, and 4 iterations.
SAM-Lite (PJFNK)
Torch-DPhys: Newton (AD Jacobian)
relative stop

(a) Step 1
(b) Step 2
(c) Step 3

(d) Step 4
(e) Step 5
(f) Step 6
Figure 16: Nonlinear residual convergence histories on six matched single-step MSFR problems comparing SAM-Lite PJFNK against Torch-DPhys Newton with exact AD Jacobians and direct LU solves: (a) backward-Euler startup step and (b–f) BDF2 continuation steps.
Preconditioner Jacobian and single-correction diagnostics. Comparing SAM-Lite's hand-coded preconditioning matrix against a finite-difference Jacobian at s reveals a relative Frobenius-norm difference of approximately (arising from omitted derivative contributions in the hand-coded stabilization/turbulence terms). While effective as a PJFNK preconditioner, using the hand-coded matrix directly as a true Newton Jacobian without line search diverges on the first step, whereas the exact AD Jacobian in Torch-DPhys converges quadratically. Furthermore, starting from four converged SAM-Lite states, a single exact Newton correction in Torch-DPhys has a maximum normalized magnitude of , confirming consistency of the discrete roots.
Adaptive time-stepping rules and retry lifecycle. The iteration-based adaptive time stepper increases by a factor of 1.1 when a step converges in fewer than 5 nonlinear iterations (and fewer than 750 linear iterations), decreases by a factor of 0.8 when nonlinear iterations exceed 9 (or linear iterations exceed 1,350), and cuts back by a factor of 0.8 to retry upon a failed nonlinear solve. Following a rejected attempt, the solver restores the last accepted state and auxiliary fields; to match the MOOSE execution lifecycle, the subsequent retry retains the failed attempt's step size as dt_old in the variable-step BDF2 coefficients. Standalone driver verification tests confirmed exact reproduction of a 65-attempt sequence containing four step rejections and boundary clips.
Stopping criteria and tight-tolerance step-rejection replay. Both solvers evaluate nonlinear convergence using the separate absolute and relative criteria
where is the Euclidean norm of the scaled residual vector. In the baseline input deck, , with velocity and pressure rows scaled by 0.1 and energy rows scaled by .
In a separate stress test using unit row scaling, , , and a maximum of 30 nonlinear iterations (Figure 17), SAM-Lite completed 10 accepted steps ( s) with a step rejection at attempt 9 before stalling in repeated cutbacks at step 11. Because the exact AD Newton solver in Torch-DPhys converges in fewer iterations (10, 5, 4, 4, 4, 4, 3, 3, 3, and 3 iterations on the 10 accepted steps), Torch-DPhys converged on attempt 9 where SAM-Lite rejected; to test retry history handling in the adjoint, the replay driver explicitly imposed the SAM-Lite rejection at attempt 9.
B.3 Baseline Adaptive Schedule Settings
In the 200-step baseline comparison (Section 4.4), both SAM-Lite and Torch-DPhys start from s with step bounds s, target nonlinear iterations, and apply with row scaling and a 15-iteration cap. Although nonlinear iteration counts differed slightly on 59 of the 200 steps, all counts remained within the growth band, resulting in bitwise-identical 200-step time grids up to s.
B.4 Time-Step Sensitivity and Conservation
Table 7 summarizes the endpoint changes observed in the Torch-DPhys constant-step refinement study ( s across s) discussed in Section 4.6.
Table 7: Endpoint solution sensitivity of the production MSFR formulation when refining a constant time step from s to s at s.
| Quantity | Change ( s minus 0.25 s) | Context |
|---|---|---|
| Mean outlet temperature | +0.46 K | |
| Mean inlet pressure | +2.2 kPa | 5.8% of the inlet–outlet pressure drop |
| Outlet mass flow from velocity field | +36 kg/s | Global mass-flux imbalance rises from 1.65% to 1.90% |
| Maximum core temperature | +0.8 K |
At the s endpoint of the 200-step baseline run, direct quadrature integration of the normal velocity field over the inlet and outlet boundaries gives mass flow rates of 14, 918.60 kg/s

Figure 17: Attempt sequence and nonlinear iteration counts during the tight-tolerance ( , unit scaling) MSFR replay. Top: step sizes and acceptance outcomes. Bottom: nonlinear iteration counts for SAM-Lite and Torch-DPhys.
and 15, 165.31 kg/s, respectively—a net imbalance of 246.71 kg/s (1.65%), matching the archived SAM-Lite boundary flux postprocessors. Because fluid density is constant, this discrepancy reflects the weak enforcement of continuity with PSPG stabilization on the coarse 1,296-element mesh rather than physical mass accumulation.
B.5 Sparse Linear Algebra and Numerical Agreement
Each Newton update and discrete-adjoint step solves a linear system
where is either the state Jacobian or its transpose . Whereas the reference dense path computes a pivoted LU factorization followed by triangular substitutions
the sparse path retains only the 182,809 structural nonzeros (0.58% density). To mitigate ill-conditioning prior to sparse factorization, each row is equilibrated by its maximum absolute entry:
The equilibrated matrix is factored with row and column permutations and :
and the initial solution is polished with one step of iterative refinement using the unscaled residual:
Table 8 compares the sparse SuperLU solver against the dense LU reference on the 10-step retry and 40-step verification windows, showing agreement to within for forward states and for trajectory gradients.
Table 8: Maximum normalized discrepancies between the sparse SuperLU and dense LU implementations across the 10-step retry and 40-step MSFR verification windows.
| Quantity | Comparison scope | Maximum discrepancy |
|---|---|---|
| Jacobian assembly | Tested states within each execution mode | Bitwise identical |
| Forward states | Eager trajectories (Eq. (8)) | |
| Adjoint gradients | Evaluated on common dense trajectories | |
| Adjoint gradients | Sparse forward trajectory vs. dense reference |
Blockwise gradient discrepancies are measured over all active parameter blocks via
while structurally zero parameter blocks match identically.
B.5.1 Sparse-Backend Verification
Across 417 benchmark linear systems (50 adjoint systems, 204 trajectory Newton systems, 131 matched-step Newton systems, and 32 diagnostic right-hand sides), the equilibrated sparse solver reproduces all acceptance sequences, Newton iteration counts, and line-search step sizes of the dense solver. Across 40 parameter directions (the 39 directions in Figure 9 plus an all-ones porosity vector), the maximum relative discrepancy between the sparse adjoint and forward tangent-linear sensitivities on the 40-step window is on the archived dense trajectory and on the sparse trajectory.
B.6 Transient-Adjoint Verification Details
Table 9 summarizes the transient-adjoint verification across the five frozen-schedule trajectory windows plotted in Figure 9. For each parameter direction , the independent forward tangent-linear recurrence propagates state sensitivities via
with .
Table 9: MSFR transient-adjoint verification across five trajectory windows. “Max. discrepancy” gives the maximum relative difference between the adjoint and forward tangent-linear recurrence across 39 directions; “FD counts” lists resolved-and-agreeing versus unresolved finite-difference directions; and “Reference change” gives (Eq. (27)) after applying two additional root-polishing Newton updates per step.
| Trajectory window / schedule | Max. discrepancy | FD counts | Reference change |
|---|---|---|---|
| 1 step, backward Euler | |||
| 3 steps, backward Euler + BDF2 | |||
| 10 steps, with step-9 retry | |||
| 10 steps, baseline schedule | |||
| 40 steps, baseline schedule |
To monitor linear-solver accuracy in the presence of an unscaled 1-norm condition number of , we track the scaled backward error and subsequent iterative-refinement step ratio :
Across all five windows, the transposed adjoint solves achieve and , while the forward-sensitivity solves achieve and .
Finally, to quantify how finite nonlinear stopping tolerances affect the discrete-adjoint gradient, each operating gradient is compared against a root-polished reference gradient computed by forcing two extra Newton updates per time step:
As shown in the final column of Table 9, remains between and across all five windows.
C Execution Configuration and Compilation Details
C.1 GPU Backend Verification and Device Residency
On the NVIDIA RTX 2000 Ada GPU (PyTorch 2.13.0+cu129, Triton 3.7.1, cuDSS 0.8.0.10, float64 precision, fused multiply-add (FMA) contraction disabled), the sparse GPU backend matches the CPU SuperLU implementation on the 40-step and 10-step retry windows within maximum normalized state differences of and , and maximum blockwise gradient differences of and , respectively.
To reduce kernel launch overhead during element-Jacobian assembly on the GPU, deterministic atomic accumulation is relaxed only on element-assembly passes verified at initialization to have duplicate-free write indices, while global assembly, residual VJPs, and linear solves retain deterministic execution. Combining device convergence checks into a single scalar host read per compiled call reduces host-device scalar reads from 361 to 249 per Newton step and from 128 to 68 per adjoint step, keeping all field tensors, sparse matrix buffers, and trajectory history records resident on the GPU.
C.2 CPU Repeatability and Compiled-Kernel Agreement
Under the baseline four-thread CPU configuration (MKL_CBWR=AUTO, STRICT, fixed 4 Torch/OpenMP/MKL threads, and PyTorch deterministic algorithms enabled), repeated forward and adjoint runs produce bitwise-identical trajectories and gradients across fresh processes and under 24-worker CPU background contention. Table 10 summarizes the numerical agreement between eager and torch.compile-compiled CPU execution on the dense backend, showing agreement to within on individual kernels and on 40-step adjoint gradients.
Table 10: Maximum normalized discrepancies between compiled (torch.compile) and eager MSFR execution on CPU (float64, 4 threads).
| Evaluated quantity | Maximum normalized discrepancy |
|---|---|
| Assembled residual vector | |
| Residual vector-Jacobian product (VJP) | |
| Element-Jacobian blocks | |
| Dense LU factors and linear-system solutions | Bitwise identical |
| Adjoint gradient (40-step window) | |
| Adjoint gradient (10-step retry window) |
Because the transient uses a backward-Euler startup step followed by variable-step BDF2, torch.compile builds separate graph specializations for the residual, element-Jacobian, and adjoint VJP operations under each time integrator. The first-execution forward costs reported in Figure 10(a) include compilation, setup, and execution of the forward path, rather than compiler time alone. Adjoint VJP specializations are compiled separately when first invoked.