1 /* Copyright 2017 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/service/gpu/kernel_thunk.h"
17 
18 #include "absl/memory/memory.h"
19 #include "absl/strings/string_view.h"
20 #include "tensorflow/compiler/xla/service/gpu/gpu_executable.h"
21 #include "tensorflow/compiler/xla/service/gpu/hlo_execution_profiler.h"
22 #include "tensorflow/compiler/xla/types.h"
23 #include "tensorflow/compiler/xla/util.h"
24 #include "tensorflow/core/platform/logging.h"
25 #include "tensorflow/core/platform/stream_executor_no_cuda.h"
26 
27 namespace xla {
28 namespace gpu {
29 
KernelThunk(absl::Span<const BufferAllocation * const> args,const string & kernel_name,const HloInstruction * hlo_instruction,int unroll_factor)30 KernelThunk::KernelThunk(absl::Span<const BufferAllocation* const> args,
31                          const string& kernel_name,
32                          const HloInstruction* hlo_instruction,
33                          int unroll_factor)
34     : Thunk(Kind::kKernel, hlo_instruction),
35       args_(args.begin(), args.end()),
36       kernel_name_(kernel_name),
37       unroll_factor_(unroll_factor) {}
38 
Initialize(const GpuExecutable & executable,se::StreamExecutor * executor)39 Status KernelThunk::Initialize(const GpuExecutable& executable,
40                                se::StreamExecutor* executor) {
41   tensorflow::mutex_lock lock(mutex_);
42   if (!loader_spec_) {
43     loader_spec_.reset(new se::MultiKernelLoaderSpec(args_.size()));
44     loader_spec_->AddCudaPtxInMemory(executable.ptx(), kernel_name_);
45 
46     if (!executable.cubin().empty()) {
47       loader_spec_->AddCudaCubinInMemory(
48           reinterpret_cast<const char*>(executable.cubin().data()),
49           kernel_name_);
50     }
51   }
52 
53   // Load the kernel into the device if necessary.
54   //
55   // We could alternatively do this within ExecuteOnStream, but doing it here
56   // lets the time spent loading the kernel not count towards our execution
57   // profiles.
58   auto it = kernel_cache_.find(executor);
59   if (kernel_cache_.end() == it) {
60     it = kernel_cache_.emplace(executor, se::KernelBase(executor)).first;
61     if (!executor->GetKernel(*loader_spec_, &it->second)) {
62       return InternalError("Unable to load kernel %s", kernel_name_);
63     }
64   }
65 
66   return Status::OK();
67 }
68 
SetLaunchDimensions(const LaunchDimensions & launch_dims)69 void KernelThunk::SetLaunchDimensions(const LaunchDimensions& launch_dims) {
70   tensorflow::mutex_lock lock(mutex_);
71   launch_dimensions_ = launch_dims;
72 }
73 
ExecuteOnStream(const BufferAllocations & buffer_allocations,se::Stream * stream,HloExecutionProfiler * profiler)74 Status KernelThunk::ExecuteOnStream(const BufferAllocations& buffer_allocations,
75                                     se::Stream* stream,
76                                     HloExecutionProfiler* profiler) {
77   // Load the kernel.
78   se::StreamExecutor* executor = stream->parent();
79   LaunchDimensions launch_dimensions;
80   const se::KernelBase* kernel = nullptr;
81 
82   {
83     tensorflow::mutex_lock lock(mutex_);
84     auto it = kernel_cache_.find(executor);
85     CHECK(it != kernel_cache_.end())
86         << "Initialize() not called for StreamExecutor " << executor;
87     launch_dimensions = launch_dimensions_;
88     kernel = &it->second;
89   }
90 
91   VLOG(3) << "Launching " << kernel->name();
92   // Launch the kernel with potentially multiple blocks and threads.
93   static constexpr int kKernelArgsLimit = 1024;
94   auto kernel_args = absl::make_unique<se::KernelArgsArray<kKernelArgsLimit>>();
95   for (const BufferAllocation* arg : args_) {
96     const auto& buf = buffer_allocations.GetDeviceAddress(arg->index());
97     kernel_args->add_device_memory_argument(buf);
98     VLOG(3) << "  Arg: alloc #" << arg->index() << ": " << buf.opaque() << " ("
99             << buf.size() << "B)";
100   }
101   auto op_profiler = profiler->MakeScopedInstructionProfiler(hlo_instruction());
102   if (!stream->parent()->Launch(
103           stream, se::ThreadDim(launch_dimensions.threads_per_block()),
104           se::BlockDim(launch_dimensions.block_count()), *kernel,
105           *kernel_args)) {
106     return InternalError("Unable to launch kernel %s", kernel_name_);
107   }
108   return Status::OK();
109 }
110 
111 }  // namespace gpu
112 }  // namespace xla
113