blob: 38fb26370c829f6a981ba24222c9c570d83b969d [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.
Georgios Pinitas5aa1a0b2020-07-02 20:02:20 +0100176 void execute_pretranspose(unsigned int m_start, unsigned int m_end, unsigned int n_start, unsigned int n_end, int threadid, int, int) {
Joseph Dobson6f8b17d2020-02-11 19:32:11 +0000177 /* 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
Joseph Dobson6f8b17d2020-02-11 19:32:11 +0000183#ifdef CYCLE_PROFILING
184 profiler prof;
185#endif
186 strategy strat(_ci);
187
188 /* Translate 'start' and 'end' into a position within the batches and rows. */
189 const unsigned int window_per_batch = _Mround / strategy::out_height();
190 unsigned int batch_0 = m_start / window_per_batch;
191 unsigned int batch_end = m_end / window_per_batch;
192
193 /* Compute the M values to operate on */
194 unsigned int m_0 = (m_start - (batch_0 * window_per_batch)) * strategy::out_height();
195 unsigned int m_max = (m_end - (batch_end * window_per_batch)) * strategy::out_height();
196
197 unsigned int n_0 = std::min(this->_Nsize, strategy::out_width() * n_start);
198 unsigned int n_max = std::min(this->_Nsize, strategy::out_width() * n_end);
199
200 blockwalker current(*this, n_0, n_max);
201
202 int8_t *working_space_bytes = reinterpret_cast<int8_t *>(_working_space);
203
204 auto c_panel_start = working_space_bytes;
205 auto a_panel_start = c_panel_start + get_c_working_size() * _maxthreads;
206
207 auto c_panel = reinterpret_cast<Tri *>(c_panel_start + get_c_working_size() * threadid);
208 auto a_panel = reinterpret_cast<Toi *>(a_panel_start + get_a_working_size() * threadid);
209
210 /* B^t is stored in interleaved panels separated by their K-block component
211 * we want to store a pointer to the start of the current k-page
212 * then when we come to the next k-block we just add the size of the previous to
213 * this base pointer
214 */
215 const Toi *b_panel_start = _B_transposed;
216 // b_panels stores a pointer to the start of our current block inside of the k-block
217 const Toi *b_panel = b_panel_start;
218
219 // newkblock() is always true on the first iteration, so this will be set properly on the first loop.
220 unsigned b_page_size = 0;
221 int kern_k = 0;
222 for (;!current.done();current.advance()) {
223 int bblocks = iceildiv(current.xmax() - current.x0(), strategy::out_width());
224
225 if (current.newkblock()) {
226 kern_k = iceildiv(current.kmax() - current.k0(), strategy::k_unroll());
227 kern_k *= strat.k_unroll();
228
229 unsigned b_thread_start_offset = iceildiv(current.x0(), strategy::out_width());
230
231 b_panel_start += b_page_size;
232 b_panel = b_panel_start + (b_thread_start_offset * strat.out_width() * kern_k);
233 b_page_size = _Nround * kern_k;
234
235 for (unsigned int batch = batch_0; batch <= batch_end; batch++) {
236 unsigned int first_m = (batch == batch_0) ? m_0 : 0;
237 unsigned int last_m = (batch == batch_end) ? m_max : _Msize;
238
239 if (first_m >= last_m)
240 continue;
241
242 auto a_thread_panel_in = this->_Aptr
243 + (batch * this->_A_batch_stride)
244 + (current.multi() * this->_A_multi_stride);
245
246 auto a_thread_panel_out = a_panel + ((batch * _Mround + first_m) * _k_block);
247
248 strat.transforms.PrepareA(
249 a_thread_panel_out,
250 a_thread_panel_in,
251 this->_lda,
252 first_m,
253 last_m,
254 current.k0(),
255 current.kmax(),
256 _trA);
257 }
258 }
259
260 /* Do the actual work. */
261 for (unsigned int batch = batch_0; batch <= batch_end; batch++) {
262 unsigned int first_m = (batch == batch_0) ? m_0 : 0;
263 unsigned int last_m = (batch == batch_end) ? m_max : _Msize;
264
265 const Toi *a_ptr = a_panel + (batch * _Mround + first_m) * _k_block;
266
267 if (first_m >= last_m)
268 continue;
269
270 for (unsigned int y=first_m; y<last_m; y+=strategy::out_height()) {
271 unsigned int ymax = std::min(_Msize, y + strategy::out_height());
272
273 strat.kernel(a_ptr, b_panel, c_panel, 1, bblocks, kern_k);
274 a_ptr += (strategy::out_height() * kern_k);
275
276 /* Only activate on last pass, only add bias on first pass, ask for accumulation on any non-first pass */
277 const bool first_pass = current.k0()==0;
278 const bool last_pass = current.kmax()==_Ksize;
279
280 auto c_panel_out = this->_Cptr
281 + this->_C_batch_stride * batch
282 + this->_C_multi_stride * current.multi();
283
284 auto bias = (first_pass && this->_bias)
285 ? this->_bias + (current.multi() * this->_bias_multi_stride)
286 : nullptr;
287
288 auto act = last_pass ? _act : Activation();
289
290 strat.transforms.Merge(
291 c_panel_out,
292 c_panel,
293 this->_ldc,
294 y,
295 ymax,
296 current.x0(),
297 current.xmax(),
298 bias,
299 act,
300 !first_pass); //Append
301 }
302 }
303
304 b_panel += (bblocks * strat.out_width() * kern_k);
305 }
306 }
307
308public:
309 GemmInterleavedPretransposed2d(GemmInterleavedPretransposed2d &) = delete;
310 GemmInterleavedPretransposed2d & operator= (GemmInterleavedPretransposed2d &) = delete;
311
312 /* Constructor */
313 GemmInterleavedPretransposed2d(const GemmArgs &args)
314 : _ci(args._ci)
315 , _Msize(args._Msize)
316 , _Nsize(args._Nsize)
317 , _Ksize(args._Ksize)
318 , _nbatches(args._nbatches)
319 , _nmulti(args._nmulti)
320 , _trA(args._trA)
321 , _trB(args._trB)
322 , _act(args._act)
323 , _maxthreads(args._maxthreads)
324 , _nthreads(args._maxthreads)
325
326 // Work out the rounded size of M - needed for some buffers.
327 , _Mround_div ( iceildiv(_Msize, strategy::out_height()) )
328 , _Mround ( _Mround_div * strategy::out_height() )
329
330 , _Nround_div ( iceildiv(_Nsize, strategy::out_width()) )
331 , _Nround ( _Nround_div * strategy::out_width() )
332 {
333
334 assert(args._pretransposed_hint);
335 assert(_maxthreads > 0);
336
337 const unsigned int L1_size = _ci->get_L1_cache_size();
338 const unsigned int L2_size = _ci->get_L2_cache_size();
339
340 // Work out blocking parameters, or override from provided GemmConfig
341 if (args._cfg && args._cfg->inner_block_size) {
342 _k_block = args._cfg->inner_block_size;
343 } else {
344 // k_block: Find out how much of the larger array can be loaded into half the cache.
345 // This should account for associative caches.
346 _k_block = (L1_size / 2) / (sizeof(Toi) * (std::max(strategy::out_width(), strategy::out_height())));
347
348 // Needs to be (at least a single) multiple of the K unroll level.
349 _k_block /= strategy::k_unroll();
350 _k_block = std::max(_k_block, 1U) * strategy::k_unroll();
351
352 // Now tune to presented problem size; this is how many blocks we need.
353 unsigned int num_k_blocks = iceildiv(_Ksize, _k_block);
354
355 // So divide the space equally into that many blocks.
356 _k_block = iceildiv(_Ksize, num_k_blocks);
357
358 // And round UP to the K unroll level required.
359 _k_block = iceildiv(_k_block, strategy::k_unroll());
360 _k_block *= strategy::k_unroll();
361 }
362
363 if (args._cfg && args._cfg->outer_block_size) {
364 _x_block = args._cfg->outer_block_size;
365 } else {
366 // x_block: Work out how many rows (of length k_block) will fit in the L2
367 // Don't allocate more than 90% of the L2 to allow for overheads, and subtract off the L1 contents.
368 _x_block = (((L2_size * 9) / 10) - (_k_block * sizeof(Toi) * (strategy::out_width() + strategy::out_height()))) /
369 (sizeof(Toi) * _k_block);
370
371 // Needs to be (at least a single) multiple of the kernel output width.
372 _x_block /= strategy::out_width();
373 _x_block = std::max(_x_block, 1U) * strategy::out_width();
374
375 // And tune to the presented problem size.
376 unsigned int num_x_blocks = iceildiv(_Nsize, _x_block);
377 _x_block = iceildiv(_Nsize, num_x_blocks);
378
379 _x_block = iceildiv(_x_block, strategy::out_width());
380 _x_block *= strategy::out_width();
381 }
382 }
383
384 // Interface implementation - Compulsory functions
385 ndrange_t get_window_size() const override {
386 unsigned m = (_Mround / strategy::out_height()) * _nbatches;
387 unsigned n = _Nround_div;
388
Georgios Pinitas5aa1a0b2020-07-02 20:02:20 +0100389 return { m, n };
Joseph Dobson6f8b17d2020-02-11 19:32:11 +0000390 }
391
392 // set_nthreads: pass on to buffer manager to avoid it waiting for non-existant threads.
393 void set_nthreads(int nthreads) override {
394 _nthreads = std::min(nthreads, _maxthreads);
395 }
396
397 void execute(const ndcoord_t& work_range, const ndcoord_t& thread_locator, int threadid) override {
398 /* This particular GEMM implementation can only be broken up over the M & N
399 * dimensions, we inform the frame work of this limitation via the get_window_size function
400 */
Joseph Dobson6f8b17d2020-02-11 19:32:11 +0000401 const auto m_start = work_range.get_position(0);
402 const auto n_start = work_range.get_position(1);
403 const auto m_size = work_range.get_size(0);
404 const auto n_size = work_range.get_size(1);
405 const auto m_end = m_start + m_size;
406 const auto n_end = n_start + n_size;
407
408 const auto m_threadid = thread_locator.get_position(0);
409 const auto n_threadid = thread_locator.get_position(1);
410
411 execute_pretranspose(m_start, m_end, n_start, n_end, threadid, m_threadid, n_threadid);
412 }
413
414 std::size_t get_working_size()const override {
415 /* Because we do not know how schedular will break up
416 * the task, we need to ensure that alloc enough
417 * space to be able to handle the case where every thread
418 * is parallelised across B AND also every thrread is parallelised across A
419 *
420 * If we parallelise across A, then we only need one buffer of A and 64 buffers of B
421 * If we parallelise across B, then we only need 64 buffer of B and
422 */
423 return get_c_working_size() * _maxthreads
424 + get_a_working_size() * _maxthreads
425 + 64; //to account for cacheline alignment
426 }
427
428
429 void set_working_space(void *working_space) override {
430 // Make sure everything ends up cache line aligned
431 int8_t *working_space_bytes = reinterpret_cast<int8_t *>(working_space);
432 intptr_t working_space_int = reinterpret_cast<intptr_t>(working_space);
433
434 size_t diff=0;
435
436 if (working_space_int & 0x3F) {
437 diff = 0x40 - (working_space_int & 0x3F);
438 }
439
440 working_space_bytes += diff;
441
442 _working_space = reinterpret_cast<void *>(working_space_bytes);
443 }
444
445 // Interface implementation - pretransposed
446 bool B_is_pretransposed() const override {
447 return true;
448 }
449
450 bool B_pretranspose_required() const override {
451 return _B_transposed==nullptr;
452 }
453
454 // TODO: this could almost certainly be considerably simpler.
455 size_t get_B_pretransposed_array_size() const override {
456 size_t total=0;
457 blockwalker current(*this);
458
459 do {
460 /* Figure out the size of each block. */
461 unsigned int x_size = (current.xmax() - current.x0());
462 unsigned int k_size = (current.kmax() - current.k0());
463
464 /* Round sizes up as needed. */
465 x_size = iceildiv(x_size, strategy::out_width());
466 x_size *= strategy::out_width();
467
468 k_size = iceildiv(k_size, strategy::k_unroll());
469 k_size *= strategy::k_unroll();
470
471 total += x_size * k_size * sizeof(Toi);
472 } while (current.advance());
473
474 return total;
475 }
476
477 void pretranspose_B_array(void *in_buffer, const To *B, const int ldb, const int B_multi_stride) override {
478 blockwalker current(*this);
479 Toi *buffer = reinterpret_cast<Toi *>(in_buffer);
480 _B_transposed = buffer;
481 strategy strat(_ci);
482
483 do {
484 /* Figure out the size of each block. */
485 unsigned int x_size = (current.xmax() - current.x0());
486 unsigned int k_size = (current.kmax() - current.k0());
487
488 /* Round sizes up as needed. */
489 x_size = iceildiv(x_size, strategy::out_width());
490 x_size *= strategy::out_width();
491
492 k_size = iceildiv(k_size, strategy::k_unroll());
493 k_size *= strategy::k_unroll();
494
495 strat.transforms.PrepareB(buffer, B + (current.multi() * B_multi_stride), ldb,
496 current.x0(), current.xmax(), current.k0(), current.kmax(), _trB);
497
498 buffer += (x_size * k_size);
499 } while (current.advance());
500 }
501
502 void set_pretransposed_B_data(void *in_buffer) override {
503 _B_transposed = reinterpret_cast<Toi *>(in_buffer);
504 }
505
506 ~GemmInterleavedPretransposed2d() override { }
507};
508
509} // namespace arm_gemm