ggml-cuda.cu 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021
  1. #include <cstddef>
  2. #include <cstdint>
  3. #include <limits>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <atomic>
  7. #include <assert.h>
  8. #include <cuda_runtime.h>
  9. #include <cublas_v2.h>
  10. #include <cuda_fp16.h>
  11. #include "ggml-cuda.h"
  12. #include "ggml.h"
  13. #if defined(_MSC_VER)
  14. #pragma warning(disable: 4244 4267) // possible loss of data
  15. #endif
  16. static_assert(sizeof(half) == sizeof(ggml_fp16_t), "wrong fp16 size");
  17. #define CUDA_CHECK(err) \
  18. do { \
  19. cudaError_t err_ = (err); \
  20. if (err_ != cudaSuccess) { \
  21. fprintf(stderr, "CUDA error %d at %s:%d: %s\n", err_, __FILE__, __LINE__, \
  22. cudaGetErrorString(err_)); \
  23. exit(1); \
  24. } \
  25. } while (0)
  26. #if CUDART_VERSION >= 12000
  27. #define CUBLAS_CHECK(err) \
  28. do { \
  29. cublasStatus_t err_ = (err); \
  30. if (err_ != CUBLAS_STATUS_SUCCESS) { \
  31. fprintf(stderr, "\ncuBLAS error %d at %s:%d: %s\n", \
  32. err_, __FILE__, __LINE__, cublasGetStatusString(err_)); \
  33. exit(1); \
  34. } \
  35. } while (0)
  36. #else
  37. #define CUBLAS_CHECK(err) \
  38. do { \
  39. cublasStatus_t err_ = (err); \
  40. if (err_ != CUBLAS_STATUS_SUCCESS) { \
  41. fprintf(stderr, "\ncuBLAS error %d at %s:%d\n", err_, __FILE__, __LINE__); \
  42. exit(1); \
  43. } \
  44. } while (0)
  45. #endif // CUDART_VERSION >= 11
  46. #ifdef GGML_CUDA_DMMV_F16
  47. typedef half dfloat; // dequantize float
  48. typedef half2 dfloat2;
  49. #else
  50. typedef float dfloat; // dequantize float
  51. typedef float2 dfloat2;
  52. #endif //GGML_CUDA_DMMV_F16
  53. typedef void (*dequantize_kernel_t)(const void * vx, const int ib, const int iqs, dfloat2 & v);
  54. typedef void (*to_fp32_cuda_t)(const void * x, float * y, int k, cudaStream_t stream);
  55. typedef void (*dot_kernel_k_t)(const void * vx, const int ib, const int iqs, const float * y, float & v);
  56. typedef void (*cpy_kernel_t)(const char * cx, char * cdst);
  57. typedef void (*ggml_cuda_func_t)(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
  58. typedef void (*ggml_cuda_op_t)(
  59. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i, float * src0_ddf_i,
  60. float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  61. cudaStream_t & cudaStream_main);
  62. // QK = number of values after dequantization
  63. // QR = QK / number of values before dequantization
  64. #define QK4_0 32
  65. #define QR4_0 2
  66. typedef struct {
  67. half d; // delta
  68. uint8_t qs[QK4_0 / 2]; // nibbles / quants
  69. } block_q4_0;
  70. static_assert(sizeof(block_q4_0) == sizeof(ggml_fp16_t) + QK4_0 / 2, "wrong q4_0 block size/padding");
  71. #define QK4_1 32
  72. #define QR4_1 2
  73. typedef struct {
  74. half d; // delta
  75. half m; // min
  76. uint8_t qs[QK4_1 / 2]; // nibbles / quants
  77. } block_q4_1;
  78. static_assert(sizeof(block_q4_1) == sizeof(ggml_fp16_t) * 2 + QK4_1 / 2, "wrong q4_1 block size/padding");
  79. #define QK5_0 32
  80. #define QR5_0 2
  81. typedef struct {
  82. half d; // delta
  83. uint8_t qh[4]; // 5-th bit of quants
  84. uint8_t qs[QK5_0 / 2]; // nibbles / quants
  85. } block_q5_0;
  86. static_assert(sizeof(block_q5_0) == sizeof(ggml_fp16_t) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding");
  87. #define QK5_1 32
  88. #define QR5_1 2
  89. typedef struct {
  90. half d; // delta
  91. half m; // min
  92. uint8_t qh[4]; // 5-th bit of quants
  93. uint8_t qs[QK5_1 / 2]; // nibbles / quants
  94. } block_q5_1;
  95. static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_fp16_t) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding");
  96. #define QK8_0 32
  97. #define QR8_0 1
  98. typedef struct {
  99. half d; // delta
  100. int8_t qs[QK8_0]; // quants
  101. } block_q8_0;
  102. static_assert(sizeof(block_q8_0) == sizeof(ggml_fp16_t) + QK8_0, "wrong q8_0 block size/padding");
  103. //================================= k-quants
  104. #ifdef GGML_QKK_64
  105. #define QK_K 64
  106. #define K_SCALE_SIZE 4
  107. #else
  108. #define QK_K 256
  109. #define K_SCALE_SIZE 12
  110. #endif
  111. typedef struct {
  112. uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits
  113. uint8_t qs[QK_K/4]; // quants
  114. half d; // super-block scale for quantized scales
  115. half dmin; // super-block scale for quantized mins
  116. } block_q2_K;
  117. static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_fp16_t) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding");
  118. typedef struct {
  119. uint8_t hmask[QK_K/8]; // quants - high bit
  120. uint8_t qs[QK_K/4]; // quants - low 2 bits
  121. #ifdef GGML_QKK_64
  122. uint8_t scales[2]; // scales, quantized with 8 bits
  123. #else
  124. uint8_t scales[K_SCALE_SIZE]; // scales, quantized with 6 bits
  125. #endif
  126. half d; // super-block scale
  127. } block_q3_K;
  128. //static_assert(sizeof(block_q3_K) == sizeof(ggml_fp16_t) + QK_K / 4 + QK_K / 8 + K_SCALE_SIZE, "wrong q3_K block size/padding");
  129. #ifdef GGML_QKK_64
  130. typedef struct {
  131. half d[2]; // super-block scales/mins
  132. uint8_t scales[2]; // 4-bit block scales/mins
  133. uint8_t qs[QK_K/2]; // 4--bit quants
  134. } block_q4_K;
  135. static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_fp16_t) + QK_K/2 + 2, "wrong q4_K block size/padding");
  136. #else
  137. typedef struct {
  138. half d; // super-block scale for quantized scales
  139. half dmin; // super-block scale for quantized mins
  140. uint8_t scales[3*QK_K/64]; // scales, quantized with 6 bits
  141. uint8_t qs[QK_K/2]; // 4--bit quants
  142. } block_q4_K;
  143. static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_fp16_t) + 3*QK_K/64 + QK_K/2, "wrong q4_K block size/padding");
  144. #endif
  145. #ifdef GGML_QKK_64
  146. typedef struct {
  147. half d; // super-block scale
  148. int8_t scales[QK_K/16]; // block scales
  149. uint8_t qh[QK_K/8]; // quants, high bit
  150. uint8_t qs[QK_K/2]; // quants, low 4 bits
  151. } block_q5_K;
  152. static_assert(sizeof(block_q5_K) == sizeof(ggml_fp16_t) + QK_K/2 + QK_K/8 + QK_K/16, "wrong q5_K block size/padding");
  153. #else
  154. typedef struct {
  155. half d; // super-block scale for quantized scales
  156. half dmin; // super-block scale for quantized mins
  157. uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits
  158. uint8_t qh[QK_K/8]; // quants, high bit
  159. uint8_t qs[QK_K/2]; // quants, low 4 bits
  160. } block_q5_K;
  161. static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_fp16_t) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding");
  162. #endif
  163. typedef struct {
  164. uint8_t ql[QK_K/2]; // quants, lower 4 bits
  165. uint8_t qh[QK_K/4]; // quants, upper 2 bits
  166. int8_t scales[QK_K/16]; // scales
  167. half d; // delta
  168. } block_q6_K;
  169. static_assert(sizeof(block_q6_K) == sizeof(ggml_fp16_t) + 13*QK_K/16, "wrong q6_K block size/padding");
  170. #define WARP_SIZE 32
  171. #define CUDA_ADD_BLOCK_SIZE 256
  172. #define CUDA_MUL_BLOCK_SIZE 256
  173. #define CUDA_SILU_BLOCK_SIZE 256
  174. #define CUDA_CPY_BLOCK_SIZE 32
  175. #define CUDA_SCALE_BLOCK_SIZE 256
  176. #define CUDA_ROPE_BLOCK_SIZE 256
  177. #define CUDA_DIAG_MASK_INF_BLOCK_SIZE 32
  178. #define CUDA_DEQUANTIZE_BLOCK_SIZE 256
  179. // dmmv = dequantize_mul_mat_vec
  180. #ifndef GGML_CUDA_DMMV_X
  181. #define GGML_CUDA_DMMV_X 32
  182. #endif
  183. #ifndef GGML_CUDA_DMMV_Y
  184. #define GGML_CUDA_DMMV_Y 1
  185. #endif
  186. #ifndef K_QUANTS_PER_ITERATION
  187. #define K_QUANTS_PER_ITERATION 2
  188. #else
  189. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  190. #endif
  191. static __global__ void add_f32(const float * x, const float * y, float * dst, const int k) {
  192. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  193. if (i >= k) {
  194. return;
  195. }
  196. dst[i] = x[i] + y[i];
  197. }
  198. static __global__ void add_f16_f32_f16(const half * x, const float * y, half * dst, const int k) {
  199. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  200. if (i >= k) {
  201. return;
  202. }
  203. dst[i] = __hadd(x[i], __float2half(y[i]));
  204. }
  205. static __global__ void mul_f32(const float * x, const float * y, float * dst, const int kx, const int ky) {
  206. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  207. if (i >= kx) {
  208. return;
  209. }
  210. dst[i] = x[i] * y[i%ky];
  211. }
  212. static __global__ void silu_f32(const float * x, float * dst, const int k) {
  213. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  214. if (i >= k) {
  215. return;
  216. }
  217. dst[i] = x[i] / (1.0f + expf(-x[i]));
  218. }
  219. static __global__ void rms_norm_f32(const float * x, float * dst, const int ncols) {
  220. const int row = blockIdx.x*blockDim.y + threadIdx.y;
  221. const int tid = threadIdx.x;
  222. const float eps = 1e-6;
  223. float tmp = 0.0f; // partial sum for thread in warp
  224. for (int i = 0; i < ncols; i += WARP_SIZE) {
  225. const int col = i + tid;
  226. const float xi = x[row*ncols + col];
  227. tmp += xi * xi;
  228. }
  229. // sum up partial sums
  230. __syncthreads();
  231. #pragma unroll
  232. for (int mask = 16; mask > 0; mask >>= 1) {
  233. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  234. }
  235. const float mean = tmp / ncols;
  236. const float scale = 1.0f / sqrtf(mean + eps);
  237. for (int i = 0; i < ncols; i += WARP_SIZE) {
  238. const int col = i + tid;
  239. dst[row*ncols + col] = scale * x[row*ncols + col];
  240. }
  241. }
  242. static __device__ __forceinline__ void dequantize_q4_0(const void * vx, const int ib, const int iqs, dfloat2 & v){
  243. const block_q4_0 * x = (const block_q4_0 *) vx;
  244. const dfloat d = x[ib].d;
  245. const int vui = x[ib].qs[iqs];
  246. v.x = vui & 0xF;
  247. v.y = vui >> 4;
  248. #ifdef GGML_CUDA_DMMV_F16
  249. v = __hsub2(v, {8.0f, 8.0f});
  250. v = __hmul2(v, {d, d});
  251. #else
  252. v.x = (v.x - 8.0f) * d;
  253. v.y = (v.y - 8.0f) * d;
  254. #endif // GGML_CUDA_DMMV_F16
  255. }
  256. static __device__ __forceinline__ void dequantize_q4_1(const void * vx, const int ib, const int iqs, dfloat2 & v){
  257. const block_q4_1 * x = (const block_q4_1 *) vx;
  258. const dfloat d = x[ib].d;
  259. const dfloat m = x[ib].m;
  260. const int vui = x[ib].qs[iqs];
  261. v.x = vui & 0xF;
  262. v.y = vui >> 4;
  263. #ifdef GGML_CUDA_DMMV_F16
  264. v = __hmul2(v, {d, d});
  265. v = __hadd2(v, {m, m});
  266. #else
  267. v.x = (v.x * d) + m;
  268. v.y = (v.y * d) + m;
  269. #endif // GGML_CUDA_DMMV_F16
  270. }
  271. static __device__ __forceinline__ void dequantize_q5_0(const void * vx, const int ib, const int iqs, dfloat2 & v){
  272. const block_q5_0 * x = (const block_q5_0 *) vx;
  273. const dfloat d = x[ib].d;
  274. uint32_t qh;
  275. memcpy(&qh, x[ib].qh, sizeof(qh));
  276. const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
  277. const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10;
  278. v.x = ((x[ib].qs[iqs] & 0xf) | xh_0);
  279. v.y = ((x[ib].qs[iqs] >> 4) | xh_1);
  280. #ifdef GGML_CUDA_DMMV_F16
  281. v = __hsub2(v, {16.0f, 16.0f});
  282. v = __hmul2(v, {d, d});
  283. #else
  284. v.x = (v.x - 16.0f) * d;
  285. v.y = (v.y - 16.0f) * d;
  286. #endif // GGML_CUDA_DMMV_F16
  287. }
  288. static __device__ __forceinline__ void dequantize_q5_1(const void * vx, const int ib, const int iqs, dfloat2 & v){
  289. const block_q5_1 * x = (const block_q5_1 *) vx;
  290. const dfloat d = x[ib].d;
  291. const dfloat m = x[ib].m;
  292. uint32_t qh;
  293. memcpy(&qh, x[ib].qh, sizeof(qh));
  294. const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
  295. const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10;
  296. v.x = ((x[ib].qs[iqs] & 0xf) | xh_0);
  297. v.y = ((x[ib].qs[iqs] >> 4) | xh_1);
  298. #ifdef GGML_CUDA_DMMV_F16
  299. v = __hmul2(v, {d, d});
  300. v = __hadd2(v, {m, m});
  301. #else
  302. v.x = (v.x * d) + m;
  303. v.y = (v.y * d) + m;
  304. #endif // GGML_CUDA_DMMV_F16
  305. }
  306. static __device__ __forceinline__ void dequantize_q8_0(const void * vx, const int ib, const int iqs, dfloat2 & v){
  307. const block_q8_0 * x = (const block_q8_0 *) vx;
  308. const dfloat d = x[ib].d;
  309. v.x = x[ib].qs[iqs + 0];
  310. v.y = x[ib].qs[iqs + 1];
  311. #ifdef GGML_CUDA_DMMV_F16
  312. v = __hmul2(v, {d, d});
  313. #else
  314. v.x *= d;
  315. v.y *= d;
  316. #endif // GGML_CUDA_DMMV_F16
  317. }
  318. //================================== k-quants
  319. static __global__ void dequantize_block_q2_K(const void * vx, float * yy) {
  320. const int i = blockIdx.x;
  321. const block_q2_K * x = (const block_q2_K *) vx;
  322. const int tid = threadIdx.x;
  323. #if QK_K == 256
  324. const int n = tid/32;
  325. const int l = tid - 32*n;
  326. const int is = 8*n + l/16;
  327. const uint8_t q = x[i].qs[32*n + l];
  328. float * y = yy + i*QK_K + 128*n;
  329. float dall = x[i].d;
  330. float dmin = x[i].dmin;
  331. y[l+ 0] = dall * (x[i].scales[is+0] & 0xF) * ((q >> 0) & 3) - dmin * (x[i].scales[is+0] >> 4);
  332. y[l+32] = dall * (x[i].scales[is+2] & 0xF) * ((q >> 2) & 3) - dmin * (x[i].scales[is+2] >> 4);
  333. y[l+64] = dall * (x[i].scales[is+4] & 0xF) * ((q >> 4) & 3) - dmin * (x[i].scales[is+4] >> 4);
  334. y[l+96] = dall * (x[i].scales[is+6] & 0xF) * ((q >> 6) & 3) - dmin * (x[i].scales[is+6] >> 4);
  335. #else
  336. const int is = tid/16; // 0 or 1
  337. const int il = tid%16; // 0...15
  338. const uint8_t q = x[i].qs[il] >> (2*is);
  339. float * y = yy + i*QK_K + 16*is + il;
  340. float dall = x[i].d;
  341. float dmin = x[i].dmin;
  342. y[ 0] = dall * (x[i].scales[is+0] & 0xF) * ((q >> 0) & 3) - dmin * (x[i].scales[is+0] >> 4);
  343. y[32] = dall * (x[i].scales[is+2] & 0xF) * ((q >> 4) & 3) - dmin * (x[i].scales[is+2] >> 4);
  344. #endif
  345. }
  346. static __global__ void dequantize_block_q3_K(const void * vx, float * yy) {
  347. const int i = blockIdx.x;
  348. const block_q3_K * x = (const block_q3_K *) vx;
  349. #if QK_K == 256
  350. const int r = threadIdx.x/4;
  351. const int tid = r/2;
  352. const int is0 = r%2;
  353. const int l0 = 16*is0 + 4*(threadIdx.x%4);
  354. const int n = tid / 4;
  355. const int j = tid - 4*n;
  356. uint8_t m = 1 << (4*n + j);
  357. int is = 8*n + 2*j + is0;
  358. int shift = 2*j;
  359. int8_t us = is < 4 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+8] >> 0) & 3) << 4) :
  360. is < 8 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+4] >> 2) & 3) << 4) :
  361. is < 12 ? (x[i].scales[is-8] >> 4) | (((x[i].scales[is+0] >> 4) & 3) << 4) :
  362. (x[i].scales[is-8] >> 4) | (((x[i].scales[is-4] >> 6) & 3) << 4);
  363. float d_all = x[i].d;
  364. float dl = d_all * (us - 32);
  365. float * y = yy + i*QK_K + 128*n + 32*j;
  366. const uint8_t * q = x[i].qs + 32*n;
  367. const uint8_t * hm = x[i].hmask;
  368. for (int l = l0; l < l0+4; ++l) y[l] = dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4));
  369. #else
  370. const int tid = threadIdx.x;
  371. const int is = tid/16; // 0 or 1
  372. const int il = tid%16; // 0...15
  373. const int im = il/8; // 0...1
  374. const int in = il%8; // 0...7
  375. float * y = yy + i*QK_K + 16*is + il;
  376. const uint8_t q = x[i].qs[il] >> (2*is);
  377. const uint8_t h = x[i].hmask[in] >> (2*is + im);
  378. const float d = (float)x[i].d;
  379. if (is == 0) {
  380. y[ 0] = d * ((x[i].scales[0] & 0xF) - 8) * ((int8_t)((q >> 0) & 3) - ((h >> 0) & 1 ? 0 : 4));
  381. y[32] = d * ((x[i].scales[1] & 0xF) - 8) * ((int8_t)((q >> 4) & 3) - ((h >> 4) & 1 ? 0 : 4));
  382. } else {
  383. y[ 0] = d * ((x[i].scales[0] >> 4) - 8) * ((int8_t)((q >> 0) & 3) - ((h >> 0) & 1 ? 0 : 4));
  384. y[32] = d * ((x[i].scales[1] >> 4) - 8) * ((int8_t)((q >> 4) & 3) - ((h >> 4) & 1 ? 0 : 4));
  385. }
  386. #endif
  387. }
  388. #if QK_K == 256
  389. static inline __device__ void get_scale_min_k4(int j, const uint8_t * q, uint8_t & d, uint8_t & m) {
  390. if (j < 4) {
  391. d = q[j] & 63; m = q[j + 4] & 63;
  392. } else {
  393. d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4);
  394. m = (q[j+4] >> 4) | ((q[j-0] >> 6) << 4);
  395. }
  396. }
  397. #endif
  398. static __global__ void dequantize_block_q4_K(const void * vx, float * yy) {
  399. const block_q4_K * x = (const block_q4_K *) vx;
  400. const int i = blockIdx.x;
  401. #if QK_K == 256
  402. // assume 32 threads
  403. const int tid = threadIdx.x;
  404. const int il = tid/8;
  405. const int ir = tid%8;
  406. const int is = 2*il;
  407. const int n = 4;
  408. float * y = yy + i*QK_K + 64*il + n*ir;
  409. const float dall = x[i].d;
  410. const float dmin = x[i].dmin;
  411. const uint8_t * q = x[i].qs + 32*il + n*ir;
  412. uint8_t sc, m;
  413. get_scale_min_k4(is + 0, x[i].scales, sc, m);
  414. const float d1 = dall * sc; const float m1 = dmin * m;
  415. get_scale_min_k4(is + 1, x[i].scales, sc, m);
  416. const float d2 = dall * sc; const float m2 = dmin * m;
  417. for (int l = 0; l < n; ++l) {
  418. y[l + 0] = d1 * (q[l] & 0xF) - m1;
  419. y[l +32] = d2 * (q[l] >> 4) - m2;
  420. }
  421. #else
  422. const int tid = threadIdx.x;
  423. const uint8_t * q = x[i].qs;
  424. float * y = yy + i*QK_K;
  425. const float d = (float)x[i].d[0];
  426. const float m = (float)x[i].d[1];
  427. y[tid+ 0] = d * (x[i].scales[0] & 0xF) * (q[tid] & 0xF) - m * (x[i].scales[0] >> 4);
  428. y[tid+32] = d * (x[i].scales[1] & 0xF) * (q[tid] >> 4) - m * (x[i].scales[1] >> 4);
  429. #endif
  430. }
  431. static __global__ void dequantize_block_q5_K(const void * vx, float * yy) {
  432. const block_q5_K * x = (const block_q5_K *) vx;
  433. const int i = blockIdx.x;
  434. #if QK_K == 256
  435. // assume 64 threads - this is very slightly better than the one below
  436. const int tid = threadIdx.x;
  437. const int il = tid/16; // il is in 0...3
  438. const int ir = tid%16; // ir is in 0...15
  439. const int is = 2*il; // is is in 0...6
  440. float * y = yy + i*QK_K + 64*il + 2*ir;
  441. const float dall = x[i].d;
  442. const float dmin = x[i].dmin;
  443. const uint8_t * ql = x[i].qs + 32*il + 2*ir;
  444. const uint8_t * qh = x[i].qh + 2*ir;
  445. uint8_t sc, m;
  446. get_scale_min_k4(is + 0, x[i].scales, sc, m);
  447. const float d1 = dall * sc; const float m1 = dmin * m;
  448. get_scale_min_k4(is + 1, x[i].scales, sc, m);
  449. const float d2 = dall * sc; const float m2 = dmin * m;
  450. uint8_t hm = 1 << (2*il);
  451. y[ 0] = d1 * ((ql[ 0] & 0xF) + (qh[ 0] & hm ? 16 : 0)) - m1;
  452. y[ 1] = d1 * ((ql[ 1] & 0xF) + (qh[ 1] & hm ? 16 : 0)) - m1;
  453. hm <<= 1;
  454. y[32] = d2 * ((ql[ 0] >> 4) + (qh[ 0] & hm ? 16 : 0)) - m2;
  455. y[33] = d2 * ((ql[ 1] >> 4) + (qh[ 1] & hm ? 16 : 0)) - m2;
  456. #else
  457. const int tid = threadIdx.x;
  458. const uint8_t q = x[i].qs[tid];
  459. const int im = tid/8; // 0...3
  460. const int in = tid%8; // 0...7
  461. const int is = tid/16; // 0 or 1
  462. const uint8_t h = x[i].qh[in] >> im;
  463. const float d = x[i].d;
  464. float * y = yy + i*QK_K + tid;
  465. y[ 0] = d * x[i].scales[is+0] * ((q & 0xF) - ((h >> 0) & 1 ? 0 : 16));
  466. y[32] = d * x[i].scales[is+2] * ((q >> 4) - ((h >> 4) & 1 ? 0 : 16));
  467. #endif
  468. }
  469. static __global__ void dequantize_block_q6_K(const void * vx, float * yy) {
  470. const block_q6_K * x = (const block_q6_K *) vx;
  471. const int i = blockIdx.x;
  472. #if QK_K == 256
  473. // assume 64 threads - this is very slightly better than the one below
  474. const int tid = threadIdx.x;
  475. const int ip = tid/32; // ip is 0 or 1
  476. const int il = tid - 32*ip; // 0...32
  477. const int is = 8*ip + il/16;
  478. float * y = yy + i*QK_K + 128*ip + il;
  479. const float d = x[i].d;
  480. const uint8_t * ql = x[i].ql + 64*ip + il;
  481. const uint8_t qh = x[i].qh[32*ip + il];
  482. const int8_t * sc = x[i].scales + is;
  483. y[ 0] = d * sc[0] * ((int8_t)((ql[ 0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32);
  484. y[32] = d * sc[2] * ((int8_t)((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32);
  485. y[64] = d * sc[4] * ((int8_t)((ql[ 0] >> 4) | (((qh >> 4) & 3) << 4)) - 32);
  486. y[96] = d * sc[6] * ((int8_t)((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32);
  487. #else
  488. // assume 32 threads
  489. const int tid = threadIdx.x;
  490. const int ip = tid/16; // 0 or 1
  491. const int il = tid - 16*ip; // 0...15
  492. float * y = yy + i*QK_K + 16*ip + il;
  493. const float d = x[i].d;
  494. const uint8_t ql = x[i].ql[16*ip + il];
  495. const uint8_t qh = x[i].qh[il] >> (2*ip);
  496. const int8_t * sc = x[i].scales;
  497. y[ 0] = d * sc[ip+0] * ((int8_t)((ql & 0xF) | (((qh >> 0) & 3) << 4)) - 32);
  498. y[32] = d * sc[ip+2] * ((int8_t)((ql >> 4) | (((qh >> 4) & 3) << 4)) - 32);
  499. #endif
  500. }
  501. static __global__ void dequantize_mul_mat_vec_q2_k(const void * vx, const float * yy, float * dst, const int ncols, int nrows) {
  502. static_assert(16%K_QUANTS_PER_ITERATION == 0, "16 must be divisible by K_QUANTS_PER_ITERATION");
  503. const int row = blockIdx.y*blockDim.y + threadIdx.y;
  504. if (row > nrows) return;
  505. const int num_blocks_per_row = ncols / QK_K;
  506. const int ib0 = row*num_blocks_per_row;
  507. const block_q2_K * x = (const block_q2_K *)vx + ib0;
  508. float tmp = 0; // partial sum for thread in warp
  509. #if QK_K == 256
  510. const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...15
  511. const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1
  512. const int step = 16/K_QUANTS_PER_ITERATION;
  513. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  514. const int in = tid - step*im; // 0...15 or 0...7
  515. const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15 or 0...14 in steps of 2
  516. const int q_offset = 32*im + l0;
  517. const int s_offset = 8*im;
  518. const int y_offset = 128*im + l0;
  519. uint32_t aux[4];
  520. const uint8_t * d = (const uint8_t *)aux;
  521. const uint8_t * m = (const uint8_t *)(aux + 2);
  522. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  523. const float * y = yy + i * QK_K + y_offset;
  524. const uint8_t * q = x[i].qs + q_offset;
  525. const float dall = x[i].d;
  526. const float dmin = x[i].dmin;
  527. const uint32_t * a = (const uint32_t *)(x[i].scales + s_offset);
  528. aux[0] = a[0] & 0x0f0f0f0f;
  529. aux[1] = a[1] & 0x0f0f0f0f;
  530. aux[2] = (a[0] >> 4) & 0x0f0f0f0f;
  531. aux[3] = (a[1] >> 4) & 0x0f0f0f0f;
  532. float sum1 = 0, sum2 = 0;
  533. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  534. sum1 += y[l+ 0] * d[0] * ((q[l+ 0] >> 0) & 3)
  535. + y[l+32] * d[2] * ((q[l+ 0] >> 2) & 3)
  536. + y[l+64] * d[4] * ((q[l+ 0] >> 4) & 3)
  537. + y[l+96] * d[6] * ((q[l+ 0] >> 6) & 3)
  538. + y[l+16] * d[1] * ((q[l+16] >> 0) & 3)
  539. + y[l+48] * d[3] * ((q[l+16] >> 2) & 3)
  540. + y[l+80] * d[5] * ((q[l+16] >> 4) & 3)
  541. +y[l+112] * d[7] * ((q[l+16] >> 6) & 3);
  542. sum2 += y[l+ 0] * m[0] + y[l+32] * m[2] + y[l+64] * m[4] + y[ l+96] * m[6]
  543. + y[l+16] * m[1] + y[l+48] * m[3] + y[l+80] * m[5] + y[l+112] * m[7];
  544. }
  545. tmp += dall * sum1 - dmin * sum2;
  546. }
  547. #else
  548. const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 or 0...7
  549. const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0....1 or 0...3
  550. const int offset = tid * K_QUANTS_PER_ITERATION;
  551. uint32_t uaux[2];
  552. const uint8_t * d = (const uint8_t *)uaux;
  553. for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) {
  554. const float * y = yy + i * QK_K + offset;
  555. const uint8_t * q = x[i].qs + offset;
  556. const uint32_t * s = (const uint32_t *)x[i].scales;
  557. uaux[0] = s[0] & 0x0f0f0f0f;
  558. uaux[1] = (s[0] >> 4) & 0x0f0f0f0f;
  559. const half2 * dh = (const half2 *)&x[i].d;
  560. const float2 dall = __half22float2(dh[0]);
  561. float sum1 = 0, sum2 = 0;
  562. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  563. const uint8_t ql = q[l];
  564. sum1 += y[l+ 0] * d[0] * ((ql >> 0) & 3)
  565. + y[l+16] * d[1] * ((ql >> 2) & 3)
  566. + y[l+32] * d[2] * ((ql >> 4) & 3)
  567. + y[l+48] * d[3] * ((ql >> 6) & 3);
  568. sum2 += y[l+0] * d[4] + y[l+16] * d[5] + y[l+32] * d[6] + y[l+48] * d[7];
  569. }
  570. tmp += dall.x * sum1 - dall.y * sum2;
  571. }
  572. #endif
  573. // sum up partial sums and write back result
  574. __syncthreads();
  575. #pragma unroll
  576. for (int mask = 16; mask > 0; mask >>= 1) {
  577. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  578. }
  579. if (threadIdx.x == 0) {
  580. dst[row] = tmp;
  581. }
  582. }
  583. static __global__ void dequantize_mul_mat_vec_q3_k(const void * vx, const float * yy, float * dst, const int ncols, int nrows) {
  584. const int row = blockIdx.y*blockDim.y + threadIdx.y;
  585. if (row > nrows) return;
  586. const int num_blocks_per_row = ncols / QK_K;
  587. const int ib0 = row*num_blocks_per_row;
  588. const block_q3_K * x = (const block_q3_K *)vx + ib0;
  589. float tmp = 0; // partial sum for thread in warp
  590. #if QK_K == 256
  591. const uint16_t kmask1 = 0x0303;
  592. const uint16_t kmask2 = 0x0f0f;
  593. const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  594. const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1
  595. const int n = K_QUANTS_PER_ITERATION; // iterations in the inner loop
  596. const int step = 16/K_QUANTS_PER_ITERATION;
  597. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  598. const int in = tid - step*im; // 0....15 or 0...7
  599. const uint8_t m = 1 << (4*im);
  600. const int l0 = n*in; // 0...15 or 0...14 in steps of 2
  601. const int q_offset = 32*im + l0;
  602. const int y_offset = 128*im + l0;
  603. uint16_t utmp[4];
  604. const int8_t * s = (const int8_t *)utmp;
  605. const uint16_t s_shift = 4*im;
  606. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  607. const float * y = yy + i * QK_K + y_offset;
  608. const uint8_t * q = x[i].qs + q_offset;
  609. const uint8_t * h = x[i].hmask + l0;
  610. const uint16_t * a = (const uint16_t *)x[i].scales;
  611. utmp[0] = ((a[0] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 0)) & kmask1) << 4);
  612. utmp[1] = ((a[1] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 0)) & kmask1) << 4);
  613. utmp[2] = ((a[2] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 2)) & kmask1) << 4);
  614. utmp[3] = ((a[3] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 2)) & kmask1) << 4);
  615. const float d = x[i].d;
  616. float sum = 0;
  617. for (int l = 0; l < n; ++l) {
  618. sum += y[l+ 0] * (s[0] - 32) * (((q[l] >> 0) & 3) - (h[l] & (m << 0) ? 0 : 4))
  619. + y[l+32] * (s[2] - 32) * (((q[l] >> 2) & 3) - (h[l] & (m << 1) ? 0 : 4))
  620. + y[l+64] * (s[4] - 32) * (((q[l] >> 4) & 3) - (h[l] & (m << 2) ? 0 : 4))
  621. + y[l+96] * (s[6] - 32) * (((q[l] >> 6) & 3) - (h[l] & (m << 3) ? 0 : 4));
  622. sum += y[l+16] * (s[1] - 32) * (((q[l+16] >> 0) & 3) - (h[l+16] & (m << 0) ? 0 : 4))
  623. + y[l+48] * (s[3] - 32) * (((q[l+16] >> 2) & 3) - (h[l+16] & (m << 1) ? 0 : 4))
  624. + y[l+80] * (s[5] - 32) * (((q[l+16] >> 4) & 3) - (h[l+16] & (m << 2) ? 0 : 4))
  625. + y[l+112] * (s[7] - 32) * (((q[l+16] >> 6) & 3) - (h[l+16] & (m << 3) ? 0 : 4));
  626. }
  627. tmp += d * sum;
  628. }
  629. #else
  630. const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 or 0...7
  631. const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0....1 or 0...3
  632. const int offset = tid * K_QUANTS_PER_ITERATION; // 0...15 or 0...14
  633. const int in = offset/8; // 0 or 1
  634. const int im = offset%8; // 0...7
  635. for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) {
  636. const float * y = yy + i * QK_K + offset;
  637. const uint8_t * q = x[i].qs + offset;
  638. const uint8_t * s = x[i].scales;
  639. const float dall = (float)x[i].d;
  640. float sum = 0;
  641. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  642. const uint8_t hl = x[i].hmask[im+l] >> in;
  643. const uint8_t ql = q[l];
  644. sum += y[l+ 0] * dall * ((s[0] & 0xF) - 8) * ((int8_t)((ql >> 0) & 3) - ((hl >> 0) & 1 ? 0 : 4))
  645. + y[l+16] * dall * ((s[0] >> 4) - 8) * ((int8_t)((ql >> 2) & 3) - ((hl >> 2) & 1 ? 0 : 4))
  646. + y[l+32] * dall * ((s[1] & 0xF) - 8) * ((int8_t)((ql >> 4) & 3) - ((hl >> 4) & 1 ? 0 : 4))
  647. + y[l+48] * dall * ((s[1] >> 4) - 8) * ((int8_t)((ql >> 6) & 3) - ((hl >> 6) & 1 ? 0 : 4));
  648. }
  649. tmp += sum;
  650. }
  651. #endif
  652. // sum up partial sums and write back result
  653. __syncthreads();
  654. #pragma unroll
  655. for (int mask = 16; mask > 0; mask >>= 1) {
  656. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  657. }
  658. if (threadIdx.x == 0) {
  659. dst[row] = tmp;
  660. }
  661. }
  662. static __global__ void dequantize_mul_mat_vec_q4_k(const void * vx, const float * yy, float * dst, const int ncols, int nrows) {
  663. const int row = blockIdx.y*blockDim.y + threadIdx.y;
  664. if (row > nrows) return;
  665. const int num_blocks_per_row = ncols / QK_K;
  666. const int ib0 = row*num_blocks_per_row;
  667. const block_q4_K * x = (const block_q4_K *)vx + ib0;
  668. #if QK_K == 256
  669. const uint16_t kmask1 = 0x3f3f;
  670. const uint16_t kmask2 = 0x0f0f;
  671. const uint16_t kmask3 = 0xc0c0;
  672. const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  673. const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1
  674. const int step = 8/K_QUANTS_PER_ITERATION; // 8 or 4
  675. const int il = tid/step; // 0...3
  676. const int ir = tid - step*il; // 0...7 or 0...3
  677. const int n = 2 * K_QUANTS_PER_ITERATION; // 2 or 4
  678. const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  679. const int in = il%2;
  680. const int l0 = n*(2*ir + in);
  681. const int q_offset = 32*im + l0;
  682. const int y_offset = 64*im + l0;
  683. uint16_t aux[4];
  684. const uint8_t * sc = (const uint8_t *)aux;
  685. float tmp = 0; // partial sum for thread in warp
  686. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  687. const uint8_t * q1 = x[i].qs + q_offset;
  688. const uint8_t * q2 = q1 + 64;
  689. const float * y1 = yy + i*QK_K + y_offset;
  690. const float * y2 = y1 + 128;
  691. const float dall = x[i].d;
  692. const float dmin = x[i].dmin;
  693. const uint16_t * a = (const uint16_t *)x[i].scales;
  694. aux[0] = a[im+0] & kmask1;
  695. aux[1] = a[im+2] & kmask1;
  696. aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2);
  697. aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2);
  698. float4 s = {0.f, 0.f, 0.f, 0.f};
  699. float smin = 0;
  700. for (int l = 0; l < n; ++l) {
  701. s.x += y1[l] * (q1[l] & 0xF); s.y += y1[l+32] * (q1[l] >> 4);
  702. s.z += y2[l] * (q2[l] & 0xF); s.w += y2[l+32] * (q2[l] >> 4);
  703. smin += y1[l] * sc[2] + y1[l+32] * sc[3] + y2[l] * sc[6] + y2[l+32] * sc[7];
  704. }
  705. tmp += dall * (s.x * sc[0] + s.y * sc[1] + s.z * sc[4] + s.w * sc[5]) - dmin * smin;
  706. }
  707. #else
  708. const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15
  709. const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION);
  710. const int step = tid * K_QUANTS_PER_ITERATION;
  711. uint16_t aux16[2];
  712. const uint8_t * s = (const uint8_t *)aux16;
  713. float tmp = 0;
  714. for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) {
  715. const uint8_t * q = x[i].qs + step;
  716. const float * y = yy + i*QK_K + step;
  717. const uint16_t * a = (const uint16_t *)x[i].scales;
  718. aux16[0] = a[0] & 0x0f0f;
  719. aux16[1] = (a[0] >> 4) & 0x0f0f;
  720. const float d = (float)x[i].d[0];
  721. const float m = (float)x[i].d[1];
  722. float sum = 0.f;
  723. for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) {
  724. sum += y[j+ 0] * (d * s[0] * (q[j+ 0] & 0xF) - m * s[2])
  725. + y[j+16] * (d * s[0] * (q[j+16] & 0xF) - m * s[2])
  726. + y[j+32] * (d * s[1] * (q[j+ 0] >> 4) - m * s[3])
  727. + y[j+48] * (d * s[1] * (q[j+16] >> 4) - m * s[3]);
  728. }
  729. tmp += sum;
  730. }
  731. #endif
  732. // sum up partial sums and write back result
  733. __syncthreads();
  734. #pragma unroll
  735. for (int mask = 16; mask > 0; mask >>= 1) {
  736. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  737. }
  738. if (tid == 0) {
  739. dst[row] = tmp;
  740. }
  741. }
  742. static __global__ void dequantize_mul_mat_vec_q5_k(const void * vx, const float * yy, float * dst, const int ncols) {
  743. const int row = blockIdx.x;
  744. const int num_blocks_per_row = ncols / QK_K;
  745. const int ib0 = row*num_blocks_per_row;
  746. const block_q5_K * x = (const block_q5_K *)vx + ib0;
  747. float tmp = 0; // partial sum for thread in warp
  748. #if QK_K == 256
  749. const uint16_t kmask1 = 0x3f3f;
  750. const uint16_t kmask2 = 0x0f0f;
  751. const uint16_t kmask3 = 0xc0c0;
  752. const int tid = threadIdx.x/2; // 0...15
  753. const int ix = threadIdx.x%2;
  754. const int il = tid/4; // 0...3
  755. const int ir = tid - 4*il;// 0...3
  756. const int n = 2;
  757. const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  758. const int in = il%2;
  759. const int l0 = n*(2*ir + in);
  760. const int q_offset = 32*im + l0;
  761. const int y_offset = 64*im + l0;
  762. const uint8_t hm1 = 1 << (2*im);
  763. const uint8_t hm2 = hm1 << 4;
  764. uint16_t aux[4];
  765. const uint8_t * sc = (const uint8_t *)aux;
  766. for (int i = ix; i < num_blocks_per_row; i += 2) {
  767. const uint8_t * ql1 = x[i].qs + q_offset;
  768. const uint8_t * ql2 = ql1 + 64;
  769. const uint8_t * qh = x[i].qh + l0;
  770. const float * y1 = yy + i*QK_K + y_offset;
  771. const float * y2 = y1 + 128;
  772. const float dall = x[i].d;
  773. const float dmin = x[i].dmin;
  774. const uint16_t * a = (const uint16_t *)x[i].scales;
  775. aux[0] = a[im+0] & kmask1;
  776. aux[1] = a[im+2] & kmask1;
  777. aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2);
  778. aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2);
  779. float4 sum = {0.f, 0.f, 0.f, 0.f};
  780. float smin = 0;
  781. for (int l = 0; l < n; ++l) {
  782. sum.x += y1[l+ 0] * ((ql1[l+ 0] & 0xF) + (qh[l+ 0] & (hm1 << 0) ? 16 : 0))
  783. + y1[l+16] * ((ql1[l+16] & 0xF) + (qh[l+16] & (hm1 << 0) ? 16 : 0));
  784. sum.y += y1[l+32] * ((ql1[l+ 0] >> 4) + (qh[l+ 0] & (hm1 << 1) ? 16 : 0))
  785. + y1[l+48] * ((ql1[l+16] >> 4) + (qh[l+16] & (hm1 << 1) ? 16 : 0));
  786. sum.z += y2[l+ 0] * ((ql2[l+ 0] & 0xF) + (qh[l+ 0] & (hm2 << 0) ? 16 : 0))
  787. + y2[l+16] * ((ql2[l+16] & 0xF) + (qh[l+16] & (hm2 << 0) ? 16 : 0));
  788. sum.w += y2[l+32] * ((ql2[l+ 0] >> 4) + (qh[l+ 0] & (hm2 << 1) ? 16 : 0))
  789. + y2[l+48] * ((ql2[l+16] >> 4) + (qh[l+16] & (hm2 << 1) ? 16 : 0));
  790. smin += (y1[l] + y1[l+16]) * sc[2] + (y1[l+32] + y1[l+48]) * sc[3]
  791. + (y2[l] + y2[l+16]) * sc[6] + (y2[l+32] + y2[l+48]) * sc[7];
  792. }
  793. tmp += dall * (sum.x * sc[0] + sum.y * sc[1] + sum.z * sc[4] + sum.w * sc[5]) - dmin * smin;
  794. }
  795. #else
  796. const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15
  797. const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION);
  798. const int step = tid * K_QUANTS_PER_ITERATION;
  799. const int im = step/8;
  800. const int in = step%8;
  801. for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) {
  802. const uint8_t * q = x[i].qs + step;
  803. const int8_t * s = x[i].scales;
  804. const float * y = yy + i*QK_K + step;
  805. const float d = x[i].d;
  806. float sum = 0.f;
  807. for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) {
  808. const uint8_t h = x[i].qh[in+j] >> im;
  809. sum += y[j+ 0] * d * s[0] * ((q[j+ 0] & 0xF) - ((h >> 0) & 1 ? 0 : 16))
  810. + y[j+16] * d * s[1] * ((q[j+16] & 0xF) - ((h >> 2) & 1 ? 0 : 16))
  811. + y[j+32] * d * s[2] * ((q[j+ 0] >> 4) - ((h >> 4) & 1 ? 0 : 16))
  812. + y[j+48] * d * s[3] * ((q[j+16] >> 4) - ((h >> 6) & 1 ? 0 : 16));
  813. }
  814. tmp += sum;
  815. }
  816. #endif
  817. // sum up partial sums and write back result
  818. __syncthreads();
  819. #pragma unroll
  820. for (int mask = 16; mask > 0; mask >>= 1) {
  821. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  822. }
  823. if (threadIdx.x == 0) {
  824. dst[row] = tmp;
  825. }
  826. }
  827. static __global__ void dequantize_mul_mat_vec_q6_k(const void * vx, const float * yy, float * dst, const int ncols, int nrows) {
  828. static_assert(16%K_QUANTS_PER_ITERATION == 0, "16 must be divisible by K_QUANTS_PER_ITERATION");
  829. const int row = blockIdx.y*blockDim.y + threadIdx.y;
  830. if (row > nrows) return;
  831. const int num_blocks_per_row = ncols / QK_K;
  832. const int ib0 = row*num_blocks_per_row;
  833. const block_q6_K * x = (const block_q6_K *)vx + ib0;
  834. #if QK_K == 256
  835. const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  836. const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  837. const int step = 16/K_QUANTS_PER_ITERATION; // 16 or 8
  838. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  839. const int in = tid - step*im; // 0...15 or 0...7
  840. #if K_QUANTS_PER_ITERATION == 1
  841. const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15
  842. const int is = 0;
  843. #else
  844. const int l0 = 4 * in; // 0, 4, 8, ..., 28
  845. const int is = in / 4;
  846. #endif
  847. const int ql_offset = 64*im + l0;
  848. const int qh_offset = 32*im + l0;
  849. const int s_offset = 8*im + is;
  850. const int y_offset = 128*im + l0;
  851. float tmp = 0; // partial sum for thread in warp
  852. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  853. const float * y = yy + i * QK_K + y_offset;
  854. const uint8_t * ql = x[i].ql + ql_offset;
  855. const uint8_t * qh = x[i].qh + qh_offset;
  856. const int8_t * s = x[i].scales + s_offset;
  857. const float d = x[i].d;
  858. #if K_QUANTS_PER_ITERATION == 1
  859. float sum = y[ 0] * s[0] * d * ((int8_t)((ql[ 0] & 0xF) | ((qh[ 0] & 0x03) << 4)) - 32)
  860. + y[16] * s[1] * d * ((int8_t)((ql[16] & 0xF) | ((qh[16] & 0x03) << 4)) - 32)
  861. + y[32] * s[2] * d * ((int8_t)((ql[32] & 0xF) | ((qh[ 0] & 0x0c) << 2)) - 32)
  862. + y[48] * s[3] * d * ((int8_t)((ql[48] & 0xF) | ((qh[16] & 0x0c) << 2)) - 32)
  863. + y[64] * s[4] * d * ((int8_t)((ql[ 0] >> 4) | ((qh[ 0] & 0x30) >> 0)) - 32)
  864. + y[80] * s[5] * d * ((int8_t)((ql[16] >> 4) | ((qh[16] & 0x30) >> 0)) - 32)
  865. + y[96] * s[6] * d * ((int8_t)((ql[32] >> 4) | ((qh[ 0] & 0xc0) >> 2)) - 32)
  866. +y[112] * s[7] * d * ((int8_t)((ql[48] >> 4) | ((qh[16] & 0xc0) >> 2)) - 32);
  867. tmp += sum;
  868. #else
  869. float sum = 0;
  870. for (int l = 0; l < 4; ++l) {
  871. sum += y[l+ 0] * s[0] * d * ((int8_t)((ql[l+ 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32)
  872. + y[l+32] * s[2] * d * ((int8_t)((ql[l+32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32)
  873. + y[l+64] * s[4] * d * ((int8_t)((ql[l+ 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32)
  874. + y[l+96] * s[6] * d * ((int8_t)((ql[l+32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32);
  875. }
  876. tmp += sum;
  877. #endif
  878. }
  879. #else
  880. const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...7
  881. const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0...3
  882. const int step = tid * K_QUANTS_PER_ITERATION;
  883. float tmp = 0; // partial sum for thread in warp
  884. for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) {
  885. const float * y = yy + i * QK_K + step;
  886. const uint8_t * ql = x[i].ql + step;
  887. const uint8_t * qh = x[i].qh + step;
  888. const int8_t * s = x[i].scales;
  889. const float d = x[i+0].d;
  890. float sum = 0;
  891. for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) {
  892. sum += y[j+ 0] * s[0] * d * ((int8_t)((ql[j+ 0] & 0xF) | ((qh[j] & 0x03) << 4)) - 32)
  893. + y[j+16] * s[1] * d * ((int8_t)((ql[j+16] & 0xF) | ((qh[j] & 0x0c) << 2)) - 32)
  894. + y[j+32] * s[2] * d * ((int8_t)((ql[j+ 0] >> 4) | ((qh[j] & 0x30) >> 0)) - 32)
  895. + y[j+48] * s[3] * d * ((int8_t)((ql[j+16] >> 4) | ((qh[j] & 0xc0) >> 2)) - 32);
  896. }
  897. tmp += sum;
  898. }
  899. #endif
  900. // sum up partial sums and write back result
  901. __syncthreads();
  902. #pragma unroll
  903. for (int mask = 16; mask > 0; mask >>= 1) {
  904. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  905. }
  906. if (tid == 0) {
  907. dst[row] = tmp;
  908. }
  909. }
  910. static __device__ void convert_f16(const void * vx, const int ib, const int iqs, dfloat2 & v){
  911. const half * x = (const half *) vx;
  912. // automatic half -> float type cast if dfloat == float
  913. v.x = x[ib + iqs + 0];
  914. v.y = x[ib + iqs + 1];
  915. }
  916. template <int qk, int qr, dequantize_kernel_t dequantize_kernel>
  917. static __global__ void dequantize_block(const void * vx, float * y, const int k) {
  918. const int i = blockDim.x*blockIdx.x + 2*threadIdx.x;
  919. if (i >= k) {
  920. return;
  921. }
  922. const int ib = i/qk; // block index
  923. const int iqs = (i%qk)/qr; // quant index
  924. const int iybs = i - i%qk; // y block start index
  925. const int y_offset = qr == 1 ? 1 : qk/2;
  926. // dequantize
  927. dfloat2 v;
  928. dequantize_kernel(vx, ib, iqs, v);
  929. y[iybs + iqs + 0] = v.x;
  930. y[iybs + iqs + y_offset] = v.y;
  931. }
  932. template <int qk, int qr, dequantize_kernel_t dequantize_kernel>
  933. static __global__ void dequantize_mul_mat_vec(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) {
  934. // qk = quantized weights per x block
  935. // qr = number of quantized weights per data value in x block
  936. const int row = blockIdx.y*blockDim.y + threadIdx.y;
  937. if (row >= nrows) {
  938. return;
  939. }
  940. const int tid = threadIdx.x;
  941. const int iter_stride = 2*GGML_CUDA_DMMV_X;
  942. const int vals_per_iter = iter_stride / WARP_SIZE; // num quantized vals per thread and i iter
  943. const int y_offset = qr == 1 ? 1 : qk/2;
  944. // partial sum for each thread
  945. #ifdef GGML_CUDA_DMMV_F16
  946. half2 tmp = {0.0f, 0.0f}; // two sums for f16 to take advantage of half2 intrinsics
  947. #else
  948. float tmp = 0.0f;
  949. #endif // GGML_CUDA_DMMV_F16
  950. for (int i = 0; i < ncols; i += iter_stride) {
  951. const int col = i + vals_per_iter*tid;
  952. const int ib = (row*ncols + col)/qk; // x block index
  953. const int iqs = (col%qk)/qr; // x quant index
  954. const int iybs = col - col%qk; // y block start index
  955. // processing >2 values per i iter is faster for fast GPUs
  956. #pragma unroll
  957. for (int j = 0; j < vals_per_iter; j += 2) {
  958. // process 2 vals per j iter
  959. // dequantize
  960. // for qr = 2 the iqs needs to increase by 1 per j iter because 2 weights per data val
  961. dfloat2 v;
  962. dequantize_kernel(vx, ib, iqs + j/qr, v);
  963. // matrix multiplication
  964. // for qr = 2 the y index needs to increase by 1 per j iter because of y_offset = qk/2
  965. #ifdef GGML_CUDA_DMMV_F16
  966. tmp += __hmul2(v, {
  967. y[iybs + iqs + j/qr + 0],
  968. y[iybs + iqs + j/qr + y_offset]
  969. });
  970. #else
  971. tmp += v.x * y[iybs + iqs + j/qr + 0];
  972. tmp += v.y * y[iybs + iqs + j/qr + y_offset];
  973. #endif // GGML_CUDA_DMMV_F16
  974. }
  975. }
  976. // sum up partial sums and write back result
  977. __syncthreads();
  978. #pragma unroll
  979. for (int mask = 16; mask > 0; mask >>= 1) {
  980. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  981. }
  982. if (tid == 0) {
  983. #ifdef GGML_CUDA_DMMV_F16
  984. dst[row] = tmp.x + tmp.y;
  985. #else
  986. dst[row] = tmp;
  987. #endif // GGML_CUDA_DMMV_F16
  988. }
  989. }
  990. static __global__ void mul_mat_p021_f16_f32(const void * vx, const float * y, float * dst, const int ncols_x, const int nrows_x, const int nchannels_x) {
  991. const half * x = (half *) vx;
  992. const int row_x = blockDim.y*blockIdx.y + threadIdx.y;
  993. const int channel = blockDim.z*blockIdx.z + threadIdx.z;
  994. const int nrows_y = ncols_x;
  995. const int nrows_dst = nrows_x;
  996. const int row_dst = row_x;
  997. float tmp = 0.0f;
  998. for (int col_x0 = 0; col_x0 < ncols_x; col_x0 += blockDim.x) {
  999. const int col_x = col_x0 + threadIdx.x;
  1000. if (col_x >= ncols_x) {
  1001. break;
  1002. }
  1003. // x is transposed and permuted
  1004. const int ix = row_x*nchannels_x*ncols_x + channel*ncols_x + col_x;
  1005. const float xi = __half2float(x[ix]);
  1006. const int row_y = col_x;
  1007. // y is not transposed but permuted
  1008. const int iy = channel*nrows_y + row_y;
  1009. tmp += xi * y[iy];
  1010. }
  1011. // dst is not transposed and not permuted
  1012. const int idst = channel*nrows_dst + row_dst;
  1013. // sum up partial sums and write back result
  1014. __syncthreads();
  1015. #pragma unroll
  1016. for (int mask = 16; mask > 0; mask >>= 1) {
  1017. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  1018. }
  1019. if (threadIdx.x == 0) {
  1020. dst[idst] = tmp;
  1021. }
  1022. }
  1023. static __global__ void mul_mat_vec_nc_f16_f32( // nc == non-contiguous
  1024. const void * vx, const float * y, float * dst, const int ncols_x, const int nrows_x,
  1025. const int row_stride_x, const int nchannels_x, const int channel_stride_x) {
  1026. const half * x = (half *) vx;
  1027. const int row_x = blockDim.y*blockIdx.y + threadIdx.y;
  1028. const int channel = blockDim.z*blockIdx.z + threadIdx.z;
  1029. const int nrows_y = ncols_x;
  1030. const int nrows_dst = nrows_x;
  1031. const int row_dst = row_x;
  1032. const int idst = channel*nrows_dst + row_dst;
  1033. float tmp = 0.0f;
  1034. for (int col_x0 = 0; col_x0 < ncols_x; col_x0 += blockDim.x) {
  1035. const int col_x = col_x0 + threadIdx.x;
  1036. if (col_x >= ncols_x) {
  1037. break;
  1038. }
  1039. const int ix = channel*channel_stride_x + row_x*row_stride_x + col_x;
  1040. const float xi = __half2float(x[ix]);
  1041. const int row_y = col_x;
  1042. const int iy = channel*nrows_y + row_y;
  1043. tmp += xi * y[iy];
  1044. }
  1045. // sum up partial sums and write back result
  1046. __syncthreads();
  1047. #pragma unroll
  1048. for (int mask = 16; mask > 0; mask >>= 1) {
  1049. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  1050. }
  1051. if (threadIdx.x == 0) {
  1052. dst[idst] = tmp;
  1053. }
  1054. }
  1055. static __device__ void cpy_1_f32_f32(const char * cxi, char * cdsti) {
  1056. const float * xi = (float *) cxi;
  1057. float * dsti = (float *) cdsti;
  1058. *dsti = *xi;
  1059. }
  1060. static __device__ void cpy_1_f32_f16(const char * cxi, char * cdsti) {
  1061. const float * xi = (float *) cxi;
  1062. half * dsti = (half *) cdsti;
  1063. *dsti = __float2half(*xi);
  1064. }
  1065. template <cpy_kernel_t cpy_1>
  1066. static __global__ void cpy_f32_f16(const char * cx, char * cdst, const int ne,
  1067. const int ne00, const int ne01, const int nb00, const int nb01, const int nb02,
  1068. const int ne10, const int ne11, const int nb10, const int nb11, const int nb12) {
  1069. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  1070. if (i >= ne) {
  1071. return;
  1072. }
  1073. // determine indices i02/i12, i01/i11, i00/i10 as a function of index i of flattened tensor
  1074. // then combine those indices with the corresponding byte offsets to get the total offsets
  1075. const int i02 = i / (ne00*ne01);
  1076. const int i01 = (i - i02*ne01*ne00) / ne00;
  1077. const int i00 = i - i02*ne01*ne00 - i01*ne00;
  1078. const int x_offset = i00*nb00 + i01*nb01 + i02*nb02;
  1079. const int i12 = i / (ne10*ne11);
  1080. const int i11 = (i - i12*ne10*ne11) / ne10;
  1081. const int i10 = i - i12*ne10*ne11 - i11*ne10;
  1082. const int dst_offset = i10*nb10 + i11*nb11 + i12*nb12;
  1083. cpy_1(cx + x_offset, cdst + dst_offset);
  1084. }
  1085. // rope == RoPE == rotary positional embedding
  1086. static __global__ void rope_f32(const float * x, float * dst, const int ncols, const float p, const float theta_scale) {
  1087. const int col = 2*(blockDim.x*blockIdx.x + threadIdx.x);
  1088. if (col >= ncols) {
  1089. return;
  1090. }
  1091. const int row = blockDim.y*blockIdx.y + threadIdx.y;
  1092. const int i = row*ncols + col;
  1093. const float theta = p*powf(theta_scale, col/2);
  1094. const float sin_theta = sinf(theta);
  1095. const float cos_theta = cosf(theta);
  1096. const float x0 = x[i + 0];
  1097. const float x1 = x[i + 1];
  1098. dst[i + 0] = x0*cos_theta - x1*sin_theta;
  1099. dst[i + 1] = x0*sin_theta + x1*cos_theta;
  1100. }
  1101. static __global__ void diag_mask_inf_f32(const float * x, float * dst, const int ncols, const int rows_per_channel, const int n_past) {
  1102. const int col = blockDim.x*blockIdx.x + threadIdx.x;
  1103. const int row = blockDim.y*blockIdx.y + threadIdx.y;
  1104. if (col >= ncols) {
  1105. return;
  1106. }
  1107. const int i = row*ncols + col;
  1108. // dst[i] = col > n_past + row ? -INFINITY : x[i];
  1109. dst[i] = x[i] - (col > n_past + row % rows_per_channel) * INT_MAX; // equivalent within rounding error but slightly faster on GPU
  1110. }
  1111. // the CUDA soft max implementation differs from the CPU implementation
  1112. // instead of doubles floats are used
  1113. // values are also not normalized to the maximum value by subtracting it in the exponential function
  1114. // theoretically these changes could cause problems with rounding error and arithmetic overflow but for LLaMa it seems to be fine
  1115. static __global__ void soft_max_f32(const float * x, float * dst, const int ncols) {
  1116. const int row = blockDim.y*blockIdx.y + threadIdx.y;
  1117. const int block_size = blockDim.x;
  1118. const int tid = threadIdx.x;
  1119. float tmp = 0.0;
  1120. for (int block_start = 0; block_start < ncols; block_start += block_size) {
  1121. const int col = block_start + tid;
  1122. if (col >= ncols) {
  1123. break;
  1124. }
  1125. const int i = row*ncols + col;
  1126. const float val = expf(x[i]);
  1127. tmp += val;
  1128. dst[i] = val;
  1129. }
  1130. // sum up partial sums
  1131. __syncthreads();
  1132. #pragma unroll
  1133. for (int mask = 16; mask > 0; mask >>= 1) {
  1134. tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32);
  1135. }
  1136. for (int block_start = 0; block_start < ncols; block_start += block_size) {
  1137. const int col = block_start + tid;
  1138. if (col >= ncols) {
  1139. break;
  1140. }
  1141. const int i = row*ncols + col;
  1142. dst[i] /= tmp;
  1143. }
  1144. }
  1145. static __global__ void scale_f32(const float * x, float * dst, const float scale, const int k) {
  1146. const int i = blockDim.x*blockIdx.x + threadIdx.x;
  1147. if (i >= k) {
  1148. return;
  1149. }
  1150. dst[i] = scale * x[i];
  1151. }
  1152. static void add_f32_cuda(const float * x, const float * y, float * dst, const int k, cudaStream_t stream) {
  1153. const int num_blocks = (k + CUDA_ADD_BLOCK_SIZE - 1) / CUDA_ADD_BLOCK_SIZE;
  1154. add_f32<<<num_blocks, CUDA_ADD_BLOCK_SIZE, 0, stream>>>(x, y, dst, k);
  1155. }
  1156. static void add_f16_f32_f16_cuda(const half * x, const float * y, half * dst, const int k, cudaStream_t stream) {
  1157. const int num_blocks = (k + CUDA_ADD_BLOCK_SIZE - 1) / CUDA_ADD_BLOCK_SIZE;
  1158. add_f16_f32_f16<<<num_blocks, CUDA_ADD_BLOCK_SIZE, 0, stream>>>(x, y, dst, k);
  1159. }
  1160. static void mul_f32_cuda(const float * x, const float * y, float * dst, const int kx, const int ky, cudaStream_t stream) {
  1161. const int num_blocks = (kx + CUDA_MUL_BLOCK_SIZE - 1) / CUDA_MUL_BLOCK_SIZE;
  1162. mul_f32<<<num_blocks, CUDA_MUL_BLOCK_SIZE, 0, stream>>>(x, y, dst, kx, ky);
  1163. }
  1164. static void silu_f32_cuda(const float * x, float * dst, const int k, cudaStream_t stream) {
  1165. const int num_blocks = (k + CUDA_SILU_BLOCK_SIZE - 1) / CUDA_SILU_BLOCK_SIZE;
  1166. silu_f32<<<num_blocks, CUDA_SILU_BLOCK_SIZE, 0, stream>>>(x, dst, k);
  1167. }
  1168. static void rms_norm_f32_cuda(const float * x, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1169. GGML_ASSERT(ncols % WARP_SIZE == 0);
  1170. const dim3 block_dims(WARP_SIZE, 1, 1);
  1171. rms_norm_f32<<<nrows, block_dims, 0, stream>>>(x, dst, ncols);
  1172. }
  1173. static void dequantize_row_q4_0_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1174. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1175. dequantize_block<QK4_0, QR4_0, dequantize_q4_0><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1176. }
  1177. static void dequantize_row_q4_1_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1178. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1179. dequantize_block<QK4_1, QR4_1, dequantize_q4_1><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1180. }
  1181. static void dequantize_row_q5_0_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1182. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1183. dequantize_block<QK5_0, QR5_0, dequantize_q5_0><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1184. }
  1185. static void dequantize_row_q5_1_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1186. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1187. dequantize_block<QK5_1, QR5_1, dequantize_q5_1><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1188. }
  1189. static void dequantize_row_q8_0_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1190. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1191. dequantize_block<QK8_0, QR8_0, dequantize_q8_0><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1192. }
  1193. static void dequantize_row_q2_K_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1194. const int nb = k / QK_K;
  1195. #if QK_K == 256
  1196. dequantize_block_q2_K<<<nb, 64, 0, stream>>>(vx, y);
  1197. #else
  1198. dequantize_block_q2_K<<<nb, 32, 0, stream>>>(vx, y);
  1199. #endif
  1200. }
  1201. static void dequantize_row_q3_K_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1202. const int nb = k / QK_K;
  1203. #if QK_K == 256
  1204. dequantize_block_q3_K<<<nb, 64, 0, stream>>>(vx, y);
  1205. #else
  1206. dequantize_block_q3_K<<<nb, 32, 0, stream>>>(vx, y);
  1207. #endif
  1208. }
  1209. static void dequantize_row_q4_K_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1210. const int nb = k / QK_K;
  1211. dequantize_block_q4_K<<<nb, 32, 0, stream>>>(vx, y);
  1212. }
  1213. static void dequantize_row_q5_K_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1214. const int nb = k / QK_K;
  1215. #if QK_K == 256
  1216. dequantize_block_q5_K<<<nb, 64, 0, stream>>>(vx, y);
  1217. #else
  1218. dequantize_block_q5_K<<<nb, 32, 0, stream>>>(vx, y);
  1219. #endif
  1220. }
  1221. static void dequantize_row_q6_K_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1222. const int nb = k / QK_K;
  1223. #if QK_K == 256
  1224. dequantize_block_q6_K<<<nb, 64, 0, stream>>>(vx, y);
  1225. #else
  1226. dequantize_block_q6_K<<<nb, 32, 0, stream>>>(vx, y);
  1227. #endif
  1228. }
  1229. static void dequantize_mul_mat_vec_q4_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1230. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1231. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1232. const dim3 block_nums(1, block_num_y, 1);
  1233. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1234. dequantize_mul_mat_vec<QK4_0, QR4_0, dequantize_q4_0>
  1235. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1236. }
  1237. static void dequantize_mul_mat_vec_q4_1_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1238. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1239. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1240. const dim3 block_nums(1, block_num_y, 1);
  1241. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1242. dequantize_mul_mat_vec<QK4_1, QR4_1, dequantize_q4_1>
  1243. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1244. }
  1245. static void dequantize_mul_mat_vec_q5_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1246. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1247. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1248. const dim3 block_nums(1, block_num_y, 1);
  1249. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1250. dequantize_mul_mat_vec<QK5_0, QR5_0, dequantize_q5_0>
  1251. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1252. }
  1253. static void dequantize_mul_mat_vec_q5_1_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1254. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1255. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1256. const dim3 block_nums(1, block_num_y, 1);
  1257. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1258. dequantize_mul_mat_vec<QK5_1, QR5_1, dequantize_q5_1>
  1259. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1260. }
  1261. static void dequantize_mul_mat_vec_q8_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1262. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1263. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1264. const dim3 block_nums(1, block_num_y, 1);
  1265. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1266. dequantize_mul_mat_vec<QK8_0, QR8_0, dequantize_q8_0>
  1267. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1268. }
  1269. static void dequantize_mul_mat_vec_q2_K_cuda(const void * vx, const float * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1270. GGML_ASSERT(ncols % QK_K == 0);
  1271. const int ny = 2; // very slightly faster than 1 even when K_QUANTS_PER_ITERATION = 2
  1272. const int block_num_y = (nrows + ny - 1) / ny;
  1273. const dim3 block_nums(1, block_num_y, 1);
  1274. const dim3 block_dims(32, ny, 1);
  1275. dequantize_mul_mat_vec_q2_k<<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1276. }
  1277. static void dequantize_mul_mat_vec_q3_K_cuda(const void * vx, const float * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1278. GGML_ASSERT(ncols % QK_K == 0);
  1279. const int ny = 2 / K_QUANTS_PER_ITERATION;
  1280. const int block_num_y = (nrows + ny - 1) / ny;
  1281. const dim3 block_nums(1, block_num_y, 1);
  1282. const dim3 block_dims(32, ny, 1);
  1283. dequantize_mul_mat_vec_q3_k<<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1284. }
  1285. static void dequantize_mul_mat_vec_q4_K_cuda(const void * vx, const float * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1286. GGML_ASSERT(ncols % QK_K == 0);
  1287. const int ny = 2 / K_QUANTS_PER_ITERATION;
  1288. const int block_num_y = (nrows + ny - 1) / ny;
  1289. const dim3 block_nums(1, block_num_y, 1);
  1290. const dim3 block_dims(32, ny, 1);
  1291. dequantize_mul_mat_vec_q4_k<<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1292. }
  1293. static void dequantize_mul_mat_vec_q5_K_cuda(const void * vx, const float * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1294. GGML_ASSERT(ncols % QK_K == 0);
  1295. const dim3 block_dims(32, 1, 1);
  1296. dequantize_mul_mat_vec_q5_k<<<nrows, block_dims, 0, stream>>>(vx, y, dst, ncols);
  1297. }
  1298. static void dequantize_mul_mat_vec_q6_K_cuda(const void * vx, const float * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1299. GGML_ASSERT(ncols % QK_K == 0);
  1300. const int ny = 2 / K_QUANTS_PER_ITERATION;
  1301. const int block_num_y = (nrows + ny - 1) / ny;
  1302. const dim3 block_nums(1, block_num_y, 1);
  1303. const dim3 block_dims(32, ny, 1);
  1304. dequantize_mul_mat_vec_q6_k<<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1305. }
  1306. static void convert_fp16_to_fp32_cuda(const void * vx, float * y, const int k, cudaStream_t stream) {
  1307. const int num_blocks = (k + CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / CUDA_DEQUANTIZE_BLOCK_SIZE;
  1308. dequantize_block<1, 1, convert_f16><<<num_blocks, CUDA_DEQUANTIZE_BLOCK_SIZE, 0, stream>>>(vx, y, k);
  1309. }
  1310. static void convert_mul_mat_vec_f16_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
  1311. GGML_ASSERT(ncols % GGML_CUDA_DMMV_X == 0);
  1312. const int block_num_y = (nrows + GGML_CUDA_DMMV_Y - 1) / GGML_CUDA_DMMV_Y;
  1313. const dim3 block_nums(1, block_num_y, 1);
  1314. const dim3 block_dims(WARP_SIZE, GGML_CUDA_DMMV_Y, 1);
  1315. dequantize_mul_mat_vec<1, 1, convert_f16>
  1316. <<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols, nrows);
  1317. }
  1318. static to_fp32_cuda_t ggml_get_to_fp32_cuda(ggml_type type) {
  1319. switch (type) {
  1320. case GGML_TYPE_Q4_0:
  1321. return dequantize_row_q4_0_cuda;
  1322. case GGML_TYPE_Q4_1:
  1323. return dequantize_row_q4_1_cuda;
  1324. case GGML_TYPE_Q5_0:
  1325. return dequantize_row_q5_0_cuda;
  1326. case GGML_TYPE_Q5_1:
  1327. return dequantize_row_q5_1_cuda;
  1328. case GGML_TYPE_Q8_0:
  1329. return dequantize_row_q8_0_cuda;
  1330. case GGML_TYPE_Q2_K:
  1331. return dequantize_row_q2_K_cuda;
  1332. case GGML_TYPE_Q3_K:
  1333. return dequantize_row_q3_K_cuda;
  1334. case GGML_TYPE_Q4_K:
  1335. return dequantize_row_q4_K_cuda;
  1336. case GGML_TYPE_Q5_K:
  1337. return dequantize_row_q5_K_cuda;
  1338. case GGML_TYPE_Q6_K:
  1339. return dequantize_row_q6_K_cuda;
  1340. case GGML_TYPE_F16:
  1341. return convert_fp16_to_fp32_cuda;
  1342. default:
  1343. return nullptr;
  1344. }
  1345. }
  1346. static void ggml_mul_mat_p021_f16_f32_cuda(const void * vx, const float * y, float * dst, const int ncols_x, const int nrows_x, const int nchannels_x, cudaStream_t stream) {
  1347. const dim3 block_nums(1, nrows_x, nchannels_x);
  1348. const dim3 block_dims(WARP_SIZE, 1, 1);
  1349. mul_mat_p021_f16_f32<<<block_nums, block_dims, 0, stream>>>(vx, y, dst, ncols_x, nrows_x, nchannels_x);
  1350. }
  1351. static void ggml_mul_mat_vec_nc_f16_f32_cuda(
  1352. const void * vx, const float * y, float * dst, const int ncols_x, const int nrows_x, const int row_stride_x,
  1353. const int nchannels_x, const int channel_stride_x, cudaStream_t stream) {
  1354. const dim3 block_nums(1, nrows_x, nchannels_x);
  1355. const dim3 block_dims(WARP_SIZE, 1, 1);
  1356. mul_mat_vec_nc_f16_f32<<<block_nums, block_dims, 0, stream>>>
  1357. (vx, y, dst, ncols_x, nrows_x, row_stride_x, nchannels_x, channel_stride_x);
  1358. }
  1359. static void ggml_cpy_f32_f32_cuda(
  1360. const char * cx, char * cdst, const int ne,
  1361. const int ne00, const int ne01, const int nb00, const int nb01, const int nb02,
  1362. const int ne10, const int ne11, const int nb10, const int nb11, const int nb12, cudaStream_t stream) {
  1363. const int num_blocks = (ne + CUDA_CPY_BLOCK_SIZE - 1) / CUDA_CPY_BLOCK_SIZE;
  1364. cpy_f32_f16<cpy_1_f32_f32><<<num_blocks, CUDA_CPY_BLOCK_SIZE, 0, stream>>>
  1365. (cx, cdst, ne, ne00, ne01, nb00, nb01, nb02, ne10, ne11, nb10, nb11, nb12);
  1366. }
  1367. static void ggml_cpy_f32_f16_cuda(
  1368. const char * cx, char * cdst, const int ne,
  1369. const int ne00, const int ne01, const int nb00, const int nb01, const int nb02,
  1370. const int ne10, const int ne11, const int nb10, const int nb11, const int nb12, cudaStream_t stream) {
  1371. const int num_blocks = (ne + CUDA_CPY_BLOCK_SIZE - 1) / CUDA_CPY_BLOCK_SIZE;
  1372. cpy_f32_f16<cpy_1_f32_f16><<<num_blocks, CUDA_CPY_BLOCK_SIZE, 0, stream>>>
  1373. (cx, cdst, ne, ne00, ne01, nb00, nb01, nb02, ne10, ne11, nb10, nb11, nb12);
  1374. }
  1375. static void scale_f32_cuda(const float * x, float * dst, const float scale, const int k, cudaStream_t stream) {
  1376. const int num_blocks = (k + CUDA_SCALE_BLOCK_SIZE - 1) / CUDA_SCALE_BLOCK_SIZE;
  1377. scale_f32<<<num_blocks, CUDA_SCALE_BLOCK_SIZE, 0, stream>>>(x, dst, scale, k);
  1378. }
  1379. static void rope_f32_cuda(const float * x, float * dst, const int ncols, const int nrows, const float p, const float theta_scale, cudaStream_t stream) {
  1380. GGML_ASSERT(nrows % 2 == 0);
  1381. const dim3 block_dims(2*CUDA_ROPE_BLOCK_SIZE, 1, 1);
  1382. const int num_blocks_x = (ncols + 2*CUDA_ROPE_BLOCK_SIZE - 1) / (2*CUDA_ROPE_BLOCK_SIZE);
  1383. const dim3 block_nums(num_blocks_x, nrows, 1);
  1384. rope_f32<<<block_nums, block_dims, 0, stream>>>(x, dst, ncols, p, theta_scale);
  1385. }
  1386. static void diag_mask_inf_f32_cuda(const float * x, float * dst, const int ncols_x, const int nrows_x, const int rows_per_channel, const int n_past, cudaStream_t stream) {
  1387. const dim3 block_dims(CUDA_DIAG_MASK_INF_BLOCK_SIZE, 1, 1);
  1388. const int block_num_x = (ncols_x + CUDA_DIAG_MASK_INF_BLOCK_SIZE - 1) / CUDA_DIAG_MASK_INF_BLOCK_SIZE;
  1389. const dim3 block_nums(block_num_x, nrows_x, 1);
  1390. diag_mask_inf_f32<<<block_nums, block_dims, 0, stream>>>(x, dst, ncols_x, rows_per_channel, n_past);
  1391. }
  1392. static void soft_max_f32_cuda(const float * x, float * dst, const int ncols_x, const int nrows_x, cudaStream_t stream) {
  1393. const dim3 block_dims(WARP_SIZE, 1, 1);
  1394. const dim3 block_nums(1, nrows_x, 1);
  1395. soft_max_f32<<<block_nums, block_dims, 0, stream>>>(x, dst, ncols_x);
  1396. }
  1397. // buffer pool for cuda
  1398. #define MAX_CUDA_BUFFERS 256
  1399. struct scoped_spin_lock {
  1400. std::atomic_flag& lock;
  1401. scoped_spin_lock(std::atomic_flag& lock) : lock(lock) {
  1402. while (lock.test_and_set(std::memory_order_acquire)) {
  1403. ; // spin
  1404. }
  1405. }
  1406. ~scoped_spin_lock() {
  1407. lock.clear(std::memory_order_release);
  1408. }
  1409. scoped_spin_lock(const scoped_spin_lock&) = delete;
  1410. scoped_spin_lock& operator=(const scoped_spin_lock&) = delete;
  1411. };
  1412. struct cuda_buffer {
  1413. void * ptr = nullptr;
  1414. size_t size = 0;
  1415. };
  1416. static cuda_buffer g_cuda_buffer_pool[GGML_CUDA_MAX_DEVICES][MAX_CUDA_BUFFERS];
  1417. static std::atomic_flag g_cuda_pool_lock = ATOMIC_FLAG_INIT;
  1418. static void * ggml_cuda_pool_malloc(size_t size, size_t * actual_size) {
  1419. scoped_spin_lock lock(g_cuda_pool_lock);
  1420. int id;
  1421. CUDA_CHECK(cudaGetDevice(&id));
  1422. for (int i = 0; i < MAX_CUDA_BUFFERS; ++i) {
  1423. cuda_buffer& b = g_cuda_buffer_pool[id][i];
  1424. if (b.size >= size && b.ptr != nullptr) {
  1425. void * ptr = b.ptr;
  1426. *actual_size = b.size;
  1427. b.ptr = nullptr;
  1428. b.size = 0;
  1429. return ptr;
  1430. }
  1431. }
  1432. void * ptr;
  1433. CUDA_CHECK(cudaMalloc((void **) &ptr, size));
  1434. *actual_size = size;
  1435. return ptr;
  1436. }
  1437. static void ggml_cuda_pool_free(void * ptr, size_t size) {
  1438. scoped_spin_lock lock(g_cuda_pool_lock);
  1439. int id;
  1440. CUDA_CHECK(cudaGetDevice(&id));
  1441. for (int i = 0; i < MAX_CUDA_BUFFERS; ++i) {
  1442. cuda_buffer& b = g_cuda_buffer_pool[id][i];
  1443. if (b.ptr == nullptr) {
  1444. b.ptr = ptr;
  1445. b.size = size;
  1446. return;
  1447. }
  1448. }
  1449. fprintf(stderr, "WARNING: cuda buffer pool full, increase MAX_CUDA_BUFFERS\n");
  1450. CUDA_CHECK(cudaFree(ptr));
  1451. }
  1452. static void * g_scratch_buffer = nullptr;
  1453. static size_t g_scratch_size = 1024*1024*1024; // 1 GB by default
  1454. static size_t g_scratch_offset = 0;
  1455. static int g_device_count = -1;
  1456. static int g_main_device = 0;
  1457. static float g_tensor_split[GGML_CUDA_MAX_DEVICES] = {0};
  1458. static cublasHandle_t g_cublas_handles[GGML_CUDA_MAX_DEVICES] = {nullptr};
  1459. static cudaStream_t g_cudaStreams_main[GGML_CUDA_MAX_DEVICES] = { nullptr };
  1460. void ggml_init_cublas() {
  1461. static bool initialized = false;
  1462. if (!initialized) {
  1463. CUDA_CHECK(cudaGetDeviceCount(&g_device_count));
  1464. GGML_ASSERT(g_device_count <= GGML_CUDA_MAX_DEVICES);
  1465. int64_t total_vram = 0;
  1466. fprintf(stderr, "%s: found %d CUDA devices:\n", __func__, g_device_count);
  1467. for (int id = 0; id < g_device_count; ++id) {
  1468. cudaDeviceProp prop;
  1469. CUDA_CHECK(cudaGetDeviceProperties(&prop, id));
  1470. fprintf(stderr, " Device %d: %s\n", id, prop.name);
  1471. g_tensor_split[id] = total_vram;
  1472. total_vram += prop.totalGlobalMem;
  1473. }
  1474. for (int id = 0; id < g_device_count; ++id) {
  1475. g_tensor_split[id] /= total_vram;
  1476. }
  1477. for (int id = 0; id < g_device_count; ++id) {
  1478. CUDA_CHECK(cudaSetDevice(id));
  1479. // create main stream
  1480. CUDA_CHECK(cudaStreamCreateWithFlags(&g_cudaStreams_main[id], cudaStreamNonBlocking));
  1481. // create cublas handle
  1482. CUBLAS_CHECK(cublasCreate(&g_cublas_handles[id]));
  1483. CUBLAS_CHECK(cublasSetMathMode(g_cublas_handles[id], CUBLAS_TF32_TENSOR_OP_MATH));
  1484. }
  1485. // configure logging to stdout
  1486. // CUBLAS_CHECK(cublasLoggerConfigure(1, 1, 0, nullptr));
  1487. initialized = true;
  1488. }
  1489. }
  1490. void ggml_cuda_set_tensor_split(const float * tensor_split) {
  1491. bool all_zero = true;
  1492. for (int i = 0; i < g_device_count; ++i) {
  1493. if (tensor_split[i] != 0.0f) {
  1494. all_zero = false;
  1495. break;
  1496. }
  1497. }
  1498. if (all_zero) {
  1499. return;
  1500. }
  1501. float split_sum = 0.0f;
  1502. for (int i = 0; i < g_device_count; ++i) {
  1503. g_tensor_split[i] = split_sum;
  1504. split_sum += tensor_split[i];
  1505. }
  1506. for (int i = 0; i < g_device_count; ++i) {
  1507. g_tensor_split[i] /= split_sum;
  1508. }
  1509. }
  1510. void * ggml_cuda_host_malloc(size_t size) {
  1511. if (getenv("GGML_CUDA_NO_PINNED") != nullptr) {
  1512. return nullptr;
  1513. }
  1514. void * ptr = nullptr;
  1515. cudaError_t err = cudaMallocHost((void **) &ptr, size);
  1516. if (err != cudaSuccess) {
  1517. // The allocation error can be bypassed. A null ptr will assigned out of this function.
  1518. // This can fixed the OOM error in WSL.
  1519. cudaGetLastError();
  1520. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory: %s\n",
  1521. size/1024.0/1024.0, cudaGetErrorString(err));
  1522. return nullptr;
  1523. }
  1524. return ptr;
  1525. }
  1526. void ggml_cuda_host_free(void * ptr) {
  1527. CUDA_CHECK(cudaFreeHost(ptr));
  1528. }
  1529. static cudaError_t ggml_cuda_cpy_tensor_2d(
  1530. void * dst, const struct ggml_tensor * src, int64_t i3, int64_t i2, int64_t i1_low, int64_t i1_high, cudaStream_t stream) {
  1531. cudaMemcpyKind kind;
  1532. char * src_ptr;
  1533. if (src->backend == GGML_BACKEND_CPU) {
  1534. kind = cudaMemcpyHostToDevice;
  1535. src_ptr = (char *) src->data;
  1536. } else if (src->backend == GGML_BACKEND_GPU) {
  1537. kind = cudaMemcpyDeviceToDevice;
  1538. struct ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src->extra;
  1539. int id;
  1540. CUDA_CHECK(cudaGetDevice(&id));
  1541. src_ptr = (char *) extra->data_device[id];
  1542. } else {
  1543. GGML_ASSERT(false);
  1544. }
  1545. char * dst_ptr = (char *) dst;
  1546. const int64_t ne0 = src->ne[0];
  1547. const int64_t nb0 = src->nb[0];
  1548. const int64_t nb1 = src->nb[1];
  1549. const int64_t nb2 = src->nb[2];
  1550. const int64_t nb3 = src->nb[3];
  1551. const enum ggml_type type = src->type;
  1552. const int64_t ts = ggml_type_size(type);
  1553. const int64_t bs = ggml_blck_size(type);
  1554. int64_t i1_diff = i1_high - i1_low;
  1555. const char * x = src_ptr + i1_low*nb1 + i2*nb2 + i3*nb3;
  1556. if (nb0 == ts && nb1 == ts*ne0/bs) {
  1557. return cudaMemcpyAsync(dst_ptr, x, i1_diff*nb1, kind, stream);
  1558. } else if (nb0 == ts) {
  1559. return cudaMemcpy2DAsync(dst_ptr, ts*ne0/bs, x, nb1, ts*ne0/bs, i1_diff, kind, stream);
  1560. } else {
  1561. for (int64_t i1 = 0; i1 < i1_diff; i1++) {
  1562. const void * rx = (const void *) ((const char *) x + i1*nb1);
  1563. void * rd = (void *) (dst_ptr + i1*ts*ne0/bs);
  1564. // pretend the row is a matrix with cols=1
  1565. cudaError_t r = cudaMemcpy2DAsync(rd, ts/bs, rx, nb0, ts/bs, ne0, kind, stream);
  1566. if (r != cudaSuccess) return r;
  1567. }
  1568. return cudaSuccess;
  1569. }
  1570. }
  1571. inline void ggml_cuda_op_add(
  1572. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1573. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1574. cudaStream_t & cudaStream_main){
  1575. GGML_ASSERT(src0_ddq_i != nullptr || src0_ddf_i != nullptr);
  1576. GGML_ASSERT(src1_ddf_i != nullptr);
  1577. GGML_ASSERT(dst_ddf_i != nullptr);
  1578. const int64_t ne0 = src0->ne[0];
  1579. const int64_t i01_diff = i01_high - i01_low;
  1580. // compute
  1581. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  1582. add_f32_cuda(src0_ddf_i, src1_ddf_i, dst_ddf_i, ne0*i01_diff, cudaStream_main);
  1583. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  1584. add_f16_f32_f16_cuda((half *) src0_ddq_i, src1_ddf_i, (half *) dst_ddf_i, ne0*i01_diff, cudaStream_main);
  1585. } else {
  1586. GGML_ASSERT(false);
  1587. }
  1588. CUDA_CHECK(cudaGetLastError());
  1589. (void) src1;
  1590. (void) dst;
  1591. (void) src0_ddq_i;
  1592. (void) i02;
  1593. (void) i1;
  1594. }
  1595. inline void ggml_cuda_op_mul(
  1596. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1597. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1598. cudaStream_t & cudaStream_main){
  1599. GGML_ASSERT(src0_ddf_i != nullptr);
  1600. GGML_ASSERT(src1_ddf_i != nullptr);
  1601. GGML_ASSERT(dst_ddf_i != nullptr);
  1602. const int64_t ne00 = src0->ne[0];
  1603. const int64_t ne10 = src1->ne[0];
  1604. const int64_t ne11 = src1->ne[1];
  1605. for (int64_t i01 = i01_low; i01 < i01_high; i01++) {
  1606. const int64_t i11 = i1*ne11 + i01%ne11; // broadcast src1 across src0
  1607. float * src0_ddf_i01 = src0_ddf_i + i01*ne00;
  1608. float * src1_ddf_i01 = src1_ddf_i + i11*ne10;
  1609. float * dst_ddf_i01 = dst_ddf_i + i01*ne00;
  1610. // compute
  1611. mul_f32_cuda(src0_ddf_i01, src1_ddf_i01, dst_ddf_i01, ne00, ne10, cudaStream_main);
  1612. CUDA_CHECK(cudaGetLastError());
  1613. }
  1614. (void) dst;
  1615. (void) src0_ddq_i;
  1616. (void) i02;
  1617. }
  1618. inline void ggml_cuda_op_silu(
  1619. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1620. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1621. cudaStream_t & cudaStream_main){
  1622. GGML_ASSERT(src0_ddf_i != nullptr);
  1623. GGML_ASSERT(dst_ddf_i != nullptr);
  1624. const int64_t ne00 = src0->ne[0];
  1625. const int64_t i01_diff = i01_high - i01_low;
  1626. // compute
  1627. silu_f32_cuda(src0_ddf_i, dst_ddf_i, ne00*i01_diff, cudaStream_main);
  1628. CUDA_CHECK(cudaGetLastError());
  1629. (void) src1;
  1630. (void) dst;
  1631. (void) src0_ddq_i;
  1632. (void) src1_ddf_i;
  1633. (void) i02;
  1634. (void) i1;
  1635. }
  1636. inline void ggml_cuda_op_rms_norm(
  1637. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1638. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1639. cudaStream_t & cudaStream_main){
  1640. GGML_ASSERT(src0_ddf_i != nullptr);
  1641. GGML_ASSERT(dst_ddf_i != nullptr);
  1642. const int64_t ne00 = src0->ne[0];
  1643. const int64_t i01_diff = i01_high - i01_low;
  1644. // compute
  1645. rms_norm_f32_cuda(src0_ddf_i, dst_ddf_i, ne00, i01_diff, cudaStream_main);
  1646. CUDA_CHECK(cudaGetLastError());
  1647. (void) src1;
  1648. (void) dst;
  1649. (void) src0_ddq_i;
  1650. (void) src1_ddf_i;
  1651. (void) i02;
  1652. (void) i1;
  1653. }
  1654. inline void ggml_cuda_op_dequantize_mul_mat_vec(
  1655. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1656. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1657. cudaStream_t & cudaStream_main){
  1658. GGML_ASSERT(src0_ddq_i != nullptr);
  1659. GGML_ASSERT(src1_ddf_i != nullptr);
  1660. GGML_ASSERT(dst_ddf_i != nullptr);
  1661. const int64_t ne00 = src0->ne[0];
  1662. const int64_t nrows = i01_high - i01_low;
  1663. // on some GPUs it is faster to convert src1 to half and to use half precision intrinsics
  1664. #ifdef GGML_CUDA_DMMV_F16
  1665. size_t ash;
  1666. dfloat * src1_dfloat = nullptr; // dfloat == half
  1667. bool src1_convert_f16 = src0->type == GGML_TYPE_Q4_0 || src0->type == GGML_TYPE_Q4_1 ||
  1668. src0->type == GGML_TYPE_Q5_0 || src0->type == GGML_TYPE_Q5_1 ||
  1669. src0->type == GGML_TYPE_Q8_0 || src0->type == GGML_TYPE_F16;
  1670. if (src1_convert_f16) {
  1671. src1_dfloat = (half *) ggml_cuda_pool_malloc(ne00*sizeof(half), &ash);
  1672. ggml_cpy_f32_f16_cuda((char *) src1_ddf_i, (char *) src1_dfloat, ne00,
  1673. ne00, 1, sizeof(float), 0, 0,
  1674. ne00, 1, sizeof(half), 0, 0, cudaStream_main);
  1675. }
  1676. #else
  1677. dfloat * src1_dfloat = src1_ddf_i; // dfloat == float, no conversion
  1678. #endif // GGML_CUDA_DMMV_F16
  1679. switch (src0->type) {
  1680. case GGML_TYPE_Q4_0:
  1681. dequantize_mul_mat_vec_q4_0_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1682. break;
  1683. case GGML_TYPE_Q4_1:
  1684. dequantize_mul_mat_vec_q4_1_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1685. break;
  1686. case GGML_TYPE_Q5_0:
  1687. dequantize_mul_mat_vec_q5_0_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1688. break;
  1689. case GGML_TYPE_Q5_1:
  1690. dequantize_mul_mat_vec_q5_1_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1691. break;
  1692. case GGML_TYPE_Q8_0:
  1693. dequantize_mul_mat_vec_q8_0_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1694. break;
  1695. case GGML_TYPE_Q2_K:
  1696. dequantize_mul_mat_vec_q2_K_cuda(src0_ddq_i, src1_ddf_i, dst_ddf_i, ne00, nrows, cudaStream_main);
  1697. break;
  1698. case GGML_TYPE_Q3_K:
  1699. dequantize_mul_mat_vec_q3_K_cuda(src0_ddq_i, src1_ddf_i, dst_ddf_i, ne00, nrows, cudaStream_main);
  1700. break;
  1701. case GGML_TYPE_Q4_K:
  1702. dequantize_mul_mat_vec_q4_K_cuda(src0_ddq_i, src1_ddf_i, dst_ddf_i, ne00, nrows, cudaStream_main);
  1703. break;
  1704. case GGML_TYPE_Q5_K:
  1705. dequantize_mul_mat_vec_q5_K_cuda(src0_ddq_i, src1_ddf_i, dst_ddf_i, ne00, nrows, cudaStream_main);
  1706. break;
  1707. case GGML_TYPE_Q6_K:
  1708. dequantize_mul_mat_vec_q6_K_cuda(src0_ddq_i, src1_ddf_i, dst_ddf_i, ne00, nrows, cudaStream_main);
  1709. break;
  1710. case GGML_TYPE_F16:
  1711. convert_mul_mat_vec_f16_cuda(src0_ddq_i, src1_dfloat, dst_ddf_i, ne00, nrows, cudaStream_main);
  1712. break;
  1713. default:
  1714. GGML_ASSERT(false);
  1715. break;
  1716. }
  1717. CUDA_CHECK(cudaGetLastError());
  1718. #ifdef GGML_CUDA_DMMV_F16
  1719. if (src1_convert_f16) {
  1720. ggml_cuda_pool_free(src1_dfloat, ash);
  1721. }
  1722. #endif // GGML_CUDA_DMMV_F16
  1723. (void) src1;
  1724. (void) dst;
  1725. (void) src0_ddf_i;
  1726. (void) i02;
  1727. (void) i1;
  1728. }
  1729. inline void ggml_cuda_op_mul_mat_cublas(
  1730. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1731. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1732. cudaStream_t & cudaStream_main){
  1733. GGML_ASSERT(src0_ddf_i != nullptr);
  1734. GGML_ASSERT(src1_ddf_i != nullptr);
  1735. GGML_ASSERT(dst_ddf_i != nullptr);
  1736. const float alpha = 1.0f;
  1737. const float beta = 0.0f;
  1738. const int64_t ne00 = src0->ne[0];
  1739. const int64_t ne10 = src1->ne[0];
  1740. const int64_t ne11 = src1->ne[1];
  1741. const int64_t ne0 = dst->ne[0];
  1742. const int64_t i01_diff = i01_high - i01_low;
  1743. int id;
  1744. CUDA_CHECK(cudaGetDevice(&id));
  1745. // the main device has a larger memory buffer to hold the results from all GPUs
  1746. // ldc == nrows of the matrix that cuBLAS writes into
  1747. int ldc = dst->backend == GGML_BACKEND_GPU && id == g_main_device ? ne0 : i01_diff;
  1748. CUBLAS_CHECK(cublasSetStream(g_cublas_handles[id], cudaStream_main));
  1749. CUBLAS_CHECK(
  1750. cublasSgemm(g_cublas_handles[id], CUBLAS_OP_T, CUBLAS_OP_N,
  1751. i01_diff, ne11, ne10,
  1752. &alpha, src0_ddf_i, ne00,
  1753. src1_ddf_i, ne10,
  1754. &beta, dst_ddf_i, ldc));
  1755. (void) dst;
  1756. (void) src0_ddq_i;
  1757. (void) i02;
  1758. (void) i1;
  1759. }
  1760. inline void ggml_cuda_op_rope(
  1761. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1762. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1763. cudaStream_t & cudaStream_main){
  1764. GGML_ASSERT(src0_ddf_i != nullptr);
  1765. GGML_ASSERT(dst_ddf_i != nullptr);
  1766. const int64_t ne00 = src0->ne[0];
  1767. const int64_t i01_diff = i01_high - i01_low;
  1768. const int n_past = ((int32_t *) src1->data)[0];
  1769. const int n_dims = ((int32_t *) src1->data)[1];
  1770. const int mode = ((int32_t *) src1->data)[2];
  1771. GGML_ASSERT(mode == 0);
  1772. const float theta_scale = powf(10000.0, -2.0f/n_dims);
  1773. const float p = ((mode & 1) == 0 ? n_past + i02 : i02);
  1774. // compute
  1775. rope_f32_cuda(src0_ddf_i, dst_ddf_i, ne00, i01_diff, p, theta_scale, cudaStream_main);
  1776. CUDA_CHECK(cudaGetLastError());
  1777. (void) dst;
  1778. (void) src0_ddq_i;
  1779. (void) src1_ddf_i;
  1780. (void) i1;
  1781. }
  1782. inline void ggml_cuda_op_diag_mask_inf(
  1783. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1784. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1785. cudaStream_t & cudaStream_main){
  1786. GGML_ASSERT(src0_ddf_i != nullptr);
  1787. GGML_ASSERT(dst_ddf_i != nullptr);
  1788. const int64_t ne00 = src0->ne[0];
  1789. const int64_t ne01 = src0->ne[1];
  1790. const int64_t i01_diff = i01_high - i01_low;
  1791. const int n_past = ((int32_t *) src1->data)[0];
  1792. // compute
  1793. diag_mask_inf_f32_cuda(src0_ddf_i, dst_ddf_i, ne00, i01_diff, ne01, n_past, cudaStream_main);
  1794. CUDA_CHECK(cudaGetLastError());
  1795. (void) dst;
  1796. (void) src0_ddq_i;
  1797. (void) src1_ddf_i;
  1798. (void) i02;
  1799. (void) i1;
  1800. }
  1801. inline void ggml_cuda_op_soft_max(
  1802. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1803. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1804. cudaStream_t & cudaStream_main){
  1805. GGML_ASSERT(src0_ddf_i != nullptr);
  1806. GGML_ASSERT(dst_ddf_i != nullptr);
  1807. const int64_t ne00 = src0->ne[0];
  1808. const int64_t i01_diff = i01_high - i01_low;
  1809. // compute
  1810. soft_max_f32_cuda(src0_ddf_i, dst_ddf_i, ne00, i01_diff, cudaStream_main);
  1811. CUDA_CHECK(cudaGetLastError());
  1812. (void) src1;
  1813. (void) dst;
  1814. (void) src0_ddq_i;
  1815. (void) src1_ddf_i;
  1816. (void) i02;
  1817. (void) i1;
  1818. }
  1819. inline void ggml_cuda_op_scale(
  1820. const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, char * src0_ddq_i,
  1821. float * src0_ddf_i, float * src1_ddf_i, float * dst_ddf_i, int64_t i02, int64_t i01_low, int64_t i01_high, int i1,
  1822. cudaStream_t & cudaStream_main){
  1823. GGML_ASSERT(src0_ddf_i != nullptr);
  1824. GGML_ASSERT(dst_ddf_i != nullptr);
  1825. const float scale = ((float *) src1->data)[0];
  1826. const int64_t ne00 = src0->ne[0];
  1827. const int64_t i01_diff = i01_high - i01_low;
  1828. // compute
  1829. scale_f32_cuda(src0_ddf_i, dst_ddf_i, scale, ne00*i01_diff, cudaStream_main);
  1830. CUDA_CHECK(cudaGetLastError());
  1831. (void) src1;
  1832. (void) dst;
  1833. (void) src0_ddq_i;
  1834. (void) src1_ddf_i;
  1835. (void) i02;
  1836. (void) i1;
  1837. }
  1838. static void ggml_cuda_op(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
  1839. ggml_cuda_op_t op, bool src0_needs_f32, bool flatten_rows) {
  1840. const int64_t ne00 = src0->ne[0];
  1841. const int64_t ne01 = src0->ne[1];
  1842. const int64_t ne02 = src0->ne[2];
  1843. const int64_t ne03 = src0->ne[3];
  1844. const int64_t nrows0 = ggml_nrows(src0);
  1845. const bool use_src1 = src1 != nullptr;
  1846. const int64_t ne10 = use_src1 ? src1->ne[0] : 1;
  1847. const int64_t ne11 = use_src1 ? src1->ne[1] : 1;
  1848. const int64_t ne12 = use_src1 ? src1->ne[2] : 1;
  1849. const int64_t ne13 = use_src1 ? src1->ne[3] : 1;
  1850. const int64_t ne0 = dst->ne[0];
  1851. const int64_t ne1 = dst->ne[1];
  1852. const int nb2 = dst->nb[2];
  1853. const int nb3 = dst->nb[3];
  1854. GGML_ASSERT(dst->backend != GGML_BACKEND_GPU_SPLIT);
  1855. GGML_ASSERT(!use_src1 || src1->backend != GGML_BACKEND_GPU_SPLIT);
  1856. // strides for iteration over dims 3 and 2
  1857. const int64_t num_iters = flatten_rows ? 1 : ne02 * ne03;
  1858. const int64_t stride_mod = flatten_rows ? ne02 * ne03 : 1;
  1859. const int64_t src0_stride = ne00 * ne01 * stride_mod;
  1860. const int64_t src1_stride = ne10 * ne11 * stride_mod;
  1861. const int64_t dst_stride = ne0 * ne1 * stride_mod;
  1862. const size_t src0_ts = ggml_type_size(src0->type);
  1863. const size_t src0_bs = ggml_blck_size(src0->type);
  1864. struct ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu *) src0->extra;
  1865. struct ggml_tensor_extra_gpu * src1_extra = use_src1 ? (ggml_tensor_extra_gpu *) src1->extra : nullptr;
  1866. struct ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  1867. const bool src0_on_device = src0->backend == GGML_BACKEND_GPU || src0->backend == GGML_BACKEND_GPU_SPLIT;
  1868. const bool src0_is_contiguous = ggml_is_contiguous(src0);
  1869. const bool src0_is_f32 = src0->type == GGML_TYPE_F32;
  1870. const bool src1_is_contiguous = use_src1 && ggml_is_contiguous(src1);
  1871. const bool src1_stays_on_host = use_src1 && (
  1872. dst->op == GGML_OP_SCALE || dst->op == GGML_OP_DIAG_MASK_INF || dst->op == GGML_OP_ROPE);
  1873. const bool split = src0->backend == GGML_BACKEND_GPU_SPLIT;
  1874. const to_fp32_cuda_t to_fp32_cuda = ggml_get_to_fp32_cuda(src0->type);
  1875. // dd = data device
  1876. char * src0_ddq[GGML_CUDA_MAX_DEVICES] = {nullptr}; // quantized
  1877. float * src0_ddf[GGML_CUDA_MAX_DEVICES] = {nullptr}; // float
  1878. float * src1_ddf[GGML_CUDA_MAX_DEVICES] = {nullptr};
  1879. float * dst_ddf[GGML_CUDA_MAX_DEVICES] = {nullptr};
  1880. // asq = actual size quantized, asf = actual size float
  1881. size_t src0_asq[GGML_CUDA_MAX_DEVICES] = {0};
  1882. size_t src0_asf[GGML_CUDA_MAX_DEVICES] = {0};
  1883. size_t src1_asf[GGML_CUDA_MAX_DEVICES] = {0};
  1884. size_t dst_asf[GGML_CUDA_MAX_DEVICES] = {0};
  1885. // if multiple GPUs are used they need to wait for the main GPU to finish
  1886. if (split && g_device_count > 1) {
  1887. CUDA_CHECK(cudaSetDevice(g_main_device));
  1888. CUDA_CHECK(cudaDeviceSynchronize());
  1889. }
  1890. for (int id = 0; id < g_device_count; ++id) {
  1891. if (!split && id != g_main_device) {
  1892. continue;
  1893. }
  1894. const bool src1_on_device = use_src1 && src1->backend == GGML_BACKEND_GPU && id == g_main_device;
  1895. const bool dst_on_device = dst->backend == GGML_BACKEND_GPU && id == g_main_device;
  1896. int64_t row_low, row_high;
  1897. if (split) {
  1898. row_low = id == 0 ? 0 : nrows0*g_tensor_split[id];
  1899. row_high = id == g_device_count - 1 ? nrows0 : nrows0*g_tensor_split[id + 1];
  1900. } else {
  1901. row_low = 0;
  1902. row_high = nrows0;
  1903. }
  1904. if (row_low == row_high) {
  1905. continue;
  1906. }
  1907. int64_t row_diff = row_high - row_low;
  1908. cudaSetDevice(id);
  1909. if (src0_on_device && src0_is_contiguous) {
  1910. if (src0_is_f32) {
  1911. src0_ddf[id] = (float *) src0_extra->data_device[id];
  1912. } else {
  1913. src0_ddq[id] = (char *) src0_extra->data_device[id];
  1914. }
  1915. } else {
  1916. if (src0_is_f32) {
  1917. src0_ddf[id] = (float *) ggml_cuda_pool_malloc(row_diff*ne00 * sizeof(float), &src0_asf[id]);
  1918. } else {
  1919. src0_ddq[id] = (char *) ggml_cuda_pool_malloc(row_diff*ne00 * src0_ts/src0_bs, &src0_asq[id]);
  1920. }
  1921. }
  1922. if (src0_needs_f32 && !src0_is_f32) {
  1923. src0_ddf[id] = (float *) ggml_cuda_pool_malloc(row_diff*ne00 * sizeof(float), &src0_asf[id]);
  1924. }
  1925. if (use_src1 && !src1_stays_on_host) {
  1926. if (src1_on_device && src1_is_contiguous) {
  1927. src1_ddf[id] = (float *) src1_extra->data_device[id];
  1928. } else {
  1929. src1_ddf[id] = (float *) ggml_cuda_pool_malloc(num_iters*src1_stride * sizeof(float), &src1_asf[id]);
  1930. }
  1931. }
  1932. if (dst_on_device) {
  1933. dst_ddf[id] = (float *) dst_extra->data_device[id];
  1934. } else {
  1935. size_t size_dst_ddf = split ? row_diff*ne1 * sizeof(float) : num_iters*dst_stride * sizeof(float);
  1936. dst_ddf[id] = (float *) ggml_cuda_pool_malloc(size_dst_ddf, &dst_asf[id]);
  1937. }
  1938. const int64_t i03_max = flatten_rows ? 1 : ne03;
  1939. const int64_t i02_max = flatten_rows ? 1 : ne02;
  1940. const int64_t rows_per_iter = flatten_rows ? nrows0 : ne01;
  1941. for (int64_t i03 = 0; i03 < i03_max; i03++) {
  1942. const int64_t i13 = i03 % ne13;
  1943. for (int64_t i02 = 0; i02 < i02_max; i02++) {
  1944. const int64_t i12 = i02 % ne12;
  1945. const int64_t i0 = i03*ne02 + i02;
  1946. // i0 values that contain the lower/upper rows for a split tensor when using multiple GPUs
  1947. const int64_t i0_offset_low = row_low/rows_per_iter;
  1948. const int64_t i0_offset_high = row_high/rows_per_iter;
  1949. int64_t i01_low = 0;
  1950. int64_t i01_high = rows_per_iter;
  1951. if (split) {
  1952. if (i0 < i0_offset_low || i0 > i0_offset_high) {
  1953. continue;
  1954. }
  1955. if (i0 == i0_offset_low) {
  1956. i01_low = row_low % rows_per_iter;
  1957. }
  1958. if (i0 == i0_offset_high) {
  1959. i01_high = row_high % rows_per_iter;
  1960. }
  1961. }
  1962. // There is possibly a bug in the Windows nvcc compiler regarding instruction reordering or optimizing out local variables.
  1963. // Removing the first assert or changing the order of the arguments causes the second assert to fail.
  1964. // Removing both asserts results in i01_high becoming 0 which in turn results in garbage output.
  1965. // The root cause seems to be a problem with i0_offset_high becoming 0 when it should always be >0 (for single GPU).
  1966. GGML_ASSERT(i01_low == 0 || g_device_count > 1);
  1967. GGML_ASSERT(i01_high == rows_per_iter || g_device_count > 1);
  1968. const int64_t i01_diff = i01_high - i01_low;
  1969. if (i01_diff == 0) {
  1970. continue;
  1971. }
  1972. const int64_t i11 = i13*ne12 + i12;
  1973. cudaStream_t cudaStream_main = g_cudaStreams_main[id];
  1974. // for split tensors the data begins at i0 == i0_offset_low
  1975. char * src0_ddq_i = src0_ddq[id] + (i0 - i0_offset_low)*src0_stride*src0_ts/src0_bs;
  1976. float * src0_ddf_i = src0_ddf[id] + (i0 - i0_offset_low)*src0_stride;
  1977. float * src1_ddf_i = src1_ddf[id] + i11*src1_stride;
  1978. float * dst_ddf_i = dst_ddf[id] + (i0 - i0_offset_low)*dst_stride;
  1979. // for split tensors the data pointer needs to be rounded down
  1980. // to the bin edge for i03, i02 bins beyond the first
  1981. if (i0 - i0_offset_low > 0) {
  1982. GGML_ASSERT(!flatten_rows);
  1983. src0_ddq_i -= (row_low % ne01)*ne00 * src0_ts/src0_bs;
  1984. src0_ddf_i -= (row_low % ne01)*ne00;
  1985. dst_ddf_i -= (row_low % ne0)*ne1;
  1986. }
  1987. // the main device memory buffer can be on VRAM scratch, with space for all partial results
  1988. // in that case an offset on dst_ddf_i is needed
  1989. if (dst->backend == GGML_BACKEND_GPU && id == g_main_device) {
  1990. dst_ddf_i += i01_low; // offset is 0 if no tensor split
  1991. }
  1992. // copy src0, src1 to device if necessary
  1993. if (use_src1 && !src1_stays_on_host) {
  1994. if (src1->backend == GGML_BACKEND_CPU) {
  1995. GGML_ASSERT(!flatten_rows || nrows0 == ggml_nrows(src1));
  1996. int64_t nrows1 = flatten_rows ? nrows0 : ne11;
  1997. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(src1_ddf_i, src1, i03, i02, 0, nrows1, cudaStream_main));
  1998. } else if (src1->backend == GGML_BACKEND_GPU && src1_is_contiguous) {
  1999. if (id != g_main_device) {
  2000. GGML_ASSERT(!flatten_rows);
  2001. float * src1_ddf_i_source = (float *) src1_extra->data_device[g_main_device];
  2002. src1_ddf_i_source += i11*src1_stride;
  2003. CUDA_CHECK(cudaMemcpyAsync(src1_ddf_i, src1_ddf_i_source, src1_stride*sizeof(float),
  2004. cudaMemcpyDeviceToDevice, cudaStream_main));
  2005. }
  2006. } else if (src1_on_device && !src1_is_contiguous) {
  2007. GGML_ASSERT(!split);
  2008. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(src1_ddf_i, src1, i03, i02, 0, ne11, cudaStream_main));
  2009. } else {
  2010. GGML_ASSERT(false);
  2011. }
  2012. }
  2013. if (!src0_on_device || !src0_is_contiguous) {
  2014. if (src0_is_f32) {
  2015. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(src0_ddf_i, src0, i03, i02, i01_low, i01_high, cudaStream_main));
  2016. } else {
  2017. CUDA_CHECK(ggml_cuda_cpy_tensor_2d(src0_ddq_i, src0, i03, i02, i01_low, i01_high, cudaStream_main));
  2018. }
  2019. }
  2020. // convert src0 to f32 if it is necessary for the ggml_cuda_op
  2021. if (src0_needs_f32 && !src0_is_f32) {
  2022. to_fp32_cuda(src0_ddq_i, src0_ddf_i, i01_diff*ne00, cudaStream_main);
  2023. CUDA_CHECK(cudaGetLastError());
  2024. }
  2025. // do the computation
  2026. op(src0, src1, dst, src0_ddq_i, src0_ddf_i, src1_ddf_i, dst_ddf_i, i02, i01_low, i01_high, i11, cudaStream_main);
  2027. // copy dst to host or other device if necessary
  2028. if (!dst_on_device) {
  2029. void * dst_off_device;
  2030. cudaMemcpyKind kind;
  2031. if (dst->backend == GGML_BACKEND_CPU) {
  2032. dst_off_device = dst->data;
  2033. kind = cudaMemcpyDeviceToHost;
  2034. } else if (dst->backend == GGML_BACKEND_GPU) {
  2035. dst_off_device = dst_extra->data_device[g_main_device];
  2036. kind = cudaMemcpyDeviceToDevice;
  2037. } else {
  2038. GGML_ASSERT(false);
  2039. }
  2040. if (split) {
  2041. // src0 = weight matrix is saved as a transposed matrix for better memory layout.
  2042. // dst is NOT transposed.
  2043. // The outputs of cuBLAS matrix matrix multiplications can therefore NOT simply be concatenated for >1 GPU.
  2044. // Instead they need to be copied to the correct slice in ne0 = dst row index.
  2045. // If dst is a vector with ne0 == 1 then you don't have to do this but it still produces correct results.
  2046. for (int64_t j = 0; j < ne1; ++j) {
  2047. float * dhf_dst_i = (float *) ((char *) dst_off_device + (j*ne0 + i01_low)*sizeof(float) + i02*nb2 + i03*nb3);
  2048. CUDA_CHECK(cudaMemcpyAsync(dhf_dst_i, dst_ddf_i + j*i01_diff, i01_diff*sizeof(float), kind, cudaStream_main));
  2049. }
  2050. } else {
  2051. float * dhf_dst_i = (float *) ((char *) dst_off_device + i02*nb2 + i03*nb3);
  2052. CUDA_CHECK(cudaMemcpyAsync(dhf_dst_i, dst_ddf_i, dst_stride*sizeof(float), kind, cudaStream_main));
  2053. }
  2054. }
  2055. }
  2056. }
  2057. }
  2058. // wait until each device is finished, then free their buffers
  2059. for (int id = 0; id < g_device_count; ++id) {
  2060. if (src0_asq[id] == 0 && src0_asf[id] == 0 && src1_asf[id] == 0 && dst_asf[id] == 0) {
  2061. continue;
  2062. }
  2063. CUDA_CHECK(cudaSetDevice(id));
  2064. CUDA_CHECK(cudaDeviceSynchronize());
  2065. if (src0_asq[id] > 0) {
  2066. ggml_cuda_pool_free(src0_ddq[id], src0_asq[id]);
  2067. }
  2068. if (src0_asf[id] > 0) {
  2069. ggml_cuda_pool_free(src0_ddf[id], src0_asf[id]);
  2070. }
  2071. if (src1_asf[id] > 0) {
  2072. ggml_cuda_pool_free(src1_ddf[id], src1_asf[id]);
  2073. }
  2074. if (dst_asf[id] > 0) {
  2075. ggml_cuda_pool_free(dst_ddf[id], dst_asf[id]);
  2076. }
  2077. }
  2078. }
  2079. void ggml_cuda_add(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2080. // ggml_cuda_add permits f16 dst even though this could in theory cause problems with the pointer arithmetic in ggml_cuda_op.
  2081. // Due to flatten_rows == true this does in practice not make a difference however.
  2082. // Better solution would be nice but right now that would require disproportionate changes.
  2083. GGML_ASSERT(
  2084. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) &&
  2085. src1->type == GGML_TYPE_F32 &&
  2086. (dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16));
  2087. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_add, false, true);
  2088. }
  2089. void ggml_cuda_mul(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2090. GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2091. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_mul, true, false); // TODO ggml_cuda_op needs modification for flatten
  2092. }
  2093. void ggml_cuda_silu(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2094. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2095. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_silu, true, true);
  2096. }
  2097. void ggml_cuda_rms_norm(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2098. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2099. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_rms_norm, true, true);
  2100. }
  2101. bool ggml_cuda_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  2102. const int64_t ne10 = src1->ne[0];
  2103. const int64_t ne0 = dst->ne[0];
  2104. const int64_t ne1 = dst->ne[1];
  2105. // TODO: find the optimal values for these
  2106. if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) &&
  2107. src1->type == GGML_TYPE_F32 &&
  2108. dst->type == GGML_TYPE_F32 &&
  2109. (ne0 >= 32 && ne1 >= 32 && ne10 >= 32)) {
  2110. return true;
  2111. }
  2112. return false;
  2113. }
  2114. void ggml_cuda_mul_mat_vec_p021(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst){
  2115. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  2116. GGML_ASSERT(src0->backend != GGML_BACKEND_GPU_SPLIT);
  2117. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // 0213 permutation
  2118. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // 0213 permutation
  2119. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2120. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2121. const int64_t ne00 = src0->ne[0];
  2122. const int64_t ne01 = src0->ne[1];
  2123. const int64_t ne02 = src0->ne[2];
  2124. CUDA_CHECK(cudaSetDevice(g_main_device));
  2125. cudaStream_t cudaStream_main = g_cudaStreams_main[g_main_device];
  2126. struct ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu *) src0->extra;
  2127. void * src0_ddq = src0_extra->data_device[g_main_device];
  2128. struct ggml_tensor_extra_gpu * src1_extra = (ggml_tensor_extra_gpu *) src1->extra;
  2129. float * src1_ddf = (float *) src1_extra->data_device[g_main_device];
  2130. struct ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  2131. float * dst_ddf = (float *) dst_extra->data_device[g_main_device];
  2132. ggml_mul_mat_p021_f16_f32_cuda(src0_ddq, src1_ddf, dst_ddf, ne00, ne01, ne02, cudaStream_main);
  2133. }
  2134. void ggml_cuda_mul_mat_vec_nc(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst){
  2135. GGML_ASSERT(!ggml_is_contiguous(src0) && ggml_is_contiguous(src1));
  2136. GGML_ASSERT(!ggml_is_permuted(src0));
  2137. GGML_ASSERT(src0->backend != GGML_BACKEND_GPU_SPLIT);
  2138. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2139. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2140. const int64_t ne00 = src0->ne[0];
  2141. const int64_t ne01 = src0->ne[1];
  2142. const int64_t ne02 = src0->ne[2];
  2143. const int64_t nb01 = src0->nb[1];
  2144. const int64_t nb02 = src0->nb[2];
  2145. CUDA_CHECK(cudaSetDevice(g_main_device));
  2146. cudaStream_t cudaStream_main = g_cudaStreams_main[g_main_device];
  2147. struct ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu *) src0->extra;
  2148. void * src0_ddq = src0_extra->data_device[g_main_device];
  2149. struct ggml_tensor_extra_gpu * src1_extra = (ggml_tensor_extra_gpu *) src1->extra;
  2150. float * src1_ddf = (float *) src1_extra->data_device[g_main_device];
  2151. struct ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  2152. float * dst_ddf = (float *) dst_extra->data_device[g_main_device];
  2153. const int row_stride_x = nb01 / sizeof(half);
  2154. const int channel_stride_x = nb02 / sizeof(half);
  2155. ggml_mul_mat_vec_nc_f16_f32_cuda(src0_ddq, src1_ddf, dst_ddf, ne00, ne01, row_stride_x, ne02, channel_stride_x, cudaStream_main);
  2156. }
  2157. void ggml_cuda_mul_mat(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2158. bool all_on_device = (src0->backend == GGML_BACKEND_GPU || src0->backend == GGML_BACKEND_GPU_SPLIT) &&
  2159. src1->backend == GGML_BACKEND_GPU && dst->backend == GGML_BACKEND_GPU;
  2160. if (all_on_device && ggml_is_permuted(src0) && ggml_is_permuted(src1) && src1->ne[1] == 1) {
  2161. ggml_cuda_mul_mat_vec_p021(src0, src1, dst);
  2162. } else if (all_on_device && !ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && src1->ne[1] == 1) {
  2163. ggml_cuda_mul_mat_vec_nc(src0, src1, dst);
  2164. }else if (src0->type == GGML_TYPE_F32) {
  2165. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_mul_mat_cublas, true, false);
  2166. } else if (ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F16) {
  2167. if (src1->ne[1] == 1 && src0->ne[0] % GGML_CUDA_DMMV_X == 0 && src0->ne[1] % GGML_CUDA_DMMV_Y == 0) {
  2168. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_dequantize_mul_mat_vec, false, false);
  2169. } else {
  2170. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_mul_mat_cublas, true, false);
  2171. }
  2172. } else {
  2173. GGML_ASSERT(false);
  2174. }
  2175. }
  2176. void ggml_cuda_scale(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2177. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2178. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_scale, true, true);
  2179. }
  2180. void ggml_cuda_cpy(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2181. const int64_t ne = ggml_nelements(src0);
  2182. GGML_ASSERT(ne == ggml_nelements(src1));
  2183. GGML_ASSERT(src0->backend == GGML_BACKEND_GPU);
  2184. GGML_ASSERT(src1->backend == GGML_BACKEND_GPU);
  2185. GGML_ASSERT(ggml_nbytes(src0) <= INT_MAX);
  2186. GGML_ASSERT(ggml_nbytes(src1) <= INT_MAX);
  2187. const int64_t ne00 = src0->ne[0];
  2188. const int64_t ne01 = src0->ne[1];
  2189. GGML_ASSERT(src0->ne[3] == 1);
  2190. const int64_t nb00 = src0->nb[0];
  2191. const int64_t nb01 = src0->nb[1];
  2192. const int64_t nb02 = src0->nb[2];
  2193. const int64_t ne10 = src1->ne[0];
  2194. const int64_t ne11 = src1->ne[1];
  2195. GGML_ASSERT(src1->ne[3] == 1);
  2196. const int64_t nb10 = src1->nb[0];
  2197. const int64_t nb11 = src1->nb[1];
  2198. const int64_t nb12 = src1->nb[2];
  2199. CUDA_CHECK(cudaSetDevice(g_main_device));
  2200. cudaStream_t cudaStream_main = g_cudaStreams_main[g_main_device];
  2201. const struct ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu *) src0->extra;
  2202. const struct ggml_tensor_extra_gpu * src1_extra = (ggml_tensor_extra_gpu *) src1->extra;
  2203. char * src0_ddc = (char *) src0_extra->data_device[g_main_device];
  2204. char * src1_ddc = (char *) src1_extra->data_device[g_main_device];
  2205. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32) {
  2206. ggml_cpy_f32_f32_cuda(src0_ddc, src1_ddc, ne, ne00, ne01, nb00, nb01, nb02,
  2207. ne10, ne11, nb10, nb11, nb12, cudaStream_main);
  2208. } else if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16) {
  2209. ggml_cpy_f32_f16_cuda(src0_ddc, src1_ddc, ne, ne00, ne01, nb00, nb01, nb02,
  2210. ne10, ne11, nb10, nb11, nb12, cudaStream_main);
  2211. } else {
  2212. GGML_ASSERT(false);
  2213. }
  2214. (void) dst;
  2215. }
  2216. void ggml_cuda_diag_mask_inf(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2217. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2218. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_diag_mask_inf, true, true);
  2219. }
  2220. void ggml_cuda_soft_max(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2221. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2222. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_soft_max, true, true);
  2223. }
  2224. void ggml_cuda_rope(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2225. GGML_ASSERT(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  2226. ggml_cuda_op(src0, src1, dst, ggml_cuda_op_rope, true, false); // FIXME flatten changes results
  2227. }
  2228. void ggml_cuda_nop(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2229. (void) src0;
  2230. (void) src1;
  2231. (void) dst;
  2232. }
  2233. void ggml_cuda_transform_tensor(void * data, struct ggml_tensor * tensor) {
  2234. int nrows = ggml_nrows(tensor);
  2235. const size_t nb1 = tensor->nb[1];
  2236. ggml_backend backend = tensor->backend;
  2237. struct ggml_tensor_extra_gpu * extra = new struct ggml_tensor_extra_gpu;
  2238. memset(extra, 0, sizeof(*extra));
  2239. for (int id = 0; id < g_device_count; ++id) {
  2240. if (backend == GGML_BACKEND_GPU && id != g_main_device) {
  2241. continue;
  2242. }
  2243. cudaSetDevice(id);
  2244. int row_low, row_high;
  2245. if (backend == GGML_BACKEND_GPU) {
  2246. row_low = 0;
  2247. row_high = nrows;
  2248. } else if (backend == GGML_BACKEND_GPU_SPLIT) {
  2249. row_low = id == 0 ? 0 : nrows*g_tensor_split[id];
  2250. row_high = id == g_device_count - 1 ? nrows : nrows*g_tensor_split[id + 1];
  2251. } else {
  2252. GGML_ASSERT(false);
  2253. }
  2254. if (row_low == row_high) {
  2255. continue;
  2256. }
  2257. int64_t nrows_split = row_high - row_low;
  2258. const size_t offset_split = row_low*nb1;
  2259. const size_t size = ggml_nbytes_split(tensor, nrows_split);
  2260. void * buf;
  2261. CUDA_CHECK(cudaMalloc(&buf, size));
  2262. void * buf_host = (char*)data + offset_split;
  2263. cudaMemcpy(buf, buf_host, size, cudaMemcpyHostToDevice);
  2264. extra->data_device[id] = buf;
  2265. }
  2266. tensor->extra = extra;
  2267. }
  2268. void ggml_cuda_free_data(struct ggml_tensor * tensor) {
  2269. if (tensor->backend != GGML_BACKEND_GPU && tensor->backend != GGML_BACKEND_GPU_SPLIT) {
  2270. return;
  2271. }
  2272. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  2273. for (int id = 0; id < g_device_count; ++id) {
  2274. if (extra->data_device[id] == nullptr) {
  2275. continue;
  2276. }
  2277. CUDA_CHECK(cudaSetDevice(id));
  2278. CUDA_CHECK(cudaFree(extra->data_device[id]));
  2279. }
  2280. delete extra;
  2281. }
  2282. void ggml_cuda_assign_buffers_impl(struct ggml_tensor * tensor, bool scratch, bool force_inplace) {
  2283. if (scratch && g_scratch_size == 0) {
  2284. return;
  2285. }
  2286. // recursively assign CUDA buffers until a compute tensor is found
  2287. if (tensor->src0 != nullptr && tensor->src0->backend == GGML_BACKEND_CPU) {
  2288. const ggml_op src0_op = tensor->src0->op;
  2289. if (src0_op == GGML_OP_RESHAPE || src0_op == GGML_OP_TRANSPOSE || src0_op == GGML_OP_VIEW) {
  2290. ggml_cuda_assign_buffers_impl(tensor->src0, scratch, force_inplace);
  2291. }
  2292. }
  2293. if (tensor->op == GGML_OP_CPY && tensor->src1->backend == GGML_BACKEND_CPU) {
  2294. ggml_cuda_assign_buffers_impl(tensor->src1, scratch, force_inplace);
  2295. }
  2296. tensor->backend = GGML_BACKEND_GPU;
  2297. struct ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu;
  2298. memset(extra, 0, sizeof(*extra));
  2299. const bool inplace = (tensor->src0 != nullptr && tensor->src0->data == tensor->data) ||
  2300. tensor->op == GGML_OP_VIEW ||
  2301. force_inplace;
  2302. const size_t size = ggml_nbytes(tensor);
  2303. CUDA_CHECK(cudaSetDevice(g_main_device));
  2304. if (inplace && (tensor->src0->backend == GGML_BACKEND_GPU || tensor->src0->backend == GGML_BACKEND_GPU_SPLIT)) {
  2305. struct ggml_tensor_extra_gpu * src0_extra = (ggml_tensor_extra_gpu * ) tensor->src0->extra;
  2306. char * src0_ddc = (char *) src0_extra->data_device[g_main_device];
  2307. size_t offset = 0;
  2308. if (tensor->op == GGML_OP_VIEW) {
  2309. memcpy(&offset, tensor->opt[0]->data, sizeof(size_t));
  2310. }
  2311. extra->data_device[g_main_device] = src0_ddc + offset;
  2312. } else if (tensor->op == GGML_OP_CPY) {
  2313. struct ggml_tensor_extra_gpu * src1_extra = (ggml_tensor_extra_gpu * ) tensor->src1->extra;
  2314. void * src1_ddv = src1_extra->data_device[g_main_device];
  2315. extra->data_device[g_main_device] = src1_ddv;
  2316. } else if (scratch) {
  2317. GGML_ASSERT(size <= g_scratch_size);
  2318. if (g_scratch_offset + size > g_scratch_size) {
  2319. g_scratch_offset = 0;
  2320. }
  2321. char * data = (char *) g_scratch_buffer;
  2322. if (data == nullptr) {
  2323. CUDA_CHECK(cudaMalloc(&data, g_scratch_size));
  2324. g_scratch_buffer = data;
  2325. }
  2326. extra->data_device[g_main_device] = data + g_scratch_offset;
  2327. g_scratch_offset += size;
  2328. GGML_ASSERT(g_scratch_offset <= g_scratch_size);
  2329. } else { // allocate new buffers outside of scratch
  2330. void * data;
  2331. CUDA_CHECK(cudaMalloc(&data, size));
  2332. CUDA_CHECK(cudaMemset(data, 0, size));
  2333. extra->data_device[g_main_device] = data;
  2334. }
  2335. tensor->extra = extra;
  2336. }
  2337. void ggml_cuda_assign_buffers(struct ggml_tensor * tensor) {
  2338. ggml_cuda_assign_buffers_impl(tensor, true, false);
  2339. }
  2340. void ggml_cuda_assign_buffers_no_scratch(struct ggml_tensor * tensor) {
  2341. ggml_cuda_assign_buffers_impl(tensor, false, false);
  2342. }
  2343. void ggml_cuda_assign_buffers_force_inplace(struct ggml_tensor * tensor) {
  2344. ggml_cuda_assign_buffers_impl(tensor, false, true);
  2345. }
  2346. void ggml_cuda_set_main_device(int main_device) {
  2347. if (main_device >= g_device_count) {
  2348. fprintf(stderr, "warning: cannot set main_device=%d because there are only %d devices. Using device %d instead.\n",
  2349. main_device, g_device_count, g_main_device);
  2350. return;
  2351. }
  2352. g_main_device = main_device;
  2353. if (g_device_count > 1) {
  2354. cudaDeviceProp prop;
  2355. CUDA_CHECK(cudaGetDeviceProperties(&prop, g_main_device));
  2356. fprintf(stderr, "%s: using device %d (%s) as main device\n", __func__, g_main_device, prop.name);
  2357. }
  2358. }
  2359. void ggml_cuda_set_scratch_size(size_t scratch_size) {
  2360. g_scratch_size = scratch_size;
  2361. }
  2362. void ggml_cuda_free_scratch() {
  2363. if (g_scratch_buffer == nullptr) {
  2364. return;
  2365. }
  2366. CUDA_CHECK(cudaFree(g_scratch_buffer));
  2367. g_scratch_buffer = nullptr;
  2368. }
  2369. bool ggml_cuda_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor){
  2370. ggml_cuda_func_t func;
  2371. const bool any_on_device = tensor->backend == GGML_BACKEND_GPU
  2372. || (tensor->src0 != nullptr && (tensor->src0->backend == GGML_BACKEND_GPU || tensor->src0->backend == GGML_BACKEND_GPU_SPLIT))
  2373. || (tensor->src1 != nullptr && tensor->src1->backend == GGML_BACKEND_GPU);
  2374. switch (tensor->op) {
  2375. case GGML_OP_ADD:
  2376. if (!any_on_device) {
  2377. return false;
  2378. }
  2379. func = ggml_cuda_add;
  2380. break;
  2381. case GGML_OP_MUL:
  2382. if (!any_on_device) {
  2383. return false;
  2384. }
  2385. func = ggml_cuda_mul;
  2386. break;
  2387. case GGML_OP_SILU:
  2388. if (!any_on_device) {
  2389. return false;
  2390. }
  2391. func = ggml_cuda_silu;
  2392. break;
  2393. case GGML_OP_RMS_NORM:
  2394. if (!any_on_device) {
  2395. return false;
  2396. }
  2397. func = ggml_cuda_rms_norm;
  2398. break;
  2399. case GGML_OP_MUL_MAT:
  2400. if (!any_on_device && !ggml_cuda_can_mul_mat(tensor->src0, tensor->src1, tensor)) {
  2401. return false;
  2402. }
  2403. func = ggml_cuda_mul_mat;
  2404. break;
  2405. case GGML_OP_SCALE:
  2406. if (!any_on_device) {
  2407. return false;
  2408. }
  2409. func = ggml_cuda_scale;
  2410. break;
  2411. case GGML_OP_CPY:
  2412. if (!any_on_device) {
  2413. return false;
  2414. }
  2415. func = ggml_cuda_cpy;
  2416. break;
  2417. case GGML_OP_RESHAPE:
  2418. case GGML_OP_VIEW:
  2419. case GGML_OP_PERMUTE:
  2420. case GGML_OP_TRANSPOSE:
  2421. if (!any_on_device) {
  2422. return false;
  2423. }
  2424. func = ggml_cuda_nop;
  2425. break;
  2426. case GGML_OP_DIAG_MASK_INF:
  2427. if (!any_on_device) {
  2428. return false;
  2429. }
  2430. func = ggml_cuda_diag_mask_inf;
  2431. break;
  2432. case GGML_OP_SOFT_MAX:
  2433. if (!any_on_device) {
  2434. return false;
  2435. }
  2436. func = ggml_cuda_soft_max;
  2437. break;
  2438. case GGML_OP_ROPE:
  2439. if (!any_on_device) {
  2440. return false;
  2441. }
  2442. func = ggml_cuda_rope;
  2443. break;
  2444. default:
  2445. return false;
  2446. }
  2447. if (params->ith != 0) {
  2448. return true;
  2449. }
  2450. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  2451. return true;
  2452. }
  2453. func(tensor->src0, tensor->src1, tensor);
  2454. return true;
  2455. }