-
Notifications
You must be signed in to change notification settings - Fork 20
/
NetTrimSolver.py
216 lines (164 loc) · 7.01 KB
/
NetTrimSolver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Feel free to redistribute and/or modify this software as long as you
make a reference to the original source code and cite the following paper
A. Aghasi, A. Abdi, N. Nguyen, and J. Romberg, "Net-Trim: Convex Pruning of
Deep Neural Networks with Performance Guarantee," NIPS 2017
Created by: Afshin Abdi, Georgia Tech
Email: [email protected]
Created: Fall 2017
"""
import tensorflow as tf
import numpy as np
import scipy
class NetTrimSolver:
def __init__(self):
self._graph = None
self._sess = None
self._initializer = None
# inputs of the graph
self._L = None
self._U = None
self._A = None
self._q = None
self._c = None
# optimization parameters
self._rho = None
self._alpha = None
# initial values of x, z, u
self._init_z = None
self._init_u = None
# outputs
self._x = None
self._z = None
self._u = None
self._dx = None
def create_graph(self, unroll_number=10):
self._graph = tf.Graph()
with self._graph.as_default():
# inputs to the graph
self._L = tf.placeholder(tf.float64)
self._U = tf.placeholder(tf.float64)
self._A = tf.placeholder(tf.float64)
self._q = tf.placeholder(tf.float64)
self._c = tf.placeholder(tf.float64)
# initial values for x, z and u
self._init_z = tf.placeholder(tf.float64)
self._init_u = tf.placeholder(tf.float64)
# optimization parameters
self._rho = tf.placeholder(dtype=tf.float64)
self._alpha = tf.placeholder(dtype=tf.float64)
# dummy variables
At = tf.transpose(self._A)
z = self._init_z
u = self._init_u
# first iteration to compute x with initial values of 0 for other variables
# compute x
_1 = tf.subtract(self._c, tf.add(u, z)) # c-u-z
_2 = tf.multiply(self._rho, tf.matmul(At, _1)) # rho*A'*(c-u-z)
_3 = tf.subtract(_2, self._q) # rho*A'*(c-u-z)-q
_4 = tf.matrix_triangular_solve(self._L, _3, lower=True)
x = tf.matrix_triangular_solve(self._U, _4, lower=False)
x_prev = x
for i in range(unroll_number):
Ax = tf.matmul(self._A, x)
c_Ax = tf.subtract(self._c, Ax)
# update z
_1 = tf.multiply(self._alpha, c_Ax) # alpha*(c-A*x)
_2 = tf.multiply(1 - self._alpha, z) # (1-alpha)*z_prev
tmp = tf.subtract(tf.add(_1, _2), u) # alpha*(c-A*x) + (1-alpha)*z_prev - u
z = tf.maximum(tmp, 0) # z = max(alpha*(c-A*x) + (1-alpha)*z_prev, 0)
# update u
u = tf.subtract(z, tmp) # z - (alpha*(c-A*x) + (1-alpha)*z_prev - u)
# update x
x_prev = x
_1 = tf.subtract(self._c, tf.add(u, z)) # c-u-z
_2 = tf.multiply(self._rho, tf.matmul(At, _1)) # rho*A'*(c-u-z)
_3 = tf.subtract(_2, self._q) # rho*A'*(c-u-z)-q
_4 = tf.matrix_triangular_solve(self._L, _3, lower=True)
x = tf.matrix_triangular_solve(self._U, _4, lower=False)
self._dx = tf.norm(tf.subtract(x, x_prev))
self._x = x
self._z = z
self._u = u
self._initializer = tf.global_variables_initializer()
self._sess = tf.Session(graph=self._graph) # ,config=tf.ConfigProto(log_device_placement=True))
def run(self, X, y, rho, alpha, lmbda, num_iterations=100):
lmbda = 1 / lmbda
y = np.reshape(y, newshape=(1, -1)) # make sure y is a row vector
N = X.shape[0]
if y.shape[1] != X.shape[1]:
raise ValueError("Dimensions of input data, X & y, are not consistent.")
Omega = np.where(y > 1e-6)[1]
Omega_c = np.where(y <= 1e-6)[1]
Q = lmbda * np.matmul(X[:, Omega], np.transpose(X[:, Omega]))
q = -lmbda * np.matmul(X, np.transpose(y))
P = X[:, Omega_c]
P = P.transpose()
c = np.zeros((len(Omega_c), 1))
Q = np.kron([[1, -1], [-1, 1]], Q)
q = 1 / 2 + np.append(q, -q, axis=0)
P = np.append(P, -P, axis=1)
A = np.append(P, -np.eye(2 * N, 2 * N), axis=0)
c = np.append(c, np.zeros((2 * N, 1)), axis=0)
# The ADMM part of the code
L = np.linalg.cholesky(Q + rho * np.matmul(A.transpose(), A))
U = L.transpose()
z = np.zeros((len(c), 1))
x = np.zeros((2 * N, 1))
u = np.zeros((len(c), 1))
self._sess.run(self._initializer)
cnt = 0
for cnt in range(num_iterations):
feed_dict = {self._L: L, self._U: U, self._A: A, self._q: q, self._c: c, self._rho: rho,
self._alpha: alpha, self._init_z: z, self._init_u: u}
dx, x, z, u = self._sess.run([self._dx, self._x, self._z, self._u], feed_dict=feed_dict)
if np.linalg.norm(dx) < 1e-3:
break
w = x[0:N] - x[N:]
w[np.abs(w) < 1e-3] = 0
w = w.squeeze()
return w, cnt
def net_trim_solver_np(X, y, rho, alpha, lmbda, num_iterations=1000):
lmbda = 1 / lmbda
y = np.reshape(y, newshape=(1, -1)) # make sure y is a row vector
N = X.shape[0]
if y.shape[1] != X.shape[1]:
raise ValueError("Dimensions of input data, X & y, are not consistent.")
Omega = np.where(y > 1e-6)[1]
Omega_c = np.where(y <= 1e-6)[1]
Q = lmbda * np.matmul(X[:, Omega], np.transpose(X[:, Omega]))
q = -lmbda * np.matmul(X, np.transpose(y))
P = X[:, Omega_c]
P = P.transpose()
c = np.zeros((len(Omega_c), 1))
Q = np.kron([[1, -1], [-1, 1]], Q)
q = 1 / 2 + np.append(q, -q, axis=0)
P = np.append(P, -P, axis=1)
A = np.append(P, -np.eye(2 * N, 2 * N), axis=0)
c = np.append(c, np.zeros((2 * N, 1)), axis=0)
# The ADMM part of the code
L = np.linalg.cholesky(Q + rho * np.matmul(A.transpose(), A))
U = L.transpose()
z = np.zeros((len(c), 1))
u = np.zeros((len(c), 1))
_1 = rho * np.matmul(A.T, c) - q # rho*A'*(c-u-z)-q
_2 = scipy.linalg.solve_triangular(L, _1, lower=True) # np.linalg.solve(L, _3)
x = scipy.linalg.solve_triangular(U, _2, lower=False) # np.linalg.solve(U, _4)
cnt = 0
for cnt in range(num_iterations):
c_Ax = c - np.matmul(A, x)
# update z
tmp = alpha * c_Ax + (1 - alpha) * z - u # alpha*(c-A*x) + (1-alpha)*z_prev - u
z = np.maximum(tmp, 0) # z = max(alpha*(c-A*x) + (1-alpha)*z_prev, 0)
# update u
u = z - tmp # z - (alpha*(c-A*x) + (1-alpha)*z_prev - u)
# update x
x_prev = x
_1 = rho * np.matmul(A.T, c - u - z) - q # rho*A'*(c-u-z)-q
_2 = scipy.linalg.solve_triangular(L, _1, lower=True)
x = scipy.linalg.solve_triangular(U, _2)
if np.linalg.norm(x - x_prev) < 1e-3:
break
w = x[0:N] - x[N:]
w[np.abs(w) < 1e-3] = 0
return w, cnt