ggml-backend.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  1. #include "ggml-backend-impl.h"
  2. #include "ggml-alloc.h"
  3. #include "ggml-impl.h"
  4. #include <assert.h>
  5. #include <limits.h>
  6. #include <stdarg.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  11. // backend buffer type
  12. const char * ggml_backend_buft_name(ggml_backend_buffer_type_t buft) {
  13. return buft->iface.get_name(buft);
  14. }
  15. GGML_CALL ggml_backend_buffer_t ggml_backend_buft_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  16. return buft->iface.alloc_buffer(buft, size);
  17. }
  18. size_t ggml_backend_buft_get_alignment(ggml_backend_buffer_type_t buft) {
  19. return buft->iface.get_alignment(buft);
  20. }
  21. GGML_CALL size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, struct ggml_tensor * tensor) {
  22. // get_alloc_size is optional, defaults to ggml_nbytes
  23. if (buft->iface.get_alloc_size) {
  24. return buft->iface.get_alloc_size(buft, tensor);
  25. }
  26. return ggml_nbytes(tensor);
  27. }
  28. bool ggml_backend_buft_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  29. return buft->iface.supports_backend(buft, backend);
  30. }
  31. bool ggml_backend_buft_is_host(ggml_backend_buffer_type_t buft) {
  32. if (buft->iface.is_host) {
  33. return buft->iface.is_host(buft);
  34. }
  35. return false;
  36. }
  37. // backend buffer
  38. GGML_CALL ggml_backend_buffer_t ggml_backend_buffer_init(
  39. ggml_backend_buffer_type_t buft,
  40. struct ggml_backend_buffer_i iface,
  41. ggml_backend_buffer_context_t context,
  42. size_t size) {
  43. ggml_backend_buffer_t buffer = malloc(sizeof(struct ggml_backend_buffer));
  44. GGML_ASSERT(iface.get_base != NULL);
  45. (*buffer) = (struct ggml_backend_buffer) {
  46. /* .interface = */ iface,
  47. /* .buft = */ buft,
  48. /* .context = */ context,
  49. /* .size = */ size,
  50. /* .usage = */ GGML_BACKEND_BUFFER_USAGE_ANY
  51. };
  52. return buffer;
  53. }
  54. const char * ggml_backend_buffer_name(ggml_backend_buffer_t buffer) {
  55. return buffer->iface.get_name(buffer);
  56. }
  57. void ggml_backend_buffer_free(ggml_backend_buffer_t buffer) {
  58. if (buffer == NULL) {
  59. return;
  60. }
  61. if (buffer->iface.free_buffer != NULL) {
  62. buffer->iface.free_buffer(buffer);
  63. }
  64. free(buffer);
  65. }
  66. size_t ggml_backend_buffer_get_size(ggml_backend_buffer_t buffer) {
  67. return buffer->size;
  68. }
  69. void * ggml_backend_buffer_get_base(ggml_backend_buffer_t buffer) {
  70. void * base = buffer->iface.get_base(buffer);
  71. GGML_ASSERT(base != NULL && "backend buffer base cannot be NULL");
  72. return base;
  73. }
  74. GGML_CALL void ggml_backend_buffer_init_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
  75. // init_tensor is optional
  76. if (buffer->iface.init_tensor) {
  77. buffer->iface.init_tensor(buffer, tensor);
  78. }
  79. }
  80. size_t ggml_backend_buffer_get_alignment (ggml_backend_buffer_t buffer) {
  81. return ggml_backend_buft_get_alignment(ggml_backend_buffer_get_type(buffer));
  82. }
  83. size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
  84. return ggml_backend_buft_get_alloc_size(ggml_backend_buffer_get_type(buffer), tensor);
  85. }
  86. void ggml_backend_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  87. buffer->iface.clear(buffer, value);
  88. }
  89. bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) {
  90. return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer));
  91. }
  92. void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) {
  93. buffer->usage = usage;
  94. }
  95. ggml_backend_buffer_type_t ggml_backend_buffer_get_type(ggml_backend_buffer_t buffer) {
  96. return buffer->buft;
  97. }
  98. void ggml_backend_buffer_reset(ggml_backend_buffer_t buffer) {
  99. if (buffer->iface.reset) {
  100. buffer->iface.reset(buffer);
  101. }
  102. }
  103. bool ggml_backend_buffer_copy_tensor(const struct ggml_tensor * src, struct ggml_tensor * dst) {
  104. ggml_backend_buffer_t dst_buf = dst->view_src ? dst->view_src->buffer : dst->buffer;
  105. if (dst_buf->iface.cpy_tensor) {
  106. return src->buffer->iface.cpy_tensor(dst_buf, src, dst);
  107. }
  108. return false;
  109. }
  110. // backend
  111. const char * ggml_backend_name(ggml_backend_t backend) {
  112. if (backend == NULL) {
  113. return "NULL";
  114. }
  115. return backend->iface.get_name(backend);
  116. }
  117. void ggml_backend_free(ggml_backend_t backend) {
  118. if (backend == NULL) {
  119. return;
  120. }
  121. backend->iface.free(backend);
  122. }
  123. ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend) {
  124. return backend->iface.get_default_buffer_type(backend);
  125. }
  126. ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size) {
  127. return ggml_backend_buft_alloc_buffer(ggml_backend_get_default_buffer_type(backend), size);
  128. }
  129. size_t ggml_backend_get_alignment(ggml_backend_t backend) {
  130. return ggml_backend_buft_get_alignment(ggml_backend_get_default_buffer_type(backend));
  131. }
  132. void ggml_backend_tensor_set_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  133. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  134. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  135. if (backend->iface.set_tensor_async == NULL) {
  136. ggml_backend_tensor_set(tensor, data, offset, size);
  137. } else {
  138. backend->iface.set_tensor_async(backend, tensor, data, offset, size);
  139. }
  140. }
  141. void ggml_backend_tensor_get_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  142. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  143. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  144. if (backend->iface.get_tensor_async == NULL) {
  145. ggml_backend_tensor_get(tensor, data, offset, size);
  146. } else {
  147. backend->iface.get_tensor_async(backend, tensor, data, offset, size);
  148. }
  149. }
  150. GGML_CALL void ggml_backend_tensor_set(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  151. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  152. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  153. GGML_ASSERT(buf != NULL && "tensor buffer not set");
  154. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  155. tensor->buffer->iface.set_tensor(buf, tensor, data, offset, size);
  156. }
  157. GGML_CALL void ggml_backend_tensor_get(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  158. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  159. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  160. GGML_ASSERT(tensor->buffer != NULL && "tensor buffer not set");
  161. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  162. tensor->buffer->iface.get_tensor(buf, tensor, data, offset, size);
  163. }
  164. void ggml_backend_synchronize(ggml_backend_t backend) {
  165. if (backend->iface.synchronize == NULL) {
  166. return;
  167. }
  168. backend->iface.synchronize(backend);
  169. }
  170. ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  171. return backend->iface.graph_plan_create(backend, cgraph);
  172. }
  173. void ggml_backend_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  174. backend->iface.graph_plan_free(backend, plan);
  175. }
  176. void ggml_backend_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  177. backend->iface.graph_plan_compute(backend, plan);
  178. }
  179. bool ggml_backend_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  180. return backend->iface.graph_compute(backend, cgraph);
  181. }
  182. bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  183. return backend->iface.supports_op(backend, op);
  184. }
  185. // backend copy
  186. static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
  187. if (a->type != b->type) {
  188. return false;
  189. }
  190. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  191. if (a->ne[i] != b->ne[i]) {
  192. return false;
  193. }
  194. if (a->nb[i] != b->nb[i]) {
  195. return false;
  196. }
  197. }
  198. return true;
  199. }
  200. void ggml_backend_tensor_copy(struct ggml_tensor * src, struct ggml_tensor * dst) {
  201. GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
  202. if (src == dst) {
  203. return;
  204. }
  205. if (ggml_backend_buffer_is_host(src->buffer)) {
  206. ggml_backend_tensor_set(dst, src->data, 0, ggml_nbytes(src));
  207. } else if (ggml_backend_buffer_is_host(dst->buffer)) {
  208. ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
  209. } else if (!ggml_backend_buffer_copy_tensor(src, dst)) {
  210. #ifndef NDEBUG
  211. fprintf(stderr, "%s: warning: slow copy from %s to %s\n", __func__, ggml_backend_buffer_name(src->buffer), ggml_backend_buffer_name(dst->buffer));
  212. #endif
  213. size_t nbytes = ggml_nbytes(src);
  214. void * data = malloc(nbytes);
  215. ggml_backend_tensor_get(src, data, 0, nbytes);
  216. ggml_backend_tensor_set(dst, data, 0, nbytes);
  217. free(data);
  218. }
  219. }
  220. void ggml_backend_tensor_copy_async(ggml_backend_t backend, struct ggml_tensor * src, struct ggml_tensor * dst) {
  221. GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
  222. if (src == dst) {
  223. return;
  224. }
  225. if (ggml_backend_buft_supports_backend(src->buffer->buft, backend) && ggml_backend_buft_supports_backend(dst->buffer->buft, backend)) {
  226. if (backend->iface.cpy_tensor_async != NULL) {
  227. if (backend->iface.cpy_tensor_async(backend, src, dst)) {
  228. return;
  229. }
  230. }
  231. }
  232. size_t nbytes = ggml_nbytes(src);
  233. if (ggml_backend_buffer_is_host(src->buffer)) {
  234. ggml_backend_tensor_set_async(backend, dst, src->data, 0, nbytes);
  235. }
  236. else {
  237. ggml_backend_tensor_copy(src, dst);
  238. }
  239. }
  240. // backend registry
  241. #define GGML_MAX_BACKENDS_REG 16
  242. struct ggml_backend_reg {
  243. char name[128];
  244. ggml_backend_init_fn init_fn;
  245. ggml_backend_buffer_type_t default_buffer_type;
  246. void * user_data;
  247. };
  248. static struct ggml_backend_reg ggml_backend_registry[GGML_MAX_BACKENDS_REG];
  249. static size_t ggml_backend_registry_count = 0;
  250. GGML_CALL static ggml_backend_t ggml_backend_reg_cpu_init(const char * params, void * user_data);
  251. GGML_CALL static void ggml_backend_registry_init(void) {
  252. static bool initialized = false;
  253. if (initialized) {
  254. return;
  255. }
  256. initialized = true;
  257. ggml_backend_register("CPU", ggml_backend_reg_cpu_init, ggml_backend_cpu_buffer_type(), NULL);
  258. // add forward decls here to avoid including the backend headers
  259. #ifdef GGML_USE_CUBLAS
  260. extern GGML_CALL void ggml_backend_cuda_reg_devices(void);
  261. ggml_backend_cuda_reg_devices();
  262. #endif
  263. #ifdef GGML_USE_METAL
  264. extern GGML_CALL ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data);
  265. extern GGML_CALL ggml_backend_buffer_type_t ggml_backend_metal_buffer_type(void);
  266. ggml_backend_register("Metal", ggml_backend_reg_metal_init, ggml_backend_metal_buffer_type(), NULL);
  267. #endif
  268. }
  269. GGML_CALL void ggml_backend_register(const char * name, ggml_backend_init_fn init_fn, ggml_backend_buffer_type_t default_buffer_type, void * user_data) {
  270. GGML_ASSERT(ggml_backend_registry_count < GGML_MAX_BACKENDS_REG);
  271. size_t id = ggml_backend_registry_count;
  272. ggml_backend_registry[id] = (struct ggml_backend_reg) {
  273. /* .name = */ {0},
  274. /* .fn = */ init_fn,
  275. /* .default_buffer_type = */ default_buffer_type,
  276. /* .user_data = */ user_data,
  277. };
  278. snprintf(ggml_backend_registry[id].name, sizeof(ggml_backend_registry[id].name), "%s", name);
  279. #ifndef NDEBUG
  280. fprintf(stderr, "%s: registered backend %s\n", __func__, name);
  281. #endif
  282. ggml_backend_registry_count++;
  283. }
  284. size_t ggml_backend_reg_get_count(void) {
  285. ggml_backend_registry_init();
  286. return ggml_backend_registry_count;
  287. }
  288. size_t ggml_backend_reg_find_by_name(const char * name) {
  289. ggml_backend_registry_init();
  290. for (size_t i = 0; i < ggml_backend_registry_count; i++) {
  291. // TODO: case insensitive in a portable way
  292. if (strcmp(ggml_backend_registry[i].name, name) == 0) {
  293. return i;
  294. }
  295. }
  296. // not found
  297. return SIZE_MAX;
  298. }
  299. // init from backend:params string
  300. ggml_backend_t ggml_backend_reg_init_backend_from_str(const char * backend_str) {
  301. ggml_backend_registry_init();
  302. const char * params = strchr(backend_str, ':');
  303. char backend_name[128];
  304. if (params == NULL) {
  305. snprintf(backend_name, sizeof(backend_name), "%s", backend_str);
  306. params = "";
  307. } else {
  308. snprintf(backend_name, sizeof(backend_name), "%.*s", (int)(params - backend_str), backend_str);
  309. params++;
  310. }
  311. size_t backend_i = ggml_backend_reg_find_by_name(backend_name);
  312. if (backend_i == SIZE_MAX) {
  313. fprintf(stderr, "%s: backend %s not found\n", __func__, backend_name);
  314. return NULL;
  315. }
  316. return ggml_backend_reg_init_backend(backend_i, params);
  317. }
  318. const char * ggml_backend_reg_get_name(size_t i) {
  319. ggml_backend_registry_init();
  320. GGML_ASSERT(i < ggml_backend_registry_count);
  321. return ggml_backend_registry[i].name;
  322. }
  323. ggml_backend_t ggml_backend_reg_init_backend(size_t i, const char * params) {
  324. ggml_backend_registry_init();
  325. GGML_ASSERT(i < ggml_backend_registry_count);
  326. return ggml_backend_registry[i].init_fn(params, ggml_backend_registry[i].user_data);
  327. }
  328. ggml_backend_buffer_type_t ggml_backend_reg_get_default_buffer_type(size_t i) {
  329. ggml_backend_registry_init();
  330. GGML_ASSERT(i < ggml_backend_registry_count);
  331. return ggml_backend_registry[i].default_buffer_type;
  332. }
  333. ggml_backend_buffer_t ggml_backend_reg_alloc_buffer(size_t i, size_t size) {
  334. ggml_backend_registry_init();
  335. GGML_ASSERT(i < ggml_backend_registry_count);
  336. return ggml_backend_buft_alloc_buffer(ggml_backend_registry[i].default_buffer_type, size);
  337. }
  338. // backend CPU
  339. GGML_CALL static const char * ggml_backend_cpu_buffer_name(ggml_backend_buffer_t buffer) {
  340. return "CPU";
  341. GGML_UNUSED(buffer);
  342. }
  343. GGML_CALL static void * ggml_backend_cpu_buffer_get_base(ggml_backend_buffer_t buffer) {
  344. return (void *)buffer->context;
  345. }
  346. GGML_CALL static void ggml_backend_cpu_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  347. free(buffer->context);
  348. }
  349. GGML_CALL static void ggml_backend_cpu_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  350. memcpy((char *)tensor->data + offset, data, size);
  351. GGML_UNUSED(buffer);
  352. }
  353. GGML_CALL static void ggml_backend_cpu_buffer_get_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  354. memcpy(data, (const char *)tensor->data + offset, size);
  355. GGML_UNUSED(buffer);
  356. }
  357. GGML_CALL static bool ggml_backend_cpu_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * src, struct ggml_tensor * dst) {
  358. if (ggml_backend_buffer_is_host(src->buffer)) {
  359. memcpy(dst->data, src->data, ggml_nbytes(src));
  360. return true;
  361. }
  362. return false;
  363. GGML_UNUSED(buffer);
  364. }
  365. GGML_CALL static void ggml_backend_cpu_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  366. memset(buffer->context, value, buffer->size);
  367. }
  368. static struct ggml_backend_buffer_i cpu_backend_buffer_i = {
  369. /* .get_name = */ ggml_backend_cpu_buffer_name,
  370. /* .free_buffer = */ ggml_backend_cpu_buffer_free_buffer,
  371. /* .get_base = */ ggml_backend_cpu_buffer_get_base,
  372. /* .init_tensor = */ NULL, // no initialization required
  373. /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
  374. /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
  375. /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
  376. /* .clear = */ ggml_backend_cpu_buffer_clear,
  377. /* .reset = */ NULL,
  378. };
  379. // for buffers from ptr, free is not called
  380. static struct ggml_backend_buffer_i cpu_backend_buffer_i_from_ptr = {
  381. /* .get_name = */ ggml_backend_cpu_buffer_name,
  382. /* .free_buffer = */ NULL, // ptr is not owned by the buffer, so it does not need to be freed
  383. /* .get_base = */ ggml_backend_cpu_buffer_get_base,
  384. /* .init_tensor = */ NULL, // no initialization required
  385. /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
  386. /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
  387. /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
  388. /* .clear = */ ggml_backend_cpu_buffer_clear,
  389. /* .reset = */ NULL,
  390. };
  391. static const size_t TENSOR_ALIGNMENT = 64; // should be enough for AVX 512
  392. GGML_CALL static const char * ggml_backend_cpu_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  393. return "CPU";
  394. GGML_UNUSED(buft);
  395. }
  396. GGML_CALL static ggml_backend_buffer_t ggml_backend_cpu_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  397. size += TENSOR_ALIGNMENT; // malloc may return an address that is not aligned
  398. void * data = malloc(size); // TODO: maybe use GGML_ALIGNED_MALLOC?
  399. GGML_ASSERT(data != NULL && "failed to allocate buffer");
  400. return ggml_backend_buffer_init(buft, cpu_backend_buffer_i, data, size);
  401. }
  402. GGML_CALL static size_t ggml_backend_cpu_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  403. return TENSOR_ALIGNMENT;
  404. GGML_UNUSED(buft);
  405. }
  406. GGML_CALL static bool ggml_backend_cpu_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  407. return ggml_backend_is_cpu(backend);
  408. GGML_UNUSED(buft);
  409. }
  410. GGML_CALL static bool ggml_backend_cpu_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  411. return true;
  412. GGML_UNUSED(buft);
  413. }
  414. GGML_CALL ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void) {
  415. static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = {
  416. /* .iface = */ {
  417. /* .get_name = */ ggml_backend_cpu_buffer_type_get_name,
  418. /* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer,
  419. /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
  420. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  421. /* .supports_backend = */ ggml_backend_cpu_buffer_type_supports_backend,
  422. /* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
  423. },
  424. /* .context = */ NULL,
  425. };
  426. return &ggml_backend_cpu_buffer_type;
  427. }
  428. #ifdef GGML_USE_CPU_HBM
  429. // buffer type HBM
  430. #include <hbwmalloc.h>
  431. GGML_CALL static const char * ggml_backend_cpu_hbm_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  432. return "CPU_HBM";
  433. GGML_UNUSED(buft);
  434. }
  435. GGML_CALL static const char * ggml_backend_cpu_hbm_buffer_get_name(ggml_backend_buffer_t buf) {
  436. return "CPU_HBM";
  437. GGML_UNUSED(buf);
  438. }
  439. GGML_CALL static void ggml_backend_cpu_hbm_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  440. hbw_free(buffer->context);
  441. }
  442. GGML_CALL static ggml_backend_buffer_t ggml_backend_cpu_hbm_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  443. //void * ptr = hbw_malloc(size);
  444. void * ptr;
  445. int result = hbw_posix_memalign(&ptr, ggml_backend_cpu_buffer_type_get_alignment(buft), size);
  446. if (result != 0) {
  447. fprintf(stderr, "failed to allocate HBM buffer of size %zu\n", size);
  448. return NULL;
  449. }
  450. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  451. buffer->buft = buft;
  452. buffer->iface.get_name = ggml_backend_cpu_hbm_buffer_get_name;
  453. buffer->iface.free_buffer = ggml_backend_cpu_hbm_buffer_free_buffer;
  454. return buffer;
  455. }
  456. ggml_backend_buffer_type_t ggml_backend_cpu_hbm_buffer_type(void) {
  457. static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type_hbm = {
  458. /* .iface = */ {
  459. /* .get_name = */ ggml_backend_cpu_hbm_buffer_type_get_name,
  460. /* .alloc_buffer = */ ggml_backend_cpu_hbm_buffer_type_alloc_buffer,
  461. /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
  462. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  463. /* .supports_backend = */ ggml_backend_cpu_buffer_type_supports_backend,
  464. /* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
  465. },
  466. /* .context = */ NULL,
  467. };
  468. return &ggml_backend_cpu_buffer_type_hbm;
  469. }
  470. #endif
  471. struct ggml_backend_cpu_context {
  472. int n_threads;
  473. void * work_data;
  474. size_t work_size;
  475. };
  476. GGML_CALL static const char * ggml_backend_cpu_name(ggml_backend_t backend) {
  477. return "CPU";
  478. GGML_UNUSED(backend);
  479. }
  480. GGML_CALL static void ggml_backend_cpu_free(ggml_backend_t backend) {
  481. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  482. free(cpu_ctx->work_data);
  483. free(cpu_ctx);
  484. free(backend);
  485. }
  486. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_cpu_get_default_buffer_type(ggml_backend_t backend) {
  487. return ggml_backend_cpu_buffer_type();
  488. GGML_UNUSED(backend);
  489. }
  490. struct ggml_backend_plan_cpu {
  491. struct ggml_cplan cplan;
  492. struct ggml_cgraph cgraph;
  493. };
  494. GGML_CALL static ggml_backend_graph_plan_t ggml_backend_cpu_graph_plan_create(ggml_backend_t backend, const struct ggml_cgraph * cgraph) {
  495. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  496. struct ggml_backend_plan_cpu * cpu_plan = malloc(sizeof(struct ggml_backend_plan_cpu));
  497. cpu_plan->cplan = ggml_graph_plan(cgraph, cpu_ctx->n_threads);
  498. cpu_plan->cgraph = *cgraph; // FIXME: deep copy
  499. if (cpu_plan->cplan.work_size > 0) {
  500. cpu_plan->cplan.work_data = malloc(cpu_plan->cplan.work_size);
  501. }
  502. return cpu_plan;
  503. }
  504. GGML_CALL static void ggml_backend_cpu_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  505. struct ggml_backend_plan_cpu * cpu_plan = (struct ggml_backend_plan_cpu *)plan;
  506. free(cpu_plan->cplan.work_data);
  507. free(cpu_plan);
  508. GGML_UNUSED(backend);
  509. }
  510. GGML_CALL static void ggml_backend_cpu_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  511. struct ggml_backend_plan_cpu * cpu_plan = (struct ggml_backend_plan_cpu *)plan;
  512. ggml_graph_compute(&cpu_plan->cgraph, &cpu_plan->cplan);
  513. GGML_UNUSED(backend);
  514. }
  515. GGML_CALL static bool ggml_backend_cpu_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  516. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  517. struct ggml_cplan cplan = ggml_graph_plan(cgraph, cpu_ctx->n_threads);
  518. if (cpu_ctx->work_size < cplan.work_size) {
  519. // TODO: may be faster to free and use malloc to avoid the copy
  520. cpu_ctx->work_data = realloc(cpu_ctx->work_data, cplan.work_size);
  521. cpu_ctx->work_size = cplan.work_size;
  522. }
  523. cplan.work_data = cpu_ctx->work_data;
  524. ggml_graph_compute(cgraph, &cplan);
  525. return true;
  526. }
  527. GGML_CALL static bool ggml_backend_cpu_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  528. switch (op->op) {
  529. case GGML_OP_MUL_MAT:
  530. return op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == ggml_internal_get_type_traits(op->src[0]->type).vec_dot_type;
  531. default:
  532. return true;
  533. }
  534. GGML_UNUSED(backend);
  535. }
  536. static struct ggml_backend_i cpu_backend_i = {
  537. /* .get_name = */ ggml_backend_cpu_name,
  538. /* .free = */ ggml_backend_cpu_free,
  539. /* .get_default_buffer_type = */ ggml_backend_cpu_get_default_buffer_type,
  540. /* .set_tensor_async = */ NULL,
  541. /* .get_tensor_async = */ NULL,
  542. /* .cpy_tensor_async = */ NULL,
  543. /* .synchronize = */ NULL,
  544. /* .graph_plan_create = */ ggml_backend_cpu_graph_plan_create,
  545. /* .graph_plan_free = */ ggml_backend_cpu_graph_plan_free,
  546. /* .graph_plan_compute = */ ggml_backend_cpu_graph_plan_compute,
  547. /* .graph_compute = */ ggml_backend_cpu_graph_compute,
  548. /* .supports_op = */ ggml_backend_cpu_supports_op,
  549. };
  550. ggml_backend_t ggml_backend_cpu_init(void) {
  551. struct ggml_backend_cpu_context * ctx = malloc(sizeof(struct ggml_backend_cpu_context));
  552. ctx->n_threads = GGML_DEFAULT_N_THREADS;
  553. ctx->work_data = NULL;
  554. ctx->work_size = 0;
  555. ggml_backend_t cpu_backend = malloc(sizeof(struct ggml_backend));
  556. *cpu_backend = (struct ggml_backend) {
  557. /* .interface = */ cpu_backend_i,
  558. /* .context = */ ctx
  559. };
  560. return cpu_backend;
  561. }
  562. GGML_CALL bool ggml_backend_is_cpu(ggml_backend_t backend) {
  563. return backend && backend->iface.get_name == ggml_backend_cpu_name;
  564. }
  565. void ggml_backend_cpu_set_n_threads(ggml_backend_t backend_cpu, int n_threads) {
  566. GGML_ASSERT(ggml_backend_is_cpu(backend_cpu));
  567. struct ggml_backend_cpu_context * ctx = (struct ggml_backend_cpu_context *)backend_cpu->context;
  568. ctx->n_threads = n_threads;
  569. }
  570. GGML_CALL ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size) {
  571. return ggml_backend_buffer_init(ggml_backend_cpu_buffer_type(), cpu_backend_buffer_i_from_ptr, ptr, size);
  572. }
  573. GGML_CALL static ggml_backend_t ggml_backend_reg_cpu_init(const char * params, void * user_data) {
  574. return ggml_backend_cpu_init();
  575. GGML_UNUSED(params);
  576. GGML_UNUSED(user_data);
  577. }
  578. // scheduler
  579. #define GGML_MAX_BACKENDS 16
  580. #define GGML_MAX_SPLITS 256
  581. #define GGML_MAX_SPLIT_INPUTS 16
  582. struct ggml_backend_sched_split {
  583. ggml_tallocr_t tallocr;
  584. int i_start;
  585. int i_end;
  586. struct ggml_tensor * inputs[GGML_MAX_SPLIT_INPUTS];
  587. int n_inputs;
  588. // graph view of this split
  589. struct ggml_cgraph graph;
  590. };
  591. struct ggml_backend_sched {
  592. bool is_reset; // true if the scheduler has been reset since the last graph split
  593. int n_backends;
  594. ggml_backend_t backends[GGML_MAX_BACKENDS];
  595. ggml_backend_buffer_type_t bufts[GGML_MAX_BACKENDS];
  596. ggml_tallocr_t tallocs[GGML_MAX_BACKENDS];
  597. ggml_gallocr_t galloc;
  598. // hash keys of the nodes in the graph
  599. struct ggml_hash_set hash_set;
  600. // hash values (arrays of [hash_set.size])
  601. ggml_tallocr_t * node_talloc; // tallocr assigned to each node (indirectly this is the backend)
  602. struct ggml_tensor * (* node_copies)[GGML_MAX_BACKENDS]; // copies of each node for each destination backend
  603. // copy of the graph with modified inputs
  604. struct ggml_cgraph * graph;
  605. struct ggml_backend_sched_split splits[GGML_MAX_SPLITS];
  606. int n_splits;
  607. struct ggml_context * ctx;
  608. // align context_buffer to GGML_MEM_ALIGN
  609. #ifdef _MSC_VER
  610. __declspec(align(GGML_MEM_ALIGN))
  611. #else
  612. __attribute__((aligned(GGML_MEM_ALIGN)))
  613. #endif
  614. char context_buffer[GGML_MAX_SPLITS*GGML_MAX_SPLIT_INPUTS*sizeof(struct ggml_tensor) + sizeof(struct ggml_cgraph)];
  615. ggml_backend_sched_eval_callback callback_eval;
  616. void * callback_eval_user_data;
  617. };
  618. #define hash_id(node) ggml_hash_find_or_insert(sched->hash_set, node)
  619. #define node_allocr(node) sched->node_talloc[hash_id(node)]
  620. static bool ggml_is_view_op(enum ggml_op op) {
  621. return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE;
  622. }
  623. // returns the priority of the backend, lower is better
  624. static int sched_backend_prio(ggml_backend_sched_t sched, ggml_backend_t backend) {
  625. for (int i = 0; i < sched->n_backends; i++) {
  626. if (sched->backends[i] == backend) {
  627. return i;
  628. }
  629. }
  630. return INT_MAX;
  631. }
  632. static int sched_allocr_prio(ggml_backend_sched_t sched, ggml_tallocr_t allocr) {
  633. for (int i = 0; i < sched->n_backends; i++) {
  634. if (sched->tallocs[i] == allocr) {
  635. return i;
  636. }
  637. }
  638. return INT_MAX;
  639. }
  640. static ggml_tallocr_t sched_allocr_from_buffer(ggml_backend_sched_t sched, ggml_backend_buffer_t buffer) {
  641. if (buffer == NULL) {
  642. return NULL;
  643. }
  644. // check if this is already allocate in a allocr buffer (from user manual allocations)
  645. for (int i = 0; i < sched->n_backends; i++) {
  646. if (ggml_tallocr_get_buffer(sched->tallocs[i]) == buffer) {
  647. return sched->tallocs[i];
  648. }
  649. }
  650. // find highest prio backend that supports the buffer type
  651. for (int i = 0; i < sched->n_backends; i++) {
  652. if (ggml_backend_buft_supports_backend(buffer->buft, sched->backends[i])) {
  653. return sched->tallocs[i];
  654. }
  655. }
  656. GGML_ASSERT(false && "tensor buffer type not supported by any backend");
  657. }
  658. static ggml_backend_t get_allocr_backend(ggml_backend_sched_t sched, ggml_tallocr_t allocr) {
  659. if (allocr == NULL) {
  660. return NULL;
  661. }
  662. for (int i = 0; i < sched->n_backends; i++) {
  663. if (sched->tallocs[i] == allocr) {
  664. return sched->backends[i];
  665. }
  666. }
  667. GGML_UNREACHABLE();
  668. }
  669. #if 0
  670. static char causes[GGML_DEFAULT_GRAPH_SIZE*16 + GGML_MAX_SPLITS*GGML_MAX_SPLIT_INPUTS][128]; // debug only
  671. #define SET_CAUSE(node, ...) sprintf(causes[hash_id(node)], __VA_ARGS__)
  672. #define GET_CAUSE(node) causes[hash_id(node)]
  673. #else
  674. #define SET_CAUSE(node, ...)
  675. #define GET_CAUSE(node) ""
  676. #endif
  677. // returns the backend that should be used for the node based on the current locations
  678. static ggml_tallocr_t sched_allocr_from_cur(ggml_backend_sched_t sched, struct ggml_tensor * node) {
  679. // assign pre-allocated nodes to their backend
  680. // dst
  681. ggml_tallocr_t cur_allocr = sched_allocr_from_buffer(sched, node->buffer);
  682. if (cur_allocr != NULL) {
  683. SET_CAUSE(node, "1.dst");
  684. return cur_allocr;
  685. }
  686. // view_src
  687. if (node->view_src != NULL) {
  688. cur_allocr = sched_allocr_from_buffer(sched, node->view_src->buffer);
  689. if (cur_allocr != NULL) {
  690. SET_CAUSE(node, "1.vsrc");
  691. return cur_allocr;
  692. }
  693. }
  694. // assign nodes that use weights to the backend of the weights
  695. for (int i = 0; i < GGML_MAX_SRC; i++) {
  696. const struct ggml_tensor * src = node->src[i];
  697. if (src == NULL) {
  698. break;
  699. }
  700. if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
  701. ggml_tallocr_t src_allocr = sched_allocr_from_buffer(sched, src->buffer);
  702. // operations with weights are always run on the same backend as the weights
  703. SET_CAUSE(node, "1.wgt%d", i);
  704. return src_allocr;
  705. }
  706. }
  707. return NULL;
  708. }
  709. static char * fmt_size(size_t size) {
  710. static char buffer[128];
  711. if (size >= 1024*1024) {
  712. sprintf(buffer, "%zuM", size/1024/1024);
  713. } else {
  714. sprintf(buffer, "%zuK", size/1024);
  715. }
  716. return buffer;
  717. }
  718. static void sched_print_assignments(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  719. int cur_split = 0;
  720. for (int i = 0; i < graph->n_nodes; i++) {
  721. if (cur_split < sched->n_splits && i == sched->splits[cur_split].i_start) {
  722. ggml_backend_t split_backend = get_allocr_backend(sched, sched->splits[cur_split].tallocr);
  723. fprintf(stderr, "\n## SPLIT #%d: %s # %d inputs: ", cur_split, ggml_backend_name(split_backend),
  724. sched->splits[cur_split].n_inputs);
  725. for (int j = 0; j < sched->splits[cur_split].n_inputs; j++) {
  726. fprintf(stderr, "[%s (%5.5s)] ", sched->splits[cur_split].inputs[j]->name,
  727. fmt_size(ggml_nbytes(sched->splits[cur_split].inputs[j])));
  728. }
  729. fprintf(stderr, "\n");
  730. cur_split++;
  731. }
  732. struct ggml_tensor * node = graph->nodes[i];
  733. if (ggml_is_view_op(node->op)) {
  734. continue;
  735. }
  736. ggml_tallocr_t node_allocr = node_allocr(node);
  737. ggml_backend_t node_backend = node_allocr ? get_allocr_backend(sched, node_allocr) : NULL; // FIXME:
  738. fprintf(stderr, "node #%3d (%10.10s): %20.20s (%5.5s) [%5.5s %8.8s]:", i, ggml_op_name(node->op), node->name,
  739. fmt_size(ggml_nbytes(node)), node_allocr ? ggml_backend_name(node_backend) : "NULL", GET_CAUSE(node));
  740. for (int j = 0; j < GGML_MAX_SRC; j++) {
  741. struct ggml_tensor * src = node->src[j];
  742. if (src == NULL) {
  743. break;
  744. }
  745. ggml_tallocr_t src_allocr = node_allocr(src);
  746. ggml_backend_t src_backend = src_allocr ? get_allocr_backend(sched, src_allocr) : NULL;
  747. fprintf(stderr, " %20.20s (%5.5s) [%5.5s %8.8s]", src->name,
  748. fmt_size(ggml_nbytes(src)), src_backend ? ggml_backend_name(src_backend) : "NULL", GET_CAUSE(src));
  749. }
  750. fprintf(stderr, "\n");
  751. }
  752. }
  753. // creates a copy of the tensor with the same memory layout
  754. static struct ggml_tensor * ggml_dup_tensor_layout(struct ggml_context * ctx, const struct ggml_tensor * tensor) {
  755. struct ggml_tensor * dup = ggml_dup_tensor(ctx, tensor);
  756. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  757. dup->nb[i] = tensor->nb[i];
  758. }
  759. return dup;
  760. }
  761. //#define DEBUG_PASS1
  762. //#define DEBUG_PASS2
  763. //#define DEBUG_PASS3
  764. //#define DEBUG_PASS4
  765. // assigns backends to ops and splits the graph into subgraphs that can be computed on the same backend
  766. static void sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  767. // reset splits
  768. sched->n_splits = 0;
  769. sched->is_reset = false;
  770. struct ggml_init_params params = {
  771. /* .mem_size = */ sizeof(sched->context_buffer),
  772. /* .mem_buffer = */ sched->context_buffer,
  773. /* .no_alloc = */ true
  774. };
  775. ggml_free(sched->ctx);
  776. sched->ctx = ggml_init(params);
  777. if (sched->ctx == NULL) {
  778. fprintf(stderr, "%s: failed to initialize context\n", __func__);
  779. GGML_ASSERT(false);
  780. }
  781. // pass 1: assign backends to ops with pre-allocated inputs
  782. for (int i = 0; i < graph->n_leafs; i++) {
  783. struct ggml_tensor * leaf = graph->leafs[i];
  784. if (node_allocr(leaf) != NULL) {
  785. // do not overwrite user assignments
  786. continue;
  787. }
  788. node_allocr(leaf) = sched_allocr_from_cur(sched, leaf);
  789. }
  790. for (int i = 0; i < graph->n_nodes; i++) {
  791. struct ggml_tensor * node = graph->nodes[i];
  792. if (node_allocr(node) != NULL) {
  793. // do not overwrite user assignments
  794. continue;
  795. }
  796. node_allocr(node) = sched_allocr_from_cur(sched, node);
  797. // src
  798. for (int j = 0; j < GGML_MAX_SRC; j++) {
  799. struct ggml_tensor * src = node->src[j];
  800. if (src == NULL) {
  801. break;
  802. }
  803. if (node_allocr(src) == NULL) {
  804. node_allocr(src) = sched_allocr_from_cur(sched, src);
  805. }
  806. }
  807. }
  808. #ifdef DEBUG_PASS1
  809. fprintf(stderr, "PASS 1 ASSIGNMENTS\n"); sched_print_assignments(sched, graph);
  810. #endif
  811. // pass 2: expand current backend assignments
  812. // assign the same backend to adjacent nodes
  813. // expand gpu backends (i.e. non last prio) up and down, ignoring cpu (the lowest priority backend)
  814. // thus, cpu will never be used unless weights are on cpu, or there are no gpu ops between cpu ops
  815. // pass 2.1 expand gpu up
  816. {
  817. ggml_tallocr_t cur_allocr = NULL;
  818. for (int i = graph->n_nodes - 1; i >= 0; i--) {
  819. struct ggml_tensor * node = graph->nodes[i];
  820. if (ggml_is_view_op(node->op)) {
  821. continue;
  822. }
  823. ggml_tallocr_t node_allocr = node_allocr(node);
  824. if (node_allocr != NULL) {
  825. if (sched_allocr_prio(sched, node_allocr) == sched->n_backends - 1) {
  826. // skip cpu (lowest prio backend)
  827. cur_allocr = NULL;
  828. } else {
  829. cur_allocr = node_allocr;
  830. }
  831. } else {
  832. node_allocr(node) = cur_allocr;
  833. SET_CAUSE(node, "2.1");
  834. }
  835. }
  836. }
  837. // pass 2.2 expand gpu down
  838. {
  839. ggml_tallocr_t cur_allocr = NULL;
  840. for (int i = 0; i < graph->n_nodes; i++) {
  841. struct ggml_tensor * node = graph->nodes[i];
  842. if (ggml_is_view_op(node->op)) {
  843. continue;
  844. }
  845. ggml_tallocr_t node_allocr = node_allocr(node);
  846. if (node_allocr != NULL) {
  847. if (sched_allocr_prio(sched, node_allocr) == sched->n_backends - 1) {
  848. // skip cpu (lowest prio backend)
  849. cur_allocr = NULL;
  850. } else {
  851. cur_allocr = node_allocr;
  852. }
  853. } else {
  854. node_allocr(node) = cur_allocr;
  855. SET_CAUSE(node, "2.2");
  856. }
  857. }
  858. }
  859. // pass 2.3 expand rest up
  860. {
  861. ggml_tallocr_t cur_allocr = NULL;
  862. for (int i = graph->n_nodes - 1; i >= 0; i--) {
  863. struct ggml_tensor * node = graph->nodes[i];
  864. if (ggml_is_view_op(node->op)) {
  865. continue;
  866. }
  867. ggml_tallocr_t node_allocr = node_allocr(node);
  868. if (node_allocr != NULL) {
  869. cur_allocr = node_allocr;
  870. } else {
  871. node_allocr(node) = cur_allocr;
  872. SET_CAUSE(node, "2.3");
  873. }
  874. }
  875. }
  876. // pass 2.4 expand rest down
  877. {
  878. ggml_tallocr_t cur_allocr = NULL;
  879. for (int i = 0; i < graph->n_nodes; i++) {
  880. struct ggml_tensor * node = graph->nodes[i];
  881. if (ggml_is_view_op(node->op)) {
  882. continue;
  883. }
  884. ggml_tallocr_t node_allocr = node_allocr(node);
  885. if (node_allocr != NULL) {
  886. cur_allocr = node_allocr;
  887. } else {
  888. node_allocr(node) = cur_allocr;
  889. SET_CAUSE(node, "2.4");
  890. }
  891. }
  892. }
  893. #ifdef DEBUG_PASS2
  894. fprintf(stderr, "PASS 2 ASSIGNMENTS\n"); sched_print_assignments(sched, graph);
  895. #endif
  896. // pass 3: assign backends to remaining src from dst and view_src
  897. for (int i = 0; i < graph->n_nodes; i++) {
  898. struct ggml_tensor * node = graph->nodes[i];
  899. ggml_tallocr_t cur_allocr = node_allocr(node);
  900. if (node->view_src != NULL && cur_allocr == NULL) {
  901. cur_allocr = node_allocr(node) = node_allocr(node->view_src);
  902. SET_CAUSE(node, "3.vsrc");
  903. }
  904. for (int j = 0; j < GGML_MAX_SRC; j++) {
  905. struct ggml_tensor * src = node->src[j];
  906. if (src == NULL) {
  907. break;
  908. }
  909. ggml_tallocr_t src_allocr = node_allocr(src);
  910. if (src_allocr == NULL) {
  911. if (src->view_src != NULL) {
  912. // views are always on the same backend as the source
  913. node_allocr(src) = node_allocr(src->view_src);
  914. SET_CAUSE(src, "3.vsrc");
  915. } else {
  916. node_allocr(src) = cur_allocr;
  917. SET_CAUSE(src, "3.cur");
  918. }
  919. }
  920. }
  921. }
  922. #ifdef DEBUG_PASS3
  923. fprintf(stderr, "PASS 3 ASSIGNMENTS\n"); sched_print_assignments(sched, graph);
  924. #endif
  925. // pass 4: split graph, find tensors that need to be copied
  926. {
  927. int cur_split = 0;
  928. // find the backend of the first split, skipping view ops
  929. for (int i = 0; i < graph->n_nodes; i++) {
  930. struct ggml_tensor * node = graph->nodes[i];
  931. if (!ggml_is_view_op(node->op)) {
  932. sched->splits[0].tallocr = node_allocr(node);
  933. break;
  934. }
  935. }
  936. sched->splits[0].i_start = 0;
  937. sched->splits[0].n_inputs = 0;
  938. memset(sched->splits[0].inputs, 0, sizeof(sched->splits[0].inputs)); //HACK
  939. ggml_tallocr_t cur_allocr = sched->splits[0].tallocr;
  940. size_t cur_backend_id = sched_allocr_prio(sched, cur_allocr);
  941. for (int i = 0; i < graph->n_nodes; i++) {
  942. struct ggml_tensor * node = graph->nodes[i];
  943. if (ggml_is_view_op(node->op)) {
  944. continue;
  945. }
  946. ggml_tallocr_t node_allocr = node_allocr(node);
  947. GGML_ASSERT(node_allocr != NULL); // all nodes should be assigned by now
  948. if (node_allocr != cur_allocr) {
  949. sched->splits[cur_split].i_end = i;
  950. cur_split++;
  951. GGML_ASSERT(cur_split < GGML_MAX_SPLITS);
  952. sched->splits[cur_split].tallocr = node_allocr;
  953. sched->splits[cur_split].i_start = i;
  954. sched->splits[cur_split].n_inputs = 0;
  955. cur_allocr = node_allocr;
  956. cur_backend_id = sched_allocr_prio(sched, cur_allocr);
  957. }
  958. // find inputs that are not on the same backend
  959. for (int j = 0; j < GGML_MAX_SRC; j++) {
  960. struct ggml_tensor * src = node->src[j];
  961. if (src == NULL) {
  962. break;
  963. }
  964. ggml_tallocr_t src_allocr = node_allocr(src);
  965. GGML_ASSERT(src_allocr != NULL); // all inputs should be assigned by now
  966. if (src_allocr != node_allocr) {
  967. // check if the input is already in the split
  968. bool found = false;
  969. for (int k = 0; k < sched->splits[cur_split].n_inputs; k++) {
  970. if (sched->splits[cur_split].inputs[k] == src) {
  971. found = true;
  972. break;
  973. }
  974. }
  975. if (!found) {
  976. int n_inputs = sched->splits[cur_split].n_inputs++;
  977. //printf("split %d input %d: %s (%s)\n", cur_split, n_inputs, src->name, ggml_backend_name(get_allocr_backend(sched, src_allocr)));
  978. GGML_ASSERT(n_inputs < GGML_MAX_SPLIT_INPUTS);
  979. sched->splits[cur_split].inputs[n_inputs] = src;
  980. }
  981. // create a copy of the input in the split's backend
  982. size_t id = hash_id(src);
  983. if (sched->node_copies[id][cur_backend_id] == NULL) {
  984. ggml_backend_t backend = get_allocr_backend(sched, cur_allocr);
  985. struct ggml_tensor * tensor_copy = ggml_dup_tensor_layout(sched->ctx, src);
  986. ggml_format_name(tensor_copy, "%s#%s", ggml_backend_name(backend), src->name);
  987. sched->node_copies[id][cur_backend_id] = tensor_copy;
  988. node_allocr(tensor_copy) = cur_allocr;
  989. SET_CAUSE(tensor_copy, "4.cpy");
  990. }
  991. node->src[j] = sched->node_copies[id][cur_backend_id];
  992. }
  993. }
  994. }
  995. sched->splits[cur_split].i_end = graph->n_nodes;
  996. sched->n_splits = cur_split + 1;
  997. }
  998. #ifdef DEBUG_PASS4
  999. fprintf(stderr, "PASS 4 ASSIGNMENTS\n"); sched_print_assignments(sched, graph);
  1000. #endif
  1001. #ifndef NDEBUG
  1002. // sanity check: all sources should have the same backend as the node
  1003. for (int i = 0; i < graph->n_nodes; i++) {
  1004. struct ggml_tensor * node = graph->nodes[i];
  1005. ggml_tallocr_t node_allocr = node_allocr(node);
  1006. if (node_allocr == NULL) {
  1007. fprintf(stderr, "!!!!!!! %s has no backend\n", node->name);
  1008. }
  1009. if (node->view_src != NULL && node_allocr != node_allocr(node->view_src)) {
  1010. fprintf(stderr, "!!!!!!! %s has backend %s, view_src %s has backend %s\n",
  1011. node->name, node_allocr ? ggml_backend_name(get_allocr_backend(sched, node_allocr)) : "NULL",
  1012. node->view_src->name, node_allocr(node->view_src) ? ggml_backend_name(get_allocr_backend(sched, node_allocr(node->view_src))) : "NULL");
  1013. }
  1014. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1015. struct ggml_tensor * src = node->src[j];
  1016. if (src == NULL) {
  1017. break;
  1018. }
  1019. ggml_tallocr_t src_allocr = node_allocr(src);
  1020. if (src_allocr != node_allocr /* && src_backend != NULL */) { // ignore nulls for now
  1021. fprintf(stderr, "!!!! %s has backend %s, src %d (%s) has backend %s\n",
  1022. node->name, node_allocr ? ggml_backend_name(get_allocr_backend(sched, node_allocr)) : "NULL",
  1023. j, src->name, src_allocr ? ggml_backend_name(get_allocr_backend(sched, src_allocr)) : "NULL");
  1024. }
  1025. if (src->view_src != NULL && src_allocr != node_allocr(src->view_src)) {
  1026. fprintf(stderr, "!!!!!!! [src] %s has backend %s, view_src %s has backend %s\n",
  1027. src->name, src_allocr ? ggml_backend_name(get_allocr_backend(sched, src_allocr)) : "NULL",
  1028. src->view_src->name, node_allocr(src->view_src) ? ggml_backend_name(get_allocr_backend(sched, node_allocr(src->view_src))) : "NULL");
  1029. }
  1030. }
  1031. }
  1032. fflush(stderr);
  1033. #endif
  1034. // create copies of the graph for each split
  1035. // FIXME: avoid this copy, pass split inputs to ggml_gallocr_alloc_graph_n in some other way
  1036. struct ggml_cgraph * graph_copy = ggml_new_graph_custom(sched->ctx, graph->n_nodes + sched->n_splits*GGML_MAX_SPLIT_INPUTS, false);
  1037. for (int i = 0; i < sched->n_splits; i++) {
  1038. struct ggml_backend_sched_split * split = &sched->splits[i];
  1039. split->graph = ggml_graph_view(graph, split->i_start, split->i_end);
  1040. // add inputs to the graph copy so that they are allocated by ggml-alloc at the start of the split
  1041. for (int j = 0; j < split->n_inputs; j++) {
  1042. struct ggml_tensor * input = split->inputs[j];
  1043. struct ggml_tensor * input_cpy = sched->node_copies[hash_id(input)][sched_allocr_prio(sched, split->tallocr)];
  1044. // add a dependency to the input source so that it is not freed before the copy is done
  1045. GGML_ASSERT(input_cpy->src[0] == NULL || input_cpy->src[0] == input);
  1046. input_cpy->src[0] = input;
  1047. graph_copy->nodes[graph_copy->n_nodes++] = input_cpy;
  1048. }
  1049. for (int j = split->i_start; j < split->i_end; j++) {
  1050. graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
  1051. }
  1052. }
  1053. sched->graph = graph_copy;
  1054. }
  1055. static void sched_alloc_splits(ggml_backend_sched_t sched) {
  1056. ggml_gallocr_alloc_graph_n(
  1057. sched->galloc,
  1058. sched->graph,
  1059. sched->hash_set,
  1060. sched->node_talloc);
  1061. }
  1062. static void sched_compute_splits(ggml_backend_sched_t sched) {
  1063. uint64_t copy_us[GGML_MAX_BACKENDS] = {0};
  1064. uint64_t compute_us[GGML_MAX_BACKENDS] = {0};
  1065. struct ggml_backend_sched_split * splits = sched->splits;
  1066. for (int i = 0; i < sched->n_splits; i++) {
  1067. struct ggml_backend_sched_split * split = &splits[i];
  1068. ggml_backend_t split_backend = get_allocr_backend(sched, split->tallocr);
  1069. int split_backend_id = sched_backend_prio(sched, split_backend);
  1070. // copy the input tensors to the split backend
  1071. uint64_t copy_start_us = ggml_time_us();
  1072. for (int j = 0; j < split->n_inputs; j++) {
  1073. struct ggml_tensor * input = split->inputs[j];
  1074. struct ggml_tensor * input_cpy = sched->node_copies[hash_id(input)][split_backend_id];
  1075. GGML_ASSERT(input->buffer != NULL);
  1076. GGML_ASSERT(input_cpy->buffer != NULL);
  1077. // TODO: avoid this copy if it was already copied in a previous split, and the input didn't change
  1078. // this is important to avoid copying constants such as KQ_mask and inp_pos multiple times
  1079. ggml_backend_tensor_copy_async(split_backend, input, input_cpy);
  1080. }
  1081. //ggml_backend_synchronize(split_backend); // necessary to measure copy time
  1082. int64_t copy_end_us = ggml_time_us();
  1083. copy_us[split_backend_id] += copy_end_us - copy_start_us;
  1084. #if 0
  1085. char split_filename[GGML_MAX_NAME];
  1086. snprintf(split_filename, GGML_MAX_NAME, "split_%i_%s.dot", i, ggml_backend_name(split_backend));
  1087. ggml_graph_dump_dot(split->graph, NULL, split_filename);
  1088. #endif
  1089. uint64_t compute_start_us = ggml_time_us();
  1090. if (!sched->callback_eval) {
  1091. ggml_backend_graph_compute(split_backend, &split->graph);
  1092. //ggml_backend_synchronize(split_backend); // necessary to measure compute time
  1093. } else {
  1094. // similar to ggml_backend_compare_graph_backend
  1095. for (int j0 = 0; j0 < split->graph.n_nodes; j0++) {
  1096. struct ggml_tensor * t = split->graph.nodes[j0];
  1097. // check if the user needs data from this node
  1098. bool need = sched->callback_eval(t, true, sched->callback_eval_user_data);
  1099. int j1 = j0;
  1100. // determine the range [j0, j1] of nodes that can be computed together
  1101. while (!need && j1 < split->graph.n_nodes - 1) {
  1102. t = split->graph.nodes[++j1];
  1103. need = sched->callback_eval(t, true, sched->callback_eval_user_data);
  1104. }
  1105. struct ggml_cgraph gv = ggml_graph_view(&split->graph, j0, j1 + 1);
  1106. ggml_backend_graph_compute(split_backend, &gv);
  1107. if (need && !sched->callback_eval(t, false, sched->callback_eval_user_data)) {
  1108. break;
  1109. }
  1110. j0 = j1;
  1111. }
  1112. }
  1113. uint64_t compute_end_us = ggml_time_us();
  1114. compute_us[split_backend_id] += compute_end_us - compute_start_us;
  1115. }
  1116. #if 0
  1117. // per-backend timings
  1118. fprintf(stderr, "sched_compute_splits times (%d splits):\n", sched->n_splits);
  1119. for (int i = 0; i < sched->n_backends; i++) {
  1120. if (copy_us[i] > 0 || compute_us[i] > 0) {
  1121. fprintf(stderr, "\t%5.5s: %lu us copy, %lu us compute\n", ggml_backend_name(sched->backends[i]), copy_us[i], compute_us[i]);
  1122. }
  1123. }
  1124. #endif
  1125. }
  1126. static void sched_reset(ggml_backend_sched_t sched) {
  1127. for (int i = 0; i < sched->n_backends; i++) {
  1128. ggml_tallocr_reset(sched->tallocs[i]);
  1129. }
  1130. // reset state for the next run
  1131. size_t hash_size = sched->hash_set.size;
  1132. memset(sched->hash_set.keys, 0, sizeof(sched->hash_set.keys[0]) * hash_size);
  1133. memset(sched->node_talloc, 0, sizeof(sched->node_talloc[0]) * hash_size);
  1134. memset(sched->node_copies, 0, sizeof(sched->node_copies[0]) * hash_size);
  1135. sched->is_reset = true;
  1136. }
  1137. ggml_backend_sched_t ggml_backend_sched_new(ggml_backend_t * backends, ggml_backend_buffer_type_t * bufts, int n_backends, size_t graph_size) {
  1138. GGML_ASSERT(n_backends > 0);
  1139. GGML_ASSERT(n_backends <= GGML_MAX_BACKENDS);
  1140. struct ggml_backend_sched * sched = calloc(sizeof(struct ggml_backend_sched), 1);
  1141. // initialize hash table
  1142. sched->hash_set = ggml_hash_set_new(graph_size + GGML_MAX_SPLITS*GGML_MAX_SPLIT_INPUTS);
  1143. sched->node_talloc = calloc(sizeof(sched->node_talloc[0]) * sched->hash_set.size, 1);
  1144. sched->node_copies = calloc(sizeof(sched->node_copies[0]) * sched->hash_set.size, 1);
  1145. sched->n_backends = n_backends;
  1146. for (int i = 0; i < n_backends; i++) {
  1147. sched->backends[i] = backends[i];
  1148. sched->bufts[i] = bufts ? bufts[i] : ggml_backend_get_default_buffer_type(backends[i]);
  1149. }
  1150. sched->galloc = ggml_gallocr_new();
  1151. // init measure allocs for each backend
  1152. for (int i = 0; i < n_backends; i++) {
  1153. sched->tallocs[i] = ggml_tallocr_new_measure_from_buft(sched->bufts[i]);
  1154. }
  1155. sched_reset(sched);
  1156. return sched;
  1157. }
  1158. void ggml_backend_sched_free(ggml_backend_sched_t sched) {
  1159. if (sched == NULL) {
  1160. return;
  1161. }
  1162. for (int i = 0; i < sched->n_backends; i++) {
  1163. ggml_tallocr_free(sched->tallocs[i]);
  1164. }
  1165. ggml_gallocr_free(sched->galloc);
  1166. ggml_free(sched->ctx);
  1167. free(sched->hash_set.keys);
  1168. free(sched->node_talloc);
  1169. free(sched->node_copies);
  1170. free(sched);
  1171. }
  1172. void ggml_backend_sched_init_measure(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph) {
  1173. GGML_ASSERT(ggml_tallocr_is_measure(sched->tallocs[0])); // can only be initialized once
  1174. sched_split_graph(sched, measure_graph);
  1175. sched_alloc_splits(sched);
  1176. // allocate buffers and reset allocators
  1177. for (int i = 0; i < sched->n_backends; i++) {
  1178. size_t size = ggml_tallocr_max_size(sched->tallocs[i]);
  1179. ggml_tallocr_free(sched->tallocs[i]);
  1180. sched->tallocs[i] = ggml_tallocr_new_from_buft(sched->bufts[i], size);
  1181. }
  1182. sched_reset(sched);
  1183. }
  1184. void ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  1185. GGML_ASSERT((int)sched->hash_set.size >= graph->n_nodes + GGML_MAX_SPLITS*GGML_MAX_SPLIT_INPUTS);
  1186. if (!sched->is_reset) {
  1187. sched_reset(sched);
  1188. }
  1189. sched_split_graph(sched, graph);
  1190. sched_alloc_splits(sched);
  1191. sched_compute_splits(sched);
  1192. }
  1193. void ggml_backend_sched_reset(ggml_backend_sched_t sched) {
  1194. sched_reset(sched);
  1195. }
  1196. void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data) {
  1197. sched->callback_eval = callback;
  1198. sched->callback_eval_user_data = user_data;
  1199. }
  1200. int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched) {
  1201. return sched->n_splits;
  1202. }
  1203. ggml_tallocr_t ggml_backend_sched_get_tallocr(ggml_backend_sched_t sched, ggml_backend_t backend) {
  1204. int backend_index = sched_backend_prio(sched, backend);
  1205. GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
  1206. return sched->tallocs[backend_index];
  1207. }
  1208. ggml_backend_buffer_t ggml_backend_sched_get_buffer(ggml_backend_sched_t sched, ggml_backend_t backend) {
  1209. int backend_index = sched_backend_prio(sched, backend);
  1210. GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
  1211. return ggml_tallocr_get_buffer(sched->tallocs[backend_index]);
  1212. }
  1213. void ggml_backend_sched_set_node_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend) {
  1214. int backend_index = sched_backend_prio(sched, backend);
  1215. GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
  1216. node_allocr(node) = sched->tallocs[backend_index];
  1217. }
  1218. ggml_backend_t ggml_backend_sched_get_node_backend(ggml_backend_sched_t sched, struct ggml_tensor * node) {
  1219. ggml_tallocr_t allocr = node_allocr(node);
  1220. if (allocr == NULL) {
  1221. return NULL;
  1222. }
  1223. return get_allocr_backend(sched, allocr);
  1224. }
  1225. // utils
  1226. void ggml_backend_view_init(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
  1227. GGML_ASSERT(tensor->buffer == NULL);
  1228. //GGML_ASSERT(tensor->data == NULL); // views of pre-allocated tensors may have the data set in ggml_new_tensor, but still need to be initialized by the backend
  1229. GGML_ASSERT(tensor->view_src != NULL);
  1230. GGML_ASSERT(tensor->view_src->buffer != NULL);
  1231. GGML_ASSERT(tensor->view_src->data != NULL);
  1232. tensor->buffer = buffer;
  1233. tensor->data = (char *)tensor->view_src->data + tensor->view_offs;
  1234. tensor->backend = tensor->view_src->backend;
  1235. ggml_backend_buffer_init_tensor(buffer, tensor);
  1236. }
  1237. void ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr) {
  1238. GGML_ASSERT(tensor->buffer == NULL);
  1239. GGML_ASSERT(tensor->data == NULL);
  1240. GGML_ASSERT(tensor->view_src == NULL);
  1241. GGML_ASSERT(addr >= ggml_backend_buffer_get_base(buffer));
  1242. GGML_ASSERT((char *)addr + ggml_backend_buffer_get_alloc_size(buffer, tensor) <=
  1243. (char *)ggml_backend_buffer_get_base(buffer) + ggml_backend_buffer_get_size(buffer));
  1244. tensor->buffer = buffer;
  1245. tensor->data = addr;
  1246. ggml_backend_buffer_init_tensor(buffer, tensor);
  1247. }
  1248. static struct ggml_tensor * graph_dup_tensor(struct ggml_hash_set hash_set, struct ggml_tensor ** node_copies,
  1249. struct ggml_context * ctx_allocated, struct ggml_context * ctx_unallocated, struct ggml_tensor * src) {
  1250. GGML_ASSERT(src != NULL);
  1251. GGML_ASSERT(src->data && "graph must be allocated");
  1252. size_t id = ggml_hash_insert(hash_set, src);
  1253. if (id == GGML_HASHTABLE_ALREADY_EXISTS) {
  1254. return node_copies[ggml_hash_find(hash_set, src)];
  1255. }
  1256. struct ggml_tensor * dst = ggml_dup_tensor_layout(src->data && !src->view_src ? ctx_allocated : ctx_unallocated, src);
  1257. if (src->view_src != NULL) {
  1258. dst->view_src = graph_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, src->view_src);
  1259. dst->view_offs = src->view_offs;
  1260. }
  1261. dst->op = src->op;
  1262. memcpy(dst->op_params, src->op_params, sizeof(dst->op_params));
  1263. ggml_set_name(dst, src->name);
  1264. // copy src
  1265. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1266. struct ggml_tensor * s = src->src[i];
  1267. if (s == NULL) {
  1268. break;
  1269. }
  1270. dst->src[i] = graph_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, s);
  1271. }
  1272. node_copies[id] = dst;
  1273. return dst;
  1274. }
  1275. static void graph_init_tensor(struct ggml_hash_set hash_set, struct ggml_tensor ** node_copies, bool * node_init, struct ggml_tensor * src) {
  1276. size_t id = ggml_hash_find(hash_set, src);
  1277. if (node_init[id]) {
  1278. return;
  1279. }
  1280. node_init[id] = true;
  1281. struct ggml_tensor * dst = node_copies[id];
  1282. if (dst->view_src != NULL) {
  1283. graph_init_tensor(hash_set, node_copies, node_init, src->view_src);
  1284. ggml_backend_view_init(dst->view_src->buffer, dst);
  1285. }
  1286. else {
  1287. ggml_backend_tensor_copy(src, dst);
  1288. }
  1289. // init src
  1290. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1291. struct ggml_tensor * s = src->src[i];
  1292. if (s == NULL) {
  1293. break;
  1294. }
  1295. graph_init_tensor(hash_set, node_copies, node_init, s);
  1296. }
  1297. }
  1298. struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph) {
  1299. struct ggml_hash_set hash_set = {
  1300. /* .size = */ graph->visited_hash_table.size,
  1301. /* .keys = */ calloc(sizeof(hash_set.keys[0]) * graph->visited_hash_table.size, 1)
  1302. };
  1303. struct ggml_tensor ** node_copies = calloc(sizeof(node_copies[0]) * hash_set.size, 1);
  1304. bool * node_init = calloc(sizeof(node_init[0]) * hash_set.size, 1);
  1305. struct ggml_init_params params = {
  1306. /* .mem_size = */ ggml_tensor_overhead()*hash_set.size + ggml_graph_overhead_custom(graph->size, false),
  1307. /* .mem_buffer = */ NULL,
  1308. /* .no_alloc = */ true
  1309. };
  1310. struct ggml_context * ctx_allocated = ggml_init(params);
  1311. struct ggml_context * ctx_unallocated = ggml_init(params);
  1312. if (ctx_allocated == NULL || ctx_unallocated == NULL) {
  1313. fprintf(stderr, "failed to allocate context for graph copy\n");
  1314. free(hash_set.keys);
  1315. free(node_copies);
  1316. free(node_init);
  1317. ggml_free(ctx_allocated);
  1318. ggml_free(ctx_unallocated);
  1319. return (struct ggml_backend_graph_copy) {
  1320. /* .buffer = */ NULL,
  1321. /* .ctx_allocated = */ NULL,
  1322. /* .ctx_unallocated = */ NULL,
  1323. /* .graph = */ NULL,
  1324. };
  1325. }
  1326. // dup nodes
  1327. for (int i = 0; i < graph->n_nodes; i++) {
  1328. struct ggml_tensor * node = graph->nodes[i];
  1329. graph_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, node);
  1330. }
  1331. // allocate nodes
  1332. ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx_allocated, backend);
  1333. if (buffer == NULL) {
  1334. fprintf(stderr, "failed to allocate buffer for graph copy\n");
  1335. free(hash_set.keys);
  1336. free(node_copies);
  1337. free(node_init);
  1338. ggml_free(ctx_allocated);
  1339. ggml_free(ctx_unallocated);
  1340. return (struct ggml_backend_graph_copy) {
  1341. /* .buffer = */ NULL,
  1342. /* .ctx_allocated = */ NULL,
  1343. /* .ctx_unallocated = */ NULL,
  1344. /* .graph = */ NULL,
  1345. };
  1346. }
  1347. //printf("copy buffer size: %zu MB\n", ggml_backend_buffer_get_size(buffer) / 1024 / 1024);
  1348. // copy data and init views
  1349. for (int i = 0; i < graph->n_nodes; i++) {
  1350. struct ggml_tensor * node = graph->nodes[i];
  1351. graph_init_tensor(hash_set, node_copies, node_init, node);
  1352. }
  1353. // build graph copy
  1354. struct ggml_cgraph * graph_copy = ggml_new_graph_custom(ctx_allocated, graph->size, false);
  1355. for (int i = 0; i < graph->n_nodes; i++) {
  1356. struct ggml_tensor * node = graph->nodes[i];
  1357. struct ggml_tensor * node_copy = node_copies[ggml_hash_find(hash_set, node)];
  1358. graph_copy->nodes[i] = node_copy;
  1359. }
  1360. graph_copy->n_nodes = graph->n_nodes;
  1361. free(hash_set.keys);
  1362. free(node_copies);
  1363. free(node_init);
  1364. return (struct ggml_backend_graph_copy) {
  1365. /* .buffer = */ buffer,
  1366. /* .ctx_allocated = */ ctx_allocated,
  1367. /* .ctx_unallocated = */ ctx_unallocated,
  1368. /* .graph = */ graph_copy,
  1369. };
  1370. }
  1371. void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy) {
  1372. ggml_backend_buffer_free(copy.buffer);
  1373. ggml_free(copy.ctx_allocated);
  1374. ggml_free(copy.ctx_unallocated);
  1375. }
  1376. bool ggml_backend_compare_graph_backend(ggml_backend_t backend1, ggml_backend_t backend2, struct ggml_cgraph * graph, ggml_backend_eval_callback callback, void * user_data) {
  1377. struct ggml_backend_graph_copy copy = ggml_backend_graph_copy(backend2, graph);
  1378. if (copy.buffer == NULL) {
  1379. return false;
  1380. }
  1381. struct ggml_cgraph * g1 = graph;
  1382. struct ggml_cgraph * g2 = copy.graph;
  1383. assert(g1->n_nodes == g2->n_nodes);
  1384. for (int i = 0; i < g1->n_nodes; i++) {
  1385. //printf("eval %d/%d\n", i, g1->n_nodes);
  1386. struct ggml_tensor * t1 = g1->nodes[i];
  1387. struct ggml_tensor * t2 = g2->nodes[i];
  1388. assert(t1->op == t2->op && ggml_are_same_layout(t1, t2));
  1389. struct ggml_cgraph g1v = ggml_graph_view(g1, i, i + 1);
  1390. struct ggml_cgraph g2v = ggml_graph_view(g2, i, i + 1);
  1391. ggml_backend_graph_compute(backend1, &g1v);
  1392. ggml_backend_graph_compute(backend2, &g2v);
  1393. if (ggml_is_view_op(t1->op)) {
  1394. continue;
  1395. }
  1396. // compare results, calculate rms etc
  1397. if (!callback(i, t1, t2, user_data)) {
  1398. break;
  1399. }
  1400. }
  1401. ggml_backend_graph_copy_free(copy);
  1402. return true;
  1403. }