Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,13 @@ fxtag = v3.2.1
fxrequired = ToplevelOptional
# Standard Fork to compare to with "git fleximod test" to ensure personal forks aren't committed
fxDONOTUSEurl = https://github.com/ESMCI/doc-builder

# FTorch interface library for AI and Machine Learning
[submodule "FTorch"]
path = libraries/FTorch
url = https://github.com/ESCOMP/FTorch_interface
fxtag = v0.0.6
fxrequired = ToplevelRequired
# Standard Fork to compare to with "git fleximod test" to ensure personal forks aren't committed
fxDONOTUSEurl = https://github.com/ESCOMP/FTorch_interface

6 changes: 6 additions & 0 deletions bld/namelist_files/namelist_definition_ctsm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ specify spatially variable soil thickness. If not present, use bottom
of soil column (nlevsoi).
</entry>

<entry id="use_ftorch_demo" type="logical" category="clm_physics"
group="clm_inparm" valid_values="" >
If TRUE, run the demo FTorch test during initialization.
Default: FALSE
</entry>

<entry id="snicar_numrad_snw" type="integer" category="clm_physics"
group="clm_inparm" valid_values="5,480" value="5" >
number of wavelength bands used in SNICAR snow albedo calculation
Expand Down
25 changes: 25 additions & 0 deletions cime_config/testdefs/testlist_clm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5168,6 +5168,31 @@
</options>
</test>

<test name="SMS_D_Ld1" grid="f10_f10_mg37" compset="I2000Clm60Sp" testmods="clm/default--clm/nofireemis--clm/ftorch_demo">
<machines>
<machine name="derecho" compiler="intel" category="aux_clm"/>
<machine name="derecho" compiler="gnu" category="aux_clm"/>
</machines>
<options>
<option name="wallclock">00:20:00</option>
<option name="comment">Test building and running CTSM case with FTorch demo inference enabled</option>
</options>
</test>

<test name="SMS_D_Ld1_Mmpi-serial" grid="1x1_brazil" compset="I2000Clm60SpRsGs" testmods="clm/default--clm/nofireemis--clm/ftorch_demo">
<machines>
<machine name="derecho" compiler="intel" category="aux_clm"/>
<machine name="derecho" compiler="gnu" category="aux_clm"/>
</machines>
<options>
<option name="wallclock">00:10:00</option>
<option name="comment">Test building and running standalone single-point CTSM case (LEAP/M2LInES setup) with FTorch demo inference enabled</option>
</options>
</test>




<test name="ERP_D_P128x1_Ld26" grid="f10_f10_mg37" compset="IHistClm60BgcCrop" testmods="clm/crop--clm/midDecStart--clm/RxCropCalsAdaptGGCMI">
<machines>
<machine name="derecho" compiler="intel" category="aux_clm"/>
Expand Down
2 changes: 2 additions & 0 deletions cime_config/testdefs/testmods_dirs/clm/ftorch/shell_commands
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
./xmlchange USE_FTORCH=TRUE
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
../ftorch
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash
lndroot=$(./xmlquery --value COMP_ROOT_DIR_LND)
rundir=$(./xmlquery --value RUNDIR)
mkdir -p "${rundir}"
cp "${lndroot}/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/constant_model.pt" "${rundir}/constant_model.pt"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use_ftorch_demo = .true.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
.. _running-with-ftorch-section:

###############################################
Running with Machine Learning Models via FTorch
###############################################

FTorch (Fortran interface to PyTorch) allows CTSM Fortran routines to call PyTorch models at runtime for machine learning parameterizations, emulators, and data-driven subgrid processes.

Prerequisites
=============

1. **Python Environment (for model export)**:
PyTorch is only required if you are creating or exporting models into TorchScript format (CTSM runtime simulations link directly against C++ LibTorch and do not require PyTorch in your Python environment). To export models, install PyTorch into your active Python environment:

* In ``ctsm_pylib`` or another conda environment:

.. code-block:: bash

conda activate ctsm_pylib
conda install pytorch-cpu -c pytorch
# or via pip:
pip install torch --index-url https://download.pytorch.org/whl/cpu

* On NCAR HPC systems (e.g., Derecho), you can alternatively activate NCAR's pre-built Python environment with PyTorch pre-installed:

.. code-block:: bash

module load conda
conda activate npl

2. **Checking out FTorch**:
Ensure the ``libraries/FTorch`` submodule is populated via ``git-fleximod``:

