ggml-cuda.cu 120 KB

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