• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef GOOGLE_CUDA
17 #include "cuda/include/cuda.h"
18 #include "tensorflow/stream_executor/cuda/cuda_activation.h"
19 #endif  // GOOGLE_CUDA
20 
21 #include "tensorflow/core/common_runtime/gpu/gpu_cudamalloc_allocator.h"
22 
23 #include "tensorflow/core/common_runtime/gpu/gpu_id.h"
24 #include "tensorflow/core/common_runtime/gpu/gpu_id_utils.h"
25 #include "tensorflow/core/common_runtime/gpu/gpu_init.h"
26 #include "tensorflow/core/platform/stream_executor.h"
27 
28 namespace tensorflow {
29 
GPUcudaMallocAllocator(Allocator * allocator,PlatformGpuId platform_gpu_id)30 GPUcudaMallocAllocator::GPUcudaMallocAllocator(Allocator* allocator,
31                                                PlatformGpuId platform_gpu_id)
32     : base_allocator_(allocator) {
33   stream_exec_ =
34       GpuIdUtil::ExecutorForPlatformGpuId(platform_gpu_id).ValueOrDie();
35 }
36 
~GPUcudaMallocAllocator()37 GPUcudaMallocAllocator::~GPUcudaMallocAllocator() { delete base_allocator_; }
38 
AllocateRaw(size_t alignment,size_t num_bytes)39 void* GPUcudaMallocAllocator::AllocateRaw(size_t alignment, size_t num_bytes) {
40 #ifdef GOOGLE_CUDA
41   // allocate with cudaMalloc
42   se::cuda::ScopedActivateExecutorContext scoped_activation{stream_exec_};
43   CUdeviceptr rv = 0;
44   CUresult res = cuMemAlloc(&rv, num_bytes);
45   if (res != CUDA_SUCCESS) {
46     LOG(ERROR) << "cuMemAlloc failed to allocate " << num_bytes;
47     return nullptr;
48   }
49   return reinterpret_cast<void*>(rv);
50 #else
51   return nullptr;
52 #endif  // GOOGLE_CUDA
53 }
DeallocateRaw(void * ptr)54 void GPUcudaMallocAllocator::DeallocateRaw(void* ptr) {
55 #ifdef GOOGLE_CUDA
56   // free with cudaFree
57   CUresult res = cuMemFree(reinterpret_cast<CUdeviceptr>(ptr));
58   if (res != CUDA_SUCCESS) {
59     LOG(ERROR) << "cuMemFree failed to free " << ptr;
60   }
61 #endif  // GOOGLE_CUDA
62 }
63 
TracksAllocationSizes()64 bool GPUcudaMallocAllocator::TracksAllocationSizes() { return false; }
65 
66 }  // namespace tensorflow
67