profiler.py 38.6 KB
Newer Older
C
chenjian 已提交
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
C
chenjian 已提交
2
#
C
chenjian 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
C
chenjian 已提交
6
#
C
chenjian 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
C
chenjian 已提交
8
#
C
chenjian 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16 17
import datetime
import importlib
import json
C
chenjian 已提交
18 19 20 21 22 23 24
import os
import socket
from enum import Enum
from typing import Any, Callable, Iterable, Optional, Union
from warnings import warn

import paddle
25 26 27
from paddle.fluid.core import (
    ProfilerOptions,
    TracerEventType,
28
    _Profiler,
29
    disable_memory_recorder,
30
    disable_op_info_recorder,
31 32
    enable_memory_recorder,
    enable_op_info_recorder,
33
)
R
ronnywang 已提交
34
from paddle.profiler import utils
35 36

from .profiler_statistic import (
R
ronnywang 已提交
37
    SortedKeys,
38 39 40 41
    StatisticData,
    _build_table,
    gen_layer_flops,
)
Z
Zhang Ting 已提交
42
from .timer import benchmark
43
from .utils import RecordEvent, wrap_optimizers
C
chenjian 已提交
44 45


46 47 48 49
class SummaryView(Enum):
    r"""
    SummaryView define the summary view of different contents.

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    - **SummaryView.DeviceView** : The device summary view.

    - **SummaryView.OverView** : The overview summary view.

    - **SummaryView.ModelView** : The model summary view.

    - **SummaryView.DistributedView** : The distributed summary view.

    - **SummaryView.KernelView** : The kernel summary view.

    - **SummaryView.OperatorView** : The operator summary view.

    - **SummaryView.MemoryView** : The memory summary view.

    - **SummaryView.MemoryManipulationView** : The meomory manipulation summary view.

    - **SummaryView.UDFView** : The user defined summary view.
67 68 69 70 71 72 73 74 75 76 77 78
    """
    DeviceView = 0
    OverView = 1
    ModelView = 2
    DistributedView = 3
    KernelView = 4
    OperatorView = 5
    MemoryView = 6
    MemoryManipulationView = 7
    UDFView = 8


C
chenjian 已提交
79 80
class ProfilerState(Enum):
    r"""
C
chenjian 已提交
81
    ProfilerState is used to present the state of :ref:`Profiler <api_paddle_profiler_Profiler>` .
C
chenjian 已提交
82

C
chenjian 已提交
83
    The meaning of each ProfilerState is as following
C
chenjian 已提交
84

C
chenjian 已提交
85
    - **ProfilerState.CLOSED** : The profiler is closed, and no profiling data will be recorded.
C
chenjian 已提交
86

C
chenjian 已提交
87
    - **ProfilerState.READY** : The profiler is open, but the data will not be recorded. This state is used for reducing overhead influence when profiler starts.
C
chenjian 已提交
88

C
chenjian 已提交
89 90 91
    - **ProfilerState.RECORD** : The profiler is open, and the data will be recorded.

    - **ProfilerState.RECORD_AND_RETURN** : The profiler is open, and this state stands for the last batch of "RECORD" state in current profiling period. The collected data will be returned in this state.
C
chenjian 已提交
92 93 94 95
    """
    CLOSED = 0
    READY = 1
    RECORD = 2
C
chenjian 已提交
96
    RECORD_AND_RETURN = 3  # the last step of RECORD
C
chenjian 已提交
97 98 99 100


class ProfilerTarget(Enum):
    r"""
101
    ProfilerTarget is used to specify target device for :ref:`profiling <api_paddle_profiler_Profiler>` . Only CPU, GPU and XPU are supported currently.
C
chenjian 已提交
102

C
chenjian 已提交
103 104 105 106 107
    The meaning of each ProfilerState is as following

    - **ProfilerTarget.CPU** : Profile events on CPU.

    - **ProfilerTarget.GPU** : Profile events on GPU.
108 109

    - **ProfilerTarget.XPU** : Profile events on XPU.
C
chenjian 已提交
110 111 112
    """
    CPU = 0
    GPU = 1
113
    XPU = 2
114
    CUSTOM_DEVICE = 3
C
chenjian 已提交
115 116


