forked from tranvinhthuy/group-adaptive-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomplementarity.py
376 lines (305 loc) · 14.7 KB
/
complementarity.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
import numpy as np
from abc import ABCMeta, abstractmethod
import operator
from typing import Dict, List
from application import Application
import os
import errno
from pprint import pprint
from tabulate import tabulate
from job_group_data import JobGroupData
class ComplementarityEstimation(metaclass=ABCMeta):
def __init__(self, recurrent_apps: List[Application]):
self.shape = (len(recurrent_apps), len(recurrent_apps))
self.apps = recurrent_apps
self.index = {}
self.reverse_index = {}
self.output_folder = "estimation"
# Loop with auto index through list of
for i, app in enumerate(sorted(recurrent_apps, key=lambda a: a.name)):
self.index[app.name] = i
self.reverse_index[i] = app.name
@abstractmethod
def best_app_index(self, scheduled_apps: List[Application], apps: List[Application],
scheduled_apps_weight: np.ndarray = None) -> int:
pass
@abstractmethod
def best_node_index(self, nodes_apps: Dict[str, List[Application]], app_to_schedule: Application) -> str:
pass
@abstractmethod
def update_app(self, app: Application, concurrent_apps: List[Application], rate: float):
pass
@abstractmethod
def save(self, folder):
pass
@abstractmethod
def load(self, folder):
pass
@abstractmethod
def print(self):
pass
def __str__(self):
return type(self).__name__
def indices(self, apps: List[Application]) -> List[int]:
if isinstance(apps, Application):
apps = [apps]
return [self.index[j.name] for j in apps]
def app_ids(self, indices: List[int]) -> List[Application]:
if not isinstance(indices, list):
indices = [indices]
return [self.reverse_index[i] for i in indices]
def _save(self, folder, filename, matrix):
try:
os.makedirs(folder)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
np.save("{}/{}.npy".format(folder, filename), matrix)
with open("{}/{}_axes.txt".format(folder, filename), "w") as f:
for i in range(len(self.reverse_index)):
f.write(self.reverse_index[i] + "\n")
class EpsilonGreedy(ComplementarityEstimation):
def __init__(self, recurrent_apps, initial_average=0., epsilon=0.1):
super().__init__(recurrent_apps)
self.epsilon = epsilon
self.average = np.full(self.shape, float(initial_average))
self.update_count = np.full(self.shape, 0 if initial_average == 0 else 1, dtype=np.int64)
def update_app(self, app, concurrent_apps, rate):
ix = np.ix_(self.indices(app), self.indices(concurrent_apps))
self.update_count[ix] += 1
self.average[ix] += (rate - self.average[ix]) / self.update_count[ix]
def best_app_index(self, scheduled_apps, apps, scheduled_apps_weight=None):
if len(scheduled_apps) == 0:
return 0
rates = self.expected_rates(scheduled_apps, apps)
if np.unique(rates).size == 1:
ix = list(range(len(apps)))[::-1]
else:
ix = np.argsort(rates)
return self.__greedy(ix)
def expected_rates(self, apps, apps_to_schedule, apps_weight=None):
avg = self.average[np.ix_(
self.indices(apps),
self.indices(apps_to_schedule)
)]
if apps_weight is not None:
avg = (avg.T * apps_weight).T
return avg.sum(axis=0)
def __greedy(self, items):
if np.random.uniform() < self.epsilon:
return items[np.random.randint(0, len(items) - 1)]
return items[-1]
def best_node_index(self, nodes_apps, app_to_schedule):
sorted_nodes_apps = sorted(
map(
lambda node_apps: (nodes_apps[0], self.expected_rates(node_apps[1], app_to_schedule)[0]),
nodes_apps.items()
),
key=operator.itemgetter(1)
)
rates = list(map(operator.itemgetter(1), sorted_nodes_apps))
if np.unique(rates).size == 1:
return nodes_apps.keys()[0]
sorted_addresses = list(map(operator.itemgetter(0), sorted_nodes_apps))
return self.__greedy(sorted_addresses)
def save(self, folder):
self._save(folder, "average", self.average)
self._save(folder, "ucount", self.update_count)
def load(self, folder):
self.average = np.load("{}/average.npy".format(folder))
self.update_count = np.load("{}/ucount.npy".format(folder))
def print(self):
rows = []
headers = ["Preferences"] + list(self.reverse_index.values())
for i, name in self.reverse_index.items():
rows.append([name] + self.average[i].tolist())
print(tabulate(rows, headers, tablefmt='pipe'))
class Gradient(ComplementarityEstimation):
def __init__(self, recurrent_apps, alpha=0.01, initial_average=0):
super().__init__(recurrent_apps)
self.alpha = alpha
self.average = np.full(self.shape[0], float(initial_average))
self.update_count = np.full(self.shape[0], 0 if initial_average == 0 else 1, dtype=np.int64)
self.preferences = np.zeros(self.shape)
def update_app(self, app, concurrent_apps, rate):
app = self.indices(app)
concurrent_apps = self.indices(concurrent_apps)
self.update_count[app] += 1
self.average[app] += (rate - self.average[app]) / self.update_count[app]
other_apps = np.delete(list(self.index.values()), concurrent_apps)
ap_concurrent = self.__action_probabilities(app, concurrent_apps)
ap_other = self.__action_probabilities(app, other_apps)
constant = self.alpha * (rate - self.average[app])
ix = np.ix_(app, concurrent_apps)
self.preferences[ix] += constant * (1 - ap_concurrent)
ix = np.ix_(app, other_apps)
self.preferences[ix] -= constant * ap_other
def __action_probabilities(self, apps_index, concurrent_apps_index):
exp = np.exp(self.preferences[apps_index])
return (exp[:, concurrent_apps_index].T / exp.sum(axis=1)).T
def best_app_index(self, scheduled_apps, apps, scheduled_apps_weight=None):
if len(scheduled_apps) == 0:
return np.random.randint(0, len(apps))
return self.__choose(
np.arange(len(apps)),
self.normalized_action_probabilities(scheduled_apps, apps, scheduled_apps_weight)
)
def normalized_action_probabilities(self, apps, apps_to_schedule, apps_weight=None):
p = self.__action_probabilities(self.indices(apps), self.indices(apps_to_schedule))
if apps_weight is not None:
p = (p.T * apps_weight).T
p = p.sum(axis=0)
return p / p.sum()
@staticmethod
def __choose(items, p):
indices = np.arange(len(items))
return items[np.random.choice(indices, p=p)]
def best_node_index(self, nodes_apps, app_to_schedule):
n = len(nodes_apps)
p = np.zeros(n)
nodes = []
for i, (node_name, apps) in enumerate(nodes_apps.items()):
p[i] = self.normalized_action_probabilities(apps, app_to_schedule)
nodes.append(node_name)
return self.__choose(nodes, p / p.sum())
def save(self, folder):
self._save(folder, "average", self.average)
self._save(folder, "preferences", self.preferences)
self._save(folder, "ucount", self.update_count)
def load(self, folder):
self.average = np.load("{}/average.npy".format(folder))
self.update_count = np.load("{}/ucount.npy".format(folder))
self.preferences = np.load("{}/preferences.npy".format(folder))
def print(self):
apps_name = list(self.reverse_index.values())
print(tabulate(
[
["Average"] + self.average.tolist(),
["Count"] + self.update_count.tolist(),
],
apps_name,
tablefmt='pipe'
))
rows = []
headers = ["Preferences"] + apps_name
for i, name in self.reverse_index.items():
rows.append([name] + self.preferences[i].tolist())
print(tabulate(rows, headers, tablefmt='pipe'))
class GroupGradient(Gradient):
def __init__(self, recurrent_apps: List[Application], alpha=0.01, initial_average=0):
super().__init__(recurrent_apps)
self.shape = (len(JobGroupData.groups), len(JobGroupData.groups))
self.apps = recurrent_apps
self.index = {}
self.reverse_index = {}
# Loop with auto index through list of
for i, app in enumerate(sorted(recurrent_apps, key=lambda a: a.name)):
index = JobGroupData.groupIndexes[app.name]
self.index[app.name] = index
self.reverse_index[index] = JobGroupData.group_names[index]
self.alpha = alpha
self.average = np.full(self.shape[0], float(initial_average))
self.update_count = np.full(self.shape[0], 0 if initial_average == 0 else 1, dtype=np.int64)
self.preferences = np.zeros(self.shape)
def update_app(self, app, concurrent_apps, rate):
#print("+++++++++++ Complementarity Update_app()")
#print("+++++++++++ App to update: {}".format(str(app)))
#print("+++++++++++ Concurrent apps with above app: {}".format(str(concurrent_apps)))
app = self.indices(app)
concurrent_apps = self.indices(concurrent_apps)
#print("+++++++++++ Apps to update (indices): {}".format(str(app)))
#print("+++++++++++ Concurrent apps with above app (indices): {}".format(str(concurrent_apps)))
self.update_count[app] += 1
self.average[app] += (rate - self.average[app]) / self.update_count[app]
other_apps = np.delete(list(set(self.index.values())), concurrent_apps)
#print("+++++++++++ Other apps: {}".format(str(other_apps)))
ap_concurrent = self.__action_probabilities(app, concurrent_apps)
ap_other = self.__action_probabilities(app, other_apps)
#print("+++++++++++ ap_concurrent: {}".format(str(ap_concurrent)))
#print("+++++++++++ ap_other: {}".format(str(ap_other)))
constant = self.alpha * (rate - self.average[app])
ix = np.ix_(app, concurrent_apps)
#print("+++++++++++ ix (app, concurrent_apps): {}".format(str(ix)))
self.preferences[ix] += constant * (1 - ap_concurrent)
np.set_printoptions(threshold=np.nan)
#print("+++++++++++ Preference matrix = {}".format(print(self.preferences)))
ix = np.ix_(app, other_apps)
#print("+++++++++++ ix (app, other_apps): {}".format(str(ix)))
self.preferences[ix] -= constant * ap_other
def __str__(self):
return type(self).__name__
def best_app_index(self, scheduled_apps, apps, scheduled_apps_weight=None):
if len(scheduled_apps) == 0 or len(scheduled_apps) == 2:
return -1, -1
print("- scheduled_apps: {}".format(",".join(app.name for app in scheduled_apps)))
print("- apps: {}".format(",".join(app.name for app in apps)))
probabilities = self.normalized_action_probabilities(scheduled_apps, apps, scheduled_apps_weight)
print("- probabilities = {}".format(str(probabilities)))
selected_app_group_index = self.__choose(
np.arange(len(probabilities)),
probabilities
)
list_groups_to_scheduled = list(set(self.indices(apps)))
if len(list_groups_to_scheduled) > len(probabilities):
list_groups_to_scheduled.remove(JobGroupData.groupIndexes[scheduled_apps[0].name])
print("- list groups to considered: {}".format(str(list_groups_to_scheduled)))
selected_app_group = list_groups_to_scheduled[selected_app_group_index]
# Select which exist job group to co-located with new job
selected_ongoing_job = np.argmax(self.preferences, axis=0)[selected_app_group]
print("-----------App group to schedule next = {}".format(selected_app_group))
#print("-----------Ongoing group to schedule with = {}".format(selected_ongoing_job))
print("-----------Preference matrix = {}".format(self.preferences[JobGroupData.groupIndexes[scheduled_apps[0].name],:]))
max_preference = -100
selected_ongoing_job = -1
for app in scheduled_apps:
index = JobGroupData.groupIndexes[app.name]
if self.preferences[JobGroupData.groupIndexes[scheduled_apps[0].name],:][index] > max_preference:
max_preference = self.preferences[JobGroupData.groupIndexes[scheduled_apps[0].name],:][index]
selected_ongoing_job = index
print("-----------Ongoing job to schdule with = {}".format(selected_ongoing_job))
return selected_app_group, selected_ongoing_job
def __action_probabilities(self, apps_index, concurrent_apps_index):
exp = np.exp(self.preferences[apps_index])
return (exp[:, concurrent_apps_index].T / exp.sum(axis=1)).T
def normalized_action_probabilities(self, apps, apps_to_schedule, apps_weight=None):
list_scheduled = list(set(self.indices(apps)))
list_to_schedule = list(set(self.indices(apps_to_schedule)))
list_to_schedule_excluded = [app for app in list_to_schedule if app not in list_scheduled]
if len(list_to_schedule_excluded) is not 0:
list_to_schedule = list_to_schedule_excluded
print("- list_scheduled={}".format(str(list_scheduled)))
print("- list_to_scheduled={}".format(str(list_to_schedule)))
p = self.__action_probabilities(list_scheduled, list_to_schedule)
# if apps_weight is not None:
# p = (p.T * apps_weight).T
p = p.sum(axis=0)
return p / p.sum()
@staticmethod
def __choose(items, p):
indices = np.arange(len(items))
return items[np.random.choice(indices, p=p)]
def save(self, folder):
self._save(folder, "average", self.average)
self._save(folder, "preferences", self.preferences)
self._save(folder, "ucount", self.update_count)
def load(self, folder):
self.average = np.load("{}/average.npy".format(folder))
self.update_count = np.load("{}/ucount.npy".format(folder))
self.preferences = np.load("{}/preferences.npy".format(folder))
def print(self):
apps_name = list(self.reverse_index.values())
print(tabulate(
[
["Average"] + self.average.tolist(),
["Count"] + self.update_count.tolist(),
],
apps_name,
tablefmt='pipe'
))
rows = []
headers = ["Preferences"] + apps_name
for i, name in self.reverse_index.items():
rows.append([name] + self.preferences[i].tolist())
#print(tabulate(rows, headers, tablefmt='pipe'))
np.set_printoptions(threshold=np.nan)
print(self.preferences)