diff --git a/.gitmodules b/.gitmodules index 6ff4b67f13..14972478e6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -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 + diff --git a/bld/namelist_files/namelist_definition_ctsm.xml b/bld/namelist_files/namelist_definition_ctsm.xml index daa0ab8ba4..ea451f3139 100644 --- a/bld/namelist_files/namelist_definition_ctsm.xml +++ b/bld/namelist_files/namelist_definition_ctsm.xml @@ -150,6 +150,12 @@ specify spatially variable soil thickness. If not present, use bottom of soil column (nlevsoi). + +If TRUE, run the demo FTorch test during initialization. +Default: FALSE + + number of wavelength bands used in SNICAR snow albedo calculation diff --git a/cime_config/testdefs/testlist_clm.xml b/cime_config/testdefs/testlist_clm.xml index 4d379aa664..04428e9265 100644 --- a/cime_config/testdefs/testlist_clm.xml +++ b/cime_config/testdefs/testlist_clm.xml @@ -5168,6 +5168,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cime_config/testdefs/testmods_dirs/clm/ftorch/shell_commands b/cime_config/testdefs/testmods_dirs/clm/ftorch/shell_commands new file mode 100755 index 0000000000..2d06944bb8 --- /dev/null +++ b/cime_config/testdefs/testmods_dirs/clm/ftorch/shell_commands @@ -0,0 +1,2 @@ +#!/bin/bash +./xmlchange USE_FTORCH=TRUE diff --git a/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/constant_model.pt b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/constant_model.pt new file mode 100644 index 0000000000..2f64d43155 Binary files /dev/null and b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/constant_model.pt differ diff --git a/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/include_user_mods b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/include_user_mods new file mode 100644 index 0000000000..7225656525 --- /dev/null +++ b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/include_user_mods @@ -0,0 +1 @@ +../ftorch diff --git a/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/shell_commands b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/shell_commands new file mode 100755 index 0000000000..b8658f95e8 --- /dev/null +++ b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/shell_commands @@ -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" diff --git a/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/user_nl_clm b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/user_nl_clm new file mode 100644 index 0000000000..b6049909f8 --- /dev/null +++ b/cime_config/testdefs/testmods_dirs/clm/ftorch_demo/user_nl_clm @@ -0,0 +1 @@ +use_ftorch_demo = .true. diff --git a/doc/source/users_guide/running-special-cases/Running-with-FTorch.rst b/doc/source/users_guide/running-special-cases/Running-with-FTorch.rst new file mode 100644 index 0000000000..285c2dc5e1 --- /dev/null +++ b/doc/source/users_guide/running-special-cases/Running-with-FTorch.rst @@ -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) diff --git a/doc/source/users_guide/running-special-cases/index.rst b/doc/source/users_guide/running-special-cases/index.rst index e8384ebd49..5c651f48af 100644 --- a/doc/source/users_guide/running-special-cases/index.rst +++ b/doc/source/users_guide/running-special-cases/index.rst @@ -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 + diff --git a/libraries/FTorch b/libraries/FTorch new file mode 160000 index 0000000000..6d03d7c46b --- /dev/null +++ b/libraries/FTorch @@ -0,0 +1 @@ +Subproject commit 6d03d7c46b7adeca12e7bb5e7995e23386d2251c diff --git a/python/ctsm/machine_learning/__init__.py b/python/ctsm/machine_learning/__init__.py new file mode 100644 index 0000000000..8971b320af --- /dev/null +++ b/python/ctsm/machine_learning/__init__.py @@ -0,0 +1,3 @@ +""" +Machine Learning tools and FTorch integration utilities for CTSM. +""" diff --git a/python/ctsm/machine_learning/export_torchscript.py b/python/ctsm/machine_learning/export_torchscript.py new file mode 100755 index 0000000000..84f073042e --- /dev/null +++ b/python/ctsm/machine_learning/export_torchscript.py @@ -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() diff --git a/python/ctsm/test/test_unit_export_torchscript.py b/python/ctsm/test/test_unit_export_torchscript.py new file mode 100644 index 0000000000..2b567c3fea --- /dev/null +++ b/python/ctsm/test/test_unit_export_torchscript.py @@ -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() diff --git a/src/main/clm_initializeMod.F90 b/src/main/clm_initializeMod.F90 index 4e583ad4cd..caadca1774 100644 --- a/src/main/clm_initializeMod.F90 +++ b/src/main/clm_initializeMod.F90 @@ -141,7 +141,7 @@ subroutine initialize2(ni,nj, currtime) use clm_varorb , only : eccen, mvelpp, lambm0, obliqr, & eccen_prev, mvelpp_prev, lambm0_prev, obliqr_prev use clm_varctl , only : use_cropcal_streams - use clm_varctl , only : use_noio + use clm_varctl , only : use_noio, use_ftorch_demo use landunit_varcon , only : landunit_varcon_init, max_lunit, numurbl use pftconMod , only : pftcon use decompInitMod , only : decompInit_clumps, decompInit_glcp @@ -185,6 +185,7 @@ subroutine initialize2(ni,nj, currtime) use FATESFireFactoryMod , only : scalar_lightning use dynFATESLandUseChangeMod , only : dynFatesLandUseInit use HillslopeHydrologyMod , only : InitHillslope + use FTorch_cesm_interface , only : torch_model, torch_tensor, torch_model_load, torch_tensor_from_array, torch_model_forward, torch_kCPU, torch_delete ! ! !ARGUMENTS integer, intent(in) :: ni, nj ! global grid sizes @@ -221,6 +222,11 @@ subroutine initialize2(ni,nj, currtime) logical :: lexists real(r8), pointer :: data2dptr(:,:) ! temp. pointers for slicing larger arrays character(len=32) :: subname = 'initialize2' ! subroutine name + type(torch_model) :: demo_ftorch_model + type(torch_tensor) :: demo_ftorch_in_tensor(1), demo_ftorch_out_tensor(1) + real(r8), target :: demo_ftorch_in_data(4) + real(r8), target :: demo_ftorch_out_data(4) + integer :: demo_ftorch_in_layout(1), demo_ftorch_out_layout(1) !----------------------------------------------------------------------- call t_startf('clm_init2_part1') @@ -801,6 +807,38 @@ subroutine initialize2(ni,nj, currtime) !$OMP END PARALLEL DO end if + if (use_ftorch_demo) then + if (masterproc) then + write(iulog,*) '=========================================' + write(iulog,*) ' RUNNING DEMO FTORCH TEST ' + end if + + demo_ftorch_in_data = [1.0_r8, 2.0_r8, 3.0_r8, 4.0_r8] + demo_ftorch_out_data = [0.0_r8, 0.0_r8, 0.0_r8, 0.0_r8] + demo_ftorch_in_layout = [1] + demo_ftorch_out_layout = [1] + + ! model_load belongs here in the initialization phase. + call torch_model_load(demo_ftorch_model, "constant_model.pt", torch_kCPU) + + ! In a real parameterization, model_forward and tensor creation would happen + ! inside the main physics loop (e.g., inside clm_drv). + call torch_tensor_from_array(demo_ftorch_in_tensor(1), demo_ftorch_in_data, demo_ftorch_in_layout, torch_kCPU) + call torch_tensor_from_array(demo_ftorch_out_tensor(1), demo_ftorch_out_data, demo_ftorch_out_layout, torch_kCPU) + call torch_model_forward(demo_ftorch_model, demo_ftorch_in_tensor, demo_ftorch_out_tensor) + + if (masterproc) then + write(iulog,*) ' FTORCH INFERENCE SUCCESSFUL: output = ', demo_ftorch_out_data + write(iulog,*) '=========================================' + end if + + ! In a real parameterization, tensor deletion happens at the end of the + ! time step, and model deletion happens in the model finalize phase. + call torch_delete(demo_ftorch_in_tensor(1)) + call torch_delete(demo_ftorch_out_tensor(1)) + call torch_delete(demo_ftorch_model) + end if + call t_stopf('clm_init2_part3') end subroutine initialize2 diff --git a/src/main/clm_varctl.F90 b/src/main/clm_varctl.F90 index 9e42c3ff21..1956d7dede 100644 --- a/src/main/clm_varctl.F90 +++ b/src/main/clm_varctl.F90 @@ -441,6 +441,7 @@ module clm_varctl !---------------------------------------------------------- logical, public :: use_bedrock = .false. ! true => use spatially variable soil depth + logical, public :: use_ftorch_demo = .false. ! true => run the demo ftorch test character(len=16), public :: soil_layerstruct_predefined = 'UNSET' real(r8), public :: soil_layerstruct_userdefined(99) = rundef integer, public :: soil_layerstruct_userdefined_nlevsoi = iundef diff --git a/src/main/controlMod.F90 b/src/main/controlMod.F90 index 70cf132dc7..40d44cd6da 100644 --- a/src/main/controlMod.F90 +++ b/src/main/controlMod.F90 @@ -284,6 +284,7 @@ subroutine control_init(dtime) namelist /clm_inparm/ use_lai_streams namelist /clm_inparm/ use_bedrock + namelist /clm_inparm/ use_ftorch_demo namelist /clm_inparm/ use_biomass_heat_storage @@ -888,6 +889,7 @@ subroutine control_spmd() call mpi_bcast (use_cropcal_streams, 1, MPI_LOGICAL, 0, mpicom, ier) call mpi_bcast (use_bedrock, 1, MPI_LOGICAL, 0, mpicom, ier) + call mpi_bcast (use_ftorch_demo, 1, MPI_LOGICAL, 0, mpicom, ier) call mpi_bcast (use_biomass_heat_storage, 1, MPI_LOGICAL, 0, mpicom, ier) diff --git a/tools/ftorch/export_torchscript b/tools/ftorch/export_torchscript new file mode 100755 index 0000000000..0e8b9920e6 --- /dev/null +++ b/tools/ftorch/export_torchscript @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +""" +Command-line wrapper for exporting PyTorch models to TorchScript (.pt) format for FTorch. +""" + +import os +import sys + +_CTSM_PYTHON = os.path.join( + os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir, "python" +) +sys.path.insert(1, _CTSM_PYTHON) + +# pylint: disable=import-error, wrong-import-position +from ctsm.machine_learning.export_torchscript import main + +if __name__ == "__main__": + main()