117 118 119 120 121 122
def make_scheduler(
    *,
    closed: int,
    ready: int,
    record: int,
    repeat: int = 0,
123
    skip_first: int = 0,
124
) -> Callable:
C
chenjian 已提交
125
    r"""
C
chenjian 已提交
126
    Return a scheduler function, which scheduler the :ref:`state <api_paddle_profiler_ProfilerState>` according to the setting.
C
chenjian 已提交
127 128
    The state transform confirms to:

C
chenjian 已提交
129 130 131 132 133 134 135 136
    .. code-block:: text

        (CLOSED)  (CLOSED)    (CLOSED)  (READY)    (RECORD,last RETURN)      (CLOSED)
        START -> skip_first -> closed -> ready    ->    record       ->      END
                                |                        |
                                |                        | (if has_repeated < repeat)
                                - - - - - - - - - - - -
        Note that repeat <= 0 means the cycle will continue until the profiler exits.
C
chenjian 已提交
137

C
chenjian 已提交
138
    Args:
C
chenjian 已提交
139
        closed(int): The number of steps in state ProfilerState.CLOSED.
C
chenjian 已提交
140
        ready(int):  The number of steps in state ProfilerState.READY.
C
chenjian 已提交
141 142 143
        record(int): The number of steps in state ProfilerState.RECORD, and the state in last step will be set as ProfilerState.RECORD_AND_RETURN.
        repeat(int, optional): The number of cycles to repeat above state transform. Default value is 0, which means it will repeat this cycle until profiler exits.
        skip_first(int, optional): The number of first steps to drop, not participate in the state transform, and at ProfilerState.CLOSED state. Default value is 0.
C
chenjian 已提交
144 145

    Returns:
146
        A scheduler function, conforms to above state transform setting. The function will takes one parameter `step_num`, and returns corresponding ProfilerState.
C
chenjian 已提交
147 148

    Examples:
149
        1. profiling range [2, 5].
C
chenjian 已提交
150

151
        Assume batch 0: closed, batch 1: ready, batch [2, 5] record.
C
chenjian 已提交
152 153

            .. code-block:: python
C
chenjian 已提交
154
                :name: code-example1
C
chenjian 已提交
155 156 157 158 159

                import paddle.profiler as profiler
                profiler.make_scheduler(closed=1, ready=1, record=4, repeat=1)


160
        2. profiling range [3,6], [9,12], [15,18].
C
chenjian 已提交
161

162
        Assume batch 0: skiped, batch 1: closed, batch 2: ready, batch [3,6]: record, repeat.
C
chenjian 已提交
163 164

            .. code-block:: python
C
chenjian 已提交
165
                :name: code-example2
C
chenjian 已提交
166 167 168

                import paddle.profiler as profiler
                profiler.make_scheduler(closed=1, ready=1, record=4, skip_first=1)
C
chenjian 已提交
169 170 171 172 173 174 175 176 177
    """

    def getScheduleState(step: int) -> ProfilerState:
        assert step >= 0
        if step < skip_first:  # within skip_first, just skip
            return ProfilerState.CLOSED
        step = step - skip_first
        period_steps = closed + ready + record
        has_repeated = step // period_steps
178 179 180
        if (
            repeat > 0 and has_repeated >= repeat
        ):  # the period has repeated repeat times, return CLOSED state
C
chenjian 已提交
181 182 183 184 185 186 187 188 189 190 191
            return ProfilerState.CLOSED
        mod_step = step % period_steps
        if mod_step < closed:
            return ProfilerState.CLOSED
        elif mod_step >= closed and mod_step < closed + ready:
            return ProfilerState.READY
        else:
            if mod_step < period_steps - 1:
                return ProfilerState.RECORD
            else:
                return ProfilerState.RECORD_AND_RETURN
192 193 194 195 196 197 198 199

    assert (
        closed >= 0
        and ready >= 0
        and record > 0
        and repeat >= 0
        and skip_first >= 0
    ), "Invalid profiler scheduler arguments"
C
chenjian 已提交
200
    if ready == 0:
201 202
        warn(
            "Profiler will record data after enabling profiler immediately, \
C
chenjian 已提交
203
          some data collected at the beginning of profiling may be 'noisy' because of overhead."
204
        )
C
chenjian 已提交
205 206 207 208 209
    return getScheduleState


def _default_state_scheduler(step: int):
    r"""
210
    A default state scheduler, keep recording from the beginning of the profiler until ending.
C
chenjian 已提交
211 212 213 214
    """
    return ProfilerState.RECORD


215 216 217
def export_chrome_tracing(
    dir_name: str, worker_name: Optional[str] = None
) -> Callable:
C
chenjian 已提交
218 219
    r"""
    Return a callable, used for outputing tracing data to chrome tracing format file.
220 221
    The output file will be saved in directory ``dir_name``, and file name will be set as `worker_name`.
    if `worker_name` is not set, the default name is `[hostname]_[pid]`.
C
chenjian 已提交
222

C
chenjian 已提交
223
    Args:
C
chenjian 已提交
224
        dir_name(str): Directory to save profiling data.
225
        worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`.
226

C
chenjian 已提交
227 228
    Returns:
        A callable, which takes a Profiler object as parameter and calls its export method to save data to chrome tracing format file.
C
chenjian 已提交
229 230

    Examples:
C
chenjian 已提交
231 232
        The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler <api_paddle_profiler_Profiler>` .

C
chenjian 已提交
233
        .. code-block:: python
C
chenjian 已提交
234 235 236 237 238 239

            # required: gpu
            import paddle.profiler as profiler
            with profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (3, 10),
C
co63oc 已提交
240
                    on_trace_ready=profiler.export_chrome_tracing('./log')) as p:
C
chenjian 已提交
241 242 243
                for iter in range(10):
                    #train()
                    p.step()
C
chenjian 已提交
244 245 246 247 248 249
    """
    if not os.path.exists(dir_name):
        try:
            os.makedirs(dir_name, exist_ok=True)
        except Exception:
            raise RuntimeError(
250 251 252 253
                "Can not create directory '{}' for saving profiling results.".format(
                    dir_name
                )
            )
C
chenjian 已提交
254 255 256 257

    def handle_fn(prof):
        nonlocal worker_name
        if not worker_name:
