xref: /aosp_15_r20/external/tensorflow/tensorflow/python/data/experimental/service/server_lib_wrapper.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 <string>
17 
18 #include "Python.h"
19 #include "absl/strings/str_cat.h"
20 #include "pybind11/chrono.h"
21 #include "pybind11/complex.h"
22 #include "pybind11/detail/common.h"
23 #include "pybind11/functional.h"
24 #include "pybind11/pybind11.h"
25 #include "pybind11/pytypes.h"
26 #include "pybind11/stl.h"
27 #include "tensorflow/core/data/service/dispatcher_client.h"
28 #include "tensorflow/core/data/service/grpc_util.h"
29 #include "tensorflow/core/data/service/server_lib.h"
30 #include "tensorflow/core/platform/errors.h"
31 #include "tensorflow/core/platform/types.h"
32 #include "tensorflow/core/protobuf/data_service.pb.h"
33 #include "tensorflow/core/protobuf/service_config.pb.h"
34 #include "tensorflow/python/lib/core/pybind11_lib.h"
35 #include "tensorflow/python/lib/core/pybind11_status.h"
36 
37 namespace py = pybind11;
38 
PYBIND11_MODULE(_pywrap_server_lib,m)39 PYBIND11_MODULE(_pywrap_server_lib, m) {
40   py::class_<tensorflow::data::DispatchGrpcDataServer>(m,
41                                                        "DispatchGrpcDataServer")
42       .def("start", &tensorflow::data::DispatchGrpcDataServer::Start)
43       .def("stop", &tensorflow::data::DispatchGrpcDataServer::Stop)
44       .def("join", &tensorflow::data::DispatchGrpcDataServer::Join,
45            py::call_guard<py::gil_scoped_release>())
46       .def("bound_port", &tensorflow::data::DispatchGrpcDataServer::BoundPort)
47       .def("num_workers",
48            [](tensorflow::data::DispatchGrpcDataServer* server) -> int {
49              int num_workers;
50              tensorflow::Status status = server->NumWorkers(&num_workers);
51              tensorflow::MaybeRaiseFromStatus(status);
52              return num_workers;
53            });
54 
55   py::class_<tensorflow::data::WorkerGrpcDataServer>(m, "WorkerGrpcDataServer")
56       .def("start", &tensorflow::data::WorkerGrpcDataServer::Start)
57       .def("stop", &tensorflow::data::WorkerGrpcDataServer::Stop)
58       .def("join", &tensorflow::data::WorkerGrpcDataServer::Join,
59            py::call_guard<py::gil_scoped_release>())
60       .def("bound_port", &tensorflow::data::WorkerGrpcDataServer::BoundPort)
61       .def("num_tasks",
62            [](tensorflow::data::WorkerGrpcDataServer* server) -> int {
63              int num_tasks;
64              tensorflow::Status status = server->NumTasks(&num_tasks);
65              tensorflow::MaybeRaiseFromStatus(status);
66              return num_tasks;
67            });
68 
69   m.def(
70       "TF_DATA_NewDispatchServer",
71       [](std::string serialized_dispatcher_config)
72           -> std::unique_ptr<tensorflow::data::DispatchGrpcDataServer> {
73         tensorflow::data::experimental::DispatcherConfig config;
74         if (!config.ParseFromString(serialized_dispatcher_config)) {
75           tensorflow::MaybeRaiseFromStatus(tensorflow::errors::InvalidArgument(
76               "Failed to deserialize dispatcher config."));
77         }
78         std::unique_ptr<tensorflow::data::DispatchGrpcDataServer> server;
79         tensorflow::Status status =
80             tensorflow::data::NewDispatchServer(config, server);
81         tensorflow::MaybeRaiseFromStatus(status);
82         return server;
83       },
84       py::return_value_policy::reference);
85 
86   m.def(
87       "TF_DATA_NewWorkerServer",
88       [](std::string serialized_worker_config)
89           -> std::unique_ptr<tensorflow::data::WorkerGrpcDataServer> {
90         tensorflow::data::experimental::WorkerConfig config;
91         if (!config.ParseFromString(serialized_worker_config)) {
92           tensorflow::MaybeRaiseFromStatus(tensorflow::errors::InvalidArgument(
93               "Failed to deserialize worker config."));
94         }
95         std::unique_ptr<tensorflow::data::WorkerGrpcDataServer> server;
96         tensorflow::Status status =
97             tensorflow::data::NewWorkerServer(config, server);
98         tensorflow::MaybeRaiseFromStatus(status);
99         return server;
100       },
101       py::return_value_policy::reference);
102 
103   // TODO(b/236725000): Remove this after the forward compatibility window
104   // has passed.
105   m.def(
106       "TF_DATA_GetDataServiceMetadata",
107       [](int64_t dataset_id, const std::string& address,
108          const std::string& protocol) -> tensorflow::data::DataServiceMetadata {
109         tensorflow::data::DataServiceMetadata metadata;
110         tensorflow::data::DataServiceDispatcherClient client(address, protocol);
111         int64_t deadline_micros = tensorflow::kint64max;
112         tensorflow::Status status;
113         Py_BEGIN_ALLOW_THREADS;
114         status = tensorflow::data::grpc_util::Retry(
115             [&]() {
116               return client.GetDataServiceMetadata(absl::StrCat(dataset_id),
117                                                    metadata);
118             },
119             /*description=*/
120             tensorflow::strings::StrCat(
121                 "Get data service metadata for dataset ", dataset_id,
122                 " from dispatcher at ", address),
123             deadline_micros);
124         Py_END_ALLOW_THREADS;
125         tensorflow::MaybeRaiseFromStatus(status);
126         return metadata;
127       },
128       py::return_value_policy::reference);
129 
130   m.def(
131       "TF_DATA_GetDataServiceMetadataByID",
132       [](std::string dataset_id, const std::string& address,
133          const std::string& protocol) -> tensorflow::data::DataServiceMetadata {
134         tensorflow::data::DataServiceMetadata metadata;
135         tensorflow::data::DataServiceDispatcherClient client(address, protocol);
136         int64_t deadline_micros = tensorflow::kint64max;
137         tensorflow::Status status;
138         Py_BEGIN_ALLOW_THREADS;
139         status = tensorflow::data::grpc_util::Retry(
140             [&]() {
141               return client.GetDataServiceMetadata(dataset_id, metadata);
142             },
143             /*description=*/
144             tensorflow::strings::StrCat(
145                 "Get data service metadata for dataset ", dataset_id,
146                 " from dispatcher at ", address),
147             deadline_micros);
148         Py_END_ALLOW_THREADS;
149         tensorflow::MaybeRaiseFromStatus(status);
150         return metadata;
151       },
152       py::return_value_policy::reference);
153 
154   py::class_<tensorflow::data::DataServiceMetadata> data_service_metadata(
155       m, "DataServiceMetadata");
156   data_service_metadata.def(py::init<>())
157       .def_property_readonly(
158           "element_spec",
159           [](const tensorflow::data::DataServiceMetadata& data_service_metadata)
160               -> py::bytes { return data_service_metadata.element_spec(); })
161       .def_property_readonly(
162           "compression", &tensorflow::data::DataServiceMetadata::compression)
163       .def("__repr__", &tensorflow::data::DataServiceMetadata::DebugString);
164 };
165