|
| 1 | +""" |
| 2 | +This module implements a simple memory monitoring utility for the whole application. |
| 3 | +
|
| 4 | +With [start_memory_monitoring()][pydvl.utils.monitor.start_memory_monitoring] one can |
| 5 | +monitor global memory usage, including the memory of child processes. The monitoring |
| 6 | +runs in a separate thread and keeps track of the *maximum** memory usage observed. |
| 7 | +
|
| 8 | +Monitoring stops automatically when the process exits or receives common termination |
| 9 | +signals (SIGINT, SIGTERM, SIGHUP). It can also be stopped manually by calling |
| 10 | +[end_memory_monitoring()][pydvl.utils.monitor.end_memory_monitoring]. |
| 11 | +
|
| 12 | +When monitoring stops, the maximum memory usage is both logged and returned (in bytes). |
| 13 | +
|
| 14 | +!!! note |
| 15 | + This is intended to report peak memory usage for the whole application, including |
| 16 | + child processes. It is not intended to be used for profiling memory usage of |
| 17 | + individual functions or modules. Given that there exist numerous profiling tools, |
| 18 | + it probably doesn't make sense to extend this module further. |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import atexit |
| 24 | +import logging |
| 25 | +import signal |
| 26 | +import threading |
| 27 | +import time |
| 28 | +from collections import defaultdict |
| 29 | +from itertools import chain |
| 30 | + |
| 31 | +import psutil |
| 32 | + |
| 33 | +__all__ = [ |
| 34 | + "end_memory_monitoring", |
| 35 | + "log_memory_usage_report", |
| 36 | + "start_memory_monitoring", |
| 37 | +] |
| 38 | + |
| 39 | +logger = logging.getLogger(__name__) |
| 40 | + |
| 41 | +__state_lock = threading.Lock() |
| 42 | +__memory_usage = defaultdict(int) # pid -> bytes |
| 43 | +__peak_memory_usage = 0 # (in bytes) |
| 44 | +__monitoring_enabled = threading.Event() |
| 45 | +__memory_monitor_thread: threading.Thread | None = None |
| 46 | + |
| 47 | + |
| 48 | +def _memory_monitor_thread() -> threading.Thread | None: |
| 49 | + """Returns the memory monitor thread. Can be None if the monitor was never started. |
| 50 | + This is only useful for testing purposes.""" |
| 51 | + return __memory_monitor_thread |
| 52 | + |
| 53 | + |
| 54 | +def start_memory_monitoring(auto_stop: bool = True): |
| 55 | + """Starts a memory monitoring thread. |
| 56 | +
|
| 57 | + The monitor runs in a separate thread and keeps track of maximum memory usage |
| 58 | + observed during the monitoring period. |
| 59 | +
|
| 60 | + The monitoring stops by calling |
| 61 | + [end_memory_monitoring()][pydvl.utils.monitor.end_memory_monitoring] or, if |
| 62 | + `auto_stop` is `True` when the process is terminated or exits. |
| 63 | +
|
| 64 | + Args: |
| 65 | + auto_stop: If True, the monitoring will stop when the process exits |
| 66 | + normally or receives common termination signals (SIGINT, SIGTERM, SIGHUP). |
| 67 | +
|
| 68 | + """ |
| 69 | + global __memory_usage |
| 70 | + global __memory_monitor_thread |
| 71 | + global __peak_memory_usage |
| 72 | + |
| 73 | + if __monitoring_enabled.is_set(): |
| 74 | + logger.warning("Memory monitoring is already running.") |
| 75 | + return |
| 76 | + |
| 77 | + with __state_lock: |
| 78 | + __memory_usage.clear() |
| 79 | + __peak_memory_usage = 0 |
| 80 | + |
| 81 | + __monitoring_enabled.set() |
| 82 | + __memory_monitor_thread = threading.Thread( |
| 83 | + target=memory_monitor_run, args=(psutil.Process().pid,) |
| 84 | + ) |
| 85 | + __memory_monitor_thread.start() |
| 86 | + |
| 87 | + if not auto_stop: |
| 88 | + return |
| 89 | + |
| 90 | + atexit.register(end_memory_monitoring) |
| 91 | + |
| 92 | + # Register signal handlers for common termination signals, re-raising the original |
| 93 | + # signal to terminate as expected |
| 94 | + |
| 95 | + def signal_handler(signum, frame): |
| 96 | + end_memory_monitoring() |
| 97 | + signal.signal(signum, signal.SIG_DFL) |
| 98 | + signal.raise_signal(signum) |
| 99 | + |
| 100 | + signal.signal(signal.SIGINT, signal_handler) # Ctrl+C |
| 101 | + signal.signal(signal.SIGTERM, signal_handler) # Termination request |
| 102 | + # SIGHUP might not be available on all platforms (e.g., Windows) |
| 103 | + if hasattr(signal, "SIGHUP"): |
| 104 | + signal.signal(signal.SIGHUP, signal_handler) # Terminal closed |
| 105 | + |
| 106 | + |
| 107 | +def memory_monitor_run(pid: int, interval: float = 0.1): |
| 108 | + """Monitors the memory usage of the process and its children. |
| 109 | +
|
| 110 | + This function runs in a separate thread and updates the global variable |
| 111 | + `__max_memory_usage` with the maximum memory usage observed during the monitoring |
| 112 | + period. |
| 113 | +
|
| 114 | + The monitoring stops when the __monitoring_enabled event is cleared, which can be |
| 115 | + achieved either by calling |
| 116 | + [end_memory_monitoring()][pydvl.utils.monitor.end_memory_monitoring], or when the |
| 117 | + process is terminated or exits. |
| 118 | + """ |
| 119 | + global __memory_usage |
| 120 | + global __peak_memory_usage |
| 121 | + |
| 122 | + try: |
| 123 | + proc = psutil.Process(pid) |
| 124 | + except psutil.NoSuchProcess: |
| 125 | + logger.error(f"Process {pid} not found. Monitoring cannot start.") |
| 126 | + return |
| 127 | + |
| 128 | + while __monitoring_enabled.is_set(): |
| 129 | + total_mem = 0 |
| 130 | + try: |
| 131 | + for p in chain([proc], proc.children(recursive=True)): |
| 132 | + try: |
| 133 | + pid = p.pid |
| 134 | + rss = p.memory_info().rss |
| 135 | + total_mem += rss |
| 136 | + with __state_lock: |
| 137 | + __memory_usage[pid] = max(__memory_usage[pid], rss) |
| 138 | + except psutil.NoSuchProcess: |
| 139 | + continue |
| 140 | + except psutil.NoSuchProcess: # Catch invalid proc / proc.children |
| 141 | + break |
| 142 | + |
| 143 | + with __state_lock: |
| 144 | + __peak_memory_usage = max(__peak_memory_usage, total_mem) |
| 145 | + |
| 146 | + time.sleep(interval) |
| 147 | + |
| 148 | + |
| 149 | +def end_memory_monitoring(log_level=logging.DEBUG) -> tuple[int, dict[int, int]]: |
| 150 | + """Ends the memory monitoring thread and logs the maximum memory usage. |
| 151 | +
|
| 152 | + Args: |
| 153 | + log_level: The logging level to use. |
| 154 | +
|
| 155 | + Returns: |
| 156 | + A tuple with the maximum memory usage observed globally, and for each pid |
| 157 | + separately as a dict. The dict will be empty if monitoring is disabled. |
| 158 | + """ |
| 159 | + global __memory_usage |
| 160 | + global __peak_memory_usage |
| 161 | + |
| 162 | + if not __monitoring_enabled.is_set(): |
| 163 | + return 0, {} |
| 164 | + |
| 165 | + __monitoring_enabled.clear() |
| 166 | + __memory_monitor_thread.join() |
| 167 | + |
| 168 | + with __state_lock: |
| 169 | + peak_mem = __peak_memory_usage |
| 170 | + mem_usage = __memory_usage.copy() |
| 171 | + __memory_usage.clear() |
| 172 | + __peak_memory_usage = 0 |
| 173 | + |
| 174 | + log_memory_usage_report(peak_mem, mem_usage, log_level) |
| 175 | + return peak_mem, mem_usage |
| 176 | + |
| 177 | + |
| 178 | +def log_memory_usage_report( |
| 179 | + peak_mem: int, mem_usage: dict[int, int], log_level=logging.DEBUG |
| 180 | +): |
| 181 | + """ |
| 182 | + Generates a nicely tabulated memory usage report and logs it. |
| 183 | +
|
| 184 | + Args: |
| 185 | + peak_mem: The maximum memory usage observed during the monitoring period. |
| 186 | + mem_usage: A dictionary mapping process IDs (pid) to memory usage in bytes. |
| 187 | + log_level: The log level used for logging the report. |
| 188 | + """ |
| 189 | + if not mem_usage: |
| 190 | + logger.log(log_level, "No memory usage data available.") |
| 191 | + return |
| 192 | + |
| 193 | + headers = ("PID", "Memory (Bytes)", "Memory (MB)") |
| 194 | + col_widths = (10, 20, 15) |
| 195 | + |
| 196 | + header_line = ( |
| 197 | + f"{headers[0]:>{col_widths[0]}} " |
| 198 | + f"{headers[1]:>{col_widths[1]}} " |
| 199 | + f"{headers[2]:>{col_widths[2]}}" |
| 200 | + ) |
| 201 | + separator = "-" * (sum(col_widths) + 2) |
| 202 | + |
| 203 | + summary = ( |
| 204 | + f"Memory monitor: {len(mem_usage)} processes monitored. " |
| 205 | + f"Peak memory usage: {peak_mem / (2**20):.2f} MB" |
| 206 | + ) |
| 207 | + |
| 208 | + lines = [header_line, separator, summary] |
| 209 | + |
| 210 | + for pid, bytes_used in sorted( |
| 211 | + mem_usage.items(), key=lambda item: item[1], reverse=True |
| 212 | + ): |
| 213 | + mb_used = bytes_used / (1024 * 1024) |
| 214 | + line = ( |
| 215 | + f"{pid:>{col_widths[0]}} " |
| 216 | + f"{bytes_used:>{col_widths[1]},} " |
| 217 | + f"{mb_used:>{col_widths[2]}.2f}" |
| 218 | + ) |
| 219 | + lines.append(line) |
| 220 | + |
| 221 | + lines.append(separator) |
| 222 | + |
| 223 | + logger.log(log_level, "\n".join(lines)) |
0 commit comments