Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PackAWithIm2Col.cc « src - github.com/marian-nmt/FBGEMM.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 367a7902c72bdcaa42792197ea153b8cf33ca2db (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
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 * All rights reserved.
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
#include <cpuinfo.h>
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <numeric>

#include "fbgemm/Fbgemm.h"

namespace fbgemm {

template <typename T, typename accT, int SPATIAL_DIM>
PackAWithIm2Col<T, accT, SPATIAL_DIM>::PackAWithIm2Col(
    const conv_param_t<SPATIAL_DIM>& conv_p,
    const T* sdata,
    inpType* pmat,
    int32_t zero_pt,
    int32_t* row_offset)
    : PackMatrix<PackAWithIm2Col<T, accT, SPATIAL_DIM>, T, accT>(
          conv_p.MB *
              std::accumulate(
                  conv_p.OUT_DIM.begin(),
                  conv_p.OUT_DIM.end(),
                  1,
                  std::multiplies<int>()),
          std::accumulate(
              conv_p.K.begin(),
              conv_p.K.end(),
              1,
              std::multiplies<int>()) *
              conv_p.IC,
          pmat,
          conv_p.G),
      conv_p_(conv_p),
      sdata_(sdata),
      zero_pt_(zero_pt) {
  static_assert(
      SPATIAL_DIM == 2 || SPATIAL_DIM == 3, "unsupported conv dimension ");
  if (cpuinfo_has_x86_avx512f()) {
    BaseType::brow_ = PackingTraits<T, accT, inst_set_t::avx512>::MCB;
    BaseType::bcol_ = PackingTraits<T, accT, inst_set_t::avx512>::KCB;
    row_interleave_B_ =
        PackingTraits<T, accT, inst_set_t::avx512>::ROW_INTERLEAVE;
  } else if (cpuinfo_has_x86_avx2()) {
    BaseType::brow_ = PackingTraits<T, accT, inst_set_t::avx2>::MCB;
    BaseType::bcol_ = PackingTraits<T, accT, inst_set_t::avx2>::KCB;
    row_interleave_B_ =
        PackingTraits<T, accT, inst_set_t::avx2>::ROW_INTERLEAVE;
  } else {
    // TODO: Have default slower path
    assert(0 && "unsupported architecure");
  }
  if (BaseType::numCols() % conv_p.G != 0) {
    throw std::runtime_error(
        "groups = " + std::to_string(conv_p.G) +
        " does not divide numCols = " + std::to_string(BaseType::numCols()));
  }
  if (pmat) {
    BaseType::buf_ = pmat;
  } else {
    BaseType::bufAllocatedHere_ = true;
    BaseType::buf_ = static_cast<T*>(
        fbgemmAlignedAlloc(64, BaseType::brow_ * BaseType::bcol_ * sizeof(T)));
    // aligned_alloc(64, BaseType::brow_ * BaseType::bcol_ * sizeof(T)));
  }
  if (row_offset) {
    rowOffsetAllocatedHere = false;
    row_offset_ = row_offset;
  } else {
    rowOffsetAllocatedHere = true;
    row_offset_ = static_cast<int32_t*>(
        fbgemmAlignedAlloc(64, BaseType::brow_ * sizeof(int32_t)));
  }
}

template <typename T, typename accT, int SPATIAL_DIM>
void PackAWithIm2Col<T, accT, SPATIAL_DIM>::pack(const block_type_t& block) {
  block_type_t block_p = {block.row_start,
                          block.row_size,
                          block.col_start,
                          (block.col_size + row_interleave_B_ - 1) /
                              row_interleave_B_ * row_interleave_B_};
  BaseType::packedBlock(block_p);
  T* out = BaseType::getBuf();
  // accumulate into row offset?
  bool row_offset_acc =
      (block.col_start % (this->numCols() / this->numGroups())) != 0;
  int32_t* row_offset_buf = getRowOffsetBuffer();

  bool point_wise = true;
  for (int d = 0; d < SPATIAL_DIM; ++d) {
    if (conv_p_.K[d] != 1 || conv_p_.pad[d] != 0 || conv_p_.stride[d] != 1 ||
        conv_p_.dilation[d] != 1) {
      point_wise = false;
      break;
    }
  }
  for (int d = SPATIAL_DIM; d < SPATIAL_DIM * 2; ++d) {
    if (conv_p_.pad[d] != 0) {
      point_wise = false;
      break;
    }
  }

  if (point_wise) {
    int32_t ld = this->numCols();
    for (int i = block.row_start; i < block.row_start + block.row_size; ++i) {
      int buf_idx = i - block.row_start;
      memcpy(
          out + buf_idx * BaseType::blockColSize(),
          sdata_ + i * ld + block.col_start,
          block.col_size * sizeof(T));
      // zero fill
      for (int j = block.col_size; j < block_p.col_size; ++j) {
        out[buf_idx * BaseType::blockColSize() + j] = 0;
      }
      int32_t row_sum =
          row_offset_acc ? row_offset_buf[i - block.row_start] : 0;
      __m256i sum_v = _mm256_setzero_si256();
      __m256i one_epi16_v = _mm256_set1_epi16(1);
      __m256i one_epi8_v = _mm256_set1_epi8(1);
      for (int j = block.col_start;
           j < block.col_start + block.col_size / 32 * 32;
           j += 32) {
        __m256i src_v = _mm256_loadu_si256(
            reinterpret_cast<__m256i const*>(sdata_ + i * ld + j));
        sum_v = _mm256_add_epi32(
            sum_v,
            _mm256_madd_epi16(
                _mm256_maddubs_epi16(src_v, one_epi8_v), one_epi16_v));
      }
      for (int j = block.col_start + block.col_size / 32 * 32;
           j < block.col_start + block.col_size;
           ++j) {
        row_sum += sdata_[i * ld + j];
      }
      // alignas(64) std::array<int32_t, 8> temp;
      alignas(64) std::int32_t temp[8];
      //_mm256_store_si256(reinterpret_cast<__m256i*>(temp.data()), sum_v);
      _mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v);
      for (int k = 0; k < 8; ++k) {
        row_sum += temp[k];
      }
      row_offset_buf[i - block.row_start] = row_sum;
    }

    return;
  }

  int ic_per_group = conv_p_.IC / conv_p_.G;
  for (int i = block.row_start; i < block.row_start + block.row_size; ++i) {
    if (SPATIAL_DIM == 2) { // static if
      int n = i / (conv_p_.OUT_DIM[0] * conv_p_.OUT_DIM[1]);
      int hw = i % (conv_p_.OUT_DIM[0] * conv_p_.OUT_DIM[1]);
      int w = hw % conv_p_.OUT_DIM[1];
      int h = hw / conv_p_.OUT_DIM[1];
      for (int j = block.col_start;
           j < block.col_start + block.col_size + ic_per_group - 1;
           j += ic_per_group) {
        int j_blk_id = j / ic_per_group;
        // max( j_blk_id * IC, START)  -> min( END, (j_blk_id + 1) * IC )
        int j_blk_start = std::max(j_blk_id * ic_per_group, block.col_start);
        int j_blk_end = std::min(
            (j_blk_id + 1) * ic_per_group, block.col_start + block.col_size);
        if (j_blk_start >= j_blk_end) {
          break;
        }

        int grs = j / ic_per_group;
        int s = grs % conv_p_.K[1];
        int r = grs / conv_p_.K[1] % conv_p_.K[0];
        int g = grs / conv_p_.K[1] / conv_p_.K[0];

        int h_in = -conv_p_.pad[0] + h * conv_p_.stride[0] + r;
        int w_in = -conv_p_.pad[1] + w * conv_p_.stride[1] + s;

        if (h_in < 0 || h_in >= conv_p_.IN_DIM[0] || w_in < 0 ||
            w_in >= conv_p_.IN_DIM[1]) {
          // Please note that padding for convolution should be filled with
          // zero_pt
          std::memset(
              out + (i - block.row_start) * BaseType::blockColSize() +
                  (j_blk_start - block.col_start),
              zero_pt_,
              sizeof(T) * (j_blk_end - j_blk_start));
        } else {
          std::memcpy(
              out + (i - block.row_start) * BaseType::blockColSize() +
                  j_blk_start - block.col_start,
              sdata_ +
                  ((n * conv_p_.IN_DIM[0] + h_in) * conv_p_.IN_DIM[1] + w_in) *
                      conv_p_.IC +
                  g * ic_per_group + (j_blk_start % ic_per_group),
              sizeof(T) * (j_blk_end - j_blk_start));
        }
      }
    } else if (SPATIAL_DIM == 3) { // static if
      int n =
          i / (conv_p_.OUT_DIM[0] * conv_p_.OUT_DIM[1] * conv_p_.OUT_DIM[2]);
      int thw =
          i % (conv_p_.OUT_DIM[0] * conv_p_.OUT_DIM[1] * conv_p_.OUT_DIM[2]);
      int w = thw % conv_p_.OUT_DIM[2];
      int h = thw / conv_p_.OUT_DIM[2] % conv_p_.OUT_DIM[1];
      int t = thw / conv_p_.OUT_DIM[2] / conv_p_.OUT_DIM[1];
      for (int j = block.col_start;
           j < block.col_start + block.col_size + ic_per_group - 1;
           j += ic_per_group) {
        int j_blk_id = j / ic_per_group;
        // max( j_blk_id * IC, START)  -> min( END, (j_blk_id + 1) * IC )
        int j_blk_start = std::max(j_blk_id * ic_per_group, block.col_start);
        int j_blk_end = std::min(
            (j_blk_id + 1) * ic_per_group, block.col_start + block.col_size);
        if (j_blk_start >= j_blk_end) {
          break;
        }

        int gqrs = j / ic_per_group;
        int s = gqrs % conv_p_.K[2];
        int r = gqrs / conv_p_.K[2] % conv_p_.K[1];
        int q = gqrs / conv_p_.K[2] / conv_p_.K[1] % conv_p_.K[0];
        int g = gqrs / conv_p_.K[2] / conv_p_.K[1] / conv_p_.K[0];

        int t_in = -conv_p_.pad[0] + t * conv_p_.stride[0] + q;
        int h_in = -conv_p_.pad[1] + h * conv_p_.stride[1] + r;
        int w_in = -conv_p_.pad[2] + w * conv_p_.stride[2] + s;

        if (t_in < 0 || t_in >= conv_p_.IN_DIM[0] || h_in < 0 ||
            h_in >= conv_p_.IN_DIM[1] || w_in < 0 ||
            w_in >= conv_p_.IN_DIM[2]) {
          // Please note that padding for convolution should be filled with
          // zero_pt
          std::memset(
              &out
                  [(i - block.row_start) * BaseType::blockColSize() +
                   (j_blk_start - block.col_start)],
              zero_pt_,
              sizeof(T) * (j_blk_end - j_blk_start));
        } else {
          std::memcpy(
              out + (i - block.row_start) * BaseType::blockColSize() +
                  j_blk_start - block.col_start,
              sdata_ +
                  (((n * conv_p_.IN_DIM[0] + t_in) * conv_p_.IN_DIM[1] + h_in) *
                       conv_p_.IN_DIM[2] +
                   w_in) *
                      conv_p_.IC +
                  g * ic_per_group + (j_blk_start % ic_per_group),
              sizeof(T) * (j_blk_end - j_blk_start));
        }
      }
    }

    // zero fill
    // Please see the comment in PackAMatrix.cc for zero vs zero_pt fill.
    if ((block_p.col_start + block_p.col_size) -
            (block.col_start + block.col_size) >
        0) {
      std::memset(
          &out
              [(i - block.row_start) * BaseType::blockColSize() +
               (block.col_size)],
          0,
          sizeof(T) *
              ((block_p.col_start + block_p.col_size) -
               (block.col_start + block.col_size)));
    }

    // TODO: skip row_offset computation when B_zero_point is 0
    int32_t row_sum = row_offset_acc ? row_offset_buf[i - block.row_start] : 0;

    __m256i sum_v = _mm256_setzero_si256();
    __m256i one_epi16_v = _mm256_set1_epi16(1);
    __m256i one_epi8_v = _mm256_set1_epi8(1);
    for (int j = 0; j < block.col_size / 32 * 32; j += 32) {
      __m256i src_v = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(
          out + (i - block.row_start) * this->blockColSize() + j));
      sum_v = _mm256_add_epi32(
          sum_v,
          _mm256_madd_epi16(
              _mm256_maddubs_epi16(src_v, one_epi8_v), one_epi16_v));
    }
    for (int j = block.col_size / 32 * 32; j < block.col_size; ++j) {
      row_sum += out[(i - block.row_start) * this->blockColSize() + j];
    }
    alignas(64) int32_t temp[8];
    _mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v);
    for (int k = 0; k < 8; ++k) {
      row_sum += temp[k];
    }

    row_offset_buf[i - block.row_start] = row_sum;
  } // for each i
}

