• Stars
    star
    1,718
  • Rank 26,184 (Top 0.6 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Differentiable convex optimization layers

cvxpylayers logo Build Status Build Status

cvxpylayers

cvxpylayers is a Python library for constructing differentiable convex optimization layers in PyTorch, JAX, and TensorFlow using CVXPY. A convex optimization layer solves a parametrized convex optimization problem in the forward pass to produce a solution. It computes the derivative of the solution with respect to the parameters in the backward pass.

This library accompanies our NeurIPS 2019 paper on differentiable convex optimization layers. For an informal introduction to convex optimization layers, see our blog post.

Our package uses CVXPY for specifying parametrized convex optimization problems.

Installation

Use the package manager pip to install cvxpylayers.

pip install cvxpylayers

Our package includes convex optimization layers for PyTorch, JAX, and TensorFlow 2.0; the layers are functionally equivalent. You will need to install PyTorch, JAX, or TensorFlow separately, which can be done by following the instructions on their websites.

cvxpylayers has the following dependencies:

Usage

Below are usage examples of our PyTorch, JAX, and TensorFlow layers. Note that the parametrized convex optimization problems must be constructed in CVXPY, using DPP.

PyTorch

import cvxpy as cp
import torch
from cvxpylayers.torch import CvxpyLayer

n, m = 2, 3
x = cp.Variable(n)
A = cp.Parameter((m, n))
b = cp.Parameter(m)
constraints = [x >= 0]
objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
problem = cp.Problem(objective, constraints)
assert problem.is_dpp()

cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
A_tch = torch.randn(m, n, requires_grad=True)
b_tch = torch.randn(m, requires_grad=True)

# solve the problem
solution, = cvxpylayer(A_tch, b_tch)

# compute the gradient of the sum of the solution with respect to A, b
solution.sum().backward()

Note: CvxpyLayer cannot be traced with torch.jit.

JAX

import cvxpy as cp
import jax
from cvxpylayers.jax import CvxpyLayer

n, m = 2, 3
x = cp.Variable(n)
A = cp.Parameter((m, n))
b = cp.Parameter(m)
constraints = [x >= 0]
objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
problem = cp.Problem(objective, constraints)
assert problem.is_dpp()

cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
key = jax.random.PRNGKey(0)
key, k1, k2 = jax.random.split(key, 3)
A_jax = jax.random.normal(k1, shape=(m, n))
b_jax = jax.random.normal(k2, shape=(m,))

solution, = cvxpylayer(A_jax, b_jax)

# compute the gradient of the summed solution with respect to A, b
dcvxpylayer = jax.grad(lambda A, b: sum(cvxpylayer(A, b)[0]), argnums=[0, 1])
gradA, gradb = dcvxpylayer(A_jax, b_jax)

Note: CvxpyLayer cannot be traced with the JAX jit or vmap operations.

TensorFlow 2

import cvxpy as cp
import tensorflow as tf
from cvxpylayers.tensorflow import CvxpyLayer

n, m = 2, 3
x = cp.Variable(n)
A = cp.Parameter((m, n))
b = cp.Parameter(m)
constraints = [x >= 0]
objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
problem = cp.Problem(objective, constraints)
assert problem.is_dpp()

cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
A_tf = tf.Variable(tf.random.normal((m, n)))
b_tf = tf.Variable(tf.random.normal((m,)))

with tf.GradientTape() as tape:
  # solve the problem, setting the values of A, b to A_tf, b_tf
  solution, = cvxpylayer(A_tf, b_tf)
  summed_solution = tf.math.reduce_sum(solution)
# compute the gradient of the summed solution with respect to A, b
gradA, gradb = tape.gradient(summed_solution, [A_tf, b_tf])

Note: CvxpyLayer cannot be traced with tf.function.

Log-log convex programs

Starting with version 0.1.3, cvxpylayers can also differentiate through log-log convex programs (LLCPs), which generalize geometric programs. Use the keyword argument gp=True when constructing a CvxpyLayer for an LLCP. Below is a simple usage example

import cvxpy as cp
import torch
from cvxpylayers.torch import CvxpyLayer

x = cp.Variable(pos=True)
y = cp.Variable(pos=True)
z = cp.Variable(pos=True)

a = cp.Parameter(pos=True, value=2.)
b = cp.Parameter(pos=True, value=1.)
c = cp.Parameter(value=0.5)

objective_fn = 1/(x*y*z)
objective = cp.Minimize(objective_fn)
constraints = [a*(x*y + x*z + y*z) <= b, x >= y**c]
problem = cp.Problem(objective, constraints)
assert problem.is_dgp(dpp=True)

layer = CvxpyLayer(problem, parameters=[a, b, c],
                   variables=[x, y, z], gp=True)
a_tch = torch.tensor(a.value, requires_grad=True)
b_tch = torch.tensor(b.value, requires_grad=True)
c_tch = torch.tensor(c.value, requires_grad=True)

x_star, y_star, z_star = layer(a_tch, b_tch, c_tch)
sum_of_solution = x_star + y_star + z_star
sum_of_solution.backward()

Solvers

At this time, we support two open-source solvers: SCS and ECOS. SCS can be used to solve any problem expressible in CVXPY; ECOS can be used to solve problems that don't use the positive semidefinite or exponential cone (this roughly means that if you have positive semidefinite matrices or use atoms like cp.log, ECOS cannot be used to solve your problem via cvxpylayers). By default, cvxpylayers uses SCS to solve the problem.

Using ECOS

First make sure that you have cvxpylayers and diffcp up to date, by running

pip install --upgrade cvxpylayers diffcp

Then, to use ECOS, you would pass the solver_args argument to the layer:

solution = layer(*params, solver_args={"solve_method": "ECOS"})

Passing arguments to the solvers

One can pass arguments to both SCS and ECOS by adding the argument as a key-value pair in the solver_args argument. For example, to increase the tolerance of SCS to 1e-8 one would write:

layer(*parameters, solver_args={"eps": 1e-8})

If SCS is not converging, we highly recommend switching to ECOS (if possible), and if not, using the following arguments to SCS:

solver_args={"eps": 1e-8, "max_iters": 10000, "acceleration_lookback": 0}

Examples

Our examples subdirectory contains simple applications of convex optimization layers in IPython notebooks.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Please lint the code with flake8.

pip install flake8  # if not already installed
flake8

Running tests

cvxpylayers uses the pytest framework for running tests. To install pytest, run:

pip install pytest

Execute the tests from the main directory of this repository with:

pytest cvxpylayers/{torch,jax,tensorflow}

Projects using cvxpylayers

Below is a list of projects using cvxpylayers. If you have used cvxpylayers in a project, you're welcome to make a PR to add it to this list.

License

cvxpylayers carries an Apache 2.0 license.

Citing

If you use cvxpylayers for research, please cite our accompanying NeurIPS paper:

@inproceedings{cvxpylayers2019,
  author={Agrawal, A. and Amos, B. and Barratt, S. and Boyd, S. and Diamond, S. and Kolter, Z.},
  title={Differentiable Convex Optimization Layers},
  booktitle={Advances in Neural Information Processing Systems},
  year={2019},
}

If you use cvxpylayers to differentiate through a log-log convex program, please cite the accompanying paper:

@article{agrawal2020differentiating,
  title={Differentiating through log-log convex programs},
  author={Agrawal, Akshay and Boyd, Stephen},
  journal={arXiv},
  archivePrefix={arXiv},
  eprint={2004.12553},
  primaryClass={math.OC},
  year={2020},
}

More Repositories

1

cvxportfolio

Portfolio optimization and back-testing.
Python
782
star
2

scs

Splitting Conic Solver
C
522
star
3

pymde

Minimum-distortion embedding with PyTorch
Python
516
star
4

cvxbook_additional_exercises

Additional exercises and data for EE364a. No solutions; for public consumption.
Julia
435
star
5

cvx_short_course

Materials for a short course on convex optimization.
Jupyter Notebook
309
star
6

CVXR

An R modeling language for convex optimization problems.
R
195
star
7

proximal

Sample implementations of proximal operators
MATLAB
180
star
8

dccp

A CVXPY extension for convex-concave programming
Python
122
star
9

cvxpygen

Code generation with CVXPY
Python
119
star
10

qcqp

A CVXPY extension for handling nonconvex QCQP via Suggest-and-Improve framework
Python
103
star
11

GGS

Greedy Gaussian Segmentation
Python
90
star
12

diffcp

Differentiation through cone programs
Python
86
star
13

cocp

Source code for the examples accompanying the paper "Learning convex optimization control policies."
Jupyter Notebook
78
star
14

ncvx

Python
69
star
15

cvxflow

Python
66
star
16

signal-decomposition

A simple and general framework for signal decomposition
Jupyter Notebook
55
star
17

auto_ks

Repository for "Fitting a Kalman Smoother to Data"
Python
51
star
18

cvxpower

Power Network Optimization and Simulation.
Python
47
star
19

cov_pred_finance

Jupyter Notebook
45
star
20

dmcp

A CVXPY extension for multi-convex programming
Python
43
star
21

CVXcanon

C++
42
star
22

qcml

A Python parser for generating Python/C/Matlab solver interfaces
Python
41
star
23

miqp_admm

ADMM for Mixed-Integer Quadratic Programming
C
39
star
24

vwap_opt_exec

Volume Weighted Average Price Optimal Execution
Jupyter Notebook
33
star
25

simulator

Tool to support backtests
Jupyter Notebook
32
star
26

a2dr

Anderson accelerated Douglas-Rachford splitting
Python
29
star
27

cptopt

Portfolio Optimization with Cumulative Prospect Theory Utility via Convex Optimization
Python
27
star
28

fastpathplanning

A fast algorithm for finding an optimal path in a collection of safe boxes
Python
27
star
29

strat_models

A distributed method for fitting Laplacian regularized stratified models.
Python
25
star
30

kelly_code

Code and examples for the project on risk-constrained Kelly gambling
Jupyter Notebook
24
star
31

dsp

A CVXPY extension for saddle problems
Python
21
star
32

osc

C package performing operator splitting for control
C
19
star
33

pdos

Primal-Dual Operator Splitting Method for Conic Optimization
C
19
star
34

nonexp_global_aa1

Globally Convergent Type-I Anderson Acceleration for Non-Smooth Fixed-Point Iterations
MATLAB
18
star
35

covpred

Covariance prediction via convex optimization
Python
18
star
36

aa

Anderson Acceleration
Jupyter Notebook
18
star
37

l1_ls

This is the repository for the l1_ls, a simple Matlab solver for l1-regularized least squares problems.
MATLAB
16
star
38

exp_util_gm_portfolio_opt

Minimal entropic value at risk (EVaR) portfolio construction under a Gaussian mixture model of returns.
Python
16
star
39

rsw

rsw: optimal representative sample weighting.
Python
15
star
40

cvxpyrepair

Code for "Automatic repair of convex optimization problems".
Python
14
star
41

cvx_opt_risk_neutral

Convex optimization over risk-neutral probabilities.
Jupyter Notebook
12
star
42

cvxstatarb

Jupyter Notebook
12
star
43

osmm

oracle-structured minimization method
Python
12
star
44

lrsm_portfolio

Portfolio Construction using Stratified Models
Jupyter Notebook
12
star
45

cvxmarkowitz

Jupyter Notebook
11
star
46

mkvchain

Fitting Feature-Dependent Markov Chains
Jupyter Notebook
10
star
47

cone_prog_refine

Cone program refinement
Python
9
star
48

icqm

MATLAB script for approximating the solution to the integer convex quadratic minimization problem
MATLAB
9
star
49

subgradpy

Subgradient calculator for Python
Python
8
star
50

PrincipalTimeSeries

MATLAB
8
star
51

torch_linops

A library to define abstract linear operators, and associated algebra and matrix-free algorithms, that works with pyTorch Tensors.
Python
8
star
52

vgi

Value-gradient iteration for convex stochastic control
Python
8
star
53

robust_bond_portfolio

Robust Bond Portfolio Construction via Convex-Concave Saddle Point Optimization
Python
8
star
54

sigopt

Solvers for sigmoidal programming problems
Python
7
star
55

cvxcla

critical line algorithm for efficient frontier
Jupyter Notebook
7
star
56

qss

QSS: Quadratic-Separable Solver
Jupyter Notebook
7
star
57

OSBDO

Oracle-Structured Bundle Distributed Optimization (OSBDO)
Python
7
star
58

SURE-CR

Tractable evaluation of Stein's Unbiased Risk Estimator on convexly regularized estimators
Python
7
star
59

mlr_fitting

Factor Fitting, Rank Allocation, and Partitioning in Multilevel Low Rank Matrices
Jupyter Notebook
6
star
60

WaveOperators.jl

Building matrices in physics is hard; that's why this package exists.
Julia
6
star
61

markowitz-reference

Python
6
star
62

l1_tf

This is the repository for the l1_tf, software for l1 trend filtering.
C
6
star
63

cvx-docker

Docker image containing CVXPY and other cvxgrp libraries
6
star
64

spcqe

Smooth periodic consistent quantile estimation
Jupyter Notebook
6
star
65

low_rank_forecasting_code

Code for "Low Rank Forecasting" paper.
Jupyter Notebook
5
star
66

lass

Linear algebra for structured sparse matrices
Python
5
star
67

sccf

Repository for "Minimizing a sum of clipped convex functions" paper
Python
5
star
68

cvxrisk

Compile risk with cvxpy
Jupyter Notebook
5
star
69

graph_isom

Python
4
star
70

conda-recipes

Anaconda recipes for cvxgrp python packages
Shell
4
star
71

lfd_lqr

Code for "Fitting a Linear Control Policy to Demonstrations with a Kalman Constraint"
Jupyter Notebook
4
star
72

mm_dist_lapl

Python
4
star
73

multi_period_liability_clearing

Code for the paper "Multi-period liability clearing via convex optimal control"
Python
4
star
74

ls-spa

Python
4
star
75

l1_logreg

This is the repository for the l1_logreg, l1-regularized logistic regression problem solver.
C
3
star
76

resalloc

Efficient allocation of fungible resources
Jupyter Notebook
3
star
77

joint-lrsm

Joint graph learning and model fitting in Laplacian Regularized Stratified Models
Python
3
star
78

n-queens

Python
2
star
79

PhysicalBounds.jl

Julia
2
star
80

cvxbson

dealing with json and bson files
Python
2
star
81

boolprob

A Python tool to analyze joint distributions of boolean random variables
Python
2
star
82

cvxcli

Example cli using fire, poetry and pipx
Python
2
star
83

opt_cap_res

Solves the problem of reserving link capacity in a network in such a way that any of a given set of flow scenarios can be supported.
Python
2
star
84

rerm_code

Public code for Robust Empirical Risk Minimization Paper
Python
1
star
85

ls-spa-benchmark

Python
1
star
86

extquadcontrol

Python
1
star
87

convexjl

A julia package for disciplined convex programming.
1
star
88

boilerplate

We use this repo to automate and avoid boilerplate issue
Python
1
star
89

incre_prox_mf_mpc

code for the paper Incremental Proximal Multi-Forecast Model Predictive Control
Jupyter Notebook
1
star
90

home-energy-management

Home energy management with dynamic tariffs and tiered peak power charges.
Jupyter Notebook
1
star
91

cvx_stat_arb

Jupyter Notebook
1
star
92

cvxbacktest

Python
1
star
93

coneos

C package that solves convex cone problems via operator splitting (DEPRECATED, new project https://github.com/cvxgrp/scs)
C
1
star
94

pd-heuristics-and-bounds

Julia
1
star