• Stars
    star
    412
  • Rank 105,024 (Top 3 %)
  • Language
    OCaml
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

OCaml bindings for PyTorch

Warning

Development for this repo has moved to https://github.com/janestreet/torch As of 2023-05-10, the version in the new repo only supports PyTorch 1.13.0 so you should continue using the old repo for PyTorch 2.0.0 support.

ocaml-torch

ocaml-torch provides some ocaml bindings for the PyTorch tensor library. This brings to OCaml NumPy-like tensor computations with GPU acceleration and tape-based automatic differentiation.

Main workflow

These bindings use the PyTorch C++ API and are mostly automatically generated. The current GitHub tip and the opam package v0.7 corresponds to PyTorch v2.0.0.

On Linux note that you will need the PyTorch version using the cxx11 abi cpu version, cuda 11.7 version.

Opam Installation

The opam package can be installed using the following command. This automatically installs the CPU version of libtorch.

opam install torch

You can then compile some sample code, see some instructions below. ocaml-torch can also be used in interactive mode via utop or ocaml-jupyter.

Here is a sample utop session.

utop

Build a Simple Example

To build a first torch program, create a file example.ml with the following content.

open Torch

let () =
  let tensor = Tensor.randn [ 4; 2 ] in
  Tensor.print tensor

Then create a dune file with the following content:

(executables
  (names example)
  (libraries torch))

Run dune exec example.exe to compile the program and run it!

Alternatively you can first compile the code via dune build example.exe then run the executable _build/default/example.exe (note that building the bytecode target example.bc may not work on macos).

Tutorials and Examples

Some more advanced applications from external repos:

Sample Code

Below is an example of a linear model trained on the MNIST dataset (full code).

  (* Create two tensors to store model weights. *)
  let ws = Tensor.zeros [image_dim; label_count] ~requires_grad:true in
  let bs = Tensor.zeros [label_count] ~requires_grad:true in

  let model xs = Tensor.(mm xs ws + bs) in
  for index = 1 to 100 do
    (* Compute the cross-entropy loss. *)
    let loss =
      Tensor.cross_entropy_for_logits (model train_images) ~targets:train_labels
    in

    Tensor.backward loss;

    (* Apply gradient descent, disable gradient tracking for these. *)
    Tensor.(no_grad (fun () ->
        ws -= grad ws * f learning_rate;
        bs -= grad bs * f learning_rate));

    (* Compute the validation error. *)
    let test_accuracy =
      Tensor.(argmax ~dim:(-1) (model test_images) = test_labels)
      |> Tensor.to_kind ~kind:(T Float)
      |> Tensor.sum
      |> Tensor.float_value
      |> fun sum -> sum /. test_samples
    in
    printf "%d %f %.2f%%\n%!" index (Tensor.float_value loss) (100. *. test_accuracy);
  done
  • Some ResNet examples on CIFAR-10.
  • 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.

Models and Weights

Various pre-trained computer vision models are implemented in the vision library. The weight files can be downloaded at the following links:

Running the pre-trained models on some sample images can the easily be done via the following commands.

dune exec examples/pretrained/predict.exe path/to/resnet18.ot tiger.jpg

Alternative Installation Option

This alternative way to install ocaml-torch could be useful to run with GPU acceleration enabled.

The libtorch library can be downloaded from the PyTorch website (2.0.0 cpu version).

Download and extract the libtorch library then to build all the examples run:

export LIBTORCH=/path/to/libtorch
git clone https://github.com/LaurentMazare/ocaml-torch.git
cd ocaml-torch
make all

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

tensorflow-ocaml

OCaml bindings for TensorFlow
OCaml
283
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