ggml-cuda.cu 127 KB

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