Skip to content

Using FTorch

Jim Edwards edited this page Aug 28, 2025 · 3 revisions

Using FTorch in CESM3: Quick Start

Goal: Call a PyTorch model from CESM3 components via the FTorch_cesm_interface wrapper.

Enable FTorch in your case

./xmlchange USE_FTORCH=TRUE

(Run in your case directory after create_newcase.)

Use the CESM interface module in Fortran

! In your CESM component code
use FTorch_cesm_interface

What the interface currently supports

torch_kCPU — device kind constant (CPU)

torch_tensor — tensor handle/type

torch_model — loaded model handle/type

torch_tensor_from_array — create a tensor from Fortran arrays

torch_model_load — load a serialized TorchScript model

torch_model_forward — run inference (forward pass)

Minimal usage pattern (pseudocode)

! PSEUDOCODE – see module for exact signatures
use FTorch_cesm_interface, only: torch_kCPU, torch_tensor, torch_model, &
                                 torch_tensor_from_array, torch_model_load, &
                                 torch_model_forward

integer :: dev
type(torch_model)  :: mdl
type(torch_tensor) :: x, y

! Select device
dev = torch_kCPU

! Load model (TorchScript .pt)
mdl = torch_model_load('path/to/model.pt', dev)

! Wrap CESM state into a tensor
x = torch_tensor_from_array(state_array, shape=(/ n /))

! Inference
call torch_model_forward(mdl, x, y)

! Map y back to CESM fields …

Need more FTorch features?

If you require FTorch capabilities beyond the list above, add them to FTorch_cesm_interface following the examples in that module—or coordinate with Jim ([email protected]) to integrate them.