|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | + |
| 8 | +""" |
| 9 | +Simple Logging Profiler |
| 10 | +=========================== |
| 11 | +
|
| 12 | +This is a simple profiler that's used as part of the trainer app example. This |
| 13 | +logs the Lightning training stage durations a logger such as Tensorboard. This |
| 14 | +output is used for HPO optimization with Ax. |
| 15 | +""" |
| 16 | + |
| 17 | +import time |
| 18 | +from typing import Dict |
| 19 | + |
| 20 | +from pytorch_lightning.loggers.base import LightningLoggerBase |
| 21 | +from pytorch_lightning.profiler.base import BaseProfiler |
| 22 | + |
| 23 | + |
| 24 | +class SimpleLoggingProfiler(BaseProfiler): |
| 25 | + """ |
| 26 | + This profiler records the duration of actions (in seconds) and reports the |
| 27 | + mean duration of each action to the specified logger. Reported metrics are |
| 28 | + in the format `duration_<event>`. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self, logger: LightningLoggerBase) -> None: |
| 32 | + super().__init__() |
| 33 | + |
| 34 | + self.current_actions: Dict[str, float] = {} |
| 35 | + self.logger = logger |
| 36 | + |
| 37 | + def start(self, action_name: str) -> None: |
| 38 | + if action_name in self.current_actions: |
| 39 | + raise ValueError( |
| 40 | + f"Attempted to start {action_name} which has already started." |
| 41 | + ) |
| 42 | + self.current_actions[action_name] = time.monotonic() |
| 43 | + |
| 44 | + def stop(self, action_name: str) -> None: |
| 45 | + end_time = time.monotonic() |
| 46 | + if action_name not in self.current_actions: |
| 47 | + raise ValueError( |
| 48 | + f"Attempting to stop recording an action ({action_name}) which was never started." |
| 49 | + ) |
| 50 | + start_time = self.current_actions.pop(action_name) |
| 51 | + duration = end_time - start_time |
| 52 | + self.logger.log_metrics({"duration_" + action_name: duration}) |
| 53 | + |
| 54 | + def summary(self) -> str: |
| 55 | + return "" |
0 commit comments