forked from OpenNMT/OpenNMT-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinference_engine.py
executable file
·258 lines (228 loc) · 9.38 KB
/
inference_engine.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
import json
from onmt.constants import CorpusTask, DefaultTokens, ModelTask
from onmt.inputters.dynamic_iterator import build_dynamic_dataset_iter
from onmt.utils.distributed import ErrorHandler, spawned_infer
from onmt.utils.logging import init_logger
from onmt.transforms import get_transforms_cls, make_transforms, TransformPipe
class InferenceEngine(object):
"""Wrapper Class to run Inference.
Args:
opt: inference options
"""
def __init__(self, opt):
self.opt = opt
def translate_batch(self, batch):
pass
def _translate(self, infer_iter):
pass
def infer_file(self):
"""File inference. Source file must be the opt.src argument"""
if self.opt.world_size <= 1:
infer_iter = build_dynamic_dataset_iter(
self.opt,
self.transforms_cls,
self.vocabs,
task=CorpusTask.INFER,
device_id=self.device_id,
)
scores, preds = self._translate(infer_iter)
else:
scores, preds = self.infer_file_parallel()
return scores, preds
def infer_list(self, src):
"""List of strings inference `src`"""
if self.opt.world_size <= 1:
infer_iter = build_dynamic_dataset_iter(
self.opt,
self.transforms_cls,
self.vocabs,
task=CorpusTask.INFER,
src=src,
device_id=self.device_id,
)
scores, preds = self._translate(infer_iter)
else:
scores, preds = self.infer_list_parallel(src)
return scores, preds
def infer_file_parallel(self):
"""File inference in mulitprocessing with partitioned models."""
raise NotImplementedError(
"The inference in mulitprocessing with partitioned models is not implemented."
)
def infer_list_parallel(self, src):
"""The inference in mulitprocessing with partitioned models."""
raise NotImplementedError(
"The inference in mulitprocessing with partitioned models is not implemented."
)
def terminate(self):
pass
class InferenceEnginePY(InferenceEngine):
"""Inference engine subclass to run inference with `translate.py`.
Args:
opt: inference options
"""
def __init__(self, opt):
import torch
from onmt.translate.translator import build_translator
super().__init__(opt)
self.opt = opt
self.logger = init_logger(opt.log_file)
if opt.world_size > 1:
mp = torch.multiprocessing.get_context("spawn")
# Create a thread to listen for errors in the child processes.
self.error_queue = mp.SimpleQueue()
self.error_handler = ErrorHandler(self.error_queue)
self.queue_instruct = []
self.queue_result = []
self.procs = []
for device_id in range(opt.world_size):
self.queue_instruct.append(mp.Queue())
self.queue_result.append(mp.Queue())
self.procs.append(
mp.Process(
target=spawned_infer,
args=(
opt,
device_id,
self.error_queue,
self.queue_instruct[device_id],
self.queue_result[device_id],
),
daemon=False,
)
)
self.procs[device_id].start()
self.error_handler.add_child(self.procs[device_id].pid)
else:
self.device_id = opt.gpu
self.translator = build_translator(
opt, self.device_id, logger=self.logger, report_score=True
)
self.transforms_cls = get_transforms_cls(opt._all_transform)
self.vocabs = self.translator.vocabs
def _translate(self, infer_iter):
scores, preds = self.translator._translate(
infer_iter, infer_iter.transforms, self.opt.attn_debug, self.opt.align_debug
)
return scores, preds
def infer_file_parallel(self):
assert self.opt.world_size > 1, "World size must be greater than 1."
for device_id in range(self.opt.world_size):
self.queue_instruct[device_id].put(("infer_file", self.opt))
scores, preds = [], []
for device_id in range(self.opt.world_size):
scores.append(self.queue_result[device_id].get())
preds.append(self.queue_result[device_id].get())
return scores[0], preds[0]
def infer_list_parallel(self, src):
for device_id in range(self.opt.world_size):
self.queue_instruct[device_id].put(("infer_list", src))
scores, preds = [], []
for device_id in range(self.opt.world_size):
scores.append(self.queue_result[device_id].get())
preds.append(self.queue_result[device_id].get())
return scores[0], preds[0]
def terminate(self):
if self.opt.world_size > 1:
for device_id in range(self.opt.world_size):
self.queue_instruct[device_id].put(("stop"))
self.procs[device_id].terminate()
class InferenceEngineCT2(InferenceEngine):
"""Inference engine subclass to run inference with ctranslate2.
Args:
opt: inference options
"""
def __init__(self, opt):
import ctranslate2
import pyonmttok
super().__init__(opt)
self.opt = opt
self.logger = init_logger(opt.log_file)
assert self.opt.world_size <= 1, "World size must be less than 1."
self.device_id = opt.gpu
if opt.world_size == 1:
self.device_index = opt.gpu_ranks
self.device = "cuda"
else:
self.device_index = 0
self.device = "cpu"
self.transforms_cls = get_transforms_cls(self.opt._all_transform)
# Build translator
if opt.model_task == ModelTask.LANGUAGE_MODEL:
self.translator = ctranslate2.Generator(
opt.models[0], device=self.device, device_index=self.device_index
)
else:
self.translator = ctranslate2.Translator(
self.opt.models[0], device=self.device, device_index=self.device_index
)
# Build vocab
vocab_path = opt.src_subword_vocab
with open(vocab_path, "r") as f:
vocab = json.load(f)
vocabs = {}
src_vocab = pyonmttok.build_vocab_from_tokens(vocab)
vocabs["src"] = src_vocab
vocabs["tgt"] = src_vocab
vocabs["data_task"] = "lm"
vocabs["decoder_start_token"] = "<s>"
self.vocabs = vocabs
# Build transform pipe
transforms = make_transforms(opt, self.transforms_cls, self.vocabs)
self.transform = TransformPipe.build_from(transforms.values())
def translate_batch(self, batch, opt):
input_tokens = []
for i in range(batch["src"].size()[0]):
start_ids = batch["src"][i, :, 0].cpu().numpy().tolist()
_input_tokens = [
self.vocabs["src"].lookup_index(id)
for id in start_ids
if id != self.vocabs["src"].lookup_token(DefaultTokens.PAD)
]
input_tokens.append(_input_tokens)
if opt.model_task == ModelTask.LANGUAGE_MODEL:
translated_batch = self.translator.generate_batch(
start_tokens=input_tokens,
batch_type=("examples" if opt.batch_type == "sents" else "tokens"),
max_batch_size=opt.batch_size,
beam_size=opt.beam_size,
num_hypotheses=opt.n_best,
max_length=opt.max_length,
return_scores=True,
include_prompt_in_result=False,
sampling_topk=opt.random_sampling_topk,
sampling_topp=opt.random_sampling_topp,
sampling_temperature=opt.random_sampling_temp,
)
preds = [
[self.transform.apply_reverse(tokens) for tokens in out.sequences]
for out in translated_batch
]
scores = [out.scores for out in translated_batch]
elif opt.model_task == ModelTask.SEQ2SEQ:
translated_batch = self.translator.translate_batch(
input_tokens,
batch_type=("examples" if opt.batch_type == "sents" else "tokens"),
max_batch_size=opt.batch_size,
beam_size=opt.beam_size,
num_hypotheses=opt.n_best,
max_decoding_length=opt.max_length,
return_scores=True,
sampling_topk=opt.random_sampling_topk,
sampling_topp=opt.random_sampling_topp,
sampling_temperature=opt.random_sampling_temp,
)
preds = [
[self.transform.apply_reverse(tokens) for tokens in out.hypotheses]
for out in translated_batch
]
scores = [out.scores for out in translated_batch]
return scores, preds
def _translate(self, infer_iter):
scores = []
preds = []
for batch, bucket_idx in infer_iter:
_scores, _preds = self.translate_batch(batch, self.opt)
scores += _scores
preds += _preds
return scores, preds