258 259 260
            worker_name = "host_{}pid_{}".format(
                socket.gethostname(), str(os.getpid())
            )
C
chenjian 已提交
261 262
        now = datetime.datetime.now()
        filename = '{}_time_{}.paddle_trace.json'.format(
263 264
            worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f')
        )
C
chenjian 已提交
265 266 267 268 269
        prof.export(os.path.join(dir_name, filename), "json")

    return handle_fn


270 271 272
def export_protobuf(
    dir_name: str, worker_name: Optional[str] = None
) -> Callable:
C
chenjian 已提交
273 274
    r"""
    Return a callable, used for outputing tracing data to protobuf file.
275 276
    The output file will be saved in directory ``dir_name``, and file name will be set as ``worker_name``.
    if ``worker_name`` is not set, the default name is `[hostname]_[pid]`.
C
chenjian 已提交
277

C
chenjian 已提交
278
    Args:
C
chenjian 已提交
279
        dir_name(str): Directory to save profiling data.
280
        worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`.
C
chenjian 已提交
281 282 283

    Returns:
        A callable, which takes a Profiler object as parameter and calls its export method to save data to protobuf file.
C
chenjian 已提交
284 285

    Examples:
C
chenjian 已提交
286 287
        The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler <api_paddle_profiler_Profiler>` .

C
chenjian 已提交
288
        .. code-block:: python
C
chenjian 已提交
289 290 291 292 293 294 295 296 297 298

            # required: gpu
            import paddle.profiler as profiler
            with profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (3, 10),
                    on_trace_ready = profiler.export_protobuf('./log')) as p:
                for iter in range(10):
                    #train()
                    p.step()
C
chenjian 已提交
299 300 301 302 303 304
    """
    if not os.path.exists(dir_name):
        try:
            os.makedirs(dir_name, exist_ok=True)
        except Exception:
            raise RuntimeError(
305 306 307 308
                "Can not create directory '{}' for saving profiling results.".format(
                    dir_name
                )
            )
C
chenjian 已提交
309 310 311 312

    def handle_fn(prof):
        nonlocal worker_name
        if not worker_name:
313 314 315
            worker_name = "host_{}pid_{}".format(
                socket.gethostname(), str(os.getpid())
            )
C
chenjian 已提交
316 317
        now = datetime.datetime.now()
        filename = '{}_time_{}.paddle_trace.pb'.format(
318 319
            worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f')
        )
C
chenjian 已提交
320 321 322 323 324 325 326 327 328
        prof.export(os.path.join(dir_name, filename), "pb")

    return handle_fn


def _get_supported_targets() -> Iterable[ProfilerTarget]:
    r"""
    Get the current supported profiler target in the system.
    """
C
chenjian 已提交
329
    if _Profiler.is_cupti_supported():
330
        return [
331 332 333
            ProfilerTarget.CPU,
            ProfilerTarget.GPU,
            ProfilerTarget.CUSTOM_DEVICE,
334
        ]
F
fwenguang 已提交
335
    if _Profiler.is_cnpapi_supported():
336
        return [
337 338
            ProfilerTarget.CPU,
            ProfilerTarget.CUSTOM_DEVICE,
339
        ]
340 341 342 343 344 345
    if _Profiler.is_xpti_supported():
        return [
            ProfilerTarget.CPU,
            ProfilerTarget.XPU,
            ProfilerTarget.CUSTOM_DEVICE,
        ]
346
    return [ProfilerTarget.CPU, ProfilerTarget.CUSTOM_DEVICE]
C
chenjian 已提交
347 348 349 350


