diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 15239a1..f3628c1 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -8,6 +8,7 @@ - [Forward Mode](./usage/fwd.md) - [Reverse Mode](./usage/rev.md) - [Higher Order Derivatives](./usage/higher.md) + - [Python Integration](./usage/python.md) - [Current Limitations](./limitations.md) - [Future Work](./future_work.md) - [History and ecosystem](./ecosystem.md) diff --git a/src/usage/python.md b/src/usage/python.md new file mode 100644 index 0000000..ef6e48a --- /dev/null +++ b/src/usage/python.md @@ -0,0 +1,35 @@ +### Python Integration + +std::autodiff is fully handled by the Rust compiler and therefore should not cause any issues with Python integration. +An example for maturin/PyO3 is provided below. You will still need to enable `lto=fat` in your Cargo.toml and adjust +the module name to match your project, otherwise python won't be able to find your functions. +The first `#[pyfunction]` macro will only be applied to the original function `f`. +We therefore add a small wrapper function `df_py` and apply the `#[pyfunction]` macro to it. + +```toml + +```rs +#![feature(autodiff)] +use std::autodiff::autodiff; +use pyo3::prelude::*; + +#[pyfunction] +#[autodiff(df, Reverse, Active, Active)] +fn f(x: f32) -> f32 { + x * x +} + +// Will return x*x and 2*x +#[pyfunction] +fn df_py(x: f32) -> (f32, f32) { + df(x, 1.0) +} + +// Remember to adjust the name of the module to match your project +#[pymodule] +fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_function(wrap_pyfunction!(f_py, m)?)?; + m.add_function(wrap_pyfunction!(df_py, m)?)?; + Ok(()) +} +```