1 /* Copyright 2021 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 #ifndef TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ 16 #define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ 17 #if GOOGLE_CUDA && GOOGLE_TENSORRT 18 19 #include "absl/strings/str_format.h" 20 #include "absl/strings/str_join.h" 21 #include "tensorflow/core/graph/graph.h" 22 #include "tensorflow/core/lib/core/status.h" 23 24 namespace tensorflow { 25 namespace tensorrt { 26 namespace convert { 27 28 constexpr std::array<const char*, 4> kQuantizationOpNames = { 29 "QuantizeAndDequantizeV2", 30 "QuantizeAndDequantizeV3", 31 "FakeQuantWithMinMaxVars", 32 "FakeQuantWithMinMaxArgs", 33 }; 34 35 // Operations with supported conversion to Q/DQ ops in TensorRT explicit 36 // precision mode. 37 constexpr std::array<const char*, 1> kExplicitQuantizationOpNames = { 38 "QuantizeAndDequantizeV2", 39 }; 40 41 // Contains two scaling factors for quantization and dequantization 42 // respectively. A shift factor is omitted as TensorRT only supports symmetric 43 // quantization. 44 template <typename T, size_t N> 45 struct QuantizationScales { 46 std::array<T, N> quantize_scale; 47 std::array<T, N> dequantize_scale; 48 }; 49 50 // In TensorRT 7 and 8, only uniform tensor scaling is supported for 51 // activations. 52 using UniformQuantizationScales = QuantizationScales<float, 1>; 53 54 // Per-channel scaling is supported for weights in TensorRT version >= 8.0. 55 template <size_t ChannelDimSize> 56 using PerChannelQuantizationScales = QuantizationScales<float, ChannelDimSize>; 57 58 template <typename T, size_t N> 59 std::ostream& operator<<(std::ostream& os, 60 const QuantizationScales<T, N>& scales) { 61 os << absl::StrFormat("QuantizationScales[quantize={%s},dequantize={%s}]", 62 absl::StrJoin(scales.quantize_scale, ","), 63 absl::StrJoin(scales.dequantize_scale, ",")); 64 return os; 65 } 66 67 // Returns true if the Tensorflow node is a quantize and dequantize operation. 68 bool IsQuantizeAndDequantizeOp(const Node*); 69 70 } // namespace convert 71 } // namespace tensorrt 72 } // namespace tensorflow 73 74 #endif // GOOGLE_CUDA && GOOGLE_TENSORRT 75 76 #endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ 77