timers.py 16.3 KB
Newer Older
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
1
2
3
4
5
# Copyright (c) 2022, NVIDIA CORPORATION.  All rights reserved.

"""Megatron timers."""

import time
xingjinliang's avatar
xingjinliang committed
6
7
from abc import ABC, abstractmethod
from typing import List
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
8
9
10

import torch

xingjinliang's avatar
xingjinliang committed
11
12
13
14
15
16
from megatron.core.utils import is_torch_min_version

if is_torch_min_version("1.13.0"):
    dist_all_gather_func = torch.distributed.all_gather_into_tensor
else:
    dist_all_gather_func = torch.distributed._all_gather_base
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
17
18
19


class TimerBase(ABC):
xingjinliang's avatar
xingjinliang committed
20
    """Timer base class."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
21
22
23
24
25
26

    def __init__(self, name):
        self.name = name

    @abstractmethod
    def start(self, barrier=False):
wangxj's avatar
wangxj committed
27
28
29
30
31
        """Start the timer.

        Args:
            barrier (bool, optional): Synchronizes ranks before starting. Defaults to False.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
32
33
34
35
        pass

    @abstractmethod
    def stop(self, barrier=False):
wangxj's avatar
wangxj committed
36
37
38
39
40
        """Stop the timer.

        Args:
            barrier (bool, optional): Synchronizes ranks before stopping. Defaults to False.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
41
42
43
44
        pass

    @abstractmethod
    def reset(self):
xingjinliang's avatar
xingjinliang committed
45
        """Reset timer."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
46
47
48
49
        pass

    @abstractmethod
    def elapsed(self, reset=True, barrier=False):
wangxj's avatar
wangxj committed
50
51
52
53
54
55
56
57
58
        """Calculates the elapsed time and restarts timer.

        Args:
            reset (bool, optional): Resets timer before restarting. Defaults to True.
            barrier (bool, optional): Synchronizes ranks before stopping. Defaults to False.

        Returns:
            float: Elapsed time.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
59
60
61
62
        pass


class DummyTimer(TimerBase):
xingjinliang's avatar
xingjinliang committed
63
    """Dummy Timer."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77

    def __init__(self):
        super().__init__('dummy timer')

    def start(self, barrier=False):
        return

    def stop(self, barrier=False):
        return

    def reset(self):
        return

    def elapsed(self, reset=True, barrier=False):
wangxj's avatar
wangxj committed
78
79
80
81
82
83
84
85
86
87
88
89
90
        raise Exception(
            'dummy timer should not be used to calculate elapsed time, '
            'check if timer\'s log_level <= self._log_level.'
        )

    def active_time(self):
        """Returns the cumulative duration the timer has been active.
        Note: Not supported for DummyTimer.
        """
        raise Exception(
            'active timer should not be used to calculate elapsed time, '
            'check if timer\'s log_level <= self._log_level.'
        )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
91
92
93
94


class Timer(TimerBase):
    """
xingjinliang's avatar
xingjinliang committed
95
96
    Timer class with ability to start/stop.

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
97
98
99
100
101
102
103
104
105
    Comment on using `barrier`: If this flag is passed, then all
    the caller processes will wait till all reach the timing routine.
    It is up to the user to make sure all the ranks in `barrier_group`
    call it otherwise, it will result in a hang.
    Comment on `barrier_group`: By default it is set to None which
    in torch distributed land, it will result in the global communicator.
    """

    def __init__(self, name):
xingjinliang's avatar
xingjinliang committed
106
107
108
109
110
        """Initialize Timer.

        Args:
            name (str): Name of the timer.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
111
112
        super().__init__(name)
        self._elapsed = 0.0
xingjinliang's avatar
xingjinliang committed
113
        self._active_time = 0.0
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
114
115
116
117
118
119
        self._started = False
        # Note that None will default to the global process group
        self._barrier_group = None
        self._start_time = time.time()

    def set_barrier_group(self, barrier_group):
xingjinliang's avatar
xingjinliang committed
120
        """Sets barrier group.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
121

xingjinliang's avatar
xingjinliang committed
122
123
124
125
        Args:
            barrier_group (ProcessGroup): Torch ProcessGroup for barrier.
        """
        self._barrier_group = barrier_group
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
126
127

    def start(self, barrier=False):
xingjinliang's avatar
xingjinliang committed
128
129
130
131
132
        """Start the timer.

        Args:
            barrier (bool, optional): Synchronizes ranks before starting. Defaults to False.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