.. code-block:: bash

./bin/git-fleximod update

Workflow: Exporting PyTorch Models to TorchScript (.pt)
=======================================================

FTorch requires models to be exported into TorchScript format (``.pt``). You can export custom PyTorch ``nn.Module`` models using ``torch.jit.script`` / ``torch.jit.trace`` (or ``ctsm.machine_learning.export_torchscript.export_model_to_torchscript``), or generate a built-in demonstration model (``constant`` or ``identity``) using the provided CTSM export tool:

.. code-block:: bash

./tools/ftorch/export_torchscript -o my_model.pt

At runtime, ensure the exported ``.pt`` model file is staged into your case's run directory (``$RUNDIR``).

Building CTSM with FTorch Support
=================================

To build CTSM with FTorch enabled, set ``USE_FTORCH=TRUE`` in your case configuration before building:

.. code-block:: bash

./xmlchange USE_FTORCH=TRUE
./case.setup
./case.build

Interfacing Fortran Code with FTorch
====================================

To load and execute a PyTorch model in CTSM Fortran code, import from ``FTorch_cesm_interface`` (see ``use_ftorch_demo`` for a working example):

.. code-block:: fortran

use FTorch_cesm_interface, only : torch_model, torch_tensor, torch_model_load, &
torch_tensor_from_array, torch_model_forward, &
torch_kCPU, torch_delete

type(torch_model) :: model
type(torch_tensor) :: in_tensor(1), out_tensor(1)
real(r8), target :: input_data(N), output_data(N)
integer :: in_layout(1), out_layout(1)

in_layout = [1]
out_layout = [1]

! 1. Load TorchScript model file (from $RUNDIR)
! (do this once, in an initialize step.)
call torch_model_load(model, "my_model.pt", torch_kCPU)

