OptNet: Differentiable Optimization as a Layer in Neural Networks

Overview

OptNet: Differentiable Optimization as a Layer in Neural Networks

This repository is by Brandon Amos and J. Zico Kolter and contains the PyTorch source code to reproduce the experiments in our ICML 2017 paper OptNet: Differentiable Optimization as a Layer in Neural Networks.

If you find this repository helpful in your publications, please consider citing our paper.

@InProceedings{amos2017optnet,
  title = {{O}pt{N}et: Differentiable Optimization as a Layer in Neural Networks},
  author = {Brandon Amos and J. Zico Kolter},
  booktitle = {Proceedings of the 34th International Conference on Machine Learning},
  pages = {136--145},
  year = {2017},
  volume = {70},
  series = {Proceedings of Machine Learning Research},
  publisher ={PMLR},
}

Informal Introduction

Mathematical optimization is a well-studied language of expressing solutions to many real-life problems that come up in machine learning and many other fields such as mechanics, economics, EE, operations research, control engineering, geophysics, and molecular modeling. As we build our machine learning systems to interact with real data from these fields, we often cannot (but sometimes can) simply ``learn away'' the optimization sub-problems by adding more layers in our network. Well-defined optimization problems may be added if you have a thorough understanding of your feature space, but oftentimes we don't have this understanding and resort to automatic feature learning for our tasks.

Until this repository, no modern deep learning library has provided a way of adding a learnable optimization layer (other than simply unrolling an optimization procedure, which is inefficient and inexact) into our model formulation that we can quickly try to see if it's a nice way of expressing our data.

See our paper OptNet: Differentiable Optimization as a Layer in Neural Networks and code at locuslab/optnet if you are interested in learning more about our initial exploration in this space of automatically learning quadratic program layers for signal denoising and sudoku.

Setup and Dependencies

  • Python/numpy/PyTorch
  • qpth: Our fast QP solver for PyTorch released in conjunction with this paper.
  • bamos/block: Our intelligent block matrix library for numpy, PyTorch, and beyond.
  • Optional: bamos/setGPU: A small library to set CUDA_VISIBLE_DEVICES on multi-GPU systems.

Denoising Experiments

denoising
├── create.py - Script to create the denoising dataset.
├── plot.py - Plot the results from any experiment.
├── main.py - Run the FC baseline and OptNet denoising experiments. (See arguments.)
├── main.tv.py - Run the TV baseline denoising experiment.
└── run-exps.sh - Run all experiments. (May need to uncomment some lines.)

Sudoku Experiments

  • The dataset we used in our experiments is available in sudoku/data.
sudoku
├── create.py - Script to create the dataset.
├── plot.py - Plot the results from any experiment.
├── main.py - Run the FC baseline and OptNet Sudoku experiments. (See arguments.)
└── models.py - Models used for Sudoku.

Classification Experiments

cls
├── train.py - Run the FC baseline and OptNet classification experiments. (See arguments.)
├── plot.py - Plot the results from any experiment.
└── models.py - Models used for classification.

Acknowledgments

The rapid development of this work would not have been possible without the immense amount of help from the PyTorch team, particularly Soumith Chintala and Adam Paszke.

Licensing

Unless otherwise stated, the source code is copyright Carnegie Mellon University and licensed under the Apache 2.0 License.