class Profiler:
    r"""
C
chenjian 已提交
351
    Profiler context manager, user interface to manage profiling process to start, stop, export profiling data and print summary table.
C
chenjian 已提交
352

C
chenjian 已提交
353
    Args:
354
        targets (list, optional): specify target devices to profile, and all existing and supported devices will be chosen by default. Currently supported values, :ref:`ProfilerTarget.CPU <api_paddle_profiler_ProfilerTarget>` , :ref:`ProfilerTarget.GPU <api_paddle_profiler_ProfilerTarget>` and :ref:`ProfilerTarget.XPU <api_paddle_profiler_ProfilerTarget>`  .
C
chenjian 已提交
355 356
        scheduler (Callable|tuple, optional): If it is a callable object, it takes a step number as parameter and return the corresponding :ref:`ProfilerState <api_paddle_profiler_ProfilerState>`. This callable object can be generated by :ref:`make_scheduler <api_paddle_profiler_make_scheduler>` function.
            If not provided (None), the default scheduler will keep tracing until the profiler exits. If it is a tuple, it has two values start_batch and end_batch,
C
chenjian 已提交
357
            which means profiling range [start_batch, end_batch).
C
chenjian 已提交
358
        on_trace_ready (Callable, optional): Callable object, serves as callback function, and takes the Profiler object as parameter, which provides a way for users to do post-processing.
359
            This callable object will be called when ``scheduler`` returns ``ProfilerState.RECORD_AND_RETURN``. The default value is :ref:`export_chrome_tracing <api_paddle_profiler_export_chrome_tracing>`.
Z
Zhang Ting 已提交
360 361
        timer_only (bool, optional): If it is True, the cost of Dataloader and every step of the model will be count without profiling. Otherwise, the model will
            be timed and profiled. Default: False.
362 363
        record_shapes (bool, optional): If it is True, collect op's input shape information. Default: False.
        profile_memory (bool, optional): If it is True, collect tensor memory allocation and release information. Default: False.
R
ronnywang 已提交
364
        custom_device_types (list, optional): If targets contain profiler.ProfilerTarget.CUSTOM_DEVICE, custom_device_types select the custom device type for profiling. The default value represents all custom devices will be selected.
365
        with_flops (bool, optional): If it is True, the flops of the op will be calculated. Default: False.
C
chenjian 已提交
366

C
chenjian 已提交
367
    Examples:
C
chenjian 已提交
368
        1. profiling range [2, 5).
C
chenjian 已提交
369 370

            .. code-block:: python
C
chenjian 已提交
371
                :name: code-example1
C
chenjian 已提交
372 373 374 375 376 377 378 379 380 381 382

                # required: gpu
                import paddle.profiler as profiler
                with profiler.Profiler(
                        targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                        scheduler = (2, 5),
                        on_trace_ready = profiler.export_chrome_tracing('./log')) as p:
                    for iter in range(10):
                        #train()
                        p.step()

383
        2. profiling range [2,4], [7, 9], [11,13].
C
chenjian 已提交
384 385

            .. code-block:: python
C
chenjian 已提交
386
                :name: code-example2
C
chenjian 已提交
387 388 389 390 391 392 393 394 395 396 397

                # required: gpu
                import paddle.profiler as profiler
                with profiler.Profiler(
                        targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                        scheduler = profiler.make_scheduler(closed=1, ready=1, record=3, repeat=3),
                        on_trace_ready = profiler.export_chrome_tracing('./log')) as p:
                    for iter in range(10):
                        #train()
                        p.step()

398
        3. Use profiler without context manager, and use default parameters.
C
chenjian 已提交
399 400

            .. code-block:: python
C
chenjian 已提交
401
                :name: code-example3
C
chenjian 已提交
402 403 404 405 406 407 408 409 410 411 412

                # required: gpu
                import paddle.profiler as profiler
                p = profiler.Profiler()
                p.start()
                for iter in range(10):
                    #train()
                    p.step()
                p.stop()
                p.summary()

413
        4. Use profiler to get throughput and cost of the model.
Z
Zhang Ting 已提交
414 415 416 417 418 419

            .. code-block:: python
                :name: code-example-timer1

                import paddle
                import paddle.profiler as profiler
420

Z
Zhang Ting 已提交
421 422 423
                class RandomDataset(paddle.io.Dataset):
                    def __init__(self, num_samples):
                        self.num_samples = num_samples
424

Z
Zhang Ting 已提交
425 426 427 428
                    def __getitem__(self, idx):
                        image = paddle.rand(shape=[100], dtype='float32')
                        label = paddle.randint(0, 10, shape=[1], dtype='int64')
                        return image, label
429

Z
Zhang Ting 已提交
430 431
                    def __len__(self):
                        return self.num_samples
432

Z
Zhang Ting 已提交
433 434
                class SimpleNet(paddle.nn.Layer):
                    def __init__(self):
435
                        super().__init__()
Z
Zhang Ting 已提交
436
                        self.fc = paddle.nn.Linear(100, 10)
437

Z
Zhang Ting 已提交
438 439
                    def forward(self, image, label=None):
                        return self.fc(image)
440

Z
Zhang Ting 已提交
441 442
                dataset = RandomDataset(20 * 4)
                simple_net = SimpleNet()
443
                opt = paddle.optimizer.SGD(learning_rate=1e-3, parameters=simple_net.parameters())
Z
Zhang Ting 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
                BATCH_SIZE = 4
                loader = paddle.io.DataLoader(
                    dataset,
                    batch_size=BATCH_SIZE)
                p = profiler.Profiler(timer_only=True)
                p.start()
                for i, (image, label) in enumerate(loader()):
                    out = simple_net(image)
                    loss = paddle.nn.functional.cross_entropy(out, label)
                    avg_loss = paddle.mean(loss)
                    avg_loss.backward()
                    opt.minimize(avg_loss)
                    simple_net.clear_gradients()
                    p.step(num_samples=BATCH_SIZE)
                    if i % 10 == 0:
                        step_info = p.step_info(unit='images')
                        print("Iter {}: {}".format(i, step_info))
                        # The average statistics for 10 steps between the last and this call will be
                        # printed when the "step_info" is called at 10 iteration intervals.
                        # The values you get may be different from the following.
                        # Iter 0:  reader_cost: 0.51946 s batch_cost: 0.66077 s ips: 6.054 images/s
                        # Iter 10:  reader_cost: 0.00014 s batch_cost: 0.00441 s ips: 907.009 images/s
                p.stop()
                # The performance summary will be automatically printed when the "stop" is called.
                # Reader Ratio: 2.658%
                # Time Unit: s, IPS Unit: images/s
                # |                 |       avg       |       max       |       min       |
                # |   reader_cost   |     0.00011     |     0.00013     |     0.00007     |
                # |    batch_cost   |     0.00405     |     0.00434     |     0.00326     |
                # |       ips       |    1086.42904   |    1227.30604   |    959.92796    |
C
chenjian 已提交
474 475
    """

