1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_BROADCAST_ARGS_H_
16 #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_BROADCAST_ARGS_H_
17
18 #include "tensorflow/lite/kernels/internal/compatibility.h"
19 #include "tensorflow/lite/kernels/internal/types.h"
20
21 namespace tflite {
22 namespace reference_ops {
23
24 template <typename T>
BroadcastArgs(const RuntimeShape & input1_shape,const T * input1_data,const RuntimeShape & input2_shape,const T * input2_data,const RuntimeShape & output_shape,T * output_data)25 void BroadcastArgs(const RuntimeShape& input1_shape, const T* input1_data,
26 const RuntimeShape& input2_shape, const T* input2_data,
27 const RuntimeShape& output_shape, T* output_data) {
28 // Gets data at the backward index i of the shape tensor. Returns 1 if the
29 // index is out of range.
30 auto get_shape_data = [](const RuntimeShape& shape, const T* data,
31 int backward_idx) -> T {
32 int forward_idx = shape.FlatSize() - 1 - backward_idx;
33 if (forward_idx < 0) return 1;
34 return data[forward_idx];
35 };
36
37 int output_num_elements = output_shape.FlatSize();
38 for (int i = 0; i < output_num_elements; ++i) {
39 int backward_i = output_num_elements - 1 - i;
40 int shape1_i = get_shape_data(input1_shape, input1_data, i);
41 int shape2_i = get_shape_data(input2_shape, input2_data, i);
42 if (shape1_i == 1) {
43 output_data[backward_i] = shape2_i;
44 } else if (shape2_i == 1) {
45 output_data[backward_i] = shape1_i;
46 } else {
47 TFLITE_CHECK_EQ(shape1_i, shape2_i);
48 output_data[backward_i] = shape1_i;
49 }
50 }
51 }
52
53 } // namespace reference_ops
54 } // namespace tflite
55
56 #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_BROADCAST_ARGS_H_
57