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