{"id":51146618,"url":"https://github.com/cambridge-iccs/fortran-tf-lib","last_synced_at":"2026-06-26T03:02:32.195Z","repository":{"id":58929216,"uuid":"449653503","full_name":"Cambridge-ICCS/fortran-tf-lib","owner":"Cambridge-ICCS","description":" A library for directly calling TensorFlow / Keras ML models from Fortran. ","archived":false,"fork":false,"pushed_at":"2023-09-03T14:55:14.000Z","size":108,"stargazers_count":36,"open_issues_count":6,"forks_count":12,"subscribers_count":4,"default_branch":"main","last_synced_at":"2026-04-14T10:12:03.666Z","etag":null,"topics":["deep-learning","fortran","interoperability","keras","machine-learning","tensorflow"],"latest_commit_sha":null,"homepage":"","language":"Fortran","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Cambridge-ICCS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-01-19T10:53:40.000Z","updated_at":"2026-04-11T23:10:15.000Z","dependencies_parsed_at":"2023-02-12T02:15:16.152Z","dependency_job_id":null,"html_url":"https://github.com/Cambridge-ICCS/fortran-tf-lib","commit_stats":{"total_commits":56,"total_committers":7,"mean_commits":8.0,"dds":0.7142857142857143,"last_synced_commit":"638df9222e50cb947c697f7d9b2cc71364060cfe"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Cambridge-ICCS/fortran-tf-lib","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cambridge-ICCS%2Ffortran-tf-lib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cambridge-ICCS%2Ffortran-tf-lib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cambridge-ICCS%2Ffortran-tf-lib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cambridge-ICCS%2Ffortran-tf-lib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Cambridge-ICCS","download_url":"https://codeload.github.com/Cambridge-ICCS/fortran-tf-lib/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Cambridge-ICCS%2Ffortran-tf-lib/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34801014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-26T02:00:06.560Z","response_time":106,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","fortran","interoperability","keras","machine-learning","tensorflow"],"created_at":"2026-06-26T03:02:31.373Z","updated_at":"2026-06-26T03:02:32.134Z","avatar_url":"https://github.com/Cambridge-ICCS.png","language":"Fortran","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Fortran-TF-lib\n\n![GitHub](https://img.shields.io/github/license/Cambridge-ICCS/fortran-tf-lib)\n\nCode and examples for directly calling Tensorflow ML models from Fortran.  \nFor calling *PyTorch* from Fortran see the [FTorch repository](https://github.com/Cambridge-ICCS/fortran-pytorch-lib).\n\n## Contents\n- [Description](#description)\n- [Installation](#installation)\n- [Usage](#usage)\n- [Examples](#examples)\n- [License](#license)\n- [Contributions](#contributions)\n- [Authors and Acknowledgment](#authors-and-acknowledgment)\n- [Users](#used-by)\n\n## Description\n\nIt is desirable be able to run machine learning (ML) models directly in Fortran.\nSuch models are often trained in some other language (say Python) using popular frameworks (say TensorFlow) and saved.\nWe want to run inference on this model without having to call a Python executable.\nTo achieve this we use the existing TensorFlow C interface.\n\nThis project provides a library enabling a user to directly couple their TensorFlow models to Fortran code.\nWe provide installation instructions for the library as well as instructions and examples for performing coupling.\nThis library implements only enough of the TensorFlow C API to allow inference, no training.\n\nProject status: This project is currently in pre-release with documentation and code being prepared for a first release.\nAs such breaking changes may be made.\nIf you are interested in using this library please get in touch.\n\n\n## Installation\n\n### Dependencies\n\nTo install the library requires the following to be installed on the system:\n\n* cmake \u003e= 3.1\n* TensorFlow C API, download from \u003chttps://www.tensorflow.org/install/lang_c\u003e\u003csup\u003e1\u003c/sup\u003e\n* Fortran and C compilers\n\n\u003csup\u003e1\u003c/sup\u003e Note that this page sometimes does not list the latest version of\nthe library.  You can try altering the library download URLs on the page to\nreflect the newest version.  E.g. if the URL ends `...-2.11.tar.gz` try\nchanging it to `...-2.13.tar.gz`.\n\n### Library installation\n\nTo build and install the library:\n\n1. Navigate to the location in which you wish to install the source and run:  \n    ```\n    git clone git@github.com:Cambridge-ICCS/fortran-tf-lib.git\n    ```\n    to clone via ssh, or  \n    ```\n    git clone https://github.com/Cambridge-ICCS/fortran-tf-lib.git\n    ```\n    to clone via https.  \n2. Navigate into the library directory by running:  \n    ```\n    cd fortran-tf-lib/fortran-tf-lib/\n    ```\n3. Create a `build` directory and execute cmake from within it using the relevant flags:  \n    ```\n    mkdir build\n    cd build\n    cmake .. -DCMAKE_BUILD_TYPE=Release\n    ```\n    It is likely that you will need to provide at least the `TENSORFLOW_LOCATION` flag.  \n    The Fortran compiler must be the same one that you are planning to compile your Fortran\n    code with.  It is advisable to use C and Fortran compilers from the same provider.\n\n    The following CMake flags are available and can be passed as arguments through `-D\u003cOption\u003e=\u003cValue\u003e`:\n    | Option                                                                                            | Value                        | Description                                                   |\n    | ------------------------------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------|\n    | [`CMAKE_Fortran_COMPILER`](https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_COMPILER.html) | `ifort` / `gfortran`         | 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.        |\n    | [`CMAKE_C_COMPILER`](https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_COMPILER.html)       | `icc` / `gcc`                | Specify a C compiler to build the library with.                |\n    | `TENSORFLOW_LOCATION`\u003csup\u003e2\u003c/sup\u003e   | `\u003c/path/to/tensorflow/\u003e`          | Location of TensorFlow C API installation\u003csup\u003e1\u003c/sup\u003e. |\n    | [`CMAKE_INSTALL_PREFIX`](https://cmake.org/cmake/help/latest/variable/CMAKE_INSTALL_PREFIX.html)  | `\u003c/path/to/install/lib/at/\u003e` | Location at which the library files should be installed. By default this is `/usr/local`. |\n    | [`CMAKE_BUILD_TYPE`](https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html)          | `Release` / `Debug`          | Specifies build type. The default is `Debug`, use `Release` for production code.|\n\n    \u003csup\u003e2\u003c/sup\u003e This should be the absolute path to where the TensorFlow C API mentioned in step 1 has been installed. CMake will look in `TENSORFLOW_LOCATION` and `TENSORFLOW_LOCATION/lib` for the TensorFlow library `libtensorflow.so`.\n4. Make and install the code to the chosen location with:\n    ```\n    make\n    make install\n    ```\n    This will place the following directories at the install location:  \n    * `CMAKE_INSTALL_PREFIX/include/` - contains mod files\n    * `CMAKE_INSTALL_PREFIX/lib64/` - contains `cmake` directory and `.so` files\n\n\n## Usage\n\nIn order to use fortran-tf users will typically need to follow these steps:\n\n1. Save a TensorFlow model in the Keras SavedModel format.\n2. Write Fortran using the fortran-tf-lib bindings to use the model from within Fortran.\n3. Build and compile the code, linking against fortran-tf-lib.\n\n\n### 1. Saving the model\n\nThe trained model needs to be exported.  This can be done from within your code\nusing the\n[`model.save`](https://www.tensorflow.org/guide/keras/serialization_and_saving)\nfunctionality from within python.  Note that the TensorFlow C API currently\n(version 2.13) only supports the Keras \"v2\" format so you must specify `format='tf'`:\n```\nimport tensorflow as tf\n# construct model (e.g. model=tf.keras.Model(inputs, outputs))\n# or load one (e.g. model=tf.keras.models.load_model('/path/to/model'))\nmodel.save(\"my_model\", format='tf')\n```\n\n### 2. Using the model from Fortran\n\nTo use the trained TensorFlow model from within Fortran we need to import the\n`TF_Interface` module and use the binding routines to load the model, construct\nthe tensors, and run inference.\n\nA very simple example is given below.  For more detailed documentation please\nconsult the API documentation, source code, and examples.\n\nThis minimal snippet loads a saved TensorFlow model, creates an input consisting of\na `1x32` matrix (with arbitrary values), and runs the model to infer the\noutput.  If you use the model provided in the test case this code will produce\nthe indicated output value.\n\n```fortran\nprogram test_program\nuse TF_Types\nuse TF_Interface\nuse iso_c_binding\nimplicit none\n\ntype(TF_Session) :: session\ntype(TF_SessionOptions) :: sessionoptions\ntype(TF_Graph) :: graph\ntype(TF_Status) :: stat\ntype(TF_Output), dimension(1) :: input_tfoutput, output_tfoutput\ncharacter(100) :: vers\ncharacter(100), dimension(1) :: tags\ntype(TF_Tensor), dimension(1) :: input_tensors, output_tensors, test_tensor\ntype(TF_Operation), dimension(1) :: target_opers\n\nreal, dimension(32), target :: raw_data\nreal, dimension(:), pointer :: output_data_ptr\ninteger(kind=c_int64_t), dimension(2) :: input_dims\ninteger(kind=c_int64_t), dimension(2) :: output_dims\ntype(c_ptr) :: raw_data_ptr\ntype(c_ptr) :: output_c_data_ptr\n\nraw_data = (/ \u0026\n        0.71332126, 0.81275973, 0.66596436, 0.79570779, 0.83973302, 0.76604397, \u0026\n        0.84371391, 0.92582056, 0.32038017, 0.0732005, 0.80589203, 0.75226581, \u0026\n        0.81602784, 0.59698078, 0.32991729, 0.43125108, 0.4368422, 0.88550326, \u0026\n        0.7131253, 0.14951148, 0.22084413, 0.70801317, 0.69433906, 0.62496564, \u0026\n        0.50744999, 0.94047845, 0.18191579, 0.2599102, 0.53161889, 0.57402205, \u0026\n        0.50751284, 0.65207096 \u0026\n        /)\n\n\ninput_dims = (/ 1, 32 /)\noutput_dims = (/ 1, 1 /)\ntags(1) = 'serve'\n\n! Print TensorFlow library version\ncall TF_Version(vers)\nwrite(*,*)'Tensorflow version', vers\n\nsessionoptions = TF_NewSessionOptions()\ngraph = TF_NewGraph()\nstat = TF_NewStatus()\n\n! Load session (also populates graph)\nsession = TF_LoadSessionFromSavedModel(sessionoptions, '/path/to/model', tags, 1, \u0026\n    graph, stat)\n\nif (TF_GetCode( stat ) .ne. TF_OK) then\n    call TF_Message( stat, vers )\n    write(*,*)'woops', TF_GetCode( stat ), vers\n    call abort\nendif\n\ncall TF_DeleteSessionOptions(sessionoptions)\n\ninput_tfoutput(1)%oper = TF_GraphOperationByName( graph, \"serving_default_input_1\" )\ninput_tfoutput(1)%index = 0\nif (.not.c_associated(input_tfoutput(1)%oper%p)) then\n    write(*,*)'input not associated'\n    stop\nendif\n\noutput_tfoutput(1)%oper = TF_GraphOperationByName( graph, \"StatefulPartitionedCall\" )\noutput_tfoutput(1)%index = 0\nif (.not.c_associated(output_tfoutput(1)%oper%p)) then\n    write(*,*)'output not associated'\n    stop\nendif\n\n! Bind the input tensor\nraw_data_ptr = c_loc(raw_data)\ninput_tensors(1) = TF_NewTensor( TF_FLOAT, input_dims, 2, raw_data_ptr, int(128, kind=c_size_t) )\n\n! Run inference\ncall TF_SessionRun( session, input_tfoutput, input_tensors, 1, output_tfoutput, output_tensors, 1, \u0026\n    target_opers, 0, stat )\nif (TF_GetCode( stat ) .ne. TF_OK) then\n    call TF_Message( stat, vers )\n    write(*,*) TF_GetCode( stat ), vers\n    call abort\nendif\n\n! Bind output tensor\ncall c_f_pointer( TF_TensorData( output_tensors(1)), output_data_ptr, shape(output_data_ptr) )\nwrite(*,*)'output data', output_data_ptr(1)\n\nif ((output_data_ptr(1) - -0.479371) .gt. 1e-6) then\n    write(*,*)'Output does not match, FAILED!'\nelse\n    write(*,*)'Output is correct, SUCCESS!'\nendif\n\n\n! Clean up\ncall TF_DeleteTensor( input_tensors(1) )\ncall TF_DeleteTensor( output_tensors(1) )\ncall TF_DeleteGraph( graph )\ncall TF_DeleteSession( session, stat )\ncall TF_DeleteStatus( stat )\n\nend program test_program\n```\n#### Generating code with `process_model`\nThe example code above illustrates a problem with the TensorFlow C API\nthat our Fortran wrapper cannot fix.  To load a model, the library requires\nthat the caller knows certain rather opaque model parameters beforehand.\nOften, the values in the example above will work for the `tags` parameter\nto `TF_LoadSessionFromSavedModel`.  However, the values needed for\n`TF_GraphOperationByName` (in this case `serving_default_input_1`, etc)\nare more likely to be different.\n\nTo address this, we provide a Python script, `process_model` that will\nread a Keras SavedModel and output a simple Fortran module intended to\nprovide a base for the user to start from.  The appropriate values will\nbe read from the model and hard-coded into the Fortran code.\n\nE.g.\n```\nprocess_model -o fortran_code.f90  my_model\n```\n\n### 3. Build the code\n\nThe code now needs to be compiled and linked against our installed library.\n\n#### CMake\nIf our project were using cmake we would need the following in the\n`CMakeLists.txt` file to find the the tf-lib installation and link it to the\nexecutable.\n\nThis can be done by adding the following to the `CMakeLists.txt` file:\n```\nfind_package(FortranTensorFlow)\ntarget_link_libraries( \u003cexecutable\u003e PRIVATE FortranTensorFlow::fortran-tf )\nmessage(STATUS \"Building with Fortran TensorFlow coupling\")\n```\nand using the `-DCMAKE_PREFIX=\u003c/path/to/fortran-tf-libs/lib64/cmake\u003e` flag when running cmake.\n\nWhen running the generated code you may also need to add the location of the\n`.so` files to your `LD_LIBRARY_PATH` unless installing in a default location:\n```\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\u003cpath/to/fortran-tf-libs\u003e/lib64\n```\n\n## Examples\n\nExamples of how to use this library will be provided in the [examples directory](examples/).  \nThey demonstrate different functionalities and are provided with instructions to modify, build, and run as necessary.\n\n## License\n\nCopyright \u0026copy; ICCS\n\n*Fortran-TF-Lib* is distributed under the [MIT Licence](https://github.com/Cambridge-ICCS/fortran-tf-lib/blob/main/LICENSE).\n\n\n## Contributions\n\nContributions and collaborations are welcome.\n\nFor bugs, feature requests, and clear suggestions for improvement please\n[open an issue](https://github.com/Cambridge-ICCS/fortran-tf-lib/issues).\n\nIf you have built something upon _Fortran-TF-Lib_ that would be useful to others, or can\naddress an [open issue](https://github.com/Cambridge-ICCS/fortran-tf-lib/issues), please\n[fork the repository](https://github.com/Cambridge-ICCS/fortran-tf-lib/fork) and open a\npull request.\n\n\n### Code of Conduct\nEveryone participating in the _Fortran-TF-Lib_ project, and in particular in the\nissue tracker, pull requests, and social media activity, is expected to treat other\npeople with respect and, more generally, to follow the guidelines articulated in the\n[Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/).\n\n\n## Authors and Acknowledgment\n\n*Fortran-TF-Lib* is written and maintained by the [ICCS](https://github.com/Cambridge-ICCS)\n\nNotable contributors to this project are:\n\n* [**@SimonClifford**](https://github.com/SimonClifford)\n\nSee [Contributors](https://github.com/Cambridge-ICCS/fortran-tf-lib/graphs/contributors)\nfor a full list.\n\n\n## Used by\nThe following projects make use of this code or derivatives in some way:\n\n* [DataWave - MiMA ML](https://github.com/DataWaveProject/MiMA-machine-learning)\n\nAre we missing anyone? Let us know.\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcambridge-iccs%2Ffortran-tf-lib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcambridge-iccs%2Ffortran-tf-lib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcambridge-iccs%2Ffortran-tf-lib/lists"}