-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
493 lines (403 loc) · 20.2 KB
/
node.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# DEEP DECLARATIVE NODES
# Defines the interface for data processing nodes and declarative nodes. The implementation here is kept simple
# with inputs and outputs assumed to be vectors. There is no distinction between data and parameters and no
# concept of batches. For using deep declarative nodes in a network for end-to-end learning see code in the
# `ddn.pytorch` package.
#
# Stephen Gould <stephen.gould@anu.edu.au>
# Dylan Campbell <dylan.campbell@anu.edu.au>
#
import autograd.numpy as np
import scipy as sci
from autograd import grad, jacobian
import warnings
class AbstractNode:
"""
Minimal interface for generic data processing node that produces an output vector given an input vector.
"""
def __init__(self, n=1, m=1):
"""
Create a node
:param n: dimensionality of the input (parameters)
:param m: dimensionality of the output (optimization solution)
"""
assert (n > 0) and (m > 0)
self.dim_x = n # dimensionality of input variable
self.dim_y = m # dimensionality of output variable
def solve(self, x):
"""Computes the output of the node given the input. The second returned object provides context
for computing the gradient if necessary. Otherwise it's None."""
raise NotImplementedError()
return None, None
def gradient(self, x, y=None, ctx=None):
"""Computes the gradient of the node for given input x and, optional, output y and context cxt.
If y or ctx is not provided then they are recomputed from x as needed."""
raise NotImplementedError()
return None
class AbstractDeclarativeNode(AbstractNode):
"""
A general deep declarative node defined by an unconstrained parameterized optimization problems of the form
minimize (over y) f(x, y)
where x is given (as a vector) and f is a scalar-valued function. Derived classes must implement the `objective`
and `solve` functions.
"""
eps = 1.0e-6 # tolerance for checking that optimality conditions are satisfied
def __init__(self, n=1, m=1):
"""
Creates an declarative node with optimization problem implied by the objecive function. Initializes the
partial derivatives of the objective function for use in computing gradients.
"""
super().__init__(n, m)
# partial derivatives of objective
self.fY = grad(self.objective, 1)
self.fYY = jacobian(self.fY, 1)
self.fXY = jacobian(self.fY, 0)
def objective(self, x, y):
"""Evaluates the objective function on a given input-output pair."""
warnings.warn("objective function not implemented.")
return 0.0
def solve(self, x):
"""
Solves the optimization problem
y \in argmin_u f(x, u)
and returns two outputs. The first is the optimal solution y and the second contains the context for
computing the gradient, such as the largrange multipliers in the case of a constrained problem, or None
if no context is available/needed.
"""
raise NotImplementedError()
return None, None
def gradient(self, x, y=None, ctx=None):
"""
Computes the gradient of the output (problem solution) with respect to the problem
parameters. The returned gradient is an ndarray of size (self.dim_y, self.dim_x). In
the case of 1-dimensional parameters the gradient is a vector of size (self.dim_y,).
Can be overridden by the derived class to provide a more efficient implementation.
"""
# compute optimal value if not already done so
if y is None:
y, ctx = self.solve(x)
assert self._check_optimality_cond(x, y)
return -1.0 * sci.linalg.solve(self.fYY(x, y), self.fXY(x, y), assume_a='pos')
def _check_optimality_cond(self, x, y, ctx=None):
"""Checks that the problem's first-order optimality condition is satisfied."""
return (abs(self.fY(x, y)) <= self.eps).all()
class EqConstDeclarativeNode(AbstractDeclarativeNode):
"""
A general deep declarative node defined by a parameterized optimization problem with single (non-linear)
equality constraint of the form
minimize (over y) f(x, y)
subject to h(x, y) = 0
where x is given (as a vector) and f and h are scalar-valued functions. Derived classes must implement the
`objective`, `constraint` and `solve` functions.
"""
def __init__(self, n, m):
super().__init__(n, m)
# partial derivatives of constraint function
self.hY = grad(self.constraint, 1)
self.hX = grad(self.constraint, 0)
self.hYY = jacobian(self.hY, 1)
self.hXY = jacobian(self.hY, 0)
def constraint(self, x, y):
"""Evaluates the equality constraint function on a given input-output pair."""
warnings.warn("constraint function not implemented.")
return 0.0
def solve(self, x):
"""
Solves the optimization problem
y \in argmin_u f(x, u) subject to h(x, u) = 0
and returns the vector y. Optionally, also returns the Lagrange multiplier associated with the
equality constraint where the Lagrangian is defined as
L(x, y, nu) = f(x, y) - ctx['nu'] * h(x, y)
Otherwise, should return None as second return variable.
If the calling function only cares about the optimal solution (and not the context) then call as
y_star, _ = self.solve(x)
"""
raise NotImplementedError()
return None, None
def gradient(self, x, y=None, ctx=None):
"""Compute the gradient of the output (problem solution) with respect to the problem
parameters. The returned gradient is an ndarray of size (prob.dim_y, prob.dim_x). In
the case of 1-dimensional parameters the gradient is a vector of size (prob.dim_y,)."""
# compute optimal value if not already done so
if y is None:
y, ctx = self.solve(x)
assert self._check_constraints(x, y), [x, y, abs(self.constraint(x, y))]
assert self._check_optimality_cond(x, y, ctx), [x, y, ctx]
nu = self._get_nu_star(x, y) if (ctx is None) else ctx['nu']
# return unconstrained gradient if nu is undefined
if np.isnan(nu):
return -1.0 * np.linalg.solve(self.fYY(x, y), self.fXY(x, y))
H = self.fYY(x, y) - nu * self.hYY(x, y)
a = self.hY(x, y)
B = self.fXY(x, y) - nu * self.hXY(x, y)
C = self.hX(x, y)
try:
v = sci.linalg.solve(H, np.concatenate((a.reshape((self.dim_y, 1)), B), axis=1), assume_a='pos')
except:
return np.full((self.dim_y, self.dim_x), np.nan).squeeze()
return (np.outer(v[:, 0], (v[:, 0].dot(B) - C) / v[:, 0].dot(a)) - v[:, 1:self.dim_x + 1]).squeeze()
def _get_nu_star(self, x, y):
"""Compute nu_star if not provided by the problem's solver."""
indx = np.nonzero(self.hY(x, y))
if len(indx[0]) == 0:
return 0.0
return self.fY(x, y)[indx[0][0]] / self.hY(x, y)[indx[0][0]]
def _check_constraints(self, x, y):
"""Check that the problem's constraints are satisfied."""
return abs(self.constraint(x, y)) <= self.eps
def _check_optimality_cond(self, x, y, ctx=None):
"""Checks that the problem's first-order optimality condition is satisfied."""
nu = self._get_nu_star(x, y) if (ctx is None) else ctx['nu']
if np.isnan(nu):
return (abs(self.fY(x, y)) <= self.eps).all()
# check for invalid lagrangian (gradient of constraint zero at optimal point)
if (abs(self.hY(x, y)) <= self.eps).all():
warnings.warn("gradient of constraint function vanishes at the optimum.")
return True
return (abs(self.fY(x, y) - nu * self.hY(x, y)) <= self.eps).all()
class IneqConstDeclarativeNode(EqConstDeclarativeNode):
"""
A general deep declarative node defined by a parameterized optimization problem with single (non-linear)
inequality constraint of the form
minimize (over y) f(x, y)
subject to h(x, y) <= 0
where x is given (as a vector) and f and h are scalar-valued functions. Derived classes must implement the
`objective`, `constraint` and `solve` functions.
"""
def __init__(self, n, m):
super().__init__(n, m)
def equality_constraints(self, x, y):
return None
def inequality_constraints(self, x, y):
return None
def gradient(self, x, y=None, ctx=None):
"""
Compute the gradient of the output
"""
if y is None:
y, ctx = self.solve(x)
assert self._check_equality_constraints(x, y)
assert self._check_inequality_constraints(x, y)
assert self._check_optimality_cond(x, y, ctx)
h_hatY, h_hatX, h_hatYY, h_hatXY = self._get_constraint_derivatives(x, y)
nu = self._get_nu(x, y, h_hatY) if (ctx is None or 'nu' not in ctx) else ctx['nu']
if nu.any() is None or nu.any() == float('-inf'):
warnings.warn("Non-regular solution")
if not self._check_optimality_cond(x, y, nu):
warnings.warn("Non-zero Lagrangian gradient at y:\n{}\n"
"fY: {}, hY: {}, nu: {}".format((self.fY(x, y) - np.dot(nu, h_hatY)),
self.fY(x, y), h_hatY, nu))
p_q = len(h_hatY)
H = self.fYY(x, y) - np.sum(nu[i] * h_hatYY[i, :, :] for i in range(p_q)) # mxm
H = (H + H.T) / 2 # make sure H is symmetric
A = h_hatY # (p+q)xm
B = self.fXY(x, y) - np.sum(nu[i] * h_hatXY[i, :, :] for i in range(p_q)) # mxn
c = h_hatX # (p+q)xn
# try to use cholesky to solve H^{-1}A^T and H^-1 B
try:
C, L = sci.linalg.cho_factor(H)
invHAT = sci.linalg.cho_solve((C, L), A.T)
invHB = sci.linalg.cho_solve((C, L), B)
# if H is not positive definite, revert to LU to solve
except:
invHAT = sci.linalg.solve(H, A.T)
invHB = sci.linalg.solve(H, B)
# compute Dy(x)=H^{-1}AT(AH^{-1}AT)^{-1}(AH^{-1}B-C)-H^{-1}B
return np.dot(invHAT, sci.linalg.solve(np.dot(A, invHAT), np.dot(A, invHB) - c)) - invHB
def _get_constraint_derivatives(self, x, y):
h = self.equality_constraints # px1
if h is not None:
if not self._check_equality_constraints(x, y):
warnings.warn("Equality constraints not satisfied exactly:\n{}".format(h))
g = self.inequality_constraints # qx1
if g is not None:
if not self._check_inequality_constraints(x, y):
warnings.warn("Inequality constraints not satisfied exactly:\n{}".format(g))
'''
Indentify active constraints:
only when g(x,y) = 0, consider it's a equality constraints, otherwise are unconstrained
'''
# only one inequality constraints
if isinstance(g(x, y), float):
if not abs(g(x, y) <= self.eps):
g = None
else:
mask = None
else:
# record the True index
mask = np.array([abs(g(x, y)[i].all() <= self.eps) for i in range(len(np.array(g(x, y))))])
if not mask.any():
g = None
# gradient calculation
h_hatY = np.vstack((jacobian(h, 1)(x, y), jacobian(g, 1)(x, y)[mask] if mask is not None else jacobian(g, 1)(x, y))) \
if g is not None else jacobian(h, 1)(x, y)
h_hatX = np.vstack((jacobian(h, 0)(x, y), jacobian(g, 0)(x, y)[mask] if mask is not None else jacobian(g, 1)(x, y))) \
if g is not None else jacobian(h, 0)(x, y)
h_hatYY = np.vstack((jacobian(jacobian(h, 1), 1)(x, y), jacobian(jacobian(g, 1), 1)(x, y)[mask] \
if mask is not None else jacobian(jacobian(g, 1), 1)(x, y).reshape(1, self.dim_y, self.dim_y))) \
if g is not None else jacobian(jacobian(h, 1), 1)(x, y)
h_hatXY = np.vstack((jacobian(jacobian(h, 1), 0)(x, y), jacobian(jacobian(g, 1), 0)(x, y)[mask] \
if mask is not None else jacobian(jacobian(g, 1), 1)(x, y).reshape(1, self.dim_y, self.dim_y))) \
if g is not None else jacobian(jacobian(h, 1), 0)(x, y)
return h_hatY, h_hatX, h_hatYY, h_hatXY
def _get_nu(self, x, y, h_hatY):
"""
solve: hY^T nu = fY^T.
"""
nu = sci.linalg.lstsq(h_hatY.T, self.fY(x, y))[0]
return nu
def _check_equality_constraints(self, x, y):
"""Check that the problem's equality constraints are satisfied."""
return (abs(self.equality_constraints(x, y)) <= self.eps).all()
def _check_inequality_constraints(self, x, y):
"""Check that the problem's inequality constraints are satisfied."""
return (abs(self.inequality_constraints(x, y)) <= self.eps).all()
def _check_optimality_cond(self, x, y, nu):
"""Checks that the problem's first-order optimality condition is satisfied."""
h_hatY = self._get_constraint_derivatives(x, y)[0]
if h_hatY is None:
return super()._check_optimality_cond(x, y)
nu = self._get_nu(x, y, h_hatY) if (nu is None) else nu
if np.isnan(nu).all():
return super()._check_optimality_cond(x, y)
# check for invalid lagrangian (gradient of constraint zero at optimal point)
if (abs(h_hatY) <= self.eps).all():
warnings.warn("gradient of constraint function vanishes at the optimum.")
return True
return (abs(self.fY(x, y) - np.dot(nu.T, h_hatY)) <= self.eps).all()
class LinEqConstDeclarativeNode(AbstractDeclarativeNode):
"""
A deep declarative node defined by a linear equality constrained parameterized optimization problem of the form:
minimize (over y) f(x, y)
subject to A y = b
where x is given. Derived classes must implement the objective and solve functions.
"""
def __init__(self, n, m, A, b):
super().__init__(n, m)
assert A.shape[1] == m, "second dimension of A must match dimension of y"
assert A.shape[0] == b.shape[0], "dimension of A must match dimension of b"
self.A, self.b = A, b
def gradient(self, x, y=None, ctx=None):
"""Compute the gradient of the output (problem solution) with respect to the problem
parameters. The returned gradient is an ndarray of size (prob.dim_y, prob.dim_x). In
the case of 1-dimensional parameters the gradient is a vector of size (prob.dim_y,)."""
# compute optimal value if not already done so
if y is None:
y, ctx = self.solve(x)
assert self._check_constraints(x, y)
assert self._check_optimality_cond(x, y, ctx)
# TODO: write test case for LinEqConstDeclarativeNode
# use cholesky to solve H^{-1}A^T and H^{-1}B
C, L = sci.linalg.cho_factor(self.fYY(x, y))
invHAT = sci.linalg.cho_solve((C, L), self.A.T)
invHB = sci.linalg.cho_solve((C, L), self.fXY(x, y))
# compute W = H^{-1}A^T (A H^{-1} A^T)^{-1} A
W = np.dot(invHAT, sci.linalg.solve(np.dot(self.A, invHAT), self.A))
# return H^{-1}A^T (A H^{-1} A^T)^{-1} A H^{-1} B - H^{-1} B
return np.dot(W, invHB) - invHB
def _check_constraints(self, x, y):
"""Check that the problem's constraints are satisfied."""
residual = np.dot(self.A, y) - self.b
return np.all(np.abs(residual) <= self.eps)
def _check_optimality_cond(self, x, y, ctx=None):
"""Checks that the problem's first-order optimality condition is satisfied."""
warnings.warn("optimality check not implemented yet")
return True
class MultiEqConstDeclarativeNode(AbstractDeclarativeNode):
"""
A deep declarative node having multiple linear or non-linear equality constraints:
minimize (over y) f(x, y)
subject to h_i(x, u) = 0, i = 1, ... , p
"""
def __init__(self, n, m):
super().__init__(n, m)
def constraint(self, x, y):
"""
Evaluates the equality constraint function on a given input-output pair.
h_i(x, y) = 0, i=1,...,p
"""
warnings.warn("constraint function not implemented.")
return 0.0
def gradient(self, x, y=None, ctx=None):
"""
Compute the gradient of the output
"""
if y is None:
y, ctx = self.solve(x)
assert self._check_constraints(x, y)
assert self._check_optimality_cond(x, y, ctx)
hY, hYY, hXY, hX = self._get_constraint_derivatives(x, y)
nu = self._get_nu(x, y, hY) if (ctx is None or 'nu' not in ctx) else ctx['nu']
if not self._check_optimality_cond(x, y, nu):
warnings.warn("Non-zero Lagrangian gradient at y:\n{}\n"
"fY: {}, hY: {}, nu: {}".format((self.fY(x, y) - np.dot(nu.T, hY(x, y))),
self.fY(x, y), hY(x, y), nu))
p = len(hY(x, y))
H = self.fYY(x, y) - np.sum(nu[i] * hYY(x, y)[i, :, :] for i in range(p)) # mxm
H = (H + H.T) / 2 # make sure H is symmetric
A = hY(x, y) # pxm
B = self.fXY(x, y) - np.sum(nu[i] * hXY(x, y)[i, :, :] for i in range(p)) # mxn
c = hX(x, y) # pxn
# try to use cholesky to solve H^{-1}A^T and H^-1 B
try:
C, L = sci.linalg.cho_factor(H)
invHAT = sci.linalg.cho_solve((C, L), A.T)
invHB = sci.linalg.cho_solve((C, L), B)
# if H is not positive definite, revert to LU to solve
except:
invHAT = sci.linalg.solve(H, A.T)
invHB = sci.linalg.solve(H, B)
# compute Dy(x)=H^{-1}AT(AH^{-1}AT)^{-1}(AH^{-1}B-C)-H^{-1}B
return np.dot(invHAT, sci.linalg.solve(np.dot(A, invHAT), np.dot(A, invHB)-c))-invHB
def _get_constraint_derivatives(self, x, y):
h = self.constraint # px1
# check constraints
if h is not None:
if not self._check_constraints(x, y):
warnings.warn("Constraints not satisfied exactly:\n{}".format(h))
# partial derivatives of constraint function
hY = jacobian(h, 1) # pxm
hX = jacobian(h, 0) # pxn
hYY = jacobian(hY, 1) # pxmxm
hXY = jacobian(hY, 0) # pxmxn
return hY, hYY, hXY, hX
def _get_nu(self, x, y, hY):
"""
solve: hY^T nu = fY^T.
"""
nu = sci.linalg.lstsq(hY(x, y).T, self.fY(x, y))[0]
return nu
def _check_constraints(self, x, y):
"""Check that the problem's constraints are satisfied."""
return (abs(self.constraint(x, y)) <= self.eps).all()
def _check_optimality_cond(self, x, y, nu):
"""Checks that the problem's first-order optimality condition is satisfied."""
hY = self._get_constraint_derivatives(x, y)[0]
if hY is None:
return super()._check_optimality_cond(x, y)
nu = self._get_nu(x, y, hY) if (nu is None) else nu
if np.isnan(nu).all():
return super()._check_optimality_cond(x, y)
# check for invalid lagrangian (gradient of constraint zero at optimal point)
if (abs(hY(x, y)) <= self.eps).all():
warnings.warn("gradient of constraint function vanishes at the optimum.")
return True
return (abs(self.fY(x, y) - np.dot(nu.T, hY(x, y))) <= self.eps).all()
class NonUniqueDeclarativeNode(AbstractDeclarativeNode):
"""
A general deep declarative node having non-unique solutions so that the pseudo-inverse is required
in computing the gradient.
"""
def __init__(self, n, m):
super().__init__(n, m)
def gradient(self, x, y=None, ctx=None):
"""
Computes the gradient of the output (problem solution) with respect to the problem parameters
using a pseudo-inverse. The returned gradient is an ndarray of size (self.dim_y, self.dim_x).
In the case of 1-dimensional parameters the gradient is a vector of size (self.dim_y,).
"""
# compute optimal value if not already done so
if y is None:
y, ctx = self.solve(x)
assert self._check_optimality_cond(x, y, ctx), abs(self.fY(x, y))
return -1.0 * np.linalg.pinv(self.fYY(x, y)).dot(self.fXY(x, y))