1
0

ggml-alloc.c 35 KB

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