ggml-alloc.c 39 KB

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