-
Notifications
You must be signed in to change notification settings - Fork 6
/
inference.py
executable file
·172 lines (133 loc) · 5.18 KB
/
inference.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
#!/usr/bin/env python3
import numpy as np
import os
import logging
import re
import json
import argparse
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import nltk
from torch.utils.data import DataLoader, Dataset
from data import get_dataset_class
from collections import defaultdict
from datasets import load_dataset, dataset_dict, Dataset
from model import (
D2TTrainingModule,
OrdTrainingModule,
AggTrainingModule,
PCTrainingModule,
)
from model import add_special_tokens
from transformers import (
AutoConfig,
AutoTokenizer,
)
"""
PL modules used for inference (decoding / testing / interactive mode)
"""
logger = logging.getLogger(__name__)
class D2TInferenceModule:
def __init__(self, args, model_path, training_module_cls):
self.args = args
self.model = training_module_cls.load_from_checkpoint(model_path)
self.model.freeze()
logger.info(f"Loaded model from {model_path}")
self.model_name = self.model.model.name_or_path
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name,
use_fast=True)
def predict(self, s, beam_size=1):
inputs = self.tokenizer(s, return_tensors='pt')
if hasattr(self.args, "gpus") and self.args.gpus > 0:
self.model.cuda()
for key in inputs.keys():
inputs[key] = inputs[key].cuda()
else:
logger.warning("Not using GPU")
return self.generate(inputs["input_ids"], beam_size)
def generate(self, input_ids, beam_size):
out = self.model.model.generate(input_ids,
max_length=self.args.max_length,
num_beams=beam_size,
num_return_sequences=beam_size
)
sentences = self.tokenizer.batch_decode(out,
skip_special_tokens=True,
clean_up_tokenization_spaces=True
)
return sentences
class OrdInferenceModule(D2TInferenceModule):
def __init__(self, args, model_path):
super().__init__(args, model_path=model_path, training_module_cls=OrdTrainingModule)
def __call__(self, sequences, decoder_start_token_ids=[0, 2], num_beams=1):
inputs = self.tokenizer(
f" {self.tokenizer.eos_token}{self.tokenizer.bos_token} ".join(sequences) \
+ f" {self.tokenizer.eos_token}{self.tokenizer.bos_token}",
truncation=True,
max_length=self.args.max_length,
return_tensors="pt",
)
# if hasattr(self.args, "gpus") and self.args.gpus > 0:
# self.model.cuda()
# for key in inputs.keys():
# inputs[key] = inputs[key].cuda()
# else:
# logger.warning("Not using GPU")
output = self.model.order(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
decoder_start_token_ids=decoder_start_token_ids,
num_beams=num_beams,
)
output = output[0]
output.remove(max(output))
for i in range(len(sequences)):
if i not in output:
output.append(i)
assert len(output) == len(sequences)
return output
def order(self, sequences, decoder_start_token_ids=[0, 2], num_beams=1):
output = self(sequences, decoder_start_token_ids, num_beams)
ordered_sequences = []
for idx in output:
ordered_sequences.append(sequences[idx])
return ordered_sequences
def order_indices(self, sequences, decoder_start_token_ids=[0, 2], num_beams=1):
output = self(sequences, decoder_start_token_ids, num_beams)
return np.argsort(output)
def predict(self, s, beam_size=1):
sequences = nltk.sent_tokenize(s)
output = self(sequences, num_beams=beam_size)
ordered_sequences = []
for idx in output:
ordered_sequences.append(sequences[idx])
return ordered_sequences
class AggInferenceModule(D2TInferenceModule):
def __init__(self, args, model_path):
super().__init__(args, model_path=model_path, training_module_cls=AggTrainingModule)
def predict(self, sents, beam_size=1):
if type(sents) == str:
sents = nltk.sent_tokenize(sents)
text = f" {self.tokenizer.sep_token} ".join(sents)
inputs = self.tokenizer(text,
max_length=self.args.max_length,
truncation=True,
return_tensors='pt'
)
if hasattr(self.args, "gpus") and self.args.gpus > 0:
self.model.cuda()
for key in inputs.keys():
inputs[key] = inputs[key].cuda()
else:
logger.warning("Not using GPU")
logits = self.model.model.forward(inputs["input_ids"])["logits"]
preds = torch.argmax(logits, axis=2)
seps = preds[inputs["input_ids"] == self.tokenizer.sep_token_id][:-1]
return seps.tolist()
class PCInferenceModule(D2TInferenceModule):
def __init__(self, args, model_path):
super().__init__(args, model_path=model_path, training_module_cls=PCTrainingModule)
add_special_tokens(self.tokenizer, None)