ggml-cuda.cu 119 KB

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