aio_bench_perf_sweep.py 10.4 KB
Newer Older
aiss's avatar
aiss committed
1
2
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
aiss's avatar
aiss committed
3

aiss's avatar
aiss committed
4
5
# DeepSpeed Team
"""
aiss's avatar
aiss committed
6
7
8
9
10
11
12
13
14
15
16
17
18
Functionality of swapping optimizer tensors to/from (NVMe) storage devices.
"""
import os
import sys
import argparse
import json
import itertools
import subprocess
import shutil

from test_ds_aio_utils import refine_integer_value
from perf_sweep_utils import READ_OP_DESC, WRITE_OP_DESC, BENCH_LOG_DIR, \
    READ_IO_DIR, WRITE_IO_DIR, READ_LOG_DIR, WRITE_LOG_DIR
aiss's avatar
aiss committed
19
from deepspeed.ops.op_builder import AsyncIOBuilder
aiss's avatar
aiss committed
20
21
22
23

OTHER_OPTIONS = '--handle'
PERF_SCRIPT = 'test_ds_aio.py'
DEFAULT_SWEEP_CONFIG = {
aiss's avatar
aiss committed
24
25
26
27
    "block_size": ["128K", "256K"],
    "queue_depth": [4, 16, 32],
    "overlap_events": [True, False],
    "io_parallel": [2, 8],
aiss's avatar
aiss committed
28
29
30
31
32
    "single_submit": [False]
}


class Job(object):
aiss's avatar
aiss committed
33

aiss's avatar
aiss committed
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
    def __init__(self, cmd_line, output_file=None, work_dir=None):
        self.cmd_line = cmd_line
        self.output_file = output_file
        self.work_dir = work_dir
        self.output_fd = None

    def cmd(self):
        return self.cmd_line

    def get_stdout(self):
        return self.output_fd

    def get_stderr(self):
        return self.output_fd

    def get_cwd(self):
        return self.work_dir

    def open_output_file(self):
        if self.output_file is not None:
            self.output_fd = open(self.output_file, 'w')

    def close_output_file(self):
        if self.output_fd is not None:
            self.output_fd.close()
            self.output_fd = None


class SweepConfig(object):
aiss's avatar
aiss committed
63

aiss's avatar
aiss committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    def __init__(self, args):
        self.nvme_dir = args.nvme_dir
        self.io_size = args.io_size
        self.search_space = get_sweep_config_dict(args.sweep_config)
        self.read = not args.no_read
        self.write = not args.no_write
        self.flush_cache = not args.no_sudo
        self.log_dir = args.log_dir
        self.loops = args.loops
        self.other_options = f'{OTHER_OPTIONS} --loops {args.loops}'


def parse_arguments():
    parser = argparse.ArgumentParser()

aiss's avatar
aiss committed
79
80
    parser.add_argument('--nvme_dir',
                        required=True,
aiss's avatar
aiss committed
81
                        type=str,
aiss's avatar
aiss committed
82
                        help='Directory in which to perform I/O tests. A writeable directory on a NVMe device.')
aiss's avatar
aiss committed
83

aiss's avatar
aiss committed
84
    parser.add_argument('--sweep_config', type=str, default=None, help='Performance sweep configuration json file.')
aiss's avatar
aiss committed
85

aiss's avatar
aiss committed
86
    parser.add_argument('--no_read', action='store_true', help='Disable read performance measurements.')
aiss's avatar
aiss committed
87

aiss's avatar
aiss committed
88
89
90
91
92
93
    parser.add_argument('--no_write', action='store_true', help='Disable write performance measurements.')

    parser.add_argument('--io_size',
                        type=str,
                        default="400M",
                        help='Number of I/O bytes to read/write for performance measurements.')
aiss's avatar
aiss committed
94
95
96
97
98

    parser.add_argument(
        '--no_sudo',
        action='store_true',
        help=
aiss's avatar
aiss committed
99
        'Run without sudo access. Page cache will not be flushed and reported read speeds may be higher than actual.')
aiss's avatar
aiss committed
100
101
102
103
104

    parser.add_argument(
        '--log_dir',
        type=str,
        default=BENCH_LOG_DIR,
aiss's avatar
aiss committed
105
        help=f'Output directory for performance log files. Default is {os.path.join(".", BENCH_LOG_DIR)}')
aiss's avatar
aiss committed
106

aiss's avatar
aiss committed
107
    parser.add_argument('--loops', type=int, default=1, help='Count of operation repetitions')
aiss's avatar
aiss committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

    args = parser.parse_args()
    print(f'args = {args}')

    return args


def dump_cmd_lines(cmd_lines):
    print(f'cmd line count =  {len(cmd_lines)}')
    for i, cmd in enumerate(cmd_lines):
        print(f'{i}:  {cmd}')


