ggml-cuda.cu 108 KB

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