ggml-alloc.c 38 KB

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