476 477 478 479 480 481 482
    def __init__(
        self,
        *,
        targets: Optional[Iterable[ProfilerTarget]] = None,
        scheduler: Union[Callable[[int], ProfilerState], tuple, None] = None,
        on_trace_ready: Optional[Callable[..., Any]] = None,
        record_shapes: Optional[bool] = False,
483
        profile_memory: Optional[bool] = False,
484 485
        timer_only: Optional[bool] = False,
        emit_nvtx: Optional[bool] = False,
486 487
        custom_device_types: Optional[list] = [],
        with_flops: Optional[bool] = False,
488
    ):
C
chenjian 已提交
489 490 491 492 493 494
        supported_targets = _get_supported_targets()
        if targets:
            self.targets = set(targets)
            for target in targets:
                if target not in supported_targets:
                    self.targets.remove(target)
495 496 497 498 499
                    warn(
                        "Profiling {} is not supported in current context.".format(
                            target
                        )
                    )
C
chenjian 已提交
500 501 502 503 504 505
        else:
            self.targets = supported_targets
        profileoption = ProfilerOptions()
        if ProfilerTarget.CPU in self.targets:
            profileoption.trace_switch |= 1
        if ProfilerTarget.GPU in self.targets:
506
            profileoption.trace_switch |= 1 << 1
507 508
        if ProfilerTarget.XPU in self.targets:
            profileoption.trace_switch |= 1 << 2
509
        if ProfilerTarget.CUSTOM_DEVICE in self.targets:
510
            profileoption.trace_switch |= 1 << 3
511 512
            if not custom_device_types:
                custom_device_types = paddle.device.get_all_custom_device_type()
C
chenjian 已提交
513
        wrap_optimizers()
514
        self.profiler = _Profiler.create(profileoption, custom_device_types)
C
chenjian 已提交
515 516 517 518 519 520 521
        if callable(scheduler):
            self.scheduler = scheduler
        elif isinstance(scheduler, (tuple, list)):
            assert len(scheduler) == 2 and scheduler[1] > scheduler[0]
            start_batch, end_batch = scheduler
            start_batch = max(start_batch, 0)
            if start_batch >= 1:
522 523 524 525 526 527
                self.scheduler = make_scheduler(
                    closed=max(start_batch - 1, 0),
                    ready=1,
                    record=(end_batch - start_batch),
                    repeat=1,
                )
C
chenjian 已提交
528
            else:
529 530 531 532 533 534
                self.scheduler = make_scheduler(
                    closed=0,
                    ready=0,
                    record=(end_batch - start_batch),
                    repeat=1,
                )
C
chenjian 已提交
535 536 537
        else:
            self.scheduler = _default_state_scheduler

538
        if on_trace_ready is None:
C
chenjian 已提交
539 540 541 542 543 544 545 546
            self.on_trace_ready = export_chrome_tracing('./profiler_log/')
        else:
            self.on_trace_ready = on_trace_ready
        self.step_num = 0
        self.previous_state = ProfilerState.CLOSED
        self.current_state = self.scheduler(self.step_num)
        self.record_event = None
        self.profiler_result = None
Z
Zhang Ting 已提交
547
        self.timer_only = timer_only
548 549
        self.record_shapes = record_shapes
        self.profile_memory = profile_memory
550
        self.with_flops = with_flops
551
        self.emit_nvtx = emit_nvtx
C
chenjian 已提交
552 553 554 555 556 557 558 559 560 561 562

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()

    def start(self):
        r'''
        Start profiler and enter the first profiler step(0).
C
chenjian 已提交
563 564 565 566
        State transformed from CLOSED to self.current_state and trigger corresponding action.

        Examples:
            .. code-block:: python
C
chenjian 已提交
567
                :name: code-example4
C
chenjian 已提交
568 569 570 571 572 573 574 575 576 577 578 579

                # required: gpu
                import paddle.profiler as profiler
                prof = profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (1, 9),
                    on_trace_ready = profiler.export_chrome_tracing('./log'))
                prof.start()
                for iter in range(10):
                    #train()
                    prof.step()
                prof.stop()
Z
Zhang Ting 已提交
580

C
chenjian 已提交
581
        '''
582
        # Timing only without profiling.
Z
Zhang Ting 已提交
583
        benchmark().begin()
584 585
        if not self.timer_only or self.emit_nvtx:
            utils._is_profiler_used = True
Z
Zhang Ting 已提交
586 587
        if self.timer_only:
            return
588 589
        if self.record_shapes or self.with_flops:
            enable_op_info_recorder()
590 591
        if self.profile_memory:
            enable_memory_recorder()
C
chenjian 已提交
592 593 594 595 596 597 598 599 600
        # CLOSED -> self.current_state
        if self.current_state == ProfilerState.READY:
            self.profiler.prepare()
        elif self.current_state == ProfilerState.RECORD:
            self.profiler.prepare()
            self.profiler.start()
        elif self.current_state == ProfilerState.RECORD_AND_RETURN:
            self.profiler.prepare()
            self.profiler.start()
