l4casadi
repository·main·Indexed 20 days ago
https://github.com/tim-salzmann/l4casadiA framework for integrating differentiable PyTorch models into CasADi-based numerical optimization. It enables data-driven control and optimization with hardware acceleration (GPU), supporting C++ and Matlab integration. Version 2.0.0 introduces batching support and updated input shape handling. The library also includes 'Real-time L4CasADi' for Neural-MPC using first- or second-order Taylor approximations, which can be integrated into Acados MPC workflows.
What's inside l4casadi
- L4CasADi is a framework that enables the seamless integration of PyTorch-learned models with CasADi for efficient numerical optimization. It allows you to use differentiable and traceable PyTorch models within CasADi optimization problems, potentially leveraging hardware acceleration (GPU).
What is Real-time L4CasADi?
mainReal-time L4CasADi is a framework designed to enable Real-time Neural-MPC (Model Predictive Control). It provides a template to approximate a PyTorch model within CasADi using first-order or second-order Taylor Approximations.
Key features include:
- Taylor Approximations: Approximates PyTorch models as first- or second-order Taylor expansions for use in optimization.
- Efficient Updates: Users update the approximation via a Python interface. The parameters required for these updates can be computed in parallel in PyTorch, potentially on a GPU.
- Scalability: This approach is efficient for large models where multiple approximations are required in parallel, such as in MPC with multiple shooting nodes.
When to use NaiveL4CasADiModule
mainL4CasADi provides
NaiveL4CasADiModulefor very small, simple models (e.g., Multi-Layer Perceptrons). This module recreates the PyTorch graph using pure CasADi operations, avoiding the overhead of context switches to Torch.Recommendation:
- Use
NaiveL4CasADiModulefor networks smaller than three hidden layers with 64 neurons each. - Use standard
L4CasADifor larger models where the Torch overhead becomes negligible.
- Use
Handle multi-input multi-output functions
mainL4CasADi supports multi-input multi-output functions by using the following pattern:
- Concatenate symbolic inputs when passing them to the model.
- Split the inputs inside the PyTorch function to match the required shapes.
L4CasADi v2 Breaking Changes
mainL4CasADi v2 introduced several changes focused on efficiency and simplicity:
- Batching Support: When passing
batched=True, L4CasADi treats the first input dimension as the batch dimension. First and second-order derivatives across this dimension are assumed to be sparse-zero. To maximize performance (5-10x speedup), batch all inputs together into a single L4CasADi call instead of making multiple calls. - Input Shapes: L4CasADi no longer changes the shape of inputs. The tensor forwarded to the PyTorch model will have the exact dimension of the CasADi input variable. You must ensure your PyTorch model handles a two-dimensional input matrix. The
model_expects_batch_dimparameter has been removed. - Hessian Generation: By default, L4CasADi provides the Jacobian of the Adjoint. To explicitly request the Hessian, pass
generate_jac_jac=True.
- Batching Support: When passing
Use L4CasADi in Matlab
mainTo use L4CasADi within Matlab, you must first export your model as an L4CasADi library and ensure the system library paths are correctly configured in your shell before launching Matlab. This process allows Matlab to link to the exported C++ libraries generated from your PyTorch models.Integrate Real-time L4CasADi with Acados MPC
mainReal-time L4CasADi can be integrated into Acados (RTI-)MPC workflows. A reference implementation is provided in the
mpc_mlp_example.pyexample, which demonstrates how to use a learned residual dynamic within an Acados MPC setup. While the provided example uses a single integrator with a learned residual set to zero, it serves as a template for full integration.# See the integration example at: # ../../examples/realtime/mpc_mlp_example.pyInstall L4CasADi via Pip (CPU Only)
mainTo install the CPU-only version via pip, ensure you have the CPU version of Torch installed and the necessary build dependencies. You must use the
--no-build-isolationflag so L4CasADi can link against your installed PyTorch.# 1. Install Torch CPU version pip install torch>=2.0 --index-url https://download.pytorch.org/whl/cpu # 2. Install build dependencies pip install "setuptools>=68.1" "scikit-build>=0.17" "cmake>=3.27" "ninja>=1.11" # 3. Install L4CasADi pip install l4casadi --no-build-isolationSetup the Fish Turbulent Flow Example
mainTo run the Fish Turbulent Flow example, you must download the required dataset and organize it into a
datadirectory within the example folder. The directory must containCC.csv,UALL.csv,VALL.csv, andVORTALL.csvfiles.Additionally, install the necessary Python dependencies and ensure
ffmpegis installed on your system to generate animations.# 1. Organize data into the 'data' folder # fish_turbulent_flow/data/CC.csv, etc. # 2. Install Python requirements pip install -r requirements.txt # 3. Install ffmpeg (required for animations) # Linux: sudo apt install ffmpeg # OSX: brew install ffmpegInstall L4CasADi and dependencies
mainTo use L4CasADi in a notebook environment (like Google Colab), you need to install PyTorch, build tools, and the L4CasADi package itself. Note that L4CasADi requires
scikit-build,cmake, andninjafor the build process.# Install PyTorch (CPU version) !pip install torch --index-url https://download.pytorch.org/whl/cpu # Install build dependencies !pip install scikit-build cmake ninja # Install L4CasADi from source !pip install git+https://github.com/Tim-Salzmann/l4casadi --no-build-isolation!pip install torch --index-url https://download.pytorch.org/whl/cpu !pip install scikit-build cmake ninja !pip install git+https://github.com/Tim-Salzmann/l4casadi --no-build-isolationPrerequisites for Matlab integration
mainTo use L4CasADi in Matlab, you must have CasADi for Matlab installed. Download it from https://web.casadi.org/get/ and place the files in the current working directory.Train the Turbulent Flow PyTorch Model from Scratch
mainIf you do not want to use a pre-trained model, you can train the neural network representing the flow from scratch. This is a two-step process:
- Generate Interpolators: Run
generate_interpolators.pyto prepare the data. - Train Network: Run
learn_turbulent_flow.pyto perform supervised learning on the generated interpolators.
# Step 1: Generate interpolators python generate_interpolators.py # Step 2: Train the network python learn_turbulent_flow.py- Generate Interpolators: Run