ggml-cuda.cu 119 KB

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