30787c0a4027ceab84c2fe9d06a02590c6dead1f
[platform/core/ml/nnfw.git] / compute / ARMComputeEx / src / core / NEON / kernels / NEHashtableLookupKernel.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * Copyright (c) 2018-2019 ARM Limited.
19  *
20  * SPDX-License-Identifier: MIT
21  *
22  * Permission is hereby granted, free of charge, to any person obtaining a copy
23  * of this software and associated documentation files (the "Software"), to
24  * deal in the Software without restriction, including without limitation the
25  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
26  * sell copies of the Software, and to permit persons to whom the Software is
27  * furnished to do so, subject to the following conditions:
28  *
29  * The above copyright notice and this permission notice shall be included in all
30  * copies or substantial portions of the Software.
31  *
32  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38  * SOFTWARE.
39  */
40
41 #include "arm_compute/core/NEON/kernels/NEHashtableLookupKernel.h"
42
43 #include "arm_compute/core/Error.h"
44 #include "arm_compute/core/Helpers.h"
45 #include "arm_compute/core/ITensor.h"
46 #include "arm_compute/core/TensorInfo.h"
47 #include "arm_compute/core/Validate.h"
48 #include "arm_compute/core/Window.h"
49
50 #include <unordered_map>
51
52 using namespace arm_compute;
53
54 namespace
55 {
56 constexpr size_t NOT_HIT = 0xFFFFFFFF;
57 } // namespace
58
59 NEHashtableLookupKernel::NEHashtableLookupKernel()
60     : _lookups(nullptr), _keys(nullptr), _input(nullptr), _output(nullptr), _hits{nullptr}
61 {
62 }
63
64 void NEHashtableLookupKernel::configure(const ITensor *lookups, const ITensor *keys,
65                                         const ITensor *input, ITensor *output, ITensor *hits)
66 {
67   ARM_COMPUTE_ERROR_ON_NULLPTR(lookups, keys, input, output, hits);
68   ARM_COMPUTE_ERROR_THROW_ON(
69       validate(lookups->info(), keys->info(), input->info(), output->info(), hits->info()));
70
71   _lookups = lookups;
72   _keys = keys;
73   _input = input;
74   _output = output;
75   _hits = hits;
76
77   // Auto initialize output if not initialized
78   auto out_shape{input->info()->tensor_shape()};
79   out_shape.set(out_shape.num_dimensions() - 1, lookups->info()->num_dimensions(), false);
80   auto_init_if_empty(*output->info(), out_shape, 1, input->info()->data_type(),
81                      input->info()->quantization_info());
82
83   // Auto initialize hits if not initialized
84   auto_init_if_empty(*hits->info(), lookups->info()->tensor_shape(), 1, DataType::U8);
85
86   INEKernel::configure(calculate_max_window(*output->info()));
87 }
88
89 Status NEHashtableLookupKernel::validate(const ITensorInfo *lookups, const ITensorInfo *keys,
90                                          const ITensorInfo *input, const ITensorInfo *output,
91                                          const ITensorInfo *hits)
92 {
93   ARM_COMPUTE_ERROR_ON_NULLPTR(lookups, keys, input, output, hits);
94   ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(
95       input, 1, DataType::U8, DataType::S8, DataType::QASYMM8, DataType::U16, DataType::S16,
96       DataType::U32, DataType::S32, DataType::F16, DataType::F32);
97   ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(lookups, 1, DataType::S32);
98   ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(keys, 1, DataType::S32);
99
100   ARM_COMPUTE_ERROR_ON(input->num_dimensions() < 2 && input->num_dimensions() > 4);
101   ARM_COMPUTE_ERROR_ON(lookups->num_dimensions() > 1);
102   ARM_COMPUTE_ERROR_ON(keys->num_dimensions() > 1);
103   ARM_COMPUTE_ERROR_ON(keys->dimension(0) != input->dimension(input->num_dimensions() - 1));
104
105   // Validate in case of configured output
106   if (output->total_size() > 0)
107   {
108     ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
109     ARM_COMPUTE_ERROR_ON(input->num_dimensions() != output->num_dimensions());
110     ARM_COMPUTE_ERROR_ON(output->dimension(output->num_dimensions() - 1) != lookups->dimension(0));
111     for (size_t i = 0; i < output->num_dimensions() - 1; ++i)
112     {
113       ARM_COMPUTE_ERROR_ON(input->dimension(i) != output->dimension(i));
114     }
115   }
116
117   // Validate in case of configured hits
118   if (hits->total_size() > 0)
119   {
120     ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(hits, 1, DataType::U8, DataType::QASYMM8);
121     ARM_COMPUTE_ERROR_ON(hits->dimension(0) != output->dimension(output->num_dimensions() - 1));
122     ARM_COMPUTE_ERROR_ON(hits->dimension(0) != lookups->dimension(0));
123     ARM_COMPUTE_ERROR_ON(hits->num_dimensions() > 1);
124   }
125
126   return Status{};
127 }
128
129 void NEHashtableLookupKernel::run(const Window &window, const ThreadInfo &info)
130 {
131   ARM_COMPUTE_UNUSED(info);
132   ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
133   ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
134
135   const size_t lookup_dim = _output->info()->num_dimensions() - 1;
136   const int const_0 = _output->info()->data_type() == DataType::QASYMM8
137                           ? _output->info()->quantization_info().uniform().offset
138                           : 0;
139
140   std::unordered_map<int32_t, size_t> key_index_map;
141   for (size_t n = 0; n < _keys->info()->dimension(0); ++n)
142   {
143     const int32_t key = *reinterpret_cast<int32_t *>(_keys->ptr_to_element({n}));
144     key_index_map[key] = n;
145   }
146   std::vector<size_t> lookup_indices;
147   for (size_t k = 0; k < _lookups->info()->dimension(0); ++k)
148   {
149     const int32_t key = *reinterpret_cast<int32_t *>(_lookups->ptr_to_element({k}));
150     const auto it = key_index_map.find(key);
151     if (it == key_index_map.end())
152     {
153       lookup_indices.emplace_back(NOT_HIT);
154       *_hits->ptr_to_element({k}) = 0;
155     }
156     else
157     {
158 #if defined(ARM_COMPUTE_DEBUG_ENABLED)
159       if (it->second >= _keys->info()->dimension(0))
160         ARM_COMPUTE_ERROR("HashTable Lookup: Index out of bounds.");
161 #endif // defined(ARM_COMPUTE_DEBUG_ENABLED)
162       lookup_indices.emplace_back(it->second);
163       *_hits->ptr_to_element({k}) = 1;
164     }
165   }
166
167   Window output_window{window};
168   output_window.set(Window::DimX,
169                     Window::Dimension(output_window.x().start(), output_window.x().end(),
170                                       _input->info()->dimension(0)));
171
172   Window out_slice = output_window.first_slice_window_4D();
173   do
174   {
175     Iterator output_it(_output, out_slice);
176
177     execute_window_loop(out_slice,
178                         [&](const Coordinates &id) {
179                           const auto lookup = lookup_indices.at(id[lookup_dim]);
180                           if (lookup == NOT_HIT)
181                           {
182                             memset(output_it.ptr(), const_0,
183                                    _output->info()->dimension(0) * _output->info()->element_size());
184                           }
185                           else
186                           {
187                             Coordinates input_id{id};
188                             input_id.set(lookup_dim, lookup);
189                             memcpy(output_it.ptr(), _input->ptr_to_element(input_id),
190                                    _output->info()->dimension(0) * _output->info()->element_size());
191                           }
192
193                         },
194                         output_it);
195
196   } while (window.slide_window_slice_4D(out_slice));
197 }