133
134
135
136
137
138
139
140
        assert not self._started, 'timer has already been started'
        if barrier:
            torch.distributed.barrier(group=self._barrier_group)
        torch.cuda.synchronize()
        self._start_time = time.time()
        self._started = True

    def stop(self, barrier=False):
xingjinliang's avatar
xingjinliang committed
141
142
143
144
145
        """Stop the timer.

        Args:
            barrier (bool, optional): Synchronizes ranks before stopping. Defaults to False.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
146
147
148
149
        assert self._started, 'timer is not started'
        if barrier:
            torch.distributed.barrier(group=self._barrier_group)
        torch.cuda.synchronize()
xingjinliang's avatar
xingjinliang committed
150
151
152
        elapsed = time.time() - self._start_time
        self._elapsed += elapsed
        self._active_time += elapsed
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
153
154
155
156
        self._started = False

    def reset(self):
        """Reset timer."""
xingjinliang's avatar
xingjinliang committed
157
        # Don't reset _active_time
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
158
159
160
161
        self._elapsed = 0.0
        self._started = False

    def elapsed(self, reset=True, barrier=False):
xingjinliang's avatar
xingjinliang committed
162
163
164
165
166
167
168
169
170
        """Calculates the elapsed time and restarts timer.

        Args:
            reset (bool, optional): Resets timer before restarting. Defaults to True.
            barrier (bool, optional): Synchronizes ranks before stopping. Defaults to False.

        Returns:
            float: Elapsed time.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        _started = self._started
        # If the timing in progress, end it first.
        if self._started:
            self.stop(barrier=barrier)
        # Get the elapsed time.
        _elapsed = self._elapsed
        # Reset the elapsed time
        if reset:
            self.reset()
        # If timing was in progress, set it back.
        if _started:
            self.start(barrier=barrier)
        return _elapsed

xingjinliang's avatar
xingjinliang committed
185
    def active_time(self):
wangxj's avatar
wangxj committed
186
        """Calculates the cumulative duration for which the timer has been active"""
xingjinliang's avatar
xingjinliang committed
187
        return self._active_time
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
188
189
190


class Timers:
xingjinliang's avatar
xingjinliang committed
191
    """Class for a group of Timers."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
192
193

    def __init__(self, log_level, log_option):
xingjinliang's avatar
xingjinliang committed
194
195
196
197
198
199
200
        """Initialize group of timers.

        Args:
            log_level (int): Log level to control what timers are enabled.
            log_option (str): Setting for logging statistics over ranks for all the timers.
                              Allowed: ['max', 'minmax', 'all'].
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
201
        self._log_level = log_level
xingjinliang's avatar
xingjinliang committed
202
203
204
205
206
207
        allowed_log_options = set(['max', 'minmax', 'all'])
        assert (
            log_option in allowed_log_options
        ), 'input log option {} is invalid. It must be one of {}'.format(
            log_option, allowed_log_options
        )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
208
209
210
211
212
213
214
        self._log_option = log_option
        self._timers = {}
        self._log_levels = {}
        self._dummy_timer = DummyTimer()
        self._max_log_level = 2

    def __call__(self, name, log_level=None):
xingjinliang's avatar
xingjinliang committed
215
        """Call timer with name and log level."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
216
217
218
219
        # If the timer has already been set, then check if the log-level
        # is provided, it matches the one that the timer was created with.
        if name in self._timers:
            if log_level is not None:
xingjinliang's avatar
xingjinliang committed
220
221
222
223
                assert log_level == self._log_levels[name], (
                    'input log level {} does not match already existing '
                    'log level {} for {} timer'.format(log_level, self._log_levels[name], name)
                )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
224
225
226
227
228
            return self._timers[name]
        # If timer does not exist and no log level is provided,
        # set it to the max log level which is 2.
        if log_level is None:
            log_level = self._max_log_level
xingjinliang's avatar
xingjinliang committed
229
230
231
232
233
        assert (
            log_level <= self._max_log_level
        ), 'log level {} is larger than max supported log level {}'.format(
            log_level, self._max_log_level
        )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
234
235
236
237
238
239
240
241
242
243
        # Now if the input log level is larger than the one set for
        # the timers class, just ignore it and return a dummy timer.
        if log_level > self._log_level:
            return self._dummy_timer
        # Otherwise, initalize the timer and set the level.
        self._timers[name] = Timer(name)
        self._log_levels[name] = log_level
        return self._timers[name]

    def _get_elapsed_time_all_ranks(self, names, reset, barrier):
xingjinliang's avatar
xingjinliang committed
244
        """Returns elapsed times of timers in names.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