601
        self.record_event = RecordEvent(
602
            name=f"ProfileStep#{self.step_num}",
603 604
            event_type=TracerEventType.ProfileStep,
        )
C
chenjian 已提交
605 606 607 608 609 610
        self.record_event.begin()

    def stop(self):
        r'''
        Stop profiler and State transformed from self.current_state to CLOSED.
        Trigger corresponding action and post-process profiler result using self.on_trace_ready if result exists.
C
chenjian 已提交
611 612 613

        Examples:
            .. code-block:: python
C
chenjian 已提交
614
                :name: code-example5
C
chenjian 已提交
615 616 617 618 619 620 621 622 623 624 625 626

                # required: gpu
                import paddle.profiler as profiler
                prof = profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (1, 7),
                    on_trace_ready = profiler.export_chrome_tracing('./log'))
                prof.start()
                for iter in range(10):
                    #train()
                    prof.step()
                prof.stop()
C
chenjian 已提交
627
        '''
Z
Zhang Ting 已提交
628 629 630
        benchmark().end()
        if self.timer_only:
            return
631 632
        if self.record_shapes or self.with_flops:
            disable_op_info_recorder()
633 634
        if self.profile_memory:
            disable_memory_recorder()
C
chenjian 已提交
635
        # self.current_state -> CLOSED
636
        # In this situation, RECORD state is regarded as RECORD_AND_RETURN.
C
chenjian 已提交
637 638 639 640 641 642 643 644 645
        if self.record_event:
            self.record_event.end()
            self.record_event = None
        if self.current_state == ProfilerState.READY:
            warn(
                "Inproper Profiler state transform: READY->CLOSED, profiler will start and stop without saving data"
            )
            self.profiler.start()
            self.profiler.stop()
646 647 648 649
        if (
            self.current_state == ProfilerState.RECORD
            or self.current_state == ProfilerState.RECORD_AND_RETURN
        ):
C
chenjian 已提交
650 651 652
            self.profiler_result = self.profiler.stop()
            if self.on_trace_ready:
                self.on_trace_ready(self)
653
        utils._is_profiler_used = False
C
chenjian 已提交
654

655
    def step(self, num_samples: Optional[int] = None):
C
chenjian 已提交
656 657 658
        r"""
        Signals the profiler that the next profiling step has started.
        Get the new ProfilerState and trigger corresponding action.
C
chenjian 已提交
659

Z
Zhang Ting 已提交
660 661
        Args:
            num_samples (int|None, optional): Specifies the batch size of every step of the model
662
                that is used to compute throughput when `timer_only` is True. Default: None.
Z
Zhang Ting 已提交
663

C
chenjian 已提交
664 665
        Examples:
            .. code-block:: python
C
chenjian 已提交
666
                :name: code-example6
C
chenjian 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679

                # required: gpu
                import paddle.profiler as profiler
                prof = profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (3, 7),
                    on_trace_ready = profiler.export_chrome_tracing('./log'))

                prof.start()
                for iter in range(10):
                    #train()
                    prof.step()
                prof.stop()
C
chenjian 已提交
680
        """
Z
Zhang Ting 已提交
681 682 683
        benchmark().step(num_samples)
        if self.timer_only:
            return
C
chenjian 已提交
684 685 686 687 688 689 690
        if self.record_event:
            self.record_event.end()
            self.record_event = None
        self.previous_state = self.current_state
        self.step_num += 1
        self.current_state = self.scheduler(self.step_num)
        self._trigger_action()
691
        self.record_event = RecordEvent(
692
            name=f"ProfileStep#{self.step_num}",
693 694
            event_type=TracerEventType.ProfileStep,
        )
C
chenjian 已提交
695 696
        self.record_event.begin()

Z
Zhang Ting 已提交
697 698 699 700
    def step_info(self, unit=None):
        r"""
        Get statistics for current step. If the function is called at certain iteration
        intervals, the result is the average of all steps between the previous call and
701
        this call. Statistics are as follows:
Z
Zhang Ting 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

        1. reader_cost: the cost of loading data measured in seconds.

        2. batch_cost: the cost of step measured in seconds.

        3. ips(Instance Per Second): the throughput of the model measured in `samples/s`
        or others depends on the `unit`. When `num_samples` of `step()` is None, it is
        measured in `steps/s`.

        Args:
            unit (string, optional): The unit of input data is only used When `num_samples`
                of `step()` is specified as a number. For example, when it is `images`, the unit
                of throughput is `images/s`. Default: None, the unit of throughput is `samples/s`.

        Returns:
            string: A string representing the statistic.

        Examples:
            .. code-block:: python
                :name: code-example-timer2

                import paddle.profiler as profiler
                prof = profiler.Profiler(timer_only=True)
                prof.start()
                for iter in range(20):
                    #train()
                    prof.step()
                    if iter % 10 == 0:
                        print("Iter {}: {}".format(iter, prof.step_info()))
                        # The example does not call the DataLoader, so there is no "reader_cost".
                        # Iter 0:  batch_cost: 0.00001 s ips: 86216.623 steps/s
                        # Iter 10:  batch_cost: 0.00001 s ips: 103645.034 steps/s
                prof.stop()
                # Time Unit: s, IPS Unit: steps/s
                # |                 |       avg       |       max       |       min       |
                # |    batch_cost   |     0.00000     |     0.00002     |     0.00000     |
                # |       ips       |   267846.19437  |   712030.38727  |   45134.16662   |
        """
        if unit is None:
            unit = 'samples'
        return benchmark().step_info(unit)

