ggml-backend.c 66 KB

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