245
246
247
248
249
        Assumptions:
            - All the ranks call this function.
            - `names` are identical on all ranks.
        If the above assumptions are not met, calling this function will
        result in hang.
xingjinliang's avatar
xingjinliang committed
250
251
252
253
254
255
256
257

        Args:
            names (List[str]): list of timer names
            reset (bool): reset the timer after recording the elapsed time
            barrier (bool): if set, do a global barrier before time measurments

        Returns:
            torch.tensor: Tensor of size [world_size, len(names)] with times in float.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        """

        # First make sure all the callers are in sync.
        if barrier:
            torch.distributed.barrier()

        world_size = torch.distributed.get_world_size()
        rank = torch.distributed.get_rank()

        # Here we can use gather on the rank we want to print the
        # timing, however, there is no gather_base support in
        # pytorch yet. It is simpler to deal with a single tensor
        # and since we are only gathering a small amount of data,
        # it should be ok to use all-gather instead of gather.
xingjinliang's avatar
xingjinliang committed
272
273
274
        rank_name_to_time = torch.zeros(
            (world_size, len(names)), dtype=torch.float, device=torch.cuda.current_device()
        )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
275
276
277
278
279
280
        for i, name in enumerate(names):
            if name in self._timers:
                # Here we don't need to pass the barrier flag as all
                # the processes are already in sync. This avoids the
                # issue of different timers having different barrier
                # groups inside their class.
xingjinliang's avatar
xingjinliang committed
281
                rank_name_to_time[rank, i] = self._timers[name].elapsed(reset=reset)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
282
283

        # See the note above for why we are not using gather.
xingjinliang's avatar
xingjinliang committed
284
        dist_all_gather_func(rank_name_to_time.view(-1), rank_name_to_time[rank, :].view(-1))
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
285
286
287
288
289
290

        return rank_name_to_time

    def _get_global_min_max_time(self, names, reset, barrier, normalizer):
        """Report only min and max times across all ranks."""

xingjinliang's avatar
xingjinliang committed
291
        rank_name_to_time = self._get_elapsed_time_all_ranks(names, reset, barrier)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
292
293
294
295
296
297
298
299
300
        name_to_min_max_time = {}
        for i, name in enumerate(names):
            rank_to_time = rank_name_to_time[:, i]
            # filter out the ones we did not have any timings for
            rank_to_time = rank_to_time[rank_to_time > 0.0]
            # If the timer exists:
            if rank_to_time.numel() > 0:
                name_to_min_max_time[name] = (
                    rank_to_time.min().item() / normalizer,
xingjinliang's avatar
xingjinliang committed
301
302
                    rank_to_time.max().item() / normalizer,
                )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
303
304
        return name_to_min_max_time

xingjinliang's avatar
xingjinliang committed
305
306
307
    def _get_global_min_max_time_string(self, names, reset, barrier, normalizer, max_only):
        """Report strings for max/minmax times across all ranks."""
        name_to_min_max_time = self._get_global_min_max_time(names, reset, barrier, normalizer)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
308
309
        if not name_to_min_max_time:
            return None
xingjinliang's avatar
xingjinliang committed
310
311
312
313
        if max_only:
            output_string = 'max time across ranks (ms):'
        else:
            output_string = '(min, max) time across ranks (ms):'
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
314
315
316
        for name in name_to_min_max_time:
            min_time, max_time = name_to_min_max_time[name]
            if max_only:
xingjinliang's avatar
xingjinliang committed
317
                output_string += '\n    {}: {:.2f}'.format((name + ' ').ljust(48, '.'), max_time)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
318
319
            else:
                output_string += '\n    {}: ({:.2f}, {:.2f})'.format(
xingjinliang's avatar
xingjinliang committed
320
321
                    (name + ' ').ljust(48, '.'), min_time, max_time
                )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
322
323
324
325
        return output_string

    def _get_all_ranks_time_string(self, names, reset, barrier, normalizer):
        """Report times across all ranks."""
xingjinliang's avatar
xingjinliang committed
326
        rank_name_to_time = self._get_elapsed_time_all_ranks(names, reset, barrier)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
327
328
329
330
331
332
333
334
335
336
337
338

        output_string = 'times across ranks (ms):'
        no_reported_timing = True
        for i, name in enumerate(names):
            not_yet_found = True
            for rank in range(torch.distributed.get_world_size()):
                if rank_name_to_time[rank, i] > 0:
                    no_reported_timing = False
                    if not_yet_found:
                        not_yet_found = False
                        output_string += '\n  {}:'.format(name)
                    output_string += '\n     rank {:2d}: {:.2f}'.format(
xingjinliang's avatar
xingjinliang committed
339
340
                        rank, rank_name_to_time[rank, i] / normalizer
                    )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
341
342
343
344
        if no_reported_timing:
            return None
        return output_string

xingjinliang's avatar
xingjinliang committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    def get_all_timers_string(
        self,
        names: List[str] = None,
        normalizer: float = 1.0,
        reset: bool = True,
        barrier: bool = False,
    ):
        """Returns the output string with logged timer values according to configured options.

        Args:
            names (List[str]): Names of the timers to log. If None, all registered timers are
                               fetched. Defaults to None.
            normalizer (float, optional): Normalizes the timer values by the factor.
                                          Defaults to 1.0.
            reset (bool, optional): Whether to reset timer values after logging. Defaults to True.
            barrier (bool, optional): Whether to do a global barrier before time measurments.
                                      Defaults to False.

        Raises:
            Exception: Raises if log option is invalid.

        Returns:
            str: Formatted string with the timer values.
        """
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
369

xingjinliang's avatar
xingjinliang committed
370
371
        if names == None:  # get all registered timers
            names = self._timers.keys()
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
372
373
374
375
376
377
378

        assert normalizer > 0.0
        if self._log_option in ['max', 'minmax']:
            max_only = False
            if self._log_option == 'max':
                max_only = True
            output_string = self._get_global_min_max_time_string(
xingjinliang's avatar
xingjinliang committed
379
380
                names, reset, barrier, normalizer / 1000.0, max_only
            )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
381
        elif self._log_option == 'all':
xingjinliang's avatar
xingjinliang committed
382
383
384
            output_string = self._get_all_ranks_time_string(
                names, reset, barrier, normalizer / 1000.0
            )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
385
        else:
xingjinliang's avatar
xingjinliang committed
386
387
            raise Exception('unknown timing log option {}'.format(self._log_option))
        return output_string
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
388

xingjinliang's avatar
xingjinliang committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    def log(
        self,
        names: List[str],
        rank: int = None,
        normalizer: float = 1.0,
        reset: bool = True,
        barrier: bool = False,
    ):
        """logs the timers passed in names to stdout. Example usage is to log average per step
           value for timer 'foo', this function can be called with normalizer factor set to logging
           interval.

        Args:
            names (List[str]): Names of the timers to log.
            rank (int, optional): logs the timers to a specific rank. If set to None, logs to the
                                  last rank. Defaults to None.
            normalizer (float, optional): Normalizes the timer values by the factor.
                                          Defaults to 1.0.
            reset (bool, optional): Whether to reset timer values after logging. Defaults to True.
            barrier (bool, optional): Whether to do a global barrier before time measurments.
                                      Defaults to False.
        """

        output_string = self.get_all_timers_string(names, normalizer, reset, barrier)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
413
414
415
416
417
418
        # If no input rank is provided, log on last rank.
        if rank is None:
            rank = torch.distributed.get_world_size() - 1
        if rank == torch.distributed.get_rank() and output_string is not None:
            print(output_string, flush=True)

xingjinliang's avatar
xingjinliang committed
419
420
421
422
423
424
425
426
427
    def write(
        self,
        names: List[str],
        writer,
        iteration: int,
        normalizer: float = 1.0,
        reset: bool = True,
        barrier: bool = False,
    ):
wangxj's avatar
wangxj committed
428
429
        """Write timers to a tensorboard writer.
        Note that we only report maximum time across ranks to tensorboard.
xingjinliang's avatar
xingjinliang committed
430
431
432
433
434
435
436
437
438
439

        Args:
            names (List[str]): Names of the timers to log.
            writer (SummaryWriter): Tensorboard SummaryWriter object
            iteration (int): Current iteration.
            normalizer (float, optional): Normalizes the timer values by the factor.
                                          Defaults to 1.0.
            reset (bool, optional): Whether to reset timer values after logging. Defaults to True.
            barrier (bool, optional): Whether to do a global barrier before time measurments.
                                      Defaults to False.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
440
441
442
443
444
        """
        # currently when using add_scalars,
        # torch.utils.add_scalars makes each timer its own run, which
        # polutes the runs list, so we just add each as a scalar
        assert normalizer > 0.0
xingjinliang's avatar
xingjinliang committed
445
        name_to_min_max_time = self._get_global_min_max_time(names, reset, barrier, normalizer)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
446
447
448
449
        if writer is not None:
            for name in name_to_min_max_time:
                _, max_time = name_to_min_max_time[name]
                writer.add_scalar(name + '-time', max_time, iteration)