Skip to content

qttools.profiling.profiler#

[docs] module qttools.profiling.profiler

  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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# Copyright (c) 2024 ETH Zurich and the authors of the qttools package.

import json
import os
import pickle
import sys
import time
import warnings
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime
from functools import wraps
from typing import Literal

from mpi4py.MPI import COMM_WORLD as comm

from qttools import strtobool, xp
from qttools.profiling.utils import get_cuda_devices

NVTX_AVAILABLE = xp.__name__ == "cupy" and xp.cuda.nvtx.available


# Set the whether to profile the GPU.
QTX_PROFILE_GPU = strtobool(os.getenv("QTX_PROFILE_GPU"), False)
if QTX_PROFILE_GPU:
    if xp.__name__ != "cupy":
        warnings.warn("CUDA is not available. Defaulting to no GPU profiling.")
        QTX_PROFILE_GPU = False
    else:
        warnings.warn(
            "GPU profiling is enabled. This will cause device "
            "synchronization for every profiled event."
        )

# Set the profiling level.
QTX_PROFILE_LEVEL = os.getenv("QTX_PROFILE_LEVEL", "basic").lower()
if QTX_PROFILE_LEVEL not in ("off", "basic", "api", "debug", "full"):
    warnings.warn(
        f"Invalid profiling level {QTX_PROFILE_LEVEL=}. Defaulting to 'basic'."
    )
    QTX_PROFILE_LEVEL = "basic"

# Define the mapping of profiling levels to numbers.
_level_to_num = {"off": 0, "basic": 1, "api": 2, "debug": 3, "full": 4}


class _ProfilingEvent:
    """A profiling event object.

    This is basically just there to parse the names of the profiled
    functions.

    Parameters
    ----------
    event : list
        The profiling event data.
    rank : int
        The MPI rank on which the event
        occurred.

    Attributes
    ----------
    datetime : datetime
        The timestamp of the event.
    prof_type : str
        The type of the profiling event.
    qualname : str
        The qualified name of the profiled function.
    prof_id : str
        The ID of the profiling event.
    host_time : float
        The time spent on the host.
    device_times : list
        The time spent on each device.
    rank : int
        The MPI rank on which the event occurred.

    """

    def __init__(self, event: list, rank: int):
        """Initializes the profiling event object."""
        timestamp, name, host_time, device_times = event
        # TODO: Here we parse the timestamp as a datetime object. It
        # would be very nice to have a trace plot of the profiling
        # data, but this would require a bit more work.
        self.datetime = datetime.fromtimestamp(timestamp)

        # Names will look like "<function Class.do_something at 0x...>".
        prof_type, qualname, *__ = name.strip("<>").split()
        self.prof_type = prof_type
        self.qualname = qualname

        self.host_time = host_time
        self.device_times = device_times
        self.rank = rank


class _ProfilingRun:
    """A profiling run object.

    Parameters
    ----------
    eventlogs : list
        A list of profiling events for each rank.

    Attributes
    ----------
    profiling_events : list[_ProfilingEvent]
        A list of parsed profiling events.

    """

    def __init__(self, eventlogs: list[list]):
        """Initializes the profiling run object."""
        profiling_events: list[_ProfilingEvent] = []
        for rank, events in enumerate(eventlogs):
            for event in events:
                profiling_events.append(_ProfilingEvent(event, rank))

        self.profiling_events = profiling_events

    def get_stats(self) -> dict:
        """Returns the profiling statistics.

        This reports some statistics for each profiled function.

        Returns
        -------
        dict
            A dictionary containing the profiling statistics.

        """
        host_stats = defaultdict(list)
        device_stats = defaultdict(list)
        ranks = defaultdict(set)
        for event in self.profiling_events:
            host_stats[event.qualname].append(event.host_time)
            device_stats[event.qualname].append(event.device_times)
            ranks[event.qualname].add(event.rank)

        stats = {}
        for key in host_stats:
            host_times = xp.array(host_stats[key])

            num_calls = len(host_times)
            num_ranks = len(ranks[key])
            total_host_time = float(xp.sum(host_times))

            stats[key] = {
                "num_calls": num_calls,
                "num_participating_ranks": num_ranks,
                "num_calls_per_rank": num_calls / num_ranks,
                "total_host_time": total_host_time,
                "total_host_time_per_rank": total_host_time / num_ranks,
                "average_host_time": float(xp.mean(host_times)),
                "median_host_time": float(xp.median(host_times)),
                "std_host_time": float(xp.std(host_times)),
                "min_host_time": float(xp.min(host_times)),
                "max_host_time": float(xp.max(host_times)),
            }
            device_times = xp.array(device_stats[key])
            if not xp.any(device_times):
                continue

            total_device_time = float(xp.sum(device_times))
            stats[key].update(
                {
                    "total_device_time": total_device_time,
                    "total_device_time_per_rank": total_device_time / num_ranks,
                    "average_device_time": float(xp.mean(device_times)),
                    "median_device_time": float(xp.median(device_times)),
                    "std_device_time": float(xp.std(device_times)),
                    "min_device_time": float(xp.min(device_times)),
                    "max_device_time": float(xp.max(device_times)),
                }
            )

        return stats


