ggml-backend.c 61 KB

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