ggml-blas.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**
  2. * llama.cpp - commit 8962422b1c6f9b8b15f5aeaea42600bcc2d44177 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #ifdef GGML_USE_BLAS
  27. #include "ggml-blas.h"
  28. #include "ggml-backend-impl.h"
  29. #include <future>
  30. #include <vector>
  31. #if defined(GGML_USE_ACCELERATE)
  32. # include <Accelerate/Accelerate.h>
  33. #elif defined(GGML_BLAS_USE_MKL)
  34. # include <mkl.h>
  35. #elif defined(GGML_BLAS_USE_BLIS)
  36. # include <blis.h>
  37. #elif defined(GGML_BLAS_USE_NVPL)
  38. # include <nvpl_blas.h>
  39. #else
  40. # include <cblas.h>
  41. #endif
  42. struct ggml_backend_blas_context {
  43. int n_threads = GGML_DEFAULT_N_THREADS;
  44. std::unique_ptr<char[]> work_data;
  45. size_t work_size = 0;
  46. #ifndef GGML_USE_OPENMP
  47. std::vector<std::future<void>> tasks;
  48. #endif
  49. };
  50. // helper function to determine if it is better to use BLAS or not
  51. // for large matrices, BLAS is faster
  52. static bool ggml_backend_blas_use_blas(const struct ggml_tensor * dst) {
  53. const struct ggml_tensor * src0 = dst->src[0];
  54. const struct ggml_tensor * src1 = dst->src[1];
  55. const int64_t ne10 = src1->ne[0];
  56. const int64_t ne0 = dst->ne[0];
  57. const int64_t ne1 = dst->ne[1];
  58. // TODO: find the optimal values for these
  59. if (ggml_is_contiguous(src0) &&
  60. ggml_is_contiguous(src1) &&
  61. src1->type == GGML_TYPE_F32 &&
  62. (ne0 >= 32 && ne1 >= 32 && ne10 >= 32)) {
  63. /*printf("BLAS: %d %d %d %d %d\n", ne0, ne1, ne10, ne00, ne01);*/
  64. return true;
  65. }
  66. return false;
  67. }
  68. static void ggml_backend_blas_mul_mat(ggml_backend_blas_context * ctx, struct ggml_tensor * dst) {
  69. const struct ggml_tensor * src0 = dst->src[0];
  70. const struct ggml_tensor * src1 = dst->src[1];
  71. GGML_TENSOR_BINARY_OP_LOCALS
  72. const enum ggml_type type = src0->type;
  73. GGML_ASSERT(ne0 == ne01);
  74. GGML_ASSERT(ne1 == ne11);
  75. GGML_ASSERT(ne2 == ne12);
  76. GGML_ASSERT(ne3 == ne13);
  77. // we don't support permuted src0 or src1
  78. GGML_ASSERT(nb00 == ggml_type_size(type));
  79. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  80. // dst cannot be transposed or permuted
  81. GGML_ASSERT(nb0 == sizeof(float));
  82. GGML_ASSERT(nb0 <= nb1);
  83. GGML_ASSERT(nb1 <= nb2);
  84. GGML_ASSERT(nb2 <= nb3);
  85. // broadcast factors
  86. const int64_t r2 = ne12/ne02;
  87. const int64_t r3 = ne13/ne03;
  88. const int64_t ne_plane = ne01*ne00;
  89. const size_t desired_wsize = type == GGML_TYPE_F32 ? 0 : ne03*ne02*ne_plane*sizeof(float);
  90. if (ctx->work_size < desired_wsize) {
  91. ctx->work_data.reset(new char[desired_wsize]);
  92. ctx->work_size = desired_wsize;
  93. }
  94. void * wdata = ctx->work_data.get();
  95. // convert src0 to float
  96. if (type != GGML_TYPE_F32) {
  97. ggml_type_traits_t type_traits = ggml_internal_get_type_traits(type);
  98. ggml_to_float_t const to_float = type_traits.to_float;
  99. for (int64_t i03 = 0; i03 < ne03; i03++) {
  100. for (int64_t i02 = 0; i02 < ne02; i02++) {
  101. const void * x = (char *) src0->data + i02*nb02 + i03*nb03;
  102. float * const wplane = (float *) wdata + i02*ne_plane + i03*ne02*ne_plane;
  103. const int min_cols_per_thread = 4096;
  104. const int min_rows_per_thread = std::max((int)(min_cols_per_thread/ne00), 1);
  105. const int n_threads = std::max(std::min(ctx->n_threads, (int)(ne01/min_rows_per_thread)), 1);
  106. #ifdef GGML_USE_OPENMP
  107. #pragma omp parallel for num_threads(n_threads)
  108. for (int64_t i01 = 0; i01 < ne01; i01++) {
  109. to_float((const char *) x + i01*nb01, wplane + i01*ne00, ne00);
  110. }
  111. #else
  112. for (int i = 1; i < n_threads; i++) {
  113. const int64_t start = i*ne01/n_threads;
  114. const int64_t end = (i + 1)*ne01/n_threads;
  115. if (start < end) {
  116. ctx->tasks.push_back(std::async(std::launch::async, [=]() {
  117. for (int64_t i01 = start; i01 < end; i01++) {
  118. to_float((const char *) x + i01*nb01, wplane + i01*ne00, ne00);
  119. }
  120. }));
  121. }
  122. }
  123. {
  124. // reuse the current thread for the first task
  125. const int64_t start = 0;
  126. const int64_t end = ne01/n_threads;
  127. for (int64_t i01 = start; i01 < end; i01++) {
  128. to_float((const char *) x + i01*nb01, wplane + i01*ne00, ne00);
  129. }
  130. }
  131. #endif
  132. }
  133. }
  134. #ifndef GGML_USE_OPENMP
  135. // wait for all tasks to finish
  136. for (auto & task : ctx->tasks) {
  137. task.get();
  138. }
  139. ctx->tasks.clear();
  140. #endif
  141. }
  142. #if defined(OPENBLAS_VERSION)
  143. openblas_set_num_threads(ctx->n_threads);
  144. #endif
  145. #if defined(GGML_BLAS_USE_BLIS)
  146. bli_thread_set_num_threads(ctx->n_threads);
  147. #endif
  148. #if defined(GGML_BLAS_USE_NVPL)
  149. nvpl_blas_set_num_threads(ctx->n_threads);
  150. #endif
  151. for (int64_t i13 = 0; i13 < ne13; i13++) {
  152. for (int64_t i12 = 0; i12 < ne12; i12++) {
  153. const int64_t i03 = i13/r3;
  154. const int64_t i02 = i12/r2;
  155. const float * x = (float *) ((char *) src0->data + i02*nb02 + i03*nb03);
  156. const float * y = (float *) ((char *) src1->data + i12*nb12 + i13*nb13);
  157. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  158. if (type != GGML_TYPE_F32) {
  159. x = (float *) wdata + i02*ne_plane + i03*ne02*ne_plane;
  160. }
  161. cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
  162. ne1, ne01, ne10,
  163. 1.0f, y, ne10,
  164. x, ne00,
  165. 0.0f, d, ne01);
  166. }
  167. }
  168. }
  169. static void ggml_backend_blas_out_prod(ggml_backend_blas_context * ctx, struct ggml_tensor * dst) {
  170. const struct ggml_tensor * src0 = dst->src[0];
  171. const struct ggml_tensor * src1 = dst->src[1];
  172. GGML_TENSOR_BINARY_OP_LOCALS
  173. GGML_ASSERT(ne0 == ne00);
  174. GGML_ASSERT(ne1 == ne10);
  175. GGML_ASSERT(ne2 == ne02);
  176. GGML_ASSERT(ne02 == ne12);
  177. GGML_ASSERT(ne3 == ne13);
  178. GGML_ASSERT(ne03 == ne13);
  179. // we don't support permuted src0 or src1
  180. GGML_ASSERT(nb00 == sizeof(float));
  181. // dst cannot be transposed or permuted
  182. GGML_ASSERT(nb0 == sizeof(float));
  183. // GGML_ASSERT(nb0 <= nb1);
  184. // GGML_ASSERT(nb1 <= nb2);
  185. // GGML_ASSERT(nb2 <= nb3);
  186. // Arguments to ggml_compute_forward_out_prod (expressed as major,minor)
  187. // src0: (k,n)
  188. // src1: (k,m)
  189. // dst: (m,n)
  190. //
  191. // Arguments to sgemm (see https://github.com/Reference-LAPACK/lapack/blob/master/BLAS/SRC/sgemm.f)
  192. // Also expressed as (major,minor)
  193. // a: (m,k): so src1 transposed
  194. // b: (k,n): so src0
  195. // c: (m,n)
  196. //
  197. // However, if ggml_is_transposed(src1) is true, then
  198. // src1->data already contains a transposed version, so sgemm mustn't
  199. // transpose it further.
  200. int n = src0->ne[0];
  201. int k = src0->ne[1];
  202. int m = src1->ne[0];
  203. CBLAS_TRANSPOSE transposeA;
  204. int lda;
  205. if (!ggml_is_transposed(src1)) {
  206. transposeA = CblasTrans;
  207. lda = m;
  208. } else {
  209. transposeA = CblasNoTrans;
  210. lda = k;
  211. }
  212. float * a = (float *) ((char *) src1->data);
  213. float * b = (float *) ((char *) src0->data);
  214. float * c = (float *) ((char *) dst->data);
  215. cblas_sgemm(CblasRowMajor, transposeA, CblasNoTrans, m, n, k, 1.0, a, lda, b, n, 0.0, c, n);
  216. GGML_UNUSED(ctx);
  217. }
  218. // backend interface
  219. GGML_CALL static const char * ggml_backend_blas_name(ggml_backend_t backend) {
  220. return "BLAS";
  221. GGML_UNUSED(backend);
  222. }
  223. GGML_CALL static void ggml_backend_blas_free(ggml_backend_t backend) {
  224. ggml_backend_blas_context * ctx = (ggml_backend_blas_context *)backend->context;
  225. delete ctx;
  226. delete backend;
  227. }
  228. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_blas_get_default_buffer_type(ggml_backend_t backend) {
  229. return ggml_backend_cpu_buffer_type();
  230. GGML_UNUSED(backend);
  231. }
  232. GGML_CALL static enum ggml_status ggml_backend_blas_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  233. ggml_backend_blas_context * ctx = (ggml_backend_blas_context *)backend->context;
  234. for (int i = 0; i < cgraph->n_nodes; i++) {
  235. struct ggml_tensor * node = cgraph->nodes[i];
  236. switch (node->op) {
  237. case GGML_OP_MUL_MAT:
  238. ggml_backend_blas_mul_mat(ctx, node);
  239. break;
  240. case GGML_OP_OUT_PROD:
  241. ggml_backend_blas_out_prod(ctx, node);
  242. break;
  243. case GGML_OP_NONE:
  244. case GGML_OP_RESHAPE:
  245. case GGML_OP_VIEW:
  246. case GGML_OP_PERMUTE:
  247. case GGML_OP_TRANSPOSE:
  248. break;
  249. default:
  250. GGML_ABORT("%s: unsupported op %s\n", __func__, ggml_op_desc(node));
  251. }
  252. }
  253. return GGML_STATUS_SUCCESS;
  254. GGML_UNUSED(backend);
  255. }
  256. GGML_CALL static bool ggml_backend_blas_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  257. const struct ggml_tensor * src0 = op->src[0];
  258. const struct ggml_tensor * src1 = op->src[1];
  259. return (op->op == GGML_OP_MUL_MAT && ggml_backend_blas_use_blas(op)) ||
  260. (op->op == GGML_OP_OUT_PROD && op->src[0]->type == GGML_TYPE_F32 &&
  261. op->src[1]->type == GGML_TYPE_F32 &&
  262. ggml_is_matrix(src0) &&
  263. ggml_is_matrix(src1) &&
  264. ggml_is_contiguous(src0) &&
  265. (ggml_is_contiguous(src1) || ggml_is_transposed(src1)));
  266. GGML_UNUSED(backend);
  267. }
  268. GGML_CALL static bool ggml_backend_blas_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
  269. return ggml_backend_buft_is_host(buft);
  270. GGML_UNUSED(backend);
  271. }
  272. static struct ggml_backend_i blas_backend_i = {
  273. /* .get_name = */ ggml_backend_blas_name,
  274. /* .free = */ ggml_backend_blas_free,
  275. /* .get_default_buffer_type = */ ggml_backend_blas_get_default_buffer_type,
  276. /* .set_tensor_async = */ NULL,
  277. /* .get_tensor_async = */ NULL,
  278. /* .cpy_tensor_async = */ NULL,
  279. /* .synchronize = */ NULL,
  280. /* .graph_plan_create = */ NULL,
  281. /* .graph_plan_free = */ NULL,
  282. /* .graph_plan_update = */ NULL,
  283. /* .graph_plan_compute = */ NULL,
  284. /* .graph_compute = */ ggml_backend_blas_graph_compute,
  285. /* .supports_op = */ ggml_backend_blas_supports_op,
  286. /* .supports_buft = */ ggml_backend_blas_supports_buft,
  287. /* .offload_op = */ NULL,
  288. /* .event_new = */ NULL,
  289. /* .event_free = */ NULL,
  290. /* .event_record = */ NULL,
  291. /* .event_wait = */ NULL,
  292. /* .event_synchronize = */ NULL,
  293. };
  294. static ggml_guid_t ggml_backend_blas_guid(void) {
  295. static ggml_guid guid = { 0x12, 0xa8, 0xae, 0xf4, 0xc0, 0x1e, 0x61, 0x97, 0x8f, 0xeb, 0x33, 0x04, 0xa1, 0x33, 0x51, 0x2d };
  296. return &guid;
  297. }
  298. ggml_backend_t ggml_backend_blas_init(void) {
  299. ggml_backend_blas_context * ctx = new ggml_backend_blas_context;
  300. ggml_backend_t backend = new ggml_backend {
  301. /* .guid = */ ggml_backend_blas_guid(),
  302. /* .interface = */ blas_backend_i,
  303. /* .context = */ ctx,
  304. };
  305. #if !defined(NDEBUG) && defined(OPENBLAS_VERSION) && defined(GGML_USE_OPENMP)
  306. if (openblas_get_parallel() != OPENBLAS_OPENMP) {
  307. fprintf(stderr, "%s: warning: ggml is using OpenMP, but OpenBLAS was compiled without OpenMP support\n", __func__);
  308. }
  309. #endif
  310. #if !defined(NDEBUG) && defined(BLIS_ENABLE_CBLAS) && defined(GGML_USE_OPENMP) && !defined(BLIS_ENABLE_OPENMP)
  311. fprintf(stderr, "%s: warning: ggml is using OpenMP, but BLIS was compiled without OpenMP support\n", __func__);
  312. #endif
  313. return backend;
  314. }
  315. GGML_CALL bool ggml_backend_is_blas(ggml_backend_t backend) {
  316. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_blas_guid());
  317. }
  318. void ggml_backend_blas_set_n_threads(ggml_backend_t backend_blas, int n_threads) {
  319. GGML_ASSERT(ggml_backend_is_blas(backend_blas));
  320. ggml_backend_blas_context * ctx = (ggml_backend_blas_context *)backend_blas->context;
  321. ctx->n_threads = n_threads;
  322. }
  323. #endif