common.h 46 KB

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