• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/core/tpu/tpu_model_server_initializer.h"
17 
18 #include <dlfcn.h>
19 
20 #include "tensorflow/core/platform/errors.h"
21 #include "tensorflow/core/platform/status.h"
22 #include "tensorflow/core/tpu/tpu_api_dlsym_set_fn.h"
23 #include "tensorflow/core/tpu/tpu_api.h"
24 #include "tensorflow/core/tpu/tpu_initializer_helper.h"
25 #include "tensorflow/stream_executor/tpu/tpu_platform.h"
26 
27 namespace tensorflow {
28 namespace tpu {
29 namespace {
30 #if !defined(PLATFORM_GOOGLE)
31 #include "tensorflow/core/tpu/tpu_library_init_fns.inc"
InitializeTpuLibrary(void * library_handle)32 Status InitializeTpuLibrary(void* library_handle) {
33   Status s = InitializeTpuStructFns(library_handle);
34 
35   // TPU platform registration must only be performed after the library is
36   // loaded. We do not want to register a TPU platform in XLA without the
37   // supporting library providing the necessary APIs.
38   if (s.ok()) {
39     // Retrieve arguments from environment if applicable
40     std::pair<std::vector<std::string>, std::vector<const char*> > args =
41         GetLibTpuInitArguments();
42 
43     void (*initialize_fn)(bool init_library, int num_args, const char** args);
44     initialize_fn = reinterpret_cast<decltype(initialize_fn)>(
45         dlsym(library_handle, "TfTpu_Initialize"));
46     (*initialize_fn)(/*init_library=*/true, args.second.size(),
47                      args.second.data());
48 
49     RegisterTpuPlatform();
50   }
51 
52   return s;
53 }
54 
FindAndLoadTpuModelServer()55 bool FindAndLoadTpuModelServer() {
56   const char* env_value = getenv("TPU_LIBRARY_PATH");
57   const char* libtpu_path =
58       env_value && strlen(env_value) > 0 ? env_value : "libtpu.so";
59   LOG(INFO) << "Libtpu path is: " << libtpu_path;
60   void* library = dlopen(libtpu_path, RTLD_NOW);
61   if (library) {
62     if (TryAcquireTpuLock()) {
63       InitializeTpuLibrary(library);
64     }
65   }
66   OpsApiFn()->TfTpu_InitializeTpuModelServerFn();
67   return true;
68 }
69 
70 static bool tpu_library_finder = FindAndLoadTpuModelServer();
71 #endif  // PLATFORM_GOOGLE
72 }  // namespace
73 }  // namespace tpu
74 }  // namespace tensorflow
75