1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/python/profiler.h"
17
18 #include "pybind11/pybind11.h"
19 #include "tensorflow/core/profiler/rpc/profiler_server.h"
20 #include "tensorflow/python/profiler/internal/traceme_wrapper.h"
21
22 namespace xla {
23
24 namespace py = pybind11;
25
26 namespace {
27 // Adds a trivial forwarding class so these Python bindings and TensorFlow's
28 // bindings of the same thing don't register the same class with pybind11.
29 class TraceMeWrapper : public tensorflow::profiler::TraceMeWrapper {
30 public:
31 using tensorflow::profiler::TraceMeWrapper::TraceMeWrapper;
32 };
33 } // namespace
34
BuildProfilerSubmodule(py::module * m)35 void BuildProfilerSubmodule(py::module* m) {
36 py::module profiler =
37 m->def_submodule("profiler", "TensorFlow profiler integration");
38 py::class_<tensorflow::profiler::ProfilerServer,
39 std::unique_ptr<tensorflow::profiler::ProfilerServer>>
40 profiler_server_class(profiler, "ProfilerServer");
41 profiler.def(
42 "start_server",
43 [](int port) -> std::unique_ptr<tensorflow::profiler::ProfilerServer> {
44 auto server = absl::make_unique<tensorflow::profiler::ProfilerServer>();
45 server->StartProfilerServer(port);
46 return server;
47 },
48 py::arg("port"));
49
50 py::class_<TraceMeWrapper> traceme_class(profiler, "TraceMe",
51 py::module_local());
52 traceme_class.def(py::init<py::str, py::kwargs>())
53 .def("__enter__", [](py::object self) -> py::object { return self; })
54 .def("__exit__",
55 [](py::object self, const py::object& ex_type,
56 const py::object& ex_value,
57 const py::object& traceback) -> py::object {
58 py::cast<TraceMeWrapper*>(self)->Stop();
59 return py::none();
60 })
61 .def("set_metadata", &TraceMeWrapper::SetMetadata)
62 .def_static("is_enabled", &TraceMeWrapper::IsEnabled);
63 }
64
65 } // namespace xla
66