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/pjrt/nccl_id_store.h"
17
18 #include <string>
19 #include <utility>
20
21 #ifdef NCCL_ENABLED
22 #include "third_party/nccl/nccl.h"
23 #endif // NCCL_ENABLED
24
25 #include "tensorflow/compiler/xla/util.h"
26
27 namespace xla {
28
GetNcclUniqueId(const gpu::NcclCliqueKey & key)29 StatusOr<std::string> NcclIdStore::GetNcclUniqueId(
30 const gpu::NcclCliqueKey& key) {
31 // The caller must ensure that threads calling this method concurrently have
32 // unique keys, otherwise the global key-value store may hold the wrong value.
33 {
34 absl::MutexLock lock(&mu_);
35 auto it = cache_.find(key);
36 if (it != cache_.end()) {
37 return it->second;
38 }
39 }
40 std::string id_string;
41 int primary_node_id = device_to_node_.at(key.devices()[0]);
42 if (node_id_ == primary_node_id) {
43 #ifdef NCCL_ENABLED
44 ncclUniqueId id;
45 ncclResult_t r = ncclGetUniqueId(&id);
46 TF_RET_CHECK(r == ncclSuccess);
47 id_string = std::string(id.internal, NCCL_UNIQUE_ID_BYTES);
48 TF_RETURN_IF_ERROR(client_->KeyValueSet(key.ToString(), id_string));
49 #else
50 return FailedPrecondition("NCCL support was not built into XLA binary.");
51 #endif
52 } else {
53 TF_ASSIGN_OR_RETURN(id_string, client_->BlockingKeyValueGet(
54 key.ToString(), absl::Minutes(5)));
55 }
56 absl::MutexLock lock(&mu_);
57 auto result = cache_.emplace(key, std::move(id_string));
58 TF_RET_CHECK(result.second) << "Unique ID already in cache.";
59 return result.first->second;
60 }
61
62 } // namespace xla
63