• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 std::string & name)149   AutoTuneMap(const std::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       VLOG(1) << "TF_AUTOTUNE_THRESHOLD = " << threshold_str;
155       strings::safe_strto32(threshold_str, &min_score_threshold_);
156     }
157     const char* min_warmup_iteration_str =
158         getenv("TF_AUTOTUNE_MIN_WARMUP_ITERATIONS");
159     if (min_warmup_iteration_str != nullptr) {
160       strings::safe_strto32(min_warmup_iteration_str, &min_warmup_iterations);
161     }
162     min_score_threshold_ = std::max(min_score_threshold_, 1);
163     max_autotune_count_ = std::max(
164         5 * min_score_threshold_ * min_score_threshold_, min_warmup_iterations);
165     max_autotune_global_count_ = 2 * max_autotune_count_;
166     autotune_global_count_ = 0;
167   }
168 
169   template <class Group, class Params, class Cfg>
170   friend class AutoTuneSingleton;
171 
172   struct Hasher {
operatorHasher173     std::size_t operator()(const Parameters& parameter) const {
174       return parameter.hash();
175     }
176   };
177 
GetActionSummary(StringPiece action,const Parameters & params,const Config & config)178   std::string GetActionSummary(StringPiece action, const Parameters& params,
179                                const Config& config) {
180     return strings::Printf("autotune_map %s %s: %s -> (%s)", name_.c_str(),
181                            string(action).c_str(), params.ToString().c_str(),
182                            config.ToString().c_str());
183   }
184 
185   mutable mutex mu_;
186   struct ValueType {
187     Config config;
188     int32 score;
189     int32 count;
190   };
191   std::unordered_map<Parameters, ValueType, Hasher> params_config_map_
192       TF_GUARDED_BY(mu_);
193   std::string name_;
194   int32 min_score_threshold_;
195   int32 max_autotune_count_;
196   int32 max_autotune_global_count_;
197   int32 autotune_global_count_;
198 
199   TF_DISALLOW_COPY_AND_ASSIGN(AutoTuneMap);
200 };
201 
202 // A Singleton helper that manages the global autotune results by groups.
203 // The caller specified arbitrary Group type that can distinguish between
204 // different autotune results, even if their Parameters and Configs are the
205 // same.
206 template <class Group, typename Parameters, typename Config>
207 class AutoTuneSingleton {
208  public:
209   typedef AutoTuneMap<Parameters, Config> AutoTuneType;
GetInstance()210   static AutoTuneType* GetInstance() {
211     static AutoTuneType* instance = new AutoTuneType(Group::name());
212     return instance;
213   }
214 };
215 
216 // Logs convolution results to customized back-storage.
217 void LogConvAutotuneResults(se::dnn::ConvolutionKind kind,
218                             se::dnn::DataType element_type,
219                             se::DeviceMemoryBase input_buffer,
220                             se::DeviceMemoryBase filter_buffer,
221                             se::DeviceMemoryBase output_buffer,
222                             const se::dnn::BatchDescriptor& input_desc,
223                             const se::dnn::FilterDescriptor& filter_desc,
224                             const se::dnn::BatchDescriptor& output_desc,
225                             const se::dnn::ConvolutionDescriptor& conv_desc,
226                             se::StreamExecutor* stream_exec,
227                             absl::Span<const AutotuneResult> results);
228 
229 // Logs fused convolution results to customized back-storage.
230 void LogFusedConvForwardAutotuneResults(
231     se::dnn::DataType element_type, se::DeviceMemoryBase input_buffer,
232     se::DeviceMemoryBase filter_buffer, se::DeviceMemoryBase output_buffer,
233     se::DeviceMemoryBase bias_buffer, se::DeviceMemoryBase side_input_buffer,
234     const se::dnn::BatchDescriptor& input_desc,
235     const se::dnn::FilterDescriptor& filter_desc,
236     const se::dnn::BatchDescriptor& output_desc,
237     const se::dnn::ConvolutionDescriptor& conv_desc, double conv_scale,
238     double side_value_scale, se::dnn::ActivationMode activation_mode,
239     se::StreamExecutor* stream_exec, absl::Span<const AutotuneResult> results);
240 
241 // Returns the best algorithms for the config, one is the fastest, the other is
242 // other is fastest with 0 scratch space. Unsuccessful autotuning results are
243 // allowed and ignored.
244 Status BestCudnnConvAlgorithm(absl::Span<const AutotuneResult> results,
245                               se::dnn::AlgorithmConfig* algo);
246 
247 }  // namespace tensorflow
248 
249 #endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
250 
251 #endif  // TENSORFLOW_CORE_KERNELS_GPU_UTILS_H_
252