-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEvolutionCEE.py
437 lines (370 loc) · 15 KB
/
EvolutionCEE.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
import torch
import random
import pickle
import copy
from statistics import mean
import numpy as np
import scipy
from cee import BaseCEE
from cee.metrics import (
representation_similarity_analysis,
language_entropy,
message_distance,
kl_divergence,
jaccard_similarity,
)
from EvolutionAgents import SenderAgent, ReceiverAgent, SingleAgent
from model import ShapesTrainer, ObverterTrainer, generate_genotype, mutate_genotype
from utils import create_folder_if_not_exists, train_one_batch, evaluate
class EvolutionCEE(BaseCEE):
def __init__(self, params, run_folder="runs", device=None):
self.run_folder = run_folder
super().__init__(params)
self.device = device
if device is None:
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def save(self):
pickle.dump(self, open(self.run_folder + "/cee.p", "wb"))
def initialize_population(self, params: dict):
"""
Initializes params.population_size sender and receiver models
Args:
params (required): params obtained from argparse
"""
if params.save_example_batch:
create_folder_if_not_exists(self.run_folder + "/messages")
if params.single_pool:
create_folder_if_not_exists(self.run_folder + "/agents")
if params.evolution:
create_folder_if_not_exists(self.run_folder + "/agents_genotype")
else:
create_folder_if_not_exists(self.run_folder + "/senders")
create_folder_if_not_exists(self.run_folder + "/receivers")
if params.evolution:
create_folder_if_not_exists(self.run_folder + "/senders_genotype")
create_folder_if_not_exists(self.run_folder + "/receivers_genotype")
for i in range(params.population_size):
sender_genotype = None
receiver_genotype = None
if params.evolution:
sender_genotype = generate_genotype(num_nodes=params.init_nodes)
receiver_genotype = generate_genotype(num_nodes=params.init_nodes)
if params.single_pool:
self.agents.append(
SingleAgent(
self.run_folder, params, genotype=sender_genotype, agent_id=i
)
)
else:
self.senders.append(
SenderAgent(
self.run_folder, params, genotype=sender_genotype, agent_id=i
)
)
self.receivers.append(
ReceiverAgent(
self.run_folder, params, genotype=receiver_genotype, agent_id=i
)
)
def train_population(self, batch):
if self.params.single_pool:
sender, receiver = self.sample_agents_pair()
else:
sender = self.sample_population()
receiver = self.sample_population(receiver=True)
sender_model = sender.get_model()
receiver_model = receiver.get_model()
model = self.get_trainer(sender_model, receiver_model)
optimizer = torch.optim.Adam(model.parameters(), lr=self.params.lr)
loss, acc = train_one_batch(model, batch, optimizer)
sender.update_loss_acc(loss, acc)
receiver.update_loss_acc(loss, acc)
# Update receiver and sender files with new state
sender.save_model(model.sender)
receiver.save_model(model.receiver)
self.iteration += 1
def save_messages(self, messages, sender, i):
filename = "{}/messages/message_from_{}_at_{}".format(
self.run_folder, sender.agent_id, i
)
messages = messages.cpu().numpy()
pickle.dump(messages, open(filename, "wb"))
def evaluate_population(
self,
test_data,
meta_data,
features,
advanced=False,
max_senders=16,
save_example_batch=False,
):
"""
Evaluates language for population
- need to get generated messages by all senders
- since receivers don't talk - pick a random one
Args:
test_data: dataloader to evaluate against
dataset (str, opt) from {"train", "valid", "test"}
meta_data: encoded metadata for inputs
features: features in test_data (in numpy array)
advanced (bool, optional): whether to compute advanced metrics
max_senders (int, optional): max number of senders to evaluate against
evaluating over the entire set is costly
so this approximation speeds it up
"""
if self.params.single_pool:
random.shuffle(self.agents)
sender_pop = self.agents[:max_senders]
else:
random.shuffle(self.senders)
sender_pop = self.senders[:max_senders]
r = self.sample_population(receiver=True)
metrics = {
"loss": 0,
"acc": 0,
"entropy": 0,
"l_entropy": 0, # language entropy
"rsa_sr": 0,
"rsa_si": 0,
"rsa_ri": 0,
"rsa_sm": 0,
"pseudo_tre": 0,
"topological_similarity": 0,
"num_unique_messages": 0,
"kl_divergence": 0,
}
messages = []
sentence_probabilities = []
for s in sender_pop:
loss, acc, entropy, msgs, sent_ps, H_s, H_r = self.evaluate_pair(
s, r, test_data
)
metrics["num_unique_messages"] += len(torch.unique(msgs, dim=0))
if save_example_batch:
self.save_messages(msgs, s, save_example_batch)
if advanced:
sr, si, ri, sm, ts, pt, l_entropy = self.get_message_metrics(
msgs, H_s, H_r, meta_data, features
)
metrics["rsa_sr"] += sr
metrics["rsa_si"] += si
metrics["rsa_ri"] += ri
metrics["rsa_sm"] += sm
metrics["topological_similarity"] += ts
metrics["pseudo_tre"] += pt
metrics["l_entropy"] += l_entropy
metrics["loss"] += loss
metrics["acc"] += acc
metrics["entropy"] += entropy
messages.append(msgs)
sentence_probabilities.append(sent_ps)
pop_size = max_senders
for metric in metrics:
metrics[metric] /= pop_size
# language comparaison metric
avg_message_dist, avg_matches = message_distance(
torch.stack(messages, dim=1).cpu().numpy()
)
js = jaccard_similarity(torch.stack(messages, dim=1).cpu().numpy())
kl_dist = kl_divergence(
torch.stack(sentence_probabilities, dim=1).cpu().numpy()
)
metrics["jaccard_similarity"] = js
metrics["kl_divergence"] = kl_dist
metrics["avg_message_dist"] = avg_message_dist
metrics["avg_matches"] = avg_matches
return metrics
def evaluate_pair(self, sender, receiver, test_data):
"""
Evaluates pair of sender/receiver on test data and returns avg loss/acc
and generated messages
Args:
sender_name (path): path of sender model
receiver_name (path): path of receiver model
test_data (dataloader): dataloader of data to evaluate on
Returns:
avg_loss (float): average loss over data
avg_acc (float): average accuracy over data
test_messages (tensor): generated messages from data
"""
sender_model = sender.get_model()
receiver_model = receiver.get_model()
model = self.get_trainer(sender_model, receiver_model)
test_loss_meter, test_acc_meter, entropy_meter, test_messages, sentence_probabilities, hidden_sender, hidden_receiver = evaluate(
model, test_data, return_softmax=True
)
return (
test_loss_meter.avg,
test_acc_meter.avg,
entropy_meter.avg,
test_messages,
sentence_probabilities,
hidden_sender,
hidden_receiver,
)
@staticmethod
def get_message_metrics(
messages, hidden_sender, hidden_receiver, meta_data, img_features
):
"""
Runs metrics on the generated messages (single set of messages)
Args:
messages: individual batch of generated messages
meta_data: encoded meta_data
"""
messages = messages.cpu().numpy()
rsa_sr, rsa_si, rsa_ri, rsa_sm, topological_similarity, pseudo_tre = representation_similarity_analysis(
img_features, meta_data, messages, hidden_sender, hidden_receiver, tre=True
)
# rsa = representation_similarity_analysis(messages, meta_data)
l_entropy = language_entropy(messages)
return (
rsa_sr,
rsa_si,
rsa_ri,
rsa_sm,
topological_similarity,
pseudo_tre,
l_entropy,
)
def get_convergence(self, att, dynamic=True, k_shot=100):
pop_size = len(getattr(self, att))
if dynamic:
# k_shot is minimum number of batches that have been seen by any agent
k_shot = self.params.culling_interval
for agent in getattr(self, att):
# so as to make loss comparaisons fair - cap to 100 batches minimum
k_shot = max(min(k_shot, agent.age), 100)
agents = []
values = []
for a in range(pop_size):
# check model has been run
if getattr(self, att)[a].age < 1 or (
not dynamic and getattr(self, att)[a].age < k_shot
):
avg_loss = 100.0 # high value for loss
else:
avg_loss = mean(getattr(self, att)[a].loss[:k_shot])
# store the latest convergence for each agent
getattr(self, att)[a].convergence = avg_loss
agents.append(a)
values.append(avg_loss)
return values, agents
def sort_agents(self, receiver=False, dynamic=True, k_shot=100):
"""
Sorts agents according to convergence (see get_convergence)
dynamic - whether k_shot is based on minimum batch size
or on passed k_shot value
K_shot - how many initial batches/training steps
to take into account in the average loss
"""
if self.params.single_pool:
att = "agents"
else:
att = "receivers" if receiver else "senders"
values, agents = self.get_convergence(att, dynamic=dynamic, k_shot=k_shot)
values, agents = zip(*sorted(zip(values, agents)))
return list(agents), list(values)
def save_best_agent(self, att, agent):
agent_filename = "{}/best_{}_at_{}".format(
self.run_folder, att[:-1], self.iteration - 1
)
pickle.dump(agent, open(agent_filename + ".p", "wb"))
def mutate_population(self, receiver=False, culling_rate=0.2, mode="best"):
"""
mutates Population according to culling rate and mode
Args:
culling_rate (float, optional): percentage of the population to replace
default: 0.2
mode (string, optional): argument for sampling {best, greedy}
"""
if self.params.single_pool:
att = "agents"
else:
att = "receivers" if receiver else "senders"
pop_size = len(getattr(self, att))
c = max(1, int(culling_rate * pop_size))
print("Mutating {} agents from {} Population".format(c, att))
# mutates best agent to make child and place this child instead of worst agent
if mode == "best":
agents, _ = self.sort_agents(receiver=receiver)
best_agent = getattr(self, att)[agents[0]]
self.save_best_agent(att, best_agent)
# replace worst c models with mutated version of best
agents.reverse() # resort from worst to best
for w in agents[:c]:
worst_agent = getattr(self, att)[w]
new_genotype = mutate_genotype(best_agent.genotype)
worst_agent.mutate(new_genotype)
if mode == "greedy":
agents, values = self.sort_agents(receiver=receiver)
best_agent = getattr(self, att)[agents[0]]
self.save_best_agent(att, best_agent)
# deep copy in case best agent is selected to be culled
best_geno = copy.deepcopy(best_agent.genotype)
# replace sampled worst c models with mutated version of best
p = scipy.special.softmax(np.array(values))
selected_agents = np.random.choice(agents, c, p=p, replace=False)
for w in selected_agents:
worst_agent = getattr(self, att)[w]
new_genotype = mutate_genotype(best_geno)
worst_agent.mutate(new_genotype)
def get_avg_age(self):
"""
Returns average age
"""
age = 0
c = 0
if self.params.single_pool:
for r in self.agents:
age += r.age
c += 1
else:
for r in self.receivers:
age += r.age
c += 1
for s in self.senders:
age += s.age
c += 1
return age / c
def get_avg_convergence_at_step(self, step=10, dynamic=False):
"""
Returns average loss over the first training steps
taken by similar agents
"""
sender_agents, sender_losses = self.sort_agents(dynamic=dynamic, k_shot=step)
receiver_agents, receiver_losses = self.sort_agents(
receiver=True, dynamic=False, k_shot=step
)
losses = sender_losses + receiver_losses
return mean(losses)
def save_genotypes_to_writer(self, writer, receiver=False):
if self.params.single_pool:
att = "agents"
else:
att = "receivers" if receiver else "senders"
self.sort_agents(receiver=receiver)
for a in getattr(self, att):
m = {
"agent id": a.agent_id,
"loss": a.loss[-1],
"convergence": a.convergence,
"acc": a.acc[-1],
"age": a.age,
}
img = a.save_genotype(generation=self.generation, metrics=m)
writer.add_image(
"{}{}".format(att, a.agent_id),
img,
global_step=self.generation,
dataformats="HWC",
)
def get_trainer(self, sender, receiver):
if self.params.task == "shapes":
model = ShapesTrainer(sender, receiver, device=self.device)
elif self.params.task == "obverter":
model = ObverterTrainer(sender, receiver, device=self.device)
else:
raise ValueError("Incorrect task parameter")
model.to(self.device)
return model