-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmodel.py
502 lines (466 loc) · 20.4 KB
/
model.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
494
495
496
497
498
499
500
501
502
import json
import os
from typing import Dict, Tuple, Union
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from pytorch_lightning.metrics.functional import accuracy
from utils.vocab import Vocab
from utils.dire_types import TypeInfo, TypeLibCodec
from model.encoder import Encoder
from model.decoder import Decoder
class RenamingDecodeModule(pl.LightningModule):
def __init__(self, config):
super().__init__()
self.decoder = Decoder.build({**config["decoder"], "rename": True})
self.soft_mem_mask = config["decoder"]["mem_mask"] == "soft"
if self.soft_mem_mask:
self.mem_encoder = Encoder.build(config["mem_encoder"])
self.mem_decoder = Decoder.build(config["mem_decoder"])
self.decoder.mem_encoder = self.mem_encoder
self.decoder.mem_decoder = self.mem_decoder
self.beam_size = config["test"]["beam_size"]
def training_step(self, input_dict, context_encoding, target_dict):
variable_name_logits = self.decoder(context_encoding, target_dict)
if self.soft_mem_mask:
variable_name_logits = variable_name_logits[target_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_logits = self.mem_decoder(mem_encoding, target_dict)
loss = F.cross_entropy(
variable_name_logits + mem_logits,
target_dict["target_name_id"][target_dict["target_mask"]],
reduction="none",
)
else:
loss = F.cross_entropy(
# cross_entropy requires num_classes at the second dimension
variable_name_logits.transpose(1, 2),
target_dict["target_name_id"],
reduction="none",
)
loss = loss[target_dict["target_mask"]]
return loss.mean()
def shared_eval_step(self, context_encoding, input_dict, target_dict, test=False):
variable_name_logits = self.decoder(context_encoding, target_dict)
if self.soft_mem_mask:
variable_name_logits = variable_name_logits[input_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_logits = self.mem_decoder(mem_encoding, target_dict)
loss = F.cross_entropy(
variable_name_logits + mem_logits,
target_dict["target_name_id"][input_dict["target_mask"]],
reduction="none",
)
else:
loss = F.cross_entropy(
variable_name_logits.transpose(1, 2),
target_dict["target_name_id"],
reduction="none",
)
loss = loss[input_dict["target_mask"]]
targets = target_dict["target_name_id"][input_dict["target_mask"]]
preds = self.decoder.predict(
context_encoding, input_dict, None, self.beam_size if test else 0
)
return dict(
rename_loss=loss.detach().cpu(),
rename_preds=preds.detach().cpu(),
rename_targets=targets.detach().cpu(),
)
class RetypingDecodeModule(pl.LightningModule):
def __init__(self, config):
super().__init__()
self.decoder = Decoder.build({**config["decoder"]})
self.subtype = config["decoder"]["type"] in ["XfmrSubtypeDecoder"]
self.soft_mem_mask = config["decoder"]["mem_mask"] == "soft"
if self.soft_mem_mask:
self.mem_encoder = Encoder.build(config["mem_encoder"])
self.mem_decoder = Decoder.build(config["mem_decoder"])
self.decoder.mem_encoder = self.mem_encoder
self.decoder.mem_decoder = self.mem_decoder
self.beam_size = config["test"]["beam_size"]
def training_step(self, input_dict, context_encoding, target_dict):
variable_type_logits = self.decoder(context_encoding, target_dict)
if self.soft_mem_mask:
variable_type_logits = variable_type_logits[target_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_type_logits = self.mem_decoder(mem_encoding, target_dict)
loss = F.cross_entropy(
variable_type_logits + mem_type_logits,
target_dict["target_type_id"][target_dict["target_mask"]],
reduction="none",
)
else:
loss = F.cross_entropy(
variable_type_logits.transpose(1, 2),
target_dict["target_subtype_id"]
if self.subtype
else target_dict["target_type_id"],
reduction="none",
)
loss = loss[
target_dict["target_submask"]
if self.subtype
else target_dict["target_mask"]
]
return loss.mean()
def shared_eval_step(self, context_encoding, input_dict, target_dict, test=False):
variable_type_logits = self.decoder(context_encoding, target_dict)
if self.soft_mem_mask:
variable_type_logits = variable_type_logits[input_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_type_logits = self.mem_decoder(mem_encoding, target_dict)
loss = F.cross_entropy(
# cross_entropy requires num_classes at the second dimension
variable_type_logits + mem_type_logits,
target_dict["target_type_id"][input_dict["target_mask"]],
reduction="none",
)
else:
loss = F.cross_entropy(
# cross_entropy requires num_classes at the second dimension
variable_type_logits.transpose(1, 2),
target_dict["target_subtype_id"]
if self.subtype
else target_dict["target_type_id"],
reduction="none",
)
loss = loss[
target_dict["target_submask"]
if self.subtype
else target_dict["target_mask"]
]
targets = target_dict["target_type_id"][input_dict["target_mask"]]
preds = self.decoder.predict(
context_encoding, input_dict, None, self.beam_size if test else 0
)
return dict(
retype_loss=loss.detach().cpu(),
retype_preds=preds.detach().cpu(),
retype_targets=targets.detach().cpu(),
)
class InterleaveDecodeModule(pl.LightningModule):
def __init__(self, config):
super().__init__()
self.decoder = Decoder.build({**config["decoder"]})
self.soft_mem_mask = config["decoder"]["mem_mask"] == "soft"
self.beam_size = config["test"]["beam_size"]
if self.soft_mem_mask:
self.mem_encoder = Encoder.build(config["mem_encoder"])
self.mem_decoder = Decoder.build(config["mem_decoder"])
self.decoder.mem_encoder = self.mem_encoder
self.decoder.mem_decoder = self.mem_decoder
def training_step(self, input_dict, context_encoding, target_dict):
variable_type_logits, variable_name_logits = self.decoder(
context_encoding, target_dict
)
# Retype
if self.soft_mem_mask:
variable_type_logits = variable_type_logits[target_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_type_logits = self.mem_decoder(mem_encoding, target_dict)
retype_loss = F.cross_entropy(
variable_type_logits + mem_type_logits,
target_dict["target_type_id"][target_dict["target_mask"]],
reduction="none",
)
else:
retype_loss = F.cross_entropy(
variable_type_logits.transpose(1, 2),
target_dict["target_type_id"],
reduction="none",
)
retype_loss = retype_loss[target_dict["target_mask"]]
retype_loss = retype_loss.mean()
rename_loss = F.cross_entropy(
# cross_entropy requires num_classes at the second dimension
variable_name_logits.transpose(1, 2),
target_dict["target_name_id"],
reduction="none",
)
rename_loss = rename_loss[target_dict["target_mask"]].mean()
return retype_loss, rename_loss
def shared_eval_step(self, context_encoding, input_dict, target_dict, test=False):
variable_type_logits, variable_name_logits = self.decoder(
context_encoding, target_dict
)
if self.soft_mem_mask:
variable_type_logits = variable_type_logits[input_dict["target_mask"]]
mem_encoding = self.mem_encoder(input_dict)
mem_type_logits = self.mem_decoder(mem_encoding, target_dict)
retype_loss = F.cross_entropy(
variable_type_logits + mem_type_logits,
target_dict["target_type_id"][input_dict["target_mask"]],
reduction="none",
)
else:
retype_loss = F.cross_entropy(
variable_type_logits.transpose(1, 2),
target_dict["target_type_id"],
reduction="none",
)
retype_loss = retype_loss[target_dict["target_mask"]]
rename_loss = F.cross_entropy(
variable_name_logits.transpose(1, 2),
target_dict["target_name_id"],
reduction="none",
)
rename_loss = rename_loss[input_dict["target_mask"]]
ret = self.decoder.predict(
context_encoding, input_dict, None, self.beam_size if test else 0
)
retype_preds, rename_preds = ret[0], ret[1]
return dict(
retype_loss=retype_loss.detach().cpu(),
retype_targets=target_dict["target_type_id"][input_dict["target_mask"]]
.detach()
.cpu(),
retype_preds=retype_preds.detach().cpu(),
rename_loss=rename_loss.detach().cpu(),
rename_targets=target_dict["target_name_id"][input_dict["target_mask"]]
.detach()
.cpu(),
rename_preds=rename_preds.detach().cpu(),
)
class TypeReconstructionModel(pl.LightningModule):
def __init__(self, config, config_load=None):
super().__init__()
if config_load is not None:
config = config_load
self.encoder = Encoder.build(config["encoder"])
self.retype = config["data"].get("retype", False)
self.rename = config["data"].get("rename", False)
self.interleave = config["data"].get("interleave", False)
if self.interleave:
self.interleave_module = InterleaveDecodeModule(config)
else:
if self.retype:
self.retyping_module = RetypingDecodeModule(config)
if self.rename:
self.renaming_module = RenamingDecodeModule(config)
self.config = config
self.vocab = Vocab.load(config["data"]["vocab_file"])
self._preprocess()
self.soft_mem_mask = config["decoder"]["mem_mask"] == "soft"
def _preprocess(self):
self.vocab.types.struct_set = set()
for idx, type_str in self.vocab.types.id2word.items():
if type_str.startswith("struct"):
self.vocab.types.struct_set.add(idx)
with open(self.config["data"]["typelib_file"]) as type_f:
typelib = TypeLibCodec.decode(type_f.read())
self.typstr_to_piece = {}
for size in typelib:
for _, tp in typelib[size]:
self.typstr_to_piece[str(tp)] = tp.tokenize()[:-1]
self.typstr_to_piece["<unk>"] = ["<unk>"]
def training_step(
self,
batch: Tuple[Dict[str, Union[torch.Tensor, int]], Dict[str, torch.Tensor]],
batch_idx,
):
input_dict, target_dict = batch
total_loss = 0
context_encoding = self.encoder(input_dict)
if self.interleave:
retype_loss, rename_loss = self.interleave_module.training_step(
input_dict, context_encoding, target_dict
)
self.log("train_retype_loss", retype_loss)
self.log("train_rename_loss", rename_loss)
total_loss = retype_loss + rename_loss
else:
if self.retype:
loss = self.retyping_module.training_step(
input_dict, context_encoding, target_dict
)
self.log("train_retype_loss", loss)
total_loss += loss
if self.rename:
loss = self.renaming_module.training_step(
input_dict, context_encoding, target_dict
)
self.log("train_rename_loss", loss)
total_loss += loss
self.log("train_loss", total_loss)
return total_loss
def validation_step(self, batch, batch_idx):
return self._shared_eval_step(batch, batch_idx)
def test_step(self, batch, batch_idx):
return self._shared_eval_step(batch, batch_idx, test=True)
def _shared_eval_step(
self,
batch: Tuple[Dict[str, Union[torch.Tensor, int]], Dict[str, torch.Tensor]],
batch_idx,
test=False,
):
input_dict, target_dict = batch
context_encoding = self.encoder(input_dict)
ret_dict = {}
if self.interleave:
ret_dict = self.interleave_module.shared_eval_step(
context_encoding, input_dict, target_dict, test
)
else:
if self.retype:
ret = self.retyping_module.shared_eval_step(
context_encoding, input_dict, target_dict, test
)
ret_dict = {**ret, **ret_dict}
if self.rename:
ret = self.renaming_module.shared_eval_step(
context_encoding, input_dict, target_dict, test
)
ret_dict = {**ret, **ret_dict}
return dict(
**ret_dict,
targets_nums=input_dict["target_mask"].sum(dim=1),
test_meta=target_dict["test_meta"],
index=input_dict["index"],
tgt_var_names=target_dict["tgt_var_names"],
)
def validation_epoch_end(self, outputs):
self._shared_epoch_end(outputs, "val")
def test_epoch_end(self, outputs):
final_ret = self._shared_epoch_end(outputs, "test")
if "pred_file" in self.config["test"]:
results = {}
for (binary, func_name, decom_var_name), retype_pred, rename_pred in zip(
final_ret["indexes"],
final_ret["retype_preds"].tolist()
if "retype_preds" in final_ret
else [None] * len(final_ret["indexes"]),
final_ret["rename_preds"].tolist()
if "rename_preds" in final_ret
else [None] * len(final_ret["indexes"]),
):
results.setdefault(binary, {}).setdefault(func_name, {})[
decom_var_name[2:-2]
] = self.vocab.types.id2word.get(
retype_pred, ""
), self.vocab.names.id2word.get(
rename_pred, ""
)
pred_file = self.config["test"]["pred_file"]
json.dump(results, open(pred_file, "w"))
def _shared_epoch_end(self, outputs, prefix):
final_ret = {}
if self.retype:
ret = self._shared_epoch_end_task(outputs, prefix, "retype")
final_ret = {**final_ret, **ret}
if self.rename:
ret = self._shared_epoch_end_task(outputs, prefix, "rename")
final_ret = {**final_ret, **ret}
if self.retype and self.rename:
# Evaluate rename accuracy on correctedly retyped samples
retype_preds = torch.cat([x[f"retype_preds"] for x in outputs])
retype_targets = torch.cat([x[f"retype_targets"] for x in outputs])
rename_preds = torch.cat([x[f"rename_preds"] for x in outputs])
rename_targets = torch.cat([x[f"rename_targets"] for x in outputs])
if (retype_preds == retype_targets).sum() > 0:
self.log(
f"{prefix}_rename_on_correct_retype_acc",
accuracy(
rename_preds[retype_preds == retype_targets],
rename_targets[retype_preds == retype_targets],
),
)
return final_ret
def _shared_epoch_end_task(self, outputs, prefix, task):
indexes = sum([x["index"] for x in outputs], [])
tgt_var_names = sum([x["tgt_var_names"] for x in outputs], [])
preds = torch.cat([x[f"{task}_preds"] for x in outputs])
targets = torch.cat([x[f"{task}_targets"] for x in outputs])
loss = torch.cat([x[f"{task}_loss"] for x in outputs]).mean()
self.log(f"{prefix}_{task}_loss", loss)
self.log(f"{prefix}_{task}_acc", accuracy(preds, targets))
self.log(
f"{prefix}_{task}_acc_macro",
accuracy(
preds,
targets,
num_classes=len(self.vocab.types),
class_reduction="macro",
),
)
# func acc
num_correct, num_funcs, pos = 0, 0, 0
body_in_train_mask = []
name_in_train_mask = []
for target_num, test_metas in map(
lambda x: (x["targets_nums"], x["test_meta"]), outputs
):
for num, test_meta in zip(target_num.tolist(), test_metas):
num_correct += all(preds[pos : pos + num] == targets[pos : pos + num])
pos += num
body_in_train_mask += [test_meta["function_body_in_train"]] * num
name_in_train_mask += [test_meta["function_name_in_train"]] * num
num_funcs += len(target_num)
body_in_train_mask = torch.tensor(body_in_train_mask)
name_in_train_mask = torch.tensor(name_in_train_mask)
if body_in_train_mask.dim() > 1:
# HACK for data parallel
body_in_train_mask = body_in_train_mask[:, 0]
name_in_train_mask = name_in_train_mask[:, 0]
self.log(
f"{prefix}_{task}_body_in_train_acc",
accuracy(preds[body_in_train_mask], targets[body_in_train_mask]),
)
if (~body_in_train_mask).sum() > 0:
self.log(
f"{prefix}_{task}_body_not_in_train_acc",
accuracy(preds[~body_in_train_mask], targets[~body_in_train_mask]),
)
assert pos == sum(x["targets_nums"].sum() for x in outputs), (
pos,
sum(x["targets_nums"].sum() for x in outputs),
)
self.log(f"{prefix}_{task}_func_acc", num_correct / num_funcs)
struc_mask = torch.zeros(len(targets), dtype=torch.bool)
for idx, target in enumerate(targets):
if target.item() in self.vocab.types.struct_set:
struc_mask[idx] = 1
task_str = "" if task == "retype" else f"_{task}"
if struc_mask.sum() > 0:
self.log(
f"{prefix}{task_str}_struc_acc",
accuracy(preds[struc_mask], targets[struc_mask]),
)
# adjust for the number of classes
self.log(
f"{prefix}{task_str}_struc_acc_macro",
accuracy(
preds[struc_mask],
targets[struc_mask],
num_classes=len(self.vocab.types),
class_reduction="macro",
)
* len(self.vocab.types)
/ len(self.vocab.types.struct_set),
)
if (struc_mask & body_in_train_mask).sum() > 0:
self.log(
f"{prefix}{task_str}_body_in_train_struc_acc",
accuracy(
preds[struc_mask & body_in_train_mask],
targets[struc_mask & body_in_train_mask],
),
)
if (~body_in_train_mask & struc_mask).sum() > 0:
self.log(
f"{prefix}{task_str}_body_not_in_train_struc_acc",
accuracy(
preds[~body_in_train_mask & struc_mask],
targets[~body_in_train_mask & struc_mask],
),
)
return {
"indexes": indexes,
"tgt_var_names": tgt_var_names,
f"{task}_preds": preds,
f"{task}_targets": preds,
"body_in_train_mask": body_in_train_mask,
}
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=self.config["train"]["lr"])
return optimizer