Repository navigation
Expand file tree
/
Copy pathprofiler.py
More file actions
133 lines (110 loc) · 4.44 KB
/
Copy pathprofiler.py
File metadata and controls
133 lines (110 loc) · 4.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
# ==============================================================================
"""Profiler for eager mode."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import threading
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.framework import c_api_util
from tensorflow.python.platform import gfile
from tensorflow.python.platform import tf_logging as logging
LOGDIR_PLUGIN = 'plugins/profile'
_profiler = None
_profiler_lock = threading.Lock()
_run_num = 0
def start():
"""Start profiling.
Only one active profiling session is allowed.
Raises:
AssertionError: If another profiling session is running.
"""
global _profiler
if _profiler is not None:
raise AssertionError('Another profiler is running.')
with _profiler_lock:
profiler_context = pywrap_tensorflow.TFE_NewProfilerContext()
if context.default_execution_mode == context.EAGER_MODE:
pywrap_tensorflow.TFE_ProfilerContextSetEagerContext(
profiler_context,
context.context()._handle) # pylint: disable=protected-access
_profiler = pywrap_tensorflow.TFE_NewProfiler(profiler_context)
pywrap_tensorflow.TFE_DeleteProfilerContext(profiler_context)
if not pywrap_tensorflow.TFE_ProfilerIsOk(_profiler):
logging.warning('Another profiler session is running which is probably '
'created by profiler server. Please avoid using profiler '
'server and profiler APIs at the same time.')
def stop():
"""Stop current profiling session and return its result.
Returns:
A binary string of tensorflow.tpu.Trace. User can write the string
to file for offline analysis by tensorboard.
Raises:
AssertionError: If there is no active profiling session.
"""
global _profiler
global _run_num
if _profiler is None:
raise AssertionError('Cannot stop profiling. No profiler is running.')
with c_api_util.tf_buffer() as buffer_:
pywrap_tensorflow.TFE_ProfilerSerializeToString(
context.context()._handle, # pylint: disable=protected-access
_profiler,
buffer_)
result = pywrap_tensorflow.TF_GetBuffer(buffer_)
with _profiler_lock:
pywrap_tensorflow.TFE_DeleteProfiler(_profiler)
_profiler = None
_run_num += 1
return result
def start_profiler_server(port):
"""Start a profiler grpc server that listens to given port.
The profiler server will keep the program running even the training finishes.
Please shutdown the server with CTRL-C. It can be used in both eager mode and
graph mode. The service defined in
tensorflow/contrib/tpu/profiler/tpu_profiler.proto. Please use
tensorflow/contrib/tpu/profiler/capture_tpu_profile to capture tracable
file following https://cloud.google.com/tpu/docs/cloud-tpu-tools#capture_trace
Args:
port: port profiler server listens to.
"""
profiler_context = pywrap_tensorflow.TFE_NewProfilerContext()
if context.default_execution_mode == context.EAGER_MODE:
pywrap_tensorflow.TFE_ProfilerContextSetEagerContext(
profiler_context,
context.context()._handle) # pylint: disable=protected-access
pywrap_tensorflow.TFE_StartProfilerServer(profiler_context, port)
pywrap_tensorflow.TFE_DeleteProfilerContext(profiler_context)
class Profiler(object):
"""Context-manager eager profiler api.
Example usage:
```python
with Profiler("/path/to/logdir"):
# do some work
```
"""
def __init__(self, logdir):
self._logdir = logdir
def __enter__(self):
start()
def __exit__(self, typ, value, tb):
result = stop()
plugin_dir = os.path.join(self._logdir, LOGDIR_PLUGIN,
'run{}'.format(_run_num))
gfile.MakeDirs(plugin_dir)
with gfile.Open(os.path.join(plugin_dir, 'local.trace'), 'wb') as f:
f.write(result)