ggml-cuda.cu 130 KB

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