common.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_COMMON_H_
  13. #define TENSORFLOW_LITE_KERNELS_INTERNAL_COMMON_H_
  14. #ifndef ALLOW_SLOW_GENERIC_DEPTHWISECONV_FALLBACK
  15. #ifdef GEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK
  16. #define ALLOW_SLOW_GENERIC_DEPTHWISECONV_FALLBACK
  17. #endif
  18. #endif
  19. #include <functional>
  20. #include "fixedpoint/fixedpoint.h"
  21. #include "tensorflow/lite/kernels/internal/cppmath.h"
  22. #include "tensorflow/lite/kernels/internal/optimized/neon_check.h"
  23. #include "tensorflow/lite/kernels/internal/types.h"
  24. namespace tflite {
  25. constexpr int kReverseShift = -1;
  26. inline void GetActivationMinMax(FusedActivationFunctionType ac,
  27. float* output_activation_min,
  28. float* output_activation_max) {
  29. switch (ac) {
  30. case FusedActivationFunctionType::kNone:
  31. *output_activation_min = std::numeric_limits<float>::lowest();
  32. *output_activation_max = std::numeric_limits<float>::max();
  33. break;
  34. case FusedActivationFunctionType::kRelu:
  35. *output_activation_min = 0.f;
  36. *output_activation_max = std::numeric_limits<float>::max();
  37. break;
  38. case FusedActivationFunctionType::kRelu1:
  39. *output_activation_min = -1.f;
  40. *output_activation_max = 1.f;
  41. break;
  42. case FusedActivationFunctionType::kRelu6:
  43. *output_activation_min = 0.f;
  44. *output_activation_max = 6.f;
  45. break;
  46. }
  47. }
  48. inline float ActivationFunctionWithMinMax(float x, float output_activation_min,
  49. float output_activation_max) {
  50. return std::min(std::max(x, output_activation_min), output_activation_max);
  51. }
  52. // Legacy function, left for compatibility only.
  53. template <FusedActivationFunctionType Ac>
  54. float ActivationFunction(float x) {
  55. float output_activation_min, output_activation_max;
  56. GetActivationMinMax(Ac, &output_activation_min, &output_activation_max);
  57. return ActivationFunctionWithMinMax(x, output_activation_min,
  58. output_activation_max);
  59. }
  60. inline void BiasAndClamp(float clamp_min, float clamp_max, int bias_size,
  61. const float* bias_data, int array_size,
  62. float* array_data) {
  63. // Note: see b/132215220: in May 2019 we thought it would be OK to replace
  64. // this with the Eigen one-liner:
  65. // return (array.colwise() + bias).cwiseMin(clamp_max).cwiseMin(clamp_max).
  66. // This turned out to severely regress performance: +4ms (i.e. 8%) on
  67. // MobileNet v2 / 1.0 / 224. So we keep custom NEON code for now.
  68. TFLITE_DCHECK_EQ((array_size % bias_size), 0);
  69. #ifdef USE_NEON
  70. float* array_ptr = array_data;
  71. float* array_end_ptr = array_ptr + array_size;
  72. const auto clamp_min_vec = vdupq_n_f32(clamp_min);
  73. const auto clamp_max_vec = vdupq_n_f32(clamp_max);
  74. for (; array_ptr != array_end_ptr; array_ptr += bias_size) {
  75. int i = 0;
  76. for (; i <= bias_size - 16; i += 16) {
  77. auto b0 = vld1q_f32(bias_data + i);
  78. auto b1 = vld1q_f32(bias_data + i + 4);
  79. auto b2 = vld1q_f32(bias_data + i + 8);
  80. auto b3 = vld1q_f32(bias_data + i + 12);
  81. auto a0 = vld1q_f32(array_ptr + i);
  82. auto a1 = vld1q_f32(array_ptr + i + 4);
  83. auto a2 = vld1q_f32(array_ptr + i + 8);
  84. auto a3 = vld1q_f32(array_ptr + i + 12);
  85. auto x0 = vaddq_f32(a0, b0);
  86. auto x1 = vaddq_f32(a1, b1);
  87. auto x2 = vaddq_f32(a2, b2);
  88. auto x3 = vaddq_f32(a3, b3);
  89. x0 = vmaxq_f32(clamp_min_vec, x0);
  90. x1 = vmaxq_f32(clamp_min_vec, x1);
  91. x2 = vmaxq_f32(clamp_min_vec, x2);
  92. x3 = vmaxq_f32(clamp_min_vec, x3);
  93. x0 = vminq_f32(clamp_max_vec, x0);
  94. x1 = vminq_f32(clamp_max_vec, x1);
  95. x2 = vminq_f32(clamp_max_vec, x2);
  96. x3 = vminq_f32(clamp_max_vec, x3);
  97. vst1q_f32(array_ptr + i, x0);
  98. vst1q_f32(array_ptr + i + 4, x1);
  99. vst1q_f32(array_ptr + i + 8, x2);
  100. vst1q_f32(array_ptr + i + 12, x3);
  101. }
  102. for (; i <= bias_size - 4; i += 4) {
  103. auto b = vld1q_f32(bias_data + i);
  104. auto a = vld1q_f32(array_ptr + i);
  105. auto x = vaddq_f32(a, b);
  106. x = vmaxq_f32(clamp_min_vec, x);
  107. x = vminq_f32(clamp_max_vec, x);
  108. vst1q_f32(array_ptr + i, x);
  109. }
  110. for (; i < bias_size; i++) {
  111. array_ptr[i] = ActivationFunctionWithMinMax(array_ptr[i] + bias_data[i],
  112. clamp_min, clamp_max);
  113. }
  114. }
  115. #else // not NEON
  116. for (int array_offset = 0; array_offset < array_size;
  117. array_offset += bias_size) {
  118. for (int i = 0; i < bias_size; i++) {
  119. array_data[array_offset + i] = ActivationFunctionWithMinMax(
  120. array_data[array_offset + i] + bias_data[i], clamp_min, clamp_max);
  121. }
  122. }
  123. #endif
  124. }
  125. inline int32 MultiplyByQuantizedMultiplierSmallerThanOneExp(
  126. int32 x, int32 quantized_multiplier, int left_shift) {
  127. using gemmlowp::RoundingDivideByPOT;
  128. using gemmlowp::SaturatingRoundingDoublingHighMul;
  129. return RoundingDivideByPOT(
  130. SaturatingRoundingDoublingHighMul(x, quantized_multiplier), -left_shift);
  131. }
  132. inline int32 MultiplyByQuantizedMultiplierGreaterThanOne(
  133. int32 x, int32 quantized_multiplier, int left_shift) {
  134. using gemmlowp::SaturatingRoundingDoublingHighMul;
  135. return SaturatingRoundingDoublingHighMul(x * (1 << left_shift),
  136. quantized_multiplier);
  137. }
  138. inline int32 MultiplyByQuantizedMultiplier(int32 x, int32 quantized_multiplier,
  139. int shift) {
  140. using gemmlowp::RoundingDivideByPOT;
  141. using gemmlowp::SaturatingRoundingDoublingHighMul;
  142. int left_shift = shift > 0 ? shift : 0;
  143. int right_shift = shift > 0 ? 0 : -shift;
  144. return RoundingDivideByPOT(SaturatingRoundingDoublingHighMul(
  145. x * (1 << left_shift), quantized_multiplier),
  146. right_shift);
  147. }
  148. inline int32 MultiplyByQuantizedMultiplier(int64_t x,
  149. int32 quantized_multiplier,
  150. int shift) {
  151. // Inputs:
  152. // - quantized_multiplier has fixed point at bit 31
  153. // - shift is -31 to +7 (negative for right shift)
  154. //
  155. // Assumptions: The following input ranges are assumed
  156. // - quantize_scale>=0 (the usual range is (1<<30) to (1>>31)-1)
  157. // - scaling is chosen so final scaled result fits in int32
  158. // - input x is in the range -(1<<47) <= x < (1<<47)
  159. assert(quantized_multiplier >= 0);
  160. assert(shift >= -31 && shift < 8);
  161. int32_t reduced_multiplier = (quantized_multiplier + (1 << 15)) >> 16;
  162. int total_shift = 15 - shift;
  163. x = (x * (int64_t)reduced_multiplier) + ((int64_t)1 << (total_shift - 1));
  164. int32_t result = x >> total_shift;
  165. return result;
  166. }
  167. template <typename T>
  168. int CountLeadingZeros(T integer_input) {
  169. static_assert(std::is_unsigned<T>::value,
  170. "Only unsigned integer types handled.");
  171. #if defined(__GNUC__)
  172. return integer_input ? __builtin_clz(integer_input)
  173. : std::numeric_limits<T>::digits;
  174. #else
  175. if (integer_input == 0) {
  176. return std::numeric_limits<T>::digits;
  177. }
  178. const T one_in_leading_positive = static_cast<T>(1)
  179. << (std::numeric_limits<T>::digits - 1);
  180. int leading_zeros = 0;
  181. while (integer_input < one_in_leading_positive) {
  182. integer_input <<= 1;
  183. ++leading_zeros;
  184. }
  185. return leading_zeros;
  186. #endif
  187. }
  188. template <typename T>
  189. inline int CountLeadingSignBits(T integer_input) {
  190. static_assert(std::is_signed<T>::value, "Only signed integer types handled.");
  191. #if defined(__GNUC__) && !defined(__clang__)
  192. return integer_input ? __builtin_clrsb(integer_input)
  193. : std::numeric_limits<T>::digits;
  194. #else
  195. using U = typename std::make_unsigned<T>::type;
  196. return integer_input >= 0
  197. ? CountLeadingZeros(static_cast<U>(integer_input)) - 1
  198. : integer_input != std::numeric_limits<T>::min()
  199. ? CountLeadingZeros(2 * static_cast<U>(-integer_input) - 1)
  200. : 0;
  201. #endif
  202. }
  203. // Use "count leading zeros" helper functions to do a fast Floor(log_2(x)).
  204. template <typename Integer>
  205. inline Integer FloorLog2(Integer n) {
  206. static_assert(std::is_integral<Integer>::value, "");
  207. static_assert(std::is_signed<Integer>::value, "");
  208. static_assert(sizeof(Integer) == 4 || sizeof(Integer) == 8, "");
  209. TFLITE_CHECK_GT(n, 0);
  210. if (sizeof(Integer) == 4) {
  211. return 30 - CountLeadingSignBits(n);
  212. } else {
  213. return 62 - CountLeadingSignBits(n);
  214. }
  215. }
  216. // generate INT16 LUT for function(), e.g., table exp(x) and 1/(1+x) used in
  217. // softmax
  218. inline void gen_lut(const std::function<double(double)>& func, double min,
  219. double max, int16_t* table, const int num) {
  220. // size of table should equal to num + 1
  221. // last element only for slope calculation
  222. double step = (max - min) / (num - 1);
  223. double half_step = step / 2.0;
  224. for (int i = 0; i < num - 1; i++) {
  225. double sample_val = TfLiteRound(func(min + i * step) * 32768.0);
  226. double midpoint_interp_val =
  227. TfLiteRound((func(min + (i + 1) * step) * 32768.0 +
  228. TfLiteRound(func(min + i * step) * 32768.0)) /
  229. 2.0);
  230. double midpoint_val =
  231. TfLiteRound(func(min + i * step + half_step) * 32768.0);
  232. double midpoint_err = midpoint_interp_val - midpoint_val;
  233. double bias = TfLiteRound(midpoint_err / 2.0);
  234. table[i] = std::min(std::max(sample_val - bias, -32768.0), 32767.0);
  235. }
  236. table[num - 1] =
  237. std::min(std::max(TfLiteRound(func(max) * 32768.0), -32768.0), 32767.0);
  238. }
  239. // int16 func table lookup, e.g., lookup exp() and 1/(1+x) used in softmax
  240. inline int16_t generic_int16_table_lookup(int16_t value, const int16_t* lut) {
  241. // 512 base value, lut[513] only for calculate slope
  242. uint16_t index = static_cast<uint16_t>(256 + (value >> 7));
  243. assert(index < 512 && "LUT index out of range.");
  244. int16_t offset = value & 0x7f;
  245. // base and slope are Q0.15
  246. int16_t base = lut[index];
  247. int16_t slope = lut[index + 1] - lut[index];
  248. // Q0.15 * Q0.7 = Q0.22
  249. // Round and convert from Q0.22 to Q0.15
  250. int32_t delta = (static_cast<int32_t>(slope) * offset + 64) >> 7;
  251. // Q0.15 + Q0.15
  252. return base + delta;
  253. }
  254. // Table of sigmoid(i/24) at 0.16 format - 256 elements.
  255. // We use combined sigmoid and tanh look-up table, since
  256. // tanh(x) = 2*sigmoid(2*x) -1.
  257. // Both functions are symmetric, so the LUT table is only needed
  258. // for the absolute value of the input.
  259. static const uint16_t sigmoid_table_uint16[256] = {
  260. 32768, 33451, 34133, 34813, 35493, 36169, 36843, 37513, 38180, 38841, 39498,
  261. 40149, 40794, 41432, 42064, 42688, 43304, 43912, 44511, 45102, 45683, 46255,
  262. 46817, 47369, 47911, 48443, 48964, 49475, 49975, 50464, 50942, 51409, 51865,
  263. 52311, 52745, 53169, 53581, 53983, 54374, 54755, 55125, 55485, 55834, 56174,
  264. 56503, 56823, 57133, 57433, 57724, 58007, 58280, 58544, 58800, 59048, 59288,
  265. 59519, 59743, 59959, 60168, 60370, 60565, 60753, 60935, 61110, 61279, 61441,
  266. 61599, 61750, 61896, 62036, 62172, 62302, 62428, 62549, 62666, 62778, 62886,
  267. 62990, 63090, 63186, 63279, 63368, 63454, 63536, 63615, 63691, 63765, 63835,
  268. 63903, 63968, 64030, 64090, 64148, 64204, 64257, 64308, 64357, 64405, 64450,
  269. 64494, 64536, 64576, 64614, 64652, 64687, 64721, 64754, 64786, 64816, 64845,
  270. 64873, 64900, 64926, 64950, 64974, 64997, 65019, 65039, 65060, 65079, 65097,
  271. 65115, 65132, 65149, 65164, 65179, 65194, 65208, 65221, 65234, 65246, 65258,
  272. 65269, 65280, 65291, 65301, 65310, 65319, 65328, 65337, 65345, 65352, 65360,
  273. 65367, 65374, 65381, 65387, 65393, 65399, 65404, 65410, 65415, 65420, 65425,
  274. 65429, 65433, 65438, 65442, 65445, 65449, 65453, 65456, 65459, 65462, 65465,
  275. 65468, 65471, 65474, 65476, 65479, 65481, 65483, 65485, 65488, 65489, 65491,
  276. 65493, 65495, 65497, 65498, 65500, 65501, 65503, 65504, 65505, 65507, 65508,
  277. 65509, 65510, 65511, 65512, 65513, 65514, 65515, 65516, 65517, 65517, 65518,
  278. 65519, 65520, 65520, 65521, 65522, 65522, 65523, 65523, 65524, 65524, 65525,
  279. 65525, 65526, 65526, 65526, 65527, 65527, 65528, 65528, 65528, 65529, 65529,
  280. 65529, 65529, 65530, 65530, 65530, 65530, 65531, 65531, 65531, 65531, 65531,
  281. 65532, 65532, 65532, 65532, 65532, 65532, 65533, 65533, 65533, 65533, 65533,
  282. 65533, 65533, 65533, 65534, 65534, 65534, 65534, 65534, 65534, 65534, 65534,
  283. 65534, 65534, 65535};
  284. // TODO(b/77858996): Add these to gemmlowp.
  285. template <typename IntegerType>
  286. IntegerType SaturatingAddNonGemmlowp(IntegerType a, IntegerType b) {
  287. static_assert(std::is_same<IntegerType, void>::value, "unimplemented");
  288. return a;
  289. }
  290. template <>
  291. inline std::int32_t SaturatingAddNonGemmlowp(std::int32_t a, std::int32_t b) {
  292. std::int64_t a64 = a;
  293. std::int64_t b64 = b;
  294. std::int64_t sum = a64 + b64;
  295. return static_cast<std::int32_t>(std::min(
  296. static_cast<std::int64_t>(std::numeric_limits<std::int32_t>::max()),
  297. std::max(
  298. static_cast<std::int64_t>(std::numeric_limits<std::int32_t>::min()),
  299. sum)));
  300. }
  301. template <typename tRawType, int tIntegerBits>
  302. gemmlowp::FixedPoint<tRawType, tIntegerBits> SaturatingAddNonGemmlowp(
  303. gemmlowp::FixedPoint<tRawType, tIntegerBits> a,
  304. gemmlowp::FixedPoint<tRawType, tIntegerBits> b) {
  305. return gemmlowp::FixedPoint<tRawType, tIntegerBits>::FromRaw(
  306. SaturatingAddNonGemmlowp(a.raw(), b.raw()));
  307. }
  308. template <typename IntegerType>
  309. IntegerType SaturatingSub(IntegerType a, IntegerType b) {
  310. static_assert(std::is_same<IntegerType, void>::value, "unimplemented");
  311. return a;
  312. }
  313. template <>
  314. inline std::int16_t SaturatingSub(std::int16_t a, std::int16_t b) {
  315. std::int32_t a32 = a;
  316. std::int32_t b32 = b;
  317. std::int32_t diff = a32 - b32;
  318. return static_cast<std::int16_t>(
  319. std::min(static_cast<int32_t>(32767),
  320. std::max(static_cast<int32_t>(-32768), diff)));
  321. }
  322. template <>
  323. inline std::int32_t SaturatingSub(std::int32_t a, std::int32_t b) {
  324. std::int64_t a64 = a;
  325. std::int64_t b64 = b;
  326. std::int64_t diff = a64 - b64;
  327. return static_cast<std::int32_t>(std::min(
  328. static_cast<std::int64_t>(std::numeric_limits<std::int32_t>::max()),
  329. std::max(
  330. static_cast<std::int64_t>(std::numeric_limits<std::int32_t>::min()),
  331. diff)));
  332. }
  333. template <typename tRawType, int tIntegerBits>
  334. gemmlowp::FixedPoint<tRawType, tIntegerBits> SaturatingSub(
  335. gemmlowp::FixedPoint<tRawType, tIntegerBits> a,
  336. gemmlowp::FixedPoint<tRawType, tIntegerBits> b) {
  337. return gemmlowp::FixedPoint<tRawType, tIntegerBits>::FromRaw(
  338. SaturatingSub(a.raw(), b.raw()));
  339. }
  340. // End section to be moved to gemmlowp.
  341. template <typename IntegerType>
  342. IntegerType SaturatingRoundingMultiplyByPOTParam(IntegerType x, int exponent) {
  343. if (exponent == 0) {
  344. return x;
  345. }
  346. using ScalarIntegerType =
  347. typename gemmlowp::FixedPointRawTypeTraits<IntegerType>::ScalarRawType;
  348. const IntegerType min =
  349. gemmlowp::Dup<IntegerType>(std::numeric_limits<ScalarIntegerType>::min());
  350. const IntegerType max =
  351. gemmlowp::Dup<IntegerType>(std::numeric_limits<ScalarIntegerType>::max());
  352. const int ScalarIntegerTypeBits = 8 * sizeof(ScalarIntegerType);
  353. const std::int32_t threshold =
  354. ((1 << (ScalarIntegerTypeBits - 1 - exponent)) - 1);
  355. const IntegerType positive_mask =
  356. gemmlowp::MaskIfGreaterThan(x, gemmlowp::Dup<IntegerType>(threshold));
  357. const IntegerType negative_mask =
  358. gemmlowp::MaskIfLessThan(x, gemmlowp::Dup<IntegerType>(-threshold));
  359. IntegerType result = gemmlowp::ShiftLeft(x, exponent);
  360. result = gemmlowp::SelectUsingMask(positive_mask, max, result);
  361. result = gemmlowp::SelectUsingMask(negative_mask, min, result);
  362. return result;
  363. }
  364. // If we want to leave IntegerBits fixed, then multiplication
  365. // by a power of two has to be saturating/rounding, not exact anymore.
  366. template <typename tRawType, int tIntegerBits>
  367. gemmlowp::FixedPoint<tRawType, tIntegerBits>
  368. SaturatingRoundingMultiplyByPOTParam(
  369. gemmlowp::FixedPoint<tRawType, tIntegerBits> a, int exponent) {
  370. return gemmlowp::FixedPoint<tRawType, tIntegerBits>::FromRaw(
  371. SaturatingRoundingMultiplyByPOTParam(a.raw(), exponent));
  372. }
  373. // Minimum output bits to accommodate log of maximum input range. It actually
  374. // does not matter if one considers, say, [-64,64] or [-64,64).
  375. //
  376. // For example, run this through Octave:
  377. // [0:127; ...
  378. // ceil(log(abs( log(2.^(0:127))+1 ))/log(2)); ...
  379. // ceil(log(abs( log(2.^(0:127))+1 ))/log(2))]
  380. constexpr int min_log_x_output_bits(int input_bits) {
  381. return input_bits > 90
  382. ? 7
  383. : input_bits > 44
  384. ? 6
  385. : input_bits > 21
  386. ? 5
  387. : input_bits > 10
  388. ? 4
  389. : input_bits > 4 ? 3 : input_bits > 1 ? 2 : 1;
  390. }
  391. // Although currently the name of this function says that it cannot handle
  392. // values less than 1, in practice it can handle as low as 1/x_max, where
  393. // x_max is the largest representable input. In other words, the output range
  394. // is symmetric.
  395. template <int OutputIntegerBits, int InputIntegerBits>
  396. inline gemmlowp::FixedPoint<int32, OutputIntegerBits>
  397. log_x_for_x_greater_than_or_equal_to_1_impl(
  398. gemmlowp::FixedPoint<int32, InputIntegerBits> input_val) {
  399. // assert(__builtin_clz(0u) >= std::numeric_limits<uint32>::digits - 1);
  400. // assert(__builtin_clz(0u) <= std::numeric_limits<uint32>::digits);
  401. using FixedPoint0 = gemmlowp::FixedPoint<int32, 0>;
  402. // The reason for accumulating the result with an extra bit of headroom is
  403. // that z_pow_2_adj * log_2 might be saturated, and adding num_scaled *
  404. // recip_denom will otherwise introduce an error.
  405. static constexpr int kAccumIntegerBits = OutputIntegerBits + 1;
  406. using FixedPointAccum = gemmlowp::FixedPoint<int32, kAccumIntegerBits>;
  407. const FixedPoint0 log_2 = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  408. FixedPoint0, 1488522236, std::log(2.0));
  409. const FixedPoint0 sqrt_sqrt_half = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  410. FixedPoint0, 1805811301, std::sqrt(std::sqrt(0.5)));
  411. const FixedPoint0 sqrt_half = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  412. FixedPoint0, 1518500250, std::sqrt(0.5));
  413. const FixedPoint0 one_quarter =
  414. GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(FixedPoint0, 536870912, 1.0 / 4.0);
  415. const FixedPoint0 alpha_n = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  416. FixedPoint0, 117049297, 11.0 / 240.0 * std::sqrt(std::sqrt(2.0)));
  417. const FixedPoint0 alpha_d = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  418. FixedPoint0, 127690142, 1.0 / 20.0 * std::sqrt(std::sqrt(2.0)));
  419. const FixedPoint0 alpha_i = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  420. FixedPoint0, 1057819769,
  421. 2.0 / std::sqrt(std::sqrt(2.0)) - std::sqrt(std::sqrt(2.0)));
  422. const FixedPoint0 alpha_f = GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(
  423. FixedPoint0, 638450708, 1.0 / 4.0 * std::sqrt(std::sqrt(2.0)));
  424. const FixedPointAccum shifted_quarter =
  425. gemmlowp::Rescale<kAccumIntegerBits>(one_quarter);
  426. // Reinterpret the input value as Q0.31, because we will figure out the
  427. // required shift "ourselves" instead of using, say, Rescale.
  428. FixedPoint0 z_a = FixedPoint0::FromRaw(input_val.raw());
  429. // z_a_pow_2 = input_integer_bits - z_a_headroom;
  430. int z_a_headroom_plus_1 = CountLeadingZeros(static_cast<uint32>(z_a.raw()));
  431. FixedPoint0 r_a_tmp =
  432. SaturatingRoundingMultiplyByPOTParam(z_a, (z_a_headroom_plus_1 - 1));
  433. const int32 r_a_raw =
  434. SaturatingRoundingMultiplyByPOTParam((r_a_tmp * sqrt_half).raw(), 1);
  435. // z_pow_2_adj = max(z_pow_2_a - 0.75, z_pow_2_b - 0.25);
  436. // z_pow_2_adj = max(InputIntegerBits - z_a_headroom_plus_1 + 0.25,
  437. // InputIntegerBits - z_b_headroom - 0.25);
  438. const FixedPointAccum z_a_pow_2_adj = SaturatingAddNonGemmlowp(
  439. FixedPointAccum::FromRaw(SaturatingRoundingMultiplyByPOTParam(
  440. InputIntegerBits - z_a_headroom_plus_1, 31 - kAccumIntegerBits)),
  441. shifted_quarter);
  442. // z_b is treated like z_a, but premultiplying by sqrt(0.5).
  443. FixedPoint0 z_b = z_a * sqrt_half;
  444. int z_b_headroom = CountLeadingZeros(static_cast<uint32>(z_b.raw())) - 1;
  445. const int32 r_b_raw =
  446. SaturatingRoundingMultiplyByPOTParam(z_a.raw(), z_b_headroom);
  447. const FixedPointAccum z_b_pow_2_adj = SaturatingSub(
  448. FixedPointAccum::FromRaw(SaturatingRoundingMultiplyByPOTParam(
  449. InputIntegerBits - z_b_headroom, 31 - kAccumIntegerBits)),
  450. shifted_quarter);
  451. const FixedPoint0 r = FixedPoint0::FromRaw(std::min(r_a_raw, r_b_raw));
  452. const FixedPointAccum z_pow_2_adj = FixedPointAccum::FromRaw(
  453. std::max(z_a_pow_2_adj.raw(), z_b_pow_2_adj.raw()));
  454. const FixedPoint0 p = gemmlowp::RoundingHalfSum(r, sqrt_sqrt_half);
  455. FixedPoint0 q = r - sqrt_sqrt_half;
  456. q = q + q;
  457. const FixedPoint0 common_sq = q * q;
  458. const FixedPoint0 num = q * r + q * common_sq * alpha_n;
  459. const FixedPoint0 denom_minus_one_0 =
  460. p * (alpha_i + q + alpha_d * common_sq) + alpha_f * q;
  461. const FixedPoint0 recip_denom =
  462. one_over_one_plus_x_for_x_in_0_1(denom_minus_one_0);
  463. const FixedPointAccum num_scaled = gemmlowp::Rescale<kAccumIntegerBits>(num);
  464. return gemmlowp::Rescale<OutputIntegerBits>(z_pow_2_adj * log_2 +
  465. num_scaled * recip_denom);
  466. }
  467. template <int OutputIntegerBits, int InputIntegerBits>
  468. inline gemmlowp::FixedPoint<int32, OutputIntegerBits>
  469. log_x_for_x_greater_than_or_equal_to_1(
  470. gemmlowp::FixedPoint<int32, InputIntegerBits> input_val) {
  471. static_assert(
  472. OutputIntegerBits >= min_log_x_output_bits(InputIntegerBits),
  473. "Output integer bits must be sufficient to accommodate logs of inputs.");
  474. return log_x_for_x_greater_than_or_equal_to_1_impl<OutputIntegerBits,
  475. InputIntegerBits>(
  476. input_val);
  477. }
  478. inline int32 GetReciprocal(int32 x, int x_integer_digits,
  479. int* num_bits_over_unit) {
  480. int headroom_plus_one = CountLeadingZeros(static_cast<uint32>(x));
  481. // This is the number of bits to the left of the binary point above 1.0.
  482. // Consider x=1.25. In that case shifted_scale=0.8 and
  483. // no later adjustment will be needed.
  484. *num_bits_over_unit = x_integer_digits - headroom_plus_one;
  485. const int32 shifted_sum_minus_one =
  486. static_cast<int32>((static_cast<uint32>(x) << headroom_plus_one) -
  487. (static_cast<uint32>(1) << 31));
  488. gemmlowp::FixedPoint<int32, 0> shifted_scale =
  489. gemmlowp::one_over_one_plus_x_for_x_in_0_1(
  490. gemmlowp::FixedPoint<int32, 0>::FromRaw(shifted_sum_minus_one));
  491. return shifted_scale.raw();
  492. }
  493. inline void GetInvSqrtQuantizedMultiplierExp(int32 input, int reverse_shift,
  494. int32* output_inv_sqrt,
  495. int* output_shift) {
  496. TFLITE_DCHECK_GE(input, 0);
  497. if (input <= 1) {
  498. // Handle the input value 1 separately to avoid overflow in that case
  499. // in the general computation below (b/143972021). Also handle 0 as if it
  500. // were a 1. 0 is an invalid input here (divide by zero) and 1 is a valid
  501. // but rare/unrealistic input value. We can expect both to occur in some
  502. // incompletely trained models, but probably not in fully trained models.
  503. *output_inv_sqrt = std::numeric_limits<std::int32_t>::max();
  504. *output_shift = 0;
  505. return;
  506. }
  507. TFLITE_DCHECK_GT(input, 1);
  508. *output_shift = 11;
  509. while (input >= (1 << 29)) {
  510. input /= 4;
  511. ++*output_shift;
  512. }
  513. const unsigned max_left_shift_bits =
  514. CountLeadingZeros(static_cast<uint32>(input)) - 1;
  515. const unsigned max_left_shift_bit_pairs = max_left_shift_bits / 2;
  516. const unsigned left_shift_bit_pairs = max_left_shift_bit_pairs - 1;
  517. *output_shift -= left_shift_bit_pairs;
  518. input <<= 2 * left_shift_bit_pairs;
  519. TFLITE_DCHECK_GE(input, (1 << 27));
  520. TFLITE_DCHECK_LT(input, (1 << 29));
  521. using gemmlowp::FixedPoint;
  522. using gemmlowp::Rescale;
  523. using gemmlowp::SaturatingRoundingMultiplyByPOT;
  524. // Using 3 integer bits gives us enough room for the internal arithmetic in
  525. // this Newton-Raphson iteration.
  526. using F3 = FixedPoint<int32, 3>;
  527. using F0 = FixedPoint<int32, 0>;
  528. const F3 fixedpoint_input = F3::FromRaw(input >> 1);
  529. const F3 fixedpoint_half_input =
  530. SaturatingRoundingMultiplyByPOT<-1>(fixedpoint_input);
  531. const F3 fixedpoint_half_three =
  532. GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(F3, (1 << 28) + (1 << 27), 1.5);
  533. // Newton-Raphson iteration
  534. // Naive unoptimized starting guess: x = 1
  535. F3 x = F3::One();
  536. // Naive unoptimized number of iterations: 5
  537. for (int i = 0; i < 5; i++) {
  538. const F3 x3 = Rescale<3>(x * x * x);
  539. x = Rescale<3>(fixedpoint_half_three * x - fixedpoint_half_input * x3);
  540. }
  541. const F0 fixedpoint_half_sqrt_2 =
  542. GEMMLOWP_CHECKED_FIXEDPOINT_CONSTANT(F0, 1518500250, std::sqrt(2.) / 2.);
  543. x = x * fixedpoint_half_sqrt_2;
  544. *output_inv_sqrt = x.raw();
  545. if (*output_shift < 0) {
  546. *output_inv_sqrt <<= -*output_shift;
  547. *output_shift = 0;
  548. }
  549. // Convert right shift (right is positive) to left shift.
  550. *output_shift *= reverse_shift;
  551. }
  552. // DO NOT USE THIS STRUCT FOR NEW FUNCTIONALITY BEYOND IMPLEMENTING
  553. // BROADCASTING.
  554. //
  555. // NdArrayDesc<N> describes the shape and memory layout of an N-dimensional
  556. // rectangular array of numbers.
  557. //
  558. // NdArrayDesc<N> is basically identical to Dims<N> defined in types.h.
  559. // However, as Dims<N> is to be deprecated, this class exists as an adaptor
  560. // to enable simple unoptimized implementations of element-wise broadcasting
  561. // operations.
  562. template <int N>
  563. struct NdArrayDesc {
  564. // The "extent" of each dimension. Indices along dimension d must be in the
  565. // half-open interval [0, extents[d]).
  566. int extents[N];
  567. // The number of *elements* (not bytes) between consecutive indices of each
  568. // dimension.
  569. int strides[N];
  570. };
  571. // DO NOT USE THIS FUNCTION FOR NEW FUNCTIONALITY BEYOND IMPLEMENTING
  572. // BROADCASTING.
  573. //
  574. // Same as Offset(), except takes as NdArrayDesc<N> instead of Dims<N>.
  575. inline int SubscriptToIndex(const NdArrayDesc<4>& desc, int i0, int i1, int i2,
  576. int i3) {
  577. TFLITE_DCHECK(i0 >= 0 && i0 < desc.extents[0]);
  578. TFLITE_DCHECK(i1 >= 0 && i1 < desc.extents[1]);
  579. TFLITE_DCHECK(i2 >= 0 && i2 < desc.extents[2]);
  580. TFLITE_DCHECK(i3 >= 0 && i3 < desc.extents[3]);
  581. return i0 * desc.strides[0] + i1 * desc.strides[1] + i2 * desc.strides[2] +
  582. i3 * desc.strides[3];
  583. }
  584. inline int SubscriptToIndex(const NdArrayDesc<5>& desc, int indexes[5]) {
  585. return indexes[0] * desc.strides[0] + indexes[1] * desc.strides[1] +
  586. indexes[2] * desc.strides[2] + indexes[3] * desc.strides[3] +
  587. indexes[4] * desc.strides[4];
  588. }
  589. // Given the dimensions of the operands for an element-wise binary broadcast,
  590. // adjusts them so that they can be directly iterated over with simple loops.
  591. // Returns the adjusted dims as instances of NdArrayDesc in 'desc0_out' and
  592. // 'desc1_out'. 'desc0_out' and 'desc1_out' cannot be nullptr.
  593. //
  594. // This function assumes that the two input shapes are compatible up to
  595. // broadcasting and the shorter one has already been prepended with 1s to be the
  596. // same length. E.g., if shape0 is (1, 16, 16, 64) and shape1 is (1, 64),
  597. // shape1 must already have been prepended to be (1, 1, 1, 64). Recall that
  598. // Dims<N> refer to shapes in reverse order. In this case, input0_dims will be
  599. // (64, 16, 16, 1) and input1_dims will be (64, 1, 1, 1).
  600. //
  601. // When two shapes are compatible up to broadcasting, for each dimension d,
  602. // the input extents are either equal, or one of them is 1.
  603. //
  604. // This function performs the following for each dimension d:
  605. // - If the extents are equal, then do nothing since the loop that walks over
  606. // both of the input arrays is correct.
  607. // - Otherwise, one (and only one) of the extents must be 1. Say extent0 is 1
  608. // and extent1 is e1. Then set extent0 to e1 and stride0 *to 0*. This allows
  609. // array0 to be referenced *at any index* in dimension d and still access the
  610. // same slice.
  611. template <int N>
  612. inline void NdArrayDescsForElementwiseBroadcast(const Dims<N>& input0_dims,
  613. const Dims<N>& input1_dims,
  614. NdArrayDesc<N>* desc0_out,
  615. NdArrayDesc<N>* desc1_out) {
  616. TFLITE_DCHECK(desc0_out != nullptr);
  617. TFLITE_DCHECK(desc1_out != nullptr);
  618. // Copy dims to desc.
  619. for (int i = 0; i < N; ++i) {
  620. desc0_out->extents[i] = input0_dims.sizes[i];
  621. desc0_out->strides[i] = input0_dims.strides[i];
  622. desc1_out->extents[i] = input1_dims.sizes[i];
  623. desc1_out->strides[i] = input1_dims.strides[i];
  624. }
  625. // Walk over each dimension. If the extents are equal do nothing.
  626. // Otherwise, set the desc with extent 1 to have extent equal to the other and
  627. // stride 0.
  628. for (int i = 0; i < N; ++i) {
  629. const int extent0 = ArraySize(input0_dims, i);
  630. const int extent1 = ArraySize(input1_dims, i);
  631. if (extent0 != extent1) {
  632. if (extent0 == 1) {
  633. desc0_out->strides[i] = 0;
  634. desc0_out->extents[i] = extent1;
  635. } else {
  636. TFLITE_DCHECK_EQ(extent1, 1);
  637. desc1_out->strides[i] = 0;
  638. desc1_out->extents[i] = extent0;
  639. }
  640. }
  641. }
  642. }
  643. // Copies dims to desc, calculating strides.
  644. template <int N>
  645. inline void CopyDimsToDesc(const RuntimeShape& input_shape,
  646. NdArrayDesc<N>* desc_out) {
  647. int desc_stride = 1;
  648. for (int i = N - 1; i >= 0; --i) {
  649. desc_out->extents[i] = input_shape.Dims(i);
  650. desc_out->strides[i] = desc_stride;
  651. desc_stride *= input_shape.Dims(i);
  652. }
  653. }
  654. template <int N>
  655. inline void NdArrayDescsForElementwiseBroadcast(
  656. const RuntimeShape& input0_shape, const RuntimeShape& input1_shape,
  657. NdArrayDesc<N>* desc0_out, NdArrayDesc<N>* desc1_out) {
  658. TFLITE_DCHECK(desc0_out != nullptr);
  659. TFLITE_DCHECK(desc1_out != nullptr);
  660. auto extended_input0_shape = RuntimeShape::ExtendedShape(N, input0_shape);
  661. auto extended_input1_shape = RuntimeShape::ExtendedShape(N, input1_shape);
  662. // Copy dims to desc, calculating strides.
  663. CopyDimsToDesc<N>(extended_input0_shape, desc0_out);
  664. CopyDimsToDesc<N>(extended_input1_shape, desc1_out);
  665. // Walk over each dimension. If the extents are equal do nothing.
  666. // Otherwise, set the desc with extent 1 to have extent equal to the other and
  667. // stride 0.
  668. for (int i = 0; i < N; ++i) {
  669. const int extent0 = extended_input0_shape.Dims(i);
  670. const int extent1 = extended_input1_shape.Dims(i);
  671. if (extent0 != extent1) {
  672. if (extent0 == 1) {
  673. desc0_out->strides[i] = 0;
  674. desc0_out->extents[i] = extent1;
  675. } else {
  676. TFLITE_DCHECK_EQ(extent1, 1);
  677. desc1_out->strides[i] = 0;
  678. desc1_out->extents[i] = extent0;
  679. }
  680. }
  681. }
  682. }
  683. template <int N>
  684. inline void NdArrayDescsForElementwiseBroadcast(
  685. const RuntimeShape& input0_shape, const RuntimeShape& input1_shape,
  686. const RuntimeShape& input2_shape, NdArrayDesc<N>* desc0_out,
  687. NdArrayDesc<N>* desc1_out, NdArrayDesc<N>* desc2_out) {
  688. TFLITE_DCHECK(desc0_out != nullptr);
  689. TFLITE_DCHECK(desc1_out != nullptr);
  690. TFLITE_DCHECK(desc2_out != nullptr);
  691. auto extended_input0_shape = RuntimeShape::ExtendedShape(N, input0_shape);
  692. auto extended_input1_shape = RuntimeShape::ExtendedShape(N, input1_shape);
  693. auto extended_input2_shape = RuntimeShape::ExtendedShape(N, input2_shape);
  694. // Copy dims to desc, calculating strides.
  695. CopyDimsToDesc<N>(extended_input0_shape, desc0_out);
  696. CopyDimsToDesc<N>(extended_input1_shape, desc1_out);
  697. CopyDimsToDesc<N>(extended_input2_shape, desc2_out);
  698. // Walk over each dimension. If the extents are equal do nothing.
  699. // Otherwise, set the desc with extent 1 to have extent equal to the other and
  700. // stride 0.
  701. for (int i = 0; i < N; ++i) {
  702. const int extent0 = extended_input0_shape.Dims(i);
  703. const int extent1 = extended_input1_shape.Dims(i);
  704. const int extent2 = extended_input2_shape.Dims(i);
  705. int extent = extent0;
  706. if (extent1 != 1) extent = extent1;
  707. if (extent2 != 1) extent = extent2;
  708. TFLITE_DCHECK(extent0 == 1 || extent0 == extent);
  709. TFLITE_DCHECK(extent1 == 1 || extent1 == extent);
  710. TFLITE_DCHECK(extent2 == 1 || extent2 == extent);
  711. if (!(extent0 == extent1 && extent1 == extent2)) {
  712. if (extent0 == 1) {
  713. desc0_out->strides[i] = 0;
  714. desc0_out->extents[i] = extent;
  715. }
  716. if (extent1 == 1) {
  717. desc1_out->strides[i] = 0;
  718. desc1_out->extents[i] = extent;
  719. }
  720. if (extent2 == 1) {
  721. desc2_out->strides[i] = 0;
  722. desc2_out->extents[i] = extent;
  723. }
  724. }
  725. }
  726. }
  727. // Detailed implementation of NDOpsHelper, the indexes must be a zero array.
  728. // This implementation is equivalent to N nested loops. Ex, if N=4, it can be
  729. // re-writen as:
  730. // for (int b = 0; b < output.extents[0]; ++b) {
  731. // for (int y = 0; y < output.extents[1]; ++y) {
  732. // for (int x = 0; x < output.extents[2]; ++x) {
  733. // for (int c = 0; c < output.extents[3]; ++c) {
  734. // calc({b,y,x,c});
  735. // }
  736. // }
  737. // }
  738. // }
  739. template <int N, int DIM, typename Calc>
  740. typename std::enable_if<DIM != N - 1, void>::type NDOpsHelperImpl(
  741. const NdArrayDesc<N>& output, const Calc& calc, int indexes[N]) {
  742. for (indexes[DIM] = 0; indexes[DIM] < output.extents[DIM]; ++indexes[DIM]) {
  743. NDOpsHelperImpl<N, DIM + 1, Calc>(output, calc, indexes);
  744. }
  745. }
  746. template <int N, int DIM, typename Calc>
  747. typename std::enable_if<DIM == N - 1, void>::type NDOpsHelperImpl(
  748. const NdArrayDesc<N>& output, const Calc& calc, int indexes[N]) {
  749. for (indexes[DIM] = 0; indexes[DIM] < output.extents[DIM]; ++indexes[DIM]) {
  750. calc(indexes);
  751. }
  752. }
  753. // Execute the calc function in the innermost iteration based on the shape of
  754. // the output. The calc function should take a single argument of type int[N].
  755. template <int N, typename Calc>
  756. inline void NDOpsHelper(const NdArrayDesc<N>& output, const Calc& calc) {
  757. int indexes[N] = {0};
  758. NDOpsHelperImpl<N, 0, Calc>(output, calc, indexes);
  759. }
  760. // Copied from gemmlowp::RoundDown when we dropped direct dependency on
  761. // gemmlowp.
  762. //
  763. // Returns the runtime argument rounded down to the nearest multiple of
  764. // the fixed Modulus.
  765. template <unsigned Modulus, typename Integer>
  766. Integer RoundDown(Integer i) {
  767. return i - (i % Modulus);
  768. }
  769. // Copied from gemmlowp::RoundUp when we dropped direct dependency on
  770. // gemmlowp.
  771. //
  772. // Returns the runtime argument rounded up to the nearest multiple of
  773. // the fixed Modulus.
  774. template <unsigned Modulus, typename Integer>
  775. Integer RoundUp(Integer i) {
  776. return RoundDown<Modulus>(i + Modulus - 1);
  777. }
  778. // Copied from gemmlowp::CeilQuotient when we dropped direct dependency on
  779. // gemmlowp.
  780. //
  781. // Returns the quotient a / b rounded up ('ceil') to the nearest integer.
  782. template <typename Integer>
  783. Integer CeilQuotient(Integer a, Integer b) {
  784. return (a + b - 1) / b;
  785. }
  786. // This function is a copy of gemmlowp::HowManyThreads, copied when we dropped
  787. // the direct dependency of internal/optimized/ on gemmlowp.
  788. //
  789. // It computes a reasonable number of threads to use for a GEMM of shape
  790. // (rows, cols, depth).
  791. //
  792. // TODO(b/131910176): get rid of this function by switching each call site
  793. // to its own more sensible logic for its own workload.
  794. template <int KernelRows>
  795. inline int LegacyHowManyThreads(int max_num_threads, int rows, int cols,
  796. int depth) {
  797. // Early-exit in the default case where multi-threading is disabled.
  798. if (max_num_threads == 1) {
  799. return 1;
  800. }
  801. // Ensure that each thread has KernelRows rows to process, if at all possible.
  802. int thread_count = std::min(max_num_threads, rows / KernelRows);
  803. // Limit the number of threads according to the overall size of the problem.
  804. if (thread_count > 1) {
  805. // Empirically determined value.
  806. static constexpr std::uint64_t min_cubic_size_per_thread = 64 * 1024;
  807. // We can only multiply two out of three sizes without risking overflow
  808. const std::uint64_t cubic_size =
  809. std::uint64_t(rows) * std::uint64_t(cols) * std::uint64_t(depth);
  810. thread_count = std::min(
  811. thread_count, static_cast<int>(cubic_size / min_cubic_size_per_thread));
  812. }
  813. if (thread_count < 1) {
  814. thread_count = 1;
  815. }
  816. assert(thread_count > 0 && thread_count <= max_num_threads);
  817. return thread_count;
  818. }
  819. template <typename T>
  820. void optimized_ops_preload_l1_stream(const T* ptr) {
  821. #ifdef __GNUC__
  822. // builtin offered by GCC-compatible compilers including clang
  823. __builtin_prefetch(ptr, /* 0 means read */ 0, /* 0 means no locality */ 0);
  824. #else
  825. (void)ptr;
  826. #endif
  827. }
  828. template <typename T>
  829. void optimized_ops_preload_l1_keep(const T* ptr) {
  830. #ifdef __GNUC__
  831. // builtin offered by GCC-compatible compilers including clang
  832. __builtin_prefetch(ptr, /* 0 means read */ 0, /* 3 means high locality */ 3);
  833. #else
  834. (void)ptr;
  835. #endif
  836. }
  837. template <typename T>
  838. void optimized_ops_prefetch_write_l1_keep(const T* ptr) {
  839. #ifdef __GNUC__
  840. // builtin offered by GCC-compatible compilers including clang
  841. __builtin_prefetch(ptr, /* 1 means write */ 1, /* 3 means high locality */ 3);
  842. #else
  843. (void)ptr;
  844. #endif
  845. }
  846. } // namespace tflite
  847. #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_COMMON_H_