forked from OpenNMT/CTranslate2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
benchmark.py
305 lines (261 loc) · 8.46 KB
/
benchmark.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import GPUtil
import argparse
import collections
import docker
import os
import sacrebleu
import tempfile
import time
client = docker.from_env()
docker_version = client.version()["Version"]
docker_version_numbers = docker_version.split(".")
docker_major_version = int(docker_version_numbers[0])
docker_minor_version = int(docker_version_numbers[1])
def _get_bleu_score(hyp_file, ref_file):
with open(hyp_file) as hyp, open(ref_file) as ref:
bleu = sacrebleu.corpus_bleu(hyp, [ref], force=True)
return bleu.score
def _count_tokens(path):
with open(path) as file:
num_tokens = 0
for line in file:
num_tokens += len(line.strip().split(" "))
return num_tokens
def _monitor_container(container, poll_interval=1, use_gpu=False):
max_cpu_mem = 0
max_gpu_mem = 0
result = None
while True:
try:
result = container.wait(timeout=1)
break
except:
pass
stats = container.stats(stream=False)
memory_stats = stats["memory_stats"]
memory_usage = memory_stats.get("usage")
if memory_usage is not None:
max_cpu_mem = max(max_cpu_mem, float(memory_usage / 1000000))
if use_gpu:
max_gpu_mem = max(max_gpu_mem, float(GPUtil.getGPUs()[0].memoryUsed))
if result is not None and result["StatusCode"] != 0:
stderr = container.logs(stdout=False).decode("utf-8")
raise RuntimeError(
"Container exited with status code %d:\n\n%s"
% (result["StatusCode"], stderr)
)
return max_cpu_mem, max_gpu_mem
def _process_file(image_name, script, input_file, output_file):
input_dir = "/input"
output_dir = "/output"
client.containers.run(
image_name,
command=[
os.path.join(input_dir, os.path.basename(input_file)),
os.path.join(output_dir, os.path.basename(output_file)),
],
entrypoint=script,
remove=True,
mounts=[
docker.types.Mount(input_dir, os.path.dirname(input_file), type="bind"),
docker.types.Mount(output_dir, os.path.dirname(output_file), type="bind"),
],
)
def _tokenize(image_name, input_file, output_file):
return _process_file(image_name, "/tokenize", input_file, output_file)
def _detokenize(image_name, input_file, output_file):
return _process_file(image_name, "/detokenize", input_file, output_file)
def _start_translation(
image_name,
source_file,
output_file,
environment,
num_cpus,
use_gpu,
):
kwargs = {}
environment = environment.copy() if environment else {}
environment["OMP_NUM_THREADS"] = str(num_cpus)
if use_gpu:
device = "GPU"
if docker_major_version < 19 or (
docker_major_version == 19 and docker_minor_version < 3
):
kwargs["runtime"] = "nvidia"
else:
kwargs["device_requests"] = [
docker.types.DeviceRequest(count=0, capabilities=[["gpu"]])
]
else:
device = "CPU"
environment["CUDA_VISIBLE_DEVICES"] = ""
data_dir = "/data"
output_dir = "/output"
container = client.containers.run(
image_name,
[
device,
os.path.join(data_dir, os.path.basename(source_file)),
os.path.join(output_dir, os.path.basename(output_file)),
],
entrypoint="/translate",
detach=True,
mounts=[
docker.types.Mount(data_dir, os.path.dirname(source_file), type="bind"),
docker.types.Mount(output_dir, os.path.dirname(output_file), type="bind"),
],
environment=environment,
**kwargs
)
return container
def _benchmark_translation(
image_name,
source_file,
target_file,
environment,
num_cpus,
use_gpu,
):
with tempfile.TemporaryDirectory() as tmp_dir:
source_file_tok = os.path.join(tmp_dir, "source.txt.tok")
output_file_tok = os.path.join(tmp_dir, "output.txt.tok")
output_file = os.path.join(tmp_dir, "output.txt")
_tokenize(image_name, source_file, source_file_tok)
container = _start_translation(
image_name,
source_file_tok,
output_file_tok,
environment,
num_cpus,
use_gpu,
)
try:
start = time.time()
max_cpu_mem, max_gpu_mem = _monitor_container(container, use_gpu=use_gpu)
end = time.time()
elapsed_time = end - start
num_tokens = _count_tokens(output_file_tok)
_detokenize(image_name, output_file_tok, output_file)
bleu = _get_bleu_score(output_file, target_file)
return elapsed_time, num_tokens, max_cpu_mem, max_gpu_mem, bleu
finally:
container.remove(force=True)
class BenchmarkResult(
collections.namedtuple(
"BenchmarkResult",
(
"total_time",
"translation_time",
"num_tokens",
"max_cpu_mem",
"max_gpu_mem",
"bleu_score",
),
)
):
pass
def benchmark_image(
image_name,
source_file,
target_file,
num_samples=1,
environment=None,
num_cpus=4,
use_gpu=False,
):
source_file = os.path.abspath(source_file)
target_file = os.path.abspath(target_file)
initialization_time = None
with tempfile.NamedTemporaryFile() as tmp_file:
for _ in range(num_samples):
container = _start_translation(
image_name,
tmp_file.name,
tmp_file.name,
environment,
num_cpus,
use_gpu,
)
try:
start = time.time()
container.wait()
end = time.time()
elapsed_time = end - start
initialization_time = (
elapsed_time
if initialization_time is None
else min(initialization_time, elapsed_time)
)
finally:
container.remove(force=True)
total_time = None
num_tokens = 0
bleu = 0
max_cpu_mem = 0
max_gpu_mem = 0
for _ in range(num_samples):
results = _benchmark_translation(
image_name,
source_file,
target_file,
environment,
num_cpus,
use_gpu,
)
total_time = results[0] if total_time is None else min(total_time, results[0])
num_tokens = results[1]
max_cpu_mem = max(max_cpu_mem, results[2])
max_gpu_mem = max(max_gpu_mem, results[3])
bleu = results[4]
translation_time = total_time - initialization_time
return BenchmarkResult(
total_time,
translation_time,
num_tokens,
max_cpu_mem,
max_gpu_mem,
bleu,
)
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--num_samples",
type=int,
default=1,
help="aggregate results over this number of runs",
)
parser.add_argument("--num_cpus", type=int, default=4, help="number of CPUs to use")
parser.add_argument("--gpu", action="store_true", help="run on GPU")
parser.add_argument(
"--env",
type=str,
nargs=2,
action="append",
default=[],
help="add this environment variable to the Docker container",
)
parser.add_argument("image", type=str, help="name of Docker image to benchmark")
parser.add_argument("src", type=str, help="source file")
parser.add_argument("ref", type=str, help="reference file")
args = parser.parse_args()
result = benchmark_image(
args.image,
args.src,
args.ref,
num_samples=args.num_samples,
environment={key: value for key, value in args.env},
num_cpus=args.num_cpus,
use_gpu=args.gpu,
)
print("Benchmark result (%d sample(s)):" % args.num_samples)
print("- total time: %.2f s" % result.total_time)
print("- translation time: %.2f s" % result.translation_time)
print("- tokens per second: %.1f" % (result.num_tokens / result.translation_time))
print("- max. CPU memory usage: %dMB" % int(result.max_cpu_mem))
if args.gpu:
print("- max. GPU memory usage: %dMB" % int(result.max_gpu_mem))
print("- BLEU score: %.2f" % result.bleu_score)
if __name__ == "__main__":
main()