C
chenjian 已提交
744 745 746 747 748 749 750
    def _trigger_action(self):
        if self.previous_state == ProfilerState.CLOSED:
            if self.current_state == ProfilerState.READY:  # CLOSED -> READY
                self.profiler.prepare()
            if self.current_state == ProfilerState.RECORD:  # CLOSED -> RECORD
                self.profiler.prepare()
                self.profiler.start()
751 752 753
            if (
                self.current_state == ProfilerState.RECORD_AND_RETURN
            ):  # CLOSED -> RECORD_AND_RETURN
C
chenjian 已提交
754 755 756 757 758 759 760 761 762 763 764 765
                self.profiler.prepare()
                self.profiler.start()

        elif self.previous_state == ProfilerState.READY:
            if self.current_state == ProfilerState.CLOSED:  # READY -> CLOSED
                warn(
                    "Improper schedule: READY->CLOSED, profiler will start and stop without saving data"
                )
                self.profiler.start()
                self.profiler.stop()
            if self.current_state == ProfilerState.RECORD:  # READY -> RECORD
                self.profiler.start()
766 767 768
            if (
                self.current_state == ProfilerState.RECORD_AND_RETURN
            ):  # READY -> RECORD_AND_RETURN
C
chenjian 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                self.profiler.start()

        elif self.previous_state == ProfilerState.RECORD:
            if self.current_state == ProfilerState.CLOSED:  # RECORD -> CLOSED
                warn(
                    "Improper schedule: RECORD->CLOSED, profiler will not saving data"
                )
                self.profiler.stop()

            if self.current_state == ProfilerState.READY:  # RECORD -> READY
                warn(
                    "Improper schedule: RECORD->READY, profiler will stop and re-prepare"
                )
                self.profiler.stop()
                self.profiler.prepare()
784 785 786
            if (
                self.current_state == ProfilerState.RECORD_AND_RETURN
            ):  # RECORD -> RECORD_AND_RETURN
C
chenjian 已提交
787 788 789 790
                pass

        else:
            assert self.previous_state == ProfilerState.RECORD_AND_RETURN
791 792 793
            if (
                self.current_state == ProfilerState.CLOSED
            ):  # RECORD_AND_RETURN -> CLOSED
C
chenjian 已提交
794
                self.profiler_result = self.profiler.stop()
795 796 797
            if (
                self.current_state == ProfilerState.READY
            ):  # RECORD_AND_RETURN -> READY
C
chenjian 已提交
798 799
                self.profiler_result = self.profiler.stop()
                self.profiler.prepare()
800 801 802
            if (
                self.current_state == ProfilerState.RECORD
            ):  # RECORD_AND_RETURN -> RECORD
C
chenjian 已提交
803 804 805
                self.profiler_result = self.profiler.stop()
                self.profiler.prepare()
                self.profiler.start()
806 807 808
            if (
                self.current_state == ProfilerState.RECORD_AND_RETURN
            ):  # RECORD_AND_RETURN -> RECORD_AND_RETURN
C
chenjian 已提交
809 810 811 812 813 814 815 816
                self.profiler_result = self.profiler.stop()
                self.profiler.prepare()
                self.profiler.start()
            if self.on_trace_ready:
                self.on_trace_ready(self)

    def export(self, path="", format="json"):
        r"""
C
chenjian 已提交
817 818 819 820
        Exports the tracing data to file.

        Args:
            path(str): file path of the output.
821
            format(str, optional): output format, can be chosen from ['json', 'pb'], 'json' for chrome tracing and 'pb' for protobuf, default value is 'json'.
C
chenjian 已提交
822

C
chenjian 已提交
823 824 825

        Examples:
            .. code-block:: python
C
chenjian 已提交
826
                :name: code-example7
C
chenjian 已提交
827 828 829 830 831 832 833 834 835 836 837 838

                # required: gpu
                import paddle.profiler as profiler
                prof = profiler.Profiler(
                    targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                    scheduler = (3, 7))
                prof.start()
                for iter in range(10):
                    #train()
                    prof.step()
                prof.stop()
                prof.export(path="./profiler_data.json", format="json")
C
chenjian 已提交
839 840 841 842
        """
        if self.profiler_result:
            self.profiler_result.save(path, format)

843 844 845 846 847 848 849 850
    def summary(
        self,
        sorted_by=SortedKeys.CPUTotal,
        op_detail=True,
        thread_sep=False,
        time_unit='ms',
        views=None,
    ):
