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/stream_executor/gpu/asm_compiler.h"
17 #include "tensorflow/compiler/xla/stream_executor/gpu/gpu_diagnostics.h"
18 #include "tensorflow/compiler/xla/stream_executor/gpu/gpu_driver.h"
19 #include "tensorflow/core/lib/core/errors.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 if (CUDA_VERSION >= 11030) {
39 int driver_cuda_version;
40 // Get the highest version of CUDA supported by this driver.
41 RETURN_IF_CUDA_ERROR(cuDriverGetVersion(&driver_cuda_version));
42 if (driver_cuda_version < CUDA_VERSION) {
43 return tensorflow::errors::Unimplemented(
44 "CUDA version unsupported by NVIDIA driver version.");
45 }
46 }
47
48 gpu::ScopedActivateContext activation(context);
49
50 CUlinkState link_state;
51 RETURN_IF_CUDA_ERROR(cuLinkCreate(0, nullptr, nullptr, &link_state));
52 for (auto& image : images) {
53 auto status = cuLinkAddData(link_state, CU_JIT_INPUT_CUBIN,
54 static_cast<void*>(image.bytes.data()),
55 image.bytes.size(), "", 0, nullptr, nullptr);
56 if (status != CUDA_SUCCESS) {
57 LOG(ERROR) << "cuLinkAddData fails. This is usually caused by stale "
58 "driver version.";
59 }
60 RETURN_IF_CUDA_ERROR(status);
61 }
62 void* cubin_out;
63 size_t cubin_size;
64 RETURN_IF_CUDA_ERROR(cuLinkComplete(link_state, &cubin_out, &cubin_size));
65 std::vector<uint8> cubin(static_cast<uint8*>(cubin_out),
66 static_cast<uint8*>(cubin_out) + cubin_size);
67 RETURN_IF_CUDA_ERROR(cuLinkDestroy(link_state));
68 return std::move(cubin);
69 }
70
71 } // namespace stream_executor
72