ggml-backend.c 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  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. size_t ggml_backend_buft_get_max_size(ggml_backend_buffer_type_t buft) {
  22. // get_max_size is optional, defaults to SIZE_MAX
  23. if (buft->iface.get_max_size) {
  24. return buft->iface.get_max_size(buft);
  25. }
  26. return SIZE_MAX;
  27. }
  28. GGML_CALL size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, struct ggml_tensor * tensor) {
  29. // get_alloc_size is optional, defaults to ggml_nbytes
  30. if (buft->iface.get_alloc_size) {
  31. size_t size = buft->iface.get_alloc_size(buft, tensor);
  32. assert(size >= ggml_nbytes(tensor));
  33. return size;
  34. }
  35. return ggml_nbytes(tensor);
  36. }
  37. bool ggml_backend_buft_is_host(ggml_backend_buffer_type_t buft) {
  38. if (buft->iface.is_host) {
  39. return buft->iface.is_host(buft);
  40. }
  41. return false;
  42. }
  43. // backend buffer
  44. GGML_CALL ggml_backend_buffer_t ggml_backend_buffer_init(
  45. ggml_backend_buffer_type_t buft,
  46. struct ggml_backend_buffer_i iface,
  47. ggml_backend_buffer_context_t context,
  48. size_t size) {
  49. ggml_backend_buffer_t buffer = malloc(sizeof(struct ggml_backend_buffer));
  50. (*buffer) = (struct ggml_backend_buffer) {
  51. /* .interface = */ iface,
  52. /* .buft = */ buft,
  53. /* .context = */ context,
  54. /* .size = */ size,
  55. /* .usage = */ GGML_BACKEND_BUFFER_USAGE_ANY
  56. };
  57. return buffer;
  58. }
  59. const char * ggml_backend_buffer_name(ggml_backend_buffer_t buffer) {
  60. return buffer->iface.get_name(buffer);
  61. }
  62. void ggml_backend_buffer_free(ggml_backend_buffer_t buffer) {
  63. if (buffer == NULL) {
  64. return;
  65. }
  66. if (buffer->iface.free_buffer != NULL) {
  67. buffer->iface.free_buffer(buffer);
  68. }
  69. free(buffer);
  70. }
  71. size_t ggml_backend_buffer_get_size(ggml_backend_buffer_t buffer) {
  72. return buffer->size;
  73. }
  74. void * ggml_backend_buffer_get_base(ggml_backend_buffer_t buffer) {
  75. void * base = buffer->iface.get_base(buffer);
  76. GGML_ASSERT(base != NULL && "backend buffer base cannot be NULL");
  77. return base;
  78. }
  79. GGML_CALL void ggml_backend_buffer_init_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
  80. // init_tensor is optional
  81. if (buffer->iface.init_tensor) {
  82. buffer->iface.init_tensor(buffer, tensor);
  83. }
  84. }
  85. size_t ggml_backend_buffer_get_alignment (ggml_backend_buffer_t buffer) {
  86. return ggml_backend_buft_get_alignment(ggml_backend_buffer_get_type(buffer));
  87. }
  88. size_t ggml_backend_buffer_get_max_size(ggml_backend_buffer_t buffer) {
  89. return ggml_backend_buft_get_max_size(ggml_backend_buffer_get_type(buffer));
  90. }
  91. size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
  92. return ggml_backend_buft_get_alloc_size(ggml_backend_buffer_get_type(buffer), tensor);
  93. }
  94. void ggml_backend_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  95. buffer->iface.clear(buffer, value);
  96. }
  97. bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) {
  98. return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer));
  99. }
  100. void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) {
  101. buffer->usage = usage;
  102. // FIXME: add a generic callback to the buffer interface
  103. if (ggml_backend_buffer_is_multi_buffer(buffer)) {
  104. ggml_backend_multi_buffer_set_usage(buffer, usage);
  105. }
  106. }
  107. enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage(ggml_backend_buffer_t buffer) {
  108. return buffer->usage;
  109. }
  110. ggml_backend_buffer_type_t ggml_backend_buffer_get_type(ggml_backend_buffer_t buffer) {
  111. return buffer->buft;
  112. }
  113. void ggml_backend_buffer_reset(ggml_backend_buffer_t buffer) {
  114. if (buffer->iface.reset) {
  115. buffer->iface.reset(buffer);
  116. }
  117. }
  118. bool ggml_backend_buffer_copy_tensor(const struct ggml_tensor * src, struct ggml_tensor * dst) {
  119. ggml_backend_buffer_t dst_buf = dst->view_src ? dst->view_src->buffer : dst->buffer;
  120. if (dst_buf->iface.cpy_tensor) {
  121. return dst_buf->iface.cpy_tensor(dst_buf, src, dst);
  122. }
  123. return false;
  124. }
  125. // backend
  126. ggml_guid_t ggml_backend_guid(ggml_backend_t backend) {
  127. if (backend == NULL) {
  128. return NULL;
  129. }
  130. return backend->guid;
  131. }
  132. const char * ggml_backend_name(ggml_backend_t backend) {
  133. if (backend == NULL) {
  134. return "NULL";
  135. }
  136. return backend->iface.get_name(backend);
  137. }
  138. void ggml_backend_free(ggml_backend_t backend) {
  139. if (backend == NULL) {
  140. return;
  141. }
  142. backend->iface.free(backend);
  143. }
  144. ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend) {
  145. return backend->iface.get_default_buffer_type(backend);
  146. }
  147. ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size) {
  148. return ggml_backend_buft_alloc_buffer(ggml_backend_get_default_buffer_type(backend), size);
  149. }
  150. size_t ggml_backend_get_alignment(ggml_backend_t backend) {
  151. return ggml_backend_buft_get_alignment(ggml_backend_get_default_buffer_type(backend));
  152. }
  153. size_t ggml_backend_get_max_size(ggml_backend_t backend) {
  154. return ggml_backend_buft_get_max_size(ggml_backend_get_default_buffer_type(backend));
  155. }
  156. void ggml_backend_tensor_set_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  157. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  158. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  159. if (backend->iface.set_tensor_async == NULL) {
  160. ggml_backend_tensor_set(tensor, data, offset, size);
  161. } else {
  162. backend->iface.set_tensor_async(backend, tensor, data, offset, size);
  163. }
  164. }
  165. void ggml_backend_tensor_get_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  166. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  167. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  168. if (backend->iface.get_tensor_async == NULL) {
  169. ggml_backend_tensor_get(tensor, data, offset, size);
  170. } else {
  171. backend->iface.get_tensor_async(backend, tensor, data, offset, size);
  172. }
  173. }
  174. GGML_CALL void ggml_backend_tensor_set(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  175. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  176. GGML_ASSERT(buf != NULL && "tensor buffer not set");
  177. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  178. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  179. if (!size) {
  180. return;
  181. }
  182. buf->iface.set_tensor(buf, tensor, data, offset, size);
  183. }
  184. GGML_CALL void ggml_backend_tensor_get(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  185. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  186. GGML_ASSERT(buf != NULL && "tensor buffer not set");
  187. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  188. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  189. if (!size) {
  190. return;
  191. }
  192. buf->iface.get_tensor(buf, tensor, data, offset, size);
  193. }
  194. void ggml_backend_synchronize(ggml_backend_t backend) {
  195. if (backend->iface.synchronize == NULL) {
  196. return;
  197. }
  198. backend->iface.synchronize(backend);
  199. }
  200. ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  201. GGML_ASSERT(backend->iface.graph_plan_create != NULL);
  202. return backend->iface.graph_plan_create(backend, cgraph);
  203. }
  204. void ggml_backend_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  205. GGML_ASSERT(backend->iface.graph_plan_free != NULL);
  206. backend->iface.graph_plan_free(backend, plan);
  207. }
  208. enum ggml_status ggml_backend_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  209. GGML_ASSERT(backend->iface.graph_plan_compute != NULL);
  210. return backend->iface.graph_plan_compute(backend, plan);
  211. }
  212. enum ggml_status ggml_backend_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  213. enum ggml_status err = ggml_backend_graph_compute_async(backend, cgraph);
  214. ggml_backend_synchronize(backend);
  215. return err;
  216. }
  217. enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  218. return backend->iface.graph_compute(backend, cgraph);
  219. }
  220. bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  221. return backend->iface.supports_op(backend, op);
  222. }
  223. bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
  224. return backend->iface.supports_buft(backend, buft);
  225. }
  226. bool ggml_backend_offload_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  227. if (backend->iface.offload_op != NULL) {
  228. return backend->iface.offload_op(backend, op);
  229. }
  230. return false;
  231. }
  232. // backend copy
  233. static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
  234. if (a->type != b->type) {
  235. return false;
  236. }
  237. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  238. if (a->ne[i] != b->ne[i]) {
  239. return false;
  240. }
  241. if (a->nb[i] != b->nb[i]) {
  242. return false;
  243. }
  244. }
  245. return true;
  246. }
  247. void ggml_backend_tensor_copy(struct ggml_tensor * src, struct ggml_tensor * dst) {
  248. GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
  249. if (src == dst) {
  250. return;
  251. }
  252. if (ggml_backend_buffer_is_host(src->buffer)) {
  253. ggml_backend_tensor_set(dst, src->data, 0, ggml_nbytes(src));
  254. } else if (ggml_backend_buffer_is_host(dst->buffer)) {
  255. ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
  256. } else if (!ggml_backend_buffer_copy_tensor(src, dst)) {
  257. #ifndef NDEBUG
  258. fprintf(stderr, "%s: warning: slow copy from %s to %s\n", __func__, ggml_backend_buffer_name(src->buffer), ggml_backend_buffer_name(dst->buffer));
  259. #endif
  260. size_t nbytes = ggml_nbytes(src);
  261. void * data = malloc(nbytes);
  262. ggml_backend_tensor_get(src, data, 0, nbytes);
  263. ggml_backend_tensor_set(dst, data, 0, nbytes);
  264. free(data);
  265. }
  266. }
  267. void ggml_backend_tensor_copy_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, struct ggml_tensor * src, struct ggml_tensor * dst) {
  268. GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
  269. if (src == dst) {
  270. return;
  271. }
  272. if (backend_dst->iface.cpy_tensor_async != NULL) {
  273. if (backend_dst->iface.cpy_tensor_async(backend_src, backend_dst, src, dst)) {
  274. return;
  275. }
  276. }
  277. // an async copy would normally happen after all the queued operations on both backends are completed
  278. // to simulate the same behavior, we need to synchronize both backends first, and do a blocking copy
  279. ggml_backend_synchronize(backend_src);
  280. ggml_backend_synchronize(backend_dst);
  281. ggml_backend_tensor_copy(src, dst);
  282. }
  283. // events
  284. ggml_backend_event_t ggml_backend_event_new(ggml_backend_t backend) {
  285. if (backend->iface.event_new == NULL) {
  286. return NULL;
  287. }
  288. return backend->iface.event_new(backend);
  289. }
  290. void ggml_backend_event_free(ggml_backend_event_t event) {
  291. if (event == NULL) {
  292. return;
  293. }
  294. event->backend->iface.event_free(event);
  295. }
  296. void ggml_backend_event_record(ggml_backend_event_t event) {
  297. GGML_ASSERT(event->backend->iface.event_record != NULL);
  298. event->backend->iface.event_record(event);
  299. }
  300. void ggml_backend_event_synchronize(ggml_backend_event_t event) {
  301. GGML_ASSERT(event->backend->iface.event_synchronize != NULL);
  302. event->backend->iface.event_synchronize(event);
  303. }
  304. void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  305. GGML_ASSERT(backend->iface.event_wait != NULL);
  306. backend->iface.event_wait(backend, event);
  307. }
  308. // backend registry
  309. #define GGML_REG_MAX_BACKENDS 64
  310. struct ggml_backend_reg {
  311. char name[128];
  312. ggml_backend_init_fn init_fn;
  313. ggml_backend_buffer_type_t default_buffer_type;
  314. void * user_data;
  315. };
  316. static struct ggml_backend_reg ggml_backend_registry[GGML_REG_MAX_BACKENDS];
  317. static size_t ggml_backend_registry_count = 0;
  318. GGML_CALL static ggml_backend_t ggml_backend_reg_cpu_init(const char * params, void * user_data);
  319. GGML_CALL static void ggml_backend_registry_init(void) {
  320. static bool initialized = false;
  321. if (initialized) {
  322. return;
  323. }
  324. initialized = true;
  325. ggml_backend_register("CPU", ggml_backend_reg_cpu_init, ggml_backend_cpu_buffer_type(), NULL);
  326. // add forward decls here to avoid including the backend headers
  327. #ifdef GGML_USE_CUDA
  328. extern GGML_CALL void ggml_backend_cuda_reg_devices(void);
  329. ggml_backend_cuda_reg_devices();
  330. #endif
  331. #ifdef GGML_USE_SYCL
  332. extern void ggml_backend_sycl_reg_devices(void);
  333. ggml_backend_sycl_reg_devices();
  334. #endif
  335. #ifdef GGML_USE_METAL
  336. extern GGML_CALL ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data);
  337. extern GGML_CALL ggml_backend_buffer_type_t ggml_backend_metal_buffer_type(void);
  338. ggml_backend_register("Metal", ggml_backend_reg_metal_init, ggml_backend_metal_buffer_type(), NULL);
  339. #endif
  340. #ifdef GGML_USE_VULKAN
  341. extern GGML_CALL int ggml_backend_vk_reg_devices(void);
  342. ggml_backend_vk_reg_devices();
  343. #endif
  344. #ifdef GGML_USE_KOMPUTE
  345. extern GGML_CALL void ggml_backend_kompute_reg_devices(void);
  346. ggml_backend_kompute_reg_devices();
  347. #endif
  348. #ifdef GGML_USE_CANN
  349. extern GGML_CALL int ggml_backend_cann_reg_devices(void);
  350. ggml_backend_cann_reg_devices();
  351. #endif
  352. }
  353. 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) {
  354. GGML_ASSERT(ggml_backend_registry_count < GGML_REG_MAX_BACKENDS);
  355. size_t id = ggml_backend_registry_count;
  356. ggml_backend_registry[id] = (struct ggml_backend_reg) {
  357. /* .name = */ {0},
  358. /* .fn = */ init_fn,
  359. /* .default_buffer_type = */ default_buffer_type,
  360. /* .user_data = */ user_data,
  361. };
  362. snprintf(ggml_backend_registry[id].name, sizeof(ggml_backend_registry[id].name), "%s", name);
  363. #ifndef NDEBUG
  364. fprintf(stderr, "%s: registered backend %s\n", __func__, name);
  365. #endif
  366. ggml_backend_registry_count++;
  367. }
  368. size_t ggml_backend_reg_get_count(void) {
  369. ggml_backend_registry_init();
  370. return ggml_backend_registry_count;
  371. }
  372. size_t ggml_backend_reg_find_by_name(const char * name) {
  373. ggml_backend_registry_init();
  374. for (size_t i = 0; i < ggml_backend_registry_count; i++) {
  375. // TODO: case insensitive in a portable way
  376. if (strcmp(ggml_backend_registry[i].name, name) == 0) {
  377. return i;
  378. }
  379. }
  380. // not found
  381. return SIZE_MAX;
  382. }
  383. // init from backend:params string
  384. ggml_backend_t ggml_backend_reg_init_backend_from_str(const char * backend_str) {
  385. ggml_backend_registry_init();
  386. const char * params = strchr(backend_str, ':');
  387. char backend_name[128];
  388. if (params == NULL) {
  389. snprintf(backend_name, sizeof(backend_name), "%s", backend_str);
  390. params = "";
  391. } else {
  392. snprintf(backend_name, sizeof(backend_name), "%.*s", (int)(params - backend_str), backend_str);
  393. params++;
  394. }
  395. size_t backend_i = ggml_backend_reg_find_by_name(backend_name);
  396. if (backend_i == SIZE_MAX) {
  397. fprintf(stderr, "%s: backend %s not found\n", __func__, backend_name);
  398. return NULL;
  399. }
  400. return ggml_backend_reg_init_backend(backend_i, params);
  401. }
  402. const char * ggml_backend_reg_get_name(size_t i) {
  403. ggml_backend_registry_init();
  404. GGML_ASSERT(i < ggml_backend_registry_count);
  405. return ggml_backend_registry[i].name;
  406. }
  407. ggml_backend_t ggml_backend_reg_init_backend(size_t i, const char * params) {
  408. ggml_backend_registry_init();
  409. GGML_ASSERT(i < ggml_backend_registry_count);
  410. return ggml_backend_registry[i].init_fn(params, ggml_backend_registry[i].user_data);
  411. }
  412. ggml_backend_buffer_type_t ggml_backend_reg_get_default_buffer_type(size_t i) {
  413. ggml_backend_registry_init();
  414. GGML_ASSERT(i < ggml_backend_registry_count);
  415. return ggml_backend_registry[i].default_buffer_type;
  416. }
  417. ggml_backend_buffer_t ggml_backend_reg_alloc_buffer(size_t i, size_t size) {
  418. ggml_backend_registry_init();
  419. GGML_ASSERT(i < ggml_backend_registry_count);
  420. return ggml_backend_buft_alloc_buffer(ggml_backend_registry[i].default_buffer_type, size);
  421. }
  422. // backend CPU
  423. static const size_t TENSOR_ALIGNMENT = 32; // required for mmap as gguf only guarantees 32-byte alignment
  424. GGML_CALL static const char * ggml_backend_cpu_buffer_name(ggml_backend_buffer_t buffer) {
  425. return "CPU";
  426. GGML_UNUSED(buffer);
  427. }
  428. GGML_CALL static void * ggml_backend_cpu_buffer_get_base(ggml_backend_buffer_t buffer) {
  429. uintptr_t data = (uintptr_t)buffer->context;
  430. // align the buffer
  431. if (data % TENSOR_ALIGNMENT != 0) {
  432. data = GGML_PAD(data, TENSOR_ALIGNMENT);
  433. }
  434. return (void *)data;
  435. }
  436. GGML_CALL static void ggml_backend_cpu_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  437. free(buffer->context);
  438. }
  439. 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) {
  440. memcpy((char *)tensor->data + offset, data, size);
  441. GGML_UNUSED(buffer);
  442. }
  443. 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) {
  444. memcpy(data, (const char *)tensor->data + offset, size);
  445. GGML_UNUSED(buffer);
  446. }
  447. GGML_CALL static bool ggml_backend_cpu_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * src, struct ggml_tensor * dst) {
  448. if (ggml_backend_buffer_is_host(src->buffer)) {
  449. memcpy(dst->data, src->data, ggml_nbytes(src));
  450. return true;
  451. }
  452. return false;
  453. GGML_UNUSED(buffer);
  454. }
  455. GGML_CALL static void ggml_backend_cpu_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  456. memset(buffer->context, value, buffer->size);
  457. }
  458. static struct ggml_backend_buffer_i cpu_backend_buffer_i = {
  459. /* .get_name = */ ggml_backend_cpu_buffer_name,
  460. /* .free_buffer = */ ggml_backend_cpu_buffer_free_buffer,
  461. /* .get_base = */ ggml_backend_cpu_buffer_get_base,
  462. /* .init_tensor = */ NULL, // no initialization required
  463. /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
  464. /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
  465. /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
  466. /* .clear = */ ggml_backend_cpu_buffer_clear,
  467. /* .reset = */ NULL,
  468. };
  469. // for buffers from ptr, free is not called
  470. static struct ggml_backend_buffer_i cpu_backend_buffer_i_from_ptr = {
  471. /* .get_name = */ ggml_backend_cpu_buffer_name,
  472. /* .free_buffer = */ NULL, // ptr is not owned by the buffer, so it does not need to be freed
  473. /* .get_base = */ ggml_backend_cpu_buffer_get_base,
  474. /* .init_tensor = */ NULL, // no initialization required
  475. /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
  476. /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
  477. /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
  478. /* .clear = */ ggml_backend_cpu_buffer_clear,
  479. /* .reset = */ NULL,
  480. };
  481. GGML_CALL static const char * ggml_backend_cpu_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  482. return "CPU";
  483. GGML_UNUSED(buft);
  484. }
  485. GGML_CALL static ggml_backend_buffer_t ggml_backend_cpu_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  486. size += TENSOR_ALIGNMENT; // malloc may return an address that is not aligned
  487. void * data = malloc(size); // TODO: use GGML_ALIGNED_MALLOC (move to ggml-impl.h)
  488. if (data == NULL) {
  489. fprintf(stderr, "%s: failed to allocate buffer of size %zu\n", __func__, size);
  490. return NULL;
  491. }
  492. return ggml_backend_buffer_init(buft, cpu_backend_buffer_i, data, size);
  493. }
  494. GGML_CALL static size_t ggml_backend_cpu_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  495. return TENSOR_ALIGNMENT;
  496. GGML_UNUSED(buft);
  497. }
  498. GGML_CALL static bool ggml_backend_cpu_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  499. return true;
  500. GGML_UNUSED(buft);
  501. }
  502. GGML_CALL ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void) {
  503. static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = {
  504. /* .iface = */ {
  505. /* .get_name = */ ggml_backend_cpu_buffer_type_get_name,
  506. /* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer,
  507. /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
  508. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  509. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  510. /* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
  511. },
  512. /* .context = */ NULL,
  513. };
  514. return &ggml_backend_cpu_buffer_type;
  515. }
  516. #ifdef GGML_USE_CPU_HBM
  517. // buffer type HBM
  518. #include <hbwmalloc.h>
  519. GGML_CALL static const char * ggml_backend_cpu_hbm_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  520. return "CPU_HBM";
  521. GGML_UNUSED(buft);
  522. }
  523. GGML_CALL static const char * ggml_backend_cpu_hbm_buffer_get_name(ggml_backend_buffer_t buf) {
  524. return "CPU_HBM";
  525. GGML_UNUSED(buf);
  526. }
  527. GGML_CALL static void ggml_backend_cpu_hbm_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  528. hbw_free(buffer->context);
  529. }
  530. GGML_CALL static ggml_backend_buffer_t ggml_backend_cpu_hbm_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  531. //void * ptr = hbw_malloc(size);
  532. void * ptr;
  533. int result = hbw_posix_memalign(&ptr, ggml_backend_cpu_buffer_type_get_alignment(buft), size);
  534. if (result != 0) {
  535. fprintf(stderr, "failed to allocate HBM buffer of size %zu\n", size);
  536. return NULL;
  537. }
  538. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  539. buffer->buft = buft;
  540. buffer->iface.get_name = ggml_backend_cpu_hbm_buffer_get_name;
  541. buffer->iface.free_buffer = ggml_backend_cpu_hbm_buffer_free_buffer;
  542. return buffer;
  543. }
  544. ggml_backend_buffer_type_t ggml_backend_cpu_hbm_buffer_type(void) {
  545. static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type_hbm = {
  546. /* .iface = */ {
  547. /* .get_name = */ ggml_backend_cpu_hbm_buffer_type_get_name,
  548. /* .alloc_buffer = */ ggml_backend_cpu_hbm_buffer_type_alloc_buffer,
  549. /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
  550. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  551. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  552. /* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
  553. },
  554. /* .context = */ NULL,
  555. };
  556. return &ggml_backend_cpu_buffer_type_hbm;
  557. }
  558. #endif
  559. struct ggml_backend_cpu_context {
  560. int n_threads;
  561. ggml_threadpool_t threadpool;
  562. void * work_data;
  563. size_t work_size;
  564. ggml_abort_callback abort_callback;
  565. void * abort_callback_data;
  566. };
  567. GGML_CALL static const char * ggml_backend_cpu_name(ggml_backend_t backend) {
  568. return "CPU";
  569. GGML_UNUSED(backend);
  570. }
  571. GGML_CALL static void ggml_backend_cpu_free(ggml_backend_t backend) {
  572. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  573. free(cpu_ctx->work_data);
  574. free(cpu_ctx);
  575. free(backend);
  576. }
  577. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_cpu_get_default_buffer_type(ggml_backend_t backend) {
  578. return ggml_backend_cpu_buffer_type();
  579. GGML_UNUSED(backend);
  580. }
  581. struct ggml_backend_plan_cpu {
  582. struct ggml_cplan cplan;
  583. struct ggml_cgraph cgraph;
  584. };
  585. GGML_CALL static ggml_backend_graph_plan_t ggml_backend_cpu_graph_plan_create(ggml_backend_t backend, const struct ggml_cgraph * cgraph) {
  586. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  587. struct ggml_backend_plan_cpu * cpu_plan = malloc(sizeof(struct ggml_backend_plan_cpu));
  588. cpu_plan->cplan = ggml_graph_plan(cgraph, cpu_ctx->n_threads, cpu_ctx->threadpool);
  589. cpu_plan->cgraph = *cgraph; // FIXME: deep copy
  590. if (cpu_plan->cplan.work_size > 0) {
  591. cpu_plan->cplan.work_data = malloc(cpu_plan->cplan.work_size);
  592. if (cpu_plan->cplan.work_data == NULL) {
  593. free(cpu_plan);
  594. return NULL;
  595. }
  596. }
  597. cpu_plan->cplan.abort_callback = cpu_ctx->abort_callback;
  598. cpu_plan->cplan.abort_callback_data = cpu_ctx->abort_callback_data;
  599. return cpu_plan;
  600. }
  601. GGML_CALL static void ggml_backend_cpu_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  602. struct ggml_backend_plan_cpu * cpu_plan = (struct ggml_backend_plan_cpu *)plan;
  603. free(cpu_plan->cplan.work_data);
  604. free(cpu_plan);
  605. GGML_UNUSED(backend);
  606. }
  607. GGML_CALL static enum ggml_status ggml_backend_cpu_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
  608. struct ggml_backend_plan_cpu * cpu_plan = (struct ggml_backend_plan_cpu *)plan;
  609. return ggml_graph_compute(&cpu_plan->cgraph, &cpu_plan->cplan);
  610. GGML_UNUSED(backend);
  611. }
  612. GGML_CALL static enum ggml_status ggml_backend_cpu_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  613. struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *)backend->context;
  614. struct ggml_cplan cplan = ggml_graph_plan(cgraph, cpu_ctx->n_threads, cpu_ctx->threadpool);
  615. if (cpu_ctx->work_size < cplan.work_size) {
  616. free(cpu_ctx->work_data);
  617. cpu_ctx->work_data = malloc(cplan.work_size);
  618. if (cpu_ctx->work_data == NULL) {
  619. cpu_ctx->work_size = 0;
  620. return GGML_STATUS_ALLOC_FAILED;
  621. }
  622. cpu_ctx->work_size = cplan.work_size;
  623. }
  624. cplan.work_data = cpu_ctx->work_data;
  625. cplan.abort_callback = cpu_ctx->abort_callback;
  626. cplan.abort_callback_data = cpu_ctx->abort_callback_data;
  627. return ggml_graph_compute(cgraph, &cplan);
  628. }
  629. GGML_CALL static bool ggml_backend_cpu_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  630. switch (op->op) {
  631. case GGML_OP_CPY:
  632. return
  633. op->type != GGML_TYPE_IQ2_XXS &&
  634. op->type != GGML_TYPE_IQ2_XS &&
  635. op->type != GGML_TYPE_IQ1_S &&
  636. op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
  637. case GGML_OP_MUL_MAT:
  638. return op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == ggml_internal_get_type_traits(op->src[0]->type).vec_dot_type;
  639. case GGML_OP_ROPE_BACK:
  640. return op->src[2] == NULL && (op->op_params[2] & 4) == 0;
  641. case GGML_OP_IM2COL_BACK:
  642. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  643. default:
  644. return true;
  645. }
  646. GGML_UNUSED(backend);
  647. }
  648. GGML_CALL static bool ggml_backend_cpu_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
  649. return ggml_backend_buft_is_host(buft);
  650. GGML_UNUSED(backend);
  651. }
  652. static struct ggml_backend_i cpu_backend_i = {
  653. /* .get_name = */ ggml_backend_cpu_name,
  654. /* .free = */ ggml_backend_cpu_free,
  655. /* .get_default_buffer_type = */ ggml_backend_cpu_get_default_buffer_type,
  656. /* .set_tensor_async = */ NULL,
  657. /* .get_tensor_async = */ NULL,
  658. /* .cpy_tensor_async = */ NULL,
  659. /* .synchronize = */ NULL,
  660. /* .graph_plan_create = */ ggml_backend_cpu_graph_plan_create,
  661. /* .graph_plan_free = */ ggml_backend_cpu_graph_plan_free,
  662. /* .graph_plan_update = */ NULL,
  663. /* .graph_plan_compute = */ ggml_backend_cpu_graph_plan_compute,
  664. /* .graph_compute = */ ggml_backend_cpu_graph_compute,
  665. /* .supports_op = */ ggml_backend_cpu_supports_op,
  666. /* .supports_buft = */ ggml_backend_cpu_supports_buft,
  667. /* .offload_op = */ NULL,
  668. /* .event_new = */ NULL,
  669. /* .event_free = */ NULL,
  670. /* .event_record = */ NULL,
  671. /* .event_wait = */ NULL,
  672. /* .event_synchronize = */ NULL,
  673. };
  674. static ggml_guid_t ggml_backend_cpu_guid(void) {
  675. static ggml_guid guid = { 0xaa, 0x67, 0xc7, 0x43, 0x96, 0xe6, 0xa3, 0x8a, 0xe3, 0xaf, 0xea, 0x92, 0x36, 0xbc, 0xfc, 0x89 };
  676. return &guid;
  677. }
  678. ggml_backend_t ggml_backend_cpu_init(void) {
  679. struct ggml_backend_cpu_context * ctx = malloc(sizeof(struct ggml_backend_cpu_context));
  680. if (ctx == NULL) {
  681. return NULL;
  682. }
  683. ctx->n_threads = GGML_DEFAULT_N_THREADS;
  684. ctx->threadpool = NULL;
  685. ctx->work_data = NULL;
  686. ctx->work_size = 0;
  687. ctx->abort_callback = NULL;
  688. ctx->abort_callback_data = NULL;
  689. ggml_backend_t cpu_backend = malloc(sizeof(struct ggml_backend));
  690. if (cpu_backend == NULL) {
  691. free(ctx);
  692. return NULL;
  693. }
  694. *cpu_backend = (struct ggml_backend) {
  695. /* .guid = */ ggml_backend_cpu_guid(),
  696. /* .interface = */ cpu_backend_i,
  697. /* .context = */ ctx
  698. };
  699. return cpu_backend;
  700. }
  701. GGML_CALL bool ggml_backend_is_cpu(ggml_backend_t backend) {
  702. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_cpu_guid());
  703. }
  704. void ggml_backend_cpu_set_n_threads(ggml_backend_t backend_cpu, int n_threads) {
  705. GGML_ASSERT(ggml_backend_is_cpu(backend_cpu));
  706. struct ggml_backend_cpu_context * ctx = (struct ggml_backend_cpu_context *)backend_cpu->context;
  707. ctx->n_threads = n_threads;
  708. }
  709. void ggml_backend_cpu_set_threadpool(ggml_backend_t backend_cpu, ggml_threadpool_t threadpool) {
  710. GGML_ASSERT(ggml_backend_is_cpu(backend_cpu));
  711. struct ggml_backend_cpu_context * ctx = (struct ggml_backend_cpu_context *)backend_cpu->context;
  712. if (ctx->threadpool && ctx->threadpool != threadpool) {
  713. // already had a different threadpool, pause/suspend it before switching
  714. ggml_threadpool_pause(ctx->threadpool);
  715. }
  716. ctx->threadpool = threadpool;
  717. }
  718. void ggml_backend_cpu_set_abort_callback(ggml_backend_t backend_cpu, ggml_abort_callback abort_callback, void * abort_callback_data) {
  719. GGML_ASSERT(ggml_backend_is_cpu(backend_cpu));
  720. struct ggml_backend_cpu_context * ctx = (struct ggml_backend_cpu_context *)backend_cpu->context;
  721. ctx->abort_callback = abort_callback;
  722. ctx->abort_callback_data = abort_callback_data;
  723. }
  724. GGML_CALL ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size) {
  725. GGML_ASSERT((uintptr_t)ptr % TENSOR_ALIGNMENT == 0 && "buffer pointer must be aligned");
  726. return ggml_backend_buffer_init(ggml_backend_cpu_buffer_type(), cpu_backend_buffer_i_from_ptr, ptr, size);
  727. }
  728. GGML_CALL static ggml_backend_t ggml_backend_reg_cpu_init(const char * params, void * user_data) {
  729. return ggml_backend_cpu_init();
  730. GGML_UNUSED(params);
  731. GGML_UNUSED(user_data);
  732. }
  733. // multi-buffer buffer
  734. struct ggml_backend_multi_buffer_context {
  735. ggml_backend_buffer_t * buffers;
  736. size_t n_buffers;
  737. };
  738. typedef struct ggml_backend_multi_buffer_context * ggml_backend_multi_buffer_context_t;
  739. GGML_CALL static const char * ggml_backend_multi_buffer_get_name(ggml_backend_buffer_t buffer) {
  740. ggml_backend_multi_buffer_context_t ctx = (ggml_backend_multi_buffer_context_t) buffer->context;
  741. return ctx->buffers[0]->iface.get_name(ctx->buffers[0]);
  742. }
  743. GGML_CALL static void ggml_backend_multi_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  744. ggml_backend_multi_buffer_context_t ctx = (ggml_backend_multi_buffer_context_t) buffer->context;
  745. for (size_t i = 0; i < ctx->n_buffers; i++) {
  746. ggml_backend_buffer_free(ctx->buffers[i]);
  747. }
  748. free(ctx->buffers);
  749. free(ctx);
  750. }
  751. GGML_CALL static void ggml_backend_multi_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  752. ggml_backend_multi_buffer_context_t ctx = (ggml_backend_multi_buffer_context_t) buffer->context;
  753. for (size_t i = 0; i < ctx->n_buffers; i++) {
  754. ggml_backend_buffer_clear(ctx->buffers[i], value);
  755. }
  756. }
  757. static struct ggml_backend_buffer_i ggml_backend_multi_buffer_context_interface(void) {
  758. static struct ggml_backend_buffer_i multi_backend_buffer_i = {
  759. /* .get_name = */ ggml_backend_multi_buffer_get_name,
  760. /* .free_buffer = */ ggml_backend_multi_buffer_free_buffer,
  761. /* .get_base = */ NULL,
  762. /* .init_tensor = */ NULL,
  763. /* .set_tensor = */ NULL,
  764. /* .get_tensor = */ NULL,
  765. /* .cpy_tensor = */ NULL,
  766. /* .clear = */ ggml_backend_multi_buffer_clear,
  767. /* .reset = */ NULL,
  768. };
  769. return multi_backend_buffer_i;
  770. }
  771. GGML_CALL ggml_backend_buffer_t ggml_backend_multi_buffer_alloc_buffer(ggml_backend_buffer_t * buffers, size_t n_buffers) {
  772. ggml_backend_multi_buffer_context_t ctx = (ggml_backend_multi_buffer_context_t) malloc(sizeof(struct ggml_backend_multi_buffer_context));
  773. ctx->n_buffers = n_buffers;
  774. ctx->buffers = (ggml_backend_buffer_t *) malloc(n_buffers * sizeof(ggml_backend_buffer_t));
  775. GGML_ASSERT(ctx->buffers != NULL);
  776. size_t total_size = 0;
  777. for (size_t i = 0; i < n_buffers; i++) {
  778. ctx->buffers[i] = buffers[i];
  779. total_size += ggml_backend_buffer_get_size(buffers[i]);
  780. }
  781. return ggml_backend_buffer_init(buffers[0]->buft, ggml_backend_multi_buffer_context_interface(), ctx, total_size);
  782. }
  783. GGML_CALL bool ggml_backend_buffer_is_multi_buffer(ggml_backend_buffer_t buffer) {
  784. return buffer->iface.get_name == ggml_backend_multi_buffer_get_name;
  785. }
  786. GGML_CALL void ggml_backend_multi_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) {
  787. GGML_ASSERT(ggml_backend_buffer_is_multi_buffer(buffer));
  788. ggml_backend_multi_buffer_context_t ctx = (ggml_backend_multi_buffer_context_t) buffer->context;
  789. for (size_t i = 0; i < ctx->n_buffers; i++) {
  790. ggml_backend_buffer_set_usage(ctx->buffers[i], usage);
  791. }
  792. }
  793. // creates a copy of the tensor with the same memory layout
  794. static struct ggml_tensor * ggml_dup_tensor_layout(struct ggml_context * ctx, const struct ggml_tensor * tensor) {
  795. struct ggml_tensor * dup = ggml_dup_tensor(ctx, tensor);
  796. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  797. dup->nb[i] = tensor->nb[i];
  798. }
  799. return dup;
  800. }
  801. static bool ggml_is_view_op(enum ggml_op op) {
  802. return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE;
  803. }
  804. // scheduler
  805. #ifndef GGML_SCHED_MAX_BACKENDS
  806. #define GGML_SCHED_MAX_BACKENDS 16
  807. #endif
  808. #ifndef GGML_SCHED_MAX_SPLIT_INPUTS
  809. #define GGML_SCHED_MAX_SPLIT_INPUTS GGML_MAX_SRC
  810. #endif
  811. #ifndef GGML_SCHED_MAX_COPIES
  812. #define GGML_SCHED_MAX_COPIES 4
  813. #endif
  814. struct ggml_backend_sched_split {
  815. int backend_id;
  816. int i_start;
  817. int i_end;
  818. struct ggml_tensor * inputs[GGML_SCHED_MAX_SPLIT_INPUTS];
  819. int n_inputs;
  820. // graph view of this split
  821. struct ggml_cgraph graph;
  822. };
  823. struct ggml_backend_sched {
  824. bool is_reset; // true if the scheduler has been reset since the last graph split
  825. bool is_alloc;
  826. int n_backends;
  827. ggml_backend_t backends[GGML_SCHED_MAX_BACKENDS];
  828. ggml_backend_buffer_type_t bufts[GGML_SCHED_MAX_BACKENDS];
  829. ggml_gallocr_t galloc;
  830. // hash map of the nodes in the graph
  831. struct ggml_hash_set hash_set;
  832. int * hv_tensor_backend_ids; // [hash_set.size]
  833. struct ggml_tensor ** hv_tensor_copies; // [hash_set.size][n_backends][n_copies]
  834. int * node_backend_ids; // [graph_size]
  835. int * leaf_backend_ids; // [graph_size]
  836. int * prev_node_backend_ids; // [graph_size]
  837. int * prev_leaf_backend_ids; // [graph_size]
  838. // copy of the graph with modified inputs
  839. struct ggml_cgraph graph;
  840. // graph splits
  841. struct ggml_backend_sched_split * splits;
  842. int n_splits;
  843. int splits_capacity;
  844. // pipeline parallelism support
  845. int n_copies;
  846. int cur_copy;
  847. ggml_backend_event_t events[GGML_SCHED_MAX_BACKENDS][GGML_SCHED_MAX_COPIES];
  848. struct ggml_tensor * graph_inputs[GGML_SCHED_MAX_SPLIT_INPUTS];
  849. int n_graph_inputs;
  850. struct ggml_context * ctx;
  851. ggml_backend_sched_eval_callback callback_eval;
  852. void * callback_eval_user_data;
  853. char * context_buffer;
  854. size_t context_buffer_size;
  855. bool debug;
  856. };
  857. #define hash_id(tensor) ggml_hash_find_or_insert(&sched->hash_set, tensor)
  858. #define tensor_backend_id(tensor) sched->hv_tensor_backend_ids[hash_id(tensor)]
  859. #define tensor_id_copy(id, backend_id, copy_id) sched->hv_tensor_copies[(id) * sched->n_backends * sched->n_copies + (backend_id) * sched->n_copies + (copy_id)]
  860. #define tensor_copy(tensor, backend_id, copy_id) tensor_id_copy(hash_id(tensor), backend_id, copy_id)
  861. // returns the priority of the backend, lower id is higher priority
  862. static int ggml_backend_sched_backend_id(ggml_backend_sched_t sched, ggml_backend_t backend) {
  863. for (int i = 0; i < sched->n_backends; i++) {
  864. if (sched->backends[i] == backend) {
  865. return i;
  866. }
  867. }
  868. return -1;
  869. }
  870. static int ggml_backend_sched_backend_from_buffer(ggml_backend_sched_t sched, const struct ggml_tensor * tensor, const struct ggml_tensor * op) {
  871. ggml_backend_buffer_t buffer = tensor->buffer;
  872. if (buffer == NULL) {
  873. return -1;
  874. }
  875. // find highest prio backend that supports the buffer type and the op
  876. for (int i = 0; i < sched->n_backends; i++) {
  877. if (ggml_backend_supports_buft(sched->backends[i], buffer->buft) &&
  878. ggml_backend_supports_op(sched->backends[i], op)) {
  879. return i;
  880. }
  881. }
  882. #ifndef NDEBUG
  883. fprintf(stderr, "%s: warning: no backend supports op %s with a weight with buffer type %s used in tensor %s, the weight will need to be copied\n",
  884. __func__, ggml_op_desc(tensor), ggml_backend_buffer_name(buffer), tensor->name);
  885. #endif
  886. return -1;
  887. }
  888. #if 0
  889. #define GGML_SCHED_MAX_SPLITS_DEBUG 4096
  890. static char causes[GGML_DEFAULT_GRAPH_SIZE*16 + GGML_SCHED_MAX_SPLITS_DEBUG*GGML_SCHED_MAX_SPLIT_INPUTS][128]; // debug only
  891. #define SET_CAUSE(node, ...) sprintf(causes[hash_id(node)], __VA_ARGS__)
  892. #define GET_CAUSE(node) causes[hash_id(node)]
  893. #else
  894. #define SET_CAUSE(node, ...)
  895. #define GET_CAUSE(node) ""
  896. #endif
  897. // returns the backend that should be used for the node based on the current locations
  898. static int ggml_backend_sched_backend_id_from_cur(ggml_backend_sched_t sched, struct ggml_tensor * tensor) {
  899. // TODO: use supports_op to check if the backend supports the op
  900. // assign pre-allocated nodes to their backend
  901. int cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor, tensor);
  902. if (cur_backend_id != -1) {
  903. SET_CAUSE(tensor, "1.dst");
  904. return cur_backend_id;
  905. }
  906. // view_src
  907. if (tensor->view_src != NULL) {
  908. cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor->view_src, tensor);
  909. if (cur_backend_id != -1) {
  910. SET_CAUSE(tensor, "1.vsrc");
  911. return cur_backend_id;
  912. }
  913. }
  914. if (tensor->buffer || (tensor->view_src && tensor->view_src->buffer)) {
  915. // since the tensor is pre-allocated, it cannot be moved to another backend
  916. GGML_ABORT("pre-allocated tensor in a backend that cannot run the operation");
  917. }
  918. // graph input
  919. if (tensor->flags & GGML_TENSOR_FLAG_INPUT) {
  920. cur_backend_id = sched->n_backends - 1; // last backend (assumed CPU)
  921. SET_CAUSE(tensor, "1.inp");
  922. return cur_backend_id;
  923. }
  924. // operations with weights are preferably run on the same backend as the weights
  925. for (int i = 0; i < GGML_MAX_SRC; i++) {
  926. const struct ggml_tensor * src = tensor->src[i];
  927. if (src == NULL) {
  928. continue;
  929. }
  930. if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
  931. int src_backend_id = ggml_backend_sched_backend_from_buffer(sched, src, tensor);
  932. // check if a backend with higher prio wants to offload the op
  933. if (src_backend_id == sched->n_backends - 1) {
  934. for (int b = 0; b < src_backend_id; b++) {
  935. if (ggml_backend_supports_op(sched->backends[b], tensor) && ggml_backend_offload_op(sched->backends[b], tensor)) {
  936. SET_CAUSE(tensor, "1.off");
  937. return b;
  938. }
  939. }
  940. }
  941. SET_CAUSE(tensor, "1.wgt%d", i);
  942. return src_backend_id;
  943. }
  944. }
  945. return -1;
  946. }
  947. static char * fmt_size(size_t size) {
  948. static char buffer[128];
  949. if (size >= 1024*1024) {
  950. snprintf(buffer, sizeof(buffer), "%zuM", size/1024/1024);
  951. } else {
  952. snprintf(buffer, sizeof(buffer), "%zuK", size/1024);
  953. }
  954. return buffer;
  955. }
  956. static void ggml_backend_sched_print_assignments(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  957. int cur_split = 0;
  958. for (int i = 0; i < graph->n_nodes; i++) {
  959. if (cur_split < sched->n_splits && i == sched->splits[cur_split].i_start) {
  960. ggml_backend_t split_backend = sched->backends[sched->splits[cur_split].backend_id];
  961. fprintf(stderr, "\n## SPLIT #%d: %s # %d inputs: ", cur_split, ggml_backend_name(split_backend),
  962. sched->splits[cur_split].n_inputs);
  963. for (int j = 0; j < sched->splits[cur_split].n_inputs; j++) {
  964. fprintf(stderr, "[%s (%5.5s)] ", sched->splits[cur_split].inputs[j]->name,
  965. fmt_size(ggml_nbytes(sched->splits[cur_split].inputs[j])));
  966. }
  967. fprintf(stderr, "\n");
  968. cur_split++;
  969. }
  970. struct ggml_tensor * node = graph->nodes[i];
  971. if (ggml_is_view_op(node->op)) {
  972. continue;
  973. }
  974. ggml_backend_t tensor_backend = ggml_backend_sched_get_tensor_backend(sched, node);
  975. fprintf(stderr, "node #%3d (%10.10s): %20.20s (%5.5s) [%5.5s %8.8s]:", i, ggml_op_name(node->op), node->name,
  976. fmt_size(ggml_nbytes(node)), tensor_backend ? ggml_backend_name(tensor_backend) : "NULL", GET_CAUSE(node));
  977. for (int j = 0; j < GGML_MAX_SRC; j++) {
  978. struct ggml_tensor * src = node->src[j];
  979. if (src == NULL) {
  980. continue;
  981. }
  982. ggml_backend_t src_backend = ggml_backend_sched_get_tensor_backend(sched, src);
  983. fprintf(stderr, " %20.20s (%5.5s) [%5.5s %8.8s]", src->name,
  984. fmt_size(ggml_nbytes(src)), src_backend ? ggml_backend_name(src_backend) : "NULL", GET_CAUSE(src));
  985. }
  986. fprintf(stderr, "\n");
  987. }
  988. }
  989. static bool ggml_backend_sched_buffer_supported(ggml_backend_sched_t sched, struct ggml_tensor * t, int backend_id) {
  990. ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer;
  991. ggml_backend_buffer_type_t buft = NULL;
  992. if (buf) {
  993. // the tensor is already allocated
  994. buft = buf->buft;
  995. } else {
  996. // see if the tensor already has a backend assigned, and use the buffer type of that backend
  997. int tensor_backend_id = tensor_backend_id(t);
  998. if (tensor_backend_id == -1 && t->view_src) {
  999. tensor_backend_id = tensor_backend_id(t->view_src);
  1000. }
  1001. if (tensor_backend_id != -1) {
  1002. buft = sched->bufts[tensor_backend_id];
  1003. }
  1004. }
  1005. return buft != NULL && ggml_backend_supports_buft(sched->backends[backend_id], buft);
  1006. }
  1007. static void ggml_backend_sched_set_if_supported(ggml_backend_sched_t sched, struct ggml_tensor * node, int cur_backend_id, int * node_backend_id) {
  1008. if (ggml_backend_supports_op(sched->backends[cur_backend_id], node)) {
  1009. *node_backend_id = cur_backend_id;
  1010. SET_CAUSE(node, "2.sup");
  1011. }
  1012. }
  1013. // assigns backends to ops and splits the graph into subgraphs that can be computed on the same backend
  1014. static void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  1015. // reset splits
  1016. sched->n_splits = 0;
  1017. sched->n_graph_inputs = 0;
  1018. sched->is_reset = false;
  1019. struct ggml_init_params params = {
  1020. /* .mem_size = */ sched->context_buffer_size,
  1021. /* .mem_buffer = */ sched->context_buffer,
  1022. /* .no_alloc = */ true
  1023. };
  1024. ggml_free(sched->ctx);
  1025. sched->ctx = ggml_init(params);
  1026. if (sched->ctx == NULL) {
  1027. GGML_ABORT("%s: failed to initialize context\n", __func__);
  1028. }
  1029. // pass 1: assign backends to ops with pre-allocated inputs
  1030. for (int i = 0; i < graph->n_leafs; i++) {
  1031. struct ggml_tensor * leaf = graph->leafs[i];
  1032. int * leaf_backend_id = &tensor_backend_id(leaf);
  1033. // do not overwrite user assignments
  1034. if (*leaf_backend_id == -1) {
  1035. *leaf_backend_id = ggml_backend_sched_backend_id_from_cur(sched, leaf);
  1036. }
  1037. }
  1038. for (int i = 0; i < graph->n_nodes; i++) {
  1039. struct ggml_tensor * node = graph->nodes[i];
  1040. int * node_backend_id = &tensor_backend_id(node);
  1041. // do not overwrite user assignments
  1042. if (*node_backend_id == -1) {
  1043. *node_backend_id = ggml_backend_sched_backend_id_from_cur(sched, node);
  1044. #if 0
  1045. // src
  1046. if (node->op == GGML_OP_NONE) {
  1047. continue;
  1048. }
  1049. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1050. struct ggml_tensor * src = node->src[j];
  1051. if (src == NULL) {
  1052. continue;
  1053. }
  1054. int * src_backend_id = &tensor_backend_id(src);
  1055. if (*src_backend_id == -1) {
  1056. *src_backend_id = ggml_backend_sched_backend_id_from_cur(sched, src);
  1057. }
  1058. }
  1059. #endif
  1060. }
  1061. }
  1062. // pass 2: expand current backend assignments
  1063. // assign the same backend to adjacent nodes
  1064. // expand gpu backends (i.e. non last prio) up and down, ignoring cpu (the lowest priority backend)
  1065. // thus, cpu will never be used unless weights are on cpu, or there are no gpu ops between cpu ops
  1066. // ops unsupported by the backend being expanded will be left unassigned so that they can be assigned later when the locations of its inputs are known
  1067. // expand gpu down
  1068. {
  1069. int cur_backend_id = -1;
  1070. for (int i = 0; i < graph->n_nodes; i++) {
  1071. struct ggml_tensor * node = graph->nodes[i];
  1072. if (ggml_is_view_op(node->op)) {
  1073. continue;
  1074. }
  1075. int * node_backend_id = &tensor_backend_id(node);
  1076. if (*node_backend_id != -1) {
  1077. if (*node_backend_id == sched->n_backends - 1) {
  1078. // skip cpu (lowest prio backend)
  1079. cur_backend_id = -1;
  1080. } else {
  1081. cur_backend_id = *node_backend_id;
  1082. }
  1083. } else if (cur_backend_id != -1) {
  1084. ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
  1085. }
  1086. }
  1087. }
  1088. // expand gpu up
  1089. {
  1090. int cur_backend_id = -1;
  1091. for (int i = graph->n_nodes - 1; i >= 0; i--) {
  1092. struct ggml_tensor * node = graph->nodes[i];
  1093. if (ggml_is_view_op(node->op)) {
  1094. continue;
  1095. }
  1096. int * node_backend_id = &tensor_backend_id(node);
  1097. if (*node_backend_id != -1) {
  1098. if (*node_backend_id == sched->n_backends - 1) {
  1099. // skip cpu (lowest prio backend)
  1100. cur_backend_id = -1;
  1101. } else {
  1102. cur_backend_id = *node_backend_id;
  1103. }
  1104. } else if (cur_backend_id != -1) {
  1105. ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
  1106. }
  1107. }
  1108. }
  1109. // expand rest down
  1110. {
  1111. int cur_backend_id = -1;
  1112. for (int i = 0; i < graph->n_nodes; i++) {
  1113. struct ggml_tensor * node = graph->nodes[i];
  1114. if (ggml_is_view_op(node->op)) {
  1115. continue;
  1116. }
  1117. int * node_backend_id = &tensor_backend_id(node);
  1118. if (*node_backend_id != -1) {
  1119. cur_backend_id = *node_backend_id;
  1120. } else if (cur_backend_id != -1) {
  1121. ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
  1122. }
  1123. }
  1124. }
  1125. // expand rest up
  1126. {
  1127. int cur_backend_id = -1;
  1128. for (int i = graph->n_nodes - 1; i >= 0; i--) {
  1129. struct ggml_tensor * node = graph->nodes[i];
  1130. if (ggml_is_view_op(node->op)) {
  1131. continue;
  1132. }
  1133. int * node_backend_id = &tensor_backend_id(node);
  1134. if (*node_backend_id != -1) {
  1135. cur_backend_id = *node_backend_id;
  1136. } else if (cur_backend_id != -1) {
  1137. ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
  1138. }
  1139. }
  1140. }
  1141. // pass 3: upgrade nodes to higher prio backends with compatible buffer types
  1142. // if the tensor is already in the same buffer type (*) as another higher priority backend, we should move it there
  1143. // however, we also need to verify that the sources are in compatible buffer types
  1144. // (*) the actual requirement is more relaxed, the buffer type of the backend should be supported by all the users of this tensor further down the graph
  1145. // however, this is slow to verify, so we have a more strict requirement that the buffer type is the same
  1146. // this is not uncommon since multiple backends can use host memory, with the same buffer type (eg. BLAS and CPU)
  1147. // additionally, set remaining unassigned nodes to the backend with the most supported inputs
  1148. // only nodes that could not be assigned during expansion due to the backend not supporting the op should be unassigned at this point
  1149. for (int i = 0; i < graph->n_nodes; i++) {
  1150. struct ggml_tensor * node = graph->nodes[i];
  1151. if (ggml_is_view_op(node->op)) {
  1152. continue;
  1153. }
  1154. int * node_backend_id = &tensor_backend_id(node);
  1155. if (*node_backend_id == -1) {
  1156. // unassigned node: find the backend with the most supported inputs
  1157. int n_supported_best = -1;
  1158. for (int b = 0; b < sched->n_backends; b++) {
  1159. if (ggml_backend_supports_op(sched->backends[b], node)) {
  1160. int n_supported = 0;
  1161. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1162. struct ggml_tensor * src = node->src[j];
  1163. if (src == NULL) {
  1164. continue;
  1165. }
  1166. if ((tensor_backend_id(src) != -1 || tensor_backend_id(src->view_src) != -1) && ggml_backend_sched_buffer_supported(sched, src, b)) {
  1167. n_supported++;
  1168. }
  1169. }
  1170. if (n_supported > n_supported_best) {
  1171. n_supported_best = n_supported;
  1172. *node_backend_id = b;
  1173. SET_CAUSE(node, "3.best");
  1174. }
  1175. }
  1176. }
  1177. } else {
  1178. // assigned node: upgrade to higher prio backend if possible
  1179. for (int b = 0; b < *node_backend_id; b++) {
  1180. if (sched->bufts[b] == sched->bufts[*node_backend_id] && ggml_backend_supports_op(sched->backends[b], node)) {
  1181. bool supported = true;
  1182. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1183. struct ggml_tensor * src = node->src[j];
  1184. if (src == NULL) {
  1185. continue;
  1186. }
  1187. if (!ggml_backend_sched_buffer_supported(sched, src, b)) {
  1188. supported = false;
  1189. break;
  1190. }
  1191. }
  1192. if (supported) {
  1193. *node_backend_id = b;
  1194. SET_CAUSE(node, "3.upg");
  1195. break;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. // pass 4: assign backends to remaining src from dst and view_src
  1202. for (int i = 0; i < graph->n_nodes; i++) {
  1203. struct ggml_tensor * node = graph->nodes[i];
  1204. int * cur_backend_id = &tensor_backend_id(node);
  1205. if (node->view_src != NULL && *cur_backend_id == -1) {
  1206. *cur_backend_id = tensor_backend_id(node->view_src);
  1207. SET_CAUSE(node, "4.vsrc");
  1208. }
  1209. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1210. struct ggml_tensor * src = node->src[j];
  1211. if (src == NULL) {
  1212. continue;
  1213. }
  1214. int * src_backend_id = &tensor_backend_id(src);
  1215. if (*src_backend_id == -1) {
  1216. if (src->view_src != NULL) {
  1217. // views are always on the same backend as the source
  1218. *src_backend_id = tensor_backend_id(src->view_src);
  1219. SET_CAUSE(src, "4.vsrc");
  1220. } else {
  1221. *src_backend_id = *cur_backend_id;
  1222. SET_CAUSE(src, "4.cur");
  1223. }
  1224. }
  1225. }
  1226. }
  1227. // pass 5: split graph, find tensors that need to be copied
  1228. {
  1229. int i_split = 0;
  1230. struct ggml_backend_sched_split * split = &sched->splits[0];
  1231. // find the backend of the first split, skipping view ops
  1232. int i = 0;
  1233. for (; i < graph->n_nodes; i++) {
  1234. struct ggml_tensor * node = graph->nodes[i];
  1235. if (!ggml_is_view_op(node->op)) {
  1236. split->backend_id = tensor_backend_id(node);
  1237. break;
  1238. }
  1239. }
  1240. split->i_start = 0;
  1241. split->n_inputs = 0;
  1242. int cur_backend_id = split->backend_id;
  1243. for (; i < graph->n_nodes; i++) {
  1244. struct ggml_tensor * node = graph->nodes[i];
  1245. if (ggml_is_view_op(node->op)) {
  1246. continue;
  1247. }
  1248. const int node_backend_id = tensor_backend_id(node);
  1249. assert(node_backend_id != -1); // all nodes should be assigned by now
  1250. // check if we should start a new split based on the sources of the current node
  1251. bool need_new_split = false;
  1252. if (node_backend_id == cur_backend_id && split->n_inputs > 0) {
  1253. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1254. struct ggml_tensor * src = node->src[j];
  1255. if (src == NULL) {
  1256. continue;
  1257. }
  1258. // check if a weight is on a different backend
  1259. // by starting a new split, the memory of the previously offloaded weights can be reused
  1260. if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
  1261. int src_backend_id = tensor_backend_id(src);
  1262. if (src_backend_id != cur_backend_id) {
  1263. need_new_split = true;
  1264. break;
  1265. }
  1266. }
  1267. // check if the split has too many inputs
  1268. // FIXME: count the number of inputs instead of only checking when full
  1269. if (split->n_inputs == GGML_SCHED_MAX_SPLIT_INPUTS) {
  1270. const size_t id = hash_id(src);
  1271. int src_backend_id = sched->hv_tensor_backend_ids[id];
  1272. bool supported = ggml_backend_sched_buffer_supported(sched, src, cur_backend_id);
  1273. if (src_backend_id != cur_backend_id && tensor_id_copy(id, cur_backend_id, 0) == NULL && !supported) {
  1274. //printf("starting new split because of too many inputs: node %s, input %s\n", node->name, src->name);
  1275. need_new_split = true;
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. if (node_backend_id != cur_backend_id || need_new_split) {
  1282. split->i_end = i;
  1283. i_split++;
  1284. if (i_split >= sched->splits_capacity) {
  1285. sched->splits_capacity *= 2;
  1286. sched->splits = realloc(sched->splits, sched->splits_capacity * sizeof(struct ggml_backend_sched_split));
  1287. GGML_ASSERT(sched->splits != NULL);
  1288. }
  1289. split = &sched->splits[i_split];
  1290. split->backend_id = node_backend_id;
  1291. split->i_start = i;
  1292. split->n_inputs = 0;
  1293. cur_backend_id = node_backend_id;
  1294. }
  1295. // find inputs that are not on the same backend
  1296. for (int j = 0; j < GGML_MAX_SRC; j++) {
  1297. struct ggml_tensor * src = node->src[j];
  1298. if (src == NULL) {
  1299. continue;
  1300. }
  1301. size_t src_id = hash_id(src);
  1302. const int src_backend_id = sched->hv_tensor_backend_ids[src_id];
  1303. assert(src_backend_id != -1); // all inputs should be assigned by now
  1304. if (src->flags & GGML_TENSOR_FLAG_INPUT && sched->n_copies > 1) {
  1305. if (tensor_id_copy(src_id, src_backend_id, 0) == NULL) {
  1306. ggml_backend_t backend = sched->backends[src_backend_id];
  1307. for (int c = 0; c < sched->n_copies; c++) {
  1308. struct ggml_tensor * tensor_copy;
  1309. if (c == sched->cur_copy) {
  1310. tensor_copy = src; // use the original tensor as the current copy
  1311. } else {
  1312. tensor_copy = ggml_dup_tensor_layout(sched->ctx, src);
  1313. ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), src->name, c);
  1314. }
  1315. if (sched->n_copies > 1) {
  1316. ggml_set_input(tensor_copy);
  1317. ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor
  1318. }
  1319. tensor_id_copy(src_id, src_backend_id, c) = tensor_copy;
  1320. SET_CAUSE(tensor_copy, "4.cpy");
  1321. }
  1322. int n_graph_inputs = sched->n_graph_inputs++;
  1323. GGML_ASSERT(n_graph_inputs < GGML_SCHED_MAX_SPLIT_INPUTS);
  1324. sched->graph_inputs[n_graph_inputs] = src;
  1325. }
  1326. }
  1327. if (src_backend_id != cur_backend_id && !ggml_backend_sched_buffer_supported(sched, src, cur_backend_id)) {
  1328. // create a copy of the input in the split's backend
  1329. if (tensor_id_copy(src_id, cur_backend_id, 0) == NULL) {
  1330. ggml_backend_t backend = sched->backends[cur_backend_id];
  1331. for (int c = 0; c < sched->n_copies; c++) {
  1332. struct ggml_tensor * tensor_copy = ggml_dup_tensor_layout(sched->ctx, src);
  1333. ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), src->name, c);
  1334. if (sched->n_copies > 1) {
  1335. ggml_set_input(tensor_copy);
  1336. ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor
  1337. }
  1338. tensor_id_copy(src_id, cur_backend_id, c) = tensor_copy;
  1339. SET_CAUSE(tensor_copy, "4.cpy");
  1340. }
  1341. int n_inputs = split->n_inputs++;
  1342. GGML_ASSERT(n_inputs < GGML_SCHED_MAX_SPLIT_INPUTS);
  1343. split->inputs[n_inputs] = src;
  1344. }
  1345. node->src[j] = tensor_id_copy(src_id, cur_backend_id, sched->cur_copy);
  1346. }
  1347. }
  1348. }
  1349. split->i_end = graph->n_nodes;
  1350. sched->n_splits = i_split + 1;
  1351. }
  1352. if (sched->debug) {
  1353. ggml_backend_sched_print_assignments(sched, graph);
  1354. }
  1355. // swap node_backend_ids and leaf _backend_ids with prevs
  1356. {
  1357. int * tmp = sched->node_backend_ids;
  1358. sched->node_backend_ids = sched->prev_node_backend_ids;
  1359. sched->prev_node_backend_ids = tmp;
  1360. tmp = sched->leaf_backend_ids;
  1361. sched->leaf_backend_ids = sched->prev_leaf_backend_ids;
  1362. sched->prev_leaf_backend_ids = tmp;
  1363. }
  1364. int graph_size = MAX(graph->n_nodes, graph->n_leafs) + sched->n_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2*sched->n_copies;
  1365. if (sched->graph.size < graph_size) {
  1366. sched->graph.size = graph_size;
  1367. sched->graph.nodes = realloc(sched->graph.nodes, graph_size * sizeof(struct ggml_tensor *));
  1368. sched->graph.leafs = realloc(sched->graph.leafs, graph_size * sizeof(struct ggml_tensor *));
  1369. GGML_ASSERT(sched->graph.nodes != NULL);
  1370. GGML_ASSERT(sched->graph.leafs != NULL);
  1371. }
  1372. sched->graph.n_nodes = 0;
  1373. sched->graph.n_leafs = 0;
  1374. struct ggml_cgraph * graph_copy = &sched->graph;
  1375. for (int i = 0; i < sched->n_splits; i++) {
  1376. struct ggml_backend_sched_split * split = &sched->splits[i];
  1377. split->graph = ggml_graph_view(graph, split->i_start, split->i_end);
  1378. // add inputs to the graph copy so that they are allocated by ggml-alloc at the start of the split
  1379. for (int j = 0; j < split->n_inputs; j++) {
  1380. assert(graph_copy->size > (graph_copy->n_nodes + 1));
  1381. struct ggml_tensor * input = split->inputs[j];
  1382. const size_t input_id = hash_id(input);
  1383. struct ggml_tensor * input_cpy = tensor_id_copy(input_id, split->backend_id, sched->cur_copy);
  1384. // add a dependency to the input source so that it is not freed before the copy is done
  1385. struct ggml_tensor * input_dep = ggml_view_tensor(sched->ctx, input);
  1386. input_dep->src[0] = input;
  1387. sched->node_backend_ids[graph_copy->n_nodes] = sched->hv_tensor_backend_ids[input_id];
  1388. graph_copy->nodes[graph_copy->n_nodes++] = input_dep;
  1389. // add a dependency to the input copy so that it is allocated at the start of the split
  1390. sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
  1391. graph_copy->nodes[graph_copy->n_nodes++] = input_cpy;
  1392. }
  1393. for (int j = split->i_start; j < split->i_end; j++) {
  1394. assert(graph_copy->size > graph_copy->n_nodes);
  1395. sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]);
  1396. graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
  1397. }
  1398. }
  1399. if (sched->n_copies > 1) {
  1400. // add input copies as leafs so that they are allocated first
  1401. for (int i = 0; i < sched->n_graph_inputs; i++) {
  1402. struct ggml_tensor * input = sched->graph_inputs[i];
  1403. size_t id = hash_id(input);
  1404. int backend_id = tensor_backend_id(input);
  1405. for (int c = 0; c < sched->n_copies; c++) {
  1406. struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c);
  1407. sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id;
  1408. assert(graph_copy->size > graph_copy->n_leafs);
  1409. graph_copy->leafs[graph_copy->n_leafs++] = input_cpy;
  1410. }
  1411. }
  1412. for (int i = 0; i < sched->n_splits; i++) {
  1413. struct ggml_backend_sched_split * split = &sched->splits[i];
  1414. int backend_id = split->backend_id;
  1415. for (int j = 0; j < split->n_inputs; j++) {
  1416. struct ggml_tensor * input = split->inputs[j];
  1417. size_t id = hash_id(input);
  1418. for (int c = 0; c < sched->n_copies; c++) {
  1419. struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c);
  1420. sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id;
  1421. assert(graph_copy->size > graph_copy->n_leafs);
  1422. graph_copy->leafs[graph_copy->n_leafs++] = input_cpy;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. // add leafs from the original graph
  1428. for (int i = 0; i < graph->n_leafs; i++) {
  1429. struct ggml_tensor * leaf = graph->leafs[i];
  1430. sched->leaf_backend_ids[graph_copy->n_leafs] = tensor_backend_id(leaf);
  1431. assert(graph_copy->size > graph_copy->n_leafs);
  1432. graph_copy->leafs[graph_copy->n_leafs++] = leaf;
  1433. }
  1434. }
  1435. static bool ggml_backend_sched_alloc_splits(ggml_backend_sched_t sched) {
  1436. bool backend_ids_changed = false;
  1437. for (int i = 0; i < sched->graph.n_nodes; i++) {
  1438. if (sched->node_backend_ids[i] != sched->prev_node_backend_ids[i] &&
  1439. sched->bufts[sched->node_backend_ids[i]] != sched->bufts[sched->prev_node_backend_ids[i]]) {
  1440. backend_ids_changed = true;
  1441. break;
  1442. }
  1443. }
  1444. if (!backend_ids_changed) {
  1445. for (int i = 0; i < sched->graph.n_leafs; i++) {
  1446. if (sched->leaf_backend_ids[i] != sched->prev_leaf_backend_ids[i] &&
  1447. sched->bufts[sched->leaf_backend_ids[i]] != sched->bufts[sched->prev_leaf_backend_ids[i]]) {
  1448. backend_ids_changed = true;
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. // allocate graph
  1454. if (backend_ids_changed || !ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) {
  1455. // the re-allocation may cause the split inputs to be moved to a different address
  1456. ggml_backend_sched_synchronize(sched);
  1457. #ifndef NDEBUG
  1458. fprintf(stderr, "%s: failed to allocate graph, reserving (backend_ids_changed = %d)\n", __func__, backend_ids_changed);
  1459. #endif
  1460. ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids);
  1461. if (!ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) {
  1462. fprintf(stderr, "%s: failed to allocate graph\n", __func__);
  1463. return false;
  1464. }
  1465. }
  1466. return true;
  1467. }
  1468. static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t sched) {
  1469. struct ggml_backend_sched_split * splits = sched->splits;
  1470. for (int i = 0; i < sched->n_splits; i++) {
  1471. struct ggml_backend_sched_split * split = &splits[i];
  1472. int split_backend_id = split->backend_id;
  1473. ggml_backend_t split_backend = sched->backends[split_backend_id];
  1474. // copy the input tensors to the split backend
  1475. for (int j = 0; j < split->n_inputs; j++) {
  1476. ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, split->inputs[j]);
  1477. struct ggml_tensor * input = split->inputs[j];
  1478. struct ggml_tensor * input_cpy = tensor_copy(input, split_backend_id, sched->cur_copy);
  1479. if (input->flags & GGML_TENSOR_FLAG_INPUT) {
  1480. // inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done
  1481. if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
  1482. ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]);
  1483. } else {
  1484. ggml_backend_synchronize(split_backend);
  1485. }
  1486. ggml_backend_tensor_copy(input, input_cpy);
  1487. } else {
  1488. // wait for the split backend to finish using the input before overwriting it
  1489. if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
  1490. ggml_backend_event_wait(split_backend, sched->events[split_backend_id][sched->cur_copy]);
  1491. } else {
  1492. ggml_backend_synchronize(split_backend);
  1493. }
  1494. // try async copy, but if not possible, we can still use a sync copy without synchronizing the dst backend, since we handle the synchronization here with multiple copies and events
  1495. // TODO: add public function to facilitate this, since applications do not have direct access to the backend interface
  1496. if (!split_backend->iface.cpy_tensor_async || !split_backend->iface.cpy_tensor_async(input_backend, split_backend, input, input_cpy)) {
  1497. ggml_backend_synchronize(input_backend);
  1498. if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
  1499. ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]);
  1500. } else {
  1501. ggml_backend_synchronize(split_backend);
  1502. }
  1503. ggml_backend_tensor_copy(input, input_cpy);
  1504. }
  1505. }
  1506. }
  1507. if (!sched->callback_eval) {
  1508. enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &split->graph);
  1509. if (ec != GGML_STATUS_SUCCESS) {
  1510. return ec;
  1511. }
  1512. } else {
  1513. // similar to ggml_backend_compare_graph_backend
  1514. for (int j0 = 0; j0 < split->graph.n_nodes; j0++) {
  1515. struct ggml_tensor * t = split->graph.nodes[j0];
  1516. // check if the user needs data from this node
  1517. bool need = sched->callback_eval(t, true, sched->callback_eval_user_data);
  1518. int j1 = j0;
  1519. // determine the range [j0, j1] of nodes that can be computed together
  1520. while (!need && j1 < split->graph.n_nodes - 1) {
  1521. t = split->graph.nodes[++j1];
  1522. need = sched->callback_eval(t, true, sched->callback_eval_user_data);
  1523. }
  1524. struct ggml_cgraph gv = ggml_graph_view(&split->graph, j0, j1 + 1);
  1525. enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &gv);
  1526. if (ec != GGML_STATUS_SUCCESS) {
  1527. return ec;
  1528. }
  1529. // TODO: pass backend to the callback, then the user can decide if they want to synchronize
  1530. ggml_backend_synchronize(split_backend);
  1531. if (need && !sched->callback_eval(t, false, sched->callback_eval_user_data)) {
  1532. break;
  1533. }
  1534. j0 = j1;
  1535. }
  1536. }
  1537. // record the event of this copy
  1538. if (split->n_inputs > 0) {
  1539. if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
  1540. ggml_backend_event_record(sched->events[split_backend_id][sched->cur_copy]);
  1541. }
  1542. }
  1543. }
  1544. sched->cur_copy = (sched->cur_copy + 1) % sched->n_copies;
  1545. return GGML_STATUS_SUCCESS;
  1546. }
  1547. ggml_backend_sched_t ggml_backend_sched_new(
  1548. ggml_backend_t * backends,
  1549. ggml_backend_buffer_type_t * bufts,
  1550. int n_backends,
  1551. size_t graph_size,
  1552. bool parallel) {
  1553. GGML_ASSERT(n_backends > 0);
  1554. GGML_ASSERT(n_backends <= GGML_SCHED_MAX_BACKENDS);
  1555. GGML_ASSERT(ggml_backend_is_cpu(backends[n_backends - 1])); // last backend must be CPU
  1556. struct ggml_backend_sched * sched = calloc(1, sizeof(struct ggml_backend_sched));
  1557. sched->debug = getenv("GGML_SCHED_DEBUG") != NULL;
  1558. sched->n_backends = n_backends;
  1559. sched->n_copies = parallel ? GGML_SCHED_MAX_COPIES : 1;
  1560. // initialize hash table
  1561. // FIXME: needs to be size*2 to account for leafs (do it in graph_split instead)
  1562. sched->hash_set = ggml_hash_set_new(graph_size);
  1563. sched->hv_tensor_backend_ids = malloc(sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0]));
  1564. sched->hv_tensor_copies = malloc(sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *));
  1565. const size_t ggml_sched_max_splits = graph_size; // at most there is one split for each node in the graph
  1566. const size_t nodes_size = graph_size + ggml_sched_max_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2;
  1567. sched->node_backend_ids = calloc(nodes_size, sizeof(sched->node_backend_ids[0]));
  1568. sched->leaf_backend_ids = calloc(nodes_size, sizeof(sched->leaf_backend_ids[0]));
  1569. sched->prev_node_backend_ids = calloc(nodes_size, sizeof(sched->prev_node_backend_ids[0]));
  1570. sched->prev_leaf_backend_ids = calloc(nodes_size, sizeof(sched->prev_leaf_backend_ids[0]));
  1571. sched->context_buffer_size = ggml_sched_max_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2*sizeof(struct ggml_tensor) + ggml_graph_overhead_custom(graph_size, false);
  1572. sched->context_buffer = malloc(sched->context_buffer_size);
  1573. const int initial_splits_capacity = 16;
  1574. sched->splits = calloc(initial_splits_capacity, sizeof(sched->splits[0]));
  1575. sched->splits_capacity = initial_splits_capacity;
  1576. for (int b = 0; b < n_backends; b++) {
  1577. sched->backends[b] = backends[b];
  1578. sched->bufts[b] = bufts ? bufts[b] : ggml_backend_get_default_buffer_type(backends[b]);
  1579. GGML_ASSERT(ggml_backend_supports_buft(backends[b], sched->bufts[b]));
  1580. if (sched->n_copies > 1) {
  1581. for (int c = 0; c < sched->n_copies; c++) {
  1582. sched->events[b][c] = ggml_backend_event_new(backends[b]);
  1583. }
  1584. }
  1585. }
  1586. sched->galloc = ggml_gallocr_new_n(sched->bufts, n_backends);
  1587. ggml_backend_sched_reset(sched);
  1588. return sched;
  1589. }
  1590. void ggml_backend_sched_free(ggml_backend_sched_t sched) {
  1591. if (sched == NULL) {
  1592. return;
  1593. }
  1594. for (int b = 0; b < sched->n_backends; b++) {
  1595. for (int c = 0; c < sched->n_copies; c++) {
  1596. ggml_backend_event_free(sched->events[b][c]);
  1597. }
  1598. }
  1599. ggml_gallocr_free(sched->galloc);
  1600. ggml_free(sched->ctx);
  1601. ggml_hash_set_free(&sched->hash_set);
  1602. free(sched->splits);
  1603. free(sched->hv_tensor_backend_ids);
  1604. free(sched->hv_tensor_copies);
  1605. free(sched->node_backend_ids);
  1606. free(sched->leaf_backend_ids);
  1607. free(sched->prev_node_backend_ids);
  1608. free(sched->prev_leaf_backend_ids);
  1609. free(sched->context_buffer);
  1610. free(sched->graph.nodes);
  1611. free(sched->graph.leafs);
  1612. free(sched);
  1613. }
  1614. void ggml_backend_sched_reset(ggml_backend_sched_t sched) {
  1615. // reset state for the next run
  1616. if (!sched->is_reset) {
  1617. ggml_hash_set_reset(&sched->hash_set);
  1618. memset(sched->hv_tensor_backend_ids, -1, sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0]));
  1619. memset(sched->hv_tensor_copies, 0, sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *));
  1620. sched->is_reset = true;
  1621. }
  1622. sched->is_alloc = false;
  1623. }
  1624. bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph) {
  1625. GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs);
  1626. ggml_backend_sched_split_graph(sched, measure_graph);
  1627. if (!ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids)) {
  1628. return false;
  1629. }
  1630. ggml_backend_sched_reset(sched);
  1631. ggml_backend_sched_synchronize(sched);
  1632. return true;
  1633. }
  1634. bool ggml_backend_sched_alloc_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  1635. GGML_ASSERT((int)sched->hash_set.size >= graph->n_nodes + graph->n_leafs);
  1636. ggml_backend_sched_split_graph(sched, graph);
  1637. if (!ggml_backend_sched_alloc_splits(sched)) {
  1638. return false;
  1639. }
  1640. sched->is_alloc = true;
  1641. return true;
  1642. }
  1643. enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  1644. enum ggml_status err = ggml_backend_sched_graph_compute_async(sched, graph);
  1645. ggml_backend_sched_synchronize(sched);
  1646. return err;
  1647. }
  1648. enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
  1649. if (!sched->is_reset && !sched->is_alloc) {
  1650. ggml_backend_sched_reset(sched);
  1651. }
  1652. if (!sched->is_alloc) {
  1653. if (!ggml_backend_sched_alloc_graph(sched, graph)) {
  1654. return GGML_STATUS_ALLOC_FAILED;
  1655. }
  1656. }
  1657. return ggml_backend_sched_compute_splits(sched);
  1658. }
  1659. void ggml_backend_sched_synchronize(ggml_backend_sched_t sched) {
  1660. for (int i = 0; i < sched->n_backends; i++) {
  1661. ggml_backend_synchronize(sched->backends[i]);
  1662. }
  1663. }
  1664. void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data) {
  1665. sched->callback_eval = callback;
  1666. sched->callback_eval_user_data = user_data;
  1667. }
  1668. int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched) {
  1669. return sched->n_splits;
  1670. }
  1671. int ggml_backend_sched_get_n_copies(ggml_backend_sched_t sched) {
  1672. return sched->n_copies;
  1673. }
  1674. int ggml_backend_sched_get_n_backends(ggml_backend_sched_t sched) {
  1675. return sched->n_backends;
  1676. }
  1677. ggml_backend_t ggml_backend_sched_get_backend(ggml_backend_sched_t sched, int i) {
  1678. GGML_ASSERT(i >= 0 && i < sched->n_backends);
  1679. return sched->backends[i];
  1680. }
  1681. size_t ggml_backend_sched_get_buffer_size(ggml_backend_sched_t sched, ggml_backend_t backend) {
  1682. int backend_index = ggml_backend_sched_backend_id(sched, backend);
  1683. GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
  1684. return ggml_gallocr_get_buffer_size(sched->galloc, backend_index);
  1685. }
  1686. void ggml_backend_sched_set_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend) {
  1687. int backend_index = ggml_backend_sched_backend_id(sched, backend);
  1688. GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
  1689. tensor_backend_id(node) = backend_index;
  1690. SET_CAUSE(node, "usr");
  1691. sched->is_reset = false;
  1692. }
  1693. ggml_backend_t ggml_backend_sched_get_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node) {
  1694. int backend_index = tensor_backend_id(node);
  1695. if (backend_index == -1) {
  1696. return NULL;
  1697. }
  1698. return sched->backends[backend_index];
  1699. }
  1700. // utils
  1701. void ggml_backend_view_init(struct ggml_tensor * tensor) {
  1702. GGML_ASSERT(tensor->buffer == NULL);
  1703. GGML_ASSERT(tensor->view_src != NULL);
  1704. GGML_ASSERT(tensor->view_src->buffer != NULL);
  1705. GGML_ASSERT(tensor->view_src->data != NULL);
  1706. tensor->buffer = tensor->view_src->buffer;
  1707. tensor->data = (char *)tensor->view_src->data + tensor->view_offs;
  1708. ggml_backend_buffer_init_tensor(tensor->buffer, tensor);
  1709. }
  1710. void ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr) {
  1711. GGML_ASSERT(tensor->buffer == NULL);
  1712. GGML_ASSERT(tensor->data == NULL);
  1713. GGML_ASSERT(tensor->view_src == NULL);
  1714. GGML_ASSERT(addr >= ggml_backend_buffer_get_base(buffer));
  1715. GGML_ASSERT((char *)addr + ggml_backend_buffer_get_alloc_size(buffer, tensor) <=
  1716. (char *)ggml_backend_buffer_get_base(buffer) + ggml_backend_buffer_get_size(buffer));
  1717. tensor->buffer = buffer;
  1718. tensor->data = addr;
  1719. ggml_backend_buffer_init_tensor(buffer, tensor);
  1720. }
  1721. static struct ggml_tensor * graph_copy_dup_tensor(struct ggml_hash_set hash_set, struct ggml_tensor ** node_copies,
  1722. struct ggml_context * ctx_allocated, struct ggml_context * ctx_unallocated, struct ggml_tensor * src) {
  1723. GGML_ASSERT(src != NULL);
  1724. GGML_ASSERT(src->data && "graph must be allocated");
  1725. size_t id = ggml_hash_insert(&hash_set, src);
  1726. if (id == GGML_HASHSET_ALREADY_EXISTS) {
  1727. return node_copies[ggml_hash_find(&hash_set, src)];
  1728. }
  1729. struct ggml_tensor * dst = ggml_dup_tensor_layout(src->data && !src->view_src ? ctx_allocated : ctx_unallocated, src);
  1730. if (src->view_src != NULL) {
  1731. dst->view_src = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, src->view_src);
  1732. dst->view_offs = src->view_offs;
  1733. }
  1734. dst->op = src->op;
  1735. memcpy(dst->op_params, src->op_params, sizeof(dst->op_params));
  1736. ggml_set_name(dst, src->name);
  1737. // copy src
  1738. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1739. struct ggml_tensor * s = src->src[i];
  1740. if (s == NULL) {
  1741. continue;
  1742. }
  1743. dst->src[i] = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, s);
  1744. }
  1745. node_copies[id] = dst;
  1746. return dst;
  1747. }
  1748. static void graph_copy_init_tensor(struct ggml_hash_set * hash_set, struct ggml_tensor ** node_copies, bool * node_init, struct ggml_tensor * src) {
  1749. size_t id = ggml_hash_find(hash_set, src);
  1750. if (node_init[id]) {
  1751. return;
  1752. }
  1753. node_init[id] = true;
  1754. struct ggml_tensor * dst = node_copies[id];
  1755. if (dst->view_src != NULL) {
  1756. graph_copy_init_tensor(hash_set, node_copies, node_init, src->view_src);
  1757. ggml_backend_view_init(dst);
  1758. }
  1759. else {
  1760. ggml_backend_tensor_copy(src, dst);
  1761. }
  1762. // init src
  1763. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1764. struct ggml_tensor * s = src->src[i];
  1765. if (s == NULL) {
  1766. continue;
  1767. }
  1768. graph_copy_init_tensor(hash_set, node_copies, node_init, s);
  1769. }
  1770. }
  1771. struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph) {
  1772. struct ggml_hash_set hash_set = ggml_hash_set_new(graph->visited_hash_set.size);
  1773. struct ggml_tensor ** node_copies = calloc(hash_set.size, sizeof(node_copies[0])); // NOLINT
  1774. bool * node_init = calloc(hash_set.size, sizeof(node_init[0]));
  1775. struct ggml_init_params params = {
  1776. /* .mem_size = */ ggml_tensor_overhead()*hash_set.size + ggml_graph_overhead_custom(graph->size, false),
  1777. /* .mem_buffer = */ NULL,
  1778. /* .no_alloc = */ true
  1779. };
  1780. struct ggml_context * ctx_allocated = ggml_init(params);
  1781. struct ggml_context * ctx_unallocated = ggml_init(params);
  1782. if (ctx_allocated == NULL || ctx_unallocated == NULL) {
  1783. fprintf(stderr, "failed to allocate context for graph copy\n");
  1784. ggml_hash_set_free(&hash_set);
  1785. free(node_copies);
  1786. free(node_init);
  1787. ggml_free(ctx_allocated);
  1788. ggml_free(ctx_unallocated);
  1789. return (struct ggml_backend_graph_copy) {
  1790. /* .buffer = */ NULL,
  1791. /* .ctx_allocated = */ NULL,
  1792. /* .ctx_unallocated = */ NULL,
  1793. /* .graph = */ NULL,
  1794. };
  1795. }
  1796. // dup nodes
  1797. for (int i = 0; i < graph->n_nodes; i++) {
  1798. struct ggml_tensor * node = graph->nodes[i];
  1799. graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, node);
  1800. }
  1801. // allocate nodes
  1802. ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx_allocated, backend);
  1803. if (buffer == NULL) {
  1804. fprintf(stderr, "failed to allocate buffer for graph copy\n");
  1805. ggml_hash_set_free(&hash_set);
  1806. free(node_copies);
  1807. free(node_init);
  1808. ggml_free(ctx_allocated);
  1809. ggml_free(ctx_unallocated);
  1810. return (struct ggml_backend_graph_copy) {
  1811. /* .buffer = */ NULL,
  1812. /* .ctx_allocated = */ NULL,
  1813. /* .ctx_unallocated = */ NULL,
  1814. /* .graph = */ NULL,
  1815. };
  1816. }
  1817. //printf("copy buffer size: %zu MB\n", ggml_backend_buffer_get_size(buffer) / 1024 / 1024);
  1818. // copy data and init views
  1819. for (int i = 0; i < graph->n_nodes; i++) {
  1820. struct ggml_tensor * node = graph->nodes[i];
  1821. graph_copy_init_tensor(&hash_set, node_copies, node_init, node);
  1822. }
  1823. // build graph copy
  1824. struct ggml_cgraph * graph_copy = ggml_new_graph_custom(ctx_allocated, graph->size, false);
  1825. for (int i = 0; i < graph->n_nodes; i++) {
  1826. struct ggml_tensor * node = graph->nodes[i];
  1827. struct ggml_tensor * node_copy = node_copies[ggml_hash_find(&hash_set, node)];
  1828. graph_copy->nodes[i] = node_copy;
  1829. }
  1830. graph_copy->n_nodes = graph->n_nodes;
  1831. ggml_hash_set_free(&hash_set);
  1832. free(node_copies);
  1833. free(node_init);
  1834. return (struct ggml_backend_graph_copy) {
  1835. /* .buffer = */ buffer,
  1836. /* .ctx_allocated = */ ctx_allocated,
  1837. /* .ctx_unallocated = */ ctx_unallocated,
  1838. /* .graph = */ graph_copy,
  1839. };
  1840. }
  1841. void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy) {
  1842. ggml_backend_buffer_free(copy.buffer);
  1843. ggml_free(copy.ctx_allocated);
  1844. ggml_free(copy.ctx_unallocated);
  1845. }
  1846. 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) {
  1847. struct ggml_backend_graph_copy copy = ggml_backend_graph_copy(backend2, graph);
  1848. if (copy.buffer == NULL) {
  1849. return false;
  1850. }
  1851. struct ggml_cgraph * g1 = graph;
  1852. struct ggml_cgraph * g2 = copy.graph;
  1853. assert(g1->n_nodes == g2->n_nodes);
  1854. for (int i = 0; i < g1->n_nodes; i++) {
  1855. //printf("eval %d/%d\n", i, g1->n_nodes);
  1856. struct ggml_tensor * t1 = g1->nodes[i];
  1857. struct ggml_tensor * t2 = g2->nodes[i];
  1858. assert(t1->op == t2->op && ggml_are_same_layout(t1, t2));
  1859. struct ggml_cgraph g1v = ggml_graph_view(g1, i, i + 1);
  1860. struct ggml_cgraph g2v = ggml_graph_view(g2, i, i + 1);
  1861. ggml_backend_graph_compute(backend1, &g1v);
  1862. ggml_backend_graph_compute(backend2, &g2v);
  1863. if (ggml_is_view_op(t1->op)) {
  1864. continue;
  1865. }
  1866. // compare results, calculate rms etc
  1867. if (!callback(i, t1, t2, user_data)) {
  1868. break;
  1869. }
  1870. }
  1871. ggml_backend_graph_copy_free(copy);
  1872. return true;
  1873. }