Comments
  • Sudoku experiment

    Sudoku experiment

    I tried running the sudoku example. My command line arguments are as follows:

    python main.py --boardSz 2 --batchSz 100 --testBatchSz 100 --nEpoch 50 --testPct 0.1 --save SAVE --work 'work' optnet
    

    I get errors arising from models.py:

    TypeError: super() takes at least 1 argument (0 given)
    > /home/robotec/Documents/NNs/optnet/sudoku/models.py(80)__init__()
         78     """ Solve a single SQP iteration of the scheduling problem"""
         79     def __init__(self, n, Qpenalty):
    ---> 80         super().__init__()
         81         nx = (n**2)**3
         82         self.Q = Variable(Qpenalty*torch.eye(nx).double().cuda())
    
    ipdb> 
    

    Did I miss something?

    opened by robotsorcerer 8
  • QP Solver with extra terms and more variables

    QP Solver with extra terms and more variables

    Hi @bamos ,

    Thank you for this promising work and clean code if you don't mind.

    I have some questions related to the solver.

    Is it possible to :

    1. Add extra terms in the objective function and variable constraints ? https://github.com/locuslab/qpth/blob/master/qpth/qp.py#L36

    A) extra terms in the objective function

    \hat z = argmin_z 1/2 z^T Q z + p^T z+......+....+......

    B) Add more variables constraints : for instance add y_, F_, K_, n_ to Q_, p_, G_, h_, A_, b_

    1. Is this constraint solver can deal with maximum solution rather than minimum ?

    \hat z = argmax_z 1/2 z^T Q z + p^T z+......+....+......

    Thank you a lot for your answer

    opened by Benjiou 1
  • several issues

    several issues

    Hi there, thx for sharing this wonderful works. I am trying to run the code, and encounter some situations:

    1. when I trying to run test and profile code, I fail to import adact. But I have no idea where the lib is?
    2. when running denoising example, I use the command as python main.py --nEpoch 50 optnet --learnD --Dpenalty 0.01 and I got the following error message: ('===>', 'Building model') Testing model: 0/1000 Traceback (most recent call last): File "main.py", line 229, in <module> main() File "main.py", line 136, in main test(args, 0, model, testF, testW, testX, testY) File "main.py", line 202, in test output = model(batch_data) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/home/jdily/Desktop/project/optnet-master/denoising/models.py", line 155, in forward x = QPFunction()(p.double(), Q.double(), G.double(), h.double(), e, e).float() File "/usr/local/lib/python2.7/dist-packages/qpth/qp.py", line 65, in forward p, _ = expandParam(p_, nBatch, 2) File "/usr/local/lib/python2.7/dist-packages/qpth/util.py", line 50, in expandParam raise RuntimeError("Unexpected number of dimensions.") RuntimeError: Unexpected number of dimensions. I use python 2.7 instead of 3.x, but I do update some part of the code to support python 2.7... Do you know how can I solve these issues?

    Meanwhile, the link to the denoising data seems broken.

    thanks a lot!

    opened by jdily 1
  • how to run the cpu version

    how to run the cpu version

    /usr/local/lib/python3.6/site-packages/IPython/core/ultratb.py(1268)call() -> self.handler((etype, evalue, etb)) (Pdb)


    AssertionError Traceback (most recent call last) /Users/gaopeng/Desktop/tensorflow/project/optnet/denoising/main.py in () 229 230 if name=='main': --> 231 main() global main = <function main at 0x114ba7510>

    /Users/gaopeng/Desktop/tensorflow/project/optnet/denoising/main.py in main() 109 elif args.model == 'optnet': 110 if args.learnD: --> 111 model = models.OptNet_LearnD(nFeatures, args) model = undefined global models.OptNet_LearnD = <class 'models.OptNet_LearnD'> nFeatures = 100 args = Namespace(Dpenalty=0.01, batchSz=150, cuda=False, eps=0.0001, learnD=True, model='optnet', nEpoch=50, no_cuda=False, save='work/optnet.eps=0.0001.learnD.0.01', testBatchSz=100, testPct=0.1, tvInit=False) 112 else: 113 model = models.OptNet(nFeatures, args)

    /Users/gaopeng/Desktop/tensorflow/project/optnet/denoising/models.py in init(self=OptNet_LearnD ( ), nFeatures=100, args=Namespace(Dpenalty=0.01, batchSz=150, cuda=False....01', testBatchSz=100, testPct=0.1, tvInit=False)) 113 114 # self.fc1 = nn.Linear(nFeatures, nHidden) --> 115 self.M = Variable(torch.tril(torch.ones(nHidden, nHidden)).cuda()) self.M = undefined global Variable = <class 'torch.autograd.variable.Variable'> global torch.tril = global torch.ones = nHidden = 199 nHidden.cuda = undefined 116 117 Q = 1e-8*torch.eye(nHidden)

    /usr/local/lib/python3.6/site-packages/torch/utils.py in cuda(self= 1 0 0 ... 0 0 0 1... 1 1 [torch.FloatTensor of size 199x199] , device=-1, async=False) 63 else: 64 new_type = getattr(torch.cuda, self.class.name) ---> 65 return new_type(self.size()).copy(self, async) new_type = <class 'torch.cuda.FloatTensor'> self.size.copy = undefined self = 1 0 0 ... 0 0 0 1 1 0 ... 0 0 0 1 1 1 ... 0 0 0 ... ⋱ ...
    1 1 1 ... 1 0 0 1 1 1 ... 1 1 0 1 1 1 ... 1 1 1 [torch.FloatTensor of size 199x199]

        async = False
     66 
     67 
    

    /usr/local/lib/python3.6/site-packages/torch/cuda/init.py in new(cls=<class 'torch.cuda.FloatTensor'>, *args=(torch.Size([199, 199]),), **kwargs={}) 275 276 def new(cls, *args, **kwargs): --> 277 _lazy_init() global _lazy_init = <function _lazy_init at 0x110ab5378> 278 # We need this method only for lazy init, so we can remove it 279 del _CudaBase.new

    /usr/local/lib/python3.6/site-packages/torch/cuda/init.py in _lazy_init() 87 raise RuntimeError( 88 "Cannot re-initialize CUDA in forked subprocess. " + msg) ---> 89 _check_driver() global _check_driver = <function _check_driver at 0x110ab52f0> 90 assert torch._C._cuda_init() 91 assert torch._C._cuda_sparse_init()

    /usr/local/lib/python3.6/site-packages/torch/cuda/init.py in _check_driver() 54 def _check_driver(): 55 if not hasattr(torch._C, '_cuda_isDriverSufficient'): ---> 56 raise AssertionError("Torch not compiled with CUDA enabled") global AssertionError = undefined 57 if not torch._C._cuda_isDriverSufficient(): 58 if torch._C._cuda_getDriverVersion() == 0:

    AssertionError: Torch not compiled with CUDA enabled

    /usr/local/lib/python3.6/site-packages/IPython/core/ultratb.py(1269)call() -> try:

    opened by gaopeng-eugene 1
  • RuntimeError: invalid argument 3: dimensions of A and b must be equal

    RuntimeError: invalid argument 3: dimensions of A and b must be equal

    When I used the optnet to run all the three experiments, I got the following error:

    ` RuntimeError: invalid argument 3: dimensions of A and b must be equal at /pytorch/torch/lib/TH/generic/THTensorLapack.c:1036

    /usr/local/lib/python3.5/dist-packages/qpth/solvers/pdipm/batch.py(357)solve_kkt() 355 h = (invQ_rx.unsqueeze(1).bmm(G.transpose(1, 2)) + rs / d - rz).squeeze(1) 356 --> 357 w = -(h.btrisolve(*S_LU)) 358 359 g1 = -rx - w[:, neq:].unsqueeze(1).bmm(G) `

    Did I miss something or do something wrong with the qpth or other environment? I can run the fc and lenet network in the classification experiment. Since I don't have a CUDA, I uncomment all the “.cuda()” in the models.py

    opened by Blanchedingding 1
  • MNIST experiments creating qpth issues

    MNIST experiments creating qpth issues

    Hi,

    I was running the optnet code for MNIST classification with the default configurations for only 10 epochs. In the first couple of epochs I get the warning "qpth warning: Returning an inaccurate and potentially incorrect solutino" and in the subsequent iterations the loss becomes nan. Is there something obviously wrong with my configurations?

    opened by guptakartik 5
Owner
CMU Locus Lab
Zico Kolter's Research Group
CMU Locus Lab
Differentiable ODE solvers with full GPU support and O(1)-memory backpropagation.

PyTorch Implementation of Differentiable ODE Solvers This library provides ordinary differential equation (ODE) solvers implemented in PyTorch. Backpr

Ricky Chen 4.4k Jan 4, 2023
Fast, general, and tested differentiable structured prediction in PyTorch

Torch-Struct: Structured Prediction Library A library of tested, GPU implementations of core structured prediction algorithms for deep learning applic

HNLP 1.1k Jan 7, 2023
Differentiable SDE solvers with GPU support and efficient sensitivity analysis.

PyTorch Implementation of Differentiable SDE Solvers This library provides stochastic differential equation (SDE) solvers with GPU support and efficie

Google Research 1.2k Jan 4, 2023
This is an differentiable pytorch implementation of SIFT patch descriptor.

This is an differentiable pytorch implementation of SIFT patch descriptor. It is very slow for describing one patch, but quite fast for batch. It can

Dmytro Mishkin 150 Dec 24, 2022
Pytorch implementation of Distributed Proximal Policy Optimization

Pytorch-DPPO Pytorch implementation of Distributed Proximal Policy Optimization: https://arxiv.org/abs/1707.02286 Using PPO with clip loss (from https

Alexis David Jacq 164 Jan 5, 2023
Riemannian Adaptive Optimization Methods with pytorch optim

geoopt Manifold aware pytorch.optim. Unofficial implementation for “Riemannian Adaptive Optimization Methods” ICLR2019 and more. Installation Make sur

null 642 Jan 3, 2023
GPU-accelerated PyTorch implementation of Zero-shot User Intent Detection via Capsule Neural Networks

GPU-accelerated PyTorch implementation of Zero-shot User Intent Detection via Capsule Neural Networks This repository implements a capsule model Inten

Joel Huang 15 Dec 24, 2022
Tutorial for surrogate gradient learning in spiking neural networks

SpyTorch A tutorial on surrogate gradient learning in spiking neural networks Version: 0.4 This repository contains tutorial files to get you started

Friedemann Zenke 203 Nov 28, 2022
Learning Sparse Neural Networks through L0 regularization

Example implementation of the L0 regularization method described at Learning Sparse Neural Networks through L0 regularization, Christos Louizos, Max W

AMLAB 202 Nov 10, 2022
PyTorch Implementation of [1611.06440] Pruning Convolutional Neural Networks for Resource Efficient Inference

PyTorch implementation of [1611.06440 Pruning Convolutional Neural Networks for Resource Efficient Inference] This demonstrates pruning a VGG16 based

Jacob Gildenblat 836 Dec 26, 2022
High-level batteries-included neural network training library for Pytorch

Pywick High-Level Training framework for Pytorch Pywick is a high-level Pytorch training framework that aims to get you up and running quickly with st

null 382 Dec 6, 2022
A tiny scalar-valued autograd engine and a neural net library on top of it with PyTorch-like API

micrograd A tiny Autograd engine (with a bite! :)). Implements backpropagation (reverse-mode autodiff) over a dynamically built DAG and a small neural

Andrej 3.5k Jan 8, 2023
PyNIF3D is an open-source PyTorch-based library for research on neural implicit functions (NIF)-based 3D geometry representation.

PyNIF3D is an open-source PyTorch-based library for research on neural implicit functions (NIF)-based 3D geometry representation. It aims to accelerate research by providing a modular design that allows for easy extension and combination of NIF-related components, as well as readily available paper implementations and dataset loaders.

Preferred Networks, Inc. 96 Nov 28, 2022
Distiller is an open-source Python package for neural network compression research.

Wiki and tutorials | Documentation | Getting Started | Algorithms | Design | FAQ Distiller is an open-source Python package for neural network compres

Intel Labs 4.1k Dec 28, 2022
A Closer Look at Structured Pruning for Neural Network Compression

A Closer Look at Structured Pruning for Neural Network Compression Code used to reproduce experiments in https://arxiv.org/abs/1810.04622. To prune, w

Bayesian and Neural Systems Group 140 Dec 5, 2022
OptNet: Differentiable Optimization as a Layer in Neural Networks

OptNet: Differentiable Optimization as a Layer in Neural Networks This repository is by Brandon Amos and J. Zico Kolter and contains the PyTorch sourc

CMU Locus Lab 428 Dec 24, 2022
Differentiable Neural Computers, Sparse Access Memory and Sparse Differentiable Neural Computers, for Pytorch

Differentiable Neural Computers and family, for Pytorch Includes: Differentiable Neural Computers (DNC) Sparse Access Memory (SAM) Sparse Differentiab

ixaxaar 302 Dec 14, 2022
An abstraction layer for mathematical optimization solvers.

MathOptInterface Documentation Build Status Social An abstraction layer for mathematical optimization solvers. Replaces MathProgBase. Citing MathOptIn

JuMP-dev 284 Jan 4, 2023
Differentiable Factor Graph Optimization for Learning Smoothers @ IROS 2021

Differentiable Factor Graph Optimization for Learning Smoothers Overview Status Setup Datasets Training Evaluation Acknowledgements Overview Code rele

Brent Yi 60 Nov 14, 2022
Pytorch implementation of "Forward Thinking: Building and Training Neural Networks One Layer at a Time"

forward-thinking-pytorch Pytorch implementation of Forward Thinking: Building and Training Neural Networks One Layer at a Time Requirements Python 2.7

Kim Heecheol 65 Oct 6, 2022