1 /* Copyright 2015 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_CORE_KERNELS_GPU_UTILS_H_
17 #define TENSORFLOW_CORE_KERNELS_GPU_UTILS_H_
18
19 #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
20
21 #include <unordered_map>
22
23 #include "absl/types/span.h"
24 #include "tensorflow/core/framework/tensor.h"
25 #include "tensorflow/core/lib/core/status.h"
26 #include "tensorflow/core/lib/strings/str_util.h"
27 #include "tensorflow/core/lib/strings/strcat.h"
28 #include "tensorflow/core/lib/strings/stringprintf.h"
29 #include "tensorflow/core/platform/logging.h"
30 #include "tensorflow/core/platform/stream_executor.h"
31
32 namespace stream_executor {
33 class RedzoneAllocator;
34 } // namespace stream_executor
35
36 namespace tensorflow {
37
38 class NodeDef;
39 class AutotuneResult;
40
41 // Return whether the redzone check is disabled.
42 //
43 // Controlled by the TF_DISABLE_RZ_CHECK environment variable.
44 bool RedzoneCheckDisabled();
45
46 // Return an allocated buffer with redzones the size of `buffer`. Does
47 // *not* copy the contents of the `buffer` into the newly allocated buffer:
48 // assumes that buffer is a pure out-parameter.
49 //
50 // Returns `buffer` if RedzoneCheckDisabled() is true.
51 //
52 // On error, return `buffer`, and log an error message (once).
53 se::DeviceMemoryBase WrapRedzoneBestEffort(se::RedzoneAllocator* rz_allocator,
54 se::DeviceMemoryBase buffer);
55
56 // Check the passed allocator for redzone violations.
57 // If violations have occurred, mark the corresponding autotune result
58 // as a failure.
59 void CheckRedzones(const se::RedzoneAllocator& rz_allocator,
60 tensorflow::AutotuneResult* autotune_result);
61
62 template <typename T>
AsDeviceMemory(const T * cuda_memory,uint64 size)63 inline se::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory, uint64 size) {
64 se::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory), size * sizeof(T));
65 se::DeviceMemory<T> typed(wrapped);
66 return typed;
67 }
68
69 // A helper class that looks up the best autotuned config from parameters.
70 // Due to the noisy nature of autotune, especially with multiple devices, it
71 // only accepts a config if its margin exceeds a threshold.
72 // For the same shape configs, if a new best config matches the previous best,
73 // they get promoted; otherwise, the winner gets demoted. This process stops
74 // when the winner's score exceeds the threshold.
75 // In a bad case when two configs are very close to each other and flips
76 // back and forth randomly, the expected number of experiments before autotune
77 // settles is O(threshold ^ 2). So we recommend that number of warmup runs
78 // for any benchmarks.
79 template <typename Parameters, typename Config>
80 class AutoTuneMap {
81 public:
Find(const Parameters & params,Config * config)82 bool Find(const Parameters& params, Config* config) const {
83 mutex_lock lock(mu_);
84 auto iter = params_config_map_.find(params);
85 if (iter == params_config_map_.end() ||
86 (iter->second.score < min_score_threshold_ &&
87 iter->second.count <= max_autotune_count_)) {
88 return false;
89 }
90 *config = iter->second.config;
91 return true;
92 }
Insert(const Parameters & params,const Config & config)93 void Insert(const Parameters& params, const Config& config) {
94 mutex_lock lock(mu_);
95 auto iter = params_config_map_.find(params);
96 int new_score = 0;
97 if (iter == params_config_map_.end()) {
98 // Create a new entry if params is new.
99 VLOG(1) << GetActionSummary("creates", params, config);
100 params_config_map_.insert(
101 std::make_pair(params, ValueType{config, 1, 1}));
102 new_score = 1;
103 } else if (iter->second.score < min_score_threshold_ &&
104 iter->second.count <= max_autotune_count_) {
105 DCHECK_GT(iter->second.score, 0);
106 if (iter->second.config != config) {
107 // If it is different from the current winner, demotes the winner.
108 VLOG(1) << GetActionSummary("demotes", params, config);
109 new_score = --iter->second.score;
110 ++iter->second.count;
111 if (new_score <= 0) {
112 VLOG(1) << GetActionSummary("erases", params, config);
113 params_config_map_.erase(iter);
114 }
115 } else {
116 // If it is the same as the current winner, promotes the winner.
117 VLOG(1) << GetActionSummary("promotes", params, config);
118 new_score = ++iter->second.score;
119 ++iter->second.count;
120 }
121 }
122 if (new_score >= min_score_threshold_) {
123 VLOG(1) << GetActionSummary("accepts", params, config);
124 } else if (autotune_global_count_ >= max_autotune_global_count_) {
125 // The autotuning exceeds the max iteration threshold and we accept the
126 // the winner if it exists in the map, otherwise we accept the current
127 // winner.
128 auto winner = params_config_map_.find(params);
129 if (winner == params_config_map_.end()) {
130 VLOG(1) << GetActionSummary("creates", params, config);
131 for (int i = 0; i < min_score_threshold_; ++i) {
132 VLOG(1) << GetActionSummary("promotes", params, config);
133 }
134 params_config_map_.insert(
135 std::make_pair(params, ValueType{config, min_score_threshold_, 1}));
136 } else {
137 int promotes_times = min_score_threshold_ - winner->second.score;
138 for (int i = 0; i < promotes_times; ++i) {
139 VLOG(1) << GetActionSummary("promotes", params, config);
140 }
141 winner->second.score = min_score_threshold_;
142 }
143 VLOG(1) << GetActionSummary("accepts", params, config);
144 }
145 autotune_global_count_++;
146 }
147
148 private:
AutoTuneMap(const string & name)149 AutoTuneMap(const string& name) : name_(name) {
150 min_score_threshold_ = 1;
151 int min_warmup_iterations = 10;
152 const char* threshold_str = getenv("TF_AUTOTUNE_THRESHOLD");
153 if (threshold_str != nullptr) {
154 strings::safe_strto32(threshold_str, &min_score_threshold_);
155 }
156 const char* min_warmup_iteration_str =
157 getenv("TF_AUTOTUNE_MIN_WARMUP_ITERATIONS");
158 if (min_warmup_iteration_str != nullptr) {
159 strings::safe_strto32(min_warmup_iteration_str, &min_warmup_iterations);
160 }
161 min_score_threshold_ = std::max(min_score_threshold_, 1);
162 max_autotune_count_ = std::max(
163 5 * min_score_threshold_ * min_score_threshold_, min_warmup_iterations);
164 max_autotune_global_count_ = 2 * max_autotune_count_;
165 autotune_global_count_ = 0;
166 }
167
168 template <class Group, class Params, class Cfg>
169 friend class AutoTuneSingleton;
170
171 struct Hasher {
operatorHasher172 std::size_t operator()(const Parameters& parameter) const {
173 return parameter.hash();
174 }
175 };
176
GetActionSummary(StringPiece action,const Parameters & params,const Config & config)177 string GetActionSummary(StringPiece action, const Parameters& params,
178 const Config& config) {
179 return strings::Printf("autotune_map %s %s: %s -> (%s)", name_.c_str(),
180 string(action).c_str(), params.ToString().c_str(),
181 config.ToString().c_str());
182 }
183
184 mutable mutex mu_;
185 struct ValueType {
186 Config config;
187 int32 score;
188 int32 count;
189 };
190 std::unordered_map<Parameters, ValueType, Hasher> params_config_map_
191 GUARDED_BY(mu_);
192 string name_;
193 int32 min_score_threshold_;
194 int32 max_autotune_count_;
195 int32 max_autotune_global_count_;
196 int32 autotune_global_count_;
197
198 TF_DISALLOW_COPY_AND_ASSIGN(AutoTuneMap);
199 };
200
201 // A Singleton helper that manages the global autotune results by groups.
202 // The caller specified arbitrary Group type that can distinguish between
203 // different autotune results, even if their Parameters and Configs are the
204 // same.
205 template <class Group, typename Parameters, typename Config>
206 class AutoTuneSingleton {
207 public:
208 typedef AutoTuneMap<Parameters, Config> AutoTuneType;
GetInstance()209 static AutoTuneType* GetInstance() {
210 static AutoTuneType* instance = new AutoTuneType(Group::name());
211 return instance;
212 }
213 };
214
215 // Logs convolution results to customized back-storage.
216 void LogConvAutotuneResults(se::dnn::ConvolutionKind kind,
217 se::dnn::DataType element_type,
218 se::DeviceMemoryBase input_buffer,
219 se::DeviceMemoryBase filter_buffer,
220 se::DeviceMemoryBase output_buffer,
221 const se::dnn::BatchDescriptor& input_desc,
222 const se::dnn::FilterDescriptor& filter_desc,
223 const se::dnn::BatchDescriptor& output_desc,
224 const se::dnn::ConvolutionDescriptor& conv_desc,
225 se::StreamExecutor* stream_exec,
226 absl::Span<const AutotuneResult> results);
227
228 // Logs fused convolution results to customized back-storage.
229 void LogFusedConvForwardAutotuneResults(
230 se::dnn::DataType element_type, se::DeviceMemoryBase input_buffer,
231 se::DeviceMemoryBase filter_buffer, se::DeviceMemoryBase output_buffer,
232 se::DeviceMemoryBase bias_buffer, se::DeviceMemoryBase side_input_buffer,
233 const se::dnn::BatchDescriptor& input_desc,
234 const se::dnn::FilterDescriptor& filter_desc,
235 const se::dnn::BatchDescriptor& output_desc,
236 const se::dnn::ConvolutionDescriptor& conv_desc, double conv_scale,
237 double side_value_scale, se::dnn::ActivationMode activation_mode,
238 se::StreamExecutor* stream_exec, absl::Span<const AutotuneResult> results);
239
240 // Returns the best algorithms for the config, one is the fastest, the other is
241 // other is fastest with 0 scracth space. Unsuccessful autotuning results are
242 // allowed and ignored.
243 Status BestCudnnConvAlgorithm(absl::Span<const AutotuneResult> results,
244 se::dnn::AlgorithmConfig* algo);
245
246 } // namespace tensorflow
247
248 #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
249
250 #endif // TENSORFLOW_CORE_KERNELS_GPU_UTILS_H_
251