ib_loopback_performance.py 8.84 KB
Newer Older
1
2
3
4
5
6
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""Module of the IB loopback benchmarks."""

import os
7
import socket
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
from pathlib import Path

from superbench.common.utils import logger
from superbench.common.utils import network
from superbench.benchmarks import BenchmarkRegistry, ReturnCode
from superbench.benchmarks.micro_benchmarks import MicroBenchmarkWithInvoke


def get_numa_cores(numa_index):
    """Get the available cores from different physical cpu core of NUMA<numa_index>.

    Args:
        numa_index (int): the index of numa node.

    Return:
        list: The available cores from different physical cpu core of NUMA<numa_index>.
        None if no available cores or numa index.
    """
    try:
        with Path(f'/sys/devices/system/node/node{numa_index}/cpulist').open('r') as f:
            cores = []
            core_ranges = f.read().strip().split(',')
            for core_range in core_ranges:
                start, end = core_range.split('-')
                for core in range(int(start), int(end) + 1):
                    cores.append(core)
        return cores
    except IOError:
        return None


class IBLoopbackBenchmark(MicroBenchmarkWithInvoke):
    """The IB loopback performance benchmark class."""
    def __init__(self, name, parameters=''):
        """Constructor.

        Args:
            name (str): benchmark name.
            parameters (str): benchmark parameters.
        """
        super().__init__(name, parameters)

        self._bin_name = 'run_perftest_loopback'
51
        self.__sock_fds = []
52
53
        self.__support_ib_commands = {'write': 'ib_write_bw', 'read': 'ib_read_bw', 'send': 'ib_send_bw'}

54
55
56
57
58
    def __del__(self):
        """Destructor."""
        for fd in self.__sock_fds:
            fd.close()

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
    def add_parser_arguments(self):
        """Add the specified arguments."""
        super().add_parser_arguments()

        self._parser.add_argument(
            '--ib_index',
            type=int,
            default=0,
            required=False,
            help='The index of ib device.',
        )
        self._parser.add_argument(
            '--iters',
            type=int,
            default=20000,
            required=False,
            help='The iterations of running ib command',
        )
        self._parser.add_argument(
            '--msg_size',
            type=int,
            default=None,
            required=False,
            help='The message size of running ib command, e.g., 8388608.',
        )
        self._parser.add_argument(
            '--commands',
            type=str,
            nargs='+',
            default=['write'],
            help='The ib command used to run, e.g., {}.'.format(' '.join(list(self.__support_ib_commands.keys()))),
        )
        self._parser.add_argument(
            '--gid_index',
            type=int,
            default=0,
            required=False,
            help='Test uses GID with GID index taken from command.',
        )

99
    def _get_arguments_from_env(self):
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        """Read environment variables from runner used for parallel and fill in ib_index and numa_node_index.

        Get 'PROC_RANK'(rank of current process) 'IB_DEVICES' 'NUMA_NODES' environment variables
        Get ib_index and numa_node_index according to 'NUMA_NODES'['PROC_RANK'] and 'IB_DEVICES'['PROC_RANK']
        Note: The config from env variables will overwrite the configs defined in the command line
        """
        try:
            if os.getenv('PROC_RANK'):
                rank = int(os.getenv('PROC_RANK'))
                if os.getenv('IB_DEVICES'):
                    self._args.ib_index = int(os.getenv('IB_DEVICES').split(',')[rank])
                if os.getenv('NUMA_NODES'):
                    self._args.numa = int(os.getenv('NUMA_NODES').split(',')[rank])
            return True
        except BaseException:
            logger.error('The proc_rank is out of index of devices - benchmark: {}.'.format(self._name))
            return False

    def _preprocess(self):
        """Preprocess/preparation operations before the benchmarking.

        Return:
            True if _preprocess() succeed.
        """
124
        if not super()._preprocess() or not self._get_arguments_from_env():
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            return False

        # Format the arguments
        self._args.commands = [command.lower() for command in self._args.commands]

        # Check whether arguments are valid
        command_mode = ''
        if self._args.msg_size is None:
            command_mode = ' -a'
        else:
            command_mode = ' -s ' + str(self._args.msg_size)

        for ib_command in self._args.commands:
            if ib_command not in self.__support_ib_commands:
                self._result.set_return_code(ReturnCode.INVALID_ARGUMENT)
                logger.error(
                    'Unsupported ib command - benchmark: {}, command: {}, expected: {}.'.format(
                        self._name, ib_command, ' '.join(list(self.__support_ib_commands.keys()))
                    )
                )
                return False
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

            try:
                self.__sock_fds.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
                # grep SO_REUSE /usr/include/asm-generic/socket.h
                self.__sock_fds[-1].setsockopt(socket.SOL_SOCKET, getattr(socket, 'SO_REUSEADDR', 2), 1)
                self.__sock_fds[-1].setsockopt(socket.SOL_SOCKET, getattr(socket, 'SO_REUSEPORT', 15), 1)
                self.__sock_fds[-1].bind(('127.0.0.1', 0))
            except OSError as e:
                self._result.set_return_code(ReturnCode.RUNTIME_EXCEPTION_ERROR)
                logger.error('Error when binding port - benchmark: %s, message: %s.', self._name, e)
                return False
            try:
                ib_devices = network.get_ib_devices()
            except BaseException as e:
                self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE)
                logger.error('Getting ib devices failure - benchmark: {}, message: {}.'.format(self._name, str(e)))
                return False
            numa_cores = get_numa_cores(self._args.numa)
            if not numa_cores or len(numa_cores) < 2:
                self._result.set_return_code(ReturnCode.MICROBENCHMARK_DEVICE_GETTING_FAILURE)
                logger.error('Getting numa core devices failure - benchmark: {}.'.format(self._name))
                return False
            command = os.path.join(self._args.bin_dir, self._bin_name)
            command += ' ' + str(numa_cores[-1]) + ' ' + str(numa_cores[-3 + int((len(numa_cores) < 4))])
            command += ' ' + os.path.join(self._args.bin_dir, self.__support_ib_commands[ib_command])
            command += command_mode + ' -F'
            command += ' --iters=' + str(self._args.iters)
            command += ' -d ' + ib_devices[self._args.ib_index].split(':')[0]
            command += ' -p ' + str(self.__sock_fds[-1].getsockname()[1])
            command += ' -x ' + str(self._args.gid_index)
            command += ' --report_gbits'
            self._commands.append(command)

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        return True

    def _process_raw_result(self, cmd_idx, raw_output):
        """Function to parse raw results and save the summarized results.

          self._result.add_raw_data() and self._result.add_result() need to be called to save the results.

        Args:
            cmd_idx (int): the index of command corresponding with the raw_output.
            raw_output (str): raw output string of the micro-benchmark.

        Return:
            True if the raw output string is valid and result can be extracted.
        """
        self._result.add_raw_data(
194
195
            'raw_output_' + self._args.commands[cmd_idx] + '_IB' + str(self._args.ib_index), raw_output,
            self._args.log_raw_data
196
197
198
199
200
201
202
203
        )

        valid = False
        content = raw_output.splitlines()

        metric_set = set()
        for line in content:
            try:
204
                values = list(filter(None, line.split()))
205
206
207
208
                if len(values) != 5:
                    continue
                # Extract value from the line
                size = int(values[0])
209
210
                avg_bw = float(values[-2]) / 8.0
                metric = f'{self.__support_ib_commands[self._args.commands[cmd_idx]]}_{size}:{self._args.ib_index}'
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
                # Filter useless value in client output
                if metric not in metric_set:
                    metric_set.add(metric)
                    self._result.add_result(metric, avg_bw)
                    valid = True
            except BaseException:
                pass
        if valid is False:
            logger.error(
                'The result format is invalid - round: {}, benchmark: {}, raw output: {}.'.format(
                    self._curr_run_index, self._name, raw_output
                )
            )
            return False

        return True


BenchmarkRegistry.register_benchmark('ib-loopback', IBLoopbackBenchmark)