ggml-cuda.cu 101 KB

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