forked from facebookresearch/EGG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
319 lines (274 loc) · 9.11 KB
/
game.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
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import print_function
import argparse
import contextlib
import torch.nn.functional as F
import torch.utils.data
from torch.utils.data import DataLoader
import egg.core as core
from egg.zoo.external_game.archs import Receiver, ReinforceReceiver, Sender
from egg.zoo.external_game.features import CSVDataset
def get_params():
parser = argparse.ArgumentParser()
parser.add_argument(
"--train_data", type=str, default=None, help="Path to the train data"
)
parser.add_argument(
"--validation_data", type=str, default=None, help="Path to the validation data"
)
parser.add_argument(
"--dump_data",
type=str,
default=None,
help="Path to the data for which to produce output information",
)
parser.add_argument(
"--dump_output",
type=str,
default=None,
help="Path for dumping output information",
)
parser.add_argument(
"--batches_per_epoch",
type=int,
default=1000,
help="Number of batches per epoch (default: 1000)",
)
parser.add_argument(
"--sender_hidden",
type=int,
default=10,
help="Size of the hidden layer of Sender (default: 10)",
)
parser.add_argument(
"--receiver_hidden",
type=int,
default=10,
help="Size of the hidden layer of Receiver (default: 10)",
)
parser.add_argument(
"--sender_embedding",
type=int,
default=10,
help="Dimensionality of the embedding hidden layer for Sender (default: 10)",
)
parser.add_argument(
"--receiver_embedding",
type=int,
default=10,
help="Dimensionality of the embedding hidden layer for Receiver (default: 10)",
)
parser.add_argument(
"--sender_cell",
type=str,
default="rnn",
help="Type of the cell used for Sender {rnn, gru, lstm} (default: rnn)",
)
parser.add_argument(
"--receiver_cell",
type=str,
default="rnn",
help="Type of the cell used for Receiver {rnn, gru, lstm} (default: rnn)",
)
parser.add_argument(
"--sender_layers",
type=int,
default=1,
help="Number of layers in Sender's RNN (default: 1)",
)
parser.add_argument(
"--receiver_layers",
type=int,
default=1,
help="Number of layers in Receiver's RNN (default: 1)",
)
parser.add_argument(
"--sender_entropy_coeff",
type=float,
default=1e-2,
help="The entropy regularisation coefficient for Sender (default: 1e-2)",
)
parser.add_argument(
"--receiver_entropy_coeff",
type=float,
default=1e-2,
help="The entropy regularisation coefficient for Receiver (default: 1e-2)",
)
parser.add_argument(
"--sender_lr",
type=float,
default=1e-1,
help="Learning rate for Sender's parameters (default: 1e-1)",
)
parser.add_argument(
"--receiver_lr",
type=float,
default=1e-1,
help="Learning rate for Receiver's parameters (default: 1e-1)",
)
parser.add_argument(
"--temperature",
type=float,
default=1.0,
help="GS temperature for the sender (default: 1.0)",
)
parser.add_argument(
"--train_mode",
type=str,
default="gs",
help="Selects whether GumbelSoftmax or Reinforce is used" "(default: gs)",
)
parser.add_argument(
"--n_classes",
type=int,
default=None,
help="Number of classes for Receiver to output. If not set, is automatically deduced from "
"the training set",
)
args = core.init(parser)
return args
def dump(game, dataset, device, is_gs):
interaction = core.dump_interactions(
game, dataset, gs=is_gs, device=device, variable_length=True
)
for i in range(interaction.size):
sender_input = interaction.sender_input[i]
message = interaction.message[i]
receiver_output = interaction.receiver_output[i]
label = interaction.labels[i]
length = interaction.message_length[i].long().item()
sender_input = " ".join(map(str, sender_input.tolist()))
message = " ".join(map(str, message[:length].tolist()))
if is_gs:
receiver_output = receiver_output.argmax()
print(f"{sender_input};{message};{receiver_output};{label.item()}")
def differentiable_loss(
_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input
):
labels = labels.squeeze(1)
acc = (receiver_output.argmax(dim=1) == labels).detach().float()
loss = F.cross_entropy(receiver_output, labels, reduction="none")
return loss, {"acc": acc}
def non_differentiable_loss(
_sender_input, _message, _receiver_input, receiver_output, labels, _aux_input
):
labels = labels.squeeze(1)
acc = (receiver_output == labels).detach().float()
return -acc, {"acc": acc}
def build_model(opts, train_loader, dump_loader):
n_features = (
train_loader.dataset.get_n_features()
if train_loader
else dump_loader.dataset.get_n_features()
)
if opts.n_classes is not None:
receiver_outputs = opts.n_classes
else:
receiver_outputs = (
train_loader.dataset.get_output_max() + 1
if train_loader
else dump_loader.dataset.get_output_max() + 1
)
sender = Sender(n_hidden=opts.sender_hidden, n_features=n_features)
if opts.train_mode.lower() == "gs":
loss = differentiable_loss
receiver = Receiver(output_size=receiver_outputs, n_hidden=opts.receiver_hidden)
else:
loss = non_differentiable_loss
receiver = ReinforceReceiver(
output_size=receiver_outputs, n_hidden=opts.receiver_hidden
)
return sender, receiver, loss
if __name__ == "__main__":
opts = get_params()
print(f"Launching game with parameters: {opts}")
device = torch.device("cuda" if opts.cuda else "cpu")
train_loader = None
if opts.train_data:
train_loader = DataLoader(
CSVDataset(path=opts.train_data),
batch_size=opts.batch_size,
shuffle=True,
num_workers=1,
)
validation_loader = None
if opts.validation_data:
validation_loader = DataLoader(
CSVDataset(path=opts.validation_data),
batch_size=opts.batch_size,
shuffle=False,
num_workers=1,
)
dump_loader = None
if opts.dump_data:
dump_loader = DataLoader(
CSVDataset(path=opts.dump_data),
batch_size=opts.batch_size,
shuffle=False,
num_workers=1,
)
assert train_loader or dump_loader, "Either training or dump data must be specified"
sender, receiver, loss = build_model(opts, train_loader, dump_loader)
if opts.train_mode.lower() == "rf":
sender = core.RnnSenderReinforce(
sender,
opts.vocab_size,
opts.sender_embedding,
opts.sender_hidden,
cell=opts.sender_cell,
max_len=opts.max_len,
num_layers=opts.sender_layers,
)
receiver = core.RnnReceiverReinforce(
receiver,
opts.vocab_size,
opts.receiver_embedding,
opts.receiver_hidden,
cell=opts.receiver_cell,
num_layers=opts.receiver_layers,
)
game = core.SenderReceiverRnnReinforce(
sender,
receiver,
non_differentiable_loss,
sender_entropy_coeff=opts.sender_entropy_coeff,
receiver_entropy_coeff=opts.receiver_entropy_coeff,
)
elif opts.train_mode.lower() == "gs":
sender = core.RnnSenderGS(
sender,
opts.vocab_size,
opts.sender_embedding,
opts.sender_hidden,
cell=opts.sender_cell,
max_len=opts.max_len,
temperature=opts.temperature,
)
receiver = core.RnnReceiverGS(
receiver,
opts.vocab_size,
opts.receiver_embedding,
opts.receiver_hidden,
cell=opts.receiver_cell,
)
game = core.SenderReceiverRnnGS(sender, receiver, differentiable_loss)
else:
raise NotImplementedError(f"Unknown training mode, {opts.mode}")
optimizer = core.build_optimizer(game.parameters())
trainer = core.Trainer(
game=game,
optimizer=optimizer,
train_data=train_loader,
validation_data=validation_loader,
)
if dump_loader is not None:
if opts.dump_output:
with open(opts.dump_output, "w") as f, contextlib.redirect_stdout(f):
dump(game, dump_loader, device, opts.train_mode.lower() == "gs")
else:
dump(game, dump_loader, device, opts.train_mode.lower() == "gs")
else:
trainer.train(n_epochs=opts.n_epochs)
core.close()