ggml-cuda.cu 123 KB

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