FTorch

FTorch: a library for coupling PyTorch models to Fortran - Published in JOSS (2025)

https://github.com/cambridge-iccs/ftorch

Science Score: 100.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 22 DOI reference(s) in README and JOSS metadata
  • Academic publication links
    Links to: joss.theoj.org
  • Committers with academic emails
    5 of 14 committers (35.7%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
    Published in Journal of Open Source Software

Keywords

deep-learning fortran hacktoberfest interoperability libtorch machine-learning python pytorch torch

Scientific Fields

Agricultural and Biological Sciences Life Sciences - 40% confidence
Last synced: 4 months ago · JSON representation ·

Repository

A library for directly calling PyTorch ML models from Fortran.

Basic Info
Statistics
  • Stars: 137
  • Watchers: 5
  • Forks: 29
  • Open Issues: 69
  • Releases: 2
Topics
deep-learning fortran hacktoberfest interoperability libtorch machine-learning python pytorch torch
Created about 3 years ago · Last pushed 4 months ago
Metadata Files
Readme Changelog License Citation

README.md

FTorch

A library for coupling (Py)Torch machine learning models to Fortran

GitHub Fortran DOI

This repository contains code, utilities, and examples for directly calling PyTorch ML models from Fortran.

For full API and user documentation please see the online documentation which is significantly more detailed than this README.

To cite use of this code please refer to Atkinson et al., (2025) DOI:10.21105/joss.07602. See acknowledgment below for more details.

Contents

Description

It is desirable to be able to run machine learning (ML) models directly in Fortran. Such models are often trained in some other language (say Python) using popular frameworks (say PyTorch) and saved. We want to run inference on this model without having to call a Python executable. To achieve this we use the existing Torch C++ interface.

This project provides a library enabling a user to directly couple their PyTorch models to Fortran code. We provide installation instructions for the library as well as instructions and examples for performing coupling.

```fortran use ftorch ... type(torchmodel) :: model type(torchtensor), dimension(ninputs) :: modelinputsarr type(torchtensor), dimension(noutputs) :: modeloutputarr ... call torchmodelload(model, "/my/saved/TorchScript/model.pt", torchkCPU) call torchtensorfromarray(modelinputsarr(1), inputfortran, inlayout, torchkCPU) call torchtensorfromarray(modeloutputarr(1), outputfortran, outlayout, torchkCPU)

call torchmodelforward(model, modelinputarr, modeloutputarr) ```

The following presentations provide an introduction and overview of FTorch:

  • Coupling Machine Learning to Numerical (Climate) Models\ Platform for Advanced Scientific Computing, Zurich - June 2024\ Slides
  • Blending Machine Learning and Numerical Simulation, with Applications to Climate Modelling\ Durham HPC days, Durham - May 2024\ Slides
  • Reducing the overheads for coupling PyTorch machine learning models to Fortran\ ML & DL Seminars, LSCE, IPSL, Paris - November 2023\ Slides - Recording
  • Reducing the Overhead of Coupled Machine Learning Models between Python and Fortran\ RSECon23, Swansea - September 2023\ Slides - Recording

If you are interested in using this library please get in touch.

For a similar approach to calling TensorFlow models from Fortran please see Fortran-TF-lib.

Installation

Dependencies

To install the library requires the following to be installed on the system:

  • CMake >= 3.15
  • LibTorch* or PyTorch
  • Fortran (2008 standard compliant), C++ (must fully support C++17), and C compilers

* The minimal example provided downloads the CPU-only Linux Nightly binary. Alternative versions may be required.

Additional dependencies of the test suite

FTorch's test suite has some additional dependencies.

  • You will also need to install the unit testing framework pFUnit.
  • FTorch's test suite requires that PyTorch has been installed, as opposed to LibTorch. We recommend installing torchvision in the same command (e.g., pip install torch torchvision)*. Doing so ensures that torch and torchvision are configured in the same way.
  • Other Python modules are installed automatically upon building the tests.

* For more details, see here.

Windows Support

If building in a Windows environment then you can either use Windows Subsystem for Linux (WSL) or Visual Studio and the Intel Fortran Compiler. For full details on the process see the online Windows documentation.\ Note that LibTorch is not supported for the GNU Fortran compiler with MinGW.

Apple Silicon Support

At the time of writing there are issues building FTorch on Apple Silicon when linking to downloaded LibTorch binaries or pip-installed PyTorch. FTorch can successfully be built, including utilising the MPS backend, from inside a conda environment using the environment files and instructions in conda/.

Conda Support

Conda is not our preferred approach for managing dependencies, but for users who want an environment to build FTorch in we provide guidance and environment files in conda/. Note that these are not minimal and will install Python, PyTorch, and modules required for running the tests and examples.

GitHub Codespace

It is possible to try FTorch through an interactive browser session using GitHub Codespace. Full instructions are in the codespace/ directory.

Library installation

For detailed installation instructions please see the online installation documentation.

To build and install the library:

  1. Navigate to the location in which you wish to install the source and run:
    git clone git@github.com:Cambridge-ICCS/FTorch.git to clone via ssh, or
    git clone https://github.com/Cambridge-ICCS/FTorch.git to clone via https.
  2. Navigate to the root FTorch directory by running:
    cd FTorch/
  3. Build the library using CMake with the relevant options from the table below:
    mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release

    The following table of CMake options are available to be passed as arguments to cmake through -D<Option>=<Value>.
    It is likely that you will need to provide at least CMAKE_PREFIX_PATH.
    | Option | Value | Description | | ------------------------------------------------------------------------------------------------- | ---------------------------- | -------------------------------------------------------------- | | CMAKE_Fortran_COMPILER | gfortran / ifx / ifort | Specify a Fortran compiler to build the library with. This should match the Fortran compiler you're using to build the code you are calling this library from.1 | | CMAKE_C_COMPILER | gcc / icx / icc | Specify a C compiler to build the library with.1 | | CMAKE_CXX_COMPILER | g++ / icx / icpc | Specify a C++ compiler to build the library with.1 | | CMAKE_PREFIX_PATH | </path/to/LibTorch/> | Location of Torch installation2 | | CMAKE_INSTALL_PREFIX | </path/to/install/lib/at/> | Location at which the library files should be installed. By default this is /usr/local | | CMAKE_BUILD_TYPE | Release / Debug | Specifies build type. The default is Debug, use Release for production code | | CMAKE_BUILD_TESTS | TRUE / FALSE | Specifies whether to compile FTorch's test suite as part of the build. | | GPU_DEVICE | NONE / CUDA / HIP / XPU / MPS | Specifies the target GPU backend architecture (if any) 3 | | MULTI_GPU | ON / OFF | Specifies whether to build the tests that involve multiple GPU devices (ON by default if CMAKE_BUILD_TESTS and GPU_DEVICE are set). |

    1 On Windows this may need to be the full path to the compiler if CMake cannot locate it by default.

    2 The path to the Torch installation needs to allow CMake to locate the relevant Torch CMake files.
    If Torch has been installed as LibTorch then this should be the absolute path to the unzipped LibTorch distribution. If Torch has been installed as PyTorch in a Python venv (virtual environment), e.g. with pip install torch, then this should be </path/to/venv/>lib/python<3.xx>/site-packages/torch/.
    You can find the location of your torch install by importing torch from your Python environment (import torch) and running `print(torch.
    file)`

    3 This is often overridden by PyTorch. When installing with pip, the index-url flag can be used to ensure a CPU-only or GPU-enabled version is installed, e.g. pip install torch --index-url https://download.pytorch.org/whl/cpu. URLs for alternative versions can be found here.

  4. Make and install the library to the desired location with either: cmake --build . --target install or, if you want to separate these steps: cmake --build . cmake --install .

Note: If using a machine capable of running multiple jobs this can be sped up by adding --parallel [<jobs>] or -j [<jobs>] to the cmake build command. See the CMake documentation for more information.

Installation will place the following directories at the install location:  
* `CMAKE_INSTALL_PREFIX/include/` - contains header and mod files
* `CMAKE_INSTALL_PREFIX/lib/` - contains `cmake` directory and `.so` files  
_Note: depending on your system and architecture `lib` may be `lib64`, and 
you may have `.dll` files or similar._  
_Note: In a Windows environment this will require administrator privileges for the default install location._

Usage

In order to use FTorch users will typically need to follow these steps:

  1. Save a PyTorch model as TorchScript.
  2. Write Fortran using the FTorch bindings to use the model from within Fortran.
  3. Build and compile the code, linking against the FTorch library

These steps are described in more detail in the online documentation

GPU Support

To run on GPU requires an installation of LibTorch compatible for the GPU device you wish to target (using the GPU_DEVICE CMake option as detailed in the table above) and two main adaptations to the code:

  1. When saving a TorchScript model, ensure that it is on the appropriate GPU device type. The pt2ts.py script has a command line argument --device_type, which currently accepts 5 different device types: cpu (default), cuda, hip, xpu, or mps.
  2. When using FTorch in Fortran, set the device for the input tensor(s) to the appropriate GPU device type, rather than torch_kCPU. There are currently three options: torch_kCUDA, torch_kHIP, torch_kXPU, or torch_kMPS.

For detailed guidance about running on GPU, including instructions for using multiple devices, please see the online GPU documentation.

Large tensor support

If your code uses large tensors (where large means more than 2,147,483,647 elements in any one dimension (the maximum value of a 32-bit integer)), you may need to compile ftorch with 64-bit integers. For information on how to do this, please see our FAQ

Examples

Examples of how to use this library are provided in the examples directory.
They demonstrate different functionalities of the code and are provided with instructions to modify, build, and run as necessary.

Tests

For information on testing, see the corresponding webpage or the README in the test subdirectory.

License

Copyright © ICCS

FTorch is distributed under the MIT Licence.

Contributions

Contributions and collaborations are welcome.

For bugs, feature requests, and clear suggestions for improvement please open an issue.

If you have built something upon FTorch that would be useful to others, or can address an open issue, please fork the repository and open a pull request.

Detailed guidelines can be found in the online developer documentation.

Code of Conduct

Everyone participating in the FTorch project, and in particular in the issue tracker, pull requests, and social media activity, is expected to treat other people with respect and, more generally, to follow the guidelines articulated in the Python Community Code of Conduct.

Authors and Acknowledgment

FTorch is written and maintained by the ICCS

To cite FTorch in research please refer to:

Atkinson et al., (2025). FTorch: a library for coupling PyTorch models to Fortran. Journal of Open Source Software, 10(107), 7602, https://doi.org/10.21105/joss.07602

See the CITATION.cff file or click 'Cite this repository' on the right.

See Contributors for a full list of contributors.

Used by

The following projects make use of this code or derivatives in some way:

Are we missing anyone? Let us know.

Owner

  • Name: Institute of Computing for Climate Science
  • Login: Cambridge-ICCS
  • Kind: organization

Institute of Computing for Climate Science at the University of Cambridge

JOSS Publication

FTorch: a library for coupling PyTorch models to Fortran
Published
March 05, 2025
Volume 10, Issue 107, Page 7602
Authors
Jack Atkinson ORCID
Institute of Computing for Climate Science, University of Cambridge, UK
Athena Elafrou
NVIDIA, UK
Elliott Kasoar ORCID
Institute of Computing for Climate Science, University of Cambridge, UK, Scientific Computing Department, Science and Technology Facilities Council, UK
Joseph G. Wallwork ORCID
Institute of Computing for Climate Science, University of Cambridge, UK
Thomas Meltzer ORCID
Institute of Computing for Climate Science, University of Cambridge, UK
Simon Clifford ORCID
Institute of Computing for Climate Science, University of Cambridge, UK
Dominic Orchard ORCID
Institute of Computing for Climate Science, University of Cambridge, UK, University of Kent, UK
Chris Edsall ORCID
Institute of Computing for Climate Science, University of Cambridge, UK
Editor
Matthew Feickert ORCID
Tags
PyTorch machine learning

Citation (CITATION.cff)

cff-version: "1.2.0"
authors:
- family-names: Atkinson
  given-names: Jack
  orcid: "https://orcid.org/0000-0001-5001-4812"
- family-names: Elafrou
  given-names: Athena
- family-names: Kasoar
  given-names: Elliott
  orcid: "https://orcid.org/0009-0005-2015-9478"
- family-names: Wallwork
  given-names: Joseph G.
  orcid: "https://orcid.org/0000-0002-3646-091X"
- family-names: Meltzer
  given-names: Thomas
  orcid: "https://orcid.org/0000-0003-1740-9550"
- family-names: Clifford
  given-names: Simon
  orcid: "https://orcid.org/0000-0001-7754-504X"
- family-names: Orchard
  given-names: Dominic
  orcid: "https://orcid.org/0000-0002-7058-7842"
- family-names: Edsall
  given-names: Chris
  orcid: "https://orcid.org/0000-0001-6863-2184"
contact:
- family-names: Atkinson
  given-names: Jack
  orcid: "https://orcid.org/0000-0001-5001-4812"
doi: 10.5281/zenodo.14968153
message: If you use this software, please cite our article in the
  Journal of Open Source Software.
preferred-citation:
  authors:
  - family-names: Atkinson
    given-names: Jack
    orcid: "https://orcid.org/0000-0001-5001-4812"
  - family-names: Elafrou
    given-names: Athena
  - family-names: Kasoar
    given-names: Elliott
    orcid: "https://orcid.org/0009-0005-2015-9478"
  - family-names: Wallwork
    given-names: Joseph G.
    orcid: "https://orcid.org/0000-0002-3646-091X"
  - family-names: Meltzer
    given-names: Thomas
    orcid: "https://orcid.org/0000-0003-1740-9550"
  - family-names: Clifford
    given-names: Simon
    orcid: "https://orcid.org/0000-0001-7754-504X"
  - family-names: Orchard
    given-names: Dominic
    orcid: "https://orcid.org/0000-0002-7058-7842"
  - family-names: Edsall
    given-names: Chris
    orcid: "https://orcid.org/0000-0001-6863-2184"
  date-published: 2025-03-05
  doi: 10.21105/joss.07602
  issn: 2475-9066
  issue: 107
  journal: Journal of Open Source Software
  publisher:
    name: Open Journals
  start: 7602
  title: "FTorch: a library for coupling PyTorch models to Fortran"
  type: article
  url: "https://joss.theoj.org/papers/10.21105/joss.07602"
  volume: 10
title: "FTorch: a library for coupling PyTorch models to Fortran"

GitHub Events

Total
  • Fork event: 13
  • Create event: 119
  • Commit comment event: 1
  • Release event: 1
  • Issues event: 137
  • Watch event: 55
  • Delete event: 119
  • Member event: 2
  • Issue comment event: 370
  • Push event: 847
  • Pull request review comment event: 461
  • Pull request review event: 550
  • Pull request event: 238
Last Year
  • Fork event: 13
  • Create event: 121
  • Commit comment event: 1
  • Release event: 1
  • Issues event: 137
  • Watch event: 55
  • Delete event: 119
  • Member event: 2
  • Issue comment event: 370
  • Push event: 848
  • Pull request review comment event: 461
  • Pull request review event: 550
  • Pull request event: 240

Committers

Last synced: 5 months ago

All Time
  • Total Commits: 388
  • Total Committers: 14
  • Avg Commits per committer: 27.714
  • Development Distribution Score (DDS): 0.608
Past Year
  • Commits: 175
  • Committers: 7
  • Avg Commits per committer: 25.0
  • Development Distribution Score (DDS): 0.6
Top Committers
Name Email Commits
jatkinson1000 1****0 152
Joe Wallwork 2****3 105
tommelt t****1@g****m 38
ElliottKasoar E****r 37
Dominic Orchard d****d@g****m 19
Athena Elafrou a****8@c****k 15
Niccolò Zanotti 7****i 10
Simon Clifford s****6@c****k 5
Mikolaj-A-Kowalski 3****i 2
Daniel S. Katz d****z@i****g 1
helgehr 3****r 1
mondus p****d@s****k 1
vopikamm 3****m 1
Simon Clifford s****d@i****k 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 4 months ago

All Time
  • Total issues: 159
  • Total pull requests: 288
  • Average time to close issues: 2 months
  • Average time to close pull requests: 16 days
  • Total issue authors: 23
  • Total pull request authors: 17
  • Average comments per issue: 1.37
  • Average comments per pull request: 1.48
  • Merged pull requests: 204
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 87
  • Pull requests: 221
  • Average time to close issues: 18 days
  • Average time to close pull requests: 7 days
  • Issue authors: 12
  • Pull request authors: 9
  • Average comments per issue: 0.92
  • Average comments per pull request: 1.32
  • Merged pull requests: 159
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • jatkinson1000 (57)
  • jwallwork23 (53)
  • ElliottKasoar (11)
  • TomMelt (7)
  • ma595 (4)
  • mondus (4)
  • dorchard (3)
  • IsidreMas (2)
  • niccolozanotti (2)
  • timothyas (2)
  • SimonClifford (2)
  • nckxneoro52449 (1)
  • anand-me (1)
  • christopheredsall (1)
  • siddanib (1)
Pull Request Authors
  • jwallwork23 (124)
  • jatkinson1000 (97)
  • niccolozanotti (16)
  • TomMelt (16)
  • dorchard (9)
  • ElliottKasoar (8)
  • Mikolaj-A-Kowalski (5)
  • aysha2016 (3)
  • ma595 (2)
  • danielskatz (1)
  • mondus (1)
  • helgehr (1)
  • zhenkunl (1)
  • vopikamm (1)
  • vbalmer (1)
Top Labels
Issue Labels
enhancement (37) documentation (37) bug (31) autograd (20) testing (15) good first issue (10) hackathon (9) gpu (9) question (5) build (4) online-training (4) potential placement (1) help wanted (1)
Pull Request Labels
documentation (64) enhancement (50) bug (40) autograd (38) testing (36) hackathon (9) gpu (9) good first issue (4) build (1) Hacktoberfest (1)

Dependencies

examples/n_c_and_cpp/requirements.txt pypi
  • torch *
  • torchvision *
examples/1_SimpleNet/requirements.txt pypi
  • torch *
examples/2_ResNet18/requirements.txt pypi
  • torch *
  • torchvision *
.github/workflows/python_qc.yaml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • psf/black stable composite