The tch crate wraps libtorch with thin Rust APIs for tensors, autograd, and neural network modules. It expects a compatible libtorch install or can download prebuilt binaries via features.
Overview
tch-rs exposes PyTorch’s C++ library to Rust so teams can run tensor math, training loops, and model inference without maintaining a separate C++ codebase. The API stays close to libtorch, with room for more idiomatic Rust layers on top.
Setup supports system-wide libtorch, a manual LIBTORCH path, linking against an existing Python torch install, or automatic download of CPU or CUDA builds when enabled. Examples cover basics, gradient-based training with VarStore and optimizers, MNIST training, pretrained vision models, and SafeTensors weight import.
The crate ships documentation on docs.rs and notes platform caveats such as Windows debug versus release ABI alignment and MinGW incompatibilities. Licensing is dual MIT and Apache-2.0 at the user’s choice.
Key features
- Tensor type wrapping libtorch tensors
- Automatic differentiation for training
- nn modules and VarStore variables
- Optimizer integrations such as Sgd and Adam
- SafeTensors weight import path
- Optional libtorch auto-download feature
- CUDA builds via TORCH_CUDA_VERSION
- Examples for MNIST and ResNet inference
Use cases
- Rust machine learning prototypes
- Deploying PyTorch-trained models in Rust
- GPU-accelerated tensor workloads
- Migrating training scripts from Python