ggml-backend.c 61 KB

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