1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 #define LOG_TAG "Operations"
18 
19 #include "HashtableLookup.h"
20 
21 #include "CpuExecutor.h"
22 #include "HalInterfaces.h"
23 #include "Operations.h"
24 
25 #include "Tracing.h"
26 
27 namespace android {
28 namespace nn {
29 
30 namespace {
31 
32 using namespace hal;
33 
greater(const void * a,const void * b)34 int greater(const void* a, const void* b) {
35     return *static_cast<const int*>(a) - *static_cast<const int*>(b);
36 }
37 
38 }  // anonymous namespace
39 
HashtableLookup(const Operation & operation,RunTimeOperandInfo * operands)40 HashtableLookup::HashtableLookup(const Operation& operation, RunTimeOperandInfo* operands) {
41     lookup_ = GetInput(operation, operands, kLookupTensor);
42     key_ = GetInput(operation, operands, kKeyTensor);
43     value_ = GetInput(operation, operands, kValueTensor);
44 
45     output_ = GetOutput(operation, operands, kOutputTensor);
46     hits_ = GetOutput(operation, operands, kHitsTensor);
47 }
48 
Eval()49 bool HashtableLookup::Eval() {
50     NNTRACE_COMP("HashtableLookup::Eval");
51     const int num_rows = value_->shape().dimensions[0];
52     const int row_bytes =
53             nonExtensionOperandSizeOfData(value_->type, value_->dimensions) / num_rows;
54     void* pointer = nullptr;
55 
56     for (int i = 0; i < static_cast<int>(lookup_->shape().dimensions[0]); i++) {
57         int idx = -1;
58         pointer = bsearch(lookup_->buffer + sizeof(int) * i, key_->buffer, num_rows, sizeof(int),
59                           greater);
60         if (pointer != nullptr) {
61             idx = (reinterpret_cast<uint8_t*>(pointer) - key_->buffer) / sizeof(float);
62         }
63 
64         if (idx >= num_rows || idx < 0) {
65             memset(output_->buffer + i * row_bytes, 0, row_bytes);
66             hits_->buffer[i] = 0;
67         } else {
68             memcpy(output_->buffer + i * row_bytes, value_->buffer + idx * row_bytes, row_bytes);
69             hits_->buffer[i] = 1;
70         }
71     }
72 
73     return true;
74 }
75 
76 }  // namespace nn
77 }  // namespace android
78