1 /* Copyright 2018 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 #ifndef TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_
17 #define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_
18 
19 #include <unordered_map>
20 
21 #include "tensorflow/core/framework/allocator.h"
22 
23 #if GOOGLE_CUDA && GOOGLE_TENSORRT
24 #include "third_party/tensorrt/NvInfer.h"
25 #endif  // GOOGLE_CUDA && GOOGLE_TENSORRT
26 
27 namespace tensorflow {
28 namespace tensorrt {
29 // std::align is not supported, so this function mimic its behavior.
30 void* Align(uint64_t alignment, uint64_t size, void*& ptr, uint64_t& space);
31 }  // namespace tensorrt
32 }  // namespace tensorflow
33 
34 #if GOOGLE_CUDA && GOOGLE_TENSORRT
35 
36 namespace tensorflow {
37 namespace tensorrt {
38 
39 class TRTBaseAllocator : public nvinfer1::IGpuAllocator {
40   // Base allocator class so we can have a virtual destructor;
41  public:
42   // python wrapper seems to be not happy with an pure virtual destructor;
43   virtual ~TRTBaseAllocator() = default;
44 };
45 
46 class TRTDeviceAllocator : public TRTBaseAllocator {
47   // Allocator implementation wrapping TF device allocators.
48  public:
49   TRTDeviceAllocator(Allocator* allocator);
50 
51   // TODO(aaroey): base class doesn't have a virtual destructor, work with
52   // Nvidia to fix it.
~TRTDeviceAllocator()53   virtual ~TRTDeviceAllocator() {
54     VLOG(1) << "Destroying allocator attached to " << allocator_->Name();
55   }
56   void* allocate(uint64_t size, uint64_t alignment, uint32_t flags) override;
57   void free(void* memory) override;
58 
59  private:
60   Allocator* allocator_;
61 
62   // supporting alignment from allocation request requires a map to free;
63   std::unordered_map<void*, void*> mem_map_;
64 };
65 
66 }  // namespace tensorrt
67 }  // namespace tensorflow
68 
69 #endif  // GOOGLE_CUDA && GOOGLE_TENSORRT
70 #endif  // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_
71