• Stars
    star
    283
  • Rank 146,066 (Top 3 %)
  • Language
    OCaml
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

OCaml bindings for TensorFlow

The tensorflow-ocaml project provides some OCaml bindings for TensorFlow.

Experimental ocaml bindings for PyTorch can be found in the ocaml-torch repo.

Installation

Use opam to install the tensorflow-ocaml package. Starting from version 0.0.11 this will automatically install the TensorFlow library.

opam install tensorflow

Build a simple example or run utop

To build your first TensorFlow program, create a new directory and cd into it. Then create a forty_two.ml file with the following content:

open Tensorflow

let () =
  let forty_two = Ops.(f 40. + f 2.) in
  let v = Session.run (Session.Output.scalar_float forty_two) in
  Printf.printf "%f\n%!" v

Then create a dune file with the following content:

(executables
  (names forty_two)
  (libraries tensorflow))

Run dune build forty_two.exe to compile the program and _build/default/forty_two.exe to run it!

You can also use Tensorflow via utop.

utop

Optional step for GPU support

The TensorFlow library installed via opam does not support GPU acceleration. In order to use your GPU you will have to install TensorFlow 1.14, either by building it from source or by using prebuilt binaries. Then the library should be installed system-wide or you could set the LIBTENSORFLOW environment variable.

    export LIBTENSORFLOW={path_to_folder_with_libtensorflow.so}

Possible ways to get the TensorFlow library:

  • Use prebuilt binaries from Google. The releases are available for download in URLs of the form: https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-TYPE-OS-ARCH-VERSION.tar.gz. For example:

  • Build the library from source. Perform the following steps:

    1. Install the Bazel build system.

    2. Clone the TensorFlow repo:

      git clone --recurse-submodules -b r1.14 https://github.com/tensorflow/tensorflow

    3. Configure the build (you will be asked if you want to enable CUDA support):

      cd tensorflow/
      ./configure
      
    4. Compile the library:

      bazel build -c opt tensorflow:libtensorflow.so

      The binary should appear under bazel-bin/tensorflow/libtensorflow.so.

Examples

Tensorflow-ocaml includes two different APIs to write graphs.

Using the Graph API

The graph API is very close to the original TensorFlow API.

  • Some MNIST based tutorials are available in the examples directory. A simple Convolutional Neural Network can be defined as follows:

    let ys_ =
      O.Placeholder.to_node xs
      |> Layer.reshape ~shape:[ -1; 28; 28; 1 ]
      |> Layer.conv2d ~ksize:(5, 5) ~strides:(1, 1) ~output_dim:32
      |> Layer.max_pool ~ksize:(2, 2) ~strides:(2, 2)
      |> Layer.conv2d ~ksize:(5, 5) ~strides:(1, 1) ~output_dim:64
      |> Layer.max_pool ~ksize:(2, 2) ~strides:(2, 2)
      |> Layer.flatten
      |> Layer.linear ~output_dim:1024 ~activation:Relu
      |> O.dropout ~keep_prob:(O.Placeholder.to_node keep_prob)
      |> Layer.linear ~output_dim:10 ~activation:Softmax
    in
  • examples/load/load.ml contains a simple example where the TensorFlow graph is loaded from a file (this graph has been generated by examples/load.py),

  • examples/basics contains some curve fitting examples. You will need gnuplot to be installed via opam to run the gnuplot versions.

Using the FNN API