class Profiler:
    """Singleton Profiler class to collect and report profiling data.

    Attributes
    ----------
    eventlog : list
        A list of profiling data.
    devices : list
        A list of CUDA device IDs.

    """

    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Profiler, cls).__new__(cls)

            cls._instance.eventlog = []
            cls._instance.devices = get_cuda_devices()

        return cls._instance

    def _gather_events(self, root: int = 0) -> list:
        """Gathers profiling events.

        Returns
        -------
        list
            A list of profiling events or an empty list.

        """
        all_events = comm.gather(self.eventlog, root=root)
        if comm.rank == root:
            return all_events
        return [[]]

    def get_stats(self) -> dict:
        """Computes statistics from profiling data accross all ranks.

        Returns
        -------
        dict
            A dictionary containing the profiling data.

        """
        return _ProfilingRun(self._gather_events()).get_stats()

    def dump_stats(self, filepath: str, format: Literal["pickle", "json"] = "pickle"):
        """Dumps the profiling statistics to a file.

        Parameters
        ----------
        filepath : str
            The path to the output file. The correct file extension
            will be appended based on the format.
        format : {"pickle", "json"}, optional
            The format in which to save the profiling data.

        """
        if format not in ("pickle", "json"):
            raise ValueError(f"Invalid format {format}.")

        stats = self.get_stats()
        if comm.rank != 0:
            # Only the root rank dumps the stats.
            return

        filepath = os.fspath(filepath)
        os.path.isdir(os.path.dirname(filepath))
        if format == "pickle":
            if not filepath.endswith(".pkl"):
                filepath += ".pkl"
            with open(filepath, "wb") as pickle_file:
                pickle.dump(stats, pickle_file)
        else:
            if not filepath.endswith(".json"):
                filepath += ".json"
            with open(filepath, "w") as json_file:
                json.dump(stats, json_file, indent=4)

    def _setup_events(self) -> tuple[list, list]:
        """Sets up CUDA events for each device.

        Returns
        -------
        tuple[list, list]
            A tuple of lists of start and end events for each device.

        """
        start_events = []
        end_events = []

        for device in self.devices:
            current_device = xp.cuda.runtime.getDevice()
            try:
                xp.cuda.runtime.setDevice(device)
                start_events.append(xp.cuda.stream.Event())
                end_events.append(xp.cuda.stream.Event())
            finally:
                xp.cuda.runtime.setDevice(current_device)

        return start_events, end_events

    def _record_events(self, events: list):
        """Records events for each device.

        Parameters
        ----------
        events : list
            A list of events to record.

        """
        for device, event in zip(self.devices, events):
            current_device = xp.cuda.runtime.getDevice()
            try:
                xp.cuda.runtime.setDevice(device)
                event.record(xp.cuda.stream.Stream(device))
            finally:
                xp.cuda.runtime.setDevice(current_device)

    def _synchronize_events(self, events: list):
        """Synchronizes events for each device.

        Parameters
        ----------
        events : list
            A list of events to synchronize.

        """
        for device, event in zip(self.devices, events):
            current_device = xp.cuda.runtime.getDevice()
            try:
                xp.cuda.runtime.setDevice(device)
                event.synchronize()
            finally:
                xp.cuda.runtime.setDevice(current_device)

    def profile(self, level: str = QTX_PROFILE_LEVEL):
        """Profiles a function and adds profiling data to the event log.

        Notes
        -----
        Two environment variables control the profiling behavior:
        - `PROFILE_GPU`: Whether to separately measure the time spent on
          the GPU. If turned on, this will cause device synchronization
          for every profiled event.
        - `PROFILE_LEVEL`: The profiling level for functions. The
            following levels are implemented:
            - `"off"`: The function is not profiled.
            - `"basic"`: The function is part of the core profiling.
            - `"api"`: The function is part of the API and does not
              always need to be timed. It is part of the underlying
              infrastructure.
            - `"debug"`: This function only needs to be profiled for
              debugging purposes.
            - `"full"`: The function does not even need to be profiled for
              debugging purposes unless the user explicitly requests it.


        Parameters
        ----------
        level : str, optional
            The profiling level controls whether the function is
            profiled or not. By default, the level is set to the
            PROFILE_LEVEL environment variable. The function is thus
            always profiled. The following levels are implemented:
            - `"off"`: The function is not profiled.
            - `"basic"`: The function is part of the core profiling.
            - `"api"`: The function is part of the API and does not
              always need to be timed. It is part of the underlying
              infrastructure.
            - `"debug"`: This function only needs to be profiled for
              debugging purposes.
            - `"full"`: The function does not even need to be profiled
              for debugging purposes unless the user explicitly requests
              it to be profiled.

        Returns
        -------
        callable
            The wrapped function with profiling according to the
            specified level.

        """
        if level not in ("off", "basic", "api", "debug", "full"):
            raise ValueError(f"Invalid profiling level {level}.")

        def decorator(func):
            if _level_to_num[level] > _level_to_num[QTX_PROFILE_LEVEL]:
                return func

            name = func.__str__()

            @wraps(func)
            def wrapper(*args, **kwargs):

                timestamp = time.time()

                if QTX_PROFILE_GPU:
                    start_events, end_events = self._setup_events()

                    # Record and sync start events for each device.
                    self._record_events(start_events)
                    self._synchronize_events(start_events)

                    # Record start events for each device.
                    self._record_events(start_events)

                # Push a range to NVTX if available.
                if NVTX_AVAILABLE:
                    xp.cuda.nvtx.RangePush(name)

                host_time = -time.perf_counter()

                # Call the function.
                result = func(*args, **kwargs)

                host_time += time.perf_counter()

                if NVTX_AVAILABLE:
                    xp.cuda.nvtx.RangePop()

                device_times = []
                if QTX_PROFILE_GPU:
                    # Record end events for each device.
                    self._record_events(end_events)

                    # Sync to ensure all devices are done.
                    self._synchronize_events(end_events)

                    # Calculate the time spent on each device.
                    for start_event, end_event in zip(start_events, end_events):
                        device_times.append(
                            xp.cuda.get_elapsed_time(start_event, end_event)
                            * 1e-3  # Convert to seconds.
                        )

                self.eventlog.append((timestamp, name, host_time, device_times))

                return result

            return wrapper

        return decorator

    @contextmanager
    def profile_range(self, label: str = "range", level: str = QTX_PROFILE_LEVEL):
        """Profiles a range of code.

        This is a context manager that profiles a range of code.

        Parameters
        ----------
        label : str, optional
            A label for the profiled range. This is used to identify
            the profiled range in the profiling data.
        level : str, optional
            The profiling level controls whether the function is
            profiled or not. By default, the function is always
            profiled, irrespective of the PROFILE_LEVEL environment
            variable. The following levels are implemented:
            - `"off"`: The function is not profiled.
            - `"basic"`: The function is part of the core profiling.
            - `"api"`: The function is part of the API and does not
              always need to be timed. It is part of the underlying
              infrastructure.
            - `"debug"`: This function only needs to be profiled for
              debugging purposes.
            - `"full"`: The function does not even need to be profiled
              for debugging purposes unless the user explicitly requests
              it to be profiled.

        Yields
        ------
        None
            The context manager does not return anything.

        """
        if level not in ("off", "basic", "api", "debug", "full"):
            raise ValueError(f"Invalid profiling level {level}.")

        if _level_to_num[level] > _level_to_num[QTX_PROFILE_LEVEL]:
            yield
            return

        # This is quite a bit of a hack to get the qualified name of the
        # function in which the context manager is called.
        qualname = "no_qualname"
        if hasattr(sys, "_getframe"):
            qualname = sys._getframe(2).f_code.co_qualname

        label = "." + label.replace(" ", "_")
        name = "<range " + qualname + label + ">"

        try:
            timestamp = time.time()

            if QTX_PROFILE_GPU:
                start_events, end_events = self._setup_events()

                # Record and sync start events for each device.
                self._record_events(start_events)
                self._synchronize_events(start_events)

                # Record start events for each device.
                self._record_events(start_events)

            # Push a range to NVTX if available.
            if NVTX_AVAILABLE:
                xp.cuda.nvtx.RangePush(name)

            host_time = -time.perf_counter()

            yield

        finally:

            host_time += time.perf_counter()

            if NVTX_AVAILABLE:
                xp.cuda.nvtx.RangePop()

            device_times = []
            if QTX_PROFILE_GPU:
                # Record end events for each device.
                self._record_events(end_events)

                # Sync to ensure all devices are done.
                self._synchronize_events(end_events)

                # Calculate the time spent on each device.
                for start_event, end_event in zip(start_events, end_events):
                    device_times.append(
                        xp.cuda.get_elapsed_time(start_event, end_event)
                        * 1e-3  # Convert to seconds.
                    )

            self.eventlog.append((timestamp, name, host_time, device_times))