executorch/lib.rs
1// some new clippy::lint annotations are supported in latest Rust but not recognized by older versions
2#![allow(unknown_lints)]
3#![deny(missing_docs)]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5
6//! Bindings for ExecuTorch - On-device AI across mobile, embedded and edge for PyTorch.
7//!
8//! Provides a high-level Rust API for executing PyTorch models on mobile, embedded and edge devices using the
9//! [ExecuTorch library](https://pytorch.org/executorch-overview), specifically the
10//! [C++ API](https://github.com/pytorch/executorch).
11//! PyTorch models are created and exported in Python, and then loaded and executed on-device using the
12//! ExecuTorch library.
13//!
14//! The following example create a simple model in Python, exports it, and then executes it in Rust:
15//!
16//! Create a model in Python and export it:
17//! ```ignore
18//! import torch
19//! from torch.export import export
20//! from executorch.exir import to_edge_transform_and_lower
21//!
22//! class Add(torch.nn.Module):
23//! def __init__(self):
24//! super(Add, self).__init__()
25//!
26//! def forward(self, x: torch.Tensor, y: torch.Tensor):
27//! return x + y
28//!
29//!
30//! model = Add()
31//! exported_program = export(model, (torch.ones(1), torch.ones(1)))
32//! executorch_program = to_edge_transform_and_lower(exported_program).to_executorch()
33//! with open("model.pte", "wb") as file:
34//! file.write(executorch_program.buffer)
35//! ```
36//!
37//! Execute the model in Rust:
38//! ```rust,ignore
39//! use executorch::evalue::{EValue, IntoEValue};
40//! use executorch::module::Module;
41//! use executorch::tensor_ptr;
42//! use ndarray::array;
43//!
44//! let mut module = Module::new("model.pte");
45//!
46//! let (tensor1, tensor2) = (tensor_ptr![1.0_f32], tensor_ptr![1.0_f32]);
47//! let inputs = [tensor1.into_evalue(), tensor2.into_evalue()];
48//!
49//! let outputs = module.forward(&inputs).unwrap();
50//! let [output]: [EValue; 1] = outputs.try_into().expect("not a single output");
51//! let output = output.as_tensor().into_typed::<f32>();
52//!
53//! println!("Output tensor computed: {:?}", output);
54//! assert_eq!(array![2.0], output.as_array());
55//! ```
56//!
57//! ## Cargo Features
58//! - `data-loader`:
59//! Includes additional structs in the [`data_loader`] module for loading data. Without this feature the only
60//! available data loader is [`BufferDataLoader`](data_loader::BufferDataLoader). The `libextension_data_loader.a` static library is
61//! required, compile C++ `executorch` with `EXECUTORCH_BUILD_EXTENSION_DATA_LOADER=ON`.
62//! - `module`:
63//! Includes the [`module`] API, a high-level API for loading and executing PyTorch models. It is an alternative to
64//! the lower-level [`Program`](crate::program::Program) API, which is more suitable for embedded systems.
65//! The `libextension_module_static.a` static library is required, compile C++ `executorch` with
66//! `EXECUTORCH_BUILD_EXTENSION_MODULE=ON`.
67//! Also includes the `std`, `data-loader` and `flat-tensor` features.
68//! - `tensor-ptr`:
69//! Includes the [`tensor::TensorPtr`] struct, a smart pointer for tensors that manage the lifetime of the tensor
70//! object alongside the lifetimes of the data buffer and additional metadata. The `extension_tensor.a`
71//! static library is required, compile C++ `executorch` with `EXECUTORCH_BUILD_EXTENSION_TENSOR=ON`.
72//! Also includes the `std` feature.
73//! - `flat-tensor`:
74//! Includes the [`data_map::FlatTensorDataMap`] struct that can read `.ptd` files with external tensors for models.
75//! The `libextension_flat_tensor.a` static library is required,
76//! compile C++ `executorch` with `EXECUTORCH_BUILD_EXTENSION_FLAT_TENSOR=ON`.
77//! - `etdump`:
78//! Includes the [`event_tracer::ETDumpGen`] struct, an implementation of an `EventTracer`, used for debugging and profiling.
79//! The `libetdump.a` static library is required, compile C++ `executorch` with `EXECUTORCH_BUILD_DEVTOOLS=ON` and
80//! `EXECUTORCH_ENABLE_EVENT_TRACER=ON`.
81//! In addition, the `flatcc` (or `flatcc_d`) library is required, available at `{CMAKE_DIR}/third-party/flatcc_ep/lib/`,
82//! and should be linked by the user.
83//! - `ndarray`:
84//! Conversions between `executorch` tensors and `ndarray` arrays.
85//! Adds a dependency to the `ndarray` crate.
86//! This feature is enabled by default.
87//! - `f16`:
88//! Adds a dependency to the `half` crate, which provides a fully capable `f16` and `bf16` types.
89//! Without this feature enabled, both of these types are available with a simple conversions to/from `u16` only.
90//! Note that this only affect input/output tensors, the internal computations always have the capability to operate on such scalars.
91//! - `num-complex`:
92//! Adds a dependency to the `num-complex` crate, which provides a fully capable complex number type.
93//! Without this feature enabled, complex numbers are available as a simple struct with two public fields without any operations.
94//! Note that this only affect input/output tensors, the internal computations always have the capability to operate on such scalars.
95//! - `std`:
96//! Enable the standard library. This feature is enabled by default, but can be disabled to build [`executorch`](crate)
97//! in a `no_std` environment.
98//! See the `examples/no_std` example.
99//! Also includes the `alloc` feature.
100//! NOTE: no_std is still WIP, see <https://github.com/pytorch/executorch/issues/4561>
101//! - `alloc`:
102//! Enable allocations.
103//! When this feature is disabled, all methods that require allocations will not be compiled.
104//! This feature is enabled by the `std` feature, which is enabled by default.
105//! Its possible to enable this feature without the `std` feature, and the allocations will be done using the
106//! [`alloc`](https://doc.rust-lang.org/alloc/) crate, that requires a global allocator to be set.
107//!
108//! By default the `std` and `ndarray` features are enabled.
109//!
110//! ## Build
111//! To use the library you must compile the C++ executorch library yourself, as there are many configurations that
112//! determines which modules, backends, and operations are supported. See the `executorch-sys` crate for more info.
113//! Currently the supported Cpp executorch version is `1.4.0`.
114//!
115//! ## Embedded Systems
116//! The library is designed to be used both in `std` and `no_std` environments. The `no_std` environment is useful for
117//! embedded systems, where the standard library is not available. The `alloc` feature can be used to provide an
118//! alternative to the standard library's allocator, but it is possible to use the library without allocations at all.
119//! Due to some difference between Cpp and Rust, it is not trivial to provide such API, and the interface may feel
120//! more verbose. See the `memory::Storage` struct for stack allocations of Cpp objects, and the `examples/no_std`
121//! example.
122
123#![cfg_attr(not(feature = "std"), no_std)]
124
125#[cfg(not(feature = "std"))]
126extern crate core as std;
127
128#[doc(hidden)]
129pub mod __private {
130 #[cfg(feature = "std")]
131 pub mod alloc {
132 pub use std::boxed::Box;
133 pub use std::vec::Vec;
134 }
135 #[cfg(not(feature = "std"))]
136 pub mod alloc {
137 extern crate alloc;
138 pub use alloc::boxed::Box;
139 pub use alloc::vec::Vec;
140 }
141}
142
143#[allow(unused_imports)]
144use crate::__private::alloc;
145
146/// The version of the crate.
147pub const VERSION: &str = env!("CARGO_PKG_VERSION");
148
149/// The version of the ExecuTorch C++ library that this crate is compatible and linked with.
150pub const EXECUTORCH_CPP_VERSION: &str = executorch_sys::EXECUTORCH_CPP_VERSION;
151
152#[macro_use]
153mod private;
154pub mod backend_options;
155pub mod data_loader;
156pub mod data_map;
157pub mod device;
158mod error;
159pub mod evalue;
160pub mod event_tracer;
161pub(crate) mod log;
162pub mod memory;
163#[cfg(feature = "module")]
164pub mod module;
165pub mod platform;
166pub mod program;
167pub mod scalar;
168pub mod tensor;
169pub mod util;
170
171pub use error::Error;
172pub(crate) use error::Result;
173
174#[cfg(feature = "ndarray")]
175pub use ndarray;
176
177#[cfg(feature = "half")]
178pub use half;
179
180#[cfg(feature = "num-complex")]
181pub use num_complex;
182
183#[cfg(test)]
184mod tests;