summaryrefslogtreecommitdiff
path: root/compiler/luci-interpreter/src/kernels/Conv2D.cpp
blob: 56ca96a349ab94c52e43743387c1534a1a6bc8fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*
 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
 * Copyright 2019 The TensorFlow Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "kernels/Conv2D.h"

#include "kernels/Utils.h"

#include <tensorflow/lite/kernels/internal/optimized/legacy_optimized_ops.h>

#include <stdexcept>
#include <thread>

namespace luci_interpreter
{
namespace kernels
{

Conv2D::Conv2D(const Tensor *input, const Tensor *filter, const Tensor *bias, Tensor *output,
               const Conv2DParams &params)
  : KernelWithParams<Conv2DParams>({input, filter, bias}, {output}, params)
{
}

void Conv2D::configure()
{
  // TensorFlow Lite (as of v2.2.0) supports the following combinations of types:
  //     | input filter bias  output |
  // ----+---------------------------+
  // (1) | float float  float float  |
  // (2) | float int8   float float  | hybrid
  // (3) | uint8 uint8  int32 uint8  | quantized
  // (4) | int8  int8   int32 int8   | quantized per channel
  //
  // We only support (1) and (3) for now, and additionally the following:
  //     | input filter bias  output |
  // ----+---------------------------+
  // (5) | int16 int16  int64 int16  |
  //
  if (input()->element_type() == DataType::FLOAT32 && filter()->element_type() == DataType::FLOAT32)
  {
    LUCI_INTERPRETER_CHECK(bias() == nullptr || bias()->element_type() == DataType::FLOAT32);
  }
  else if (input()->element_type() == DataType::U8 && filter()->element_type() == DataType::U8)
  {
    LUCI_INTERPRETER_CHECK(bias() == nullptr || bias()->element_type() == DataType::S32);
  }
  else if (input()->element_type() == DataType::S16 && filter()->element_type() == DataType::S16)
  {
    LUCI_INTERPRETER_CHECK(bias() == nullptr || bias()->element_type() == DataType::S64);
  }
  else
  {
    throw std::runtime_error("Unsupported type.");
  }
  LUCI_INTERPRETER_CHECK(output()->element_type() == input()->element_type());

  const Shape &input_shape = input()->shape();
  const Shape &filter_shape = filter()->shape();
  LUCI_INTERPRETER_CHECK(input_shape.num_dims() == 4 && filter_shape.num_dims() == 4);

  const int32_t batches = input_shape.dim(0);
  const int32_t input_height = input_shape.dim(1);
  const int32_t input_width = input_shape.dim(2);
  const int32_t output_depth = filter_shape.dim(0);
  const int32_t filter_height = filter_shape.dim(1);
  const int32_t filter_width = filter_shape.dim(2);
  LUCI_INTERPRETER_CHECK(filter_shape.dim(3) == input_shape.dim(3));

  LUCI_INTERPRETER_CHECK(bias() == nullptr || (bias()->shape().num_dims() == 1 &&
                                               bias()->shape().dim(0) == output_depth));

  const int32_t output_height =
    computeOutputSize(_params.padding, input_height, filter_height, _params.stride_height,
                      _params.dilation_height_factor);
  const int32_t output_width =
    computeOutputSize(_params.padding, input_width, filter_width, _params.stride_width,
                      _params.dilation_width_factor);

  _padding_height = computePadding(_params.stride_height, _params.dilation_height_factor,
                                   input_height, filter_height, output_height);
  _padding_width = computePadding(_params.stride_width, _params.dilation_width_factor, input_width,
                                  filter_width, output_width);

  output()->resize({batches, output_height, output_width, output_depth});

  // Allocate tensor for Im2Col, if needed.
  // The checks here should be aligned with the actual implementation.
  const bool need_dilated_im2col =
    _params.dilation_height_factor != 1 || _params.dilation_width_factor != 1;
  const bool need_non_dilated_im2col = _params.stride_height != 1 || _params.stride_width != 1 ||
                                       filter_height != 1 || filter_width != 1;
  const bool need_im2col =
    input()->element_type() != DataType::S16 && (need_dilated_im2col || need_non_dilated_im2col);
  if (need_im2col)
  {
    const int input_depth = input_shape.dim(3);
    Shape im2col_shape{batches, output_height, output_width,
                       input_depth * filter_height * filter_width};
    try
    {
      _im2col =
        std::make_unique<Tensor>(input()->element_type(), im2col_shape, AffineQuantization{}, "");
    }
    catch (std::bad_alloc &ba)
    {
      // Failed memory allocation
      _im2col = nullptr;
    }
  }
}

void Conv2D::execute() const
{
  switch (input()->element_type())
  {
    case DataType::FLOAT32:
      if (filter()->element_type() == DataType::FLOAT32)
      {
        evalFloat();
        break;
      }
      throw std::runtime_error("Unsupported type.");
    case DataType::U8:
      if (filter()->scales().size() == 1)
      {
        evalQuantized();
      }
      else if (filter()->scales().size() > 1)
      {
        LUCI_INTERPRETER_CHECK(filter()->shape().num_dims() == 4);
        LUCI_INTERPRETER_CHECK(filter()->scales().size() ==
                               static_cast<size_t>(filter()->shape().dim(0)));
        evalQuantizedPerChannel();
      }
      break;
    case DataType::S16:
      evalQuantizedS16();
      break;
    default:
      throw std::runtime_error("Unsupported type.");
  }
  if (!!_im2col)
    _im2col->deallocate();
}

void Conv2D::evalFloat() const
{
  float activation_min{};
  float activation_max{};
  calculateActivationRange(_params.activation, &activation_min, &activation_max);

  tflite::ConvParams params{};
  params.padding_values.height = _padding_height;
  params.padding_values.width = _padding_width;
  params.stride_height = _params.stride_height;
  params.stride_width = _params.stride_width;
  params.dilation_height_factor = _params.dilation_height_factor;
  params.dilation_width_factor = _params.dilation_width_factor;
  params.float_activation_min = activation_min;
  params.float_activation_max = activation_max;

  if (_im2col)
  {
    try
    {
      tflite::optimized_ops::Conv(
        params, getTensorShape(input()), getTensorData<float>(input()), getTensorShape(filter()),
        getTensorData<float>(filter()), getTensorShape(bias()), getTensorData<float>(bias()),
        getTensorShape(output()), getTensorData<float>(output()), getTensorShape(_im2col.get()),
        getTensorData<float>(_im2col.get()));
    }
    catch (std::bad_alloc &ba)
    {
      // Failed memory allocation
      _im2col->deallocate();

      tflite::reference_ops::Conv(
        params, getTensorShape(input()), getTensorData<float>(input()), getTensorShape(filter()),
        getTensorData<float>(filter()), getTensorShape(bias()), getTensorData<float>(bias()),
        getTensorShape(output()), getTensorData<float>(output()), tflite::RuntimeShape(), nullptr);
    }
  }
  else
    tflite::reference_ops::Conv(
      params, getTensorShape(input()), getTensorData<float>(input()), getTensorShape(filter()),
      getTensorData<float>(filter()), getTensorShape(bias()), getTensorData<float>(bias()),
      getTensorShape(output()), getTensorData<float>(output()), tflite::RuntimeShape(), nullptr);
}

void Conv2D::evalQuantized() const
{
  const auto input_scale = static_cast<double>(input()->scale());
  const auto filter_scale = static_cast<double>(filter()->scale());
  const auto output_scale = static_cast<double>(output()->scale());

  const double real_multiplier = input_scale * filter_scale / output_scale;
  int32_t output_multiplier{};
  int output_shift{};
  quantizeMultiplier(real_multiplier, &output_multiplier, &output_shift);

  int32_t activation_min{};
  int32_t activation_max{};
  calculateActivationRangeQuantized(_params.activation, output(), &activation_min, &activation_max);

  tflite::ConvParams params{};
  params.padding_values.height = _padding_height;
  params.padding_values.width = _padding_width;
  params.stride_height = _params.stride_height;
  params.stride_width = _params.stride_width;
  params.dilation_height_factor = _params.dilation_height_factor;
  params.dilation_width_factor = _params.dilation_width_factor;
  // The kernel expects input and filter zero points to be negated.
  params.input_offset = -input()->zero_point();    // Note the '-'.
  params.weights_offset = -filter()->zero_point(); // Note the '-'.
  params.output_offset = output()->zero_point();
  params.output_multiplier = output_multiplier;
  params.output_shift = output_shift;
  params.quantized_activation_min = activation_min;
  params.quantized_activation_max = activation_max;

  // TODO This should only be done once (although it takes only a few microseconds).
  //  Also, the user should be able to adjust the number of threads.
  auto gemmlowp_context = std::make_unique<gemmlowp::GemmContext>();
  gemmlowp_context->set_max_num_threads(static_cast<int>(std::thread::hardware_concurrency()));

  tflite::optimized_ops::Conv(
    params, getTensorShape(input()), getTensorData<uint8_t>(input()), getTensorShape(filter()),
    getTensorData<uint8_t>(filter()), getTensorShape(bias()), getTensorData<int32_t>(bias()),
    getTensorShape(output()), getTensorData<uint8_t>(output()), getTensorShape(_im2col.get()),
    getTensorData<uint8_t>(_im2col.get()), gemmlowp_context.get());
}

void Conv2D::evalQuantizedPerChannel() const
{
  const auto *input_data = getTensorData<uint8_t>(input());
  const auto *filter_data = getTensorData<uint8_t>(filter());
  const auto *bias_data = getTensorData<int32_t>(bias());
  auto *output_data = getTensorData<uint8_t>(output());

  const Shape &input_shape = input()->shape();
  const Shape &filter_shape = filter()->shape();
  const Shape &output_shape = output()->shape();

  const int32_t batches = input_shape.dim(0);
  const int32_t input_height = input_shape.dim(1);
  const int32_t input_width = input_shape.dim(2);
  const int32_t input_depth = input_shape.dim(3);
  const int32_t output_depth = filter_shape.dim(0);
  const int32_t filter_height = filter_shape.dim(1);
  const int32_t filter_width = filter_shape.dim(2);
  const int32_t output_height = output_shape.dim(1);
  const int32_t output_width = output_shape.dim(2);

  const int32_t stride_height = _params.stride_height;
  const int32_t stride_width = _params.stride_width;
  const int32_t dilation_height_factor = _params.dilation_height_factor;
  const int32_t dilation_width_factor = _params.dilation_width_factor;

  int32_t activation_min{};
  int32_t activation_max{};
  calculateActivationRangeQuantized(_params.activation, output(), &activation_min, &activation_max);

  const std::vector<double> effective_output_scale =
    getQuantizedConvolutionMultiplers(input()->scale(), filter()->scales(), output()->scale());

  const std::vector<ChannelQuantMultipliers> multipliers_raw =
    quantizeMultipliers(effective_output_scale);
  BroadcastableWrapper<ChannelQuantMultipliers> quant_multipliers(multipliers_raw);

  for (int32_t batch = 0; batch < batches; ++batch)
  {
    for (int32_t out_y = 0; out_y < output_height; ++out_y)
    {
      for (int32_t out_x = 0; out_x < output_width; ++out_x)
      {
        for (int32_t out_c = 0; out_c < output_depth; ++out_c)
        {
          const int32_t in_y_origin = out_y * stride_height - _padding_height;
          const int32_t in_x_origin = out_x * stride_width - _padding_width;
          int32_t acc = 0;
          for (int32_t filter_y = 0; filter_y < filter_height; ++filter_y)
          {
            for (int32_t filter_x = 0; filter_x < filter_width; ++filter_x)
            {
              const int32_t in_y = in_y_origin + dilation_height_factor * filter_y;
              const int32_t in_x = in_x_origin + dilation_width_factor * filter_x;
              if ((in_y >= 0 && in_y < input_height) && (in_x >= 0 && in_x < input_width))
              {
                for (int32_t in_c = 0; in_c < input_depth; ++in_c)
                {
                  const uint8_t input_val =
                    input_data[calcOffset(input_shape, batch, in_y, in_x, in_c)];
                  const uint8_t filter_val =
                    filter_data[calcOffset(filter_shape, out_c, filter_y, filter_x, in_c)];
                  acc += static_cast<int32_t>(input_val - input()->zero_point()) *
                         static_cast<int32_t>(filter_val - filter()->zero_points()[out_c]);
                }
              }
            }
          }
          if (bias_data)
          {
            acc += bias_data[out_c];
          }

          int32_t scaled_acc = tflite::MultiplyByQuantizedMultiplier(
            acc, quant_multipliers[out_c].multiplier, quant_multipliers[out_c].shift);

          scaled_acc += output()->zero_point();
          scaled_acc = std::max(scaled_acc, activation_min);
          scaled_acc = std::min(scaled_acc, activation_max);
          output_data[calcOffset(output_shape, batch, out_y, out_x, out_c)] = scaled_acc;
        }
      }
    }
  }
}

void Conv2D::evalQuantizedS16() const
{
  const auto *input_data = getTensorData<int16_t>(input());
  const auto *filter_data = getTensorData<int16_t>(filter());
  const auto *bias_data = getTensorData<int64_t>(bias());
  auto *output_data = getTensorData<int16_t>(output());

  const Shape &input_shape = input()->shape();
  const Shape &filter_shape = filter()->shape();
  const Shape &output_shape = output()->shape();

  const int32_t batches = input_shape.dim(0);
  const int32_t input_height = input_shape.dim(1);
  const int32_t input_width = input_shape.dim(2);
  const int32_t input_depth = input_shape.dim(3);
  const int32_t output_depth = filter_shape.dim(0);
  const int32_t filter_height = filter_shape.dim(1);
  const int32_t filter_width = filter_shape.dim(2);
  const int32_t output_height = output_shape.dim(1);
  const int32_t output_width = output_shape.dim(2);

  const int32_t stride_height = _params.stride_height;
  const int32_t stride_width = _params.stride_width;
  const int32_t dilation_height_factor = _params.dilation_height_factor;
  const int32_t dilation_width_factor = _params.dilation_width_factor;

  int32_t activation_min{};
  int32_t activation_max{};
  calculateActivationRangeQuantized(_params.activation, output(), &activation_min, &activation_max);

  const std::vector<double> effective_output_scale =
    getQuantizedConvolutionMultiplers(input()->scale(), filter()->scales(), output()->scale());

  const std::vector<ChannelQuantMultipliers> multipliers_raw =
    quantizeMultipliers(effective_output_scale);
  BroadcastableWrapper<ChannelQuantMultipliers> multipliers(multipliers_raw);

  for (int32_t batch = 0; batch < batches; ++batch)
  {
    for (int32_t out_y = 0; out_y < output_height; ++out_y)
    {
      for (int32_t out_x = 0; out_x < output_width; ++out_x)
      {
        for (int32_t out_c = 0; out_c < output_depth; ++out_c)
        {
          const int32_t in_y_origin = out_y * stride_height - _padding_height;
          const int32_t in_x_origin = out_x * stride_width - _padding_width;
          int64_t acc = 0;
          for (int32_t filter_y = 0; filter_y < filter_height; ++filter_y)
          {
            for (int32_t filter_x = 0; filter_x < filter_width; ++filter_x)
            {
              const int32_t in_y = in_y_origin + dilation_height_factor * filter_y;
              const int32_t in_x = in_x_origin + dilation_width_factor * filter_x;
              if ((in_y >= 0 && in_y < input_height) && (in_x >= 0 && in_x < input_width))
              {
                for (int32_t in_c = 0; in_c < input_depth; ++in_c)
                {
                  const int16_t input_val =
                    input_data[calcOffset(input_shape, batch, in_y, in_x, in_c)];
                  const int16_t filter_val =
                    filter_data[calcOffset(filter_shape, out_c, filter_y, filter_x, in_c)];
                  acc += static_cast<int64_t>(input_val) * static_cast<int64_t>(filter_val);
                }
              }
            }
          }
          if (bias_data)
          {
            acc += bias_data[out_c];
          }

          int32_t scaled_acc = tflite::MultiplyByQuantizedMultiplier(
            acc, multipliers[out_c].multiplier, multipliers[out_c].shift);

          scaled_acc = std::max(scaled_acc, activation_min);
          scaled_acc = std::min(scaled_acc, activation_max);

          output_data[calcOffset(output_shape, batch, out_y, out_x, out_c)] = scaled_acc;
        }
      }
    }
  }
}

} // namespace kernels
} // namespace luci_interpreter