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 "QuantizedLSTM.h"
20
21 #include "CpuExecutor.h"
22 #include "CpuOperationUtils.h"
23 #include "HalInterfaces.h"
24
25 #include "Tracing.h"
26
27 #include <public/gemmlowp.h>
28 #include <tensorflow/lite/kernels/internal/reference/legacy_reference_ops.h>
29 #include <algorithm>
30 #include <vector>
31
32 namespace android {
33 namespace nn {
34
35 namespace {
36
37 using namespace hal;
38
39 template <typename T>
GetBuffer(RunTimeOperandInfo * operand)40 inline T* GetBuffer(RunTimeOperandInfo* operand) {
41 return reinterpret_cast<T*>(operand->buffer);
42 }
43
44 template <typename T>
GetBuffer(const RunTimeOperandInfo * operand)45 inline const T* GetBuffer(const RunTimeOperandInfo* operand) {
46 return reinterpret_cast<const T*>(operand->buffer);
47 }
48
49 using tflite::Dims;
50
51 // The function below is taken from TF Lite implementation in order to decouple
52 // NN API from TF Lite dependency. Original function, with a description of its
53 // parameters and types can be found by this link:
54 // https://github.com/tensorflow/tensorflow/blob/0d697e5fc4c05c699eea0764364104ea500ccc68/tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h#L1926
55 //
56 // clang-format off
57 template <int StateIntegerBits>
quantizedLstmStep(const uint8_t * input_data_uint8,const Dims<4> & input_dims,const uint8_t * prev_activ_data_uint8,const Dims<4> & prev_activ_dims,const uint8_t * weights_data_uint8,const Dims<4> & weights_dims,const int32_t * bias_data_int32,const Dims<4> & bias_dims,const int16_t * prevCellState_data_int16,const Dims<4> & prevCellState_dims,int16_t * output_state_data_int16,const Dims<4> & output_state_dims,uint8_t * output_activ_data_uint8,const Dims<4> & output_activ_dims,uint8_t * concat_temp_data_uint8,const Dims<4> & concat_temp_dims,int16_t * activ_temp_data_int16,const Dims<4> & activ_temp_dims,int32_t weights_zero_point,int32_t accum_multiplier,int accum_shift)58 void quantizedLstmStep(const uint8_t* input_data_uint8, const Dims<4>& input_dims,
59 const uint8_t* prev_activ_data_uint8,
60 const Dims<4>& prev_activ_dims, const uint8_t* weights_data_uint8,
61 const Dims<4>& weights_dims, const int32_t* bias_data_int32,
62 const Dims<4>& bias_dims, const int16_t* prevCellState_data_int16,
63 const Dims<4>& prevCellState_dims, int16_t* output_state_data_int16,
64 const Dims<4>& output_state_dims, uint8_t* output_activ_data_uint8,
65 const Dims<4>& output_activ_dims, uint8_t* concat_temp_data_uint8,
66 const Dims<4>& concat_temp_dims, int16_t* activ_temp_data_int16,
67 const Dims<4>& activ_temp_dims, int32_t weights_zero_point,
68 int32_t accum_multiplier, int accum_shift) {
69 // Gather dimensions information, and perform consistency checks.
70 const int outer_size =
71 MatchingFlatSizeSkipDim(input_dims, 0, prev_activ_dims, prevCellState_dims,
72 output_state_dims, output_activ_dims);
73 TFLITE_CHECK_EQ(ArraySize(weights_dims, 2), 1);
74 TFLITE_CHECK_EQ(ArraySize(weights_dims, 3), 1);
75 const int input_depth = ArraySize(input_dims, 0);
76 const int prev_activ_depth = ArraySize(prev_activ_dims, 0);
77 const int total_input_depth = prev_activ_depth + input_depth;
78 TFLITE_CHECK_EQ(ArraySize(weights_dims, 0), total_input_depth);
79 TFLITE_CHECK_EQ(MatchingArraySize(bias_dims, 1, bias_dims, 2, bias_dims, 3),
80 1);
81 const int intern_activ_depth =
82 MatchingArraySize(weights_dims, 1, bias_dims, 0);
83 TFLITE_CHECK_EQ(intern_activ_depth % 4, 0);
84 const int output_depth =
85 MatchingArraySize(prevCellState_dims, 0, prev_activ_dims, 0,
86 output_state_dims, 0, output_activ_dims, 0);
87 TFLITE_CHECK_EQ(output_depth, intern_activ_depth / 4);
88 const int fc_batches = FlatSizeSkipDim(activ_temp_dims, 0);
89 const int fc_output_depth =
90 MatchingArraySize(weights_dims, 1, activ_temp_dims, 0);
91 const int fc_accum_depth = ArraySize(weights_dims, 0);
92 TFLITE_CHECK_EQ(fc_output_depth, 4 * output_depth);
93
94 // Depth-concatenate prev_activ and input data together.
95 uint8_t const* concat_input_arrays_data[2] = {input_data_uint8,
96 prev_activ_data_uint8};
97 Dims<4> const* concat_input_arrays_dims[2] = {&input_dims, &prev_activ_dims};
98 tflite::reference_ops::Concatenation<tflite::FusedActivationFunctionType::kNone, uint8_t>(
99 0, concat_input_arrays_data, concat_input_arrays_dims, 2,
100 concat_temp_data_uint8, concat_temp_dims);
101
102 // Implementation of the fully connected node inside the LSTM cell.
103 // The operands are 8-bit integers, the accumulators are internally 32bit
104 // integers, and the output is 16-bit fixed-point with 3 integer bits so
105 // the output range is [-2^3, 2^3] == [-8, 8]. The rationale for that
106 // is explained in the function comment above.
107 for (int b = 0; b < fc_batches; ++b) {
108 for (int out_c = 0; out_c < fc_output_depth; ++out_c) {
109 // Internal accumulation.
110 // Initialize accumulator with the bias-value.
111 int32_t accum = bias_data_int32[out_c];
112 // Accumulation loop.
113 for (int d = 0; d < fc_accum_depth; ++d) {
114 int16_t input_val = concat_temp_data_uint8[b * fc_accum_depth + d] - 128;
115 int16_t weights_val =
116 weights_data_uint8[out_c * fc_accum_depth + d] - weights_zero_point;
117 accum += input_val * weights_val;
118 }
119 // Down-scale the final int32 accumulator to the scale used by our
120 // (16-bit, using 3 integer bits) fixed-point format. The quantized
121 // multiplier and shift here have been pre-computed offline
122 // (e.g. by toco).
123 accum =
124 tflite::MultiplyByQuantizedMultiplier(accum, accum_multiplier, accum_shift);
125 // Saturate, cast to int16, and store to the temporary activations array.
126 accum = std::max(-32768, std::min(32767, accum));
127 activ_temp_data_int16[out_c + fc_output_depth * b] = accum;
128 }
129 }
130
131 // Rest of the LSTM cell: tanh and logistic math functions, and some adds
132 // and muls, all done in 16-bit fixed-point.
133 for (int b = 0; b < outer_size; ++b) {
134 for (int c = 0; c < output_depth; ++c) {
135 // Define the fixed-point data types that we will use here. All use
136 // int16 as the underlying integer type i.e. all are 16-bit fixed-point.
137 // They only differ by the number of integral vs. fractional bits,
138 // determining the range of values that they can represent.
139 //
140 // F0 uses 0 integer bits, range [-1, 1].
141 // This is the return type of math functions such as tanh, logistic,
142 // whose range is in [-1, 1].
143 using F0 = gemmlowp::FixedPoint<std::int16_t, 0>;
144 // F3 uses 3 integer bits, range [-8, 8].
145 // This is the range of the previous fully-connected node's output,
146 // which is our input here.
147 using F3 = gemmlowp::FixedPoint<std::int16_t, 3>;
148 // FS uses StateIntegerBits integer bits, range [-2^StateIntegerBits,
149 // 2^StateIntegerBits]. It's used to represent the internal state, whose
150 // number of integer bits is currently dictated by the model. See comment
151 // on the StateIntegerBits template parameter above.
152 using FS = gemmlowp::FixedPoint<std::int16_t, StateIntegerBits>;
153 // Implementation of input gate, using fixed-point logistic function.
154 F3 input_gate_input = F3::FromRaw(
155 activ_temp_data_int16[b * fc_output_depth + 0 * output_depth + c]);
156 F0 input_gate_output = gemmlowp::logistic(input_gate_input);
157 // Implementation of input modulation gate, using fixed-point tanh
158 // function.
159 F3 input_modulation_gate_input = F3::FromRaw(
160 activ_temp_data_int16[b * fc_output_depth + 1 * output_depth + c]);
161 F0 input_modulation_gate_output =
162 gemmlowp::tanh(input_modulation_gate_input);
163 // Implementation of forget gate, using fixed-point logistic function.
164 F3 forget_gate_input = F3::FromRaw(
165 activ_temp_data_int16[b * fc_output_depth + 2 * output_depth + c]);
166 F0 forget_gate_output = gemmlowp::logistic(forget_gate_input);
167 // Implementation of output gate, using fixed-point logistic function.
168 F3 output_gate_input = F3::FromRaw(
169 activ_temp_data_int16[b * fc_output_depth + 3 * output_depth + c]);
170 F0 output_gate_output = gemmlowp::logistic(output_gate_input);
171 // Implementation of internal multiplication nodes, still in fixed-point.
172 F0 input_times_input_modulation =
173 input_gate_output * input_modulation_gate_output;
174 FS prevCellState = FS::FromRaw(prevCellState_data_int16[b * output_depth + c]);
175 FS prevCellState_times_forget_state = forget_gate_output * prevCellState;
176 // Implementation of internal addition node, saturating.
177 FS new_state = gemmlowp::SaturatingAdd(
178 gemmlowp::Rescale<StateIntegerBits>(input_times_input_modulation),
179 prevCellState_times_forget_state);
180 // Implementation of last internal Tanh node, still in fixed-point.
181 // Since a Tanh fixed-point implementation is specialized for a given
182 // number or integer bits, and each specialization can have a substantial
183 // code size, and we already used above a Tanh on an input with 3 integer
184 // bits, and per the table in the above function comment there is no
185 // significant accuracy to be lost by clamping to [-8, +8] for a
186 // 3-integer-bits representation, let us just do that. This helps people
187 // porting this to targets where code footprint must be minimized.
188 F3 new_state_f3 = gemmlowp::Rescale<3>(new_state);
189 F0 output_activ_int16 = output_gate_output * gemmlowp::tanh(new_state_f3);
190 // Store the new internal state back to memory, as 16-bit integers.
191 // Note: here we store the original value with StateIntegerBits, not
192 // the rescaled 3-integer-bits value fed to tanh.
193 output_state_data_int16[b * output_depth + c] = new_state.raw();
194 // Down-scale the output activations to 8-bit integers, saturating,
195 // and store back to memory.
196 int16_t rescaled_output_activ =
197 gemmlowp::RoundingDivideByPOT(output_activ_int16.raw(), 8);
198 int16_t clamped_output_activ =
199 std::max<int16_t>(-128, std::min<int16_t>(127, rescaled_output_activ));
200 output_activ_data_uint8[b * output_depth + c] =
201 128 + clamped_output_activ;
202 }
203 }
204 }
205 // clang-format on
206
207 // The function assigns a 2D matrix to a submatrix of the weights at a given row
208 // and column offsets.
assignWeightsSubmatrix(const RunTimeOperandInfo * submatrix,const int32_t offset_row,const int32_t offset_column,const std::vector<uint32_t> & weightsDims,uint8_t * weights)209 void assignWeightsSubmatrix(const RunTimeOperandInfo* submatrix, const int32_t offset_row,
210 const int32_t offset_column, const std::vector<uint32_t>& weightsDims,
211 uint8_t* weights) {
212 const uint8_t* submatrixValues = GetBuffer<uint8_t>(submatrix);
213 const std::vector<uint32_t> submatrixDims = submatrix->shape().dimensions;
214 for (uint32_t i = 0; i < submatrixDims[0] * submatrixDims[1]; ++i) {
215 const uint32_t row = i / submatrixDims[1];
216 const uint32_t column = i % submatrixDims[1];
217 weights[(row + offset_row) * weightsDims[1] + column + offset_column] = submatrixValues[i];
218 }
219 }
220
221 } // namespace
222
QuantizedLSTMCell(const Operation & operation,RunTimeOperandInfo * operands)223 QuantizedLSTMCell::QuantizedLSTMCell(const Operation& operation, RunTimeOperandInfo* operands) {
224 input_ = GetInput(operation, operands, kInputTensor);
225
226 inputToInputWeights_ = GetInput(operation, operands, kInputToInputWeightsTensor);
227 inputToForgetWeights_ = GetInput(operation, operands, kInputToForgetWeightsTensor);
228 inputToCellWeights_ = GetInput(operation, operands, kInputToCellWeightsTensor);
229 inputToOutputWeights_ = GetInput(operation, operands, kInputToOutputWeightsTensor);
230
231 recurrentToInputWeights_ = GetInput(operation, operands, kRecurrentToInputWeightsTensor);
232 recurrentToForgetWeights_ = GetInput(operation, operands, kRecurrentToForgetWeightsTensor);
233 recurrentToCellWeights_ = GetInput(operation, operands, kRecurrentToCellWeightsTensor);
234 recurrentToOutputWeights_ = GetInput(operation, operands, kRecurrentToOutputWeightsTensor);
235
236 inputGateBias_ = GetInput(operation, operands, kInputGateBiasTensor);
237 forgetGateBias_ = GetInput(operation, operands, kForgetGateBiasTensor);
238 cellGateBias_ = GetInput(operation, operands, kCellGateBiasTensor);
239 outputGateBias_ = GetInput(operation, operands, kOutputGateBiasTensor);
240
241 prevCellState_ = GetInput(operation, operands, kPrevCellStateTensor);
242 prevOutput_ = GetInput(operation, operands, kPrevOutputTensor);
243
244 cellStateOut_ = GetOutput(operation, operands, kCellStateOutTensor);
245 output_ = GetOutput(operation, operands, kOutputTensor);
246 }
247
prepare(const Operation & operation,RunTimeOperandInfo * operands,Shape * cellStateOutShape,Shape * outputShape)248 bool QuantizedLSTMCell::prepare(const Operation& operation, RunTimeOperandInfo* operands,
249 Shape* cellStateOutShape, Shape* outputShape) {
250 auto input = GetInput(operation, operands, kInputTensor);
251 NN_RET_CHECK_EQ(NumDimensions(input), 2);
252 NN_RET_CHECK_EQ(input->scale, 1. / 128.0);
253 NN_RET_CHECK_EQ(input->zeroPoint, 128);
254 const uint32_t numBatches = SizeOfDimension(input, 0);
255 const uint32_t inputSize = SizeOfDimension(input, 1);
256
257 auto prevOutput = GetInput(operation, operands, kPrevOutputTensor);
258 NN_RET_CHECK_EQ(NumDimensions(prevOutput), 2);
259 NN_RET_CHECK_EQ(SizeOfDimension(prevOutput, 0), numBatches);
260 NN_RET_CHECK_EQ(prevOutput->scale, 1. / 128.0);
261 NN_RET_CHECK_EQ(prevOutput->zeroPoint, 128);
262 const uint32_t outputSize = SizeOfDimension(prevOutput, 1);
263
264 auto inputToInputWeights = GetInput(operation, operands, kInputToInputWeightsTensor);
265 const float weightsScale = inputToInputWeights->scale;
266 NN_RET_CHECK(weightsScale != 0);
267 const float weightsZeroPoint = inputToInputWeights->zeroPoint;
268
269 auto checkWeightsShape = [&](const RunTimeOperandInfo* weights, uint32_t columns) -> bool {
270 NN_RET_CHECK_EQ(NumDimensions(weights), 2);
271 NN_RET_CHECK_EQ(SizeOfDimension(weights, 0), outputSize);
272 NN_RET_CHECK_EQ(SizeOfDimension(weights, 1), columns);
273 NN_RET_CHECK_EQ(weights->scale, weightsScale);
274 NN_RET_CHECK_EQ(weights->zeroPoint, weightsZeroPoint);
275 return true;
276 };
277
278 auto inputToForgetWeights = GetInput(operation, operands, kInputToForgetWeightsTensor);
279 auto inputToCellWeights = GetInput(operation, operands, kInputToCellWeightsTensor);
280 auto inputToOutputWeights = GetInput(operation, operands, kInputToOutputWeightsTensor);
281 NN_RET_CHECK(checkWeightsShape(inputToInputWeights, inputSize));
282 NN_RET_CHECK(checkWeightsShape(inputToForgetWeights, inputSize));
283 NN_RET_CHECK(checkWeightsShape(inputToCellWeights, inputSize));
284 NN_RET_CHECK(checkWeightsShape(inputToOutputWeights, inputSize));
285
286 auto recurrentToInputWeights = GetInput(operation, operands, kRecurrentToInputWeightsTensor);
287 auto recurrentToForgetWeights = GetInput(operation, operands, kRecurrentToForgetWeightsTensor);
288 auto recurrentToCellWeights = GetInput(operation, operands, kRecurrentToCellWeightsTensor);
289 auto recurrentToOutputWeights = GetInput(operation, operands, kRecurrentToOutputWeightsTensor);
290 NN_RET_CHECK(checkWeightsShape(recurrentToInputWeights, outputSize));
291 NN_RET_CHECK(checkWeightsShape(recurrentToForgetWeights, outputSize));
292 NN_RET_CHECK(checkWeightsShape(recurrentToCellWeights, outputSize));
293 NN_RET_CHECK(checkWeightsShape(recurrentToOutputWeights, outputSize));
294
295 auto inputGateBias = GetInput(operation, operands, kInputGateBiasTensor);
296 const float biasScale = inputGateBias->scale;
297 NN_RET_CHECK_EQ(biasScale, weightsScale / 128.0);
298 const float biasZeroPoint = inputGateBias->zeroPoint;
299 NN_RET_CHECK_EQ(biasZeroPoint, 0);
300
301 auto checkBiasShape = [&](const RunTimeOperandInfo* bias) -> bool {
302 NN_RET_CHECK_EQ(NumDimensions(bias), 1);
303 NN_RET_CHECK_EQ(SizeOfDimension(bias, 0), outputSize);
304 NN_RET_CHECK_EQ(bias->scale, biasScale);
305 NN_RET_CHECK_EQ(bias->zeroPoint, biasZeroPoint);
306 return true;
307 };
308
309 auto forgetGateBias = GetInput(operation, operands, kForgetGateBiasTensor);
310 auto cellGateBias = GetInput(operation, operands, kCellGateBiasTensor);
311 auto outputGateBias = GetInput(operation, operands, kOutputGateBiasTensor);
312 NN_RET_CHECK(checkBiasShape(inputGateBias));
313 NN_RET_CHECK(checkBiasShape(forgetGateBias));
314 NN_RET_CHECK(checkBiasShape(cellGateBias));
315 NN_RET_CHECK(checkBiasShape(outputGateBias));
316
317 auto prevCellState = GetInput(operation, operands, kPrevCellStateTensor);
318 NN_CHECK_EQ(NumDimensions(prevCellState), 2);
319 NN_CHECK_EQ(SizeOfDimension(prevCellState, 0), numBatches);
320 NN_CHECK_EQ(SizeOfDimension(prevCellState, 1), outputSize);
321 NN_CHECK_EQ(prevCellState->zeroPoint, 0);
322 // Cell state range for quantized LSTM is a function of StateIntegerBits and
323 // can be calculated as:
324 // [-2^StateIntegerBits, 2^StateIntegerBits * 32767/32768].
325 // Therefore, for a fixed StateIntegerBits parameter, cell state scale is
326 // equal to 2^StateIntegerBits * 2^(-15) = 2^(StateIntegerBits - 15) and
327 // therefore:
328 // StateIntegerBits = log2(cell state scale) + 15
329 int stateScaleLog2Rounded;
330 NN_CHECK(tflite::CheckedLog2(prevCellState->scale, &stateScaleLog2Rounded));
331 const int stateIntegerBits = 15 + stateScaleLog2Rounded;
332 // We only support StateIntegerBits == 4
333 NN_CHECK(stateIntegerBits == 4);
334
335 *cellStateOutShape = prevCellState->shape();
336 *outputShape = prevOutput->shape();
337 return true;
338 }
339
340 // The function contatenates 8 input weight matrices into one. Resulting matrix
341 // has a shape [4 * outputSize, outputSize + inputSize]. The matrix is
342 // constructed as follows:
343 // +-----------------------------------+
344 // | recurrentToInput | inputToInput |
345 // |-------------------+---------------|
346 // | recurrentToCell | inputToCell |
347 // |-------------------+---------------|
348 // | recurrentToForget | inputToForget |
349 // |-------------------+---------------|
350 // | recurrentToOutput | inputToOutput |
351 // +-----------------------------------+
concatenateWeights(const std::vector<uint32_t> & weightsDims,uint8_t * weights)352 void QuantizedLSTMCell::concatenateWeights(const std::vector<uint32_t>& weightsDims,
353 uint8_t* weights) {
354 const int outputSize = SizeOfDimension(inputToInputWeights_, 0);
355
356 assignWeightsSubmatrix(inputToInputWeights_, 0 * outputSize, outputSize, weightsDims, weights);
357 assignWeightsSubmatrix(inputToCellWeights_, 1 * outputSize, outputSize, weightsDims, weights);
358 assignWeightsSubmatrix(inputToForgetWeights_, 2 * outputSize, outputSize, weightsDims, weights);
359 assignWeightsSubmatrix(inputToOutputWeights_, 3 * outputSize, outputSize, weightsDims, weights);
360 assignWeightsSubmatrix(recurrentToInputWeights_, 0 * outputSize, 0, weightsDims, weights);
361 assignWeightsSubmatrix(recurrentToCellWeights_, 1 * outputSize, 0, weightsDims, weights);
362 assignWeightsSubmatrix(recurrentToForgetWeights_, 2 * outputSize, 0, weightsDims, weights);
363 assignWeightsSubmatrix(recurrentToOutputWeights_, 3 * outputSize, 0, weightsDims, weights);
364 }
365
366 // The function concatenate four bias vectors of shape [outputSize] into one
367 // vector of shape [4 * outputSize].
concatenateBiases(uint32_t outputSize,int32_t * bias)368 void QuantizedLSTMCell::concatenateBiases(uint32_t outputSize, int32_t* bias) {
369 memcpy(bias + 0 * outputSize, GetBuffer<int32_t>(inputGateBias_), sizeof(int32_t) * outputSize);
370 memcpy(bias + 1 * outputSize, GetBuffer<int32_t>(cellGateBias_), sizeof(int32_t) * outputSize);
371 memcpy(bias + 2 * outputSize, GetBuffer<int32_t>(forgetGateBias_),
372 sizeof(int32_t) * outputSize);
373 memcpy(bias + 3 * outputSize, GetBuffer<int32_t>(outputGateBias_),
374 sizeof(int32_t) * outputSize);
375 }
376
eval()377 bool QuantizedLSTMCell::eval() {
378 NNTRACE_COMP("QuantizedLSTM::eval");
379
380 Shape weightsShape;
381 weightsShape.dimensions = {4 * SizeOfDimension(prevOutput_, 1),
382 SizeOfDimension(input_, 1) + SizeOfDimension(prevOutput_, 1)};
383 std::vector<uint8_t> weights(getNumberOfElements(weightsShape));
384 concatenateWeights(weightsShape.dimensions, weights.data());
385
386 Shape biasShape;
387 biasShape.dimensions = {getSizeOfDimension(weightsShape, 0)};
388 std::vector<int32_t> bias(getNumberOfElements(biasShape));
389 concatenateBiases(SizeOfDimension(prevOutput_, 1), bias.data());
390
391 Shape concatTempShape;
392 concatTempShape.dimensions = {SizeOfDimension(input_, 0), getSizeOfDimension(weightsShape, 1)};
393
394 Shape activationTempShape;
395 activationTempShape.dimensions = {SizeOfDimension(input_, 0),
396 getSizeOfDimension(weightsShape, 0)};
397
398 std::vector<uint8_t> concatTemp(getNumberOfElements(concatTempShape));
399 std::vector<int16_t> activationTemp(getNumberOfElements(activationTempShape));
400
401 // From https://arxiv.org/pdf/1712.05877, for a fully-connected layer,
402 // accumulator multiplier is equal to:
403 // (input scale) * (weights scale) / (fully-connected output scale)
404 // In our case fully-connected output scale is fixed and equal to
405 // 2^(-12) (See LSTMCell definition in TF Lite for more details on that).
406 // But bias scale is set to (input scale) * (weights scale) (also from the
407 // paper), so we can multiply it to an inverse of the fc-output scale to get
408 // the multiplier value:
409 double realAccumMultiplier = 4096 * inputGateBias_->scale;
410 int32_t accumMultiplier;
411 int accumShift;
412 tflite::QuantizeMultiplier(realAccumMultiplier, &accumMultiplier, &accumShift);
413 quantizedLstmStep<4>(
414 // Inputs.
415 GetBuffer<const uint8_t>(input_), convertShapeToDims(input_->shape()),
416 GetBuffer<const uint8_t>(prevOutput_), convertShapeToDims(prevOutput_->shape()),
417 weights.data(), convertShapeToDims(weightsShape), bias.data(),
418 convertShapeToDims(biasShape), GetBuffer<const int16_t>(prevCellState_),
419 convertShapeToDims(prevCellState_->shape()),
420 // Outputs.
421 GetBuffer<int16_t>(cellStateOut_), convertShapeToDims(cellStateOut_->shape()),
422 GetBuffer<uint8_t>(output_), convertShapeToDims(output_->shape()), concatTemp.data(),
423 convertShapeToDims(concatTempShape), activationTemp.data(),
424 convertShapeToDims(activationTempShape), inputToInputWeights_->zeroPoint,
425 accumMultiplier, accumShift);
426 return true;
427 }
428
429 } // namespace nn
430 } // namespace android
431