forked from LibreTranslate/Locomotive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py
135 lines (114 loc) · 4.43 KB
/
eval.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
import os
import json
import argparse
import ctranslate2
import sentencepiece
from sacrebleu import corpus_bleu
from data import get_flores
from tokenizer import BPETokenizer, SentencePieceTokenizer
parser = argparse.ArgumentParser(description='Evaluate LibreTranslate compatible models')
parser.add_argument('--config',
type=str,
default="model-config.json",
help='Path to model-config.json. Default: %(default)s')
parser.add_argument('--reverse',
action='store_true',
help='Reverse the source and target languages in the configuration and data sources. Default: %(default)s')
parser.add_argument('--bleu',
action="store_true",
help='Evaluate BLEU score. Default: %(default)s')
parser.add_argument('--flores-id',
type=int,
default=None,
help='Evaluate this flores sentence ID. Default: %(default)s')
parser.add_argument('--tokens',
action="store_true",
help='Display tokens rather than words. Default: %(default)s')
parser.add_argument('--cpu',
action="store_true",
help='Force CPU use. Default: %(default)s')
parser.add_argument('--max-batch-size',
type=int,
default=16,
help='Max batch size for translation. Default: %(default)s')
args = parser.parse_args()
try:
with open(args.config) as f:
config = json.loads(f.read())
if args.reverse:
config["from"], config["to"] = config["to"], config["from"]
except Exception as e:
print(f"Cannot open config file: {e}")
exit(1)
current_dir = os.path.dirname(__file__)
cache_dir = os.path.join(current_dir, "cache")
model_dirname = f"{config['from']['code']}_{config['to']['code']}-{config['version']}"
run_dir = os.path.join(current_dir, "run", model_dirname)
ct2_model_dir = os.path.join(run_dir, "model")
sp_model = os.path.join(run_dir, "sentencepiece.model")
bpe_model = os.path.join(run_dir, "bpe.model")
if not os.path.isdir(ct2_model_dir) or (not os.path.isfile(sp_model) and not os.path.isfile(bpe_model)):
print(f"The model in {run_dir} is not valid. Did you run train.py first?")
exit(1)
def translator():
device = "cuda" if ctranslate2.get_cuda_device_count() > 0 and not args.cpu else "cpu"
model = ctranslate2.Translator(ct2_model_dir, device=device, compute_type="default")
if os.path.isfile(sp_model):
tokenizer = SentencePieceTokenizer(sp_model)
elif os.path.isfile(bpe_model):
tokenizer = BPETokenizer(bpe_model, config["from"]["code"], config["to"]["code"])
return {"model": model, "tokenizer": tokenizer}
def encode(text, tokenizer):
return tokenizer.encode(text)
def decode(tokens, tokenizer):
if args.tokens:
return " ".join(tokens)
else:
detokenized = tokenizer.decode(tokens)
if len(detokenized) > 0 and detokenized[0] == " ":
detokenized = detokenized[1:]
return detokenized
data = translator()
if args.bleu or args.flores_id is not None:
src_text = get_flores(config["from"]["code"], "dev")
tgt_text = get_flores(config["to"]["code"], "dev")
if args.flores_id is not None:
src_text = [src_text[args.flores_id]]
tgt_text = [tgt_text[args.flores_id]]
translation_obj = data["model"].translate_batch(
[encode(t, data["tokenizer"]) for t in src_text],
beam_size=4, # same as argos
return_scores=False, # speed up,
max_batch_size=args.max_batch_size,
)
translated_text = [
decode(tokens.hypotheses[0], data["tokenizer"])
for tokens in translation_obj
]
bleu_score = round(corpus_bleu(
translated_text, [[x] for x in tgt_text]
).score, 5)
if args.flores_id is not None:
print(f"({config['from']['code']})> {src_text[0]}\n(gt)> {tgt_text[0]}\n({config['to']['code']})> {' '.join(translated_text)}")
else:
print(f"BLEU score: {bleu_score}")
else:
# Interactive mode
print("Starting interactive mode")
while True:
try:
text = input(f"({config['from']['code']})> ")
except KeyboardInterrupt:
print("")
exit(0)
src_text = text.rstrip('\n')
translation_obj = data["model"].translate_batch(
[encode(src_text, data["tokenizer"])],
beam_size=4, # same as argos
return_scores=False, # speed up
)
translated_text = [
decode(tokens.hypotheses[0], data["tokenizer"])
for tokens in translation_obj
]
print(f"({config['to']['code']})> {translated_text[0]}")