Skip to content

Instantly share code, notes, and snippets.

@currymj
Created September 9, 2020 22:57
Show Gist options
  • Save currymj/a74cf5a5887b363d697382c7ac35551f to your computer and use it in GitHub Desktop.
Save currymj/a74cf5a5887b363d697382c7ac35551f to your computer and use it in GitHub Desktop.
an example testing runtime for our convex program
import cvxpy as cp
from cvxpylayers.torch import CvxpyLayer
import torch
import time
import numpy as np
n_structures = 24
n_types = 7
n_hos = 2
n_h_t_combos = 14
S = torch.tensor([[1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[1., 0., 1., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 1., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 1.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,
1., 0., 1., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 1., 0., 1., 0.],
[0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 1., 0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 1., 1., 0., 0.,
0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 1., 0., 0.,
1., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
0., 1., 0., 0., 1., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 1., 0., 1.]])
weights = torch.tensor([2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
2., 2., 2., 2., 2., 2.])
x1 = cp.Variable(n_structures)
w = cp.Parameter(n_structures)
b = cp.Parameter(n_h_t_combos)
constraints = [x1 >= 0, S.numpy() @ x1 <= b] # constraint for positive allocation and less than true bid
objective = cp.Maximize((w).T @ x1)
problem = cp.Problem(objective, constraints)
l_prog_layer = CvxpyLayer(problem, parameters=[w, b], variables=[x1])
batch_size = 128
batch=torch.rand(batch_size,2,7)
B = batch.view(batch_size, n_hos * n_types) # max bids to make sure not over allocated
W = weights.unsqueeze(0).repeat(batch_size, 1)
times = []
for i in range(100):
start_time = time.time()
l_prog_layer(W, B)
end_time = time.time()
times.append(end_time - start_time)
print(np.mean(times))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment