1 /*
2 * Copyright (C) 2018 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 #include "lang_id/common/embedding-network.h"
18
19 #include <vector>
20
21 #include "lang_id/common/lite_base/integral-types.h"
22 #include "lang_id/common/lite_base/logging.h"
23
24 namespace libtextclassifier3 {
25 namespace mobile {
26 namespace {
27
CheckNoQuantization(const EmbeddingNetworkParams::Matrix & matrix)28 void CheckNoQuantization(const EmbeddingNetworkParams::Matrix &matrix) {
29 SAFTM_CHECK_EQ(static_cast<int>(QuantizationType::NONE),
30 static_cast<int>(matrix.quant_type))
31 << "Quantization not allowed here";
32 }
33
GetMatrixRowSizeInBytes(const EmbeddingNetworkParams::Matrix & matrix)34 int GetMatrixRowSizeInBytes(const EmbeddingNetworkParams::Matrix &matrix) {
35 int cols = matrix.cols;
36 QuantizationType quant_type = matrix.quant_type;
37 switch (quant_type) {
38 case QuantizationType::NONE:
39 return cols * sizeof(float);
40 case QuantizationType::UINT8:
41 return cols * sizeof(uint8);
42 case QuantizationType::UINT4:
43 SAFTM_DCHECK_EQ(cols % 2, 0) << "UINT4 with odd #cols = " << cols;
44 return cols / 2;
45 case QuantizationType::FLOAT16:
46 return cols * sizeof(float16);
47 default:
48 SAFTM_LOG(FATAL) << "Unknown quant type: "
49 << static_cast<int>(quant_type);
50 }
51 }
52
53 // Computes y = weights * Relu(x) + b where Relu is optionally applied.
54 //
55 // weights and b are the weight matrix, respectively the bias vector of a neural
56 // network layer.
57 //
58 // Note: in the research literature, usually Relu (the activation function) is
59 // the last part of a neural layer. From that perspective, this function
60 // computes the Relu part of the previous layer (if any) and next the first half
61 // (the computation of the state) for the current layer.
62 //
63 // Note: weights is expected to be the transposed version of the real weight
64 // matrix. Hence, instead of computing a linear combination of the columns of
65 // weights, we compute a linear combination of its rows; but we are mindful that
66 // these rows are the columns of the original matrix, hence the name
67 // weights_col_i in the code.
SparseReluProductPlusBias(bool apply_relu,const EmbeddingNetworkParams::Matrix & weights,const EmbeddingNetworkParams::Matrix & b,const std::vector<float> & x,std::vector<float> * y)68 void SparseReluProductPlusBias(bool apply_relu,
69 const EmbeddingNetworkParams::Matrix &weights,
70 const EmbeddingNetworkParams::Matrix &b,
71 const std::vector<float> &x,
72 std::vector<float> *y) {
73 // Initialize y to b. b is a column matrix (i.e., nb.cols == 1); we already
74 // CHECK-ed that the EmbeddingNetwork constructor.
75 const float *b_start = reinterpret_cast<const float *>(b.elements);
76 SAFTM_DCHECK_EQ(b.cols, 1);
77 y->assign(b_start, b_start + b.rows);
78
79 float *const y_data = y->data();
80 const int y_size = y->size();
81 SAFTM_CHECK_EQ(weights.cols, y_size);
82 const int x_size = x.size();
83 SAFTM_CHECK_EQ(weights.rows, x_size);
84
85 // NOTE: the code below reads x_size * y_size elements from weights; these
86 // reads are safe as long as weights.elements contains weights.rows *
87 // weights.cols elements (where the element size depends on the quantization
88 // type). That requirement is checked by the params provider, e.g., by
89 // EmbeddingNetworkParamsFromFlatbuffer.
90
91 // There is some code duplication between the two main cases of the switch
92 // below: the idea was to "lift" the switch outside the loops, to reduce the
93 // number of tests at runtime.
94 switch (weights.quant_type) {
95 case QuantizationType::NONE: {
96 // We compute a linear combination of the rows from |weights|, using
97 // elements of x (optionally, Relu(x)) as scaling factors (the i-th row
98 // gets multiplied by x[i] before being added with the other rows). Note:
99 // elements of |weights| are stored in row-major order: first the elements
100 // of row #0, next the elements of row #1, etc. In the comments below, we
101 // write "weights[i][j]" to refer to the j-th element from the i-th row of
102 // weights.
103 const float *weight_ptr =
104 reinterpret_cast<const float *>(weights.elements);
105 for (int i = 0; i < x_size; ++i) {
106 // Invariant 1: weight_ptr points to the beginning of the i-th row from
107 // weights (i.e., weights[i][0]).
108 const float scale = x[i];
109 if (!apply_relu || (scale > 0)) {
110 for (int j = 0; j < y_size; ++j, ++weight_ptr) {
111 // Invariant 2: weight_ptr points to weights[i][j].
112 y_data[j] += (*weight_ptr) * scale;
113 }
114 } else {
115 // We don't update y_data, but we still have to move weight_ptr to the
116 // next row (to satisfy Invariant 1). We do this by adding y_size ==
117 // weights.cols() (see earlier CHECK_EQ).
118 weight_ptr += y_size;
119 }
120 }
121 break;
122 }
123 case QuantizationType::FLOAT16: {
124 // See comments for the QuantizationType::NONE case: the code is almost
125 // identical, except for float16 (instead of float) and the Float16To32
126 // conversion. We could unify these two cases using a template, but since
127 // this is a critical loop, don't want to risk that e.g., inlining of the
128 // conversion function doesn't happen.
129 const float16 *weight_ptr =
130 reinterpret_cast<const float16 *>(weights.elements);
131 for (int i = 0; i < x_size; ++i) {
132 const float scale = x[i];
133 if (!apply_relu || (scale > 0)) {
134 for (int j = 0; j < y_size; ++j, ++weight_ptr) {
135 y_data[j] += Float16To32(*weight_ptr) * scale;
136 }
137 } else {
138 weight_ptr += y_size;
139 }
140 }
141 break;
142 }
143 default:
144 SAFTM_LOG(FATAL) << "Unsupported weights quantization type: "
145 << static_cast<int>(weights.quant_type);
146 }
147 }
148 } // namespace
149
ConcatEmbeddings(const std::vector<FeatureVector> & feature_vectors,std::vector<float> * concat) const150 void EmbeddingNetwork::ConcatEmbeddings(
151 const std::vector<FeatureVector> &feature_vectors,
152 std::vector<float> *concat) const {
153 concat->resize(concat_layer_size_);
154
155 // "es_index" stands for "embedding space index".
156 for (int es_index = 0; es_index < feature_vectors.size(); ++es_index) {
157 const int concat_offset = concat_offset_[es_index];
158
159 const EmbeddingNetworkParams::Matrix &embedding_matrix =
160 embedding_matrices_[es_index];
161 const int embedding_dim = embedding_matrix.cols;
162 const int embedding_row_size_in_bytes =
163 embedding_row_size_in_bytes_[es_index];
164
165 const FeatureVector &feature_vector = feature_vectors[es_index];
166 const int num_features = feature_vector.size();
167 for (int fi = 0; fi < num_features; ++fi) {
168 const FeatureType *feature_type = feature_vector.type(fi);
169 int feature_offset = concat_offset + feature_type->base() * embedding_dim;
170 SAFTM_CHECK_LE(feature_offset + embedding_dim, concat->size());
171
172 // Weighted embeddings will be added starting from this address.
173 float *concat_ptr = concat->data() + feature_offset;
174
175 // Multiplier for each embedding weight. Includes feature weight (for
176 // continuous features) and quantization scale (for quantized embeddings).
177 float multiplier;
178 int feature_id;
179 const FeatureValue feature_value = feature_vector.value(fi);
180 if (feature_type->is_continuous()) {
181 // Continuous features (encoded as FloatFeatureValue).
182 FloatFeatureValue float_feature_value(feature_value);
183 feature_id = float_feature_value.id;
184 multiplier = float_feature_value.weight;
185 } else {
186 // Discrete features: every present feature has implicit value 1.0.
187 feature_id = feature_value;
188 multiplier = 1.0;
189 }
190
191 SAFTM_CHECK_GE(feature_id, 0);
192 SAFTM_CHECK_LT(feature_id, embedding_matrix.rows);
193
194 // Pointer to float / uint8 weights for relevant embedding.
195 const void *embedding_data =
196 (reinterpret_cast<const char *>(embedding_matrix.elements) +
197 feature_id * embedding_row_size_in_bytes);
198
199 switch (embedding_matrix.quant_type) {
200 case QuantizationType::NONE: {
201 const float *weights =
202 reinterpret_cast<const float *>(embedding_data);
203 for (int i = 0; i < embedding_dim; ++i, ++weights, ++concat_ptr) {
204 *concat_ptr += *weights * multiplier;
205 }
206 break;
207 }
208 case QuantizationType::UINT8: {
209 multiplier *= Float16To32(embedding_matrix.quant_scales[feature_id]);
210 const uint8 *quant_weights =
211 reinterpret_cast<const uint8 *>(embedding_data);
212 for (int i = 0; i < embedding_dim;
213 ++i, ++quant_weights, ++concat_ptr) {
214 // 128 is bias for UINT8 quantization.
215 *concat_ptr +=
216 (static_cast<int>(*quant_weights) - 128) * multiplier;
217 }
218 break;
219 }
220 case QuantizationType::UINT4: {
221 multiplier *= Float16To32(embedding_matrix.quant_scales[feature_id]);
222 const uint8 *quant_weights =
223 reinterpret_cast<const uint8 *>(embedding_data);
224 for (int i = 0; i < embedding_dim / 2; ++i, ++quant_weights) {
225 const uint8 qq = *quant_weights;
226 concat_ptr[0] +=
227 (static_cast<int>((qq & 0xF0) | 0x08) - 128) * multiplier;
228 concat_ptr[1] +=
229 (static_cast<int>(((qq & 0x0F) << 4) | 0x08) - 128) *
230 multiplier;
231 concat_ptr += 2;
232 }
233 break;
234 }
235 default:
236 // We already checked (in GetMatrixRowSizeInBytes) that each embedding
237 // matrix has a known quantization type. Hence, DLOG is enough here.
238 SAFTM_DLOG(ERROR) << "Unknown embeddings quantization type "
239 << static_cast<int>(embedding_matrix.quant_type);
240 break;
241 }
242 }
243 }
244 }
245
ComputeFinalScores(const std::vector<FeatureVector> & features,std::vector<float> * scores) const246 void EmbeddingNetwork::ComputeFinalScores(
247 const std::vector<FeatureVector> &features,
248 std::vector<float> *scores) const {
249 ComputeFinalScores(features, {}, scores);
250 }
251
ComputeFinalScores(const std::vector<FeatureVector> & features,const std::vector<float> & extra_inputs,std::vector<float> * scores) const252 void EmbeddingNetwork::ComputeFinalScores(
253 const std::vector<FeatureVector> &features,
254 const std::vector<float> &extra_inputs, std::vector<float> *scores) const {
255 // Construct the input layer for our feed-forward neural network (FFNN).
256 std::vector<float> input;
257 ConcatEmbeddings(features, &input);
258 if (!extra_inputs.empty()) {
259 input.reserve(input.size() + extra_inputs.size());
260 for (int i = 0; i < extra_inputs.size(); i++) {
261 input.push_back(extra_inputs[i]);
262 }
263 }
264
265 // Propagate input through all layers of our FFNN.
266
267 // Alternating storage for activations of the different layers. We can't use
268 // a single vector because all activations of the previous layer are required
269 // when computing the activations of the next one.
270 std::vector<float> storage[2];
271 const std::vector<float> *v_in = &input;
272 const int num_layers = layer_weights_.size();
273 for (int i = 0; i < num_layers; ++i) {
274 std::vector<float> *v_out = nullptr;
275 if (i == num_layers - 1) {
276 // Final layer: write results directly into |scores|.
277 v_out = scores;
278 } else {
279 // Hidden layer: write results into the alternating storage. The i % 2
280 // trick ensures the alternation.
281 v_out = &(storage[i % 2]);
282 }
283 const bool apply_relu = i > 0;
284 SparseReluProductPlusBias(
285 apply_relu, layer_weights_[i], layer_bias_[i], *v_in, v_out);
286 v_in = v_out;
287 }
288 }
289
EmbeddingNetwork(const EmbeddingNetworkParams * model)290 EmbeddingNetwork::EmbeddingNetwork(const EmbeddingNetworkParams *model)
291 : model_(model) {
292 int offset_sum = 0;
293 for (int i = 0; i < model_->embedding_num_features_size(); ++i) {
294 concat_offset_.push_back(offset_sum);
295 EmbeddingNetworkParams::Matrix matrix = model_->GetEmbeddingMatrix(i);
296 offset_sum += matrix.cols * model_->embedding_num_features(i);
297
298 // NOTE: each Matrix is a small struct that doesn't own the actual matrix
299 // weights. Hence, the push_back below is fast.
300 embedding_matrices_.push_back(matrix);
301 embedding_row_size_in_bytes_.push_back(GetMatrixRowSizeInBytes(matrix));
302 }
303 concat_layer_size_ = offset_sum;
304
305 SAFTM_CHECK_EQ(model_->hidden_size(), model_->hidden_bias_size());
306 for (int i = 0; i < model_->hidden_size(); ++i) {
307 layer_weights_.push_back(model_->GetHiddenLayerMatrix(i));
308
309 EmbeddingNetworkParams::Matrix bias = model_->GetHiddenLayerBias(i);
310 SAFTM_CHECK_EQ(1, bias.cols);
311 CheckNoQuantization(bias);
312 layer_bias_.push_back(bias);
313 }
314
315 SAFTM_CHECK(model_->HasSoftmax());
316 layer_weights_.push_back(model_->GetSoftmaxMatrix());
317
318 EmbeddingNetworkParams::Matrix softmax_bias = model_->GetSoftmaxBias();
319 SAFTM_CHECK_EQ(1, softmax_bias.cols);
320 CheckNoQuantization(softmax_bias);
321 layer_bias_.push_back(softmax_bias);
322 }
323
324 } // namespace mobile
325 } // namespace nlp_saft
326