-
Notifications
You must be signed in to change notification settings - Fork 7
/
transition.py
53 lines (44 loc) · 1.68 KB
/
transition.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
import json
import sys
import torch
from tqdm.auto import tqdm
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
if __name__ == "__main__":
device = "cuda" if torch.cuda.is_available() else "cpu"
t5_transition = []
with open(sys.argv[1], "r") as f:
for dialog in tqdm(json.load(f)):
position = dialog["intent"]["position"]
checkpoint = "stanleychu2/t5-transition"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint).to(device)
model.eval()
context = " ".join(dialog["dialog"][: position + 1])
future = dialog["dialog"][position + 2]
example = (
f"<context> {context} </context> <blank> <future> {future} </future>"
)
inputs = tokenizer(
example, max_length=512, truncation=True, return_tensors="pt"
).to(device)
outputs = model.generate(
**inputs,
do_sample=True,
top_k=80,
top_p=0.95,
max_length=64,
repetition_penalty=0.8,
num_return_sequences=4,
).squeeze(0)
transition_sentence = [
tokenizer.decode(i, skip_special_tokens=True) for i in outputs
]
dialog["dialog"][position + 1] = transition_sentence[0]
dialog["transition_candidates"] = transition_sentence
t5_transition.append(dialog)
json.dump(
t5_transition,
open(f"{sys.argv[1].split('.')[0]}_transition.json", "w"),
indent=4,
ensure_ascii=False,
)