|
| 1 | +import functools |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import time |
| 5 | +from typing import Callable, Optional, List |
| 6 | +from mpi4py import MPI |
| 7 | + |
| 8 | +from pylops.utils import deps as pylops_deps # avoid namespace crashes with pylops_mpi.utils |
| 9 | +from pylops_mpi.utils import deps |
| 10 | + |
| 11 | +cupy_message = pylops_deps.cupy_import("the benchmark module") |
| 12 | +nccl_message = deps.nccl_import("the benchmark module") |
| 13 | + |
| 14 | +if nccl_message is None and cupy_message is None: |
| 15 | + from pylops_mpi.utils._nccl import _nccl_sync |
| 16 | +else: |
| 17 | + def _nccl_sync(): |
| 18 | + pass |
| 19 | + |
| 20 | +# Benchmark is enabled by default |
| 21 | +ENABLE_BENCHMARK = int(os.getenv("BENCH_PYLOPS_MPI", 1)) == 1 |
| 22 | + |
| 23 | +# Stack of active mark functions for nested support |
| 24 | +_mark_func_stack = [] |
| 25 | +_markers = [] |
| 26 | + |
| 27 | + |
| 28 | +def _parse_output_tree(markers: List[str]): |
| 29 | + """This function parses the list of strings gathered during the benchmark call and output them |
| 30 | + as one properly formatted string. The format of output string follows the hierarchy of function calls |
| 31 | + i.e., the nested funtion calls are indented. |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + markers: :obj:`list`, optional |
| 36 | + A list of markers/labels generated from the benchmark call |
| 37 | + """ |
| 38 | + global _markers |
| 39 | + output = [] |
| 40 | + stack = [] |
| 41 | + i = 0 |
| 42 | + while i < len(markers): |
| 43 | + label, time, level = markers[i] |
| 44 | + if label.startswith("[decorator]"): |
| 45 | + indent = "\t" * (level - 1) |
| 46 | + output.append(f"{indent}{label}: total runtime: {time:6f} s\n") |
| 47 | + else: |
| 48 | + if stack: |
| 49 | + prev_label, prev_time, prev_level = stack[-1] |
| 50 | + if prev_level == level: |
| 51 | + indent = "\t" * level |
| 52 | + output.append(f"{indent}{prev_label}-->{label}: {time - prev_time:6f} s\n") |
| 53 | + stack.pop() |
| 54 | + |
| 55 | + # Push to the stack only if it is going deeper or still at the same level |
| 56 | + if i + 1 <= len(markers) - 1: |
| 57 | + _, _ , next_level = markers[i + 1] |
| 58 | + if next_level >= level: |
| 59 | + stack.append(markers[i]) |
| 60 | + i += 1 |
| 61 | + # reset markers, allowing other benchmarked function to start fresh |
| 62 | + _markers = [] |
| 63 | + return output |
| 64 | + |
| 65 | + |
| 66 | +def _sync(): |
| 67 | + """Synchronize all MPI processes or CUDA Devices""" |
| 68 | + _nccl_sync() |
| 69 | + MPI.COMM_WORLD.Barrier() |
| 70 | + |
| 71 | + |
| 72 | +def mark(label: str): |
| 73 | + """This function allows users to measure time arbitary lines of the function |
| 74 | +
|
| 75 | + Parameters |
| 76 | + ---------- |
| 77 | + label: :obj:`str` |
| 78 | + A label of the mark. This signifies both 1) the end of the |
| 79 | + previous mark 2) the beginning of the new mark |
| 80 | + """ |
| 81 | + if not ENABLE_BENCHMARK: |
| 82 | + return |
| 83 | + if not _mark_func_stack: |
| 84 | + raise RuntimeError("mark() called outside of a benchmarked region") |
| 85 | + _mark_func_stack[-1](label) |
| 86 | + |
| 87 | + |
| 88 | +def benchmark(func: Optional[Callable] = None, |
| 89 | + description: Optional[str] = "", |
| 90 | + logger: Optional[logging.Logger] = None, |
| 91 | + ): |
| 92 | + """A wrapper for code injection for time measurement. |
| 93 | +
|
| 94 | + This wrapper measures the start-to-end time of the wrapped function when |
| 95 | + decorated without any argument. |
| 96 | +
|
| 97 | + It also allows users to put a call to mark() anywhere inside the wrapped function |
| 98 | + for fine-grain time benchmark. This wrapper defines the local_mark() and pushes it |
| 99 | + to the _mark_func_stack for isolation in case of nested call. |
| 100 | + The user-facing mark() will always call the function at the top of the _mark_func_stack. |
| 101 | +
|
| 102 | + Parameters |
| 103 | + ---------- |
| 104 | + func : :obj:`callable`, optional |
| 105 | + Function to be decorated. Defaults to ``None``. |
| 106 | + description : :obj:`str`, optional |
| 107 | + Description for the output text. Defaults to ``''``. |
| 108 | + logger: :obj:`logging.Logger`, optional |
| 109 | + A `logging.Logger` object for logging the benchmark text output. This logger must be setup before |
| 110 | + passing to this function to either writing output to a file or log to stdout. If `logger` |
| 111 | + is not provided, the output is printed to stdout. |
| 112 | + """ |
| 113 | + |
| 114 | + def noop_decorator(func): |
| 115 | + @functools.wraps(func) |
| 116 | + def wrapped(*args, **kwargs): |
| 117 | + return func(*args, **kwargs) |
| 118 | + return wrapped |
| 119 | + |
| 120 | + @functools.wraps(func) |
| 121 | + def decorator(func): |
| 122 | + def wrapper(*args, **kwargs): |
| 123 | + rank = MPI.COMM_WORLD.Get_rank() |
| 124 | + |
| 125 | + level = len(_mark_func_stack) + 1 |
| 126 | + # The header is needed for later tree parsing. Here it is allocating its spot. |
| 127 | + # the tuple at this index will be replaced after elapsed time is calculated. |
| 128 | + _markers.append((f"[decorator]{description or func.__name__}", None, level)) |
| 129 | + header_index = len(_markers) - 1 |
| 130 | + |
| 131 | + def local_mark(label): |
| 132 | + _markers.append((label, time.perf_counter(), level)) |
| 133 | + |
| 134 | + _mark_func_stack.append(local_mark) |
| 135 | + |
| 136 | + _sync() |
| 137 | + start_time = time.perf_counter() |
| 138 | + # the mark() called in wrapped function will now call local_mark |
| 139 | + result = func(*args, **kwargs) |
| 140 | + _sync() |
| 141 | + end_time = time.perf_counter() |
| 142 | + |
| 143 | + elapsed = end_time - start_time |
| 144 | + _markers[header_index] = (f"[decorator]{description or func.__name__}", elapsed, level) |
| 145 | + |
| 146 | + # In case of nesting, the wrapped callee must pop its closure from stack so that |
| 147 | + # when the callee returns, the wrapped caller operates on its closure (and its level label), which now becomes |
| 148 | + # the top of the stack. |
| 149 | + _mark_func_stack.pop() |
| 150 | + |
| 151 | + # all the calls have fininshed |
| 152 | + if not _mark_func_stack: |
| 153 | + if rank == 0: |
| 154 | + output = _parse_output_tree(_markers) |
| 155 | + if logger: |
| 156 | + logger.info("".join(output)) |
| 157 | + else: |
| 158 | + print("".join(output)) |
| 159 | + return result |
| 160 | + return wrapper |
| 161 | + |
| 162 | + # The code still has to return decorator so that the in-place decorator with arguments |
| 163 | + # like @benchmark(logger=logger) does not throw the error and can be kept untouched. |
| 164 | + if not ENABLE_BENCHMARK: |
| 165 | + return noop_decorator if func is None else noop_decorator(func) |
| 166 | + |
| 167 | + return decorator if func is None else decorator(func) |
0 commit comments