-
Notifications
You must be signed in to change notification settings - Fork 0
/
wikihow_contrastive_model.py
74 lines (59 loc) · 2.29 KB
/
wikihow_contrastive_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
import torch
from modules.modeling_bart import ContrastiveBartForConditionalGeneration
class BartWikiHow(ContrastiveBartForConditionalGeneration):
def __init__(self, config, tokenizer):
super().__init__(config, tokenizer)
def train_step(self, batch):
device = next(self.parameters()).device
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_masks'].to(device)
max_hist = batch['max_hist']
hist_l = batch['hist_l']
retrieve_ids = batch['retrieve_ids'].to(device)
retrieve_attention_mask = batch['retrieve_attention_mask'].to(device)
neg_ids = batch['neg_ids'].to(device)
lm_labels = batch["target_ids"].to(device)
neg_num_total = batch["neg_num_total"]
output = self(
input_ids=input_ids,
attention_mask=attention_mask,
hist_l=hist_l,
max_hist=max_hist,
retrieve_ids=retrieve_ids,
retrieve_attention_mask=retrieve_attention_mask,
neg_ids=neg_ids,
neg_num_total=neg_num_total,
labels=lm_labels,
)
loss = output['loss']
cl_loss = output['cl_loss']
result = {
'loss': loss + cl_loss * 0.5,
'cl_loss': cl_loss,
'lm_loss': loss
}
return result
@torch.no_grad()
def test_step(self, batch, **kwargs):
self.eval()
device = next(self.parameters()).device
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_masks'].to(device)
max_hist = batch['max_hist']
hist_l = batch['hist_l']
retrieve_ids = batch['retrieve_ids'].to(device)
retrieve_attention_mask = batch['retrieve_attention_mask'].to(device)
result = {}
output = self.generate(
input_ids=input_ids,
attention_mask=attention_mask,
hist_l=hist_l,
max_hist=max_hist,
retrieve_ids=retrieve_ids,
retrieve_attention_mask=retrieve_attention_mask,
**kwargs
)
generated_sents = self.tokenizer.batch_decode(output, skip_special_tokens=True)
result['token_ids'] = output
result['pred_ans'] = generated_sents
return result