ggml-cuda.cu 122 KB

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