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_GATHER_H_
16 #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_GATHER_H_
17 
18 #include <cstring>
19 
20 #include "tensorflow/lite/kernels/internal/common.h"
21 
22 namespace tflite {
23 namespace reference_ops {
24 
25 template <typename T, typename CoordsT = int32>
Gather(const tflite::GatherParams & op_params,const RuntimeShape & input_shape,const T * input_data,const RuntimeShape & coords_shape,const CoordsT * coords_data,const RuntimeShape & output_shape,T * output_data)26 inline void Gather(const tflite::GatherParams& op_params,
27                    const RuntimeShape& input_shape, const T* input_data,
28                    const RuntimeShape& coords_shape, const CoordsT* coords_data,
29                    const RuntimeShape& output_shape, T* output_data) {
30   ruy::profiler::ScopeLabel label("Gather");
31   int axis = op_params.axis;
32   if (axis < 0) {
33     axis += input_shape.DimensionsCount();
34   }
35   TFLITE_DCHECK_GE(axis, 0);
36   TFLITE_DCHECK_LT(axis, input_shape.DimensionsCount());
37   const int axis_size = input_shape.Dims(axis);
38   const int coords_count = coords_shape.FlatSize();
39 
40   int outer_size = 1;
41   for (int i = 0; i < axis; ++i) {
42     outer_size *= input_shape.Dims(i);
43   }
44 
45   int inner_size = 1;
46   for (int i = axis + 1; i < input_shape.DimensionsCount(); ++i) {
47     inner_size *= input_shape.Dims(i);
48   }
49 
50   for (int outer = 0; outer < outer_size; ++outer) {
51     for (int i = 0; i < coords_count; ++i) {
52       TFLITE_DCHECK_GE(coords_data[i], 0);
53       TFLITE_DCHECK_LT(coords_data[i], axis_size);
54       // TODO(rsun): replace memcpy with a for loop
55       std::memcpy(
56           output_data + (outer * coords_count + i) * inner_size,
57           input_data + (outer * axis_size + coords_data[i]) * inner_size,
58           sizeof(T) * inner_size);
59     }
60   }
61 }
62 
63 }  // namespace reference_ops
64 }  // namespace tflite
65 
66 #endif  // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_GATHER_H_
67