ggml-alloc.c 37 KB

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