|
| 1 | +from contextlib import contextmanager |
| 2 | +from collections import defaultdict |
| 3 | +import time |
| 4 | +import numpy as np |
| 5 | +import cProfile |
| 6 | +import pstats |
| 7 | +import io |
| 8 | +from abc import ABC, abstractmethod |
| 9 | +import logging |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class BaseProfiler(ABC): |
| 15 | + """ |
| 16 | + If you wish to write a custom profiler, you should inhereit from this class. |
| 17 | + """ |
| 18 | + |
| 19 | + @abstractmethod |
| 20 | + def start(self, action_name): |
| 21 | + """ |
| 22 | + Defines how to start recording an action. |
| 23 | + """ |
| 24 | + pass |
| 25 | + |
| 26 | + @abstractmethod |
| 27 | + def stop(self, action_name): |
| 28 | + """ |
| 29 | + Defines how to record the duration once an action is complete. |
| 30 | + """ |
| 31 | + pass |
| 32 | + |
| 33 | + @contextmanager |
| 34 | + def profile(self, action_name): |
| 35 | + """ |
| 36 | + Yields a context manager to encapsulate the scope of a profiled action. |
| 37 | +
|
| 38 | + Example:: |
| 39 | +
|
| 40 | + with self.profile('load training data'): |
| 41 | + # load training data code |
| 42 | +
|
| 43 | + The profiler will start once you've entered the context and will automatically |
| 44 | + stop once you exit the code block. |
| 45 | + """ |
| 46 | + try: |
| 47 | + self.start(action_name) |
| 48 | + yield action_name |
| 49 | + finally: |
| 50 | + self.stop(action_name) |
| 51 | + |
| 52 | + def profile_iterable(self, iterable, action_name): |
| 53 | + iterator = iter(iterable) |
| 54 | + while True: |
| 55 | + try: |
| 56 | + self.start(action_name) |
| 57 | + value = next(iterator) |
| 58 | + self.stop(action_name) |
| 59 | + yield value |
| 60 | + except StopIteration: |
| 61 | + self.stop(action_name) |
| 62 | + break |
| 63 | + |
| 64 | + def describe(self): |
| 65 | + """ |
| 66 | + Logs a profile report after the conclusion of the training run. |
| 67 | + """ |
| 68 | + pass |
| 69 | + |
| 70 | + |
| 71 | +class PassThroughProfiler(BaseProfiler): |
| 72 | + """ |
| 73 | + This class should be used when you don't want the (small) overhead of profiling. |
| 74 | + The Trainer uses this class by default. |
| 75 | + """ |
| 76 | + |
| 77 | + def __init__(self): |
| 78 | + pass |
| 79 | + |
| 80 | + def start(self, action_name): |
| 81 | + pass |
| 82 | + |
| 83 | + def stop(self, action_name): |
| 84 | + pass |
| 85 | + |
| 86 | + |
| 87 | +class Profiler(BaseProfiler): |
| 88 | + """ |
| 89 | + This profiler simply records the duration of actions (in seconds) and reports |
| 90 | + the mean duration of each action and the total time spent over the entire training run. |
| 91 | + """ |
| 92 | + |
| 93 | + def __init__(self): |
| 94 | + self.current_actions = {} |
| 95 | + self.recorded_durations = defaultdict(list) |
| 96 | + |
| 97 | + def start(self, action_name): |
| 98 | + if action_name in self.current_actions: |
| 99 | + raise ValueError( |
| 100 | + f"Attempted to start {action_name} which has already started." |
| 101 | + ) |
| 102 | + self.current_actions[action_name] = time.monotonic() |
| 103 | + |
| 104 | + def stop(self, action_name): |
| 105 | + end_time = time.monotonic() |
| 106 | + if action_name not in self.current_actions: |
| 107 | + raise ValueError( |
| 108 | + f"Attempting to stop recording an action ({action_name}) which was never started." |
| 109 | + ) |
| 110 | + start_time = self.current_actions.pop(action_name) |
| 111 | + duration = end_time - start_time |
| 112 | + self.recorded_durations[action_name].append(duration) |
| 113 | + |
| 114 | + def describe(self): |
| 115 | + output_string = "\n\nProfiler Report\n" |
| 116 | + |
| 117 | + def log_row(action, mean, total): |
| 118 | + return f"\n{action:<20s}\t| {mean:<15}\t| {total:<15}" |
| 119 | + |
| 120 | + output_string += log_row("Action", "Mean duration (s)", "Total time (s)") |
| 121 | + output_string += f"\n{'-' * 65}" |
| 122 | + for action, durations in self.recorded_durations.items(): |
| 123 | + output_string += log_row( |
| 124 | + action, f"{np.mean(durations):.5}", f"{np.sum(durations):.5}", |
| 125 | + ) |
| 126 | + output_string += "\n" |
| 127 | + logger.info(output_string) |
| 128 | + |
| 129 | + |
| 130 | +class AdvancedProfiler(BaseProfiler): |
| 131 | + """ |
| 132 | + This profiler uses Python's cProfiler to record more detailed information about |
| 133 | + time spent in each function call recorded during a given action. The output is quite |
| 134 | + verbose and you should only use this if you want very detailed reports. |
| 135 | + """ |
| 136 | + |
| 137 | + def __init__(self, output_filename=None, line_count_restriction=1.0): |
| 138 | + """ |
| 139 | + :param output_filename (str): optionally save profile results to file instead of printing |
| 140 | + to std out when training is finished. |
| 141 | + :param line_count_restriction (int|float): this can be used to limit the number of functions |
| 142 | + reported for each action. either an integer (to select a count of lines), |
| 143 | + or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines) |
| 144 | + """ |
| 145 | + self.profiled_actions = {} |
| 146 | + self.output_filename = output_filename |
| 147 | + self.line_count_restriction = line_count_restriction |
| 148 | + |
| 149 | + def start(self, action_name): |
| 150 | + if action_name not in self.profiled_actions: |
| 151 | + self.profiled_actions[action_name] = cProfile.Profile() |
| 152 | + self.profiled_actions[action_name].enable() |
| 153 | + |
| 154 | + def stop(self, action_name): |
| 155 | + pr = self.profiled_actions.get(action_name) |
| 156 | + if pr is None: |
| 157 | + raise ValueError( |
| 158 | + f"Attempting to stop recording an action ({action_name}) which was never started." |
| 159 | + ) |
| 160 | + pr.disable() |
| 161 | + |
| 162 | + def describe(self): |
| 163 | + self.recorded_stats = {} |
| 164 | + for action_name, pr in self.profiled_actions.items(): |
| 165 | + s = io.StringIO() |
| 166 | + sortby = pstats.SortKey.CUMULATIVE |
| 167 | + ps = pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby) |
| 168 | + ps.print_stats(self.line_count_restriction) |
| 169 | + self.recorded_stats[action_name] = s.getvalue() |
| 170 | + if self.output_filename is not None: |
| 171 | + # save to file |
| 172 | + with open(self.output_filename, "w") as f: |
| 173 | + for action, stats in self.recorded_stats.items(): |
| 174 | + f.write(f"Profile stats for: {action}") |
| 175 | + f.write(stats) |
| 176 | + else: |
| 177 | + # log to standard out |
| 178 | + output_string = "\nProfiler Report\n" |
| 179 | + for action, stats in self.recorded_stats.items(): |
| 180 | + output_string += f"\nProfile stats for: {action}\n{stats}" |
| 181 | + logger.info(output_string) |
0 commit comments