C
chenjian 已提交
851
        r"""
C
chenjian 已提交
852
        Print the Summary table. Currently support overview, model, distributed, operator, memory manipulation and userdefined summary.
C
chenjian 已提交
853

C
chenjian 已提交
854 855 856 857 858
        Args:
            sorted_by( :ref:`SortedKeys <api_paddle_profiler_SortedKeys>` , optional): how to rank the op table items, default value is SortedKeys.CPUTotal.
            op_detail(bool, optional): expand each operator detail information, default value is True.
            thread_sep(bool, optional): print op table each thread, default value is False.
            time_unit(str, optional): time unit for display, can be chosen form ['s', 'ms', 'us', 'ns'], default value is 'ms'.
859
            views(SummaryView|list[SummaryView], optional): summary tables to print, default to None means all views to be printed.
C
chenjian 已提交
860 861 862 863

        Examples:
            .. code-block:: python

864 865 866 867 868 869 870 871 872 873 874 875 876 877
                >>> # doctest: +REQUIRES(env:GPU)
                >>> import paddle
                >>> paddle.device.set_device('gpu')
                >>> import paddle.profiler as profiler
                >>> prof = profiler.Profiler(
                ...     targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
                ...     scheduler = (3, 7),
                ...     on_trace_ready = profiler.export_chrome_tracing('./log'))
                >>> prof.start()
                >>> for iter in range(10):
                ...     #train()
                ...     prof.step()
                >>> prof.stop()
                >>> prof.summary(sorted_by=profiler.SortedKeys.CPUTotal, op_detail=True, thread_sep=False, time_unit='ms')
C
chenjian 已提交
878
        """
879 880 881
        if isinstance(views, SummaryView):
            views = [views]

C
chenjian 已提交
882 883 884
        if self.profiler_result:
            statistic_data = StatisticData(
                self.profiler_result.get_data(),
885 886
                self.profiler_result.get_extra_info(),
            )
C
chenjian 已提交
887
            print(
888 889 890 891 892 893 894 895 896
                _build_table(
                    statistic_data,
                    sorted_by=sorted_by,
                    op_detail=op_detail,
                    thread_sep=thread_sep,
                    time_unit=time_unit,
                    views=views,
                )
            )
C
chenjian 已提交
897

898 899 900 901 902 903 904 905 906 907 908 909
        if self.with_flops:
            self._print_flops()

    def _print_flops(self, repeat=1):
        if not self.with_flops:
            print('ERROR: with_flops disabled.')
            return

        print(" Flops Profiler Begin ".center(100, "-"))
        print(gen_layer_flops(self.profiler_result.get_data(), repeat))
        print("- Flops Profiler End -".center(100, "-"))

C
chenjian 已提交
910 911 912 913 914 915

def get_profiler(config_path):
    try:
        with open(config_path, 'r') as filehandle:
            config_dict = json.load(filehandle)
    except Exception as e:
916
        print(f'Load config file for profiler error: {e}')
C
chenjian 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
        print('Use default parameters instead.')
        return Profiler()
    translated_config_dict = {}
    if "targets" in config_dict:
        try:
            translated_config_dict['targets'] = []
            for target in config_dict['targets']:
                if target.lower() == "cpu":
                    translated_config_dict['targets'].append(ProfilerTarget.CPU)
                elif target.lower() == 'gpu':
                    translated_config_dict['targets'].append(ProfilerTarget.GPU)
        except:
            print('Set targets parameter error, use default parameter instead.')
            translated_config_dict['targets'] = None
    if "scheduler" in config_dict:
        try:
            if isinstance(config_dict['scheduler'], dict):
                for key, value in config_dict['scheduler'].items():
                    module_path = value['module']
                    use_direct = value['use_direct']
                    module = importlib.import_module(module_path)
                    method = getattr(module, key)
                    if not use_direct:
                        translated_config_dict['scheduler'] = method(
941 942
                            *value['args'], **value['kwargs']
                        )
C
chenjian 已提交
943 944 945 946
                    else:
                        translated_config_dict['scheduler'] = method
            else:
                translated_config_dict['scheduler'] = [
947 948
                    config_dict['scheduler'][0],
                    config_dict['scheduler'][1],
C
chenjian 已提交
949 950 951 952
                ]

        except:
            print(
953 954
                'Set scheduler parameter error, use default parameter instead.'
            )
C
chenjian 已提交
955 956 957 958 959 960 961 962 963 964 965
            translated_config_dict['scheduler'] = None
    if "on_trace_ready" in config_dict:
        try:
            if isinstance(config_dict['on_trace_ready'], dict):
                for key, value in config_dict['on_trace_ready'].items():
                    module_path = value['module']
                    use_direct = value['use_direct']
                    module = importlib.import_module(module_path)
                    method = getattr(module, key)
                    if not use_direct:
                        translated_config_dict['on_trace_ready'] = method(
966 967
                            *value['args'], **value['kwargs']
                        )
C
chenjian 已提交
968 969 970 971 972 973 974 975 976 977 978 979
                    else:
                        translated_config_dict['on_trace_ready'] = method
        except:
            print(
                'Set on_trace_ready parameter error, use default parameter instead.'
            )
            translated_config_dict['on_trace_ready'] = None
    if "timer_only" in config_dict:
        if isinstance(config_dict['timer_only'], bool):
            translated_config_dict['timer_only'] = config_dict['timer_only']
        else:
            print(
980 981
                'Set timer_only parameter error, use default parameter instead.'
            )
C
chenjian 已提交
982 983

    return Profiler(**translated_config_dict)