1 /*
2  * Copyright (C) 2010-2021 Arm Limited or its affiliates. All rights reserved.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Licensed under the Apache License, Version 2.0 (the License); you may
7  * not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an AS IS BASIS, WITHOUT
14  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 /* ----------------------------------------------------------------------
20  * Project:      CMSIS NN Library
21  * Title:        arm_convolve_s8.c
22  * Description:  s8 version of convolution using symmetric quantization.
23  *
24  * $Date:        January 26, 2021
25  * $Revision:    V.2.0.4
26  *
27  * Target Processor:  Cortex-M cores
28  *
29  * -------------------------------------------------------------------- */
30 
31 #include "arm_nnfunctions.h"
32 #include "arm_nnsupportfunctions.h"
33 
34 /**
35  *  @ingroup groupNN
36  */
37 
38 /**
39  * @addtogroup NNConv
40  * @{
41  */
42 
43 /*
44  * Basic s8 convolution function.
45  *
46  * Refer header file for details. Optimal use case for the DSP/MVE implementation is when input and output channels
47  * are multiples of 4 or atleast greater than 4.
48  *
49  */
50 
arm_convolve_s8(const cmsis_nn_context * ctx,const cmsis_nn_conv_params * conv_params,const cmsis_nn_per_channel_quant_params * quant_params,const cmsis_nn_dims * input_dims,const q7_t * input_data,const cmsis_nn_dims * filter_dims,const q7_t * filter_data,const cmsis_nn_dims * bias_dims,const int32_t * bias_data,const cmsis_nn_dims * output_dims,q7_t * output_data)51 arm_status arm_convolve_s8(const cmsis_nn_context *ctx,
52                            const cmsis_nn_conv_params *conv_params,
53                            const cmsis_nn_per_channel_quant_params *quant_params,
54                            const cmsis_nn_dims *input_dims,
55                            const q7_t *input_data,
56                            const cmsis_nn_dims *filter_dims,
57                            const q7_t *filter_data,
58                            const cmsis_nn_dims *bias_dims,
59                            const int32_t *bias_data,
60                            const cmsis_nn_dims *output_dims,
61                            q7_t *output_data)
62 {
63     (void)bias_dims;
64     q15_t *buffer_a = (q15_t *)ctx->buf;
65 
66     const uint16_t input_batches = input_dims->n;
67     const uint16_t input_x = input_dims->w;
68     const uint16_t input_y = input_dims->h;
69     const uint16_t input_ch = input_dims->c;
70     const uint16_t kernel_x = filter_dims->w;
71     const uint16_t kernel_y = filter_dims->h;
72     const uint16_t output_x = output_dims->w;
73     const uint16_t output_y = output_dims->h;
74     const uint16_t output_ch = output_dims->c;
75 
76     const uint16_t pad_x = conv_params->padding.w;
77     const uint16_t pad_y = conv_params->padding.h;
78     const uint16_t stride_x = conv_params->stride.w;
79     const uint16_t stride_y = conv_params->stride.h;
80 
81     const int32_t input_offset = conv_params->input_offset;
82     const int32_t out_offset = conv_params->output_offset;
83     const int32_t out_activation_min = conv_params->activation.min;
84     const int32_t out_activation_max = conv_params->activation.max;
85     int32_t *output_mult = quant_params->multiplier;
86     int32_t *output_shift = quant_params->shift;
87 
88     int i_batch;
89     for (i_batch = 0; i_batch < input_batches; i_batch++)
90     {
91 #if defined(ARM_MATH_MVEI)
92         /* Generate upto four columns from the input tensor a GEMM computation */
93         q7_t *im2col_buf = (q7_t *)buffer_a;
94         q7_t *out = output_data;
95         int32_t buffer_fill_cnt = 0;
96         int32_t padded = 0;
97         const int32_t num_elem = kernel_x * kernel_y * input_ch;
98 
99         /* This part implements the im2col function */
100         for (int i_out_y = 0; i_out_y < output_y; i_out_y++)
101         {
102             for (int i_out_x = 0; i_out_x < output_x; i_out_x++)
103             {
104                 for (int i_ker_y = i_out_y * stride_y - pad_y; i_ker_y < i_out_y * stride_y - pad_y + kernel_y;
105                      i_ker_y++)
106                 {
107                     for (int i_ker_x = i_out_x * stride_x - pad_x; i_ker_x < i_out_x * stride_x - pad_x + kernel_x;
108                          i_ker_x++)
109                     {
110                         if (i_ker_y < 0 || i_ker_y >= input_y || i_ker_x < 0 || i_ker_x >= input_x)
111                         {
112                             memset(im2col_buf, (int8_t)-input_offset, sizeof(q7_t) * input_ch);
113                             padded = 1;
114                         }
115                         else
116                         {
117                             arm_memcpy_q7(im2col_buf, input_data + (i_ker_y * input_x + i_ker_x) * input_ch, input_ch);
118                         }
119                         im2col_buf += input_ch;
120                     }
121                 }
122 
123                 buffer_fill_cnt++;
124 
125                 /* Computation is filed for every 4 columns */
126                 if (buffer_fill_cnt == 4 && (padded == 0))
127                 {
128                     buffer_fill_cnt = 0;
129                     for (int i_out_ch = 0; i_out_ch < output_ch; i_out_ch++)
130                     {
131                         int32_t sum_row;
132                         int32_t acc[4];
133 
134                         (void)arm_nn_mat_mul_core_4x_s8(
135                             num_elem, num_elem, (q7_t *)buffer_a, filter_data + num_elem * i_out_ch, &sum_row, acc);
136                         int32x4_t s_offset = vdupq_n_s32(sum_row);
137 
138                         int32x4_t res = vldrwq_s32(acc);
139                         s_offset = vmulq_n_s32(s_offset, input_offset);
140                         if (bias_data)
141                         {
142                             res = vaddq_n_s32(res, bias_data[i_out_ch]);
143                         }
144                         res = vaddq_s32(res, s_offset);
145                         res = arm_requantize_mve(res, output_mult[i_out_ch], output_shift[i_out_ch]);
146                         res = vaddq_n_s32(res, out_offset);
147 
148                         res = vmaxq_s32(res, vdupq_n_s32(out_activation_min));
149                         res = vminq_s32(res, vdupq_n_s32(out_activation_max));
150 
151                         const uint32x4_t scatter_offset = {0, output_ch, output_ch * 2, output_ch * 3};
152                         vstrbq_scatter_offset_s32(out, scatter_offset, res);
153                         out++;
154                     }
155                     out += (3 * output_ch);
156                     im2col_buf = (q7_t *)buffer_a;
157                 }
158                 else if (buffer_fill_cnt == 4 && (padded != 0))
159                 {
160                     buffer_fill_cnt = 0;
161                     out = arm_nn_mat_mult_s8(filter_data,
162                                              (q7_t *)buffer_a,
163                                              output_ch,
164                                              4,
165                                              output_shift,
166                                              output_mult,
167                                              out_offset,
168                                              input_offset,
169                                              0,
170                                              out_activation_min,
171                                              out_activation_max,
172                                              num_elem,
173                                              bias_data,
174                                              out);
175 
176                     im2col_buf = (q7_t *)buffer_a;
177                     padded = 0;
178                 }
179             }
180         }
181         /* Handle left over columns */
182         if (buffer_fill_cnt != 0)
183         {
184             out = arm_nn_mat_mult_s8(filter_data,
185                                      (q7_t *)buffer_a,
186                                      output_ch,
187                                      buffer_fill_cnt,
188                                      output_shift,
189                                      output_mult,
190                                      out_offset,
191                                      input_offset,
192                                      0,
193                                      out_activation_min,
194                                      out_activation_max,
195                                      num_elem,
196                                      bias_data,
197                                      out);
198         }
199 
200 #elif defined(ARM_MATH_DSP)
201         int32_t i_out_y, i_out_x, i_ker_y, i_ker_x;
202 
203         /* Generate two columns from the input tensor a GEMM computation */
204         q15_t *two_column_buf = buffer_a;
205         q7_t *out = output_data;
206 
207         /* This part implements the im2col function */
208         for (i_out_y = 0; i_out_y < output_y; i_out_y++)
209         {
210             for (i_out_x = 0; i_out_x < output_x; i_out_x++)
211             {
212                 for (i_ker_y = i_out_y * stride_y - pad_y; i_ker_y < i_out_y * stride_y - pad_y + kernel_y; i_ker_y++)
213                 {
214                     for (i_ker_x = i_out_x * stride_x - pad_x; i_ker_x < i_out_x * stride_x - pad_x + kernel_x;
215                          i_ker_x++)
216                     {
217                         if (i_ker_y < 0 || i_ker_y >= input_y || i_ker_x < 0 || i_ker_x >= input_x)
218                         {
219                             /* Filling 0 for out-of-bound paddings */
220                             memset(two_column_buf, 0, sizeof(q15_t) * input_ch);
221                         }
222                         else
223                         {
224                             /* Copying the pixel data to column */
225                             arm_q7_to_q15_with_offset(input_data + (i_ker_y * input_x + i_ker_x) * input_ch,
226                                                       two_column_buf,
227                                                       input_ch,
228                                                       input_offset);
229                         }
230                         two_column_buf += input_ch;
231                     }
232                 }
233 
234                 /* Computation is filed for every 2 columns */
235                 if (two_column_buf == buffer_a + 2 * input_ch * kernel_y * kernel_x)
236                 {
237                     out = arm_nn_mat_mult_kernel_s8_s16(filter_data,
238                                                         buffer_a,
239                                                         output_ch,
240                                                         output_shift,
241                                                         output_mult,
242                                                         out_offset,
243                                                         out_activation_min,
244                                                         out_activation_max,
245                                                         input_ch * kernel_y * kernel_x,
246                                                         bias_data,
247                                                         out);
248 
249                     /* counter reset */
250                     two_column_buf = buffer_a;
251                 }
252             }
253         }
254 
255         /* left-over because odd number of output pixels */
256         if (two_column_buf != buffer_a)
257         {
258             const q7_t *ker_a = filter_data;
259             int i;
260 
261             for (i = 0; i < output_ch; i++)
262             {
263                 /* Load the accumulator with bias first */
264                 q31_t sum = 0;
265                 if (bias_data)
266                 {
267                     sum = bias_data[i];
268                 }
269 
270                 /* Point to the beginning of the im2col buffer where the input is available as a rearranged column */
271                 const q15_t *ip_as_col = buffer_a;
272 
273                 /* 4 multiply and accumulates are done in one loop. */
274                 uint16_t col_count = (input_ch * kernel_y * kernel_x) >> 2;
275 
276                 while (col_count)
277                 {
278                     q31_t ker_a1, ker_a2;
279                     q31_t ip_b1, ip_b2;
280 
281                     ker_a = read_and_pad(ker_a, &ker_a1, &ker_a2);
282 
283                     ip_b1 = arm_nn_read_q15x2_ia(&ip_as_col);
284                     sum = __SMLAD(ker_a1, ip_b1, sum);
285                     ip_b2 = arm_nn_read_q15x2_ia(&ip_as_col);
286                     sum = __SMLAD(ker_a2, ip_b2, sum);
287 
288                     col_count--;
289                 }
290                 /* Handle left over mac */
291                 col_count = input_ch * kernel_y * kernel_x & 0x3;
292                 while (col_count)
293                 {
294                     q7_t ker_a1 = *ker_a++;
295                     q15_t ip_b1 = *ip_as_col++;
296                     sum += ker_a1 * ip_b1;
297                     col_count--;
298                 }
299 
300                 sum = arm_nn_requantize(sum, output_mult[i], output_shift[i]);
301                 sum += out_offset;
302                 sum = MAX(sum, out_activation_min);
303                 sum = MIN(sum, out_activation_max);
304                 *out++ = (q7_t)sum;
305             }
306         }
307 #else
308         /* Run the following code as reference implementation for Cortex-M0 and Cortex-M3 */
309         (void)buffer_a;
310         int32_t i_out_ch, i_out_y, i_out_x, i_input_ch, i_ker_y, i_ker_x;
311         int32_t conv_out;
312 
313         for (i_out_ch = 0; i_out_ch < output_ch; i_out_ch++)
314         {
315             for (i_out_y = 0; i_out_y < output_y; i_out_y++)
316             {
317                 for (i_out_x = 0; i_out_x < output_x; i_out_x++)
318                 {
319                     conv_out = 0;
320 
321                     const int32_t base_idx_y = stride_y * i_out_y - pad_y;
322                     const int32_t base_idx_x = stride_x * i_out_x - pad_x;
323 
324                     const int32_t ker_y_start = MAX(0, -base_idx_y);
325                     const int32_t ker_x_start = MAX(0, -base_idx_x);
326 
327                     const int32_t ker_y_end = MIN(kernel_y, input_y - base_idx_y);
328                     const int32_t ker_x_end = MIN(kernel_x, input_x - base_idx_x);
329 
330                     for (i_ker_y = ker_y_start; i_ker_y < ker_y_end; i_ker_y++)
331                     {
332                         for (i_ker_x = ker_x_start; i_ker_x < ker_x_end; i_ker_x++)
333                         {
334                             const int32_t in_row = base_idx_y + i_ker_y;
335                             const int32_t in_col = base_idx_x + i_ker_x;
336                             for (i_input_ch = 0; i_input_ch < input_ch; i_input_ch++)
337                             {
338                                 conv_out +=
339                                     (input_data[(in_row * input_x + in_col) * input_ch + i_input_ch] + input_offset) *
340                                     filter_data[i_out_ch * input_ch * kernel_y * kernel_x +
341                                                 (i_ker_y * kernel_x + i_ker_x) * input_ch + i_input_ch];
342                             }
343                         }
344                     }
345                     if (bias_data)
346                     {
347                         conv_out += bias_data[i_out_ch];
348                     }
349                     conv_out = arm_nn_requantize(conv_out, output_mult[i_out_ch], output_shift[i_out_ch]);
350                     conv_out += out_offset;
351                     conv_out = MAX(conv_out, out_activation_min);
352                     conv_out = MIN(conv_out, out_activation_max);
353                     output_data[i_out_ch + (i_out_y * output_x + i_out_x) * output_ch] = (int8_t)conv_out;
354                 }
355             }
356         }
357 #endif
358         /* Advance to the next batch */
359         input_data += (input_x * input_y * input_ch);
360         output_data += (output_x * output_y * output_ch);
361     }
362 
363     /* Return to application */
364     return ARM_MATH_SUCCESS;
365 }
366 
arm_convolve_s8_get_buffer_size(const cmsis_nn_dims * input_dims,const cmsis_nn_dims * filter_dims)367 int32_t arm_convolve_s8_get_buffer_size(const cmsis_nn_dims *input_dims, const cmsis_nn_dims *filter_dims)
368 {
369 #if defined(ARM_MATH_DSP)
370     return (2 * input_dims->c * filter_dims->w * filter_dims->h) * (int32_t)sizeof(int16_t);
371 #else
372     (void)input_dims;
373     (void)filter_dims;
374     return 0;
375 #endif
376 }
377 
378 /**
379  * @} end of NNConv group
380  */
381