1/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include <string>
17
18#include "pybind11/pybind11.h"
19#include "tensorflow/core/common_runtime/device.h"
20#include "tensorflow/core/common_runtime/device_factory.h"
21#include "tensorflow/core/framework/device_attributes.pb.h"
22#include "tensorflow/core/lib/core/errors.h"
23#include "tensorflow/core/protobuf/config.pb.h"
24#include "tensorflow/core/public/session_options.h"
25#include "tensorflow/python/lib/core/pybind11_proto.h"
26#include "tensorflow/python/lib/core/pybind11_status.h"
27
28namespace py = ::pybind11;
29
30PYBIND11_MODULE(_pywrap_device_lib, m) {
31 m.def("list_devices", [](py::object serialized_config) {
32 tensorflow::ConfigProto config;
33 if (!serialized_config.is_none()) {
34 config.ParseFromString(
35 static_cast<std::string>(serialized_config.cast<py::bytes>()));
36 }
37
38 tensorflow::SessionOptions options;
39 options.config = config;
40 std::vector<std::unique_ptr<tensorflow::Device>> devices;
41 tensorflow::MaybeRaiseFromStatus(tensorflow::DeviceFactory::AddDevices(
42 options, /*name_prefix=*/"", &devices));
43
44 py::list results;
45 std::string serialized_attr;
46 for (const auto& device : devices) {
47 if (!device->attributes().SerializeToString(&serialized_attr)) {
48 tensorflow::MaybeRaiseFromStatus(tensorflow::errors::Internal(
49 "Could not serialize DeviceAttributes to bytes"));
50 }
51
52 // The default type caster for std::string assumes its contents
53 // is UTF8-encoded.
54 results.append(py::bytes(serialized_attr));
55 }
56 return results;
57 });
58}
59