ggml-alloc.c 37 KB

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