ggml-blas.cpp 13 KB

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