pytorch-lightning

Форк
0
99 строк · 3.7 Кб
1
# Copyright The Lightning AI team.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
"""Profiler to check if there are any bottlenecks in your code."""
15

16
import cProfile
17
import io
18
import logging
19
import pstats
20
from pathlib import Path
21
from typing import Dict, Optional, Tuple, Union
22

23
from typing_extensions import override
24

25
from lightning.pytorch.profilers.profiler import Profiler
26

27
log = logging.getLogger(__name__)
28

29

30
class AdvancedProfiler(Profiler):
31
    """This profiler uses Python's cProfiler to record more detailed information about time spent in each function call
32
    recorded during a given action.
33

34
    The output is quite verbose and you should only use this if you want very detailed reports.
35

36
    """
37

38
    def __init__(
39
        self,
40
        dirpath: Optional[Union[str, Path]] = None,
41
        filename: Optional[str] = None,
42
        line_count_restriction: float = 1.0,
43
    ) -> None:
44
        """
45
        Args:
46
            dirpath: Directory path for the ``filename``. If ``dirpath`` is ``None`` but ``filename`` is present, the
47
                ``trainer.log_dir`` (from :class:`~lightning.pytorch.loggers.tensorboard.TensorBoardLogger`)
48
                will be used.
49

50
            filename: If present, filename where the profiler results will be saved instead of printing to stdout.
51
                The ``.txt`` extension will be used automatically.
52

53
            line_count_restriction: this can be used to limit the number of functions
54
                reported for each action. either an integer (to select a count of lines),
55
                or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines)
56

57
        Raises:
58
            ValueError:
59
                If you attempt to stop recording an action which was never started.
60
        """
61
        super().__init__(dirpath=dirpath, filename=filename)
62
        self.profiled_actions: Dict[str, cProfile.Profile] = {}
63
        self.line_count_restriction = line_count_restriction
64

65
    @override
66
    def start(self, action_name: str) -> None:
67
        if action_name not in self.profiled_actions:
68
            self.profiled_actions[action_name] = cProfile.Profile()
69
        self.profiled_actions[action_name].enable()
70

71
    @override
72
    def stop(self, action_name: str) -> None:
73
        pr = self.profiled_actions.get(action_name)
74
        if pr is None:
75
            raise ValueError(f"Attempting to stop recording an action ({action_name}) which was never started.")
76
        pr.disable()
77

78
    @override
79
    def summary(self) -> str:
80
        recorded_stats = {}
81
        for action_name, pr in self.profiled_actions.items():
82
            s = io.StringIO()
83
            ps = pstats.Stats(pr, stream=s).strip_dirs().sort_stats("cumulative")
84
            ps.print_stats(self.line_count_restriction)
85
            recorded_stats[action_name] = s.getvalue()
86
        return self._stats_to_str(recorded_stats)
87

88
    @override
89
    def teardown(self, stage: Optional[str]) -> None:
90
        super().teardown(stage=stage)
91
        self.profiled_actions = {}
92

93
    def __reduce__(self) -> Tuple:
94
        # avoids `TypeError: cannot pickle 'cProfile.Profile' object`
95
        return (
96
            self.__class__,
97
            (),
98
            {"dirpath": self.dirpath, "filename": self.filename, "line_count_restriction": self.line_count_restriction},
99
        )
100

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.