Skip to main content

hanzo_ml/
lib.rs

1//! ML framework for Rust
2//!
3//! ```rust
4//! use hanzo_ml::{Tensor, DType, Device};
5//! # use hanzo_ml::Error;
6//! # fn main() -> Result<(), Error>{
7//!
8//! let a = Tensor::arange(0f32, 6f32, &Device::Cpu)?.reshape((2, 3))?;
9//! let b = Tensor::arange(0f32, 12f32, &Device::Cpu)?.reshape((3, 4))?;
10//! let c = a.matmul(&b)?;
11//!
12//! # Ok(())}
13//! ```
14//!
15//! ## Features
16//!
17//! - Simple syntax (looks and feels like PyTorch)
18//! - CPU and Cuda backends (and M1 support)
19//! - Enable serverless (CPU) small and fast deployments
20//! - Model training
21//! - Distributed computing (NCCL).
22//! - Models out of the box (Llama, Whisper, Falcon, ...)
23//!
24//! ## FAQ
25//!
26//! - Why Hanzo?
27//!
28//! Hanzo stems from the need to reduce binary size in order to *enable serverless*
29//! possible by making the whole engine smaller than PyTorch very large library volume
30//!
31//! And simply *removing Python* from production workloads.
32//! Python can really add overhead in more complex workflows and the [GIL](https://www.backblaze.com/blog/the-python-gil-past-present-and-future/) is a notorious source of headaches.
33//!
34//! Rust is cool, and a lot of the HF ecosystem already has Rust crates [safetensors](https://github.com/huggingface/safetensors) and [tokenizers](https://github.com/huggingface/tokenizers)
35//!
36//! ## Other Crates
37//!
38//! Hanzo consists of a number of crates. This crate holds core the common data structures but you may wish
39//! to look at the docs for the other crates which can be found here:
40//!
41//! - [hanzo-ml](https://docs.rs/hanzo-ml/). Core Datastructures and DataTypes.
42//! - [hanzo-nn](https://docs.rs/hanzo-nn/). Building blocks for Neural Nets.
43//! - [hanzo-datasets](https://docs.rs/hanzo-datasets/). Rust access to commonly used Datasets like MNIST.
44//! - [hanzo-ml-examples](https://docs.rs/hanzo-ml-examples/). Examples of Hanzo in Use.
45//! - [hanzo-onnx](https://docs.rs/hanzo-onnx/). Loading and using ONNX models.
46//! - [hanzo-ml-pyo3](https://docs.rs/hanzo-ml-pyo3/). Access to Hanzo from Python.
47//! - [hanzo-transformers](https://docs.rs/hanzo-transformers/). Hanzo implementation of many published transformer models.
48//!
49
50#[cfg(feature = "accelerate")]
51mod accelerate;
52pub mod backend;
53pub mod backprop;
54pub mod conv;
55mod convert;
56pub mod cpu;
57pub mod cpu_backend;
58#[cfg(feature = "cuda")]
59pub mod cuda_backend;
60mod custom_op;
61mod device;
62pub mod display;
63mod dtype;
64pub mod dummy_cuda_backend;
65pub mod dummy_dtype;
66mod dummy_metal_backend;
67pub mod dummy_vulkan_backend;
68pub mod dummy_wgpu_backend;
69pub mod error;
70mod indexer;
71pub mod layout;
72#[cfg(feature = "metal")]
73pub mod metal_backend;
74#[cfg(feature = "mkl")]
75mod mkl;
76pub mod model_delta;
77pub mod npy;
78pub mod op;
79pub mod pickle;
80pub mod quantized;
81#[cfg(feature = "rocm")]
82pub mod rocm_backend;
83pub mod safetensors;
84pub mod scalar;
85pub mod shape;
86mod sort;
87mod storage;
88pub mod streaming;
89mod strided_index;
90mod tensor;
91mod tensor_cat;
92pub mod test_utils;
93pub mod utils;
94mod variable;
95#[cfg(feature = "vulkan")]
96pub mod vulkan_backend;
97#[cfg(feature = "wgpu")]
98pub mod wgpu_backend;
99
100#[cfg(feature = "cudnn")]
101pub use cuda_backend::cudnn;
102
103pub use cpu_backend::{CpuStorage, CpuStorageRef};
104#[cfg(feature = "ug")]
105pub use custom_op::UgIOp1;
106pub use custom_op::{CustomOp1, CustomOp2, CustomOp3, InplaceOp1, InplaceOp2, InplaceOp3};
107pub use device::{Device, DeviceLocation, NdArray};
108pub use dtype::{DType, DTypeParseError, FloatDType, IntDType, WithDType};
109pub use dummy_dtype::{F4, F6E2M3, F6E3M2, F8E8M0};
110pub use error::{Context, Error, Result};
111pub use indexer::{IndexOp, TensorIndexer};
112pub use layout::Layout;
113pub use shape::{Shape, D};
114pub use storage::Storage;
115pub use streaming::{StreamTensor, StreamingBinOp, StreamingModule};
116pub use strided_index::{StridedBlocks, StridedIndex};
117pub use tensor::{Tensor, TensorId};
118pub use variable::Var;
119
120#[cfg(feature = "cuda")]
121pub use cuda_backend as cuda;
122
123#[cfg(not(feature = "cuda"))]
124pub use dummy_cuda_backend as cuda;
125
126pub use cuda::{CudaDevice, CudaStorage};
127
128#[cfg(feature = "metal")]
129pub use metal_backend::{MetalDevice, MetalError, MetalStorage};
130
131#[cfg(not(feature = "metal"))]
132pub use dummy_metal_backend::{MetalDevice, MetalError, MetalStorage};
133
134#[cfg(feature = "rocm")]
135pub use rocm_backend::{RocmDevice, RocmError, RocmQuantType, RocmStorage};
136
137#[cfg(feature = "vulkan")]
138pub use vulkan_backend as vulkan;
139
140#[cfg(not(feature = "vulkan"))]
141pub use dummy_vulkan_backend as vulkan;
142
143pub use vulkan::{VulkanDevice, VulkanStorage};
144
145#[cfg(feature = "vulkan")]
146pub use vulkan::{PagedAttnArgs, ReshapeCacheArgs};
147
148// `wgpu_be` alias to avoid clashing with the `wgpu` crate name.
149#[cfg(feature = "wgpu")]
150pub use wgpu_backend as wgpu_be;
151
152#[cfg(not(feature = "wgpu"))]
153pub use dummy_wgpu_backend as wgpu_be;
154
155pub use wgpu_be::{WgpuDevice, WgpuStorage};
156
157#[cfg(feature = "mkl")]
158extern crate intel_mkl_src;
159
160#[cfg(feature = "accelerate")]
161extern crate accelerate_src;
162
163pub trait ToUsize2 {
164    fn to_usize2(self) -> (usize, usize);
165}
166
167impl ToUsize2 for usize {
168    fn to_usize2(self) -> (usize, usize) {
169        (self, self)
170    }
171}
172
173impl ToUsize2 for (usize, usize) {
174    fn to_usize2(self) -> (usize, usize) {
175        self
176    }
177}
178
179/// Defining a module with forward method using a single argument.
180pub trait Module {
181    fn forward(&self, xs: &Tensor) -> Result<Tensor>;
182}
183
184impl<T: Fn(&Tensor) -> Result<Tensor>> Module for T {
185    fn forward(&self, xs: &Tensor) -> Result<Tensor> {
186        self(xs)
187    }
188}
189
190impl<M: Module> Module for Option<&M> {
191    fn forward(&self, xs: &Tensor) -> Result<Tensor> {
192        match self {
193            None => Ok(xs.clone()),
194            Some(m) => m.forward(xs),
195        }
196    }
197}
198
199/// A single forward method using a single single tensor argument and a flag to
200/// separate the training and evaluation behaviors.
201pub trait ModuleT {
202    fn forward_t(&self, xs: &Tensor, train: bool) -> Result<Tensor>;
203}
204
205impl<M: Module> ModuleT for M {
206    fn forward_t(&self, xs: &Tensor, _train: bool) -> Result<Tensor> {
207        self.forward(xs)
208    }
209}