sub.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /* Copyright 2020 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_REFERENCE_SUB_H_
  13. #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_SUB_H_
  14. #include <stdint.h>
  15. #include <algorithm>
  16. #include <limits>
  17. #include "ruy/profiler/instrumentation.h" // from @ruy
  18. #include "tensorflow/lite/kernels/internal/common.h"
  19. #include "tensorflow/lite/kernels/internal/compatibility.h"
  20. #include "tensorflow/lite/kernels/internal/types.h"
  21. namespace tflite {
  22. namespace reference_ops {
  23. inline void SubNonBroadcast(const ArithmeticParams& params,
  24. const RuntimeShape& input1_shape,
  25. const float* input1_data,
  26. const RuntimeShape& input2_shape,
  27. const float* input2_data,
  28. const RuntimeShape& output_shape,
  29. float* output_data) {
  30. const int flat_size =
  31. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  32. for (int i = 0; i < flat_size; ++i) {
  33. output_data[i] = ActivationFunctionWithMinMax(
  34. input1_data[i] - input2_data[i], params.float_activation_min,
  35. params.float_activation_max);
  36. }
  37. }
  38. inline void SubNonBroadcast(const ArithmeticParams& params,
  39. const RuntimeShape& input1_shape,
  40. const int32_t* input1_data,
  41. const RuntimeShape& input2_shape,
  42. const int32_t* input2_data,
  43. const RuntimeShape& output_shape,
  44. int32_t* output_data) {
  45. const int flat_size =
  46. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  47. for (int i = 0; i < flat_size; ++i) {
  48. output_data[i] = ActivationFunctionWithMinMax(
  49. input1_data[i] - input2_data[i], params.quantized_activation_min,
  50. params.quantized_activation_max);
  51. }
  52. }
  53. // TODO(b/151345304): We can implement BroadcastSub on buffers of arbitrary
  54. // dimensionality if the runtime code does a single loop over one dimension
  55. // that handles broadcasting as the base case. The code generator would then
  56. // generate max(D1, D2) nested for loops.
  57. template <int N = 5>
  58. inline void BroadcastSubSlow(const ArithmeticParams& params,
  59. const RuntimeShape& input1_shape,
  60. const float* input1_data,
  61. const RuntimeShape& input2_shape,
  62. const float* input2_data,
  63. const RuntimeShape& output_shape,
  64. float* output_data) {
  65. ruy::profiler::ScopeLabel label("BroadcastSubSlow/float");
  66. TFLITE_DCHECK_LE(input1_shape.DimensionsCount(), N);
  67. TFLITE_DCHECK_LE(input2_shape.DimensionsCount(), N);
  68. TFLITE_DCHECK_LE(output_shape.DimensionsCount(), N);
  69. NdArrayDesc<N> desc1;
  70. NdArrayDesc<N> desc2;
  71. NdArrayDesc<N> output_desc;
  72. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  73. &desc2);
  74. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  75. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  76. // col, channel), with extents (batches, height, width, depth), with the
  77. // trailing dimension changing most rapidly (channels has the smallest stride,
  78. // typically 1 element).
  79. //
  80. // In generated C code, we store arrays with the dimensions reversed. The
  81. // first dimension has smallest stride.
  82. //
  83. // We name our variables by their Tensorflow convention, but generate C code
  84. // nesting loops such that the innermost loop has the smallest stride for the
  85. // best cache behavior.
  86. auto sub_func = [&](int indexes[N]) {
  87. output_data[SubscriptToIndex(output_desc, indexes)] =
  88. ActivationFunctionWithMinMax(
  89. input1_data[SubscriptToIndex(desc1, indexes)] -
  90. input2_data[SubscriptToIndex(desc2, indexes)],
  91. params.float_activation_min, params.float_activation_max);
  92. };
  93. NDOpsHelper<N>(output_desc, sub_func);
  94. }
  95. template <int N = 5>
  96. inline void BroadcastSubSlow(const ArithmeticParams& params,
  97. const RuntimeShape& input1_shape,
  98. const int32_t* input1_data,
  99. const RuntimeShape& input2_shape,
  100. const int32_t* input2_data,
  101. const RuntimeShape& output_shape,
  102. int32_t* output_data) {
  103. ruy::profiler::ScopeLabel label("BroadcastSubSlow/int32_t");
  104. TFLITE_DCHECK_LE(input1_shape.DimensionsCount(), N);
  105. TFLITE_DCHECK_LE(input2_shape.DimensionsCount(), N);
  106. TFLITE_DCHECK_LE(output_shape.DimensionsCount(), N);
  107. NdArrayDesc<N> desc1;
  108. NdArrayDesc<N> desc2;
  109. NdArrayDesc<N> output_desc;
  110. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  111. &desc2);
  112. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  113. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  114. // col, channel), with extents (batches, height, width, depth), with the
  115. // trailing dimension changing most rapidly (channels has the smallest stride,
  116. // typically 1 element).
  117. //
  118. // In generated C code, we store arrays with the dimensions reversed. The
  119. // first dimension has smallest stride.
  120. //
  121. // We name our variables by their Tensorflow convention, but generate C code
  122. // nesting loops such that the innermost loop has the smallest stride for the
  123. // best cache behavior.
  124. auto sub_func = [&](int indexes[N]) {
  125. output_data[SubscriptToIndex(output_desc, indexes)] =
  126. ActivationFunctionWithMinMax(
  127. input1_data[SubscriptToIndex(desc1, indexes)] -
  128. input2_data[SubscriptToIndex(desc2, indexes)],
  129. params.quantized_activation_min, params.quantized_activation_max);
  130. };
  131. NDOpsHelper<N>(output_desc, sub_func);
  132. }
  133. template <int N = 5>
  134. void BroadcastSubSlow(const ArithmeticParams& params,
  135. const RuntimeShape& input1_shape,
  136. const int64_t* input1_data,
  137. const RuntimeShape& input2_shape,
  138. const int64_t* input2_data,
  139. const RuntimeShape& output_shape, int64_t* output_data) {
  140. ruy::profiler::ScopeLabel label("BroadcastSubSlow/int64_t");
  141. TFLITE_DCHECK_LE(input1_shape.DimensionsCount(), N);
  142. TFLITE_DCHECK_LE(input2_shape.DimensionsCount(), N);
  143. TFLITE_DCHECK_LE(output_shape.DimensionsCount(), N);
  144. NdArrayDesc<N> desc1;
  145. NdArrayDesc<N> desc2;
  146. NdArrayDesc<N> output_desc;
  147. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  148. &desc2);
  149. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  150. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  151. // col, channel), with extents (batches, height, width, depth), with the
  152. // trailing dimension changing most rapidly (channels has the smallest stride,
  153. // typically 1 element).
  154. //
  155. // In generated C code, we store arrays with the dimensions reversed. The
  156. // first dimension has smallest stride.
  157. //
  158. // We name our variables by their Tensorflow convention, but generate C code
  159. // nesting loops such that the innermost loop has the smallest stride for the
  160. // best cache behavior.
  161. auto sub_func = [&](int indexes[N]) {
  162. output_data[SubscriptToIndex(output_desc, indexes)] =
  163. ActivationFunctionWithMinMax(
  164. input1_data[SubscriptToIndex(desc1, indexes)] -
  165. input2_data[SubscriptToIndex(desc2, indexes)],
  166. params.int64_activation_min, params.int64_activation_max);
  167. };
  168. NDOpsHelper<N>(output_desc, sub_func);
  169. }
  170. template <typename T, int N = 5>
  171. void BroadcastSubSlow(const ArithmeticParams& params,
  172. const RuntimeShape& input1_shape, const T* input1_data,
  173. const RuntimeShape& input2_shape, const T* input2_data,
  174. const RuntimeShape& output_shape, T* output_data) {
  175. ruy::profiler::ScopeLabel label("BroadcastSubSlow/templated");
  176. TFLITE_DCHECK_LE(input1_shape.DimensionsCount(), N);
  177. TFLITE_DCHECK_LE(input2_shape.DimensionsCount(), N);
  178. TFLITE_DCHECK_LE(output_shape.DimensionsCount(), N);
  179. NdArrayDesc<N> desc1;
  180. NdArrayDesc<N> desc2;
  181. NdArrayDesc<N> output_desc;
  182. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  183. &desc2);
  184. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  185. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  186. // col, channel), with extents (batches, height, width, depth), with the
  187. // trailing dimension changing most rapidly (channels has the smallest stride,
  188. // typically 1 element).
  189. //
  190. // In generated C code, we store arrays with the dimensions reversed. The
  191. // first dimension has smallest stride.
  192. //
  193. // We name our variables by their Tensorflow convention, but generate C code
  194. // nesting loops such that the innermost loop has the smallest stride for the
  195. // best cache behavior.
  196. auto sub_func = [&](int indexes[N]) {
  197. output_data[SubscriptToIndex(output_desc, indexes)] =
  198. ActivationFunctionWithMinMax(
  199. input1_data[SubscriptToIndex(desc1, indexes)] -
  200. input2_data[SubscriptToIndex(desc2, indexes)],
  201. params.quantized_activation_min, params.quantized_activation_max);
  202. };
  203. NDOpsHelper<N>(output_desc, sub_func);
  204. }
  205. template <int N = 5>
  206. inline void BroadcastSub16POTSlow(const ArithmeticParams& params,
  207. const RuntimeShape& input1_shape,
  208. const int16_t* input1_data,
  209. const RuntimeShape& input2_shape,
  210. const int16_t* input2_data,
  211. const RuntimeShape& output_shape,
  212. int16_t* output_data) {
  213. ruy::profiler::ScopeLabel label("BroadcastSub16POTSlow/int16_t");
  214. NdArrayDesc<N> desc1;
  215. NdArrayDesc<N> desc2;
  216. NdArrayDesc<N> output_desc;
  217. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  218. &desc2);
  219. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  220. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  221. // col, channel), with extents (batches, height, width, depth), with the
  222. // trailing dimension changing most rapidly (channels has the smallest stride,
  223. // typically 1 element).
  224. //
  225. // In generated C code, we store arrays with the dimensions reversed. The
  226. // first dimension has smallest stride.
  227. //
  228. // We name our variables by their Tensorflow convention, but generate C code
  229. // nesting loops such that the innermost loop has the smallest stride for the
  230. // best cache behavior.
  231. auto sub_func = [&](int indexes[N]) {
  232. const int32_t input1_val = input1_data[SubscriptToIndex(desc1, indexes)];
  233. const int32_t input2_val = input2_data[SubscriptToIndex(desc2, indexes)];
  234. const int32_t scaled_input1_val =
  235. gemmlowp::RoundingDivideByPOT(input1_val, -params.input1_shift);
  236. const int32_t scaled_input2_val =
  237. gemmlowp::RoundingDivideByPOT(input2_val, -params.input2_shift);
  238. const int32_t raw_output = scaled_input1_val - scaled_input2_val;
  239. const int32_t clamped_output =
  240. std::min(params.quantized_activation_max,
  241. std::max(params.quantized_activation_min, raw_output));
  242. output_data[SubscriptToIndex(output_desc, indexes)] =
  243. static_cast<int16_t>(clamped_output);
  244. };
  245. NDOpsHelper<N>(output_desc, sub_func);
  246. }
  247. template <typename T, int N = 5>
  248. void BroadcastQuantSubSlow(const ArithmeticParams& params,
  249. const RuntimeShape& input1_shape,
  250. const T* input1_data,
  251. const RuntimeShape& input2_shape,
  252. const T* input2_data,
  253. const RuntimeShape& output_shape, T* output_data) {
  254. ruy::profiler::ScopeLabel label("BroadcastQuantSubSlow/T");
  255. TFLITE_DCHECK_LE(input1_shape.DimensionsCount(), N);
  256. TFLITE_DCHECK_LE(input2_shape.DimensionsCount(), N);
  257. TFLITE_DCHECK_LE(output_shape.DimensionsCount(), N);
  258. NdArrayDesc<N> desc1;
  259. NdArrayDesc<N> desc2;
  260. NdArrayDesc<N> output_desc;
  261. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  262. &desc2);
  263. CopyDimsToDesc(RuntimeShape::ExtendedShape(N, output_shape), &output_desc);
  264. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  265. // col, channel), with extents (batches, height, width, depth), with the
  266. // trailing dimension changing most rapidly (channels has the smallest stride,
  267. // typically 1 element).
  268. //
  269. // In generated C code, we store arrays with the dimensions reversed. The
  270. // first dimension has smallest stride.
  271. //
  272. // We name our variables by their Tensorflow convention, but generate C code
  273. // nesting loops such that the innermost loop has the smallest stride for the
  274. // best cache behavior.
  275. auto sub_func = [&](int indexes[N]) {
  276. const int32_t input1_val =
  277. params.input1_offset + input1_data[SubscriptToIndex(desc1, indexes)];
  278. const int32_t input2_val =
  279. params.input2_offset + input2_data[SubscriptToIndex(desc2, indexes)];
  280. const int32_t shifted_input1_val = input1_val * (1 << params.left_shift);
  281. const int32_t shifted_input2_val = input2_val * (1 << params.left_shift);
  282. const int32_t scaled_input1_val =
  283. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  284. shifted_input1_val, params.input1_multiplier, params.input1_shift);
  285. const int32_t scaled_input2_val =
  286. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  287. shifted_input2_val, params.input2_multiplier, params.input2_shift);
  288. const int32_t raw_sub = scaled_input1_val - scaled_input2_val;
  289. const int32_t raw_output =
  290. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  291. raw_sub, params.output_multiplier, params.output_shift) +
  292. params.output_offset;
  293. const int32_t clamped_output =
  294. std::min(params.quantized_activation_max,
  295. std::max(params.quantized_activation_min, raw_output));
  296. output_data[SubscriptToIndex(output_desc, indexes)] =
  297. static_cast<T>(clamped_output);
  298. };
  299. NDOpsHelper<N>(output_desc, sub_func);
  300. }
  301. // Element-wise add that can often be used for inner loop of broadcast add as
  302. // well as the non-broadcast add.
  303. template <typename T>
  304. inline void SubElementwise(int size, const ArithmeticParams& params,
  305. const T* input1_data, const T* input2_data,
  306. T* output_data) {
  307. for (int i = 0; i < size; ++i) {
  308. const int32_t input1_val = params.input1_offset + input1_data[i];
  309. const int32_t input2_val = params.input2_offset + input2_data[i];
  310. const int32_t shifted_input1_val = input1_val * (1 << params.left_shift);
  311. const int32_t shifted_input2_val = input2_val * (1 << params.left_shift);
  312. const int32_t scaled_input1_val =
  313. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  314. shifted_input1_val, params.input1_multiplier, params.input1_shift);
  315. const int32_t scaled_input2_val =
  316. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  317. shifted_input2_val, params.input2_multiplier, params.input2_shift);
  318. const int32_t raw_sub = scaled_input1_val - scaled_input2_val;
  319. const int32_t raw_output =
  320. MultiplyByQuantizedMultiplierSmallerThanOneExp(
  321. raw_sub, params.output_multiplier, params.output_shift) +
  322. params.output_offset;
  323. const int32_t clamped_output =
  324. std::min(params.quantized_activation_max,
  325. std::max(params.quantized_activation_min, raw_output));
  326. output_data[i] = static_cast<T>(clamped_output);
  327. }
  328. }
  329. inline void Sub(const ArithmeticParams& params,
  330. const RuntimeShape& input1_shape, const uint8_t* input1_data,
  331. const RuntimeShape& input2_shape, const uint8_t* input2_data,
  332. const RuntimeShape& output_shape, uint8_t* output_data) {
  333. TFLITE_DCHECK_LE(params.quantized_activation_min,
  334. params.quantized_activation_max);
  335. const int flat_size =
  336. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  337. TFLITE_DCHECK_GT(params.input1_offset, -256);
  338. TFLITE_DCHECK_GT(params.input2_offset, -256);
  339. TFLITE_DCHECK_LT(params.input1_offset, 256);
  340. TFLITE_DCHECK_LT(params.input2_offset, 256);
  341. SubElementwise(flat_size, params, input1_data, input2_data, output_data);
  342. }
  343. inline void Sub(const ArithmeticParams& params,
  344. const RuntimeShape& input1_shape, const int8_t* input1_data,
  345. const RuntimeShape& input2_shape, const int8_t* input2_data,
  346. const RuntimeShape& output_shape, int8_t* output_data) {
  347. TFLITE_DCHECK_LE(params.quantized_activation_min,
  348. params.quantized_activation_max);
  349. const int flat_size =
  350. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  351. TFLITE_DCHECK_GE(params.input1_offset, -128);
  352. TFLITE_DCHECK_GE(params.input2_offset, -128);
  353. // offset = -quantization_params.zero_point in PrepareGeneralSubOp().
  354. // So it's maximum can be 128 not 127.
  355. TFLITE_DCHECK_LE(params.input1_offset, 128);
  356. TFLITE_DCHECK_LE(params.input2_offset, 128);
  357. SubElementwise(flat_size, params, input1_data, input2_data, output_data);
  358. }
  359. inline void Sub(const ArithmeticParams& params,
  360. const RuntimeShape& input1_shape, const int16_t* input1_data,
  361. const RuntimeShape& input2_shape, const int16_t* input2_data,
  362. const RuntimeShape& output_shape, int16_t* output_data) {
  363. TFLITE_DCHECK_LE(params.quantized_activation_min,
  364. params.quantized_activation_max);
  365. const int flat_size =
  366. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  367. TFLITE_DCHECK_EQ(params.input1_offset, 0);
  368. TFLITE_DCHECK_EQ(params.input2_offset, 0);
  369. SubElementwise(flat_size, params, input1_data, input2_data, output_data);
  370. }
  371. template <typename T>
  372. void Sub(const ArithmeticParams& params, const RuntimeShape& input1_shape,
  373. const T* input1_data, const RuntimeShape& input2_shape,
  374. const T* input2_data, const RuntimeShape& output_shape,
  375. T* output_data) {
  376. NdArrayDesc<4> desc1;
  377. NdArrayDesc<4> desc2;
  378. NdArrayDescsForElementwiseBroadcast(input1_shape, input2_shape, &desc1,
  379. &desc2);
  380. const RuntimeShape extended_output_shape =
  381. RuntimeShape::ExtendedShape(4, output_shape);
  382. // In Tensorflow, the dimensions are canonically named (batch_number, row,
  383. // col, channel), with extents (batches, height, width, depth), with the
  384. // trailing dimension changing most rapidly (channels has the smallest stride,
  385. // typically 1 element).
  386. //
  387. // In generated C code, we store arrays with the dimensions reversed. The
  388. // first dimension has smallest stride.
  389. //
  390. // We name our variables by their Tensorflow convention, but generate C code
  391. // nesting loops such that the innermost loop has the smallest stride for the
  392. // best cache behavior.
  393. for (int b = 0; b < extended_output_shape.Dims(0); ++b) {
  394. for (int y = 0; y < extended_output_shape.Dims(1); ++y) {
  395. for (int x = 0; x < extended_output_shape.Dims(2); ++x) {
  396. for (int c = 0; c < extended_output_shape.Dims(3); ++c) {
  397. output_data[Offset(extended_output_shape, b, y, x, c)] =
  398. input1_data[SubscriptToIndex(desc1, b, y, x, c)] -
  399. input2_data[SubscriptToIndex(desc2, b, y, x, c)];
  400. }
  401. }
  402. }
  403. }
  404. }
  405. inline void SetActivationMinMax(const ArithmeticParams& params,
  406. int32_t* activation_min,
  407. int32_t* activation_max) {
  408. *activation_min = params.quantized_activation_min;
  409. *activation_max = params.quantized_activation_max;
  410. }
  411. inline void SetActivationMinMax(const ArithmeticParams& params,
  412. float* activation_min, float* activation_max) {
  413. *activation_min = params.float_activation_min;
  414. *activation_max = params.float_activation_max;
  415. }
  416. inline void SetActivationMinMax(const ArithmeticParams& params,
  417. int64_t* activation_min,
  418. int64_t* activation_max) {
  419. *activation_min = params.int64_activation_min;
  420. *activation_max = params.int64_activation_max;
  421. }
  422. template <typename T>
  423. inline void SubWithActivation(
  424. const ArithmeticParams& params, const RuntimeShape& input1_shape,
  425. const T* input1_data, const RuntimeShape& input2_shape,
  426. const T* input2_data, const RuntimeShape& output_shape, T* output_data) {
  427. ruy::profiler::ScopeLabel label("SubWithActivation");
  428. const int flat_size =
  429. MatchingElementsSize(input1_shape, input2_shape, output_shape);
  430. T activation_min, activation_max;
  431. SetActivationMinMax(params, &activation_min, &activation_max);
  432. for (int i = 0; i < flat_size; ++i) {
  433. output_data[i] = ActivationFunctionWithMinMax(
  434. input1_data[i] - input2_data[i], activation_min, activation_max);
  435. }
  436. }
  437. } // namespace reference_ops
  438. } // namespace tflite
  439. #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_SUB_H_