ggml-cuda.cu 119 KB

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