Skip to content

anvil

Write numerical functions in Python, deploy as C++, Metal, or CUDA.

anvil is a code generation framework built on tinygrad that turns Python numerical functions into standalone, efficient native code. It targets optimization and optimal control workflows where you prototype in Python and deploy on embedded systems or GPUs.

Under active development

anvil is still in early development. APIs may change without notice. If you encounter issues, please open an issue on GitHub.

import anvil as av

@av.numerical_function("do_square", 1024)
def do_square(x: av.Tensor) -> av.Tensor:
    return 0.5 * x.square()

# Call from Python (JIT-compiled to native code)
import numpy as np
result = do_square(np.random.randn(1024))

# Compute sparse Jacobian automatically
from anvil.ad import spjacobian
jac_fn = spjacobian(do_square)

# Export to standalone C++ (no Python dependency)
av.generate_module("my_module", [do_square, jac_fn])

Key features

  • Automatic differentiation -- dense and sparse gradients, Jacobians, and Hessians via graph coloring
  • AOT code generation -- standalone .hpp/.cpp files with no runtime dependencies (except PIQP for solvers)
  • SQP solvers -- dense and sparse Sequential Quadratic Programming with PIQP as the QP backend, both callable from Python and exportable to C++
  • Multistage optimal control -- MultistageProblem exploits block-tridiagonal sparsity for efficient OCP solving
  • GPU acceleration -- target Metal or CUDA with the same Python code
  • JIT compilation -- lazy native compilation for zero-overhead Python calling

Installation

# with uv (recommended)
uv add git+https://github.com/PREDICT-EPFL/anvil.git
# with pip
pip install git+https://github.com/PREDICT-EPFL/anvil.git

Note

anvil is not yet published to PyPI. Install from the GitHub repository directly.

Motivation

The deep learning community has invested heavily in compilation infrastructure for high-performance numerical computation on heterogeneous hardware: XLA, IREE, MLIR, Mojo, and others. anvil brings these ideas to the optimization and optimal control community -- write your models once in Python, generate efficient native code for deployment.