| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | // |
| 5 | // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 6 | // in compliance with the License. You may obtain a copy of the License at |
| 7 | // |
| 8 | // https://opensource.org/licenses/BSD-3-Clause |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software distributed |
| 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | // specific language governing permissions and limitations under the License. |
| 14 | |
| 15 | #include "embed.h" |
| 16 | |
| 17 | #include <string.h> |
| 18 | |
| 19 | namespace ncnn { |
| 20 | |
| 21 | Embed::Embed() |
| 22 | { |
| 23 | one_blob_only = true; |
| 24 | support_inplace = false; |
| 25 | } |
| 26 | |
| 27 | int Embed::load_param(const ParamDict& pd) |
| 28 | { |
| 29 | num_output = pd.get(0, 0); |
| 30 | input_dim = pd.get(1, 0); |
| 31 | bias_term = pd.get(2, 0); |
| 32 | weight_data_size = pd.get(3, 0); |
| 33 | |
| 34 | return 0; |
| 35 | } |
| 36 | |
| 37 | int Embed::load_model(const ModelBin& mb) |
| 38 | { |
| 39 | weight_data = mb.load(weight_data_size, 0); |
| 40 | if (weight_data.empty()) |
| 41 | return -100; |
| 42 | |
| 43 | if (bias_term) |
| 44 | { |
| 45 | bias_data = mb.load(num_output, 1); |
| 46 | if (bias_data.empty()) |
| 47 | return -100; |
| 48 | } |
| 49 | |
| 50 | return 0; |
| 51 | } |
| 52 | |
| 53 | int Embed::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const |
| 54 | { |
| 55 | int words = static_cast<int>(bottom_blob.total()); |
| 56 | |
| 57 | top_blob.create(num_output, words, 4u, opt.blob_allocator); |
| 58 | if (top_blob.empty()) |
| 59 | return -100; |
| 60 | |
| 61 | // num_output |
| 62 | #pragma omp parallel for num_threads(opt.num_threads) |
| 63 | for (int q = 0; q < words; q++) |
| 64 | { |
| 65 | float* outptr = top_blob.row(q); |
| 66 | |
| 67 | int word_index = ((const int*)bottom_blob)[q]; |
| 68 | |
| 69 | if (word_index < 0) |
| 70 | word_index = 0; |
| 71 | if (word_index >= input_dim) |
| 72 | word_index = input_dim - 1; |
| 73 | |
| 74 | const float* em = (const float*)weight_data + num_output * word_index; |
| 75 | |
| 76 | memcpy(outptr, em, num_output * sizeof(float)); |
| 77 | |
| 78 | if (bias_term) |
| 79 | { |
| 80 | for (int p = 0; p < num_output; p++) |
| 81 | { |
| 82 | outptr[p] += bias_data[p]; |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | return 0; |
| 88 | } |
| 89 | |
| 90 | } // namespace ncnn |