Skip to content

Commit

Permalink
add python interop example (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
ZuseZ4 authored Nov 13, 2024
1 parent bc12a59 commit 98c47b9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 35 additions & 0 deletions src/usage/python.md
Original file line number Diff line number Diff line change
@@ -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(())
}
```

0 comments on commit 98c47b9

Please sign in to comment.