! 2. Bind Fortran arrays to Torch tensors (shape is inferred from array; layout orders dimensions)
! (do this and #3 once per inference - probably once per timestep)
call torch_tensor_from_array(in_tensor(1), input_data, in_layout, torch_kCPU)
call torch_tensor_from_array(out_tensor(1), output_data, out_layout, torch_kCPU)

! 3. Perform forward inference pass
call torch_model_forward(model, in_tensor, out_tensor)

! 4. Clean up model and tensor handles
! (do this once, in a teardown step.)
call torch_delete(in_tensor(1))
call torch_delete(out_tensor(1))
call torch_delete(model)
2 changes: 2 additions & 0 deletions doc/source/users_guide/running-special-cases/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ Running Special Cases
Running-with-MOAR-data-as-atmospheric-forcing-to-spinup-the-model.rst
Running-with-your-own-previous-simulation-as-atmospheric-forcing-to-spinup-the-model.rst
Running-with-anomaly-forcing.rst
Running-with-FTorch.rst

1 change: 1 addition & 0 deletions libraries/FTorch
Submodule FTorch added at 6d03d7
3 changes: 3 additions & 0 deletions python/ctsm/machine_learning/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Machine Learning tools and FTorch integration utilities for CTSM.
"""
146 changes: 146 additions & 0 deletions python/ctsm/machine_learning/export_torchscript.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""
Tool and library to create toy models and export PyTorch models to TorchScript.

As a tool, this creates toy models for testing. As a library, it converts a
PyTorch nn.Module to a TorchScript file.
"""

import argparse
import logging
import sys

try:
import torch # pylint: disable=import-error
from torch import nn # pylint: disable=import-error

HAS_TORCH = True
except ImportError:
# Allows ctsm python test discovery (run_ctsm_py_tests) to succeed
# on environments without PyTorch installed.
torch = None
nn = None
HAS_TORCH = False

logger = logging.getLogger(__name__)


if HAS_TORCH:

class SampleIdentityModel(nn.Module): # pylint: disable=too-few-public-methods
"""Sample Identity Model used for testing and demonstration.

Returns input unchanged.
"""

def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward pass returning the input tensor unchanged."""
return x * 1.0

class ConstantModel(nn.Module): # pylint: disable=too-few-public-methods
"""Sample Constant Model used for testing and demonstration.

Returns tensor of ones matching input shape, multiplied by a constant.
"""

def __init__(self, constant_value: float = 1.0):
super().__init__()
self.constant_value = constant_value

def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward pass returning a constant tensor of the input shape."""
return torch.ones_like(x) * self.constant_value

else:

class SampleIdentityModel: # pylint: disable=too-few-public-methods
"""Fallback SampleIdentityModel placeholder when PyTorch is unavailable."""

class ConstantModel: # pylint: disable=too-few-public-methods
"""Fallback ConstantModel placeholder when PyTorch is unavailable."""

def __init__(self, constant_value: float = 1.0):
self.constant_value = constant_value


def export_model_to_torchscript(model, output_file, method="script", example_input=None):
"""Export a PyTorch nn.Module to a TorchScript file.

:param model: PyTorch nn.Module instance
:param output_file: Path to output .pt file
:param method: 'script' or 'trace'
:param example_input: Tensor input required if method is 'trace'
"""
if not HAS_TORCH:
raise RuntimeError(
"PyTorch is not installed in the active environment. Please activate ctsm_pylib."
)

model.eval()
if method == "script":
scripted_model = torch.jit.script(model)
elif method == "trace":
if example_input is None:
raise ValueError("example_input is required when method='trace'")
scripted_model = torch.jit.trace(model, example_input)
else:
raise ValueError(f"Unknown export method: {method}. Must be 'script' or 'trace'.")

scripted_model.save(output_file)
logger.info("Successfully exported TorchScript model to: %s", output_file)
return output_file


def main():
"""Command-line interface for exporting sample models to TorchScript."""
parser = argparse.ArgumentParser(
description="Export PyTorch model to TorchScript .pt format for FTorch."
)
parser.add_argument(
"-o",
"--output",
default="constant_model.pt",
help="Output .pt file path (default: constant_model.pt)",
)
parser.add_argument(
"-m",
"--method",
choices=["script", "trace"],
default="script",
help="Export method (default: script)",
)
parser.add_argument(
"--model-type",
choices=["constant", "identity"],
default="constant",
help="Type of model to export (default: constant)",
)
parser.add_argument(
"--constant-val",
type=float,
default=1.0,
help="Value for constant model (default: 1.0)",
)
args = parser.parse_args()

logging.basicConfig(level=logging.INFO)

if not HAS_TORCH:
print(
"ERROR: PyTorch is not available. Ensure PyTorch is installed in your "
"python environment (ctsm_pylib).",
file=sys.stderr,
)
sys.exit(1)

if args.model_type == "constant":
model = ConstantModel(constant_value=args.constant_val)
else:
model = SampleIdentityModel()

export_model_to_torchscript(model, args.output, method=args.method)
print(f"Exported {args.model_type} TorchScript model to: {args.output}")


if __name__ == "__main__":
main()
57 changes: 57 additions & 0 deletions python/ctsm/test/test_unit_export_torchscript.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Unit test for ctsm.machine_learning.export_torchscript."""

import os
import tempfile
import unittest

from ctsm.machine_learning.export_torchscript import (
HAS_TORCH,
ConstantModel,
SampleIdentityModel,
export_model_to_torchscript,
)

try:
import torch # pylint: disable=import-error
except ImportError:
torch = None


class TestExportTorchscript(unittest.TestCase):
"""Unit tests for export_torchscript module and models."""

def test_sample_identity_model(self):
"""Test instantiation and identity behavior of SampleIdentityModel."""
model = SampleIdentityModel()
self.assertIsNotNone(model)
if HAS_TORCH:
x = torch.tensor([1.0, -2.5, 3.14])
out = model(x)
self.assertTrue(torch.allclose(out, x))

def test_constant_model(self):
"""Test instantiation and constant behavior of ConstantModel."""
model = ConstantModel(constant_value=2.0)
self.assertIsNotNone(model)
self.assertEqual(model.constant_value, 2.0)
if HAS_TORCH:
x = torch.tensor([0.5, 1.5, -3.0])
out = model(x)
expected = torch.full_like(x, 2.0)
self.assertTrue(torch.allclose(out, expected))

def test_export_model(self):
"""Test export_model_to_torchscript behavior with or without torch."""
if not HAS_TORCH:
with self.assertRaises(RuntimeError):
export_model_to_torchscript(None, "dummy.pt")
else:
with tempfile.TemporaryDirectory() as tmpdir:
output_file = os.path.join(tmpdir, "model.pt")
model = ConstantModel(constant_value=1.0)
export_model_to_torchscript(model, output_file, method="script")
self.assertTrue(os.path.isfile(output_file))


if __name__ == "__main__":
unittest.main()
Loading
Loading