1
0

ggml-backend.c 66 KB

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