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 #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_ 17 #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_ 18 19 #include "tensorflow/core/grappler/optimizers/graph_optimizer.h" 20 #include "tensorflow/core/platform/cpu_info.h" 21 #include "tensorflow/core/protobuf/rewriter_config.pb.h" 22 23 namespace tensorflow { 24 namespace grappler { 25 26 // CUDA: convert to float16 on GPU 27 // BF16: convert to bfloat16 on CPU 28 // CPU: emulate float16 on CPU without changing operator kernel 29 enum class AutoMixedPrecisionMode { CUDA, BF16, CPU }; 30 31 // Convert data types to float16 or bfloat16 where appropriate to improve 32 // performance on GPUs or CPUs. 33 class AutoMixedPrecision : public GraphOptimizer { 34 public: 35 // If 'mode' is CUDA, converts nodes to float16 on Nvidia GPUs. If BF16, 36 // converts nodes to bfloat16 on CPUs in order to take advantage of oneDNN 37 // performance improvements with bfloat16. 38 explicit AutoMixedPrecision( 39 AutoMixedPrecisionMode mode = AutoMixedPrecisionMode::CUDA) mode_(mode)40 : mode_(mode) {} 41 ~AutoMixedPrecision()42 ~AutoMixedPrecision() override {} 43 name()44 string name() const override { 45 switch (mode_) { 46 case AutoMixedPrecisionMode::CUDA: 47 return "auto_mixed_precision"; 48 case AutoMixedPrecisionMode::BF16: 49 return "auto_mixed_precision_onednn_bfloat16"; 50 case AutoMixedPrecisionMode::CPU: 51 return "auto_mixed_precision_cpu"; 52 default: 53 LOG(FATAL) << "Invalid value for AutoMixedPrecisionMode: " // Crash Ok 54 << static_cast<int>(mode_); 55 } 56 }; 57 UsesFunctionLibrary()58 bool UsesFunctionLibrary() const override { return false; } 59 60 Status Optimize(Cluster* cluster, const GrapplerItem& item, 61 GraphDef* output) override; 62 63 private: 64 const AutoMixedPrecisionMode mode_; 65 }; 66 67 } // end namespace grappler 68 } // end namespace tensorflow 69 70 #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_ 71