ggml-alloc.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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. #include "ggml-alloc.h"
  27. #include "ggml-backend-impl.h"
  28. #include "ggml.h"
  29. #include "ggml-impl.h"
  30. #include <assert.h>
  31. #include <limits.h>
  32. #include <stdarg.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  37. #define MAX_FREE_BLOCKS 256
  38. //#define GGML_ALLOCATOR_DEBUG
  39. //#define AT_PRINTF(...) fprintf(stderr, __VA_ARGS__)
  40. #define AT_PRINTF(...)
  41. static bool ggml_is_view(const struct ggml_tensor * t) {
  42. return t->view_src != NULL;
  43. }
  44. static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
  45. if (a->type != b->type) {
  46. return false;
  47. }
  48. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  49. if (a->ne[i] != b->ne[i]) {
  50. return false;
  51. }
  52. if (a->nb[i] != b->nb[i]) {
  53. return false;
  54. }
  55. }
  56. return true;
  57. }
  58. static bool ggml_op_can_inplace(enum ggml_op op) {
  59. switch (op) {
  60. case GGML_OP_SCALE:
  61. case GGML_OP_DIAG_MASK_ZERO:
  62. case GGML_OP_DIAG_MASK_INF:
  63. case GGML_OP_ADD:
  64. case GGML_OP_ADD1:
  65. case GGML_OP_SUB:
  66. case GGML_OP_MUL:
  67. case GGML_OP_DIV:
  68. case GGML_OP_SQR:
  69. case GGML_OP_SQRT:
  70. case GGML_OP_LOG:
  71. case GGML_OP_UNARY:
  72. case GGML_OP_ROPE:
  73. case GGML_OP_RMS_NORM:
  74. case GGML_OP_SOFT_MAX:
  75. return true;
  76. default:
  77. return false;
  78. }
  79. }
  80. static size_t aligned_offset(const void * buffer, size_t offset, size_t alignment) {
  81. assert(alignment && !(alignment & (alignment - 1))); // power of 2
  82. size_t align = (alignment - (((uintptr_t)buffer + offset) % alignment)) % alignment;
  83. return offset + align;
  84. }
  85. // tallocr
  86. struct ggml_tallocr ggml_tallocr_new(ggml_backend_buffer_t buffer) {
  87. void * base = ggml_backend_buffer_get_base(buffer);
  88. size_t align = ggml_backend_buffer_get_alignment(buffer);
  89. assert(align && !(align & (align - 1))); // power of 2
  90. struct ggml_tallocr talloc = (struct ggml_tallocr) {
  91. /*.buffer = */ buffer,
  92. /*.base = */ base,
  93. /*.alignment = */ align,
  94. /*.offset = */ aligned_offset(base, 0, align),
  95. };
  96. return talloc;
  97. }
  98. void ggml_tallocr_alloc(struct ggml_tallocr * talloc, struct ggml_tensor * tensor) {
  99. size_t size = ggml_backend_buffer_get_alloc_size(talloc->buffer, tensor);
  100. size = GGML_PAD(size, talloc->alignment);
  101. if (talloc->offset + size > ggml_backend_buffer_get_size(talloc->buffer)) {
  102. fprintf(stderr, "%s: not enough space in the buffer to allocate %s (needed %zu, available %zu)\n",
  103. __func__, tensor->name, size, ggml_backend_buffer_get_size(talloc->buffer) - talloc->offset);
  104. GGML_ABORT("not enough space in the buffer");
  105. }
  106. void * addr = (char *)ggml_backend_buffer_get_base(talloc->buffer) + talloc->offset;
  107. talloc->offset += size;
  108. assert(((uintptr_t)addr % talloc->alignment) == 0);
  109. ggml_backend_tensor_alloc(talloc->buffer, tensor, addr);
  110. }
  111. // dynamic tensor allocator
  112. struct free_block {
  113. size_t offset;
  114. size_t size;
  115. };
  116. struct ggml_dyn_tallocr {
  117. size_t alignment;
  118. int n_free_blocks;
  119. struct free_block free_blocks[MAX_FREE_BLOCKS];
  120. size_t max_size;
  121. #ifdef GGML_ALLOCATOR_DEBUG
  122. struct {
  123. const struct ggml_tensor * tensor;
  124. size_t offset;
  125. } allocated_tensors[1024];
  126. #endif
  127. };
  128. #ifdef GGML_ALLOCATOR_DEBUG
  129. static void add_allocated_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, const struct ggml_tensor * tensor) {
  130. for (int i = 0; i < 1024; i++) {
  131. if (alloc->allocated_tensors[i].tensor == NULL) {
  132. alloc->allocated_tensors[i].tensor = tensor;
  133. alloc->allocated_tensors[i].offset = offset;
  134. return;
  135. }
  136. }
  137. GGML_ABORT("out of allocated_tensors");
  138. }
  139. static void remove_allocated_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, const struct ggml_tensor * tensor) {
  140. for (int i = 0; i < 1024; i++) {
  141. if (alloc->allocated_tensors[i].offset == offset) {
  142. alloc->allocated_tensors[i].tensor = NULL;
  143. return;
  144. }
  145. }
  146. GGML_ABORT("tried to free tensor %s not found\n", tensor->name);
  147. }
  148. #endif
  149. static size_t ggml_dyn_tallocr_alloc(struct ggml_dyn_tallocr * alloc, size_t size, const struct ggml_tensor * tensor) {
  150. size = aligned_offset(NULL, size, alloc->alignment);
  151. AT_PRINTF("%s: allocating %s (%zu bytes) - ", __func__, tensor->name, size);
  152. size_t max_avail = 0;
  153. // find the best fitting free block besides the last block
  154. int best_fit_block = -1;
  155. size_t best_fit_size = SIZE_MAX;
  156. for (int i = 0; i < alloc->n_free_blocks - 1; i++) {
  157. struct free_block * block = &alloc->free_blocks[i];
  158. max_avail = MAX(max_avail, block->size);
  159. if (block->size >= size && block->size <= best_fit_size) {
  160. best_fit_block = i;
  161. best_fit_size = block->size;
  162. }
  163. }
  164. if (best_fit_block == -1) {
  165. // the last block is our last resort
  166. struct free_block * block = &alloc->free_blocks[alloc->n_free_blocks - 1];
  167. max_avail = MAX(max_avail, block->size);
  168. if (block->size >= size) {
  169. best_fit_block = alloc->n_free_blocks - 1;
  170. } else {
  171. // this should never happen
  172. fprintf(stderr, "%s: not enough space in the buffer to allocate %zu bytes, largest block available %zu bytes\n",
  173. __func__, size, max_avail);
  174. GGML_ABORT("not enough space in the buffer");
  175. }
  176. }
  177. struct free_block * block = &alloc->free_blocks[best_fit_block];
  178. size_t offset = block->offset;
  179. block->offset = offset + size;
  180. block->size -= size;
  181. if (block->size == 0) {
  182. // remove block if empty
  183. alloc->n_free_blocks--;
  184. for (int j = best_fit_block; j < alloc->n_free_blocks; j++) {
  185. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  186. }
  187. }
  188. AT_PRINTF("block %d, offset %zu\n", best_fit_block, offset);
  189. #ifdef GGML_ALLOCATOR_DEBUG
  190. add_allocated_tensor(alloc, offset, tensor);
  191. size_t cur_max = offset + size;
  192. if (cur_max > alloc->max_size) {
  193. // sort allocated_tensors by offset
  194. for (int i = 0; i < 1024; i++) {
  195. for (int j = i + 1; j < 1024; j++) {
  196. if (alloc->allocated_tensors[i].offset > alloc->allocated_tensors[j].offset) {
  197. const struct ggml_tensor * tmp_tensor = alloc->allocated_tensors[i].tensor;
  198. size_t tmp_offset = alloc->allocated_tensors[i].offset;
  199. alloc->allocated_tensors[i].tensor = alloc->allocated_tensors[j].tensor;
  200. alloc->allocated_tensors[i].offset = alloc->allocated_tensors[j].offset;
  201. alloc->allocated_tensors[j].tensor = tmp_tensor;
  202. alloc->allocated_tensors[j].offset = tmp_offset;
  203. }
  204. }
  205. }
  206. fprintf(stderr, "max_size = %.2f MB: tensors: ", cur_max / 1024.0 / 1024.0);
  207. for (int i = 0; i < 1024; i++) {
  208. if (alloc->allocated_tensors[i].tensor) {
  209. fprintf(stderr, "%s [%zx-%zx] (%.2f MB) ", alloc->allocated_tensors[i].tensor->name,
  210. alloc->allocated_tensors[i].offset,
  211. alloc->allocated_tensors[i].offset + ggml_nbytes(alloc->allocated_tensors[i].tensor),
  212. ggml_nbytes(alloc->allocated_tensors[i].tensor) / 1024.0 / 1024.0);
  213. }
  214. }
  215. fprintf(stderr, "\n");
  216. }
  217. #endif
  218. alloc->max_size = MAX(alloc->max_size, offset + size);
  219. return offset;
  220. GGML_UNUSED(tensor);
  221. }
  222. // this is a very naive implementation, but for our case the number of free blocks should be very small
  223. static void ggml_dyn_tallocr_free_tensor(struct ggml_dyn_tallocr * alloc, size_t offset, size_t size, const struct ggml_tensor * tensor) {
  224. size = aligned_offset(NULL, size, alloc->alignment);
  225. AT_PRINTF("%s: freeing %s at %zu (%zu bytes) - n_free_blocks = %d\n", __func__, tensor->name, offset, size, alloc->n_free_blocks);
  226. #ifdef GGML_ALLOCATOR_DEBUG
  227. remove_allocated_tensor(alloc, offset, tensor);
  228. #endif
  229. // see if we can merge with an existing block
  230. for (int i = 0; i < alloc->n_free_blocks; i++) {
  231. struct free_block * block = &alloc->free_blocks[i];
  232. // check if ptr is at the end of the block
  233. if (block->offset + block->size == offset) {
  234. block->size += size;
  235. // check if we can merge with the next block
  236. if (i < alloc->n_free_blocks - 1 && block->offset + block->size == alloc->free_blocks[i+1].offset) {
  237. block->size += alloc->free_blocks[i+1].size;
  238. alloc->n_free_blocks--;
  239. for (int j = i+1; j < alloc->n_free_blocks; j++) {
  240. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  241. }
  242. }
  243. return;
  244. }
  245. // check if ptr is at the beginning of the block
  246. if (offset + size == block->offset) {
  247. block->offset = offset;
  248. block->size += size;
  249. // check if we can merge with the previous block
  250. if (i > 0 && alloc->free_blocks[i-1].offset + alloc->free_blocks[i-1].size == block->offset) {
  251. alloc->free_blocks[i-1].size += block->size;
  252. alloc->n_free_blocks--;
  253. for (int j = i; j < alloc->n_free_blocks; j++) {
  254. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  255. }
  256. }
  257. return;
  258. }
  259. }
  260. // otherwise, add a new block
  261. GGML_ASSERT(alloc->n_free_blocks < MAX_FREE_BLOCKS && "out of free blocks");
  262. // insert the new block in the correct position to keep the array sorted by address (to make merging blocks faster)
  263. int insert_pos = 0;
  264. while (insert_pos < alloc->n_free_blocks && alloc->free_blocks[insert_pos].offset < offset) {
  265. insert_pos++;
  266. }
  267. // shift all blocks from insert_pos onward to make room for the new block
  268. for (int i = alloc->n_free_blocks; i > insert_pos; i--) {
  269. alloc->free_blocks[i] = alloc->free_blocks[i-1];
  270. }
  271. // insert the new block
  272. alloc->free_blocks[insert_pos].offset = offset;
  273. alloc->free_blocks[insert_pos].size = size;
  274. alloc->n_free_blocks++;
  275. GGML_UNUSED(tensor);
  276. }
  277. static void ggml_dyn_tallocr_reset(struct ggml_dyn_tallocr * alloc) {
  278. alloc->n_free_blocks = 1;
  279. alloc->free_blocks[0].offset = 0;
  280. alloc->free_blocks[0].size = SIZE_MAX/2; // restrict maximum size of a measure allocator to half size_t max to avoid overflows
  281. alloc->max_size = 0;
  282. }
  283. static struct ggml_dyn_tallocr * ggml_dyn_tallocr_new(size_t alignment) {
  284. struct ggml_dyn_tallocr * alloc = (struct ggml_dyn_tallocr *)malloc(sizeof(struct ggml_dyn_tallocr));
  285. *alloc = (struct ggml_dyn_tallocr) {
  286. /*.alignment = */ alignment,
  287. /*.n_free_blocks = */ 0,
  288. /*.free_blocks = */ {{0}},
  289. /*.max_size = */ 0,
  290. #ifdef GGML_ALLOCATOR_DEBUG
  291. /*.allocated_tensors = */ {{0}},
  292. #endif
  293. };
  294. ggml_dyn_tallocr_reset(alloc);
  295. return alloc;
  296. }
  297. static void ggml_dyn_tallocr_free(struct ggml_dyn_tallocr * alloc) {
  298. free(alloc);
  299. }
  300. static size_t ggml_dyn_tallocr_max_size(struct ggml_dyn_tallocr * alloc) {
  301. return alloc->max_size;
  302. }
  303. /////////////////////////////////////
  304. // graph allocator
  305. struct hash_node {
  306. int n_children;
  307. int n_views;
  308. int buffer_id;
  309. size_t offset; // offset within the buffer
  310. bool allocated;
  311. };
  312. struct tensor_alloc {
  313. int buffer_id;
  314. size_t offset;
  315. size_t size_max; // 0 = pre-allocated, unused, or view
  316. };
  317. struct leaf_alloc {
  318. int buffer_id;
  319. struct tensor_alloc leaf;
  320. };
  321. struct node_alloc {
  322. struct tensor_alloc dst;
  323. struct tensor_alloc src[GGML_MAX_SRC];
  324. };
  325. struct ggml_gallocr {
  326. ggml_backend_buffer_type_t * bufts; // [n_buffers]
  327. ggml_backend_buffer_t * buffers; // [n_buffers]
  328. struct ggml_dyn_tallocr ** buf_tallocs; // [n_buffers]
  329. int n_buffers;
  330. struct ggml_hash_set hash_set;
  331. struct hash_node * hash_values; // [hash_set.size]
  332. struct node_alloc * node_allocs; // [n_nodes]
  333. int n_nodes;
  334. struct leaf_alloc * leaf_allocs; // [n_leafs]
  335. int n_leafs;
  336. };
  337. ggml_gallocr_t ggml_gallocr_new_n(ggml_backend_buffer_type_t * bufts, int n_bufs) {
  338. ggml_gallocr_t galloc = (ggml_gallocr_t)calloc(1, sizeof(struct ggml_gallocr));
  339. GGML_ASSERT(galloc != NULL);
  340. galloc->bufts = calloc(n_bufs, sizeof(ggml_backend_buffer_type_t));
  341. GGML_ASSERT(galloc->bufts != NULL);
  342. galloc->buffers = calloc(n_bufs, sizeof(ggml_backend_buffer_t));
  343. GGML_ASSERT(galloc->buffers != NULL);
  344. galloc->buf_tallocs = calloc(n_bufs, sizeof(struct ggml_dyn_tallocr *));
  345. GGML_ASSERT(galloc->buf_tallocs != NULL);
  346. for (int i = 0; i < n_bufs; i++) {
  347. galloc->bufts[i] = bufts[i];
  348. galloc->buffers[i] = NULL;
  349. // check if the same buffer type is used multiple times and reuse the same allocator
  350. for (int j = 0; j < i; j++) {
  351. if (bufts[i] == bufts[j]) {
  352. galloc->buf_tallocs[i] = galloc->buf_tallocs[j];
  353. break;
  354. }
  355. }
  356. if (galloc->buf_tallocs[i] == NULL) {
  357. size_t alignment = ggml_backend_buft_get_alignment(bufts[i]);
  358. galloc->buf_tallocs[i] = ggml_dyn_tallocr_new(alignment);
  359. }
  360. }
  361. galloc->n_buffers = n_bufs;
  362. return galloc;
  363. }
  364. ggml_gallocr_t ggml_gallocr_new(ggml_backend_buffer_type_t buft) {
  365. return ggml_gallocr_new_n(&buft, 1);
  366. }
  367. void ggml_gallocr_free(ggml_gallocr_t galloc) {
  368. if (galloc == NULL) {
  369. return;
  370. }
  371. for (int i = 0; i < galloc->n_buffers; i++) {
  372. if (galloc->buffers != NULL) {
  373. // skip if already freed
  374. bool freed = false;
  375. for (int j = 0; j < i; j++) {
  376. if (galloc->buffers[j] == galloc->buffers[i]) {
  377. freed = true;
  378. break;
  379. }
  380. }
  381. if (!freed) {
  382. ggml_backend_buffer_free(galloc->buffers[i]);
  383. }
  384. }
  385. if (galloc->buf_tallocs != NULL) {
  386. // skip if already freed
  387. bool freed = false;
  388. for (int j = 0; j < i; j++) {
  389. if (galloc->buf_tallocs[j] == galloc->buf_tallocs[i]) {
  390. freed = true;
  391. break;
  392. }
  393. }
  394. if (!freed) {
  395. ggml_dyn_tallocr_free(galloc->buf_tallocs[i]);
  396. }
  397. }
  398. }
  399. ggml_hash_set_free(&galloc->hash_set);
  400. free(galloc->hash_values);
  401. free(galloc->bufts);
  402. free(galloc->buffers);
  403. free(galloc->buf_tallocs);
  404. free(galloc->node_allocs);
  405. free(galloc->leaf_allocs);
  406. free(galloc);
  407. }
  408. typedef struct ggml_gallocr * ggml_gallocr_t;
  409. static struct hash_node * ggml_gallocr_hash_get(ggml_gallocr_t galloc, struct ggml_tensor * t) {
  410. size_t i = ggml_hash_find_or_insert(&galloc->hash_set, t);
  411. return &galloc->hash_values[i];
  412. }
  413. static bool ggml_gallocr_is_own(ggml_gallocr_t galloc, struct ggml_tensor * t) {
  414. return ggml_gallocr_hash_get(galloc, t)->allocated;
  415. }
  416. static void ggml_gallocr_set_node_offset(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id, size_t offset) {
  417. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  418. hn->buffer_id = buffer_id;
  419. hn->offset = offset;
  420. hn->allocated = true;
  421. }
  422. static bool ggml_gallocr_is_allocated(ggml_gallocr_t galloc, struct ggml_tensor * t) {
  423. return t->data != NULL || ggml_gallocr_hash_get(galloc, t)->allocated;
  424. }
  425. static void ggml_gallocr_allocate_node(ggml_gallocr_t galloc, struct ggml_tensor * node, int buffer_id) {
  426. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  427. if (!ggml_gallocr_is_allocated(galloc, node) && !ggml_is_view(node)) {
  428. hn->allocated = true;
  429. assert(hn->offset == 0);
  430. // try to reuse a parent's buffer (inplace)
  431. if (ggml_op_can_inplace(node->op)) {
  432. for (int i = 0; i < GGML_MAX_SRC; i++) {
  433. struct ggml_tensor * parent = node->src[i];
  434. if (parent == NULL) {
  435. continue;
  436. }
  437. // if the node's data is external, then we cannot re-use it
  438. if (!ggml_gallocr_is_own(galloc, parent)) {
  439. AT_PRINTF("not reusing parent %s for %s as %p is external\n", parent->name, node->name, parent->data);
  440. continue;
  441. }
  442. // outputs cannot be reused
  443. if (parent->flags & GGML_TENSOR_FLAG_OUTPUT || (parent->view_src != NULL && parent->view_src->flags & GGML_TENSOR_FLAG_OUTPUT)) {
  444. AT_PRINTF("not reusing parent %s for %s as it is an output\n", parent->name, node->name);
  445. continue;
  446. }
  447. if (!ggml_are_same_layout(node, parent)) {
  448. AT_PRINTF("not reusing parent %s for %s as layouts are different\n", parent->name, node->name);
  449. continue;
  450. }
  451. struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
  452. if (p_hn->n_children == 1 && p_hn->n_views == 0) {
  453. if (ggml_is_view(parent)) {
  454. struct ggml_tensor * view_src = parent->view_src;
  455. struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
  456. if (view_src_hn->n_views == 1 && view_src_hn->n_children == 0 && view_src->data == parent->data) {
  457. AT_PRINTF("reusing view parent %s (%s) for %s\n", parent->name, view_src->name, node->name);
  458. assert(view_src_hn->offset == p_hn->offset);
  459. hn->buffer_id = p_hn->buffer_id;
  460. hn->offset = p_hn->offset;
  461. p_hn->allocated = false; // avoid freeing the parent
  462. view_src_hn->allocated = false;
  463. return;
  464. }
  465. } else {
  466. AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
  467. hn->buffer_id = p_hn->buffer_id;
  468. hn->offset = p_hn->offset;
  469. p_hn->allocated = false; // avoid freeing the parent
  470. return;
  471. }
  472. }
  473. }
  474. }
  475. // allocate tensor from the buffer
  476. struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
  477. ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
  478. size_t size = ggml_backend_buft_get_alloc_size(buft, node);
  479. size_t offset = ggml_dyn_tallocr_alloc(alloc, size, node);
  480. hn->buffer_id = buffer_id;
  481. hn->offset = offset;
  482. return;
  483. }
  484. }
  485. static void ggml_gallocr_free_node(ggml_gallocr_t galloc, struct ggml_tensor * node) {
  486. // graph outputs are never freed
  487. if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
  488. AT_PRINTF("not freeing output %s\n", node->name);
  489. return;
  490. }
  491. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  492. size_t offset = hn->offset;
  493. int buffer_id = hn->buffer_id;
  494. struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
  495. ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
  496. size_t size = ggml_backend_buft_get_alloc_size(buft, node);
  497. ggml_dyn_tallocr_free_tensor(alloc, offset, size, node);
  498. hn->allocated = false;
  499. }
  500. static int get_node_buffer_id(const int * node_buffer_ids, int i) {
  501. return node_buffer_ids ? node_buffer_ids[i] : 0;
  502. }
  503. static void ggml_gallocr_alloc_graph_impl(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids) {
  504. // clear hash tables
  505. ggml_hash_set_reset(&galloc->hash_set);
  506. memset(galloc->hash_values, 0, sizeof(struct hash_node) * galloc->hash_set.size);
  507. // allocate leafs
  508. // these may be tensors that the application is not using in the graph, but may still want to allocate for other purposes
  509. for (int i = 0; i < graph->n_leafs; i++) {
  510. struct ggml_tensor * leaf = graph->leafs[i];
  511. ggml_gallocr_allocate_node(galloc, leaf, get_node_buffer_id(leaf_buffer_ids, i));
  512. }
  513. // count number of children and views
  514. // allocate other graph inputs and leafs first to avoid overwriting them
  515. for (int i = 0; i < graph->n_nodes; i++) {
  516. struct ggml_tensor * node = graph->nodes[i];
  517. // TODO: better way to add external dependencies
  518. // GGML_OP_NONE does not appear normally in the graph nodes, but is used by ggml-backend to add dependencies to
  519. // control when some tensors are allocated and freed. in this case, the dependencies are in `src`, but the node
  520. // itself is never used and should not be considered a dependency
  521. if (ggml_is_view(node) && node->op != GGML_OP_NONE) {
  522. struct ggml_tensor * view_src = node->view_src;
  523. ggml_gallocr_hash_get(galloc, view_src)->n_views += 1;
  524. }
  525. if (node->flags & GGML_TENSOR_FLAG_INPUT) {
  526. ggml_gallocr_allocate_node(galloc, graph->nodes[i], get_node_buffer_id(node_buffer_ids, i));
  527. }
  528. for (int j = 0; j < GGML_MAX_SRC; j++) {
  529. struct ggml_tensor * src = node->src[j];
  530. if (src == NULL) {
  531. continue;
  532. }
  533. ggml_gallocr_hash_get(galloc, src)->n_children += 1;
  534. // allocate explicit inputs
  535. if (src->flags & GGML_TENSOR_FLAG_INPUT) {
  536. ggml_gallocr_allocate_node(galloc, src, get_node_buffer_id(node_buffer_ids, i));
  537. }
  538. }
  539. }
  540. // allocate tensors
  541. for (int i = 0; i < graph->n_nodes; i++) {
  542. struct ggml_tensor * node = graph->nodes[i];
  543. int buffer_id = get_node_buffer_id(node_buffer_ids, i);
  544. // allocate parents (only leafs need to be allocated at this point)
  545. for (int j = 0; j < GGML_MAX_SRC; j++) {
  546. struct ggml_tensor * parent = node->src[j];
  547. if (parent == NULL) {
  548. continue;
  549. }
  550. ggml_gallocr_allocate_node(galloc, parent, buffer_id);
  551. }
  552. // allocate node
  553. ggml_gallocr_allocate_node(galloc, node, buffer_id);
  554. AT_PRINTF("exec: %s (%s) <= ", ggml_op_desc(node), node->name);
  555. for (int j = 0; j < GGML_MAX_SRC; j++) {
  556. struct ggml_tensor * parent = node->src[j];
  557. if (parent == NULL) {
  558. continue;
  559. }
  560. AT_PRINTF("%s", parent->name);
  561. if (j < GGML_MAX_SRC - 1 && node->src[j + 1] != NULL) {
  562. AT_PRINTF(", ");
  563. }
  564. }
  565. AT_PRINTF("\n");
  566. // update parents
  567. for (int j = 0; j < GGML_MAX_SRC; j++) {
  568. struct ggml_tensor * parent = node->src[j];
  569. if (parent == NULL) {
  570. continue;
  571. }
  572. struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
  573. p_hn->n_children -= 1;
  574. AT_PRINTF("parent %s: %d children, %d views, allocated: %d\n",
  575. parent->name, p_hn->n_children, p_hn->n_views, p_hn->allocated);
  576. if (p_hn->n_children == 0 && p_hn->n_views == 0) {
  577. if (ggml_is_view(parent)) {
  578. struct ggml_tensor * view_src = parent->view_src;
  579. struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
  580. view_src_hn->n_views -= 1;
  581. AT_PRINTF("view_src %s: %d children, %d views\n",
  582. view_src->name, view_src_hn->n_children, view_src_hn->n_views);
  583. if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src_hn->allocated) {
  584. ggml_gallocr_free_node(galloc, view_src);
  585. }
  586. }
  587. else if (p_hn->allocated) {
  588. ggml_gallocr_free_node(galloc, parent);
  589. }
  590. }
  591. AT_PRINTF("\n");
  592. }
  593. }
  594. }
  595. bool ggml_gallocr_reserve_n(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids) {
  596. size_t min_hash_size = graph->n_nodes + graph->n_leafs;
  597. // add 25% margin to avoid hash collisions
  598. min_hash_size += min_hash_size / 4;
  599. // initialize hash table
  600. if (galloc->hash_set.size < min_hash_size) {
  601. ggml_hash_set_free(&galloc->hash_set);
  602. galloc->hash_set = ggml_hash_set_new(min_hash_size);
  603. GGML_ASSERT(galloc->hash_set.keys != NULL);
  604. free(galloc->hash_values);
  605. galloc->hash_values = malloc(sizeof(struct hash_node) * galloc->hash_set.size);
  606. GGML_ASSERT(galloc->hash_values != NULL);
  607. }
  608. // reset allocators
  609. for (int i = 0; i < galloc->n_buffers; i++) {
  610. ggml_dyn_tallocr_reset(galloc->buf_tallocs[i]);
  611. }
  612. // allocate in hash table
  613. ggml_gallocr_alloc_graph_impl(galloc, graph, node_buffer_ids, leaf_buffer_ids);
  614. // set the node_allocs from the hash table
  615. if (galloc->n_nodes < graph->n_nodes) {
  616. free(galloc->node_allocs);
  617. galloc->node_allocs = calloc(graph->n_nodes, sizeof(struct node_alloc));
  618. GGML_ASSERT(galloc->node_allocs != NULL);
  619. }
  620. galloc->n_nodes = graph->n_nodes;
  621. for (int i = 0; i < graph->n_nodes; i++) {
  622. struct ggml_tensor * node = graph->nodes[i];
  623. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  624. if (node->view_src || node->data) {
  625. node_alloc->dst.buffer_id = -1;
  626. node_alloc->dst.offset = SIZE_MAX;
  627. node_alloc->dst.size_max = 0;
  628. } else {
  629. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  630. node_alloc->dst.buffer_id = hn->buffer_id;
  631. node_alloc->dst.offset = hn->offset;
  632. node_alloc->dst.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
  633. }
  634. for (int j = 0; j < GGML_MAX_SRC; j++) {
  635. struct ggml_tensor * src = node->src[j];
  636. if (!src || src->view_src || src->data) {
  637. node_alloc->src[j].buffer_id = -1;
  638. node_alloc->src[j].offset = SIZE_MAX;
  639. node_alloc->src[j].size_max = 0;
  640. } else {
  641. struct hash_node * hn = ggml_gallocr_hash_get(galloc, src);
  642. node_alloc->src[j].buffer_id = hn->buffer_id;
  643. node_alloc->src[j].offset = hn->offset;
  644. node_alloc->src[j].size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], src);
  645. }
  646. }
  647. }
  648. if (galloc->n_leafs < graph->n_leafs) {
  649. free(galloc->leaf_allocs);
  650. galloc->leaf_allocs = calloc(graph->n_leafs, sizeof(galloc->leaf_allocs[0]));
  651. GGML_ASSERT(galloc->leaf_allocs != NULL);
  652. }
  653. galloc->n_leafs = graph->n_leafs;
  654. for (int i = 0; i < graph->n_leafs; i++) {
  655. struct ggml_tensor * leaf = graph->leafs[i];
  656. struct hash_node * hn = ggml_gallocr_hash_get(galloc, leaf);
  657. galloc->leaf_allocs[i].buffer_id = hn->buffer_id;
  658. if (leaf->view_src || leaf->data) {
  659. galloc->leaf_allocs[i].leaf.buffer_id = -1;
  660. galloc->leaf_allocs[i].leaf.offset = SIZE_MAX;
  661. galloc->leaf_allocs[i].leaf.size_max = 0;
  662. } else {
  663. galloc->leaf_allocs[i].leaf.buffer_id = hn->buffer_id;
  664. galloc->leaf_allocs[i].leaf.offset = hn->offset;
  665. galloc->leaf_allocs[i].leaf.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], leaf);
  666. }
  667. }
  668. // reallocate buffers if needed
  669. for (int i = 0; i < galloc->n_buffers; i++) {
  670. // if the buffer type is used multiple times, we reuse the same buffer
  671. for (int j = 0; j < i; j++) {
  672. if (galloc->buf_tallocs[j] == galloc->buf_tallocs[i]) {
  673. galloc->buffers[i] = galloc->buffers[j];
  674. break;
  675. }
  676. }
  677. size_t cur_size = galloc->buffers[i] ? ggml_backend_buffer_get_size(galloc->buffers[i]) : 0;
  678. size_t new_size = ggml_dyn_tallocr_max_size(galloc->buf_tallocs[i]);
  679. // even if there are no tensors allocated in this buffer, we still need to allocate it to initialize views
  680. if (new_size > cur_size || galloc->buffers[i] == NULL) {
  681. #ifndef NDEBUG
  682. fprintf(stderr, "%s: reallocating %s buffer from size %.02f MiB to %.02f MiB\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), cur_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
  683. #endif
  684. ggml_backend_buffer_free(galloc->buffers[i]);
  685. galloc->buffers[i] = ggml_backend_buft_alloc_buffer(galloc->bufts[i], new_size);
  686. if (galloc->buffers[i] == NULL) {
  687. fprintf(stderr, "%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), new_size);
  688. return false;
  689. }
  690. ggml_backend_buffer_set_usage(galloc->buffers[i], GGML_BACKEND_BUFFER_USAGE_COMPUTE);
  691. }
  692. }
  693. return true;
  694. }
  695. bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph *graph) {
  696. return ggml_gallocr_reserve_n(galloc, graph, NULL, NULL);
  697. }
  698. static void ggml_gallocr_init_tensor(ggml_gallocr_t galloc, struct ggml_tensor * tensor, struct tensor_alloc * tensor_alloc) {
  699. int buffer_id = tensor_alloc->buffer_id;
  700. assert(tensor->data || tensor->view_src || ggml_backend_buffer_get_alloc_size(galloc->buffers[buffer_id], tensor) <= tensor_alloc->size_max);
  701. if (tensor->view_src != NULL) {
  702. if (tensor->buffer == NULL) {
  703. assert(tensor_alloc->offset == SIZE_MAX);
  704. if (tensor->view_src->buffer == NULL) {
  705. // this tensor was allocated without ggml-backend
  706. return;
  707. }
  708. ggml_backend_view_init(tensor);
  709. }
  710. } else {
  711. if (tensor->data == NULL) {
  712. assert(tensor_alloc->offset != SIZE_MAX);
  713. assert(ggml_backend_buffer_get_alloc_size(galloc->buffers[buffer_id], tensor) <= tensor_alloc->size_max);
  714. void * base = ggml_backend_buffer_get_base(galloc->buffers[buffer_id]);
  715. void * addr = (char *)base + tensor_alloc->offset;
  716. ggml_backend_tensor_alloc(galloc->buffers[buffer_id], tensor, addr);
  717. } else {
  718. if (tensor->buffer == NULL) {
  719. // this tensor was allocated without ggml-backend
  720. return;
  721. }
  722. }
  723. }
  724. }
  725. static bool ggml_gallocr_node_needs_realloc(ggml_gallocr_t galloc, struct ggml_tensor * node, struct tensor_alloc * talloc) {
  726. size_t node_size = (node->data || node->view_src) ? 0 : ggml_backend_buft_get_alloc_size(galloc->bufts[talloc->buffer_id], node);
  727. return talloc->size_max >= node_size;
  728. }
  729. static bool ggml_gallocr_needs_realloc(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
  730. if (galloc->n_nodes != graph->n_nodes) {
  731. #ifndef NDEBUG
  732. fprintf(stderr, "%s: graph has different number of nodes\n", __func__);
  733. #endif
  734. return true;
  735. }
  736. if (galloc->n_leafs != graph->n_leafs) {
  737. #ifndef NDEBUG
  738. fprintf(stderr, "%s: graph has different number of leafs\n", __func__);
  739. #endif
  740. return true;
  741. }
  742. for (int i = 0; i < graph->n_nodes; i++) {
  743. struct ggml_tensor * node = graph->nodes[i];
  744. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  745. if (!ggml_gallocr_node_needs_realloc(galloc, node, &node_alloc->dst)) {
  746. #ifndef NDEBUG
  747. fprintf(stderr, "%s: node %s is not valid\n", __func__, node->name);
  748. #endif
  749. return true;
  750. }
  751. for (int j = 0; j < GGML_MAX_SRC; j++) {
  752. struct ggml_tensor * src = node->src[j];
  753. if (src == NULL) {
  754. continue;
  755. }
  756. if (!ggml_gallocr_node_needs_realloc(galloc, src, &node_alloc->src[j])) {
  757. #ifndef NDEBUG
  758. fprintf(stderr, "%s: src %d (%s) of node %s is not valid\n", __func__, j, src->name, node->name);
  759. #endif
  760. return true;
  761. }
  762. }
  763. }
  764. return false;
  765. }
  766. bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
  767. if (ggml_gallocr_needs_realloc(galloc, graph)) {
  768. if (galloc->n_buffers == 1) {
  769. #ifndef NDEBUG
  770. fprintf(stderr, "%s: reallocating buffers automatically\n", __func__);
  771. #endif
  772. if (!ggml_gallocr_reserve(galloc, graph)) {
  773. return false;
  774. }
  775. } else {
  776. #ifndef NDEBUG
  777. fprintf(stderr, "%s: cannot reallocate multi buffer graph automatically, call reserve\n", __func__);
  778. #endif
  779. return false;
  780. }
  781. }
  782. // reset buffers
  783. for (int i = 0; i < galloc->n_buffers; i++) {
  784. if (galloc->buffers[i] != NULL) {
  785. ggml_backend_buffer_reset(galloc->buffers[i]);
  786. }
  787. }
  788. // allocate the graph tensors from the previous assignments
  789. // leafs
  790. for (int i = 0; i < graph->n_leafs; i++) {
  791. struct ggml_tensor * leaf = graph->leafs[i];
  792. struct leaf_alloc * leaf_alloc = &galloc->leaf_allocs[i];
  793. ggml_gallocr_init_tensor(galloc, leaf, &leaf_alloc->leaf);
  794. }
  795. // nodes
  796. for (int i = 0; i < graph->n_nodes; i++) {
  797. struct ggml_tensor * node = graph->nodes[i];
  798. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  799. for (int j = 0; j < GGML_MAX_SRC; j++) {
  800. struct ggml_tensor * src = node->src[j];
  801. if (src == NULL) {
  802. continue;
  803. }
  804. ggml_gallocr_init_tensor(galloc, src, &node_alloc->src[j]);
  805. }
  806. ggml_gallocr_init_tensor(galloc, node, &node_alloc->dst);
  807. }
  808. return true;
  809. }
  810. size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id) {
  811. GGML_ASSERT(buffer_id >= 0 && buffer_id < galloc->n_buffers);
  812. if (galloc->buffers[buffer_id] == NULL) {
  813. return 0;
  814. }
  815. for (int i = 0; i < buffer_id; i++) {
  816. if (galloc->buffers[i] == galloc->buffers[buffer_id]) {
  817. // this buffer is the same as a previous one due to the same buffer type being used multiple times
  818. // only return the buffer size the first time it appears to avoid double counting
  819. return 0;
  820. }
  821. }
  822. return ggml_backend_buffer_get_size(galloc->buffers[buffer_id]);
  823. }
  824. // utils
  825. static bool alloc_tensor_range(struct ggml_context * ctx,
  826. struct ggml_tensor * first, struct ggml_tensor * last,
  827. ggml_backend_buffer_type_t buft, size_t size,
  828. ggml_backend_buffer_t ** buffers, size_t * n_buffers) {
  829. ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, size);
  830. if (buffer == NULL) {
  831. #ifndef NDEBUG
  832. fprintf(stderr, "%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), size);
  833. #endif
  834. for (size_t i = 0; i < *n_buffers; i++) {
  835. ggml_backend_buffer_free((*buffers)[i]);
  836. }
  837. free(*buffers);
  838. return false;
  839. }
  840. struct ggml_tallocr tallocr = ggml_tallocr_new(buffer);
  841. for (struct ggml_tensor * t = first; t != last; t = ggml_get_next_tensor(ctx, t)) {
  842. if (t->data == NULL) {
  843. if (t->view_src == NULL) {
  844. ggml_tallocr_alloc(&tallocr, t);
  845. } else if (t->buffer == NULL) {
  846. ggml_backend_view_init(t);
  847. }
  848. } else {
  849. if (t->view_src != NULL && t->buffer == NULL) {
  850. // view of a pre-allocated tensor
  851. ggml_backend_view_init(t);
  852. }
  853. }
  854. }
  855. *buffers = realloc(*buffers, sizeof(ggml_backend_buffer_t) * (*n_buffers + 1));
  856. (*buffers)[(*n_buffers)++] = buffer;
  857. return true;
  858. }
  859. ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft) {
  860. GGML_ASSERT(ggml_get_no_alloc(ctx) == true);
  861. size_t alignment = ggml_backend_buft_get_alignment(buft);
  862. size_t max_size = ggml_backend_buft_get_max_size(buft);
  863. ggml_backend_buffer_t * buffers = NULL;
  864. size_t n_buffers = 0;
  865. size_t cur_buf_size = 0;
  866. struct ggml_tensor * first = ggml_get_first_tensor(ctx);
  867. for (struct ggml_tensor * t = first; t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  868. size_t this_size = 0;
  869. if (t->data == NULL && t->view_src == NULL) {
  870. this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
  871. }
  872. if (this_size > max_size) {
  873. fprintf(stderr, "%s: tensor %s is too large to fit in a %s buffer (tensor size: %zu, max buffer size: %zu)\n",
  874. __func__, t->name,
  875. ggml_backend_buft_name(buft),
  876. this_size, max_size);
  877. for (size_t i = 0; i < n_buffers; i++) {
  878. ggml_backend_buffer_free(buffers[i]);
  879. }
  880. free(buffers);
  881. return NULL;
  882. }
  883. if ((cur_buf_size + this_size) > max_size) {
  884. // allocate tensors in the current buffer
  885. if (!alloc_tensor_range(ctx, first, t, buft, cur_buf_size, &buffers, &n_buffers)) {
  886. return NULL;
  887. }
  888. first = t;
  889. cur_buf_size = this_size;
  890. } else {
  891. cur_buf_size += this_size;
  892. }
  893. }
  894. // allocate remaining tensors
  895. if (cur_buf_size > 0) {
  896. if (!alloc_tensor_range(ctx, first, NULL, buft, cur_buf_size, &buffers, &n_buffers)) {
  897. return NULL;
  898. }
  899. }
  900. if (n_buffers == 0) {
  901. #ifndef NDEBUG
  902. fprintf(stderr, "%s: all tensors in the context are already allocated\n", __func__);
  903. #endif
  904. return NULL;
  905. }
  906. ggml_backend_buffer_t buffer;
  907. if (n_buffers == 1) {
  908. buffer = buffers[0];
  909. } else {
  910. buffer = ggml_backend_multi_buffer_alloc_buffer(buffers, n_buffers);
  911. }
  912. free(buffers);
  913. return buffer;
  914. }
  915. ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend) {
  916. return ggml_backend_alloc_ctx_tensors_from_buft(ctx, ggml_backend_get_default_buffer_type(backend));
  917. }