ocaml-torch provides OCaml bindings for the PyTorch tensor library. This brings to OCaml NumPy-like tensor computations with GPU acceleration and tape-based automatic differentiation.
These bindings use the PyTorch C++ API and are mostly automatically generated. The current GitHub tip corresponds to PyTorch v2.3.
Torch depends on libtorch, so when you install this package, it will try linking to
libtorch depending on your environment variables.
The code for discovering libtorch is in src/config/discover.ml
.
In order to change how torch binds to libtorch, you must uninstall and reinstall torch.
To install with any of these methods, after configuring your environment, you may either
opam install torch
, orgit clone https://github.com/janestreet/torch.git
cd torch
make all
The opam libtorch package (an optional dependency) can be installed, and torch will automatically detect it and build with it. However, it might not suit your needs if you use any of these:
If you've installed libtorch via Conda, ensure that you are in the Conda environment with
the CONDA_PREFIX
set before installing.
If you have libtorch installed as a system library (e.g. RPM), set LIBTORCH_USE_SYSTEM=1
before installing.
If you have downloaded libtorch somewhere, set
LIBTORCH=/path/to/libtorch/
before installing.
ocaml-torch can be used in interactive mode via utop or ocaml-jupyter.
Here is a sample utop session:
To build a simple torch program, create a file example.ml
:
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).
Some more advanced applications from external repos:
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 sample images can the easily be done via:
dune exec examples/pretrained/predict.exe path/to/resnet18.ot images/tiger.jpg
ocaml-torch uses extensive code generation to produce bindings to thousands of torch C++ functions. Read internals.md for details.
Many thanks to @LaurentMazare for the original work of ocaml-torch.