def get_sweep_config_dict(sweep_config_json):
    if sweep_config_json is None:
        return DEFAULT_SWEEP_CONFIG

    with open(sweep_config_json) as fp:
        sweep_config = json.load(fp)
    return sweep_config


def get_sweep_cmd_lines(sweep_config_dict):
aiss's avatar
aiss committed
131

aiss's avatar
aiss committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    def flatten_options(key, value_list):
        flat_list = []
        for v in value_list:
            if not type(v) is bool:
                flat_list.append(f'--{key} {v}')
            elif v:
                flat_list.append(f'--{key}')
            else:
                flat_list.append(' ')

        return flat_list

    flat_list = [flatten_options(key, value) for key, value in sweep_config_dict.items()]
    cmd_list = list(itertools.product(*flat_list))
    cmd_list = [list(cmd) for cmd in cmd_list]
    #dump_cmd_lines(cmd_list)
    return cmd_list


def run_job(job):
    args = ' '.join(job.cmd())
    print(f'args = {args}')
    job.open_output_file()
aiss's avatar
aiss committed
155
    proc = subprocess.run(args=args, shell=True, stdout=job.get_stdout(), stderr=job.get_stderr(), cwd=job.get_cwd())
aiss's avatar
aiss committed
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
    job.close_output_file()
    assert proc.returncode == 0, \
    f"This command failed: {job.cmd()}"


def launch_sweep(sweep_jobs, sync_job, flush_cache_job):
    for perf_job in sweep_jobs:
        if flush_cache_job is not None:
            run_job(sync_job)
            run_job(flush_cache_job)

        run_job(perf_job)

        run_job(sync_job)


def create_cmd_tags(cmd_line):
    tags = {}
    for param_value in cmd_line:
        fields = param_value.split()
        if len(fields) == 1:
            tags[fields[0]] = None
        elif len(fields) == 2:
            tags[fields[0]] = fields[1]
    return tags


def get_log_file(io_op_desc, cmd_line):
    QUEUE_DEPTH = "--queue_depth"
    BLOCK_SIZE = "--block_size"
    SINGLE_SUBMIT = "--single_submit"
    OVERLAP_EVENTS = "--overlap_events"
    THREAD_COUNT = "--threads"
    IO_PARALLEL = "--io_parallel"

    tag_map = {
        QUEUE_DEPTH: "d",
        BLOCK_SIZE: "bs",
        SINGLE_SUBMIT: "single",
        OVERLAP_EVENTS: "overlap",
        THREAD_COUNT: "t",
        IO_PARALLEL: "p"
    }

    tag_default = {
        QUEUE_DEPTH: 1,
        BLOCK_SIZE: "1M",
        SINGLE_SUBMIT: "block",
        OVERLAP_EVENTS: "sequential",
        THREAD_COUNT: 1,
        IO_PARALLEL: 1
    }

    def get_default_value(tag):
        value = tag_default[tag]
        if tag in [SINGLE_SUBMIT, OVERLAP_EVENTS]:
            return value
        return f'{tag_map[tag]}{value}'

    def get_config_value(tag, value):
        tag_key = tag_map[tag]
        if value is None:
            return tag_key
        return f'{tag_key}{value}'

aiss's avatar
aiss committed
221
    tag_list = [SINGLE_SUBMIT, OVERLAP_EVENTS, THREAD_COUNT, IO_PARALLEL, QUEUE_DEPTH, BLOCK_SIZE]
aiss's avatar
aiss committed
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
    log_tags = [io_op_desc]
    cmd_tags = create_cmd_tags(cmd_line)
    for tag in tag_list:
        if tag in cmd_tags:
            log_tags.append(get_config_value(tag, cmd_tags[tag]))
        else:
            log_tags.append(get_default_value(tag))

    log_file = '_'.join(log_tags)
    log_file += '.txt'
    return log_file


def create_perf_jobs(io_op_desc, log_dir, cmd_lines):
    py_cmd = ['python', os.path.join(script_path(), PERF_SCRIPT)]

    perf_jobs = []
    for cmd in cmd_lines:
        log_file = os.path.join(log_dir, get_log_file(io_op_desc, cmd))
        job = Job(cmd_line=py_cmd + cmd, output_file=log_file)
        perf_jobs.append(job)

    return perf_jobs


def script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))


def async_io_setup():
    return AsyncIOBuilder().is_compatible()


def get_block_size_and_count(io_bytes):
    block_size = 1
    block_count = io_bytes
    bytes_in_KB = 1024

    while block_count % bytes_in_KB == 0:
        block_size *= bytes_in_KB
        block_count /= bytes_in_KB

    return int(block_size), int(block_count)


