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 "EmbeddingLookup.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 using namespace hal;
31 
EmbeddingLookup(const Operation & operation,RunTimeOperandInfo * operands)32 EmbeddingLookup::EmbeddingLookup(const Operation& operation, RunTimeOperandInfo* operands) {
33     value_ = GetInput(operation, operands, kValueTensor);
34     lookup_ = GetInput(operation, operands, kLookupTensor);
35 
36     output_ = GetOutput(operation, operands, kOutputTensor);
37 }
38 
Eval()39 bool EmbeddingLookup::Eval() {
40     NNTRACE_COMP("EmbeddingLookup::Eval");
41     const int row_size = value_->shape().dimensions[0];
42     const int total_bytes = nonExtensionOperandSizeOfData(value_->type, value_->dimensions);
43     const int row_bytes = total_bytes / row_size;
44 
45     for (uint32_t i = 0; i < lookup_->shape().dimensions[0]; i++) {
46         int idx = (reinterpret_cast<int*>(lookup_->buffer))[i];
47         if (idx >= row_size || idx < 0) {
48             LOG(ERROR) << "Embedding Lookup: index out of bounds.";
49             return false;
50         } else {
51             memcpy(output_->buffer + i * row_bytes, value_->buffer + idx * row_bytes, row_bytes);
52         }
53     }
54 
55     return true;
56 }
57 
58 }  // namespace nn
59 }  // namespace android
60