template <typename T, typename accT, int SPATIAL_DIM>
void PackAWithIm2Col<T, accT, SPATIAL_DIM>::printPackedMatrix(
    std::string name) {
  std::cout << name << ":"
            << "[" << BaseType::numPackedRows() << ", "
            << BaseType::numPackedCols() << "]" << std::endl;

  T* out = BaseType::getBuf();
  for (auto r = 0; r < BaseType::numPackedRows(); ++r) {
    for (auto c = 0; c < BaseType::numPackedCols(); ++c) {
      T val = out[r * BaseType::blockColSize() + c];
      if (std::is_integral<T>::value) {
        // cast to int64 because cout doesn't print int8_t type directly
        std::cout << std::setw(5) << static_cast<int64_t>(val) << " ";
      } else {
        std::cout << std::setw(5) << val << " ";
      }
    }
    std::cout << std::endl;
  }
  std::cout << std::endl;
}

template <typename T, typename accT, int SPATIAL_DIM>
int PackAWithIm2Col<T, accT, SPATIAL_DIM>::rowOffsetBufferSize() {
  if (cpuinfo_initialize()) {
    if (cpuinfo_has_x86_avx512f()) {
      return PackingTraits<T, accT, inst_set_t::avx512>::MCB;
    } else if (cpuinfo_has_x86_avx2()) {
      return PackingTraits<T, accT, inst_set_t::avx2>::MCB;
    } else {
      // TODO: Have default slower path
      assert(0 && "unsupported architecture");
      return -1;
    }
  } else {
    throw std::runtime_error("Failed to initialize cpuinfo!");
  }
}

template class PackAWithIm2Col<uint8_t, int32_t>;
template class PackAWithIm2Col<uint8_t, int16_t>;
template class PackAWithIm2Col<uint8_t, int32_t, 3>;
template class PackAWithIm2Col<uint8_t, int16_t, 3>;

} // namespace fbgemm