ggml-alloc.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. /**
  2. * llama.cpp - commit ba1cb19cdd0d92e012e0f6e009e0620f854b6afd - 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. return;
  482. }
  483. }
  484. static void ggml_gallocr_free_node(ggml_gallocr_t galloc, struct ggml_tensor * node) {
  485. // graph outputs are never freed
  486. if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
  487. AT_PRINTF("not freeing output %s\n", node->name);
  488. return;
  489. }
  490. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  491. size_t offset = hn->offset;
  492. int buffer_id = hn->buffer_id;
  493. struct ggml_dyn_tallocr * alloc = galloc->buf_tallocs[buffer_id];
  494. ggml_backend_buffer_type_t buft = galloc->bufts[buffer_id];
  495. size_t size = ggml_backend_buft_get_alloc_size(buft, node);
  496. ggml_dyn_tallocr_free_tensor(alloc, offset, size, node);
  497. hn->allocated = false;
  498. }
  499. static int get_node_buffer_id(const int * node_buffer_ids, int i) {
  500. return node_buffer_ids ? node_buffer_ids[i] : 0;
  501. }
  502. 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) {
  503. // clear hash tables
  504. ggml_hash_set_reset(&galloc->hash_set);
  505. memset(galloc->hash_values, 0, sizeof(struct hash_node) * galloc->hash_set.size);
  506. // allocate leafs
  507. // these may be tensors that the application is not using in the graph, but may still want to allocate for other purposes
  508. for (int i = 0; i < graph->n_leafs; i++) {
  509. struct ggml_tensor * leaf = graph->leafs[i];
  510. ggml_gallocr_allocate_node(galloc, leaf, get_node_buffer_id(leaf_buffer_ids, i));
  511. }
  512. // count number of children and views
  513. // allocate other graph inputs and leafs first to avoid overwriting them
  514. for (int i = 0; i < graph->n_nodes; i++) {
  515. struct ggml_tensor * node = graph->nodes[i];
  516. // TODO: better way to add external dependencies
  517. // GGML_OP_NONE does not appear normally in the graph nodes, but is used by ggml-backend to add dependencies to
  518. // control when some tensors are allocated and freed. in this case, the dependencies are in `src`, but the node
  519. // itself is never used and should not be considered a dependency
  520. if (ggml_is_view(node) && node->op != GGML_OP_NONE) {
  521. struct ggml_tensor * view_src = node->view_src;
  522. ggml_gallocr_hash_get(galloc, view_src)->n_views += 1;
  523. }
  524. if (node->flags & GGML_TENSOR_FLAG_INPUT) {
  525. ggml_gallocr_allocate_node(galloc, graph->nodes[i], get_node_buffer_id(node_buffer_ids, i));
  526. }
  527. for (int j = 0; j < GGML_MAX_SRC; j++) {
  528. struct ggml_tensor * src = node->src[j];
  529. if (src == NULL) {
  530. continue;
  531. }
  532. ggml_gallocr_hash_get(galloc, src)->n_children += 1;
  533. // allocate explicit inputs
  534. if (src->flags & GGML_TENSOR_FLAG_INPUT) {
  535. ggml_gallocr_allocate_node(galloc, src, get_node_buffer_id(node_buffer_ids, i));
  536. }
  537. }
  538. }
  539. // allocate tensors
  540. for (int i = 0; i < graph->n_nodes; i++) {
  541. struct ggml_tensor * node = graph->nodes[i];
  542. int buffer_id = get_node_buffer_id(node_buffer_ids, i);
  543. // allocate parents (only leafs need to be allocated at this point)
  544. for (int j = 0; j < GGML_MAX_SRC; j++) {
  545. struct ggml_tensor * parent = node->src[j];
  546. if (parent == NULL) {
  547. continue;
  548. }
  549. ggml_gallocr_allocate_node(galloc, parent, buffer_id);
  550. }
  551. // allocate node
  552. ggml_gallocr_allocate_node(galloc, node, buffer_id);
  553. AT_PRINTF("exec: %s (%s) <= ", ggml_op_desc(node), node->name);
  554. for (int j = 0; j < GGML_MAX_SRC; j++) {
  555. struct ggml_tensor * parent = node->src[j];
  556. if (parent == NULL) {
  557. continue;
  558. }
  559. AT_PRINTF("%s", parent->name);
  560. if (j < GGML_MAX_SRC - 1 && node->src[j + 1] != NULL) {
  561. AT_PRINTF(", ");
  562. }
  563. }
  564. AT_PRINTF("\n");
  565. // update parents
  566. for (int j = 0; j < GGML_MAX_SRC; j++) {
  567. struct ggml_tensor * parent = node->src[j];
  568. if (parent == NULL) {
  569. continue;
  570. }
  571. struct hash_node * p_hn = ggml_gallocr_hash_get(galloc, parent);
  572. p_hn->n_children -= 1;
  573. AT_PRINTF("parent %s: %d children, %d views, allocated: %d\n",
  574. parent->name, p_hn->n_children, p_hn->n_views, p_hn->allocated);
  575. if (p_hn->n_children == 0 && p_hn->n_views == 0) {
  576. if (ggml_is_view(parent)) {
  577. struct ggml_tensor * view_src = parent->view_src;
  578. struct hash_node * view_src_hn = ggml_gallocr_hash_get(galloc, view_src);
  579. view_src_hn->n_views -= 1;
  580. AT_PRINTF("view_src %s: %d children, %d views\n",
  581. view_src->name, view_src_hn->n_children, view_src_hn->n_views);
  582. if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src_hn->allocated) {
  583. ggml_gallocr_free_node(galloc, view_src);
  584. }
  585. }
  586. else if (p_hn->allocated) {
  587. ggml_gallocr_free_node(galloc, parent);
  588. }
  589. }
  590. AT_PRINTF("\n");
  591. }
  592. }
  593. }
  594. bool ggml_gallocr_reserve_n(ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids) {
  595. size_t min_hash_size = graph->n_nodes + graph->n_leafs;
  596. // add 25% margin to avoid hash collisions
  597. min_hash_size += min_hash_size / 4;
  598. // initialize hash table
  599. if (galloc->hash_set.size < min_hash_size) {
  600. ggml_hash_set_free(&galloc->hash_set);
  601. galloc->hash_set = ggml_hash_set_new(min_hash_size);
  602. GGML_ASSERT(galloc->hash_set.keys != NULL);
  603. free(galloc->hash_values);
  604. galloc->hash_values = malloc(sizeof(struct hash_node) * galloc->hash_set.size);
  605. GGML_ASSERT(galloc->hash_values != NULL);
  606. }
  607. // reset allocators
  608. for (int i = 0; i < galloc->n_buffers; i++) {
  609. ggml_dyn_tallocr_reset(galloc->buf_tallocs[i]);
  610. }
  611. // allocate in hash table
  612. ggml_gallocr_alloc_graph_impl(galloc, graph, node_buffer_ids, leaf_buffer_ids);
  613. // set the node_allocs from the hash table
  614. if (galloc->n_nodes < graph->n_nodes) {
  615. free(galloc->node_allocs);
  616. galloc->node_allocs = calloc(graph->n_nodes, sizeof(struct node_alloc));
  617. GGML_ASSERT(galloc->node_allocs != NULL);
  618. }
  619. galloc->n_nodes = graph->n_nodes;
  620. for (int i = 0; i < graph->n_nodes; i++) {
  621. struct ggml_tensor * node = graph->nodes[i];
  622. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  623. if (node->view_src || node->data) {
  624. node_alloc->dst.buffer_id = -1;
  625. node_alloc->dst.offset = SIZE_MAX;
  626. node_alloc->dst.size_max = 0;
  627. } else {
  628. struct hash_node * hn = ggml_gallocr_hash_get(galloc, node);
  629. node_alloc->dst.buffer_id = hn->buffer_id;
  630. node_alloc->dst.offset = hn->offset;
  631. node_alloc->dst.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], node);
  632. }
  633. for (int j = 0; j < GGML_MAX_SRC; j++) {
  634. struct ggml_tensor * src = node->src[j];
  635. if (!src || src->view_src || src->data) {
  636. node_alloc->src[j].buffer_id = -1;
  637. node_alloc->src[j].offset = SIZE_MAX;
  638. node_alloc->src[j].size_max = 0;
  639. } else {
  640. struct hash_node * hn = ggml_gallocr_hash_get(galloc, src);
  641. node_alloc->src[j].buffer_id = hn->buffer_id;
  642. node_alloc->src[j].offset = hn->offset;
  643. node_alloc->src[j].size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], src);
  644. }
  645. }
  646. }
  647. if (galloc->n_leafs < graph->n_leafs) {
  648. free(galloc->leaf_allocs);
  649. galloc->leaf_allocs = calloc(graph->n_leafs, sizeof(galloc->leaf_allocs[0]));
  650. GGML_ASSERT(galloc->leaf_allocs != NULL);
  651. }
  652. galloc->n_leafs = graph->n_leafs;
  653. for (int i = 0; i < graph->n_leafs; i++) {
  654. struct ggml_tensor * leaf = graph->leafs[i];
  655. struct hash_node * hn = ggml_gallocr_hash_get(galloc, leaf);
  656. if (leaf->view_src || leaf->data) {
  657. galloc->leaf_allocs[i].leaf.buffer_id = -1;
  658. galloc->leaf_allocs[i].leaf.offset = SIZE_MAX;
  659. galloc->leaf_allocs[i].leaf.size_max = 0;
  660. } else {
  661. galloc->leaf_allocs[i].leaf.buffer_id = hn->buffer_id;
  662. galloc->leaf_allocs[i].leaf.offset = hn->offset;
  663. galloc->leaf_allocs[i].leaf.size_max = ggml_backend_buft_get_alloc_size(galloc->bufts[hn->buffer_id], leaf);
  664. }
  665. }
  666. // reallocate buffers if needed
  667. for (int i = 0; i < galloc->n_buffers; i++) {
  668. // if the buffer type is used multiple times, we reuse the same buffer
  669. for (int j = 0; j < i; j++) {
  670. if (galloc->buf_tallocs[j] == galloc->buf_tallocs[i]) {
  671. galloc->buffers[i] = galloc->buffers[j];
  672. break;
  673. }
  674. }
  675. size_t cur_size = galloc->buffers[i] ? ggml_backend_buffer_get_size(galloc->buffers[i]) : 0;
  676. size_t new_size = ggml_dyn_tallocr_max_size(galloc->buf_tallocs[i]);
  677. // even if there are no tensors allocated in this buffer, we still need to allocate it to initialize views
  678. if (new_size > cur_size || galloc->buffers[i] == NULL) {
  679. #ifndef NDEBUG
  680. 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);
  681. #endif
  682. ggml_backend_buffer_free(galloc->buffers[i]);
  683. galloc->buffers[i] = ggml_backend_buft_alloc_buffer(galloc->bufts[i], new_size);
  684. if (galloc->buffers[i] == NULL) {
  685. GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(galloc->bufts[i]), new_size);
  686. return false;
  687. }
  688. ggml_backend_buffer_set_usage(galloc->buffers[i], GGML_BACKEND_BUFFER_USAGE_COMPUTE);
  689. }
  690. }
  691. return true;
  692. }
  693. bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph *graph) {
  694. return ggml_gallocr_reserve_n(galloc, graph, NULL, NULL);
  695. }
  696. static void ggml_gallocr_init_tensor(ggml_gallocr_t galloc, struct ggml_tensor * tensor, struct tensor_alloc * tensor_alloc) {
  697. int buffer_id = tensor_alloc->buffer_id;
  698. assert(tensor->data || tensor->view_src || ggml_backend_buffer_get_alloc_size(galloc->buffers[buffer_id], tensor) <= tensor_alloc->size_max);
  699. if (tensor->view_src != NULL) {
  700. if (tensor->buffer == NULL) {
  701. assert(tensor_alloc->offset == SIZE_MAX);
  702. if (tensor->view_src->buffer == NULL) {
  703. // this tensor was allocated without ggml-backend
  704. return;
  705. }
  706. ggml_backend_view_init(tensor);
  707. }
  708. } else {
  709. if (tensor->data == NULL) {
  710. assert(tensor_alloc->offset != SIZE_MAX);
  711. assert(ggml_backend_buffer_get_alloc_size(galloc->buffers[buffer_id], tensor) <= tensor_alloc->size_max);
  712. void * base = ggml_backend_buffer_get_base(galloc->buffers[buffer_id]);
  713. void * addr = (char *)base + tensor_alloc->offset;
  714. ggml_backend_tensor_alloc(galloc->buffers[buffer_id], tensor, addr);
  715. } else {
  716. if (tensor->buffer == NULL) {
  717. // this tensor was allocated without ggml-backend
  718. return;
  719. }
  720. }
  721. }
  722. }
  723. static bool ggml_gallocr_node_needs_realloc(ggml_gallocr_t galloc, struct ggml_tensor * node, struct tensor_alloc * talloc) {
  724. size_t node_size = 0;
  725. if (!node->data && !node->view_src) {
  726. GGML_ASSERT(talloc->buffer_id >= 0); // prevent segfault when misusing the API
  727. node_size = ggml_backend_buft_get_alloc_size(galloc->bufts[talloc->buffer_id], node);
  728. }
  729. return talloc->size_max >= node_size;
  730. }
  731. static bool ggml_gallocr_needs_realloc(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
  732. if (galloc->n_nodes != graph->n_nodes) {
  733. #ifndef NDEBUG
  734. GGML_LOG_DEBUG("%s: graph has different number of nodes\n", __func__);
  735. #endif
  736. return true;
  737. }
  738. if (galloc->n_leafs != graph->n_leafs) {
  739. #ifndef NDEBUG
  740. GGML_LOG_DEBUG("%s: graph has different number of leafs\n", __func__);
  741. #endif
  742. return true;
  743. }
  744. for (int i = 0; i < graph->n_nodes; i++) {
  745. struct ggml_tensor * node = graph->nodes[i];
  746. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  747. if (!ggml_gallocr_node_needs_realloc(galloc, node, &node_alloc->dst)) {
  748. #ifndef NDEBUG
  749. GGML_LOG_DEBUG("%s: node %s is not valid\n", __func__, node->name);
  750. #endif
  751. return true;
  752. }
  753. for (int j = 0; j < GGML_MAX_SRC; j++) {
  754. struct ggml_tensor * src = node->src[j];
  755. if (src == NULL) {
  756. continue;
  757. }
  758. if (!ggml_gallocr_node_needs_realloc(galloc, src, &node_alloc->src[j])) {
  759. #ifndef NDEBUG
  760. GGML_LOG_DEBUG("%s: src %d (%s) of node %s is not valid\n", __func__, j, src->name, node->name);
  761. #endif
  762. return true;
  763. }
  764. }
  765. }
  766. return false;
  767. }
  768. bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph) {
  769. if (ggml_gallocr_needs_realloc(galloc, graph)) {
  770. if (galloc->n_buffers == 1) {
  771. #ifndef NDEBUG
  772. GGML_LOG_DEBUG("%s: reallocating buffers automatically\n", __func__);
  773. #endif
  774. if (!ggml_gallocr_reserve(galloc, graph)) {
  775. return false;
  776. }
  777. } else {
  778. #ifndef NDEBUG
  779. GGML_LOG_DEBUG("%s: cannot reallocate multi buffer graph automatically, call reserve\n", __func__);
  780. #endif
  781. return false;
  782. }
  783. }
  784. // reset buffers
  785. for (int i = 0; i < galloc->n_buffers; i++) {
  786. if (galloc->buffers[i] != NULL) {
  787. ggml_backend_buffer_reset(galloc->buffers[i]);
  788. }
  789. }
  790. // allocate the graph tensors from the previous assignments
  791. // leafs
  792. for (int i = 0; i < graph->n_leafs; i++) {
  793. struct ggml_tensor * leaf = graph->leafs[i];
  794. struct leaf_alloc * leaf_alloc = &galloc->leaf_allocs[i];
  795. ggml_gallocr_init_tensor(galloc, leaf, &leaf_alloc->leaf);
  796. }
  797. // nodes
  798. for (int i = 0; i < graph->n_nodes; i++) {
  799. struct ggml_tensor * node = graph->nodes[i];
  800. struct node_alloc * node_alloc = &galloc->node_allocs[i];
  801. for (int j = 0; j < GGML_MAX_SRC; j++) {
  802. struct ggml_tensor * src = node->src[j];
  803. if (src == NULL) {
  804. continue;
  805. }
  806. ggml_gallocr_init_tensor(galloc, src, &node_alloc->src[j]);
  807. }
  808. ggml_gallocr_init_tensor(galloc, node, &node_alloc->dst);
  809. }
  810. return true;
  811. }
  812. size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id) {
  813. GGML_ASSERT(buffer_id >= 0 && buffer_id < galloc->n_buffers);
  814. if (galloc->buffers[buffer_id] == NULL) {
  815. return 0;
  816. }
  817. for (int i = 0; i < buffer_id; i++) {
  818. if (galloc->buffers[i] == galloc->buffers[buffer_id]) {
  819. // this buffer is the same as a previous one due to the same buffer type being used multiple times
  820. // only return the buffer size the first time it appears to avoid double counting
  821. return 0;
  822. }
  823. }
  824. return ggml_backend_buffer_get_size(galloc->buffers[buffer_id]);
  825. }
  826. // utils
  827. static bool alloc_tensor_range(struct ggml_context * ctx,
  828. struct ggml_tensor * first, struct ggml_tensor * last,
  829. ggml_backend_buffer_type_t buft, size_t size,
  830. ggml_backend_buffer_t ** buffers, size_t * n_buffers) {
  831. ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, size);
  832. if (buffer == NULL) {
  833. #ifndef NDEBUG
  834. GGML_LOG_DEBUG("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), size);
  835. #endif
  836. for (size_t i = 0; i < *n_buffers; i++) {
  837. ggml_backend_buffer_free((*buffers)[i]);
  838. }
  839. free(*buffers);
  840. return false;
  841. }
  842. struct ggml_tallocr tallocr = ggml_tallocr_new(buffer);
  843. for (struct ggml_tensor * t = first; t != last; t = ggml_get_next_tensor(ctx, t)) {
  844. if (t->data == NULL) {
  845. if (t->view_src == NULL) {
  846. ggml_tallocr_alloc(&tallocr, t);
  847. } else if (t->buffer == NULL) {
  848. ggml_backend_view_init(t);
  849. }
  850. } else {
  851. if (t->view_src != NULL && t->buffer == NULL) {
  852. // view of a pre-allocated tensor
  853. ggml_backend_view_init(t);
  854. }
  855. }
  856. }
  857. *buffers = realloc(*buffers, sizeof(ggml_backend_buffer_t) * (*n_buffers + 1));
  858. (*buffers)[(*n_buffers)++] = buffer;
  859. return true;
  860. }
  861. ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft) {
  862. GGML_ASSERT(ggml_get_no_alloc(ctx) == true);
  863. size_t alignment = ggml_backend_buft_get_alignment(buft);
  864. size_t max_size = ggml_backend_buft_get_max_size(buft);
  865. ggml_backend_buffer_t * buffers = NULL;
  866. size_t n_buffers = 0;
  867. size_t cur_buf_size = 0;
  868. struct ggml_tensor * first = ggml_get_first_tensor(ctx);
  869. for (struct ggml_tensor * t = first; t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  870. size_t this_size = 0;
  871. if (t->data == NULL && t->view_src == NULL) {
  872. this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
  873. }
  874. if (this_size > max_size) {
  875. GGML_LOG_ERROR("%s: tensor %s is too large to fit in a %s buffer (tensor size: %zu, max buffer size: %zu)\n",
  876. __func__, t->name,
  877. ggml_backend_buft_name(buft),
  878. this_size, max_size);
  879. for (size_t i = 0; i < n_buffers; i++) {
  880. ggml_backend_buffer_free(buffers[i]);
  881. }
  882. free(buffers);
  883. return NULL;
  884. }
  885. if ((cur_buf_size + this_size) > max_size) {
  886. // allocate tensors in the current buffer
  887. if (!alloc_tensor_range(ctx, first, t, buft, cur_buf_size, &buffers, &n_buffers)) {
  888. return NULL;
  889. }
  890. first = t;
  891. cur_buf_size = this_size;
  892. } else {
  893. cur_buf_size += this_size;
  894. }
  895. }
  896. // allocate remaining tensors
  897. if (cur_buf_size > 0) {
  898. if (!alloc_tensor_range(ctx, first, NULL, buft, cur_buf_size, &buffers, &n_buffers)) {
  899. return NULL;
  900. }
  901. }
  902. if (n_buffers == 0) {
  903. #ifndef NDEBUG
  904. GGML_LOG_DEBUG("%s: all tensors in the context are already allocated\n", __func__);
  905. #endif
  906. return NULL;
  907. }
  908. ggml_backend_buffer_t buffer;
  909. if (n_buffers == 1) {
  910. buffer = buffers[0];
  911. } else {
  912. buffer = ggml_backend_multi_buffer_alloc_buffer(buffers, n_buffers);
  913. }
  914. free(buffers);
  915. return buffer;
  916. }
  917. ggml_backend_buffer_t ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend) {
  918. return ggml_backend_alloc_ctx_tensors_from_buft(ctx, ggml_backend_get_default_buffer_type(backend));
  919. }