The FNN API is a layer based API to easily build neural-networks. A linear classifier could be defined and trained in a couple lines:

  let input, input_id = Fnn.input ~shape:(D1 image_dim) in
  let model =
    Fnn.dense label_count input
    |> Fnn.softmax
    |> Fnn.Model.create Float
  in
  Fnn.Model.fit model
    ~loss:(Fnn.Loss.cross_entropy `mean)
    ~optimizer:(Fnn.Optimizer.gradient_descent ~learning_rate:8.)
    ~epochs
    ~input_id
    ~xs:train_images
    ~ys:train_labels;

A complete VGG-19 model can be defined as follows:

let vgg19 () =
  let block iter ~block_idx ~out_channels x =
    List.init iter ~f:Fn.id
    |> List.fold ~init:x ~f:(fun acc idx ->
      Fnn.conv2d () acc
        ~name:(sprintf "conv%d_%d" block_idx (idx+1))
        ~w_init:(`normal 0.1) ~filter:(3, 3) ~strides:(1, 1) ~padding:`same ~out_channels
      |> Fnn.relu)
    |> Fnn.max_pool ~filter:(2, 2) ~strides:(2, 2) ~padding:`same
  in
  let input, input_id = Fnn.input ~shape:(D3 (img_size, img_size, 3)) in
  let model =
    Fnn.reshape input ~shape:(D3 (img_size, img_size, 3))
    |> block 2 ~block_idx:1 ~out_channels:64
    |> block 2 ~block_idx:2 ~out_channels:128
    |> block 4 ~block_idx:3 ~out_channels:256
    |> block 4 ~block_idx:4 ~out_channels:512
    |> block 4 ~block_idx:5 ~out_channels:512
    |> Fnn.flatten
    |> Fnn.dense ~name:"fc6" ~w_init:(`normal 0.1) 4096
    |> Fnn.relu
    |> Fnn.dense ~name:"fc7" ~w_init:(`normal 0.1) 4096
    |> Fnn.relu
    |> Fnn.dense ~name:"fc8" ~w_init:(`normal 0.1) 1000
    |> Fnn.softmax
    |> Fnn.Model.create Float
  in
  input_id, model

This model is used in the following example to classify an input image. In order to use it you will have to download the pre-trained weights.

There are also some MNIST based examples.

Other Examples

The examples directory contains various models among which:

  • A simplified version of char-rnn illustrating character level language modeling using Recurrent Neural Networks.
  • Neural Style Transfer applies the style of an image to the content of another image. This uses some deep Convolutional Neural Network.
  • Some variants of Generative Adversarial Networks. These are used to generate MNIST like images.

Dependencies

  • dune is used as a build system.
  • ocaml-ctypes is used for the C bindings.
  • Base is only necessary when generating the TensorFlow graph from OCaml, the wrapper itself does not need it.
  • The code in the piqi directory comes from the Piqi project. There is no need to install piqi though.
  • Cmdliner is used for command line interfaces.
  • Gnuplot-ocaml is an optional dependency used by a couple examples.
  • npy-ocaml is used to read/write from npy/npz files.

More Repositories

1

tch-rs

Rust bindings for the C++ api of PyTorch.
Rust
4,162
star
2

diffusers-rs

An implementation of the diffusers api in Rust
Rust
521
star
3

ocaml-torch

OCaml bindings for PyTorch
OCaml
412
star
4

deep-models

Implementation of a couple deep learning models using TensorFlow
Python
145
star
5

mamba.rs

Rust
121
star
6

xla-rs

Experimentation using the xla compiler from rust
Rust
87
star
7

npy-ocaml

Numpy file format support for ocaml.
OCaml
41
star
8

ocaml-arrow

OCaml
34
star
9

ocaml-rust

Safe OCaml-Rust Foreign Function Interface
Rust
34
star
10

ocaml-wasmtime

OCaml WebAssembly runtime powered by Wasmtime
OCaml
34
star
11

tch-ext

Sample Python extension using Rust/PyO3/tch to interact with PyTorch
Rust
31
star
12

ocaml-matplotlib

Plotting for ocaml based on matplotlib.pyplot
OCaml
30
star
13

btc-ocaml

A toy implementation of the bitcoin protocol in ocaml.
OCaml
29
star
14

ocaml-xla

XLA (Accelerated Linear Algebra) bindings for OCaml
OCaml
28
star
15

ocaml-dataframe

Simple and type-safe dataframe api implemented in pure ocaml
OCaml
25
star
16

ocaml-bert

Transformer-based models for Natural Language Processing in OCaml
OCaml
23
star
17

binprot-rs

Bin_prot binary protocols in Rust
Rust
19
star
18

ocaml-onnx

OCaml ONNX runtime powered by onnxruntime
C
18
star
19

ocaml-tqdm

An ocaml progress bar library similar to https://tqdm.github.io
OCaml
17
star
20

rsexp

S-expression parsing and writing in Rust
Rust
17
star
21

sphn

python bindings for symphonia/opus - read various audio formats from python and write opus files
Rust
16
star
22

tboard-rs

Read and write tensorboard data using Rust
Rust
16
star
23

ProjectEuler

Python
15
star
24

glim

Rust
15
star
25

ocaml-minipy

Naive interpreter for a Python like language
OCaml
13
star
26

syncarp

An async rpc implementation based on tokio and compatible with OCaml Async_rpc
Rust
12
star
27

ocaml.jl

Prototype code for some Julia-OCaml bindings
OCaml
12
star
28

ocaml-tensorflow-eager

OCaml bindings for TensorFlow Eager mode
OCaml
11
star
29

wtensor

Experiments around a webgpu based tensor library
Rust
9
star
30

hojo

A small python library to run iterators in a separate process
Rust
9
star
31

LaurentMazare.github.io

JavaScript
8
star
32

timens-rs

Simple and efficient time representation in Rust.
Rust
7
star
33

ocaml-smbus

C
6
star
34

cmt-fun

OCaml
6
star
35

serde-binprot

Rust binprot serialization using serde
Rust
6
star
36

ocaml-jupyter-async

An OCaml kernel for Jupyter using async.
OCaml
5
star
37

jax-flash-attn2

JAX bindings for the flash-attention2 kernels
C++
5
star
38

jax-flash-attn3

JAX bindings for the flash-attention3 kernels
C++
5
star
39

openai-gym-ocaml

OCaml
4
star
40

ocaml-tensorboard

Write tensorboard compatible log files from ocaml
OCaml
4
star
41

ocaml-rust-stubs

OCaml
4
star
42

ocaml-rpi-gpio

ocaml api for raspberry pi gpio access
C
3
star
43

ocaml-gym

Bindings for OpenAI Gym using the Python C API
OCaml
3
star
44

ogg-table

Ogg-vorbis reader with fast random access
Rust
3
star
45

ocaml-rplidar

RPLidar A1M8 ocaml library
OCaml
2
star
46

ocamldate

Very simple ocaml date implementation
OCaml
1
star