ggml-cuda.cu 119 KB

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