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