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/lib/core/errors.h"
17 #include "tensorflow/stream_executor/gpu/asm_compiler.h"
18 #include "tensorflow/stream_executor/gpu/gpu_diagnostics.h"
19 #include "tensorflow/stream_executor/gpu/gpu_driver.h"
20
21 namespace stream_executor {
22
23 #define RETURN_IF_CUDA_ERROR(expr) \
24 do { \
25 CUresult _status = expr; \
26 if (!SE_PREDICT_TRUE(_status == CUDA_SUCCESS)) { \
27 const char* error_string; \
28 cuGetErrorString(_status, &error_string); \
29 std::ostringstream oss; \
30 oss << error_string << "\nin " << __FILE__ << "(" << __LINE__ << "): '" \
31 << #expr << "'"; \
32 return port::Status(port::error::UNKNOWN, oss.str().c_str()); \
33 } \
34 } while (false)
35
LinkGpuAsm(gpu::GpuContext * context,std::vector<CubinOrPTXImage> images)36 port::StatusOr<std::vector<uint8>> LinkGpuAsm(
37 gpu::GpuContext* context, std::vector<CubinOrPTXImage> images) {
38 const bool linking_supported = [] {
39 if (CUDA_VERSION < 11030) {
40 return true;
41 }
42 auto version_or_status = gpu::Diagnostician::FindKernelDriverVersion();
43 if (!version_or_status.ok()) {
44 LOG(WARNING) << "Couldn't read CUDA driver version.";
45 return false;
46 }
47 return std::get<0>(*version_or_status) >= 465;
48 }();
49
50 if (!linking_supported) {
51 return tensorflow::errors::Unimplemented("Linking is unsupported");
52 }
53
54 gpu::ScopedActivateContext activation(context);
55
56 CUlinkState link_state;
57 RETURN_IF_CUDA_ERROR(cuLinkCreate(0, nullptr, nullptr, &link_state));
58 for (auto& image : images) {
59 auto status = cuLinkAddData(link_state, CU_JIT_INPUT_CUBIN,
60 static_cast<void*>(image.bytes.data()),
61 image.bytes.size(), "", 0, nullptr, nullptr);
62 if (status != CUDA_SUCCESS) {
63 LOG(ERROR) << "cuLinkAddData fails. This is usually caused by stale "
64 "driver version.";
65 }
66 RETURN_IF_CUDA_ERROR(status);
67 }
68 void* cubin_out;
69 size_t cubin_size;
70 RETURN_IF_CUDA_ERROR(cuLinkComplete(link_state, &cubin_out, &cubin_size));
71 std::vector<uint8> cubin(static_cast<uint8*>(cubin_out),
72 static_cast<uint8*>(cubin_out) + cubin_size);
73 RETURN_IF_CUDA_ERROR(cuLinkDestroy(link_state));
74 return std::move(cubin);
75 }
76
77 } // namespace stream_executor
78