def create_read_file(sweep_config):
    read_folder = os.path.join(sweep_config.nvme_dir, f'{READ_IO_DIR}')
    os.makedirs(read_folder, exist_ok=True)
    read_file_name = os.path.join(read_folder, f'random_{sweep_config.io_size}B.pt')
    block_size, block_count = get_block_size_and_count(refine_integer_value(sweep_config.io_size))
aiss's avatar
aiss committed
272
273
    dd_job = Job(cmd_line=[f'dd if=/dev/urandom of={read_file_name} bs={block_size} count={block_count}'])
    print(f'[Start] Create read file of {sweep_config.io_size} bytes by running {dd_job.cmd()} ....')
aiss's avatar
aiss committed
274
    run_job(dd_job)
aiss's avatar
aiss committed
275
    print(f'[Done] Create read file of {sweep_config.io_size} bytes by running {dd_job.cmd()} ....')
aiss's avatar
aiss committed
276
277
278
279
280
281
282
283
284
285
286
    return read_folder, read_file_name


def remove_folder(folder):
    assert os.path.isdir(folder), f"Error: cannot remove {folder} - folder not found"
    shutil.rmtree(folder)


def run_read_sweep(sweep_config, flush_cache_job, sync_job, cmd_lines):
    read_folder, read_file_name = create_read_file(sweep_config)
    read_option = f'--read_file {read_file_name}'
aiss's avatar
aiss committed
287
    read_cmd_lines = [[f'{read_option} {sweep_config.other_options}'] + cmd for cmd in cmd_lines]
aiss's avatar
aiss committed
288
289
290
291
292
    #dump_cmd_lines(read_cmd_lines)

    log_folder = os.path.join(sweep_config.log_dir, f'{READ_LOG_DIR}')
    os.makedirs(log_folder, exist_ok=True)

aiss's avatar
aiss committed
293
    perf_jobs = create_perf_jobs(io_op_desc=READ_OP_DESC, log_dir=log_folder, cmd_lines=read_cmd_lines)
aiss's avatar
aiss committed
294

aiss's avatar
aiss committed
295
    launch_sweep(sweep_jobs=perf_jobs, sync_job=sync_job, flush_cache_job=flush_cache_job)
aiss's avatar
aiss committed
296
297
298
299
300
301
302
303
304

    remove_folder(read_folder)


def run_write_sweep(sweep_config, flush_cache_job, sync_job, cmd_lines):
    write_folder = os.path.join(sweep_config.nvme_dir, f'{WRITE_IO_DIR}')
    os.makedirs(write_folder, exist_ok=True)
    write_file_name = os.path.join(write_folder, f'random_{sweep_config.io_size}B.pt')
    write_option = f'--write_size {sweep_config.io_size} --write_file {write_file_name}'
aiss's avatar
aiss committed
305
    write_cmd_lines = [[f'{write_option} {sweep_config.other_options}'] + cmd for cmd in cmd_lines]
aiss's avatar
aiss committed
306
307
308
309
310
    #dump_cmd_lines(write_cmd_lines)

    log_folder = os.path.join(sweep_config.log_dir, f'{WRITE_LOG_DIR}')
    os.makedirs(log_folder, exist_ok=True)

aiss's avatar
aiss committed
311
    perf_jobs = create_perf_jobs(io_op_desc=WRITE_OP_DESC, log_dir=log_folder, cmd_lines=write_cmd_lines)
aiss's avatar
aiss committed
312

aiss's avatar
aiss committed
313
    launch_sweep(sweep_jobs=perf_jobs, sync_job=sync_job, flush_cache_job=flush_cache_job)
aiss's avatar
aiss committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333

    remove_folder(write_folder)


def main():
    print("Running performance sweep of deepspeed nvme library")

    if not async_io_setup():
        error_msg = """
            Failing because environment is not properly configured for deepspeed async i/o module.
            Possible fix: apt install libaio-dev.
        """
        print(error_msg)
        quit()

    args = parse_arguments()
    sweep_config = SweepConfig(args)
    cmd_lines = get_sweep_cmd_lines(sweep_config.search_space)

    if sweep_config.flush_cache:
aiss's avatar
aiss committed
334
        flush_cache_job = Job(cmd_line=['sudo', 'bash -c', "'echo 1 > /proc/sys/vm/drop_caches'"])
aiss's avatar
aiss committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
    else:
        flush_cache_job = None

    sync_job = Job(cmd_line=['sync'])

    if sweep_config.read:
        run_read_sweep(sweep_config, flush_cache_job, sync_job, cmd_lines)

    if sweep_config.write:
        run_write_sweep(sweep_config, flush_cache_job, sync_job, cmd_lines)


if __name__ == "__main__":
    main()