blob: eff48771982a351b4c20d990a8a4b7b6bca79bdc [file] [log] [blame]
Joseph Dobson6f8b17d2020-02-11 19:32:11 +00001/*
2 * Copyright (c) 2020 ARM Limited.
3 *
4 * SPDX-License-Identifier: MIT
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24#pragma once
25
26#include "arm_gemm.hpp"
27#include "utils.hpp"
28
29#include "mergeresults.hpp"
30#include "transform.hpp"
31
32#ifdef CYCLE_PROFILING
33#include "profiler.hpp"
34#endif
35
36#include <algorithm>
37#include <cassert>
38
39// Some macros used to decide how much working space to allocate.
40// Round allocations up to the next cache line.
41#define ALLOC_ROUND 64
42#define ROUND_UP(x) ((((x) + ALLOC_ROUND-1) / ALLOC_ROUND) * ALLOC_ROUND)
43
44// Implementation of the GemmCommon abstract class.
45//
46// This implementation interleaves the source matrices in blocks - good for
47// larger matrices.
48namespace arm_gemm {
49
50template<typename strategy, typename To, typename Tr>
51class GemmInterleavedPretransposed2d : public GemmCommon<To, Tr> {
52 typedef typename strategy::operand_type Toi;
53 typedef typename strategy::result_type Tri;
54
55 /* const properties set by constructor */
56 const CPUInfo * const _ci;
57
58 const unsigned int _Msize;
59 const unsigned int _Nsize;
60 const unsigned int _Ksize;
61
62 const unsigned int _nbatches;
63 const unsigned int _nmulti;
64
65 const bool _trA;
66 const bool _trB;
67
68 const Activation _act;
69
70 const int _maxthreads;
71 int _nthreads;
72
73 /* Blocking info */
74 unsigned int _k_block=0;
75 unsigned int _x_block=0;
76
77 unsigned int _Mround_div=0;
78 unsigned int _Mround=0;
79 unsigned int _Nround_div=0;
80 unsigned int _Nround=0;
81
82 /* Working space, pretransposed buffer */
83 const Toi *_B_transposed=nullptr;
84 void *_working_space=nullptr;
85
86 /* We will need to walk through the blocks of B in a few contexts, so
87 * factor that out. */
88 class blockwalker {
89 private:
90 /* Size loops, etc. based on our parent's configuration */
91 const GemmInterleavedPretransposed2d<strategy, To, Tr> &_parent;
92
93 /* K, X and multi parameters for current iteration. */
94 unsigned int _k0=0, _x0=0, _xmin=0, _xmax=0, _multi=0;
95
96 unsigned int _index=0;
97 bool _done=false;
98 bool _newkblock=true;
99 bool _newmulti=true;
100
101 public:
102 blockwalker(const GemmInterleavedPretransposed2d<strategy, To, Tr> &parent)
103 : _parent(parent)
104 , _xmax { parent._Nsize }
105 { }
106
107 blockwalker(const GemmInterleavedPretransposed2d<strategy, To, Tr> &parent, unsigned int x0, unsigned int xmax)
108 : _parent(parent)
109 , _x0 { x0 }
110 , _xmin { x0 }
111 , _xmax { xmax }
112 {
113 assert(_x0 <= _xmax);
114 }
115
116 unsigned int xmax() {
117 return std::min(_x0 + _parent._x_block, _xmax);
118 }
119
120 unsigned int kmax() {
121 return std::min(_k0 + _parent._k_block, _parent._Ksize);
122 }
123
124 /* Advance to the next block, return false at the end. */
125 bool advance(void) {
126 if (_done) {
127 return false;
128 }
129
130 _newkblock=false;
131 _x0 += _parent._x_block;
132 if (_x0 >= _xmax) {
133 _x0=_xmin;
134 _k0 += _parent._k_block;
135 if (_k0 >= _parent._Ksize) {
136 _k0=0;
137 _multi++;
138 if (_multi >= _parent._nmulti) {
139 _done=true;
140 return false;
141 }
142 _newmulti=true;
143 }
144 _newkblock=true;
145 }
146 _index++;
147
148 return true;
149 }
150
151 unsigned int k0(void) { return _k0; }
152 unsigned int x0(void) { return _x0; }
153 unsigned int multi(void) { return _multi; }
154 unsigned int index(void) { return _index; }
155 bool done(void) { return _done; }
156 bool newkblock(void) { return _newkblock; }
157 };
158
159 // A working size: One of these needed, regardless of thread count. Divided according to window.
160 size_t get_a_working_size() const {
161 return ROUND_UP(sizeof(Toi) * _k_block * _Mround * _nbatches) * 2;
162 }
163
164 // As B will be pretranspose we do not need to alloc any space for it
165 size_t get_b_working_size() const {
166 return 0;
167 }
168
169 // C working size: One needed per thread.
170 size_t get_c_working_size() const {
171 return ROUND_UP(sizeof(Tri) * _x_block * strategy::out_height());
172 }
173
174 // Internal execute function.
175 // This supports both the "pretransposed" and "standard" interfaces via the template parameter.
176 void execute_pretranspose(unsigned int m_start, unsigned int m_end, unsigned int n_start, unsigned int n_end, int threadid, int mthreadid, int nthreadid) {
177 /* Make sure we've been set up correctly. */
178 assert(_B_transposed);
179 assert(_working_space);
180 assert(this->_Aptr);
181 assert(this->_Cptr);
182
183 UNUSED(mthreadid);
184 UNUSED(nthreadid);
185
186#ifdef CYCLE_PROFILING
187 profiler prof;
188#endif
189 strategy strat(_ci);
190
191 /* Translate 'start' and 'end' into a position within the batches and rows. */
192 const unsigned int window_per_batch = _Mround / strategy::out_height();
193 unsigned int batch_0 = m_start / window_per_batch;
194 unsigned int batch_end = m_end / window_per_batch;
195
196 /* Compute the M values to operate on */
197 unsigned int m_0 = (m_start - (batch_0 * window_per_batch)) * strategy::out_height();
198 unsigned int m_max = (m_end - (batch_end * window_per_batch)) * strategy::out_height();
199
200 unsigned int n_0 = std::min(this->_Nsize, strategy::out_width() * n_start);
201 unsigned int n_max = std::min(this->_Nsize, strategy::out_width() * n_end);
202
203 blockwalker current(*this, n_0, n_max);
204
205 int8_t *working_space_bytes = reinterpret_cast<int8_t *>(_working_space);
206
207 auto c_panel_start = working_space_bytes;
208 auto a_panel_start = c_panel_start + get_c_working_size() * _maxthreads;
209
210 auto c_panel = reinterpret_cast<Tri *>(c_panel_start + get_c_working_size() * threadid);
211 auto a_panel = reinterpret_cast<Toi *>(a_panel_start + get_a_working_size() * threadid);
212
213 /* B^t is stored in interleaved panels separated by their K-block component
214 * we want to store a pointer to the start of the current k-page
215 * then when we come to the next k-block we just add the size of the previous to
216 * this base pointer
217 */
218 const Toi *b_panel_start = _B_transposed;
219 // b_panels stores a pointer to the start of our current block inside of the k-block
220 const Toi *b_panel = b_panel_start;
221
222 // newkblock() is always true on the first iteration, so this will be set properly on the first loop.
223 unsigned b_page_size = 0;
224 int kern_k = 0;
225 for (;!current.done();current.advance()) {
226 int bblocks = iceildiv(current.xmax() - current.x0(), strategy::out_width());
227
228 if (current.newkblock()) {
229 kern_k = iceildiv(current.kmax() - current.k0(), strategy::k_unroll());
230 kern_k *= strat.k_unroll();
231
232 unsigned b_thread_start_offset = iceildiv(current.x0(), strategy::out_width());
233
234 b_panel_start += b_page_size;
235 b_panel = b_panel_start + (b_thread_start_offset * strat.out_width() * kern_k);
236 b_page_size = _Nround * kern_k;
237
238 for (unsigned int batch = batch_0; batch <= batch_end; batch++) {
239 unsigned int first_m = (batch == batch_0) ? m_0 : 0;
240 unsigned int last_m = (batch == batch_end) ? m_max : _Msize;
241
242 if (first_m >= last_m)
243 continue;
244
245 auto a_thread_panel_in = this->_Aptr
246 + (batch * this->_A_batch_stride)
247 + (current.multi() * this->_A_multi_stride);
248
249 auto a_thread_panel_out = a_panel + ((batch * _Mround + first_m) * _k_block);
250
251 strat.transforms.PrepareA(
252 a_thread_panel_out,
253 a_thread_panel_in,
254 this->_lda,
255 first_m,
256 last_m,
257 current.k0(),
258 current.kmax(),
259 _trA);
260 }
261 }
262
263 /* Do the actual work. */
264 for (unsigned int batch = batch_0; batch <= batch_end; batch++) {
265 unsigned int first_m = (batch == batch_0) ? m_0 : 0;
266 unsigned int last_m = (batch == batch_end) ? m_max : _Msize;
267
268 const Toi *a_ptr = a_panel + (batch * _Mround + first_m) * _k_block;
269
270 if (first_m >= last_m)
271 continue;
272
273 for (unsigned int y=first_m; y<last_m; y+=strategy::out_height()) {
274 unsigned int ymax = std::min(_Msize, y + strategy::out_height());
275
276 strat.kernel(a_ptr, b_panel, c_panel, 1, bblocks, kern_k);
277 a_ptr += (strategy::out_height() * kern_k);
278
279 /* Only activate on last pass, only add bias on first pass, ask for accumulation on any non-first pass */
280 const bool first_pass = current.k0()==0;
281 const bool last_pass = current.kmax()==_Ksize;
282
283 auto c_panel_out = this->_Cptr
284 + this->_C_batch_stride * batch
285 + this->_C_multi_stride * current.multi();
286
287 auto bias = (first_pass && this->_bias)
288 ? this->_bias + (current.multi() * this->_bias_multi_stride)
289 : nullptr;
290
291 auto act = last_pass ? _act : Activation();
292
293 strat.transforms.Merge(
294 c_panel_out,
295 c_panel,
296 this->_ldc,
297 y,
298 ymax,
299 current.x0(),
300 current.xmax(),
301 bias,
302 act,
303 !first_pass); //Append
304 }
305 }
306
307 b_panel += (bblocks * strat.out_width() * kern_k);
308 }
309 }
310
311public:
312 GemmInterleavedPretransposed2d(GemmInterleavedPretransposed2d &) = delete;
313 GemmInterleavedPretransposed2d & operator= (GemmInterleavedPretransposed2d &) = delete;
314
315 /* Constructor */
316 GemmInterleavedPretransposed2d(const GemmArgs &args)
317 : _ci(args._ci)
318 , _Msize(args._Msize)
319 , _Nsize(args._Nsize)
320 , _Ksize(args._Ksize)
321 , _nbatches(args._nbatches)
322 , _nmulti(args._nmulti)
323 , _trA(args._trA)
324 , _trB(args._trB)
325 , _act(args._act)
326 , _maxthreads(args._maxthreads)
327 , _nthreads(args._maxthreads)
328
329 // Work out the rounded size of M - needed for some buffers.
330 , _Mround_div ( iceildiv(_Msize, strategy::out_height()) )
331 , _Mround ( _Mround_div * strategy::out_height() )
332
333 , _Nround_div ( iceildiv(_Nsize, strategy::out_width()) )
334 , _Nround ( _Nround_div * strategy::out_width() )
335 {
336
337 assert(args._pretransposed_hint);
338 assert(_maxthreads > 0);
339
340 const unsigned int L1_size = _ci->get_L1_cache_size();
341 const unsigned int L2_size = _ci->get_L2_cache_size();
342
343 // Work out blocking parameters, or override from provided GemmConfig
344 if (args._cfg && args._cfg->inner_block_size) {
345 _k_block = args._cfg->inner_block_size;
346 } else {
347 // k_block: Find out how much of the larger array can be loaded into half the cache.
348 // This should account for associative caches.
349 _k_block = (L1_size / 2) / (sizeof(Toi) * (std::max(strategy::out_width(), strategy::out_height())));
350
351 // Needs to be (at least a single) multiple of the K unroll level.
352 _k_block /= strategy::k_unroll();
353 _k_block = std::max(_k_block, 1U) * strategy::k_unroll();
354
355 // Now tune to presented problem size; this is how many blocks we need.
356 unsigned int num_k_blocks = iceildiv(_Ksize, _k_block);
357
358 // So divide the space equally into that many blocks.
359 _k_block = iceildiv(_Ksize, num_k_blocks);
360
361 // And round UP to the K unroll level required.
362 _k_block = iceildiv(_k_block, strategy::k_unroll());
363 _k_block *= strategy::k_unroll();
364 }
365
366 if (args._cfg && args._cfg->outer_block_size) {
367 _x_block = args._cfg->outer_block_size;
368 } else {
369 // x_block: Work out how many rows (of length k_block) will fit in the L2
370 // Don't allocate more than 90% of the L2 to allow for overheads, and subtract off the L1 contents.
371 _x_block = (((L2_size * 9) / 10) - (_k_block * sizeof(Toi) * (strategy::out_width() + strategy::out_height()))) /
372 (sizeof(Toi) * _k_block);
373
374 // Needs to be (at least a single) multiple of the kernel output width.
375 _x_block /= strategy::out_width();
376 _x_block = std::max(_x_block, 1U) * strategy::out_width();
377
378 // And tune to the presented problem size.
379 unsigned int num_x_blocks = iceildiv(_Nsize, _x_block);
380 _x_block = iceildiv(_Nsize, num_x_blocks);
381
382 _x_block = iceildiv(_x_block, strategy::out_width());
383 _x_block *= strategy::out_width();
384 }
385 }
386
387 // Interface implementation - Compulsory functions
388 ndrange_t get_window_size() const override {
389 unsigned m = (_Mround / strategy::out_height()) * _nbatches;
390 unsigned n = _Nround_div;
391
392 return { m, n, 1u, 1u, 1u, 1u };
393 }
394
395 // set_nthreads: pass on to buffer manager to avoid it waiting for non-existant threads.
396 void set_nthreads(int nthreads) override {
397 _nthreads = std::min(nthreads, _maxthreads);
398 }
399
400 void execute(const ndcoord_t& work_range, const ndcoord_t& thread_locator, int threadid) override {
401 /* This particular GEMM implementation can only be broken up over the M & N
402 * dimensions, we inform the frame work of this limitation via the get_window_size function
403 */
404 assert(ndrange_popcount(work_range) <= 2);
405
406 const auto m_start = work_range.get_position(0);
407 const auto n_start = work_range.get_position(1);
408 const auto m_size = work_range.get_size(0);
409 const auto n_size = work_range.get_size(1);
410 const auto m_end = m_start + m_size;
411 const auto n_end = n_start + n_size;
412
413 const auto m_threadid = thread_locator.get_position(0);
414 const auto n_threadid = thread_locator.get_position(1);
415
416 execute_pretranspose(m_start, m_end, n_start, n_end, threadid, m_threadid, n_threadid);
417 }
418
419 std::size_t get_working_size()const override {
420 /* Because we do not know how schedular will break up
421 * the task, we need to ensure that alloc enough
422 * space to be able to handle the case where every thread
423 * is parallelised across B AND also every thrread is parallelised across A
424 *
425 * If we parallelise across A, then we only need one buffer of A and 64 buffers of B
426 * If we parallelise across B, then we only need 64 buffer of B and
427 */
428 return get_c_working_size() * _maxthreads
429 + get_a_working_size() * _maxthreads
430 + 64; //to account for cacheline alignment
431 }
432
433
434 void set_working_space(void *working_space) override {
435 // Make sure everything ends up cache line aligned
436 int8_t *working_space_bytes = reinterpret_cast<int8_t *>(working_space);
437 intptr_t working_space_int = reinterpret_cast<intptr_t>(working_space);
438
439 size_t diff=0;
440
441 if (working_space_int & 0x3F) {
442 diff = 0x40 - (working_space_int & 0x3F);
443 }
444
445 working_space_bytes += diff;
446
447 _working_space = reinterpret_cast<void *>(working_space_bytes);
448 }
449
450 // Interface implementation - pretransposed
451 bool B_is_pretransposed() const override {
452 return true;
453 }
454
455 bool B_pretranspose_required() const override {
456 return _B_transposed==nullptr;
457 }
458
459 // TODO: this could almost certainly be considerably simpler.
460 size_t get_B_pretransposed_array_size() const override {
461 size_t total=0;
462 blockwalker current(*this);
463
464 do {
465 /* Figure out the size of each block. */
466 unsigned int x_size = (current.xmax() - current.x0());
467 unsigned int k_size = (current.kmax() - current.k0());
468
469 /* Round sizes up as needed. */
470 x_size = iceildiv(x_size, strategy::out_width());
471 x_size *= strategy::out_width();
472
473 k_size = iceildiv(k_size, strategy::k_unroll());
474 k_size *= strategy::k_unroll();
475
476 total += x_size * k_size * sizeof(Toi);
477 } while (current.advance());
478
479 return total;
480 }
481
482 void pretranspose_B_array(void *in_buffer, const To *B, const int ldb, const int B_multi_stride) override {
483 blockwalker current(*this);
484 Toi *buffer = reinterpret_cast<Toi *>(in_buffer);
485 _B_transposed = buffer;
486 strategy strat(_ci);
487
488 do {
489 /* Figure out the size of each block. */
490 unsigned int x_size = (current.xmax() - current.x0());
491 unsigned int k_size = (current.kmax() - current.k0());
492
493 /* Round sizes up as needed. */
494 x_size = iceildiv(x_size, strategy::out_width());
495 x_size *= strategy::out_width();
496
497 k_size = iceildiv(k_size, strategy::k_unroll());
498 k_size *= strategy::k_unroll();
499
500 strat.transforms.PrepareB(buffer, B + (current.multi() * B_multi_stride), ldb,
501 current.x0(), current.xmax(), current.k0(), current.kmax(), _trB);
502
503 buffer += (x_size * k_size);
504 } while (current.advance());
505 }
506
507 void set_pretransposed_B_data(void *in_buffer) override {
508 _B_transposed = reinterpret_cast<Toi *>(in_buffer);
509 }
510
511 ~GemmInterleavedPretransposed2d() override { }
512};
513
514} // namespace arm_gemm