You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

gemm_vec.c 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /*
  2. * Copyright (c) IBM Corporation 2020.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in
  14. * the documentation and/or other materials provided with the
  15. * distribution.
  16. * 3. Neither the name of the OpenBLAS project nor the names of
  17. * its contributors may be used to endorse or promote products
  18. * derived from this software without specific prior written
  19. * permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  22. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  25. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  30. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include "common.h"
  33. #include <vecintrin.h>
  34. #include <stdbool.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #ifdef COMPLEX
  38. #error "Handling for complex numbers is not supported in this kernel"
  39. #endif
  40. #ifdef DOUBLE
  41. #define UNROLL_M DGEMM_DEFAULT_UNROLL_M
  42. #define UNROLL_N DGEMM_DEFAULT_UNROLL_N
  43. #else
  44. #define UNROLL_M SGEMM_DEFAULT_UNROLL_M
  45. #define UNROLL_N SGEMM_DEFAULT_UNROLL_N
  46. #endif
  47. static const size_t unroll_m = UNROLL_M;
  48. static const size_t unroll_n = UNROLL_N;
  49. /* Handling of triangular matrices */
  50. #ifdef TRMMKERNEL
  51. static const bool trmm = true;
  52. static const bool left =
  53. #ifdef LEFT
  54. true;
  55. #else
  56. false;
  57. #endif
  58. static const bool backwards =
  59. #if defined(LEFT) != defined(TRANSA)
  60. true;
  61. #else
  62. false;
  63. #endif
  64. #else
  65. static const bool trmm = false;
  66. static const bool left = false;
  67. static const bool backwards = false;
  68. #endif /* TRMMKERNEL */
  69. /*
  70. * Background:
  71. *
  72. * The algorithm of GotoBLAS / OpenBLAS breaks down the matrix multiplication
  73. * problem by splitting all matrices into partitions multiple times, so that the
  74. * submatrices fit into the L1 or L2 caches. As a result, each multiplication of
  75. * submatrices can stream data fast from L1 and L2 caches. Inbetween, it copies
  76. * and rearranges the submatrices to enable contiguous memory accesses to
  77. * improve locality in both caches and TLBs.
  78. *
  79. * At the heart of the algorithm is this kernel, which multiplies, a "Block
  80. * matrix" A (small dimensions) with a "Panel matrix" B (number of rows is
  81. * small) and adds the result into a "Panel matrix" C; GotoBLAS calls this
  82. * operation GEBP. This kernel further partitions GEBP twice, such that (1)
  83. * submatrices of C and B fit into the L1 caches (GEBP_column_block) and (2) a
  84. * block of C fits into the registers, while multiplying panels from A and B
  85. * streamed from the L2 and L1 cache, respectively (GEBP_block).
  86. *
  87. *
  88. * Algorithm GEBP(A, B, C, m, n, k, alpha):
  89. *
  90. * The problem is calculating C += alpha * (A * B)
  91. * C is an m x n matrix, A is an m x k matrix, B is an k x n matrix.
  92. *
  93. * - C is in column-major-order, with an offset of ldc to the element in the
  94. * next column (same row).
  95. * - A is in row-major-order yet stores SGEMM_UNROLL_M elements of each column
  96. * contiguously while walking along rows.
  97. * - B is in column-major-order but packs SGEMM_UNROLL_N elements of a row
  98. * contiguously.
  99. * If the numbers of rows and columns are not multiples of SGEMM_UNROLL_M or
  100. * SGEMM_UNROLL_N, the remaining elements are arranged in blocks with power-of-2
  101. * dimensions (e.g., 5 remaining columns would be in a block-of-4 and a
  102. * block-of-1).
  103. *
  104. * Note that packing A and B into that form is taken care of by the caller in
  105. * driver/level3/level3.c (actually done by "copy kernels").
  106. *
  107. * Steps:
  108. * - Partition C and B into blocks of n_r (SGEMM_UNROLL_N) columns, C_j and B_j.
  109. * Now, B_j should fit into the L1 cache.
  110. * - For each partition, calculate C_j += alpha * (A * B_j) by
  111. * (1) Calculate C_aux := A * B_j (see below)
  112. * (2) unpack C_j = C_j + alpha * C_aux
  113. *
  114. *
  115. * Algorithm for Calculating C_aux:
  116. *
  117. * - Further partition C_aux and A into groups of m_r (SGEMM_UNROLL_M) rows,
  118. * such that the m_r x n_r-submatrix of C_aux can be held in registers. Each
  119. * submatrix of C_aux can be calculated independently, and the registers are
  120. * added back into C_j.
  121. *
  122. * - For each row-block of C_aux:
  123. * (uses a row block of A and full B_j)
  124. * - stream over all columns of A, multiply with elements from B and
  125. * accumulate in registers. (use different inner-kernels to exploit
  126. * vectorization for varying block sizes)
  127. * - add alpha * row block of C_aux back into C_j.
  128. *
  129. * Note that there are additional mechanics for handling triangular matrices,
  130. * calculating B := alpha (A * B) where either of the matrices A or B can be
  131. * triangular. In case of A, the macro "LEFT" is defined. In addition, A can
  132. * optionally be transposed.
  133. * The code effectively skips an "offset" number of columns in A and rows of B
  134. * in each block, to save unnecessary work by exploiting the triangular nature.
  135. * To handle all cases, the code discerns (1) a "left" mode when A is triangular
  136. * and (2) "forward" / "backwards" modes where only the first "offset"
  137. * columns/rows of A/B are used or where the first "offset" columns/rows are
  138. * skipped, respectively.
  139. *
  140. * Reference:
  141. *
  142. * The summary above is based on staring at various kernel implementations and:
  143. * K. Goto and R. A. Van de Geijn, Anatomy of High-Performance Matrix
  144. * Multiplication, in ACM Transactions of Mathematical Software, Vol. 34, No.
  145. * 3, May 2008.
  146. */
  147. #define VLEN_BYTES 16
  148. #define VLEN_FLOATS (VLEN_BYTES / sizeof(FLOAT))
  149. typedef FLOAT vector_float __attribute__ ((vector_size (16)));
  150. /**
  151. * Calculate for a row-block in C_i of size ROWSxCOLS using vector intrinsics.
  152. *
  153. * @param[in] A Pointer current block of input matrix A.
  154. * @param[in] k Number of columns in A.
  155. * @param[in] B Pointer current block of input matrix B.
  156. * @param[inout] C Pointer current block of output matrix C.
  157. * @param[in] ldc Offset between elements in adjacent columns in C.
  158. * @param[in] alpha Scalar factor.
  159. */
  160. #define VECTOR_BLOCK(ROWS, COLS) \
  161. static inline void GEBP_block_##ROWS##_##COLS( \
  162. FLOAT const *restrict A, BLASLONG bk, FLOAT const *restrict B, \
  163. FLOAT *restrict C, BLASLONG ldc, FLOAT alpha) { \
  164. _Static_assert( \
  165. ROWS % VLEN_FLOATS == 0, \
  166. "rows in block must be multiples of vector length"); \
  167. vector_float Caux[ROWS / VLEN_FLOATS][COLS]; \
  168. \
  169. for (BLASLONG i = 0; i < ROWS / VLEN_FLOATS; i++) \
  170. for (BLASLONG j = 0; j < COLS; j++) \
  171. Caux[i][j] = vec_splats(ZERO); \
  172. \
  173. /* \
  174. * Stream over the row-block of A, which is packed \
  175. * column-by-column, multiply by coefficients in B and add up \
  176. * into temporaries Caux (which the compiler will hold in \
  177. * registers). Vectorization: Multiply column vectors from A \
  178. * with scalars from B and add up in column vectors of Caux. \
  179. * That equates to unrolling the loop over rows (in i) and \
  180. * executing each unrolled iteration as a vector element. \
  181. */ \
  182. for (BLASLONG k = 0; k < bk; k++) { \
  183. for (BLASLONG i = 0; i < ROWS / VLEN_FLOATS; i++) { \
  184. vector_float Ak = \
  185. *(vector_float *)(A + i * VLEN_FLOATS + \
  186. k * ROWS); \
  187. \
  188. for (BLASLONG j = 0; j < COLS; j++) \
  189. Caux[i][j] += Ak * B[j + k * COLS]; \
  190. } \
  191. } \
  192. \
  193. /* \
  194. * Unpack row-block of C_aux into outer C_i, multiply by \
  195. * alpha and add up. \
  196. */ \
  197. for (BLASLONG j = 0; j < COLS; j++) { \
  198. for (BLASLONG i = 0; i < ROWS / VLEN_FLOATS; i++) { \
  199. vector_float *C_ij = \
  200. (vector_float *)(C + i * VLEN_FLOATS + \
  201. j * ldc); \
  202. if (trmm) { \
  203. *C_ij = alpha * Caux[i][j]; \
  204. } else { \
  205. *C_ij += alpha * Caux[i][j]; \
  206. } \
  207. } \
  208. } \
  209. }
  210. VECTOR_BLOCK(8, 4)
  211. VECTOR_BLOCK(8, 2)
  212. VECTOR_BLOCK(8, 1)
  213. VECTOR_BLOCK(4, 4)
  214. VECTOR_BLOCK(4, 2)
  215. VECTOR_BLOCK(4, 1)
  216. #ifdef DOUBLE
  217. VECTOR_BLOCK(2, 4)
  218. VECTOR_BLOCK(2, 2)
  219. #endif
  220. /**
  221. * Handle calculation for row blocks in C_i of any size by dispatching into
  222. * macro-defined (inline) functions or by deferring to a simple generic
  223. * implementation. Note that the compiler can remove this awkward-looking
  224. * dispatching code while inlineing.
  225. *
  226. * @param[in] m Number of rows in block C_i.
  227. * @param[in] n Number of columns in block C_i.
  228. * @param[in] first_row Index of first row of the block C_i (relative to C).
  229. * @param[in] A Pointer to input matrix A (note: all of it).
  230. * @param[in] k Number of columns in A and rows in B.
  231. * @param[in] B Pointer to current column block (panel) of input matrix B.
  232. * @param[inout] C Pointer to current column block (panel) of output matrix C.
  233. * @param[in] ldc Offset between elements in adjacent columns in C.
  234. * @param[in] alpha Scalar factor.
  235. * @param[in] offset Number of columns of A and rows of B to skip (for triangular matrices).
  236. * @param[in] off Running offset for handling triangular matrices.
  237. */
  238. static inline void GEBP_block(BLASLONG m, BLASLONG n,
  239. BLASLONG first_row,
  240. const FLOAT * restrict A, BLASLONG k,
  241. const FLOAT * restrict B,
  242. FLOAT *restrict C, BLASLONG ldc,
  243. FLOAT alpha,
  244. BLASLONG offset, BLASLONG off)
  245. {
  246. if (trmm && left)
  247. off = offset + first_row;
  248. A += first_row * k;
  249. C += first_row;
  250. if (trmm) {
  251. if (backwards) {
  252. A += off * m;
  253. B += off * n;
  254. k -= off;
  255. } else {
  256. if (left) {
  257. k = off + m;
  258. } else {
  259. k = off + n;
  260. }
  261. }
  262. }
  263. #define BLOCK(bm, bn) \
  264. if (m == bm && n == bn) { \
  265. GEBP_block_##bm##_##bn(A, k, B, C, ldc, alpha); \
  266. return; \
  267. }
  268. BLOCK(8, 4); BLOCK(8, 2); BLOCK(8, 1);
  269. BLOCK(4, 4); BLOCK(4, 2); BLOCK(4, 1);
  270. #ifdef DOUBLE
  271. BLOCK(2, 4);
  272. BLOCK(2, 2);
  273. #endif
  274. #undef BLOCK
  275. /* simple implementation for smaller block sizes: */
  276. FLOAT Caux[m][n] __attribute__ ((aligned (16)));
  277. /*
  278. * Peel off first iteration (i.e., column of A) for initializing Caux
  279. */
  280. for (BLASLONG i = 0; i < m; i++)
  281. for (BLASLONG j = 0; j < n; j++)
  282. Caux[i][j] = A[i] * B[j];
  283. for (BLASLONG kk = 1; kk < k; kk++)
  284. for (BLASLONG i = 0; i < m; i++)
  285. for (BLASLONG j = 0; j < n; j++)
  286. Caux[i][j] += A[i + kk * m] * B[j + kk * n];
  287. for (BLASLONG i = 0; i < m; i++)
  288. for (BLASLONG j = 0; j < n; j++)
  289. if (trmm) {
  290. C[i + j * ldc] = alpha * Caux[i][j];
  291. } else {
  292. C[i + j * ldc] += alpha * Caux[i][j];
  293. }
  294. }
  295. /**
  296. * Handle a column block (panel) of C and B while calculating C += alpha(A * B).
  297. *
  298. * @param[in] num_cols Number of columns in the block (in C and B).
  299. * @param[in] first_col First column of the current block (in C and B).
  300. * @param[in] A Pointer to input matrix A.
  301. * @param[in] bk Number of columns in A and rows in B.
  302. * @param[in] B Pointer to input matrix B (note: all of it).
  303. * @param[in] bm Number of rows in C and A.
  304. * @param[inout] C Pointer to output matrix C (note: all of it).
  305. * @param[in] ldc Offset between elements in adjacent columns in C.
  306. * @param[in] alpha Scalar factor.
  307. * @param[in] offset Number of columns of A and rows of B to skip (for triangular matrices).
  308. */
  309. static inline void GEBP_column_block(BLASLONG num_cols, BLASLONG first_col,
  310. const FLOAT *restrict A, BLASLONG bk,
  311. const FLOAT *restrict B, BLASLONG bm,
  312. FLOAT *restrict C, BLASLONG ldc,
  313. FLOAT alpha,
  314. BLASLONG const offset) {
  315. FLOAT *restrict C_i = C + first_col * ldc;
  316. /*
  317. * B is in column-order with n_r packed row elements, which does
  318. * not matter -- we always move in full such blocks of
  319. * column*pack
  320. */
  321. const FLOAT *restrict B_i = B + first_col * bk;
  322. BLASLONG off = 0;
  323. if (trmm) {
  324. if (left) {
  325. off = offset;
  326. } else {
  327. off = -offset + first_col;
  328. }
  329. }
  330. /*
  331. * Calculate C_aux := A * B_j
  332. * then unpack C_i += alpha * C_aux.
  333. *
  334. * For that purpose, further partition C_aux and A into blocks
  335. * of m_r (unroll_m) rows, or powers-of-2 if smaller.
  336. */
  337. BLASLONG row = 0;
  338. for (BLASLONG block_size = unroll_m; block_size > 0; block_size /= 2)
  339. for (; bm - row >= block_size; row += block_size)
  340. GEBP_block(block_size, num_cols, row, A, bk, B_i, C_i,
  341. ldc, alpha, offset, off);
  342. }
  343. /**
  344. * Inner kernel for matrix-matrix multiplication. C += alpha (A * B)
  345. * where C is an m-by-n matrix, A is m-by-k and B is k-by-n. Note that A, B, and
  346. * C are pointers to submatrices of the actual matrices.
  347. *
  348. * For triangular matrix multiplication, calculate B := alpha (A * B) where A
  349. * or B can be triangular (in case of A, the macro LEFT will be defined).
  350. *
  351. * @param[in] bm Number of rows in C and A.
  352. * @param[in] bn Number of columns in C and B.
  353. * @param[in] bk Number of columns in A and rows in B.
  354. * @param[in] alpha Scalar factor.
  355. * @param[in] ba Pointer to input matrix A.
  356. * @param[in] bb Pointer to input matrix B.
  357. * @param[inout] C Pointer to output matrix C.
  358. * @param[in] ldc Offset between elements in adjacent columns in C.
  359. * @param[in] offset Number of columns of A and rows of B to skip (for triangular matrices).
  360. * @returns 0 on success.
  361. */
  362. int CNAME(BLASLONG bm, BLASLONG bn, BLASLONG bk, FLOAT alpha,
  363. FLOAT *restrict ba, FLOAT *restrict bb,
  364. FLOAT *restrict C, BLASLONG ldc
  365. #ifdef TRMMKERNEL
  366. , BLASLONG offset
  367. #endif
  368. )
  369. {
  370. if ( (bm == 0) || (bn == 0) || (bk == 0) || (alpha == ZERO))
  371. return 0;
  372. /*
  373. * interface code allocates buffers for ba and bb at page
  374. * granularity (i.e., using mmap(MAP_ANONYMOUS), so enable the compiler
  375. * to make use of the fact in vector load operations.
  376. */
  377. ba = __builtin_assume_aligned(ba, 16);
  378. bb = __builtin_assume_aligned(bb, 16);
  379. /*
  380. * Use offset and off even when compiled as SGEMMKERNEL to simplify
  381. * function signatures and function calls.
  382. */
  383. #ifndef TRMMKERNEL
  384. BLASLONG const offset = 0;
  385. #endif
  386. /*
  387. * Partition B and C into blocks of n_r (unroll_n) columns, called B_i
  388. * and C_i. For each partition, calculate C_i += alpha * (A * B_j).
  389. *
  390. * For remaining columns that do not fill up a block of n_r, iteratively
  391. * use smaller block sizes of powers of 2.
  392. */
  393. BLASLONG col = 0;
  394. for (BLASLONG block_size = unroll_n; block_size > 0; block_size /= 2)
  395. for (; bn - col >= block_size; col += block_size)
  396. GEBP_column_block(block_size, col, ba, bk, bb, bm, C, ldc, alpha, offset);
  397. return 0;
  398. }