ggml-cuda.cu 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318
  1. /**
  2. * llama.cpp - commit 46e3556e01b824e52395fb050b29804b6cff2a7c - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "ggml-cuda.h"
  27. #include "ggml-impl.h"
  28. #include "ggml-backend-impl.h"
  29. #include "ggml-cuda/common.cuh"
  30. #include "ggml-cuda/acc.cuh"
  31. #include "ggml-cuda/arange.cuh"
  32. #include "ggml-cuda/argmax.cuh"
  33. #include "ggml-cuda/argsort.cuh"
  34. #include "ggml-cuda/binbcast.cuh"
  35. #include "ggml-cuda/clamp.cuh"
  36. #include "ggml-cuda/concat.cuh"
  37. #include "ggml-cuda/conv-transpose-1d.cuh"
  38. #include "ggml-cuda/convert.cuh"
  39. #include "ggml-cuda/count-equal.cuh"
  40. #include "ggml-cuda/cpy.cuh"
  41. #include "ggml-cuda/cross-entropy-loss.cuh"
  42. #include "ggml-cuda/diagmask.cuh"
  43. #include "ggml-cuda/fattn.cuh"
  44. #include "ggml-cuda/getrows.cuh"
  45. #include "ggml-cuda/im2col.cuh"
  46. #include "ggml-cuda/mmq.cuh"
  47. #include "ggml-cuda/mmv.cuh"
  48. #include "ggml-cuda/mmvq.cuh"
  49. #include "ggml-cuda/norm.cuh"
  50. #include "ggml-cuda/opt-step-adamw.cuh"
  51. #include "ggml-cuda/out-prod.cuh"
  52. #include "ggml-cuda/pad.cuh"
  53. #include "ggml-cuda/pool2d.cuh"
  54. #include "ggml-cuda/quantize.cuh"
  55. #include "ggml-cuda/rope.cuh"
  56. #include "ggml-cuda/scale.cuh"
  57. #include "ggml-cuda/softmax.cuh"
  58. #include "ggml-cuda/sum.cuh"
  59. #include "ggml-cuda/sumrows.cuh"
  60. #include "ggml-cuda/tsembd.cuh"
  61. #include "ggml-cuda/unary.cuh"
  62. #include "ggml-cuda/upscale.cuh"
  63. #include "ggml-cuda/wkv6.cuh"
  64. #include <algorithm>
  65. #include <array>
  66. #include <atomic>
  67. #include <cinttypes>
  68. #include <cstddef>
  69. #include <cstdint>
  70. #include <float.h>
  71. #include <limits>
  72. #include <map>
  73. #include <memory>
  74. #include <mutex>
  75. #include <stdint.h>
  76. #include <stdio.h>
  77. #include <stdarg.h>
  78. #include <stdlib.h>
  79. #include <string>
  80. #include <vector>
  81. static_assert(sizeof(half) == sizeof(ggml_fp16_t), "wrong fp16 size");
  82. [[noreturn]]
  83. void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg) {
  84. int id = -1; // in case cudaGetDevice fails
  85. cudaGetDevice(&id);
  86. GGML_LOG_ERROR(GGML_CUDA_NAME " error: %s\n", msg);
  87. GGML_LOG_ERROR(" current device: %d, in function %s at %s:%d\n", id, func, file, line);
  88. GGML_LOG_ERROR(" %s\n", stmt);
  89. // abort with GGML_ABORT to get a stack trace
  90. GGML_ABORT(GGML_CUDA_NAME " error");
  91. }
  92. // this is faster on Windows
  93. // probably because the Windows CUDA libraries forget to make this check before invoking the drivers
  94. void ggml_cuda_set_device(int device) {
  95. int current_device;
  96. CUDA_CHECK(cudaGetDevice(&current_device));
  97. if (device == current_device) {
  98. return;
  99. }
  100. CUDA_CHECK(cudaSetDevice(device));
  101. }
  102. int ggml_cuda_get_device() {
  103. int id;
  104. CUDA_CHECK(cudaGetDevice(&id));
  105. return id;
  106. }
  107. static cudaError_t ggml_cuda_device_malloc(void ** ptr, size_t size, int device) {
  108. ggml_cuda_set_device(device);
  109. #if defined(GGML_USE_HIP) && defined(GGML_HIP_UMA)
  110. auto res = hipMallocManaged(ptr, size);
  111. if (res == hipSuccess) {
  112. // if error we "need" to know why...
  113. CUDA_CHECK(hipMemAdvise(*ptr, size, hipMemAdviseSetCoarseGrain, device));
  114. }
  115. return res;
  116. #else
  117. #if !defined(GGML_USE_HIP)
  118. cudaError_t err;
  119. if (getenv("GGML_CUDA_ENABLE_UNIFIED_MEMORY") != nullptr)
  120. {
  121. err = cudaMallocManaged(ptr, size);
  122. }
  123. else
  124. {
  125. err = cudaMalloc(ptr, size);
  126. }
  127. return err;
  128. #else
  129. return cudaMalloc(ptr, size);
  130. #endif // !defined(GGML_USE_HIP)
  131. #endif
  132. }
  133. static ggml_cuda_device_info ggml_cuda_init() {
  134. #ifdef __HIP_PLATFORM_AMD__
  135. // Workaround for a rocBLAS bug when using multiple graphics cards:
  136. // https://github.com/ROCmSoftwarePlatform/rocBLAS/issues/1346
  137. rocblas_initialize();
  138. CUDA_CHECK(cudaDeviceSynchronize());
  139. #endif
  140. ggml_cuda_device_info info = {};
  141. cudaError_t err = cudaGetDeviceCount(&info.device_count);
  142. if (err != cudaSuccess) {
  143. GGML_LOG_ERROR("%s: failed to initialize " GGML_CUDA_NAME ": %s\n", __func__, cudaGetErrorString(err));
  144. return info;
  145. }
  146. GGML_ASSERT(info.device_count <= GGML_CUDA_MAX_DEVICES);
  147. int64_t total_vram = 0;
  148. #ifdef GGML_CUDA_FORCE_MMQ
  149. GGML_LOG_INFO("%s: GGML_CUDA_FORCE_MMQ: yes\n", __func__);
  150. #else
  151. GGML_LOG_INFO("%s: GGML_CUDA_FORCE_MMQ: no\n", __func__);
  152. #endif // GGML_CUDA_FORCE_MMQ
  153. #ifdef GGML_CUDA_FORCE_CUBLAS
  154. GGML_LOG_INFO("%s: GGML_CUDA_FORCE_CUBLAS: yes\n", __func__);
  155. #else
  156. GGML_LOG_INFO("%s: GGML_CUDA_FORCE_CUBLAS: no\n", __func__);
  157. #endif // GGML_CUDA_FORCE_CUBLAS
  158. GGML_LOG_INFO("%s: found %d " GGML_CUDA_NAME " devices:\n", __func__, info.device_count);
  159. for (int id = 0; id < info.device_count; ++id) {
  160. int device_vmm = 0;
  161. #if !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  162. CUdevice device;
  163. CU_CHECK(cuDeviceGet(&device, id));
  164. CU_CHECK(cuDeviceGetAttribute(&device_vmm, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, device));
  165. if (device_vmm) {
  166. CUmemAllocationProp alloc_prop = {};
  167. alloc_prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
  168. alloc_prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  169. alloc_prop.location.id = id;
  170. CU_CHECK(cuMemGetAllocationGranularity(&info.devices[id].vmm_granularity, &alloc_prop, CU_MEM_ALLOC_GRANULARITY_RECOMMENDED));
  171. }
  172. #endif // !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  173. info.devices[id].vmm = !!device_vmm;
  174. cudaDeviceProp prop;
  175. CUDA_CHECK(cudaGetDeviceProperties(&prop, id));
  176. GGML_LOG_INFO(" Device %d: %s, compute capability %d.%d, VMM: %s\n", id, prop.name, prop.major, prop.minor, device_vmm ? "yes" : "no");
  177. info.default_tensor_split[id] = total_vram;
  178. total_vram += prop.totalGlobalMem;
  179. info.devices[id].nsm = prop.multiProcessorCount;
  180. info.devices[id].smpb = prop.sharedMemPerBlock;
  181. #if defined(GGML_USE_HIP) && defined(__HIP_PLATFORM_AMD__)
  182. info.devices[id].smpbo = prop.sharedMemPerBlock;
  183. info.devices[id].cc = 100*prop.major + 10*prop.minor + GGML_CUDA_CC_OFFSET_AMD;
  184. #else
  185. info.devices[id].smpbo = prop.sharedMemPerBlockOptin;
  186. info.devices[id].cc = 100*prop.major + 10*prop.minor;
  187. #endif // defined(GGML_USE_HIP) && defined(__HIP_PLATFORM_AMD__)
  188. }
  189. for (int id = 0; id < info.device_count; ++id) {
  190. info.default_tensor_split[id] /= total_vram;
  191. }
  192. // configure logging to stdout
  193. // CUBLAS_CHECK(cublasLoggerConfigure(1, 1, 0, nullptr));
  194. return info;
  195. }
  196. const ggml_cuda_device_info & ggml_cuda_info() {
  197. static ggml_cuda_device_info info = ggml_cuda_init();
  198. return info;
  199. }
  200. // #define DEBUG_CUDA_MALLOC
  201. // buffer pool for cuda (legacy)
  202. struct ggml_cuda_pool_leg : public ggml_cuda_pool {
  203. static const int MAX_BUFFERS = 256;
  204. int device;
  205. struct ggml_cuda_buffer {
  206. void * ptr = nullptr;
  207. size_t size = 0;
  208. };
  209. ggml_cuda_buffer buffer_pool[MAX_BUFFERS] = {};
  210. size_t pool_size = 0;
  211. explicit ggml_cuda_pool_leg(int device) :
  212. device(device) {
  213. }
  214. ~ggml_cuda_pool_leg() {
  215. ggml_cuda_set_device(device);
  216. for (int i = 0; i < MAX_BUFFERS; ++i) {
  217. ggml_cuda_buffer & b = buffer_pool[i];
  218. if (b.ptr != nullptr) {
  219. CUDA_CHECK(cudaFree(b.ptr));
  220. pool_size -= b.size;
  221. }
  222. }
  223. GGML_ASSERT(pool_size == 0);
  224. }
  225. void * alloc(size_t size, size_t * actual_size) override {
  226. #ifdef DEBUG_CUDA_MALLOC
  227. int nnz = 0;
  228. size_t max_size = 0;
  229. #endif
  230. size_t best_diff = 1ull << 36;
  231. int ibest = -1;
  232. for (int i = 0; i < MAX_BUFFERS; ++i) {
  233. ggml_cuda_buffer& b = buffer_pool[i];
  234. if (b.ptr != nullptr) {
  235. #ifdef DEBUG_CUDA_MALLOC
  236. ++nnz;
  237. if (b.size > max_size) max_size = b.size;
  238. #endif
  239. if (b.size >= size) {
  240. size_t diff = b.size - size;
  241. if (diff < best_diff) {
  242. best_diff = diff;
  243. ibest = i;
  244. if (!best_diff) {
  245. void * ptr = b.ptr;
  246. *actual_size = b.size;
  247. b.ptr = nullptr;
  248. b.size = 0;
  249. return ptr;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. if (ibest >= 0) {
  256. ggml_cuda_buffer& b = buffer_pool[ibest];
  257. void * ptr = b.ptr;
  258. *actual_size = b.size;
  259. b.ptr = nullptr;
  260. b.size = 0;
  261. return ptr;
  262. }
  263. void * ptr;
  264. size_t look_ahead_size = (size_t) (1.05 * size);
  265. look_ahead_size = 256 * ((look_ahead_size + 255)/256);
  266. ggml_cuda_set_device(device);
  267. CUDA_CHECK(ggml_cuda_device_malloc(&ptr, look_ahead_size, device));
  268. *actual_size = look_ahead_size;
  269. pool_size += look_ahead_size;
  270. #ifdef DEBUG_CUDA_MALLOC
  271. GGML_LOG_INFO("%s[%d]: %d buffers, max_size = %u MB, pool_size = %u MB, requested %u MB\n", __func__, device, nnz,
  272. (uint32_t)(max_size / 1024 / 1024), (uint32_t)(pool_size / 1024 / 1024), (uint32_t)(size / 1024 / 1024));
  273. #endif
  274. return ptr;
  275. }
  276. void free(void * ptr, size_t size) override {
  277. for (int i = 0; i < MAX_BUFFERS; ++i) {
  278. ggml_cuda_buffer& b = buffer_pool[i];
  279. if (b.ptr == nullptr) {
  280. b.ptr = ptr;
  281. b.size = size;
  282. return;
  283. }
  284. }
  285. GGML_LOG_DEBUG(GGML_CUDA_NAME " buffer pool full, increase MAX_CUDA_BUFFERS\n");
  286. ggml_cuda_set_device(device);
  287. CUDA_CHECK(cudaFree(ptr));
  288. pool_size -= size;
  289. }
  290. };
  291. // pool with virtual memory
  292. #if !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  293. struct ggml_cuda_pool_vmm : public ggml_cuda_pool {
  294. static const size_t CUDA_POOL_VMM_MAX_SIZE = 1ull << 35; // 32 GB
  295. int device;
  296. CUdeviceptr pool_addr = 0;
  297. size_t pool_used = 0;
  298. size_t pool_size = 0;
  299. size_t granularity;
  300. explicit ggml_cuda_pool_vmm(int device) :
  301. device(device),
  302. granularity(ggml_cuda_info().devices[device].vmm_granularity) {
  303. }
  304. ~ggml_cuda_pool_vmm() {
  305. if (pool_addr != 0) {
  306. CU_CHECK(cuMemUnmap(pool_addr, pool_size));
  307. CU_CHECK(cuMemAddressFree(pool_addr, CUDA_POOL_VMM_MAX_SIZE));
  308. }
  309. }
  310. void * alloc(size_t size, size_t * actual_size) override {
  311. // round up the allocation size to the alignment to ensure that all allocations are aligned for all data types
  312. const size_t alignment = 128;
  313. size = alignment * ((size + alignment - 1) / alignment);
  314. size_t avail = pool_size - pool_used;
  315. if (size > avail) {
  316. // round up to the next multiple of the granularity
  317. size_t reserve_size = size - avail;
  318. reserve_size = granularity * ((reserve_size + granularity - 1) / granularity);
  319. GGML_ASSERT(pool_size + reserve_size <= CUDA_POOL_VMM_MAX_SIZE);
  320. // allocate more physical memory
  321. CUmemAllocationProp prop = {};
  322. prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
  323. prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  324. prop.location.id = device;
  325. CUmemGenericAllocationHandle handle;
  326. CU_CHECK(cuMemCreate(&handle, reserve_size, &prop, 0));
  327. // reserve virtual address space (if not already reserved)
  328. if (pool_addr == 0) {
  329. CU_CHECK(cuMemAddressReserve(&pool_addr, CUDA_POOL_VMM_MAX_SIZE, 0, 0, 0));
  330. }
  331. // map at the end of the pool
  332. CU_CHECK(cuMemMap(pool_addr + pool_size, reserve_size, 0, handle, 0));
  333. // the memory allocation handle is no longer needed after mapping
  334. CU_CHECK(cuMemRelease(handle));
  335. // set access
  336. CUmemAccessDesc access = {};
  337. access.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
  338. access.location.id = device;
  339. access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
  340. CU_CHECK(cuMemSetAccess(pool_addr + pool_size, reserve_size, &access, 1));
  341. // add to the pool
  342. pool_size += reserve_size;
  343. //printf("cuda pool[%d]: size increased to %llu MB (reserved %llu MB)\n",
  344. // device, (unsigned long long) (pool_size/1024/1024),
  345. // (unsigned long long) (reserve_size/1024/1024));
  346. }
  347. GGML_ASSERT(pool_addr != 0);
  348. void * ptr = (void *) (pool_addr + pool_used);
  349. *actual_size = size;
  350. pool_used += size;
  351. #ifdef DEBUG_CUDA_MALLOC
  352. printf("cuda pool[%d]: allocated %llu bytes at %llx\n", device, (unsigned long long) size, ptr);
  353. #endif
  354. return ptr;
  355. }
  356. void free(void * ptr, size_t size) override {
  357. #ifdef DEBUG_CUDA_MALLOC
  358. printf("cuda pool[%d]: freed %llu bytes at %llx\n", device, (unsigned long long) size, ptr);
  359. #endif
  360. pool_used -= size;
  361. // all deallocations must be in reverse order of the allocations
  362. GGML_ASSERT(ptr == (void *) (pool_addr + pool_used));
  363. }
  364. };
  365. #endif // !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  366. std::unique_ptr<ggml_cuda_pool> ggml_backend_cuda_context::new_pool_for_device(int device) {
  367. #if !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  368. if (ggml_cuda_info().devices[device].vmm) {
  369. return std::unique_ptr<ggml_cuda_pool>(new ggml_cuda_pool_vmm(device));
  370. }
  371. #endif // !defined(GGML_USE_HIP) && !defined(GGML_CUDA_NO_VMM)
  372. return std::unique_ptr<ggml_cuda_pool>(new ggml_cuda_pool_leg(device));
  373. }
  374. // cuda buffer
  375. struct ggml_backend_cuda_buffer_context {
  376. int device;
  377. void * dev_ptr = nullptr;
  378. std::string name;
  379. ggml_backend_cuda_buffer_context(int device, void * dev_ptr) :
  380. device(device), dev_ptr(dev_ptr),
  381. name(GGML_CUDA_NAME + std::to_string(device)) {
  382. }
  383. ~ggml_backend_cuda_buffer_context() {
  384. CUDA_CHECK(cudaFree(dev_ptr));
  385. }
  386. };
  387. static void ggml_backend_cuda_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  388. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  389. delete ctx;
  390. // TODO: this needs to be freed in cuda and hipblas backends because
  391. // the cuda backend implementation compiled with msvc
  392. free(buffer);
  393. }
  394. static bool ggml_backend_buffer_is_cuda(ggml_backend_buffer_t buffer) {
  395. return buffer->iface.free_buffer == ggml_backend_cuda_buffer_free_buffer;
  396. }
  397. static void * ggml_backend_cuda_buffer_get_base(ggml_backend_buffer_t buffer) {
  398. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  399. return ctx->dev_ptr;
  400. }
  401. static void ggml_backend_cuda_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  402. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  403. if (tensor->view_src != NULL) {
  404. assert(tensor->view_src->buffer->buft == buffer->buft);
  405. return;
  406. }
  407. if (ggml_is_quantized(tensor->type) && tensor->view_src == nullptr && ggml_backend_buffer_get_usage(buffer) != GGML_BACKEND_BUFFER_USAGE_COMPUTE) {
  408. // initialize padding to 0 to avoid possible NaN values
  409. size_t original_size = ggml_nbytes(tensor);
  410. size_t padded_size = ggml_backend_buft_get_alloc_size(buffer->buft, tensor);
  411. if (padded_size > original_size) {
  412. ggml_cuda_set_device(ctx->device);
  413. CUDA_CHECK(cudaMemset((char *)tensor->data + original_size, 0, padded_size - original_size));
  414. }
  415. }
  416. }
  417. static void ggml_backend_cuda_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
  418. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  419. ggml_cuda_set_device(ctx->device);
  420. CUDA_CHECK(cudaMemsetAsync((char *)tensor->data + offset, value, size, cudaStreamPerThread));
  421. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  422. }
  423. static void ggml_backend_cuda_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  424. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  425. ggml_cuda_set_device(ctx->device);
  426. CUDA_CHECK(cudaMemcpyAsync((char *)tensor->data + offset, data, size, cudaMemcpyHostToDevice, cudaStreamPerThread));
  427. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  428. }
  429. static void ggml_backend_cuda_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  430. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  431. ggml_cuda_set_device(ctx->device);
  432. CUDA_CHECK(cudaMemcpyAsync(data, (const char *)tensor->data + offset, size, cudaMemcpyDeviceToHost, cudaStreamPerThread));
  433. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  434. }
  435. static bool ggml_backend_cuda_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  436. if (ggml_backend_buffer_is_cuda(src->buffer)) {
  437. ggml_backend_cuda_buffer_context * src_ctx = (ggml_backend_cuda_buffer_context *)src->buffer->context;
  438. ggml_backend_cuda_buffer_context * dst_ctx = (ggml_backend_cuda_buffer_context *)dst->buffer->context;
  439. if (src_ctx->device == dst_ctx->device) {
  440. CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(src), cudaMemcpyDeviceToDevice, cudaStreamPerThread));
  441. } else {
  442. #ifdef GGML_CUDA_NO_PEER_COPY
  443. return false;
  444. #else
  445. CUDA_CHECK(cudaMemcpyPeerAsync(dst->data, dst_ctx->device, src->data, src_ctx->device, ggml_nbytes(src), cudaStreamPerThread));
  446. #endif
  447. }
  448. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  449. return true;
  450. }
  451. return false;
  452. GGML_UNUSED(buffer);
  453. }
  454. static void ggml_backend_cuda_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  455. ggml_backend_cuda_buffer_context * ctx = (ggml_backend_cuda_buffer_context *)buffer->context;
  456. ggml_cuda_set_device(ctx->device);
  457. CUDA_CHECK(cudaDeviceSynchronize());
  458. CUDA_CHECK(cudaMemset(ctx->dev_ptr, value, buffer->size));
  459. CUDA_CHECK(cudaDeviceSynchronize());
  460. }
  461. static const ggml_backend_buffer_i ggml_backend_cuda_buffer_interface = {
  462. /* .free_buffer = */ ggml_backend_cuda_buffer_free_buffer,
  463. /* .get_base = */ ggml_backend_cuda_buffer_get_base,
  464. /* .init_tensor = */ ggml_backend_cuda_buffer_init_tensor,
  465. /* .memset_tensor = */ ggml_backend_cuda_buffer_memset_tensor,
  466. /* .set_tensor = */ ggml_backend_cuda_buffer_set_tensor,
  467. /* .get_tensor = */ ggml_backend_cuda_buffer_get_tensor,
  468. /* .cpy_tensor = */ ggml_backend_cuda_buffer_cpy_tensor,
  469. /* .clear = */ ggml_backend_cuda_buffer_clear,
  470. /* .reset = */ NULL,
  471. };
  472. // cuda buffer type
  473. struct ggml_backend_cuda_buffer_type_context {
  474. int device;
  475. std::string name;
  476. };
  477. static const char * ggml_backend_cuda_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  478. ggml_backend_cuda_buffer_type_context * ctx = (ggml_backend_cuda_buffer_type_context *)buft->context;
  479. return ctx->name.c_str();
  480. }
  481. static bool ggml_backend_buft_is_cuda(ggml_backend_buffer_type_t buft) {
  482. return buft->iface.get_name == ggml_backend_cuda_buffer_type_get_name;
  483. }
  484. static ggml_backend_buffer_t ggml_backend_cuda_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  485. ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *)buft->context;
  486. ggml_cuda_set_device(buft_ctx->device);
  487. void * dev_ptr;
  488. cudaError_t err = ggml_cuda_device_malloc(&dev_ptr, size, buft_ctx->device);
  489. if (err != cudaSuccess) {
  490. // clear the error
  491. cudaGetLastError();
  492. GGML_LOG_ERROR("%s: allocating %.2f MiB on device %d: cudaMalloc failed: %s\n", __func__, size / 1024.0 / 1024.0, buft_ctx->device, cudaGetErrorString(err));
  493. return nullptr;
  494. }
  495. ggml_backend_cuda_buffer_context * ctx = new ggml_backend_cuda_buffer_context(buft_ctx->device, dev_ptr);
  496. return ggml_backend_buffer_init(buft, ggml_backend_cuda_buffer_interface, ctx, size);
  497. }
  498. static size_t ggml_backend_cuda_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  499. return 128;
  500. GGML_UNUSED(buft);
  501. }
  502. static size_t ggml_backend_cuda_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  503. size_t size = ggml_nbytes(tensor);
  504. int64_t ne0 = tensor->ne[0];
  505. if (ggml_is_quantized(tensor->type)) {
  506. if (ne0 % MATRIX_ROW_PADDING != 0) {
  507. size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  508. }
  509. }
  510. return size;
  511. GGML_UNUSED(buft);
  512. }
  513. static const ggml_backend_buffer_type_i ggml_backend_cuda_buffer_type_interface = {
  514. /* .get_name = */ ggml_backend_cuda_buffer_type_get_name,
  515. /* .alloc_buffer = */ ggml_backend_cuda_buffer_type_alloc_buffer,
  516. /* .get_alignment = */ ggml_backend_cuda_buffer_type_get_alignment,
  517. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  518. /* .get_alloc_size = */ ggml_backend_cuda_buffer_type_get_alloc_size,
  519. /* .is_host = */ NULL,
  520. };
  521. ggml_backend_buffer_type_t ggml_backend_cuda_buffer_type(int device) {
  522. static std::mutex mutex;
  523. std::lock_guard<std::mutex> lock(mutex);
  524. if (device >= ggml_backend_cuda_get_device_count()) {
  525. return nullptr;
  526. }
  527. static ggml_backend_buffer_type ggml_backend_cuda_buffer_types[GGML_CUDA_MAX_DEVICES];
  528. static bool ggml_backend_cuda_buffer_type_initialized = false;
  529. if (!ggml_backend_cuda_buffer_type_initialized) {
  530. for (int i = 0; i < ggml_backend_cuda_get_device_count(); i++) {
  531. ggml_backend_cuda_buffer_types[i] = {
  532. /* .iface = */ ggml_backend_cuda_buffer_type_interface,
  533. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), i),
  534. /* .context = */ new ggml_backend_cuda_buffer_type_context{i, GGML_CUDA_NAME + std::to_string(i)},
  535. };
  536. }
  537. ggml_backend_cuda_buffer_type_initialized = true;
  538. }
  539. return &ggml_backend_cuda_buffer_types[device];
  540. }
  541. // cuda split buffer
  542. static int64_t get_row_rounding(const std::array<float, GGML_CUDA_MAX_DEVICES> & tensor_split) {
  543. int64_t row_rounding = 0;
  544. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  545. if (tensor_split[id] >= (id + 1 < ggml_backend_cuda_get_device_count() ? tensor_split[id + 1] : 1.0f)) {
  546. continue;
  547. }
  548. const int cc = ggml_cuda_info().devices[id].cc;
  549. row_rounding = std::max(row_rounding, (int64_t)get_mmq_y_host(cc));
  550. }
  551. return row_rounding;
  552. }
  553. static void get_row_split(int64_t * row_low, int64_t * row_high, const ggml_tensor * tensor, const std::array<float, GGML_CUDA_MAX_DEVICES> & tensor_split, int id) {
  554. const int64_t nrows = ggml_nrows(tensor);
  555. const int64_t rounding = get_row_rounding(tensor_split);
  556. *row_low = id == 0 ? 0 : nrows*tensor_split[id];
  557. *row_low -= *row_low % rounding;
  558. if (id == ggml_backend_cuda_get_device_count() - 1) {
  559. *row_high = nrows;
  560. } else {
  561. *row_high = nrows*tensor_split[id + 1];
  562. *row_high -= *row_high % rounding;
  563. }
  564. }
  565. static size_t ggml_nbytes_split(const struct ggml_tensor * tensor, int nrows_split) {
  566. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  567. return nrows_split*ggml_row_size(tensor->type, tensor->ne[0]);
  568. }
  569. struct ggml_backend_cuda_split_buffer_type_context {
  570. int main_device;
  571. std::array<float, GGML_CUDA_MAX_DEVICES> tensor_split;
  572. std::string name;
  573. };
  574. struct ggml_backend_cuda_split_buffer_context {
  575. ~ggml_backend_cuda_split_buffer_context() {
  576. for (ggml_tensor_extra_gpu * extra : tensor_extras) {
  577. for (int id = 0; id < GGML_CUDA_MAX_DEVICES; ++id) {
  578. for (int64_t is = 0; is < GGML_CUDA_MAX_STREAMS; ++is) {
  579. if (extra->events[id][is] != nullptr) {
  580. CUDA_CHECK(cudaEventDestroy(extra->events[id][is]));
  581. }
  582. }
  583. if (extra->data_device[id] != nullptr) {
  584. CUDA_CHECK(cudaFree(extra->data_device[id]));
  585. }
  586. }
  587. delete extra;
  588. }
  589. }
  590. std::vector<ggml_tensor_extra_gpu *> tensor_extras;
  591. };
  592. static void ggml_backend_cuda_split_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  593. ggml_backend_cuda_split_buffer_context * ctx = (ggml_backend_cuda_split_buffer_context *)buffer->context;
  594. delete ctx;
  595. }
  596. static void * ggml_backend_cuda_split_buffer_get_base(ggml_backend_buffer_t buffer) {
  597. // the pointers are stored in the tensor extras, this is just a dummy address and never dereferenced
  598. return (void *)0x1000;
  599. GGML_UNUSED(buffer);
  600. }
  601. static void ggml_backend_cuda_split_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  602. GGML_ASSERT(tensor->view_src == nullptr); // views of split tensors are not supported
  603. ggml_backend_cuda_split_buffer_context * ctx = (ggml_backend_cuda_split_buffer_context *)buffer->context;
  604. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *)buffer->buft->context;
  605. const int64_t ne0 = tensor->ne[0];
  606. ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{};
  607. ctx->tensor_extras.push_back(extra);
  608. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  609. int64_t row_low, row_high;
  610. get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, id);
  611. int64_t nrows_split = row_high - row_low;
  612. if (nrows_split == 0) {
  613. continue;
  614. }
  615. size_t size = ggml_nbytes_split(tensor, nrows_split);
  616. const size_t original_size = size;
  617. // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses
  618. if (ne0 % MATRIX_ROW_PADDING != 0) {
  619. size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  620. }
  621. // FIXME: do not crash if cudaMalloc fails
  622. // currently, init_tensor cannot fail, it needs to be fixed in ggml-backend first
  623. ggml_cuda_set_device(id);
  624. char * buf;
  625. CUDA_CHECK(ggml_cuda_device_malloc((void**)&buf, size, id));
  626. // set padding to 0 to avoid possible NaN values
  627. if (size > original_size) {
  628. CUDA_CHECK(cudaMemset(buf + original_size, 0, size - original_size));
  629. }
  630. extra->data_device[id] = buf;
  631. for (int64_t is = 0; is < GGML_CUDA_MAX_STREAMS; ++is) {
  632. CUDA_CHECK(cudaEventCreateWithFlags(&extra->events[id][is], cudaEventDisableTiming));
  633. }
  634. }
  635. tensor->extra = extra;
  636. }
  637. static void ggml_backend_cuda_split_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  638. // split tensors must always be set in their entirety at once
  639. GGML_ASSERT(offset == 0);
  640. GGML_ASSERT(size == ggml_nbytes(tensor));
  641. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *)buffer->buft->context;
  642. const int64_t ne0 = tensor->ne[0];
  643. const size_t nb1 = tensor->nb[1];
  644. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *)tensor->extra;
  645. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  646. int64_t row_low, row_high;
  647. get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, id);
  648. int64_t nrows_split = row_high - row_low;
  649. if (nrows_split == 0) {
  650. continue;
  651. }
  652. const size_t offset_split = row_low*nb1;
  653. size_t size = ggml_nbytes_split(tensor, nrows_split);
  654. const size_t original_size = size;
  655. // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses
  656. if (ne0 % MATRIX_ROW_PADDING != 0) {
  657. size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  658. }
  659. const char * buf_host = (const char *)data + offset_split;
  660. CUDA_CHECK(cudaMemcpyAsync(extra->data_device[id], buf_host, original_size, cudaMemcpyHostToDevice, cudaStreamPerThread));
  661. }
  662. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  663. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  664. }
  665. }
  666. static void ggml_backend_cuda_split_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  667. // split tensors must always be set in their entirety at once
  668. GGML_ASSERT(offset == 0);
  669. GGML_ASSERT(size == ggml_nbytes(tensor));
  670. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *)buffer->buft->context;
  671. const int64_t ne0 = tensor->ne[0];
  672. const size_t nb1 = tensor->nb[1];
  673. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *)tensor->extra;
  674. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  675. int64_t row_low, row_high;
  676. get_row_split(&row_low, &row_high, tensor, buft_ctx->tensor_split, id);
  677. int64_t nrows_split = row_high - row_low;
  678. if (nrows_split == 0) {
  679. continue;
  680. }
  681. const size_t offset_split = row_low*nb1;
  682. size_t size = ggml_nbytes_split(tensor, nrows_split);
  683. const size_t original_size = size;
  684. // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses
  685. if (ne0 % MATRIX_ROW_PADDING != 0) {
  686. size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  687. }
  688. char * buf_host = (char *)data + offset_split;
  689. CUDA_CHECK(cudaMemcpyAsync(buf_host, extra->data_device[id], original_size, cudaMemcpyDeviceToHost, cudaStreamPerThread));
  690. }
  691. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  692. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread));
  693. }
  694. }
  695. static void ggml_backend_cuda_split_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  696. GGML_UNUSED(buffer);
  697. GGML_UNUSED(value);
  698. }
  699. static const ggml_backend_buffer_i ggml_backend_cuda_split_buffer_interface = {
  700. /* .free_buffer = */ ggml_backend_cuda_split_buffer_free_buffer,
  701. /* .get_base = */ ggml_backend_cuda_split_buffer_get_base,
  702. /* .init_tensor = */ ggml_backend_cuda_split_buffer_init_tensor,
  703. /* .memset_tensor = */ NULL,
  704. /* .set_tensor = */ ggml_backend_cuda_split_buffer_set_tensor,
  705. /* .get_tensor = */ ggml_backend_cuda_split_buffer_get_tensor,
  706. /* .cpy_tensor = */ NULL,
  707. /* .clear = */ ggml_backend_cuda_split_buffer_clear,
  708. /* .reset = */ NULL,
  709. };
  710. // cuda split buffer type
  711. static const char * ggml_backend_cuda_split_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  712. ggml_backend_cuda_split_buffer_type_context * ctx = (ggml_backend_cuda_split_buffer_type_context *)buft->context;
  713. return ctx->name.c_str();
  714. }
  715. static bool ggml_backend_buft_is_cuda_split(ggml_backend_buffer_type_t buft) {
  716. return buft->iface.get_name == ggml_backend_cuda_split_buffer_type_get_name;
  717. }
  718. static ggml_backend_buffer_t ggml_backend_cuda_split_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  719. // since we don't know the exact split after rounding, we cannot allocate the device buffers at this point
  720. // instead, we allocate them for each tensor separately in init_tensor
  721. // however, the size still represents the maximum cumulative size of all the device buffers after the tensors are allocated,
  722. // as returned by get_alloc_size. this limit is enforced during tensor allocation by ggml-alloc, so it must be correct.
  723. ggml_backend_cuda_split_buffer_context * ctx = new ggml_backend_cuda_split_buffer_context();
  724. return ggml_backend_buffer_init(buft, ggml_backend_cuda_split_buffer_interface, ctx, size);
  725. }
  726. static size_t ggml_backend_cuda_split_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  727. return 128;
  728. GGML_UNUSED(buft);
  729. }
  730. static size_t ggml_backend_cuda_split_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  731. ggml_backend_cuda_split_buffer_type_context * ctx = (ggml_backend_cuda_split_buffer_type_context *)buft->context;
  732. size_t total_size = 0;
  733. const int64_t ne0 = tensor->ne[0];
  734. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  735. int64_t row_low, row_high;
  736. get_row_split(&row_low, &row_high, tensor, ctx->tensor_split, id);
  737. int64_t nrows_split = row_high - row_low;
  738. if (nrows_split == 0) {
  739. continue;
  740. }
  741. total_size += ggml_nbytes_split(tensor, nrows_split);
  742. // pad last row to a multiple of 512 elements to avoid out-of-bounds memory accesses
  743. if (ne0 % MATRIX_ROW_PADDING != 0) {
  744. total_size += ggml_row_size(tensor->type, MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING);
  745. }
  746. }
  747. return total_size;
  748. }
  749. static bool ggml_backend_cuda_split_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  750. return false;
  751. GGML_UNUSED(buft);
  752. }
  753. static const ggml_backend_buffer_type_i ggml_backend_cuda_split_buffer_type_interface = {
  754. /* .get_name = */ ggml_backend_cuda_split_buffer_type_get_name,
  755. /* .alloc_buffer = */ ggml_backend_cuda_split_buffer_type_alloc_buffer,
  756. /* .get_alignment = */ ggml_backend_cuda_split_buffer_type_get_alignment,
  757. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  758. /* .get_alloc_size = */ ggml_backend_cuda_split_buffer_type_get_alloc_size,
  759. /* .is_host = */ ggml_backend_cuda_split_buffer_type_is_host,
  760. };
  761. ggml_backend_buffer_type_t ggml_backend_cuda_split_buffer_type(int main_device, const float * tensor_split) {
  762. static std::mutex mutex;
  763. std::lock_guard<std::mutex> lock(mutex);
  764. static std::map<std::pair<int, std::array<float, GGML_CUDA_MAX_DEVICES>>, struct ggml_backend_buffer_type> buft_map;
  765. std::array<float, GGML_CUDA_MAX_DEVICES> tensor_split_arr = {};
  766. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + GGML_CUDA_MAX_DEVICES, [](float x) { return x == 0.0f; });
  767. if (all_zero) {
  768. tensor_split_arr = ggml_cuda_info().default_tensor_split;
  769. } else {
  770. float split_sum = 0.0f;
  771. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  772. tensor_split_arr[i] = split_sum;
  773. split_sum += tensor_split[i];
  774. }
  775. for (int i = 0; i < ggml_backend_cuda_get_device_count(); ++i) {
  776. tensor_split_arr[i] /= split_sum;
  777. }
  778. }
  779. auto it = buft_map.find({main_device, tensor_split_arr});
  780. if (it != buft_map.end()) {
  781. return &it->second;
  782. }
  783. auto * ctx = new ggml_backend_cuda_split_buffer_type_context{
  784. main_device,
  785. tensor_split_arr,
  786. GGML_CUDA_NAME + std::to_string(main_device) + "_Split",
  787. };
  788. struct ggml_backend_buffer_type buft {
  789. /* .iface = */ ggml_backend_cuda_split_buffer_type_interface,
  790. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), main_device),
  791. /* .context = */ ctx,
  792. };
  793. auto result = buft_map.emplace(std::make_pair(main_device, tensor_split_arr), buft);
  794. return &result.first->second;
  795. }
  796. // host buffer type
  797. static const char * ggml_backend_cuda_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  798. return GGML_CUDA_NAME "_Host";
  799. GGML_UNUSED(buft);
  800. }
  801. static void ggml_backend_cuda_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  802. CUDA_CHECK(cudaFreeHost(buffer->context));
  803. }
  804. static void * ggml_cuda_host_malloc(size_t size) {
  805. if (getenv("GGML_CUDA_NO_PINNED") != nullptr) {
  806. return nullptr;
  807. }
  808. void * ptr = nullptr;
  809. cudaError_t err = cudaMallocHost((void **) &ptr, size);
  810. if (err != cudaSuccess) {
  811. // clear the error
  812. cudaGetLastError();
  813. GGML_LOG_DEBUG("%s: failed to allocate %.2f MiB of pinned memory: %s\n", __func__,
  814. size / 1024.0 / 1024.0, cudaGetErrorString(err));
  815. return nullptr;
  816. }
  817. return ptr;
  818. }
  819. static ggml_backend_buffer_t ggml_backend_cuda_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  820. void * ptr = ggml_cuda_host_malloc(size);
  821. if (ptr == nullptr) {
  822. // fallback to cpu buffer
  823. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  824. }
  825. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  826. buffer->buft = buft;
  827. buffer->iface.free_buffer = ggml_backend_cuda_host_buffer_free_buffer;
  828. return buffer;
  829. }
  830. ggml_backend_buffer_type_t ggml_backend_cuda_host_buffer_type() {
  831. static struct ggml_backend_buffer_type ggml_backend_cuda_buffer_type_host = {
  832. /* .iface = */ {
  833. /* .get_name = */ ggml_backend_cuda_host_buffer_type_name,
  834. /* .alloc_buffer = */ ggml_backend_cuda_host_buffer_type_alloc_buffer,
  835. /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment,
  836. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  837. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  838. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  839. },
  840. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), 0),
  841. /* .context = */ nullptr,
  842. };
  843. return &ggml_backend_cuda_buffer_type_host;
  844. }
  845. //static bool ggml_backend_buffer_is_cuda_host(ggml_backend_buffer_t buffer) {
  846. // return buffer->buft->iface.get_name == ggml_backend_cuda_host_buffer_type_name;
  847. //}
  848. /// kernels
  849. typedef void (*ggml_cuda_op_mul_mat_t)(
  850. ggml_backend_cuda_context & ctx,
  851. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const char * src0_dd_i, const float * src1_ddf_i,
  852. const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
  853. const int64_t src1_padded_row_size, cudaStream_t stream);
  854. #ifndef GGML_CUDA_PEER_MAX_BATCH_SIZE
  855. #define GGML_CUDA_PEER_MAX_BATCH_SIZE 128
  856. #endif // GGML_CUDA_PEER_MAX_BATCH_SIZE
  857. #define MUL_MAT_SRC1_COL_STRIDE 128
  858. static cudaError_t ggml_cuda_cpy_tensor_2d(
  859. void * dst, const struct ggml_tensor * src, int64_t i3, int64_t i2, int64_t i1_low, int64_t i1_high, cudaStream_t stream) {
  860. GGML_ASSERT(ggml_backend_buffer_is_cuda(src->buffer));
  861. const char * src_ptr = (const char *) src->data;
  862. char * dst_ptr = (char *) dst;
  863. const int64_t ne0 = src->ne[0];
  864. const int64_t nb0 = src->nb[0];
  865. const int64_t nb1 = src->nb[1];
  866. const int64_t nb2 = src->nb[2];
  867. const int64_t nb3 = src->nb[3];
  868. const enum ggml_type type = src->type;
  869. const int64_t ts = ggml_type_size(type);
  870. const int64_t bs = ggml_blck_size(type);
  871. const int64_t i1_diff = i1_high - i1_low;
  872. const char * x = src_ptr + i1_low*nb1 + i2*nb2 + i3*nb3;
  873. if (nb0 == ts && nb1 == ts*ne0/bs) {
  874. return cudaMemcpyAsync(dst_ptr, x, i1_diff*nb1, cudaMemcpyDeviceToDevice, stream);
  875. } else if (nb0 == ts) {
  876. return cudaMemcpy2DAsync(dst_ptr, ts*ne0/bs, x, nb1, ts*ne0/bs, i1_diff, cudaMemcpyDeviceToDevice, stream);
  877. } else {
  878. for (int64_t i1 = 0; i1 < i1_diff; i1++) {
  879. const void * rx = (const void *) ((const char *) x + i1*nb1);
  880. void * rd = (void *) (dst_ptr + i1*ts*ne0/bs);
  881. // pretend the row is a matrix with cols=1
  882. cudaError_t r = cudaMemcpy2DAsync(rd, ts/bs, rx, nb0, ts/bs, ne0, cudaMemcpyDeviceToDevice, stream);
  883. if (r != cudaSuccess) {
  884. return r;
  885. }
  886. }
  887. return cudaSuccess;
  888. }
  889. }
  890. static void ggml_cuda_op_mul_mat_cublas(
  891. ggml_backend_cuda_context & ctx,
  892. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const char * src0_dd_i, const float * src1_ddf_i,
  893. const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
  894. const int64_t src1_padded_row_size, cudaStream_t stream) {
  895. GGML_ASSERT(src0_dd_i != nullptr);
  896. GGML_ASSERT(src1_ddf_i != nullptr);
  897. GGML_ASSERT(dst_dd_i != nullptr);
  898. const int64_t ne00 = src0->ne[0];
  899. const int64_t ne10 = src1->ne[0];
  900. const int64_t ne0 = dst->ne[0];
  901. const int64_t row_diff = row_high - row_low;
  902. int id = ggml_cuda_get_device();
  903. // the main device has a larger memory buffer to hold the results from all GPUs
  904. // ldc == nrows of the matrix that cuBLAS writes into
  905. int64_t ldc = id == ctx.device ? ne0 : row_diff;
  906. const int compute_capability = ggml_cuda_info().devices[id].cc;
  907. if (compute_capability >= GGML_CUDA_CC_VOLTA && (src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) && ggml_is_contiguous(src0) && row_diff == src0->ne[1] && dst->op_params[0] == GGML_PREC_DEFAULT) {
  908. // convert src0 and src1 to fp16, multiply as fp16, convert dst to fp32
  909. ggml_cuda_pool_alloc<half> src0_as_f16(ctx.pool(id));
  910. if (src0->type != GGML_TYPE_F16) {
  911. const to_fp16_cuda_t to_fp16_cuda = ggml_get_to_fp16_cuda(src0->type);
  912. GGML_ASSERT(to_fp16_cuda != nullptr);
  913. size_t ne = row_diff*ne00;
  914. src0_as_f16.alloc(ne);
  915. to_fp16_cuda(src0_dd_i, src0_as_f16.get(), ne, stream);
  916. }
  917. const half * src0_ptr = src0->type == GGML_TYPE_F16 ? (const half *) src0_dd_i : src0_as_f16.get();
  918. ggml_cuda_pool_alloc<half> src1_as_f16(ctx.pool(id));
  919. if (src1->type != GGML_TYPE_F16) {
  920. const to_fp16_cuda_t to_fp16_cuda = ggml_get_to_fp16_cuda(src1->type);
  921. GGML_ASSERT(to_fp16_cuda != nullptr);
  922. size_t ne = src1_ncols*ne10;
  923. src1_as_f16.alloc(ne);
  924. to_fp16_cuda(src1_ddf_i, src1_as_f16.get(), ne, stream);
  925. }
  926. const half * src1_ptr = src1->type == GGML_TYPE_F16 ? (const half *) src1_ddf_i : src1_as_f16.get();
  927. ggml_cuda_pool_alloc<half> dst_f16(ctx.pool(id), row_diff*src1_ncols);
  928. const half alpha_f16 = 1.0f;
  929. const half beta_f16 = 0.0f;
  930. cublasComputeType_t cu_compute_type = CUBLAS_COMPUTE_16F;
  931. if (ggml_cuda_info().devices[ctx.device].cc == GGML_CUDA_CC_CDNA) {
  932. cu_compute_type = CUBLAS_COMPUTE_32F;
  933. }
  934. CUBLAS_CHECK(cublasSetStream(ctx.cublas_handle(id), stream));
  935. CUBLAS_CHECK(
  936. cublasGemmEx(ctx.cublas_handle(id), CUBLAS_OP_T, CUBLAS_OP_N,
  937. row_diff, src1_ncols, ne10,
  938. &alpha_f16, src0_ptr, CUDA_R_16F, ne00,
  939. src1_ptr, CUDA_R_16F, ne10,
  940. &beta_f16, dst_f16.get(), CUDA_R_16F, ldc,
  941. cu_compute_type,
  942. CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  943. const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(GGML_TYPE_F16);
  944. to_fp32_cuda(dst_f16.get(), dst_dd_i, row_diff*src1_ncols, stream);
  945. } else {
  946. ggml_cuda_pool_alloc<float> src0_ddq_as_f32(ctx.pool(id));
  947. ggml_cuda_pool_alloc<float> src1_ddq_as_f32(ctx.pool(id));
  948. if (src0->type != GGML_TYPE_F32) {
  949. const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(src0->type);
  950. GGML_ASSERT(to_fp32_cuda != nullptr);
  951. src0_ddq_as_f32.alloc(row_diff*ne00);
  952. to_fp32_cuda(src0_dd_i, src0_ddq_as_f32.get(), row_diff*ne00, stream);
  953. }
  954. if (src1->type != GGML_TYPE_F32) {
  955. const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(src1->type);
  956. GGML_ASSERT(to_fp32_cuda != nullptr);
  957. src1_ddq_as_f32.alloc(src1_ncols*ne10);
  958. to_fp32_cuda(src1_ddf_i, src1_ddq_as_f32.get(), src1_ncols*ne10, stream);
  959. }
  960. const float * src0_ddf_i = src0->type == GGML_TYPE_F32 ? (const float *) src0_dd_i : src0_ddq_as_f32.get();
  961. const float * src1_ddf1_i = src1->type == GGML_TYPE_F32 ? (const float *) src1_ddf_i : src1_ddq_as_f32.get();
  962. const float alpha = 1.0f;
  963. const float beta = 0.0f;
  964. CUBLAS_CHECK(cublasSetStream(ctx.cublas_handle(id), stream));
  965. CUBLAS_CHECK(
  966. cublasSgemm(ctx.cublas_handle(id), CUBLAS_OP_T, CUBLAS_OP_N,
  967. row_diff, src1_ncols, ne10,
  968. &alpha, src0_ddf_i, ne00,
  969. src1_ddf1_i, ne10,
  970. &beta, dst_dd_i, ldc));
  971. }
  972. GGML_UNUSED(dst);
  973. GGML_UNUSED(src1_ddq_i);
  974. GGML_UNUSED(src1_padded_row_size);
  975. }
  976. static void ggml_cuda_set_peer_access(const int n_tokens, int main_device) {
  977. static bool peer_access_enabled = false;
  978. const bool enable_peer_access = n_tokens <= GGML_CUDA_PEER_MAX_BATCH_SIZE;
  979. if (peer_access_enabled == enable_peer_access) {
  980. return;
  981. }
  982. #ifdef NDEBUG
  983. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  984. ggml_cuda_set_device(id);
  985. CUDA_CHECK(cudaDeviceSynchronize());
  986. }
  987. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  988. ggml_cuda_set_device(id);
  989. for (int id_other = 0; id_other < ggml_backend_cuda_get_device_count(); ++id_other) {
  990. if (id == id_other) {
  991. continue;
  992. }
  993. if (id != main_device && id_other != main_device) {
  994. continue;
  995. }
  996. int can_access_peer;
  997. CUDA_CHECK(cudaDeviceCanAccessPeer(&can_access_peer, id, id_other));
  998. if (can_access_peer) {
  999. if (enable_peer_access) {
  1000. cudaError_t err = cudaDeviceEnablePeerAccess(id_other, 0);
  1001. if (err != cudaErrorPeerAccessAlreadyEnabled) {
  1002. CUDA_CHECK(err);
  1003. } else {
  1004. // reset the error
  1005. cudaGetLastError();
  1006. }
  1007. } else {
  1008. cudaError_t err = cudaDeviceDisablePeerAccess(id_other);
  1009. if (err != cudaErrorPeerAccessNotEnabled) {
  1010. CUDA_CHECK(err);
  1011. } else {
  1012. // reset the error
  1013. cudaGetLastError();
  1014. }
  1015. }
  1016. }
  1017. }
  1018. }
  1019. ggml_cuda_set_device(main_device);
  1020. #endif // NDEBUG
  1021. peer_access_enabled = enable_peer_access;
  1022. GGML_UNUSED(main_device);
  1023. }
  1024. static cudaError_t ggml_cuda_Memcpy2DPeerAsync(
  1025. void * dst, int dstDevice, size_t dpitch, void * src, int srcDevice, size_t spitch, size_t width, size_t height, cudaStream_t stream) {
  1026. #if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
  1027. // cudaMemcpy2DAsync may fail with copies between vmm pools of different devices
  1028. cudaMemcpy3DPeerParms p = {};
  1029. p.dstDevice = dstDevice;
  1030. p.dstPtr = make_cudaPitchedPtr(dst, dpitch, dpitch, height);
  1031. p.srcDevice = srcDevice;
  1032. p.srcPtr = make_cudaPitchedPtr(src, spitch, spitch, height);
  1033. p.extent = make_cudaExtent(width, height, 1);
  1034. return cudaMemcpy3DPeerAsync(&p, stream);
  1035. #else
  1036. // HIP does not support cudaMemcpy3DPeerAsync or vmm pools
  1037. GGML_UNUSED(dstDevice);
  1038. GGML_UNUSED(srcDevice);
  1039. return cudaMemcpy2DAsync(dst, dpitch, src, spitch, width, height, cudaMemcpyDeviceToDevice, stream);
  1040. #endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
  1041. }
  1042. static void ggml_cuda_op_mul_mat(
  1043. ggml_backend_cuda_context & ctx,
  1044. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, ggml_cuda_op_mul_mat_t op,
  1045. quantize_cuda_t quantize_src1) {
  1046. const int64_t ne00 = src0->ne[0];
  1047. const int64_t ne01 = src0->ne[1];
  1048. const int64_t ne02 = src0->ne[2];
  1049. const int64_t ne03 = src0->ne[3];
  1050. const int64_t ne10 = src1->ne[0];
  1051. const int64_t ne11 = src1->ne[1];
  1052. const int64_t ne12 = src1->ne[2];
  1053. const int64_t ne13 = src1->ne[3];
  1054. const int64_t nrows1 = ggml_nrows(src1);
  1055. GGML_ASSERT(ne03 == ne13);
  1056. const int64_t ne0 = dst->ne[0];
  1057. const int64_t ne1 = dst->ne[1];
  1058. const int64_t nb2 = dst->nb[2];
  1059. const int64_t nb3 = dst->nb[3];
  1060. GGML_ASSERT(ggml_backend_buffer_is_cuda(dst->buffer));
  1061. GGML_ASSERT(ggml_backend_buffer_is_cuda(src1->buffer));
  1062. ggml_backend_cuda_buffer_context * src1_ctx = (ggml_backend_cuda_buffer_context *) src1->buffer->context;
  1063. ggml_backend_cuda_buffer_context * dst_ctx = (ggml_backend_cuda_buffer_context *) dst->buffer->context;
  1064. GGML_ASSERT(src1->type == GGML_TYPE_F32 || (src1->ne[2] == 1 && src1->ne[3] == 1));
  1065. GGML_ASSERT(ne12 >= ne02 && ne12 % ne02 == 0);
  1066. const int64_t i02_divisor = ne12 / ne02;
  1067. const size_t src0_ts = ggml_type_size(src0->type);
  1068. const size_t src0_bs = ggml_blck_size(src0->type);
  1069. const size_t q8_1_ts = sizeof(block_q8_1);
  1070. const size_t q8_1_bs = QK8_1;
  1071. const bool src0_is_contiguous = ggml_is_contiguous(src0);
  1072. const bool src1_is_contiguous = ggml_is_contiguous(src1);
  1073. const int64_t src1_padded_col_size = GGML_PAD(ne10, MATRIX_ROW_PADDING);
  1074. const bool split = ggml_backend_buft_is_cuda_split(src0->buffer->buft);
  1075. GGML_ASSERT(!(split && ne02 > 1));
  1076. GGML_ASSERT(!(split && ne03 > 1));
  1077. GGML_ASSERT(!(split && ne02 < ne12));
  1078. ggml_tensor_extra_gpu * src0_extra = split ? (ggml_tensor_extra_gpu *) src0->extra : nullptr;
  1079. std::array<float, GGML_CUDA_MAX_DEVICES> tensor_split;
  1080. if (split) {
  1081. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *) src0->buffer->buft->context;
  1082. tensor_split = buft_ctx->tensor_split;
  1083. }
  1084. struct dev_data {
  1085. int cc;
  1086. ggml_cuda_pool_alloc<char> src0_dd_alloc;
  1087. ggml_cuda_pool_alloc<float> src1_ddf_alloc;
  1088. ggml_cuda_pool_alloc<char> src1_ddq_alloc;
  1089. ggml_cuda_pool_alloc<float> dst_dd_alloc;
  1090. char * src0_dd = nullptr;
  1091. float * src1_ddf = nullptr; // float
  1092. char * src1_ddq = nullptr; // q8_1
  1093. float * dst_dd = nullptr;
  1094. int64_t row_low;
  1095. int64_t row_high;
  1096. };
  1097. dev_data dev[GGML_CUDA_MAX_DEVICES];
  1098. int used_devices = 0;
  1099. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  1100. dev[id].cc = ggml_cuda_info().devices[id].cc;
  1101. // by default, use all rows
  1102. dev[id].row_low = 0;
  1103. dev[id].row_high = ne01;
  1104. // for multi GPU, get the row boundaries from tensor split
  1105. // and round to mul_mat_q tile sizes
  1106. if (split) {
  1107. const int64_t rounding = get_row_rounding(tensor_split);
  1108. if (id != 0) {
  1109. dev[id].row_low = ne01*tensor_split[id];
  1110. if (dev[id].row_low < ne01) {
  1111. dev[id].row_low -= dev[id].row_low % rounding;
  1112. }
  1113. }
  1114. if (id != ggml_backend_cuda_get_device_count() - 1) {
  1115. dev[id].row_high = ne01*tensor_split[id + 1];
  1116. if (dev[id].row_high < ne01) {
  1117. dev[id].row_high -= dev[id].row_high % rounding;
  1118. }
  1119. }
  1120. }
  1121. }
  1122. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  1123. if ((!split && id != ctx.device) || dev[id].row_low == dev[id].row_high) {
  1124. continue;
  1125. }
  1126. used_devices++;
  1127. const bool src1_on_device = id == src1_ctx->device;
  1128. const bool dst_on_device = id == dst_ctx->device;
  1129. ggml_cuda_set_device(id);
  1130. cudaStream_t stream = ctx.stream(id, 0);
  1131. if (src0_is_contiguous) {
  1132. dev[id].src0_dd = split ? (char *) src0_extra->data_device[id] : (char *) src0->data;
  1133. } else {
  1134. // If src0 is not contiguous it will be copied to a temporary buffer.
  1135. // This buffer needs to be cleared entirely because multiple regions will function as padding.
  1136. const size_t nbytes_data = ggml_nbytes(src0);
  1137. const size_t nbytes_padding = ggml_row_size(src0->type, MATRIX_ROW_PADDING - ne00 % MATRIX_ROW_PADDING);
  1138. dev[id].src0_dd = dev[id].src0_dd_alloc.alloc(ctx.pool(id), nbytes_data + nbytes_padding);
  1139. // TODO: remove this for MUSA once the Guilty Lockup issue is resolved
  1140. #ifndef GGML_USE_MUSA
  1141. CUDA_CHECK(cudaMemsetAsync(dev[id].src0_dd, 0, nbytes_data + nbytes_padding, stream));
  1142. #else // GGML_USE_MUSA
  1143. CUDA_CHECK(cudaMemsetAsync(dev[id].src0_dd + nbytes_data, 0, nbytes_padding, stream));
  1144. #endif // !GGML_USE_MUSA
  1145. }
  1146. // If src0 is on a temporary compute buffer (partial offloading) there may be some padding that needs to be cleared:
  1147. if (ne00 % MATRIX_ROW_PADDING != 0 && ggml_is_quantized(src0->type) && ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && src0->view_src == nullptr) {
  1148. const size_t nbytes_data = ggml_row_size(src0->type, (dev[id].row_high - dev[id].row_low)*ne00);
  1149. const size_t nbytes_padding = ggml_row_size(src0->type, MATRIX_ROW_PADDING - ne00 % MATRIX_ROW_PADDING);
  1150. CUDA_CHECK(cudaMemsetAsync(dev[id].src0_dd + nbytes_data, 0, nbytes_padding, stream));
  1151. }
  1152. if (src1_on_device && src1_is_contiguous) {
  1153. dev[id].src1_ddf = (float *) src1->data;
  1154. } else {
  1155. dev[id].src1_ddf = dev[id].src1_ddf_alloc.alloc(ctx.pool(id), ggml_nelements(src1));
  1156. }
  1157. if (quantize_src1) {
  1158. size_t src_1_ddq_size = nrows1*src1_padded_col_size*q8_1_ts/q8_1_bs;
  1159. if (quantize_src1 == quantize_mmq_q8_1_cuda) {
  1160. src_1_ddq_size += get_mmq_x_max_host(dev[id].cc)*sizeof(block_q8_1_mmq);
  1161. }
  1162. dev[id].src1_ddq = dev[id].src1_ddq_alloc.alloc(ctx.pool(id), src_1_ddq_size);
  1163. if (src1_on_device && src1_is_contiguous) {
  1164. quantize_src1(dev[id].src1_ddf, dev[id].src1_ddq, ne10, ne11, ne12*ne13, src1_padded_col_size, src0->type, stream);
  1165. CUDA_CHECK(cudaGetLastError());
  1166. }
  1167. }
  1168. if (dst_on_device) {
  1169. dev[id].dst_dd = (float *) dst->data;
  1170. } else {
  1171. const size_t size_dst_ddf = split ? (dev[id].row_high - dev[id].row_low)*ne1 : ggml_nelements(dst);
  1172. dev[id].dst_dd = dev[id].dst_dd_alloc.alloc(ctx.pool(id), size_dst_ddf);
  1173. }
  1174. }
  1175. // if multiple devices are used they need to wait for the main device
  1176. // here an event is recorded that signals that the main device has finished calculating the input data
  1177. if (split && used_devices > 1) {
  1178. ggml_cuda_set_device(ctx.device);
  1179. CUDA_CHECK(cudaEventRecord(src0_extra->events[ctx.device][0], ctx.stream()));
  1180. }
  1181. const int64_t src1_col_stride = split && used_devices > 1 ? MUL_MAT_SRC1_COL_STRIDE : ne11;
  1182. for (int64_t src1_col_0 = 0; src1_col_0 < ne11; src1_col_0 += src1_col_stride) {
  1183. const int64_t is = split ? (src1_col_0/src1_col_stride) % GGML_CUDA_MAX_STREAMS : 0;
  1184. const int64_t src1_ncols = src1_col_0 + src1_col_stride > ne11 ? ne11 - src1_col_0 : src1_col_stride;
  1185. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  1186. if ((!split && id != ctx.device) || dev[id].row_low == dev[id].row_high) {
  1187. continue;
  1188. }
  1189. const bool src1_on_device = id == src1_ctx->device;
  1190. const bool dst_on_device = id == dst_ctx->device;
  1191. const int64_t row_diff = dev[id].row_high - dev[id].row_low;
  1192. ggml_cuda_set_device(id);
  1193. cudaStream_t stream = ctx.stream(id, is);
  1194. // wait for main GPU data if necessary
  1195. if (split && (id != ctx.device || is != 0)) {
  1196. CUDA_CHECK(cudaStreamWaitEvent(stream, src0_extra->events[ctx.device][0], 0));
  1197. }
  1198. for (int64_t i0 = 0; i0 < ne13*ne12; ++i0) {
  1199. const int64_t i03 = i0 / ne12;
  1200. const int64_t i02 = i0 % ne12;
  1201. size_t src1_ddq_i_offset = i0*ne11 * src1_padded_col_size*q8_1_ts/q8_1_bs;
  1202. if (quantize_src1 == quantize_mmq_q8_1_cuda) {
  1203. src1_ddq_i_offset += src1_col_0 * sizeof(block_q8_1_mmq);
  1204. } else {
  1205. src1_ddq_i_offset += src1_col_0 * src1_padded_col_size*q8_1_ts/q8_1_bs;
  1206. }
  1207. // for split tensors the data begins at i0 == i0_offset_low
  1208. char * src0_dd_i = dev[id].src0_dd + (i0/i02_divisor) * (ne01*ne00*src0_ts)/src0_bs;
  1209. float * src1_ddf_i = dev[id].src1_ddf + (i0*ne11 + src1_col_0) * ne10;
  1210. char * src1_ddq_i = dev[id].src1_ddq + src1_ddq_i_offset;
  1211. float * dst_dd_i = dev[id].dst_dd + (i0*ne1 + src1_col_0) * (dst_on_device ? ne0 : row_diff);
  1212. // the main device memory buffer can be on VRAM scratch, with space for all partial results
  1213. // in that case an offset on dst_ddf_i is needed
  1214. if (id == ctx.device) {
  1215. dst_dd_i += dev[id].row_low; // offset is 0 if no tensor split
  1216. }
  1217. // copy src0, src1 to device if necessary
  1218. if (src1_is_contiguous) {
  1219. if (id != ctx.device) {
  1220. if (quantize_src1) {
  1221. char * src1_ddq_i_source = dev[ctx.device].src1_ddq + src1_ddq_i_offset;
  1222. if (quantize_src1 == quantize_mmq_q8_1_cuda) {
  1223. const size_t pitch = ne11*sizeof(block_q8_1_mmq);
  1224. const size_t width = src1_ncols*sizeof(block_q8_1_mmq);
  1225. const size_t height = src1_padded_col_size/(4*QK8_1);
  1226. CUDA_CHECK(ggml_cuda_Memcpy2DPeerAsync(src1_ddq_i, id, pitch, src1_ddq_i_source, ctx.device, pitch, width, height, stream));
  1227. } else {
  1228. CUDA_CHECK(cudaMemcpyPeerAsync(
  1229. src1_ddq_i, id, src1_ddq_i_source, ctx.device, src1_ncols*src1_padded_col_size*q8_1_ts/q8_1_bs, stream));
  1230. }
  1231. } else {
  1232. float * src1_ddf_i_source = (float *) src1->data;
  1233. src1_ddf_i_source += (i0*ne11 + src1_col_0) * ne10;
  1234. CUDA_CHECK(cudaMemcpyPeerAsync(src1_ddf_i, id, src1_ddf_i_source, ctx.device,
  1235. src1_ncols*ne10*sizeof(float), stream));
  1236. }
  1237. }
  1238. } else if (src1_on_device && !src1_is_contiguous) {
  1239. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(
  1240. src1_ddf_i, src1, i03, i02, src1_col_0, src1_col_0+src1_ncols, stream));
  1241. } else {
  1242. GGML_ABORT("fatal error");
  1243. }
  1244. if (quantize_src1 && !src1_is_contiguous) {
  1245. quantize_src1(src1_ddf_i, src1_ddq_i, ne10, src1_ncols, 1, src1_padded_col_size, src0->type, stream);
  1246. CUDA_CHECK(cudaGetLastError());
  1247. }
  1248. if (src1_col_0 == 0 && !src0_is_contiguous && i02 % i02_divisor == 0) {
  1249. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(src0_dd_i, src0, i03, i02/i02_divisor, dev[id].row_low, dev[id].row_high, stream));
  1250. }
  1251. // do the computation
  1252. op(ctx, src0, src1, dst, src0_dd_i, src1_ddf_i, src1_ddq_i, dst_dd_i,
  1253. dev[id].row_low, dev[id].row_high, src1_ncols, src1_padded_col_size, stream);
  1254. CUDA_CHECK(cudaGetLastError());
  1255. // copy dst to host or other device if necessary
  1256. if (!dst_on_device) {
  1257. void * dst_off_device = dst->data;
  1258. if (split) {
  1259. // src0 = weight matrix is saved as a transposed matrix for better memory layout.
  1260. // dst is NOT transposed.
  1261. // The outputs of matrix matrix multiplications can therefore NOT simply be concatenated for >1 GPU.
  1262. // Instead they need to be copied to the correct slice in ne0 = dst row index.
  1263. // If dst is a vector with ne0 == 1 then you don't have to do this but it still produces correct results.
  1264. float * dhf_dst_i = (float *) ((char *) dst_off_device + i02*nb2 + i03*nb3);
  1265. GGML_ASSERT(dst->nb[1] == ne0*sizeof(float));
  1266. dhf_dst_i += src1_col_0*ne0 + dev[id].row_low;
  1267. CUDA_CHECK(ggml_cuda_Memcpy2DPeerAsync(
  1268. dhf_dst_i, ctx.device, ne0*sizeof(float), dst_dd_i, id, row_diff*sizeof(float), row_diff*sizeof(float), src1_ncols, stream));
  1269. } else {
  1270. float * dhf_dst_i = (float *) ((char *) dst_off_device + i02*nb2 + i03*nb3);
  1271. GGML_ASSERT(dst->nb[1] == ne0*sizeof(float));
  1272. dhf_dst_i += src1_col_0*ne0;
  1273. CUDA_CHECK(cudaMemcpyAsync(dhf_dst_i, dst_dd_i, src1_ncols*ne0*sizeof(float), cudaMemcpyDeviceToDevice, stream));
  1274. }
  1275. }
  1276. // add event for the main device to wait on until other device is done
  1277. if (split && (id != ctx.device || is != 0)) {
  1278. CUDA_CHECK(cudaEventRecord(src0_extra->events[id][is], stream));
  1279. }
  1280. }
  1281. }
  1282. }
  1283. // main device waits for all other devices to be finished
  1284. if (split && ggml_backend_cuda_get_device_count() > 1) {
  1285. int64_t is_max = (ne11 + MUL_MAT_SRC1_COL_STRIDE - 1) / MUL_MAT_SRC1_COL_STRIDE;
  1286. is_max = is_max <= GGML_CUDA_MAX_STREAMS ? is_max : GGML_CUDA_MAX_STREAMS;
  1287. ggml_cuda_set_device(ctx.device);
  1288. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  1289. if (dev[id].row_low == dev[id].row_high) {
  1290. continue;
  1291. }
  1292. for (int64_t is = 0; is < is_max; ++is) {
  1293. CUDA_CHECK(cudaStreamWaitEvent(ctx.stream(), src0_extra->events[id][is], 0));
  1294. }
  1295. }
  1296. }
  1297. }
  1298. static __global__ void k_compute_batched_ptrs(
  1299. const half * src0_as_f16, const half * src1_as_f16, char * dst,
  1300. const void ** ptrs_src, void ** ptrs_dst,
  1301. int64_t ne12, int64_t ne13,
  1302. int64_t ne23,
  1303. size_t nb02, size_t nb03,
  1304. size_t nb12, size_t nb13,
  1305. size_t nbd2, size_t nbd3,
  1306. int64_t r2, int64_t r3) {
  1307. int64_t i13 = blockIdx.x * blockDim.x + threadIdx.x;
  1308. int64_t i12 = blockIdx.y * blockDim.y + threadIdx.y;
  1309. if (i13 >= ne13 || i12 >= ne12) {
  1310. return;
  1311. }
  1312. int64_t i03 = i13 / r3;
  1313. int64_t i02 = i12 / r2;
  1314. ptrs_src[0*ne23 + i12 + i13*ne12] = (const char *) src0_as_f16 + i02*nb02 + i03*nb03;
  1315. ptrs_src[1*ne23 + i12 + i13*ne12] = (const char *) src1_as_f16 + i12*nb12 + i13*nb13;
  1316. ptrs_dst[0*ne23 + i12 + i13*ne12] = ( char *) dst + i12*nbd2 + i13*nbd3;
  1317. }
  1318. static void ggml_cuda_mul_mat_batched_cublas(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1319. GGML_ASSERT(!ggml_is_transposed(src0));
  1320. GGML_ASSERT(!ggml_is_transposed(src1));
  1321. GGML_ASSERT(ggml_backend_buffer_is_cuda(src0->buffer));
  1322. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  1323. GGML_TENSOR_BINARY_OP_LOCALS
  1324. const int64_t ne_dst = ggml_nelements(dst);
  1325. cudaStream_t main_stream = ctx.stream();
  1326. CUBLAS_CHECK(cublasSetStream(ctx.cublas_handle(), main_stream));
  1327. void * src0_ddq = src0->data;
  1328. half * src0_f16 = (half *) src0_ddq;
  1329. float * src1_ddf = (float *) src1->data;
  1330. float * dst_ddf = (float *) dst->data;
  1331. // convert src1 to fp16
  1332. ggml_cuda_pool_alloc<half> src1_f16_alloc(ctx.pool());
  1333. if (src1->type != GGML_TYPE_F16) {
  1334. const to_fp16_cuda_t to_fp16_cuda = ggml_get_to_fp16_cuda(src1->type);
  1335. const int64_t ne_src1 = ggml_nelements(src1);
  1336. src1_f16_alloc.alloc(ne_src1);
  1337. GGML_ASSERT(to_fp16_cuda != nullptr);
  1338. to_fp16_cuda(src1_ddf, src1_f16_alloc.get(), ne_src1, main_stream);
  1339. }
  1340. half * src1_f16 = src1->type == GGML_TYPE_F16 ? (half *) src1_ddf : src1_f16_alloc.get();
  1341. ggml_cuda_pool_alloc<half> dst_f16(ctx.pool());
  1342. char * dst_t;
  1343. cublasComputeType_t cu_compute_type = CUBLAS_COMPUTE_16F;
  1344. cudaDataType_t cu_data_type = CUDA_R_16F;
  1345. if (ggml_cuda_info().devices[ctx.device].cc == GGML_CUDA_CC_CDNA) {
  1346. cu_compute_type = CUBLAS_COMPUTE_32F;
  1347. }
  1348. // dst strides
  1349. size_t nbd2 = dst->nb[2];
  1350. size_t nbd3 = dst->nb[3];
  1351. const half alpha_f16 = 1.0f;
  1352. const half beta_f16 = 0.0f;
  1353. const float alpha_f32 = 1.0f;
  1354. const float beta_f32 = 0.0f;
  1355. const void * alpha = &alpha_f16;
  1356. const void * beta = &beta_f16;
  1357. if (dst->op_params[0] == GGML_PREC_DEFAULT) {
  1358. dst_t = (char *) dst_f16.alloc(ne_dst);
  1359. nbd2 /= sizeof(float) / sizeof(half);
  1360. nbd3 /= sizeof(float) / sizeof(half);
  1361. } else {
  1362. dst_t = (char *) dst_ddf;
  1363. cu_compute_type = CUBLAS_COMPUTE_32F;
  1364. cu_data_type = CUDA_R_32F;
  1365. alpha = &alpha_f32;
  1366. beta = &beta_f32;
  1367. }
  1368. GGML_ASSERT(ne12 % ne02 == 0);
  1369. GGML_ASSERT(ne13 % ne03 == 0);
  1370. // broadcast factors
  1371. const int64_t r2 = ne12/ne02;
  1372. const int64_t r3 = ne13/ne03;
  1373. #if 0
  1374. // use cublasGemmEx
  1375. {
  1376. for (int i13 = 0; i13 < ne13; ++i13) {
  1377. for (int i12 = 0; i12 < ne12; ++i12) {
  1378. int i03 = i13 / r3;
  1379. int i02 = i12 / r2;
  1380. CUBLAS_CHECK(
  1381. cublasGemmEx(g_cublas_handles[g_main_device], CUBLAS_OP_T, CUBLAS_OP_N,
  1382. ne01, ne11, ne10,
  1383. alpha, (const char *) src0_as_f16 + i02*src0->nb[2] + i03*src0->nb[3] , CUDA_R_16F, nb01/sizeof(half),
  1384. (const char *) src1_as_f16 + i12*src1->nb[2]/2 + i13*src1->nb[3]/2, CUDA_R_16F, nb11/sizeof(float),
  1385. beta, ( char *) dst_t + i12*nbd2 + i13*nbd3, cu_data_type, ne01,
  1386. cu_compute_type,
  1387. CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  1388. }
  1389. }
  1390. }
  1391. #else
  1392. #ifdef GGML_USE_MUSA
  1393. GGML_ASSERT(false);
  1394. #else // !GGML_USE_MUSA
  1395. if (r2 == 1 && r3 == 1 && ggml_is_contiguous_2(src0) && ggml_is_contiguous_2(src1)) {
  1396. // there is no broadcast and src0, src1 are contiguous across dims 2, 3
  1397. // use cublasGemmStridedBatchedEx
  1398. CUBLAS_CHECK(
  1399. cublasGemmStridedBatchedEx(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N,
  1400. ne01, ne11, ne10,
  1401. alpha, (const char *) src0_f16, CUDA_R_16F, nb01/nb00, nb02/nb00, // strideA
  1402. (const char *) src1_f16, CUDA_R_16F, nb11/nb10, nb12/nb10, // strideB
  1403. beta, ( char *) dst_t, cu_data_type, ne01, nb2/nb0, // strideC
  1404. ne12*ne13,
  1405. cu_compute_type,
  1406. CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  1407. } else {
  1408. // use cublasGemmBatchedEx
  1409. const int ne23 = ne12*ne13;
  1410. ggml_cuda_pool_alloc<const void *> ptrs_src(ctx.pool(), 2*ne23);
  1411. ggml_cuda_pool_alloc< void *> ptrs_dst(ctx.pool(), 1*ne23);
  1412. dim3 block_dims(ne13, ne12);
  1413. k_compute_batched_ptrs<<<1, block_dims, 0, main_stream>>>(
  1414. src0_f16, src1_f16, dst_t,
  1415. ptrs_src.get(), ptrs_dst.get(),
  1416. ne12, ne13,
  1417. ne23,
  1418. nb02, nb03,
  1419. src1->type == GGML_TYPE_F16 ? nb12 : nb12/2,
  1420. src1->type == GGML_TYPE_F16 ? nb13 : nb13/2,
  1421. nbd2, nbd3,
  1422. r2, r3);
  1423. CUDA_CHECK(cudaGetLastError());
  1424. CUBLAS_CHECK(
  1425. cublasGemmBatchedEx(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N,
  1426. ne01, ne11, ne10,
  1427. alpha, (const void **) (ptrs_src.get() + 0*ne23), CUDA_R_16F, nb01/nb00,
  1428. (const void **) (ptrs_src.get() + 1*ne23), CUDA_R_16F, nb11/nb10,
  1429. beta, ( void **) (ptrs_dst.get() + 0*ne23), cu_data_type, ne01,
  1430. ne23,
  1431. cu_compute_type,
  1432. CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  1433. }
  1434. #endif // GGML_USE_MUSA
  1435. #endif
  1436. if (dst->op_params[0] == GGML_PREC_DEFAULT) {
  1437. const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(GGML_TYPE_F16);
  1438. to_fp32_cuda(dst_f16.get(), dst_ddf, ne_dst, main_stream);
  1439. }
  1440. }
  1441. static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1442. const bool split = ggml_backend_buft_is_cuda_split(src0->buffer->buft);
  1443. bool use_mul_mat_vec = (src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16)
  1444. && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32
  1445. && src0->ne[0] % 2 == 0 && src1->ne[1] == 1;
  1446. bool use_mul_mat_vec_q = ggml_is_quantized(src0->type)
  1447. && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32
  1448. && src1->ne[1] <= MMVQ_MAX_BATCH_SIZE;
  1449. bool use_mul_mat_q = ggml_is_quantized(src0->type)
  1450. && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32;
  1451. bool any_gpus_with_slow_fp16 = false;
  1452. bool any_gpus_without_fp16_mma = false;
  1453. if (split) {
  1454. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *) src0->buffer->buft->context;
  1455. auto & tensor_split = buft_ctx->tensor_split;
  1456. for (int id = 0; id < ggml_backend_cuda_get_device_count(); ++id) {
  1457. // skip devices that are not going to do any work:
  1458. if (tensor_split[id] >= (id + 1 < ggml_backend_cuda_get_device_count() ? tensor_split[id + 1] : 1.0f)) {
  1459. continue;
  1460. }
  1461. const int cc = ggml_cuda_info().devices[id].cc;
  1462. use_mul_mat_q = use_mul_mat_q && ggml_cuda_should_use_mmq(src0->type, cc, src1->ne[1]);
  1463. any_gpus_with_slow_fp16 = any_gpus_with_slow_fp16 || !fast_fp16_available(cc);
  1464. any_gpus_without_fp16_mma = any_gpus_without_fp16_mma || !fp16_mma_available(cc);
  1465. }
  1466. } else {
  1467. const int cc = ggml_cuda_info().devices[ctx.device].cc;
  1468. use_mul_mat_q = use_mul_mat_q && ggml_cuda_should_use_mmq(src0->type, cc, src1->ne[1]);
  1469. any_gpus_with_slow_fp16 = any_gpus_with_slow_fp16 || !fast_fp16_available(cc);
  1470. any_gpus_without_fp16_mma = any_gpus_without_fp16_mma || !fp16_mma_available(cc);
  1471. }
  1472. // debug helpers
  1473. //printf("src0: %8d %8d %8d %8d\n", src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3]);
  1474. //printf(" %8d %8d %8d %8d\n", src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3]);
  1475. //printf("src1: %8d %8d %8d %8d\n", src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3]);
  1476. //printf(" %8d %8d %8d %8d\n", src1->nb[0], src1->nb[1], src1->nb[2], src1->nb[3]);
  1477. //printf("src0 is contiguous %d, transposed %d, type = %s, name = %s\n", ggml_is_contiguous(src0), ggml_is_transposed(src0), ggml_type_name(src0->type), src0->name);
  1478. //printf("src1 is contiguous %d, transposed %d, type = %s, name = %s\n", ggml_is_contiguous(src1), ggml_is_transposed(src1), ggml_type_name(src1->type), src1->name);
  1479. if (!split && use_mul_mat_vec && dst->ne[3] == 1 && (src0->ne[1] < MMV_MAX_ROWS || any_gpus_without_fp16_mma)) {
  1480. // the custom F16 vector kernel can be used over batched cuBLAS GEMM
  1481. // but this is only faster for GPUs without tensor cores or with a thin src0 matrix (particularly KQV in attention)
  1482. ggml_cuda_mul_mat_vec(ctx, src0, src1, dst);
  1483. } else if (!split && src0->type == GGML_TYPE_F16 && (src1->type == GGML_TYPE_F16 || !any_gpus_with_slow_fp16)
  1484. && !ggml_is_transposed(src0) && !ggml_is_transposed(src1) && src1->ne[2]*src1->ne[3] > 1) {
  1485. // general KQ + KQV multi-batch without FlashAttention
  1486. ggml_cuda_mul_mat_batched_cublas(ctx, src0, src1, dst);
  1487. } else if (use_mul_mat_vec) {
  1488. ggml_cuda_op_mul_mat(ctx, src0, src1, dst, ggml_cuda_op_mul_mat_vec, nullptr);
  1489. } else if (use_mul_mat_vec_q) {
  1490. ggml_cuda_op_mul_mat(ctx, src0, src1, dst, ggml_cuda_op_mul_mat_vec_q, quantize_row_q8_1_cuda);
  1491. } else if (use_mul_mat_q) {
  1492. ggml_cuda_op_mul_mat(ctx, src0, src1, dst, ggml_cuda_op_mul_mat_q, quantize_mmq_q8_1_cuda);
  1493. } else {
  1494. ggml_cuda_op_mul_mat(ctx, src0, src1, dst, ggml_cuda_op_mul_mat_cublas, nullptr);
  1495. }
  1496. }
  1497. struct mmid_row_mapping {
  1498. int32_t i1;
  1499. int32_t i2;
  1500. };
  1501. static __global__ void k_copy_src1_to_contiguous(const char * __restrict__ src1_original, char * __restrict__ src1_contiguous,
  1502. int * __restrict__ cur_src1_row, mmid_row_mapping * __restrict__ row_mapping,
  1503. const char * __restrict ids, int64_t i02, size_t ids_nb1, size_t ids_nb0,
  1504. int64_t ne11, int64_t ne10,
  1505. size_t nb11, size_t nb12) {
  1506. int32_t iid1 = blockIdx.x;
  1507. int32_t id = blockIdx.y;
  1508. const int32_t row_id_i = *(const int32_t *) (ids + iid1*ids_nb1 + id*ids_nb0);
  1509. if (row_id_i != i02) {
  1510. return;
  1511. }
  1512. const int64_t i11 = id % ne11;
  1513. const int64_t i12 = iid1;
  1514. __shared__ int src1_row;
  1515. if (threadIdx.x == 0) {
  1516. src1_row = atomicAdd(cur_src1_row, 1);
  1517. row_mapping[src1_row] = {id, iid1};
  1518. }
  1519. __syncthreads();
  1520. const float * src1_row_original = (const float *)(src1_original + i11*nb11 + i12*nb12);
  1521. float * src1_row_contiguous = (float *)(src1_contiguous + src1_row*nb11);
  1522. for (int i = threadIdx.x; i < ne10; i += blockDim.x) {
  1523. src1_row_contiguous[i] = src1_row_original[i];
  1524. }
  1525. }
  1526. static __global__ void k_copy_dst_from_contiguous(char * __restrict__ dst_original, const char * __restrict__ dst_contiguous,
  1527. const mmid_row_mapping * __restrict__ row_mapping,
  1528. int64_t ne0,
  1529. size_t nb1, size_t nb2) {
  1530. int32_t i = blockIdx.x;
  1531. const int32_t i1 = row_mapping[i].i1;
  1532. const int32_t i2 = row_mapping[i].i2;
  1533. const float * dst_row_contiguous = (const float *)(dst_contiguous + i*nb1);
  1534. float * dst_row_original = (float *)(dst_original + i1*nb1 + i2*nb2);
  1535. for (int j = threadIdx.x; j < ne0; j += blockDim.x) {
  1536. dst_row_original[j] = dst_row_contiguous[j];
  1537. }
  1538. }
  1539. static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
  1540. const ggml_tensor * src0 = dst->src[0];
  1541. const ggml_tensor * src1 = dst->src[1];
  1542. const ggml_tensor * ids = dst->src[2];
  1543. GGML_TENSOR_BINARY_OP_LOCALS
  1544. GGML_ASSERT(!ggml_backend_buft_is_cuda_split(src0->buffer->buft) && "mul_mat_id does not support split buffers");
  1545. cudaStream_t stream = ctx.stream();
  1546. const int64_t n_as = ne02;
  1547. const int64_t n_ids = ids->ne[0];
  1548. std::vector<char> ids_host(ggml_nbytes(ids));
  1549. const char * ids_dev = (const char *) ids->data;
  1550. CUDA_CHECK(cudaMemcpyAsync(ids_host.data(), ids_dev, ggml_nbytes(ids), cudaMemcpyDeviceToHost, stream));
  1551. CUDA_CHECK(cudaStreamSynchronize(stream));
  1552. ggml_tensor src0_row = *src0;
  1553. ggml_tensor src1_row = *src1;
  1554. ggml_tensor dst_row = *dst;
  1555. char * src0_original = (char *) src0->data;
  1556. char * src1_original = (char *) src1->data;
  1557. char * dst_original = (char *) dst->data;
  1558. src0_row.ne[2] = 1;
  1559. src0_row.ne[3] = 1;
  1560. src0_row.nb[3] = nb02;
  1561. src1_row.ne[1] = 1;
  1562. src1_row.ne[2] = 1;
  1563. src1_row.ne[3] = 1;
  1564. src1_row.nb[2] = nb11;
  1565. src1_row.nb[3] = nb11;
  1566. dst_row.ne[1] = 1;
  1567. dst_row.ne[2] = 1;
  1568. dst_row.ne[3] = 1;
  1569. dst_row.nb[2] = nb1;
  1570. dst_row.nb[3] = nb1;
  1571. if (ne12 == 1) {
  1572. for (int64_t iid1 = 0; iid1 < ids->ne[1]; iid1++) {
  1573. for (int64_t id = 0; id < n_ids; id++) {
  1574. const int32_t i02 = *(const int32_t *) (ids_host.data() + iid1*ids->nb[1] + id*ids->nb[0]);
  1575. GGML_ASSERT(i02 >= 0 && i02 < n_as);
  1576. const int64_t i11 = id % ne11;
  1577. const int64_t i12 = iid1;
  1578. const int64_t i1 = id;
  1579. const int64_t i2 = i12;
  1580. src0_row.data = src0_original + i02*nb02;
  1581. src1_row.data = src1_original + i11*nb11 + i12*nb12;
  1582. dst_row.data = dst_original + i1*nb1 + i2*nb2;
  1583. ggml_cuda_mul_mat(ctx, &src0_row, &src1_row, &dst_row);
  1584. }
  1585. }
  1586. } else {
  1587. ggml_cuda_pool_alloc<char> src1_contiguous(ctx.pool(), sizeof(float)*ggml_nelements(src1));
  1588. ggml_cuda_pool_alloc<char> dst_contiguous(ctx.pool(), sizeof(float)*ggml_nelements(dst));
  1589. src1_row.data = src1_contiguous.get();
  1590. dst_row.data = dst_contiguous.get();
  1591. for (int64_t i02 = 0; i02 < n_as; i02++) {
  1592. int64_t num_src1_rows = 0;
  1593. for (int64_t iid1 = 0; iid1 < ids->ne[1]; iid1++) {
  1594. for (int64_t id = 0; id < n_ids; id++) {
  1595. const int32_t row_id_i = *(const int32_t *) (ids_host.data() + iid1*ids->nb[1] + id*ids->nb[0]);
  1596. GGML_ASSERT(row_id_i >= 0 && row_id_i < n_as);
  1597. if (row_id_i != i02) {
  1598. continue;
  1599. }
  1600. num_src1_rows++;
  1601. }
  1602. }
  1603. if (num_src1_rows == 0) {
  1604. continue;
  1605. }
  1606. ggml_cuda_pool_alloc<int> dev_cur_src1_row(ctx.pool(), 1);
  1607. ggml_cuda_pool_alloc<mmid_row_mapping> dev_row_mapping(ctx.pool(), num_src1_rows);
  1608. CUDA_CHECK(cudaMemsetAsync(dev_cur_src1_row.get(), 0, sizeof(int), stream));
  1609. {
  1610. dim3 block_dims(std::min((unsigned int)ne10, 768u));
  1611. dim3 grid_dims(ids->ne[1], n_ids);
  1612. k_copy_src1_to_contiguous<<<grid_dims, block_dims, 0, stream>>>(
  1613. src1_original, src1_contiguous.get(),
  1614. dev_cur_src1_row.get(), dev_row_mapping.get(),
  1615. ids_dev, i02, ids->nb[1], ids->nb[0],
  1616. ne11, ne10,
  1617. nb11, nb12);
  1618. CUDA_CHECK(cudaGetLastError());
  1619. }
  1620. src0_row.data = src0_original + i02*nb02;
  1621. GGML_ASSERT(nb11 == sizeof(float)*ne10);
  1622. GGML_ASSERT(nb1 == sizeof(float)*ne0);
  1623. src1_row.ne[1] = num_src1_rows;
  1624. src1_row.nb[1] = nb11;
  1625. src1_row.nb[2] = num_src1_rows*nb11;
  1626. src1_row.nb[3] = num_src1_rows*nb11;
  1627. dst_row.ne[1] = num_src1_rows;
  1628. dst_row.nb[1] = nb1;
  1629. dst_row.nb[2] = num_src1_rows*nb1;
  1630. dst_row.nb[3] = num_src1_rows*nb1;
  1631. ggml_cuda_mul_mat(ctx, &src0_row, &src1_row, &dst_row);
  1632. {
  1633. dim3 block_dims(std::min((unsigned int)ne0, 768u));
  1634. dim3 grid_dims(num_src1_rows);
  1635. k_copy_dst_from_contiguous<<<grid_dims, block_dims, 0, stream>>>(
  1636. dst_original, dst_contiguous.get(),
  1637. dev_row_mapping.get(),
  1638. ne0,
  1639. nb1, nb2);
  1640. CUDA_CHECK(cudaGetLastError());
  1641. }
  1642. }
  1643. }
  1644. }
  1645. static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct ggml_tensor * dst) {
  1646. // why is this here instead of mul_mat?
  1647. if (dst->src[0] != nullptr && ggml_backend_buft_is_cuda_split(dst->src[0]->buffer->buft)) {
  1648. ggml_cuda_set_peer_access(dst->src[1]->ne[1], ctx.device);
  1649. }
  1650. switch (dst->op) {
  1651. case GGML_OP_ARGMAX:
  1652. ggml_cuda_argmax(ctx, dst);
  1653. break;
  1654. case GGML_OP_COUNT_EQUAL:
  1655. ggml_cuda_count_equal(ctx, dst);
  1656. break;
  1657. case GGML_OP_REPEAT:
  1658. ggml_cuda_op_repeat(ctx, dst);
  1659. break;
  1660. case GGML_OP_REPEAT_BACK:
  1661. ggml_cuda_op_repeat_back(ctx, dst);
  1662. break;
  1663. case GGML_OP_GET_ROWS:
  1664. ggml_cuda_op_get_rows(ctx, dst);
  1665. break;
  1666. case GGML_OP_DUP:
  1667. ggml_cuda_dup(ctx, dst);
  1668. break;
  1669. case GGML_OP_CPY:
  1670. ggml_cuda_cpy(ctx, dst->src[0], dst->src[1]);
  1671. break;
  1672. case GGML_OP_CONT:
  1673. ggml_cuda_dup(ctx, dst);
  1674. break;
  1675. case GGML_OP_ADD:
  1676. case GGML_OP_ADD1: // TODO: more efficient implementation
  1677. ggml_cuda_op_add(ctx, dst);
  1678. break;
  1679. case GGML_OP_SUB:
  1680. ggml_cuda_op_sub(ctx, dst);
  1681. break;
  1682. case GGML_OP_ACC:
  1683. ggml_cuda_op_acc(ctx, dst);
  1684. break;
  1685. case GGML_OP_MUL:
  1686. ggml_cuda_op_mul(ctx, dst);
  1687. break;
  1688. case GGML_OP_DIV:
  1689. ggml_cuda_op_div(ctx, dst);
  1690. break;
  1691. case GGML_OP_UNARY:
  1692. switch (ggml_get_unary_op(dst)) {
  1693. case GGML_UNARY_OP_NEG:
  1694. ggml_cuda_op_neg(ctx, dst);
  1695. break;
  1696. case GGML_UNARY_OP_STEP:
  1697. ggml_cuda_op_step(ctx, dst);
  1698. break;
  1699. case GGML_UNARY_OP_GELU:
  1700. ggml_cuda_op_gelu(ctx, dst);
  1701. break;
  1702. case GGML_UNARY_OP_SILU:
  1703. ggml_cuda_op_silu(ctx, dst);
  1704. break;
  1705. case GGML_UNARY_OP_GELU_QUICK:
  1706. ggml_cuda_op_gelu_quick(ctx, dst);
  1707. break;
  1708. case GGML_UNARY_OP_TANH:
  1709. ggml_cuda_op_tanh(ctx, dst);
  1710. break;
  1711. case GGML_UNARY_OP_RELU:
  1712. ggml_cuda_op_relu(ctx, dst);
  1713. break;
  1714. case GGML_UNARY_OP_SIGMOID:
  1715. ggml_cuda_op_sigmoid(ctx, dst);
  1716. break;
  1717. case GGML_UNARY_OP_HARDSIGMOID:
  1718. ggml_cuda_op_hardsigmoid(ctx, dst);
  1719. break;
  1720. case GGML_UNARY_OP_HARDSWISH:
  1721. ggml_cuda_op_hardswish(ctx, dst);
  1722. break;
  1723. case GGML_UNARY_OP_EXP:
  1724. ggml_cuda_op_exp(ctx, dst);
  1725. break;
  1726. default:
  1727. return false;
  1728. }
  1729. break;
  1730. case GGML_OP_NORM:
  1731. ggml_cuda_op_norm(ctx, dst);
  1732. break;
  1733. case GGML_OP_GROUP_NORM:
  1734. ggml_cuda_op_group_norm(ctx, dst);
  1735. break;
  1736. case GGML_OP_CONCAT:
  1737. ggml_cuda_op_concat(ctx, dst);
  1738. break;
  1739. case GGML_OP_UPSCALE:
  1740. ggml_cuda_op_upscale(ctx, dst);
  1741. break;
  1742. case GGML_OP_PAD:
  1743. ggml_cuda_op_pad(ctx, dst);
  1744. break;
  1745. case GGML_OP_UNPAD:
  1746. ggml_cuda_op_unpad(ctx, dst);
  1747. break;
  1748. case GGML_OP_ARANGE:
  1749. ggml_cuda_op_arange(ctx, dst);
  1750. break;
  1751. case GGML_OP_TIMESTEP_EMBEDDING:
  1752. ggml_cuda_op_timestep_embedding(ctx, dst);
  1753. break;
  1754. case GGML_OP_LEAKY_RELU:
  1755. ggml_cuda_op_leaky_relu(ctx, dst);
  1756. break;
  1757. case GGML_OP_RMS_NORM:
  1758. ggml_cuda_op_rms_norm(ctx, dst);
  1759. break;
  1760. case GGML_OP_MUL_MAT:
  1761. if (dst->src[0]->ne[3] != dst->src[1]->ne[3]) {
  1762. GGML_LOG_ERROR("%s: cannot compute %s: src0->ne[3] = %" PRId64 ", src1->ne[3] = %" PRId64 " - fallback to CPU\n", __func__, dst->name, dst->src[0]->ne[3], dst->src[1]->ne[3]);
  1763. return false;
  1764. } else {
  1765. ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst);
  1766. }
  1767. break;
  1768. case GGML_OP_MUL_MAT_ID:
  1769. ggml_cuda_mul_mat_id(ctx, dst);
  1770. break;
  1771. case GGML_OP_OUT_PROD:
  1772. ggml_cuda_out_prod(ctx, dst);
  1773. break;
  1774. case GGML_OP_SCALE:
  1775. ggml_cuda_op_scale(ctx, dst);
  1776. break;
  1777. case GGML_OP_SQR:
  1778. ggml_cuda_op_sqr(ctx, dst);
  1779. break;
  1780. case GGML_OP_SQRT:
  1781. ggml_cuda_op_sqrt(ctx, dst);
  1782. break;
  1783. case GGML_OP_SIN:
  1784. ggml_cuda_op_sin(ctx, dst);
  1785. break;
  1786. case GGML_OP_COS:
  1787. ggml_cuda_op_cos(ctx, dst);
  1788. break;
  1789. case GGML_OP_CLAMP:
  1790. ggml_cuda_op_clamp(ctx, dst);
  1791. break;
  1792. case GGML_OP_NONE:
  1793. case GGML_OP_RESHAPE:
  1794. case GGML_OP_VIEW:
  1795. case GGML_OP_PERMUTE:
  1796. case GGML_OP_TRANSPOSE:
  1797. break;
  1798. case GGML_OP_DIAG_MASK_INF:
  1799. ggml_cuda_op_diag_mask_inf(ctx, dst);
  1800. break;
  1801. case GGML_OP_SOFT_MAX:
  1802. ggml_cuda_op_soft_max(ctx, dst);
  1803. break;
  1804. case GGML_OP_ROPE:
  1805. ggml_cuda_op_rope(ctx, dst);
  1806. break;
  1807. case GGML_OP_IM2COL:
  1808. ggml_cuda_op_im2col(ctx, dst);
  1809. break;
  1810. case GGML_OP_CONV_TRANSPOSE_1D:
  1811. ggml_cuda_op_conv_transpose_1d(ctx,dst);
  1812. break;
  1813. case GGML_OP_POOL_2D:
  1814. ggml_cuda_op_pool2d(ctx, dst);
  1815. break;
  1816. case GGML_OP_SUM:
  1817. ggml_cuda_op_sum(ctx, dst);
  1818. break;
  1819. case GGML_OP_SUM_ROWS:
  1820. ggml_cuda_op_sum_rows(ctx, dst);
  1821. break;
  1822. case GGML_OP_ARGSORT:
  1823. ggml_cuda_op_argsort(ctx, dst);
  1824. break;
  1825. #if !defined(GGML_DISABLE_FLASH_ATTN)
  1826. case GGML_OP_FLASH_ATTN_EXT:
  1827. ggml_cuda_flash_attn_ext(ctx, dst);
  1828. break;
  1829. #endif
  1830. case GGML_OP_CROSS_ENTROPY_LOSS:
  1831. ggml_cuda_cross_entropy_loss(ctx, dst);
  1832. break;
  1833. case GGML_OP_RWKV_WKV6:
  1834. ggml_cuda_op_rwkv_wkv6(ctx, dst);
  1835. break;
  1836. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  1837. ggml_cuda_cross_entropy_loss_back(ctx, dst);
  1838. break;
  1839. case GGML_OP_OPT_STEP_ADAMW:
  1840. ggml_cuda_opt_step_adamw(ctx, dst);
  1841. break;
  1842. default:
  1843. return false;
  1844. }
  1845. cudaError_t err = cudaGetLastError();
  1846. if (err != cudaSuccess) {
  1847. GGML_LOG_ERROR("%s: %s failed\n", __func__, ggml_op_desc(dst));
  1848. CUDA_CHECK(err);
  1849. }
  1850. return true;
  1851. }
  1852. ////////////////////////////////////////////////////////////////////////////////
  1853. // backend
  1854. static const char * ggml_backend_cuda_get_name(ggml_backend_t backend) {
  1855. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1856. return cuda_ctx->name.c_str();
  1857. }
  1858. static void ggml_backend_cuda_free(ggml_backend_t backend) {
  1859. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1860. delete cuda_ctx;
  1861. delete backend;
  1862. }
  1863. static void ggml_backend_cuda_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  1864. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1865. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  1866. GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
  1867. CUDA_CHECK(cudaMemcpyAsync((char *)tensor->data + offset, data, size, cudaMemcpyHostToDevice, cuda_ctx->stream()));
  1868. }
  1869. static void ggml_backend_cuda_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  1870. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1871. ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
  1872. GGML_ASSERT(buf->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) && "unsupported buffer type");
  1873. CUDA_CHECK(cudaMemcpyAsync(data, (const char *)tensor->data + offset, size, cudaMemcpyDeviceToHost, cuda_ctx->stream()));
  1874. }
  1875. static bool ggml_backend_cuda_cpy_tensor_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const ggml_tensor * src, ggml_tensor * dst) {
  1876. ggml_backend_buffer_t buf_src = src->view_src ? src->view_src->buffer : src->buffer;
  1877. ggml_backend_buffer_t buf_dst = dst->view_src ? dst->view_src->buffer : dst->buffer;
  1878. if (!ggml_backend_is_cuda(backend_src) || !ggml_backend_is_cuda(backend_dst)) {
  1879. return false;
  1880. }
  1881. if (!ggml_backend_buffer_is_cuda(src->buffer) || !ggml_backend_buffer_is_cuda(dst->buffer)) {
  1882. return false;
  1883. }
  1884. // device -> device copy
  1885. ggml_backend_cuda_context * cuda_ctx_src = (ggml_backend_cuda_context *)backend_src->context;
  1886. ggml_backend_cuda_context * cuda_ctx_dst = (ggml_backend_cuda_context *)backend_dst->context;
  1887. ggml_backend_cuda_buffer_context * buf_ctx_src = (ggml_backend_cuda_buffer_context *)buf_src->context;
  1888. ggml_backend_cuda_buffer_context * buf_ctx_dst = (ggml_backend_cuda_buffer_context *)buf_dst->context;
  1889. if (cuda_ctx_src->device != buf_ctx_src->device || cuda_ctx_dst->device != buf_ctx_dst->device) {
  1890. #ifndef NDEBUG
  1891. GGML_LOG_DEBUG("%s: backend and buffer devices do not match\n", __func__);
  1892. #endif
  1893. return false;
  1894. }
  1895. if (backend_src != backend_dst) {
  1896. // copy on src stream
  1897. if (cuda_ctx_src->device == cuda_ctx_dst->device) {
  1898. CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(dst), cudaMemcpyDeviceToDevice, cuda_ctx_src->stream()));
  1899. } else {
  1900. #ifdef GGML_CUDA_NO_PEER_COPY
  1901. return false;
  1902. #else
  1903. CUDA_CHECK(cudaMemcpyPeerAsync(dst->data, cuda_ctx_dst->device, src->data, cuda_ctx_src->device, ggml_nbytes(dst), cuda_ctx_src->stream()));
  1904. #endif
  1905. }
  1906. // record event on src stream after the copy
  1907. if (!cuda_ctx_src->copy_event) {
  1908. ggml_cuda_set_device(cuda_ctx_src->device);
  1909. CUDA_CHECK(cudaEventCreateWithFlags(&cuda_ctx_src->copy_event, cudaEventDisableTiming));
  1910. }
  1911. CUDA_CHECK(cudaEventRecord(cuda_ctx_src->copy_event, cuda_ctx_src->stream()));
  1912. // wait on dst stream for the copy to complete
  1913. CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx_dst->stream(), cuda_ctx_src->copy_event, 0));
  1914. } else {
  1915. // src and dst are on the same backend
  1916. CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(dst), cudaMemcpyDeviceToDevice, cuda_ctx_src->stream()));
  1917. }
  1918. return true;
  1919. }
  1920. static void ggml_backend_cuda_synchronize(ggml_backend_t backend) {
  1921. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1922. CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream()));
  1923. GGML_UNUSED(backend);
  1924. }
  1925. #ifdef USE_CUDA_GRAPH
  1926. static void set_ggml_graph_node_properties(ggml_tensor * node, ggml_graph_node_properties * graph_node_properties) {
  1927. graph_node_properties->node_address = node->data;
  1928. graph_node_properties->node_op = node->op;
  1929. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  1930. graph_node_properties->ne[i] = node->ne[i];
  1931. graph_node_properties->nb[i] = node->nb[i];
  1932. }
  1933. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1934. graph_node_properties->src_address[i] = node->src[i] ? node->src[i]->data : nullptr;
  1935. }
  1936. memcpy(graph_node_properties->op_params, node->op_params, GGML_MAX_OP_PARAMS);
  1937. }
  1938. static bool ggml_graph_node_has_matching_properties(ggml_tensor * node, ggml_graph_node_properties * graph_node_properties) {
  1939. if (node->data != graph_node_properties->node_address &&
  1940. node->op != GGML_OP_CPY &&
  1941. node->op != GGML_OP_VIEW) {
  1942. return false;
  1943. }
  1944. if (node->op != graph_node_properties->node_op) {
  1945. return false;
  1946. }
  1947. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  1948. if (node->ne[i] != graph_node_properties->ne[i]) {
  1949. return false;
  1950. }
  1951. if (node->nb[i] != graph_node_properties->nb[i]) {
  1952. return false;
  1953. }
  1954. }
  1955. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1956. if (node->src[i] &&
  1957. node->src[i]->data != graph_node_properties->src_address[i] &&
  1958. node->op != GGML_OP_CPY &&
  1959. node->op != GGML_OP_VIEW
  1960. ) {
  1961. return false;
  1962. }
  1963. }
  1964. if (node->op == GGML_OP_SCALE &&
  1965. memcmp(graph_node_properties->op_params, node->op_params, GGML_MAX_OP_PARAMS) != 0) {
  1966. return false;
  1967. }
  1968. return true;
  1969. }
  1970. #endif
  1971. static enum ggml_status ggml_backend_cuda_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  1972. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  1973. ggml_cuda_set_device(cuda_ctx->device);
  1974. #ifdef USE_CUDA_GRAPH
  1975. static const bool disable_cuda_graphs_due_to_env = (getenv("GGML_CUDA_DISABLE_GRAPHS") != nullptr);
  1976. // Objects required for CUDA Graph
  1977. if (cuda_ctx->cuda_graph == nullptr) {
  1978. cuda_ctx->cuda_graph.reset(new ggml_cuda_graph());
  1979. }
  1980. bool use_cuda_graph = true;
  1981. bool cuda_graph_update_required = false;
  1982. // vector of pointers to CUDA cpy kernels, which are required to identify
  1983. // kernel parameters which need updated in the graph for each token
  1984. std::vector<void *> ggml_cuda_cpy_fn_ptrs;
  1985. if (cuda_ctx->cuda_graph->graph == nullptr) {
  1986. if (ggml_cuda_info().devices[cuda_ctx->device].cc < GGML_CUDA_CC_AMPERE) {
  1987. cuda_ctx->cuda_graph->disable_due_to_gpu_arch = true;
  1988. #ifndef NDEBUG
  1989. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to GPU architecture\n", __func__);
  1990. #endif
  1991. }
  1992. }
  1993. // Disable CUDA graphs in presence of env var, old GPU, use-case which is changing too rapidly,
  1994. // or previous graph capture failure.
  1995. // Also disable for multi-gpu for now. TO DO investigate
  1996. if (disable_cuda_graphs_due_to_env
  1997. || cuda_ctx->cuda_graph->disable_due_to_gpu_arch
  1998. || cuda_ctx->cuda_graph->disable_due_to_too_many_updates
  1999. || cuda_ctx->cuda_graph->disable_due_to_failed_graph_capture) {
  2000. use_cuda_graph = false;
  2001. }
  2002. if (use_cuda_graph) {
  2003. if (cuda_ctx->cuda_graph->instance == nullptr) {
  2004. cuda_graph_update_required = true;
  2005. }
  2006. // Check if the graph size has changed
  2007. if (cuda_ctx->cuda_graph->ggml_graph_properties.size() != (size_t)cgraph->n_nodes) {
  2008. cuda_graph_update_required = true;
  2009. cuda_ctx->cuda_graph->ggml_graph_properties.resize(cgraph->n_nodes);
  2010. }
  2011. // Loop over nodes in GGML graph to determine if CUDA graph update is required
  2012. // and store properties to allow this comparison for the next token
  2013. for (int i = 0; i < cgraph->n_nodes; i++) {
  2014. bool has_matching_properties = true;
  2015. if (!cuda_graph_update_required) {
  2016. has_matching_properties = ggml_graph_node_has_matching_properties(cgraph->nodes[i], &cuda_ctx->cuda_graph->ggml_graph_properties[i]);
  2017. }
  2018. if (!has_matching_properties) {
  2019. cuda_graph_update_required = true;
  2020. }
  2021. set_ggml_graph_node_properties(cgraph->nodes[i], &cuda_ctx->cuda_graph->ggml_graph_properties[i]);
  2022. }
  2023. // Loop over nodes in GGML graph to obtain info needed for CUDA graph
  2024. cuda_ctx->cuda_graph->updated_kernel_arg.clear();
  2025. for (int i = 0; i < cgraph->n_nodes; i++) {
  2026. ggml_tensor * node = cgraph->nodes[i];
  2027. if (ggml_is_empty(node) || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) {
  2028. continue;
  2029. }
  2030. if (node->src[0] && node->src[0]->buffer && ggml_backend_buft_is_cuda_split(node->src[0]->buffer->buft)) {
  2031. use_cuda_graph = false; // Split buffers are not supported by CUDA graph capture
  2032. #ifndef NDEBUG
  2033. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to split buffer\n", __func__);
  2034. #endif
  2035. }
  2036. if (node->op == GGML_OP_MUL_MAT_ID) {
  2037. use_cuda_graph = false; // This node type is not supported by CUDA graph capture
  2038. #ifndef NDEBUG
  2039. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to mul_mat_id\n", __func__);
  2040. #endif
  2041. }
  2042. if (node->op == GGML_OP_ADD && node->src[1] && node->src[1]->ne[1] > 1) {
  2043. // disable CUDA graphs for batch size > 1 for now.
  2044. // Changes in batch size or context size can cause changes to the grid size of some kernels.
  2045. use_cuda_graph = false;
  2046. #ifndef NDEBUG
  2047. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to batch size > 1 [%s] [%ld %ld %ld %ld]\n", __func__, node->name, node->ne[0], node->ne[1], node->ne[2], node->ne[3]);
  2048. #endif
  2049. }
  2050. if (node->op == GGML_OP_CPY) {
  2051. // store the copy op parameter which changes with each token.
  2052. cuda_ctx->cuda_graph->updated_kernel_arg.push_back((char **) &(node->src[1]->data));
  2053. // store a pointer to each copy op CUDA kernel to identify it later
  2054. void * ptr = ggml_cuda_cpy_fn(node->src[0], node->src[1]);
  2055. if (!ptr) {
  2056. use_cuda_graph = false;
  2057. #ifndef NDEBUG
  2058. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to unsupported copy op\n", __func__);
  2059. #endif
  2060. } else {
  2061. if (std::find(ggml_cuda_cpy_fn_ptrs.begin(), ggml_cuda_cpy_fn_ptrs.end(), ptr) == ggml_cuda_cpy_fn_ptrs.end()) {
  2062. ggml_cuda_cpy_fn_ptrs.push_back(ptr);
  2063. }
  2064. }
  2065. }
  2066. if (!use_cuda_graph) {
  2067. break;
  2068. }
  2069. }
  2070. // Disable CUDA graphs (from the next token) if the use-case is demanding too many consecutive graph updates.
  2071. if (use_cuda_graph && cuda_graph_update_required) {
  2072. cuda_ctx->cuda_graph->number_consecutive_updates++;
  2073. } else {
  2074. cuda_ctx->cuda_graph->number_consecutive_updates = 0;
  2075. }
  2076. if (cuda_ctx->cuda_graph->number_consecutive_updates >= 4) {
  2077. cuda_ctx->cuda_graph->disable_due_to_too_many_updates = true;
  2078. #ifndef NDEBUG
  2079. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to too many consecutive updates\n", __func__);
  2080. #endif
  2081. }
  2082. }
  2083. if (use_cuda_graph && cuda_graph_update_required) { // Start CUDA graph capture
  2084. CUDA_CHECK(cudaStreamBeginCapture(cuda_ctx->stream(), cudaStreamCaptureModeRelaxed));
  2085. }
  2086. #else
  2087. bool use_cuda_graph = false;
  2088. bool cuda_graph_update_required = false;
  2089. #endif // USE_CUDA_GRAPH
  2090. bool graph_evaluated_or_captured = false;
  2091. while (!graph_evaluated_or_captured) {
  2092. // Only perform the graph execution if CUDA graphs are not enabled, or we are capturing the graph.
  2093. // With the use of CUDA graphs, the execution will be performed by the graph launch.
  2094. if (!use_cuda_graph || cuda_graph_update_required) {
  2095. for (int i = 0; i < cgraph->n_nodes; i++) {
  2096. ggml_tensor * node = cgraph->nodes[i];
  2097. if (ggml_is_empty(node) || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) {
  2098. continue;
  2099. }
  2100. #ifndef NDEBUG
  2101. assert(node->buffer->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device));
  2102. for (int j = 0; j < GGML_MAX_SRC; j++) {
  2103. if (node->src[j] != nullptr) {
  2104. assert(node->src[j]->buffer);
  2105. assert(node->src[j]->buffer->buft == ggml_backend_cuda_buffer_type(cuda_ctx->device) ||
  2106. ggml_backend_buft_is_cuda_split(node->src[j]->buffer->buft));
  2107. }
  2108. }
  2109. #endif
  2110. bool ok = ggml_cuda_compute_forward(*cuda_ctx, node);
  2111. if (!ok) {
  2112. GGML_LOG_ERROR("%s: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op));
  2113. }
  2114. GGML_ASSERT(ok);
  2115. }
  2116. }
  2117. #ifdef USE_CUDA_GRAPH
  2118. if (use_cuda_graph && cuda_graph_update_required) { // End CUDA graph capture
  2119. if (cuda_ctx->cuda_graph->graph != nullptr) {
  2120. CUDA_CHECK(cudaGraphDestroy(cuda_ctx->cuda_graph->graph));
  2121. cuda_ctx->cuda_graph->graph = nullptr;
  2122. }
  2123. CUDA_CHECK(cudaStreamEndCapture(cuda_ctx->stream(), &cuda_ctx->cuda_graph->graph));
  2124. #if 0
  2125. if (disable_cuda_graphs_due_to_failed_capture) {
  2126. use_cuda_graph = false;
  2127. cuda_ctx->cuda_graph->disable_due_to_failed_graph_capture = true;
  2128. #ifndef NDEBUG
  2129. GGML_LOG_DEBUG("%s: disabling CUDA graphs due to failed graph capture\n", __func__);
  2130. #endif
  2131. } else {
  2132. graph_evaluated_or_captured = true; // CUDA graph has been captured
  2133. }
  2134. #endif
  2135. graph_evaluated_or_captured = true; // CUDA graph has been captured
  2136. } else {
  2137. graph_evaluated_or_captured = true; // ggml graph has been directly evaluated
  2138. }
  2139. }
  2140. if (use_cuda_graph) {
  2141. if (cuda_ctx->cuda_graph->instance == nullptr) { // Create executable graph from captured graph.
  2142. CUDA_CHECK(cudaGraphInstantiate(&cuda_ctx->cuda_graph->instance, cuda_ctx->cuda_graph->graph, NULL, NULL, 0));
  2143. }
  2144. // Perform update to graph (if required for this token), and change copy parameter (required for every token)
  2145. if (cuda_graph_update_required) {
  2146. // Extract nodes from graph
  2147. // First call with null argument gets number of nodes in graph
  2148. CUDA_CHECK(cudaGraphGetNodes(cuda_ctx->cuda_graph->graph, nullptr, &cuda_ctx->cuda_graph->num_nodes));
  2149. // Subsequent call with non-null argument gets nodes
  2150. cuda_ctx->cuda_graph->nodes.clear();
  2151. cuda_ctx->cuda_graph->nodes.resize(cuda_ctx->cuda_graph->num_nodes);
  2152. cuda_ctx->cuda_graph->params.clear();
  2153. cuda_ctx->cuda_graph->params.resize(cuda_ctx->cuda_graph->num_nodes);
  2154. if (cuda_ctx->cuda_graph->num_nodes > 0) {
  2155. CUDA_CHECK(cudaGraphGetNodes(cuda_ctx->cuda_graph->graph, cuda_ctx->cuda_graph->nodes.data(), &cuda_ctx->cuda_graph->num_nodes));
  2156. // Loop over nodes, and extract kernel parameters from each node
  2157. for (size_t i = 0; i < cuda_ctx->cuda_graph->num_nodes; i++) {
  2158. cudaGraphNodeType node_type;
  2159. CUDA_CHECK(cudaGraphNodeGetType(cuda_ctx->cuda_graph->nodes[i], &node_type));
  2160. if (node_type == cudaGraphNodeTypeKernel) {
  2161. cudaError_t stat = cudaGraphKernelNodeGetParams(cuda_ctx->cuda_graph->nodes[i], &cuda_ctx->cuda_graph->params[i]); // Get params using runtime
  2162. if (stat == cudaErrorInvalidDeviceFunction) {
  2163. // Fails due to incorrect handling by CUDA runtime of CUDA BLAS node.
  2164. // We don't need to update blas nodes, so clear error and move on.
  2165. cudaGetLastError();
  2166. } else {
  2167. GGML_ASSERT(stat == cudaSuccess);
  2168. }
  2169. }
  2170. }
  2171. }
  2172. }
  2173. // One of the arguments to the copy kernel is updated for each token, hence we need to
  2174. // replace that argument with the updated value in the CUDA graph
  2175. if (!cuda_graph_update_required) { // on update steps, the live parameters will already be captured
  2176. int k = 0;
  2177. for (size_t i = 0; i < cuda_ctx->cuda_graph->num_nodes; i++) {
  2178. if(count(ggml_cuda_cpy_fn_ptrs.begin(), ggml_cuda_cpy_fn_ptrs.end(), cuda_ctx->cuda_graph->params[i].func) > 0) {
  2179. char ** updated_kernel_arg_ptr = cuda_ctx->cuda_graph->updated_kernel_arg.at(k++);
  2180. cuda_ctx->cuda_graph->params[i].kernelParams[1] = updated_kernel_arg_ptr;
  2181. CUDA_CHECK(cudaGraphKernelNodeSetParams(cuda_ctx->cuda_graph->nodes[i], &cuda_ctx->cuda_graph->params[i]));
  2182. }
  2183. }
  2184. }
  2185. // Update graph executable
  2186. cudaGraphExecUpdateResultInfo result_info;
  2187. cudaError_t stat = cudaGraphExecUpdate(cuda_ctx->cuda_graph->instance, cuda_ctx->cuda_graph->graph, &result_info);
  2188. if (stat == cudaErrorGraphExecUpdateFailure) {
  2189. #ifndef NDEBUG
  2190. GGML_LOG_DEBUG("%s: CUDA graph update failed\n", __func__);
  2191. #endif
  2192. // The pre-existing graph exec cannot be updated due to violated constraints
  2193. // so instead clear error and re-instantiate
  2194. cudaGetLastError();
  2195. CUDA_CHECK(cudaGraphExecDestroy(cuda_ctx->cuda_graph->instance));
  2196. cuda_ctx->cuda_graph->instance = nullptr;
  2197. CUDA_CHECK(cudaGraphInstantiate(&cuda_ctx->cuda_graph->instance, cuda_ctx->cuda_graph->graph, NULL, NULL, 0));
  2198. } else {
  2199. GGML_ASSERT(stat == cudaSuccess);
  2200. }
  2201. // Launch graph
  2202. CUDA_CHECK(cudaGraphLaunch(cuda_ctx->cuda_graph->instance, cuda_ctx->stream()));
  2203. #else
  2204. graph_evaluated_or_captured = true;
  2205. #endif // USE_CUDA_GRAPH
  2206. }
  2207. return GGML_STATUS_SUCCESS;
  2208. }
  2209. static void ggml_backend_cuda_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
  2210. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  2211. CUDA_CHECK(cudaEventRecord((cudaEvent_t)event->context, cuda_ctx->stream()));
  2212. }
  2213. static void ggml_backend_cuda_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  2214. ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context;
  2215. if (ggml_backend_is_cuda(backend)) {
  2216. CUDA_CHECK(cudaStreamWaitEvent(cuda_ctx->stream(), (cudaEvent_t)event->context, 0));
  2217. } else {
  2218. #if 0
  2219. // untested
  2220. auto wait_fn = [](void * user_data) {
  2221. ggml_backend_event_t event = (ggml_backend_event_t)user_data;
  2222. ggml_backend_event_synchronize(event);
  2223. };
  2224. CUDA_CHECK(cudaLaunchHostFunc(cuda_ctx->stream(), wait_fn, event));
  2225. #endif
  2226. GGML_ABORT("fatal error");
  2227. }
  2228. }
  2229. static const ggml_backend_i ggml_backend_cuda_interface = {
  2230. /* .get_name = */ ggml_backend_cuda_get_name,
  2231. /* .free = */ ggml_backend_cuda_free,
  2232. /* .set_tensor_async = */ ggml_backend_cuda_set_tensor_async,
  2233. /* .get_tensor_async = */ ggml_backend_cuda_get_tensor_async,
  2234. /* .cpy_tensor_async = */ ggml_backend_cuda_cpy_tensor_async,
  2235. /* .synchronize = */ ggml_backend_cuda_synchronize,
  2236. /* .graph_plan_create = */ NULL,
  2237. /* .graph_plan_free = */ NULL,
  2238. /* .graph_plan_update = */ NULL,
  2239. /* .graph_plan_compute = */ NULL,
  2240. /* .graph_compute = */ ggml_backend_cuda_graph_compute,
  2241. /* .event_record = */ ggml_backend_cuda_event_record,
  2242. /* .event_wait = */ ggml_backend_cuda_event_wait,
  2243. };
  2244. static ggml_guid_t ggml_backend_cuda_guid() {
  2245. static ggml_guid guid = { 0x2c, 0xdd, 0xe8, 0x1c, 0x65, 0xb3, 0x65, 0x73, 0x6a, 0x12, 0x88, 0x61, 0x1c, 0xc9, 0xdc, 0x25 };
  2246. return &guid;
  2247. }
  2248. bool ggml_backend_is_cuda(ggml_backend_t backend) {
  2249. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_cuda_guid());
  2250. }
  2251. int ggml_backend_cuda_get_device_count() {
  2252. return ggml_cuda_info().device_count;
  2253. }
  2254. void ggml_backend_cuda_get_device_description(int device, char * description, size_t description_size) {
  2255. cudaDeviceProp prop;
  2256. CUDA_CHECK(cudaGetDeviceProperties(&prop, device));
  2257. snprintf(description, description_size, "%s", prop.name);
  2258. }
  2259. void ggml_backend_cuda_get_device_memory(int device, size_t * free, size_t * total) {
  2260. ggml_cuda_set_device(device);
  2261. CUDA_CHECK(cudaMemGetInfo(free, total));
  2262. }
  2263. bool ggml_backend_cuda_register_host_buffer(void * buffer, size_t size) {
  2264. if (getenv("GGML_CUDA_REGISTER_HOST") == nullptr) {
  2265. return false;
  2266. }
  2267. #if CUDART_VERSION >= 11100 || defined(GGML_USE_MUSA)
  2268. cudaError_t err = cudaHostRegister(buffer, size, cudaHostRegisterPortable | cudaHostRegisterReadOnly);
  2269. if (err != cudaSuccess) {
  2270. // clear the error
  2271. cudaGetLastError();
  2272. GGML_LOG_DEBUG("%s: failed to register %.2f MiB of pinned memory: %s\n", __func__,
  2273. size / 1024.0 / 1024.0, cudaGetErrorString(err));
  2274. return false;
  2275. }
  2276. return true;
  2277. #else
  2278. return false;
  2279. #endif
  2280. }
  2281. void ggml_backend_cuda_unregister_host_buffer(void * buffer) {
  2282. if (getenv("GGML_CUDA_REGISTER_HOST") == nullptr) {
  2283. return;
  2284. }
  2285. cudaError_t err = cudaHostUnregister(buffer);
  2286. if (err != cudaSuccess) {
  2287. // clear the error
  2288. cudaGetLastError();
  2289. }
  2290. }
  2291. // backend device
  2292. struct ggml_backend_cuda_device_context {
  2293. int device;
  2294. std::string name;
  2295. std::string description;
  2296. };
  2297. static const char * ggml_backend_cuda_device_get_name(ggml_backend_dev_t dev) {
  2298. ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
  2299. return ctx->name.c_str();
  2300. }
  2301. static const char * ggml_backend_cuda_device_get_description(ggml_backend_dev_t dev) {
  2302. ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
  2303. return ctx->description.c_str();
  2304. }
  2305. static void ggml_backend_cuda_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
  2306. ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
  2307. ggml_cuda_set_device(ctx->device);
  2308. CUDA_CHECK(cudaMemGetInfo(free, total));
  2309. }
  2310. static enum ggml_backend_dev_type ggml_backend_cuda_device_get_type(ggml_backend_dev_t dev) {
  2311. GGML_UNUSED(dev);
  2312. return GGML_BACKEND_DEVICE_TYPE_GPU;
  2313. }
  2314. static void ggml_backend_cuda_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
  2315. props->name = ggml_backend_cuda_device_get_name(dev);
  2316. props->description = ggml_backend_cuda_device_get_description(dev);
  2317. props->type = ggml_backend_cuda_device_get_type(dev);
  2318. ggml_backend_cuda_device_get_memory(dev, &props->memory_free, &props->memory_total);
  2319. bool host_buffer = getenv("GGML_CUDA_NO_PINNED") == nullptr;
  2320. #ifdef GGML_CUDA_NO_PEER_COPY
  2321. bool events = false;
  2322. #else
  2323. bool events = true;
  2324. #endif
  2325. props->caps = {
  2326. /* .async = */ true,
  2327. /* .host_buffer = */ host_buffer,
  2328. /* .buffer_from_host_ptr = */ false,
  2329. /* .events = */ events,
  2330. };
  2331. }
  2332. static ggml_backend_t ggml_backend_cuda_device_init_backend(ggml_backend_dev_t dev, const char * params) {
  2333. GGML_UNUSED(params);
  2334. ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
  2335. return ggml_backend_cuda_init(ctx->device);
  2336. }
  2337. static ggml_backend_buffer_type_t ggml_backend_cuda_device_get_buffer_type(ggml_backend_dev_t dev) {
  2338. ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *)dev->context;
  2339. return ggml_backend_cuda_buffer_type(ctx->device);
  2340. }
  2341. static ggml_backend_buffer_type_t ggml_backend_cuda_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  2342. GGML_UNUSED(dev);
  2343. return ggml_backend_cuda_host_buffer_type();
  2344. }
  2345. // TODO: move these functions here
  2346. static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  2347. ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *) dev->context;
  2348. // split buffers can only be used with GGML_OP_MUL_MAT
  2349. if (op->op != GGML_OP_MUL_MAT) {
  2350. for (int i = 0; i < GGML_MAX_SRC; i++) {
  2351. if (op->src[i] && op->src[i]->buffer && ggml_backend_buft_is_cuda_split(op->src[i]->buffer->buft)) {
  2352. return false;
  2353. }
  2354. }
  2355. }
  2356. // check if all the sources are allocated on this device
  2357. for (int i = 0; i < GGML_MAX_SRC; i++) {
  2358. if (op->src[i] && op->src[i]->buffer && ggml_backend_buft_is_cuda(op->src[i]->buffer->buft)) {
  2359. ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *)op->src[i]->buffer->buft->context;
  2360. if (buft_ctx->device != dev_ctx->device) {
  2361. return false;
  2362. }
  2363. }
  2364. }
  2365. switch (op->op) {
  2366. case GGML_OP_UNARY:
  2367. switch (ggml_get_unary_op(op)) {
  2368. case GGML_UNARY_OP_NEG:
  2369. case GGML_UNARY_OP_STEP:
  2370. case GGML_UNARY_OP_GELU:
  2371. case GGML_UNARY_OP_SILU:
  2372. case GGML_UNARY_OP_RELU:
  2373. case GGML_UNARY_OP_SIGMOID:
  2374. case GGML_UNARY_OP_HARDSIGMOID:
  2375. case GGML_UNARY_OP_HARDSWISH:
  2376. case GGML_UNARY_OP_GELU_QUICK:
  2377. case GGML_UNARY_OP_TANH:
  2378. case GGML_UNARY_OP_EXP:
  2379. return ggml_is_contiguous(op->src[0]);
  2380. default:
  2381. return false;
  2382. }
  2383. break;
  2384. case GGML_OP_MUL_MAT:
  2385. case GGML_OP_MUL_MAT_ID:
  2386. {
  2387. struct ggml_tensor * a = op->src[0];
  2388. struct ggml_tensor * b = op->src[1];
  2389. // for small weight matrices the active device can end up without any rows, don't use row split in those cases
  2390. // this avoids some edge cases (and the performance would not be good anyways)
  2391. if (a->buffer && ggml_backend_buft_is_cuda_split(a->buffer->buft)) {
  2392. ggml_backend_cuda_split_buffer_type_context * buft_ctx = (ggml_backend_cuda_split_buffer_type_context *) a->buffer->buft->context;
  2393. int64_t row_low;
  2394. int64_t row_high;
  2395. get_row_split(&row_low, &row_high, a, buft_ctx->tensor_split, dev_ctx->device);
  2396. if (row_low == row_high) {
  2397. return false;
  2398. }
  2399. }
  2400. if (b->type == GGML_TYPE_F16 && a->type != GGML_TYPE_F16) {
  2401. return false;
  2402. }
  2403. if (op->op == GGML_OP_MUL_MAT && a->ne[3] != b->ne[3]) {
  2404. return false;
  2405. }
  2406. #ifdef GGML_USE_MUSA
  2407. if (b->type == GGML_TYPE_F16 && b->ne[2]*b->ne[3] > 1 &&
  2408. !ggml_is_transposed(a) && !ggml_is_transposed(b)) {
  2409. return false;
  2410. }
  2411. #endif // GGML_USE_MUSA
  2412. switch (a->type) {
  2413. case GGML_TYPE_F32:
  2414. case GGML_TYPE_F16:
  2415. case GGML_TYPE_Q4_0:
  2416. case GGML_TYPE_Q4_1:
  2417. case GGML_TYPE_Q5_0:
  2418. case GGML_TYPE_Q5_1:
  2419. case GGML_TYPE_Q8_0:
  2420. case GGML_TYPE_Q2_K:
  2421. case GGML_TYPE_Q3_K:
  2422. case GGML_TYPE_Q4_K:
  2423. case GGML_TYPE_Q5_K:
  2424. case GGML_TYPE_Q6_K:
  2425. case GGML_TYPE_Q8_K:
  2426. case GGML_TYPE_IQ1_M:
  2427. case GGML_TYPE_IQ1_S:
  2428. case GGML_TYPE_IQ2_S:
  2429. case GGML_TYPE_IQ2_XS:
  2430. case GGML_TYPE_IQ2_XXS:
  2431. case GGML_TYPE_IQ3_S:
  2432. case GGML_TYPE_IQ3_XXS:
  2433. case GGML_TYPE_IQ4_NL:
  2434. case GGML_TYPE_IQ4_XS:
  2435. case GGML_TYPE_BF16:
  2436. #ifdef GGML_USE_MUSA
  2437. if (a->type == GGML_TYPE_Q3_K) {
  2438. return false;
  2439. }
  2440. #endif // GGML_USE_MUSA
  2441. return true;
  2442. default:
  2443. return false;
  2444. }
  2445. } break;
  2446. case GGML_OP_OUT_PROD:
  2447. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->ne[2] == 1 && op->ne[3] == 1;
  2448. case GGML_OP_GET_ROWS:
  2449. {
  2450. switch (op->src[0]->type) {
  2451. case GGML_TYPE_F16:
  2452. case GGML_TYPE_F32:
  2453. case GGML_TYPE_Q4_0:
  2454. case GGML_TYPE_Q4_1:
  2455. case GGML_TYPE_Q5_0:
  2456. case GGML_TYPE_Q5_1:
  2457. case GGML_TYPE_Q8_0:
  2458. return true;
  2459. default:
  2460. return false;
  2461. }
  2462. } break;
  2463. case GGML_OP_CPY:
  2464. {
  2465. ggml_type src0_type = op->src[0]->type;
  2466. ggml_type src1_type = op->src[1]->type;
  2467. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2468. return true;
  2469. }
  2470. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  2471. return true;
  2472. }
  2473. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q8_0) {
  2474. return true;
  2475. }
  2476. if (src0_type == GGML_TYPE_Q8_0 && src1_type == GGML_TYPE_F32) {
  2477. return true;
  2478. }
  2479. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q4_0) {
  2480. return true;
  2481. }
  2482. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q4_1) {
  2483. return true;
  2484. }
  2485. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q5_0) {
  2486. return true;
  2487. }
  2488. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_Q5_1) {
  2489. return true;
  2490. }
  2491. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_IQ4_NL) {
  2492. return true;
  2493. }
  2494. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2495. return true;
  2496. }
  2497. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2498. return true;
  2499. }
  2500. if (src0_type == src1_type && ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1])) {
  2501. return true;
  2502. }
  2503. return false;
  2504. } break;
  2505. case GGML_OP_DUP:
  2506. {
  2507. ggml_type src0_type = op->src[0]->type;
  2508. return src0_type != GGML_TYPE_I32 && src0_type != GGML_TYPE_I16;
  2509. } break;
  2510. case GGML_OP_ARGMAX:
  2511. case GGML_OP_COUNT_EQUAL:
  2512. {
  2513. return true;
  2514. } break;
  2515. case GGML_OP_REPEAT:
  2516. {
  2517. ggml_type src0_type = op->src[0]->type;
  2518. return src0_type != GGML_TYPE_I32 && src0_type != GGML_TYPE_I16;
  2519. } break;
  2520. case GGML_OP_REPEAT_BACK:
  2521. return op->type == GGML_TYPE_F32 && op->src[0]->ne[3] == 1;
  2522. case GGML_OP_CONCAT:
  2523. {
  2524. ggml_type src0_type = op->src[0]->type;
  2525. return src0_type != GGML_TYPE_I32 && src0_type != GGML_TYPE_I16;
  2526. } break;
  2527. case GGML_OP_CONV_TRANSPOSE_1D:
  2528. {
  2529. ggml_type src0_type = op->src[0]->type;
  2530. ggml_type src1_type = op->src[1]->type;
  2531. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2532. return true;
  2533. }
  2534. return false;
  2535. } break;
  2536. case GGML_OP_NORM:
  2537. case GGML_OP_RMS_NORM:
  2538. return ggml_is_contiguous(op->src[0]) && op->ne[0] % WARP_SIZE == 0;
  2539. break;
  2540. case GGML_OP_NONE:
  2541. case GGML_OP_RESHAPE:
  2542. case GGML_OP_VIEW:
  2543. case GGML_OP_PERMUTE:
  2544. case GGML_OP_TRANSPOSE:
  2545. case GGML_OP_ADD:
  2546. case GGML_OP_ADD1:
  2547. case GGML_OP_SUB:
  2548. case GGML_OP_MUL:
  2549. case GGML_OP_DIV:
  2550. case GGML_OP_SCALE:
  2551. case GGML_OP_SQR:
  2552. case GGML_OP_SQRT:
  2553. case GGML_OP_SIN:
  2554. case GGML_OP_COS:
  2555. case GGML_OP_CLAMP:
  2556. return true;
  2557. case GGML_OP_CONT:
  2558. return op->src[0]->type != GGML_TYPE_BF16;
  2559. case GGML_OP_DIAG_MASK_INF:
  2560. case GGML_OP_SOFT_MAX:
  2561. return true;
  2562. case GGML_OP_ROPE:
  2563. return ggml_is_contiguous(op->src[0]);
  2564. case GGML_OP_IM2COL:
  2565. case GGML_OP_POOL_2D:
  2566. case GGML_OP_SUM:
  2567. case GGML_OP_SUM_ROWS:
  2568. case GGML_OP_ARGSORT:
  2569. case GGML_OP_ACC:
  2570. case GGML_OP_GROUP_NORM:
  2571. case GGML_OP_UPSCALE:
  2572. case GGML_OP_PAD:
  2573. case GGML_OP_UNPAD:
  2574. case GGML_OP_ARANGE:
  2575. case GGML_OP_TIMESTEP_EMBEDDING:
  2576. case GGML_OP_LEAKY_RELU:
  2577. case GGML_OP_RWKV_WKV6:
  2578. return true;
  2579. case GGML_OP_FLASH_ATTN_EXT: {
  2580. #ifndef FLASH_ATTN_AVAILABLE
  2581. return false;
  2582. #endif
  2583. if (op->src[1]->type == GGML_TYPE_BF16 || op->src[2]->type == GGML_TYPE_BF16) {
  2584. return false;
  2585. }
  2586. if (op->src[0]->ne[0] == 64 && op->src[1]->type == GGML_TYPE_F16) {
  2587. return true;
  2588. }
  2589. if (op->src[0]->ne[0] == 128) {
  2590. return true;
  2591. }
  2592. if (op->src[0]->ne[0] == 256 && op->src[1]->type == GGML_TYPE_F16 && op->src[2]->type == GGML_TYPE_F16) {
  2593. return true;
  2594. }
  2595. const int cc = ggml_cuda_info().devices[dev_ctx->device].cc;
  2596. return cc >= GGML_CUDA_CC_VOLTA && cc < GGML_CUDA_CC_OFFSET_AMD && op->src[1]->type == GGML_TYPE_F16 && op->src[2]->type == GGML_TYPE_F16;
  2597. }
  2598. case GGML_OP_CROSS_ENTROPY_LOSS:
  2599. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  2600. case GGML_OP_OPT_STEP_ADAMW:
  2601. return true;
  2602. default:
  2603. return false;
  2604. }
  2605. }
  2606. static bool ggml_backend_cuda_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  2607. return (ggml_backend_buft_is_cuda(buft) || ggml_backend_buft_is_cuda_split(buft)) && buft->device == dev;
  2608. }
  2609. static int64_t get_op_batch_size(const ggml_tensor * op) {
  2610. switch (op->op) {
  2611. case GGML_OP_GET_ROWS:
  2612. return 0;
  2613. case GGML_OP_MUL_MAT:
  2614. return op->ne[1];
  2615. case GGML_OP_MUL_MAT_ID:
  2616. case GGML_OP_ROPE:
  2617. return op->ne[2];
  2618. default:
  2619. return ggml_nrows(op);
  2620. }
  2621. }
  2622. static bool ggml_backend_cuda_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  2623. const int min_batch_size = 32;
  2624. return get_op_batch_size(op) >= min_batch_size;
  2625. GGML_UNUSED(dev);
  2626. }
  2627. static ggml_backend_event_t ggml_backend_cuda_device_event_new(ggml_backend_dev_t dev) {
  2628. #ifdef GGML_CUDA_NO_PEER_COPY
  2629. return nullptr;
  2630. #else
  2631. ggml_backend_cuda_device_context * dev_ctx = (ggml_backend_cuda_device_context *)dev->context;
  2632. ggml_cuda_set_device(dev_ctx->device);
  2633. cudaEvent_t event;
  2634. CUDA_CHECK(cudaEventCreateWithFlags(&event, cudaEventDisableTiming));
  2635. return new ggml_backend_event {
  2636. /* .device = */ dev,
  2637. /* .context = */ event,
  2638. };
  2639. #endif
  2640. }
  2641. static void ggml_backend_cuda_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  2642. GGML_UNUSED(dev);
  2643. CUDA_CHECK(cudaEventDestroy((cudaEvent_t)event->context));
  2644. delete event;
  2645. }
  2646. static void ggml_backend_cuda_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  2647. GGML_UNUSED(dev);
  2648. CUDA_CHECK(cudaEventSynchronize((cudaEvent_t)event->context));
  2649. }
  2650. static const ggml_backend_device_i ggml_backend_cuda_device_interface = {
  2651. /* .get_name = */ ggml_backend_cuda_device_get_name,
  2652. /* .get_description = */ ggml_backend_cuda_device_get_description,
  2653. /* .get_memory = */ ggml_backend_cuda_device_get_memory,
  2654. /* .get_type = */ ggml_backend_cuda_device_get_type,
  2655. /* .get_props = */ ggml_backend_cuda_device_get_props,
  2656. /* .init_backend = */ ggml_backend_cuda_device_init_backend,
  2657. /* .get_buffer_type = */ ggml_backend_cuda_device_get_buffer_type,
  2658. /* .get_host_buffer_type = */ ggml_backend_cuda_device_get_host_buffer_type,
  2659. /* .buffer_from_host_ptr = */ NULL,
  2660. /* .supports_op = */ ggml_backend_cuda_device_supports_op,
  2661. /* .supports_buft = */ ggml_backend_cuda_device_supports_buft,
  2662. /* .offload_op = */ ggml_backend_cuda_device_offload_op,
  2663. /* .event_new = */ ggml_backend_cuda_device_event_new,
  2664. /* .event_free = */ ggml_backend_cuda_device_event_free,
  2665. /* .event_synchronize = */ ggml_backend_cuda_device_event_synchronize,
  2666. };
  2667. // backend reg
  2668. struct ggml_backend_cuda_reg_context {
  2669. std::vector<ggml_backend_dev_t> devices;
  2670. };
  2671. static const char * ggml_backend_cuda_reg_get_name(ggml_backend_reg_t reg) {
  2672. GGML_UNUSED(reg);
  2673. return GGML_CUDA_NAME;
  2674. }
  2675. static size_t ggml_backend_cuda_reg_get_device_count(ggml_backend_reg_t reg) {
  2676. ggml_backend_cuda_reg_context * ctx = (ggml_backend_cuda_reg_context *)reg->context;
  2677. return ctx->devices.size();
  2678. }
  2679. static ggml_backend_dev_t ggml_backend_cuda_reg_get_device(ggml_backend_reg_t reg, size_t index) {
  2680. ggml_backend_cuda_reg_context * ctx = (ggml_backend_cuda_reg_context *)reg->context;
  2681. GGML_ASSERT(index < ctx->devices.size());
  2682. return ctx->devices[index];
  2683. }
  2684. static ggml_backend_feature * ggml_backend_cuda_get_features(ggml_backend_reg_t reg) {
  2685. static std::vector<ggml_backend_feature> features = []() {
  2686. std::vector<ggml_backend_feature> features;
  2687. #define _STRINGIFY(...) #__VA_ARGS__
  2688. #define STRINGIFY(...) _STRINGIFY(__VA_ARGS__)
  2689. #ifdef __CUDA_ARCH_LIST__
  2690. features.push_back({ "ARCHS", STRINGIFY(__CUDA_ARCH_LIST__) });
  2691. #endif
  2692. #ifdef GGML_CUDA_FORCE_MMQ
  2693. features.push_back({ "FORCE_MMQ", "1" });
  2694. #endif
  2695. #ifdef GGML_CUDA_FORCE_CUBLAS
  2696. features.push_back({ "FORCE_CUBLAS", "1" });
  2697. #endif
  2698. #ifdef GGML_CUDA_NO_VMM
  2699. features.push_back({ "NO_VMM", "1" });
  2700. #endif
  2701. #ifdef GGML_CUDA_NO_PEER_COPY
  2702. features.push_back({ "NO_PEER_COPY", "1" });
  2703. #endif
  2704. #ifdef GGML_CUDA_F16
  2705. features.push_back({ "F16", "1" });
  2706. #endif
  2707. #ifdef GGML_CUDA_USE_GRAPHS
  2708. features.push_back({ "USE_GRAPHS", "1" });
  2709. #endif
  2710. #ifdef GGML_CUDA_PEER_MAX_BATCH_SIZE
  2711. features.push_back({ "PEER_MAX_BATCH_SIZE", STRINGIFY(GGML_CUDA_PEER_MAX_BATCH_SIZE) });
  2712. #endif
  2713. #ifdef GGML_CUDA_FA_ALL_QUANTS
  2714. features.push_back({ "FA_ALL_QUANTS", "1" });
  2715. #endif
  2716. #undef _STRINGIFY
  2717. #undef STRINGIFY
  2718. features.push_back({ nullptr, nullptr });
  2719. return features;
  2720. }();
  2721. return features.data();
  2722. GGML_UNUSED(reg);
  2723. }
  2724. static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) {
  2725. GGML_UNUSED(reg);
  2726. if (strcmp(name, "ggml_backend_split_buffer_type") == 0) {
  2727. return (void *)ggml_backend_cuda_split_buffer_type;
  2728. }
  2729. if (strcmp(name, "ggml_backend_register_host_buffer") == 0) {
  2730. return (void *)ggml_backend_cuda_register_host_buffer;
  2731. }
  2732. if (strcmp(name, "ggml_backend_unregister_host_buffer") == 0) {
  2733. return (void *)ggml_backend_cuda_unregister_host_buffer;
  2734. }
  2735. if (strcmp(name, "ggml_backend_get_features") == 0) {
  2736. return (void *)ggml_backend_cuda_get_features;
  2737. }
  2738. return nullptr;
  2739. }
  2740. static const ggml_backend_reg_i ggml_backend_cuda_reg_interface = {
  2741. /* .get_name = */ ggml_backend_cuda_reg_get_name,
  2742. /* .get_device_count = */ ggml_backend_cuda_reg_get_device_count,
  2743. /* .get_device = */ ggml_backend_cuda_reg_get_device,
  2744. /* .get_proc_address = */ ggml_backend_cuda_reg_get_proc_address,
  2745. };
  2746. // backend registry
  2747. ggml_backend_reg_t ggml_backend_cuda_reg() {
  2748. static ggml_backend_reg reg;
  2749. static bool initialized = false;
  2750. {
  2751. static std::mutex mutex;
  2752. std::lock_guard<std::mutex> lock(mutex);
  2753. if (!initialized) {
  2754. ggml_backend_cuda_reg_context * ctx = new ggml_backend_cuda_reg_context;
  2755. for (int i = 0; i < ggml_cuda_info().device_count; i++) {
  2756. ggml_backend_cuda_device_context * dev_ctx = new ggml_backend_cuda_device_context;
  2757. dev_ctx->device = i;
  2758. dev_ctx->name = GGML_CUDA_NAME + std::to_string(i);
  2759. ggml_cuda_set_device(i);
  2760. cudaDeviceProp prop;
  2761. CUDA_CHECK(cudaGetDeviceProperties(&prop, i));
  2762. dev_ctx->description = prop.name;
  2763. ggml_backend_dev_t dev = new ggml_backend_device {
  2764. /* .iface = */ ggml_backend_cuda_device_interface,
  2765. /* .reg = */ &reg,
  2766. /* .context = */ dev_ctx
  2767. };
  2768. ctx->devices.push_back(dev);
  2769. }
  2770. reg = ggml_backend_reg {
  2771. /* .api_version = */ GGML_BACKEND_API_VERSION,
  2772. /* .iface = */ ggml_backend_cuda_reg_interface,
  2773. /* .context = */ ctx
  2774. };
  2775. }
  2776. initialized = true;
  2777. }
  2778. return &reg;
  2779. }
  2780. ggml_backend_t ggml_backend_cuda_init(int device) {
  2781. if (device < 0 || device >= ggml_backend_cuda_get_device_count()) {
  2782. GGML_LOG_ERROR("%s: invalid device %d\n", __func__, device);
  2783. return nullptr;
  2784. }
  2785. ggml_backend_cuda_context * ctx = new ggml_backend_cuda_context(device);
  2786. if (ctx == nullptr) {
  2787. GGML_LOG_ERROR("%s: failed to allocate context\n", __func__);
  2788. return nullptr;
  2789. }
  2790. ggml_backend_t cuda_backend = new ggml_backend {
  2791. /* .guid = */ ggml_backend_cuda_guid(),
  2792. /* .interface = */ ggml_backend_cuda_interface,
  2793. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_cuda_reg(), device),
  2794. /* .context = */ ctx,
  2795. };
  2796. return cuda_backend;
  2797. }
  2798. GGML_BACKEND_DL_IMPL(ggml_backend_cuda_reg)