1
0

ggml-alloc.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #include "ggml-alloc.h"
  2. #include "ggml.h"
  3. #include <assert.h>
  4. #include <stdarg.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #define UNUSED(x) (void)(x)
  9. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  10. //#define GGML_ALLOCATOR_DEBUG
  11. //#define AT_PRINTF printf
  12. #define AT_PRINTF(...) ((void)0)
  13. struct hash_node {
  14. struct ggml_tensor * t;
  15. int n_children;
  16. int n_views;
  17. };
  18. static size_t hash(void * p) {
  19. return (size_t)p % GGML_GRAPH_HASHTABLE_SIZE;
  20. }
  21. static struct hash_node * hash_get(struct hash_node hash_table[], struct ggml_tensor * t) {
  22. size_t h = hash(t);
  23. // linear probing
  24. size_t i = h;
  25. while (hash_table[i].t != NULL) {
  26. if (hash_table[i].t == t) {
  27. return &hash_table[i];
  28. }
  29. i = (i + 1) % GGML_GRAPH_HASHTABLE_SIZE;
  30. if (i == h) {
  31. // hash table is full
  32. GGML_ASSERT(false);
  33. }
  34. }
  35. hash_table[i].t = t;
  36. return &hash_table[i];
  37. }
  38. // TODO: GGML_PAD ?
  39. static size_t aligned_offset(const void * buffer, size_t offset, size_t alignment) {
  40. assert(alignment && !(alignment & (alignment - 1))); // power of 2
  41. size_t align = (alignment - (((uintptr_t)buffer + offset) % alignment)) % alignment;
  42. return offset + align;
  43. }
  44. struct free_block {
  45. void * addr;
  46. size_t size;
  47. };
  48. #define MAX_FREE_BLOCKS 128
  49. struct ggml_allocr {
  50. void * data;
  51. size_t size;
  52. size_t alignment;
  53. int n_free_blocks;
  54. struct free_block free_blocks[MAX_FREE_BLOCKS];
  55. struct hash_node hash_table[GGML_GRAPH_HASHTABLE_SIZE];
  56. size_t max_size;
  57. bool measure;
  58. #ifdef GGML_ALLOCATOR_DEBUG
  59. struct ggml_tensor * allocated_tensors[1024];
  60. #endif
  61. };
  62. #ifdef GGML_ALLOCATOR_DEBUG
  63. static void add_allocated_tensor(struct ggml_allocator * alloc, struct ggml_tensor * tensor) {
  64. for (int i = 0; i < 1024; i++) {
  65. if (alloc->allocated_tensors[i] == NULL) {
  66. alloc->allocated_tensors[i] = tensor;
  67. return;
  68. }
  69. }
  70. GGML_ASSERT(!"out of allocated_tensors");
  71. }
  72. static void remove_allocated_tensor(struct ggml_allocator * alloc, struct ggml_tensor * tensor) {
  73. for (int i = 0; i < 1024; i++) {
  74. if (alloc->allocated_tensors[i] == tensor ||
  75. (alloc->allocated_tensors[i] != NULL && alloc->allocated_tensors[i]->data == tensor->data)) {
  76. alloc->allocated_tensors[i] = NULL;
  77. return;
  78. }
  79. }
  80. printf("tried to free tensor %s not found\n", tensor->name);
  81. GGML_ASSERT(!"tensor not found");
  82. }
  83. #endif
  84. static size_t ggml_allocator_get_alloc_size(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
  85. return ggml_nbytes(tensor);
  86. UNUSED(alloc);
  87. }
  88. void ggml_allocr_alloc(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
  89. size_t size = ggml_allocator_get_alloc_size(alloc, tensor);
  90. size = aligned_offset(NULL, size, alloc->alignment);
  91. AT_PRINTF("%s: allocating %s (%zu bytes) - ", __func__, tensor->name, size);
  92. size_t max_avail = 0;
  93. // find the best fitting free block
  94. int best_fit_block = -1;
  95. size_t best_fit_size = SIZE_MAX;
  96. for (int i = 0; i < alloc->n_free_blocks; i++) {
  97. struct free_block * block = &alloc->free_blocks[i];
  98. max_avail = MAX(max_avail, block->size);
  99. if (block->size >= size && block->size <= best_fit_size) {
  100. best_fit_block = i;
  101. best_fit_size = block->size;
  102. }
  103. }
  104. AT_PRINTF("block %d\n", best_fit_block);
  105. if (best_fit_block == -1) {
  106. fprintf(stderr, "%s: not enough space in the buffer (needed %zu, largest block available %zu)\n",
  107. __func__, size, max_avail);
  108. GGML_ASSERT(!"not enough space in the buffer");
  109. return;
  110. }
  111. struct free_block * block = &alloc->free_blocks[best_fit_block];
  112. void * addr = block->addr;
  113. block->addr = (char*)block->addr + size;
  114. block->size -= size;
  115. if (block->size == 0) {
  116. // remove block if empty
  117. alloc->n_free_blocks--;
  118. for (int j = best_fit_block; j < alloc->n_free_blocks; j++) {
  119. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  120. }
  121. }
  122. tensor->data = addr;
  123. #ifdef GGML_ALLOCATOR_DEBUG
  124. add_allocated_tensor(alloc, tensor);
  125. size_t cur_max = (char*)addr - (char*)alloc->data + size;
  126. if (cur_max > alloc->max_size) {
  127. printf("max_size = %.2f MB: tensors: ", cur_max / 1024.0 / 1024.0);
  128. for (int i = 0; i < 1024; i++) {
  129. if (alloc->allocated_tensors[i]) {
  130. printf("%s (%.2f MB) ", alloc->allocated_tensors[i]->name, ggml_nbytes(alloc->allocated_tensors[i]) / 1024.0 / 1024.0);
  131. }
  132. }
  133. printf("\n");
  134. }
  135. #endif
  136. alloc->max_size = MAX(alloc->max_size, (char*)addr - (char*)alloc->data + size);
  137. }
  138. // this is a very naive implementation, but for our case the number of free blocks should be very small
  139. static void ggml_allocator_free_tensor(struct ggml_allocr * alloc, struct ggml_tensor * tensor) {
  140. void * ptr = tensor->data;
  141. if (ptr < alloc->data || (char*)ptr >= (char*)alloc->data + alloc->max_size) {
  142. // the tensor was not allocated in this buffer
  143. // this can happen because the graph allocator will try to free weights and other tensors from different buffers
  144. // the easiest way to deal with this is just to ignore it
  145. return;
  146. }
  147. size_t size = ggml_allocator_get_alloc_size(alloc, tensor);
  148. size = aligned_offset(NULL, size, alloc->alignment);
  149. AT_PRINTF("%s: freeing %s (%zu bytes) - n_free_blocks = %d\n", __func__, tensor->name, size, alloc->n_free_blocks);
  150. #ifdef GGML_ALLOCATOR_DEBUG
  151. remove_allocated_tensor(alloc, tensor);
  152. #endif
  153. // see if we can merge with an existing block
  154. for (int i = 0; i < alloc->n_free_blocks; i++) {
  155. struct free_block * block = &alloc->free_blocks[i];
  156. // check if ptr is at the end of the block
  157. if ((char*)block->addr + block->size == ptr) {
  158. block->size += size;
  159. // check if we can merge with the next block
  160. if (i < alloc->n_free_blocks - 1 && (char*)block->addr + block->size == alloc->free_blocks[i+1].addr) {
  161. block->size += alloc->free_blocks[i+1].size;
  162. alloc->n_free_blocks--;
  163. for (int j = i+1; j < alloc->n_free_blocks; j++) {
  164. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  165. }
  166. }
  167. return;
  168. }
  169. // check if ptr is at the beginning of the block
  170. if ((char*)ptr + size == block->addr) {
  171. block->addr = ptr;
  172. block->size += size;
  173. // check if we can merge with the previous block
  174. if (i > 0 && (char*)alloc->free_blocks[i-1].addr + alloc->free_blocks[i-1].size == block->addr) {
  175. alloc->free_blocks[i-1].size += block->size;
  176. alloc->n_free_blocks--;
  177. for (int j = i; j < alloc->n_free_blocks; j++) {
  178. alloc->free_blocks[j] = alloc->free_blocks[j+1];
  179. }
  180. }
  181. return;
  182. }
  183. }
  184. // otherwise, add a new block
  185. GGML_ASSERT(alloc->n_free_blocks < MAX_FREE_BLOCKS && "out of free blocks");
  186. // insert the new block in the correct position to keep the array sorted by address (to make merging blocks faster)
  187. int insert_pos = 0;
  188. while (insert_pos < alloc->n_free_blocks && alloc->free_blocks[insert_pos].addr < ptr) {
  189. insert_pos++;
  190. }
  191. // shift all blocks from insert_pos onward to make room for the new block
  192. for (int i = alloc->n_free_blocks; i > insert_pos; i--) {
  193. alloc->free_blocks[i] = alloc->free_blocks[i-1];
  194. }
  195. // insert the new block
  196. alloc->free_blocks[insert_pos].addr = ptr;
  197. alloc->free_blocks[insert_pos].size = size;
  198. alloc->n_free_blocks++;
  199. }
  200. void ggml_allocr_reset(struct ggml_allocr * alloc) {
  201. alloc->n_free_blocks = 1;
  202. size_t align_offset = aligned_offset(alloc->data, 0, alloc->alignment);
  203. alloc->free_blocks[0].addr = (char *)alloc->data + align_offset;
  204. alloc->free_blocks[0].size = alloc->size - align_offset;
  205. }
  206. struct ggml_allocr * ggml_allocr_new(void * data, size_t size, size_t alignment) {
  207. struct ggml_allocr * alloc = (struct ggml_allocr *)malloc(sizeof(struct ggml_allocr) /* + n_free_blocks * sizeof(struct free_block) */);
  208. *alloc = (struct ggml_allocr){
  209. /*.data = */ data,
  210. /*.size = */ size,
  211. /*.alignment = */ alignment,
  212. /*.n_free_blocks = */ 0,
  213. /*.free_blocks = */ {{0}},
  214. /*.hash_table = */ {{0}},
  215. /*.max_size = */ 0,
  216. /*.measure = */ false,
  217. #ifdef GGML_ALLOCATOR_DEBUG
  218. /*.allocated_tensors = */ = {0},
  219. #endif
  220. };
  221. ggml_allocr_reset(alloc);
  222. return alloc;
  223. }
  224. // address and size of the buffer when measuring
  225. // it needs to be large enough to fit all the tensors, but it cannot overlap with other existing buffers
  226. static void * const MEASURE_BASE_ADDR = (void *) 0x1000;
  227. static const size_t MEASURE_MAX_SIZE = 1ULL<<40; // 1 TB
  228. struct ggml_allocr * ggml_allocr_new_measure(size_t alignment) {
  229. struct ggml_allocr * alloc = (struct ggml_allocr *)malloc(sizeof(struct ggml_allocr) /* + n_free_blocks * sizeof(struct free_block) */);
  230. *alloc = (struct ggml_allocr){
  231. /*.data = */ MEASURE_BASE_ADDR,
  232. /*.size = */ MEASURE_MAX_SIZE,
  233. /*.alignment = */ alignment,
  234. /*.n_free_blocks = */ 0,
  235. /*.free_blocks = */ {{0}},
  236. /*.hash_table = */ {{0}},
  237. /*.max_size = */ 0,
  238. /*.measure = */ true,
  239. #ifdef GGML_ALLOCATOR_DEBUG
  240. /*.allocated_tensors = */ = {0},
  241. #endif
  242. };
  243. ggml_allocr_reset(alloc);
  244. return alloc;
  245. }
  246. void ggml_allocr_free(struct ggml_allocr * alloc) {
  247. free(alloc);
  248. }
  249. bool ggml_allocr_is_measure(struct ggml_allocr * alloc) {
  250. return alloc->measure;
  251. }
  252. //////////// compute graph allocator
  253. static bool ggml_is_view(struct ggml_tensor * t) {
  254. return t->op == GGML_OP_RESHAPE || t->op == GGML_OP_VIEW || t->op == GGML_OP_TRANSPOSE ||
  255. t->op == GGML_OP_PERMUTE || t->op == GGML_OP_CPY;
  256. }
  257. static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
  258. if (a->type != b->type) {
  259. return false;
  260. }
  261. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  262. if (a->ne[i] != b->ne[i]) {
  263. return false;
  264. }
  265. if (a->nb[i] != b->nb[i]) {
  266. return false;
  267. }
  268. }
  269. return true;
  270. }
  271. static struct ggml_tensor * get_view_parent(struct ggml_tensor * t) {
  272. switch (t->op) {
  273. case GGML_OP_PERMUTE:
  274. case GGML_OP_RESHAPE:
  275. case GGML_OP_TRANSPOSE:
  276. case GGML_OP_VIEW:
  277. return t->src[0];
  278. case GGML_OP_CPY:
  279. return t->src[1];
  280. default:
  281. return NULL;
  282. }
  283. }
  284. static struct ggml_tensor * get_view_source(struct ggml_tensor * t) {
  285. struct ggml_tensor * parent = t;
  286. do {
  287. parent = get_view_parent(parent);
  288. } while (ggml_is_view(parent));
  289. return parent;
  290. }
  291. static bool ggml_op_can_inplace(enum ggml_op op) {
  292. switch (op) {
  293. case GGML_OP_SCALE:
  294. case GGML_OP_DIAG_MASK_ZERO:
  295. case GGML_OP_DIAG_MASK_INF:
  296. case GGML_OP_ADD:
  297. case GGML_OP_ADD1:
  298. case GGML_OP_ACC:
  299. case GGML_OP_SUB:
  300. case GGML_OP_MUL:
  301. case GGML_OP_DIV:
  302. case GGML_OP_SQR:
  303. case GGML_OP_SQRT:
  304. case GGML_OP_LOG:
  305. case GGML_OP_UNARY:
  306. case GGML_OP_ROPE:
  307. case GGML_OP_RMS_NORM:
  308. case GGML_OP_SET:
  309. case GGML_OP_SOFT_MAX:
  310. case GGML_OP_CONT:
  311. return true;
  312. default:
  313. return false;
  314. }
  315. }
  316. static void allocate_node(struct ggml_allocr * alloc, struct ggml_tensor * node) {
  317. struct hash_node * ht = alloc->hash_table;
  318. if (node->data == NULL) {
  319. if (ggml_is_view(node)) {
  320. size_t offset;
  321. switch(node->op) {
  322. case GGML_OP_VIEW:
  323. memcpy(&offset, node->op_params, sizeof(size_t));
  324. node->data = (char *) node->src[0]->data + offset;
  325. break;
  326. case GGML_OP_PERMUTE:
  327. case GGML_OP_RESHAPE:
  328. case GGML_OP_TRANSPOSE:
  329. node->data = node->src[0]->data;
  330. break;
  331. case GGML_OP_CPY:
  332. node->data = node->src[1]->data;
  333. break;
  334. default:
  335. GGML_ASSERT(!"unknown view op");
  336. break;
  337. }
  338. } else {
  339. // see if we can reuse a parent's buffer (inplace)
  340. if (ggml_op_can_inplace(node->op)) {
  341. for (int i = 0; i < GGML_MAX_SRC; i++) {
  342. struct ggml_tensor * parent = node->src[i];
  343. if (parent == NULL) {
  344. break;
  345. }
  346. // if the node's data is external, then we cannot re-use it
  347. if ((char *) parent->data < (char *) alloc->data ||
  348. (char *) parent->data >= ((char *) alloc->data + alloc->size)) {
  349. AT_PRINTF("not reusing parent %s for %s as %p is external\n", parent->name, node->name, parent->data);
  350. continue;
  351. }
  352. struct hash_node * p_hn = hash_get(ht, parent);
  353. if (parent->data != NULL && p_hn->n_children == 1 && p_hn->n_views == 0 && ggml_are_same_layout(node, parent)) {
  354. if (ggml_is_view(parent)) {
  355. struct ggml_tensor * view_src = get_view_source(parent);
  356. struct hash_node * view_src_hn = hash_get(ht, view_src);
  357. if (view_src_hn->n_views == 1 && view_src_hn->n_children == 0 && view_src->data == parent->data) {
  358. // TODO: the offset of the view parent must be kept to ensure that the op doesn't overwrite
  359. // the parent's data that it will need later (same layout requirement). the problem is that then
  360. // we cannot free the tensor because the original address of the allocation is lost.
  361. // adding a view_src pointer to the tensor would solve this and simplify the code dealing with views
  362. // for now, we only reuse the parent's data if the offset is zero (view_src->data == parent->data)
  363. AT_PRINTF("reusing view parent %s (%s) for %s\n", parent->name, view_src->name, node->name);
  364. node->data = parent->data;
  365. return;
  366. }
  367. }
  368. else {
  369. AT_PRINTF("reusing parent %s for %s\n", parent->name, node->name);
  370. node->data = parent->data;
  371. }
  372. return;
  373. }
  374. }
  375. }
  376. ggml_allocr_alloc(alloc, node);
  377. }
  378. }
  379. }
  380. static size_t ggml_allocator_alloc_graph_tensors_n(
  381. struct ggml_allocr * alloc,
  382. struct ggml_cgraph ** graphs, int n_graphs,
  383. struct ggml_tensor *** inputs, struct ggml_tensor *** outputs) {
  384. // reset hash table
  385. struct hash_node * ht = alloc->hash_table;
  386. memset(ht, 0, sizeof(struct hash_node) * GGML_GRAPH_HASHTABLE_SIZE);
  387. // count number of children and views
  388. for (int g = 0; g < n_graphs; g++) {
  389. struct ggml_cgraph * gf = graphs[g];
  390. for (int i = 0; i < gf->n_nodes; i++) {
  391. struct ggml_tensor * node = gf->nodes[i];
  392. if (ggml_is_view(node)) {
  393. struct ggml_tensor * view_src = get_view_source(node);
  394. hash_get(ht, view_src)->n_views += 1;
  395. }
  396. for (int j = 0; j < GGML_MAX_SRC; j++) {
  397. struct ggml_tensor * parent = node->src[j];
  398. if (parent == NULL) {
  399. break;
  400. }
  401. hash_get(ht, parent)->n_children += 1;
  402. }
  403. }
  404. }
  405. // allocate tensors
  406. for (int g = 0; g < n_graphs; g++) {
  407. struct ggml_cgraph * gf = graphs[g];
  408. AT_PRINTF("####### graph %d/%d\n", g, n_graphs);
  409. // graph inputs are allocated first to ensure that they are not overwritten by each other
  410. if (inputs != NULL && inputs[g] != NULL) {
  411. for (int i = 0; inputs[g][i] != NULL; i++) {
  412. struct ggml_tensor * input = inputs[g][i];
  413. AT_PRINTF("input: %s\n", input->name);
  414. allocate_node(alloc, input);
  415. }
  416. }
  417. for (int i = 0; i < gf->n_nodes; i++) {
  418. struct ggml_tensor * node = gf->nodes[i];
  419. // allocate parents (leafs)
  420. for (int j = 0; j < GGML_MAX_SRC; j++) {
  421. struct ggml_tensor * parent = node->src[j];
  422. if (parent == NULL) {
  423. break;
  424. }
  425. allocate_node(alloc, parent);
  426. }
  427. // allocate node
  428. allocate_node(alloc, node);
  429. AT_PRINTF("exec: %s (%s) <= ", ggml_op_name(node->op), node->name);
  430. for (int j = 0; j < GGML_MAX_SRC; j++) {
  431. struct ggml_tensor * parent = node->src[j];
  432. if (parent == NULL) {
  433. break;
  434. }
  435. AT_PRINTF("%s", parent->name);
  436. if (j < GGML_MAX_SRC - 1 && node->src[j + 1] != NULL) {
  437. AT_PRINTF(", ");
  438. }
  439. }
  440. AT_PRINTF("\n");
  441. // update parents
  442. for (int j = 0; j < GGML_MAX_SRC; j++) {
  443. struct ggml_tensor * parent = node->src[j];
  444. if (parent == NULL) {
  445. break;
  446. }
  447. struct hash_node * p_hn = hash_get(ht, parent);
  448. p_hn->n_children -= 1;
  449. //AT_PRINTF("parent %s: %d children, %d views\n", parent->name, parent->n_children, parent->n_views);
  450. if (p_hn->n_children == 0 && p_hn->n_views == 0) {
  451. if (ggml_is_view(parent)) {
  452. struct ggml_tensor * view_src = get_view_source(parent);
  453. struct hash_node * view_src_hn = hash_get(ht, view_src);
  454. view_src_hn->n_views -= 1;
  455. AT_PRINTF("view_src %s: %d children, %d views\n", view_src->name, view_src->n_children, view_src->n_views);
  456. if (view_src_hn->n_views == 0 && view_src_hn->n_children == 0 && view_src->data != node->data) {
  457. ggml_allocator_free_tensor(alloc, view_src);
  458. }
  459. }
  460. else {
  461. if (parent->data != node->data) {
  462. ggml_allocator_free_tensor(alloc, parent);
  463. }
  464. }
  465. }
  466. }
  467. AT_PRINTF("\n");
  468. }
  469. // free graph outputs here that wouldn't be freed otherwise because they have no children
  470. if (outputs != NULL && outputs[g] != NULL) {
  471. for (int i = 0; outputs[g][i] != NULL; i++) {
  472. struct ggml_tensor * output = outputs[g][i];
  473. AT_PRINTF("output: %s\n", output->name);
  474. ggml_allocator_free_tensor(alloc, output);
  475. }
  476. }
  477. }
  478. return alloc->max_size;
  479. }
  480. size_t ggml_allocr_alloc_graph(struct ggml_allocr * alloc, struct ggml_cgraph * graph) {
  481. return ggml_allocator_alloc_graph_tensors_n(alloc, &graph, 1, NULL, NULL);
  482. }