-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition.py
234 lines (185 loc) · 6.58 KB
/
partition.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
import os
import time
import logging
import calendar
import numpy as np
import scipy.sparse as sp
import networkx as nx
import gurobipy as gp
from gurobipy import GRB
from utils import grb_vars_shape, grb_vars_to_ndarray
from EleNetX.mpdl import *
from EleNetX.visualize import plot_ele_nx
# Global Gurobi setting
current_GMT = time.gmtime()
timestamp = calendar.timegm(current_GMT)
log_file = "gurobi.partition.{}.log".format(timestamp)
def get_partition_constraints(X:gp.tupledict,
w:np.ndarray,
max_size,
min_size) -> dict:
""" Get partition constraints for each individual graph
:param X: partition 0-1 variable, shape $l \times m$,
l nodes in total, m subgraphs
:param w: node weight, constant, shape l
:param max_size:
:param min_size:
"""
l, m = grb_vars_shape(X)
# (1) unique cluster assignment
unique_assign = (X.sum(k, '*') == 1 for k in range(l))
# (2) max size
size_ub = (gp.quicksum(X[k, j] * w[k] for k in range(l))
<= max_size for j in range(m))
# (3) min size
size_lb = (gp.quicksum(X[k, j] * w[k] for k in range(l))
>= min_size for j in range(m))
return {
"Partition:unique-subgraph-assignment" : unique_assign,
"Partition:cluster-size-upper-bound" : size_ub,
"Partition:cluster-size-lower-bound" : size_lb
}
def get_partition_objective(X:gp.tupledict,
L:sp.coo_matrix) -> gp.QuadExpr:
""" Get partition objective for each individual graph
"""
l, m = grb_vars_shape(X)
# enumerate node k1, k2, and subgraph j
cut_size = gp.quicksum(X[k1, j] * val * X[k2, j]
for (k1, k2, val) in zip(L.row, L.col, L.data)
for j in range(m))
cut_size = cut_size * 0.5 # remove duplication
return cut_size
def get_partition_model(L:sp.coo_matrix,
w:np.ndarray,
m:int,
max_size,
min_size):
"""
"""
model = gp.Model("quadratic graph partition")
l, _ = L.shape
# set variables
X = model.addVars(l, m, vtype=GRB.BINARY)
# set constraints
partition_constrs = get_partition_constraints(X, w=w,
max_size=max_size,
min_size=min_size)
for constrs in partition_constrs:
model.addConstrs(partition_constrs[constrs], name=constrs)
# set objective
cut_size = get_partition_objective(X, L)
model.setObjective(cut_size)
model.update()
return model, X
def get_partition_nG_model(Ls:list,
ws:list,
max_size,
min_size):
model = gp.Model("quadratic multi graphs partition")
n = len(Ls); assert n == len(ws)
# init objective and variables
cut_size = 0.0
Xs = []
for i in range(n):
L = Ls[i]; w = ws[i]
l, _ = L.shape
m = int(np.floor(l / min_size))
m = min(l, m)
print(l, m)
# set variables
X = model.addVars(l, m, vtype=GRB.BINARY)
Xs.append(X)
# set constraints
partition_constrs = get_partition_constraints(X, w=w,
max_size=max_size,
min_size=min_size)
for constrs in partition_constrs:
model.addConstrs(partition_constrs[constrs], name=constrs)
# update objective
cut_size += get_partition_objective(X, L)
# set objective
model.setObjective(cut_size)
model.update()
return model, Xs
if __name__ == "__main__":
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)
# neural_net = 'resnet50'
# gpath = compose_graph_path(neural_net, 0)
# print(gpath)
# G = nx.read_gpickle(gpath)
# L = nx.laplacian_matrix(G)
# L = L.tocoo()
# l, _ = L.shape
# max_size = l
# min_size = 5
# # assume node weights are almost balanced
# # need to figure out when this problem will be infeasible
# # with max and min area constraints for subgraphs
# # since we have a minimum size constraint, we cannot automatic
# # get some empty subgraphs, so we must enumerate m
# m = int(np.floor(l / min_size))
# m = min(l, m)
# print(l, m)
# w = np.ones(l)
# model, X = get_partition_model(L, w=w, m=m, max_size=max_size, min_size=min_size)
# # add Gurobi configuration and update model
# model.setParam("LogFile", log_file)
# model.setParam("LogToConsole", 0)
# model.setParam('TimeLimit', 20 * 60)
# model.update()
# model.optimize()
# if (model.status == GRB.OPTIMAL or
# model.status == GRB.TIME_LIMIT or
# model.status == GRB.NODE_LIMIT or
# model.status == GRB.ITERATION_LIMIT or
# model.status == GRB.USER_OBJ_LIMIT):
# # get a solution
# X = grb_vars_to_ndarray(X, dtype=int)
# print(X)
# if model.status == GRB.TIME_LIMIT:
# print("time limit")
# if model.status == GRB.OPTIMAL:
# print("get optimal")
# elif (model.status == GRB.INFEASIBLE):
# print("Infeasible")
# else:
# print("unknown error")
Ls = []; ws = []
for neural_net in MPDL_BENCHMARKS.keys():
num_cfg = MPDL_BENCHMARKS[neural_net]['num_cfg']
# enumerate configs
for i in range(num_cfg):
gpath = compose_graph_path(neural_net, i)
print(gpath)
G = nx.read_gpickle(gpath)
L = nx.laplacian_matrix(G)
L = L.tocoo()
Ls.append(L)
l, _ = L.shape
w = np.ones(l)
ws.append(w)
max_size = 20
min_size = 10
model, Xs = get_partition_nG_model(Ls, ws, max_size, min_size)
# add Gurobi configuration and update model
model.setParam("LogFile", log_file)
model.setParam("LogToConsole", 0)
model.setParam('TimeLimit', 20 * 60)
model.update()
model.optimize()
if (model.status == GRB.OPTIMAL or
model.status == GRB.TIME_LIMIT or
model.status == GRB.NODE_LIMIT or
model.status == GRB.ITERATION_LIMIT or
model.status == GRB.USER_OBJ_LIMIT):
# get a solution
if model.status == GRB.TIME_LIMIT:
print("time limit")
if model.status == GRB.OPTIMAL:
print("get optimal")
# print solution
for X in Xs:
X = grb_vars_to_ndarray(X, dtype=int)
print(X)