ggml-alloc.c 36 KB

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