ggml-opencl.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. #include "ggml.h"
  2. #include "ggml-opencl.h"
  3. #include "ggml-backend-impl.h"
  4. #include <array>
  5. #include <atomic>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <limits>
  10. #include <sstream>
  11. #include <vector>
  12. #define CL_TARGET_OPENCL_VERSION 120
  13. #include <clblast.h>
  14. #if defined(_MSC_VER)
  15. #pragma warning(disable: 4244 4267) // possible loss of data
  16. #endif
  17. #define CL_DMMV_LOCAL_SIZE 32
  18. #ifndef K_QUANTS_PER_ITERATION
  19. #define K_QUANTS_PER_ITERATION 1
  20. #else
  21. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  22. #endif
  23. #define MULTILINE_QUOTE(...) #__VA_ARGS__
  24. static std::string program_source = MULTILINE_QUOTE(
  25. typedef char int8_t;
  26. typedef uchar uint8_t;
  27. typedef short int16_t;
  28. typedef ushort uint16_t;
  29. typedef int int32_t;
  30. typedef uint uint32_t;
  31. struct __attribute__ ((packed)) block_q4_0
  32. {
  33. half d;
  34. uint8_t qs[QK4_0 / 2];
  35. };
  36. struct __attribute__ ((packed)) block_q4_1
  37. {
  38. half d;
  39. half m;
  40. uint8_t qs[QK4_1 / 2];
  41. };
  42. struct __attribute__ ((packed)) block_q5_0
  43. {
  44. half d;
  45. uint32_t qh;
  46. uint8_t qs[QK5_0 / 2];
  47. };
  48. struct __attribute__ ((packed)) block_q5_1
  49. {
  50. half d;
  51. half m;
  52. uint32_t qh;
  53. uint8_t qs[QK5_1 / 2];
  54. };
  55. struct __attribute__ ((packed)) block_q8_0
  56. {
  57. half d;
  58. int8_t qs[QK8_0];
  59. };
  60. struct __attribute__((packed)) block_q2_K
  61. {
  62. uint8_t scales[16];
  63. uint8_t qs[64];
  64. half d;
  65. half dmin;
  66. };
  67. struct __attribute__((packed)) block_q3_K
  68. {
  69. uint8_t hmask[32];
  70. uint8_t qs[64];
  71. uint8_t scales[12];
  72. half d;
  73. };
  74. struct __attribute__((packed)) block_q4_K
  75. {
  76. half d;
  77. half dmin;
  78. uint8_t scales[12];
  79. uint8_t qs[128];
  80. };
  81. struct __attribute__((packed)) block_q5_K
  82. {
  83. half d;
  84. half dmin;
  85. uint8_t scales[12];
  86. uint8_t qh[32];
  87. uint8_t qs[128];
  88. };
  89. struct __attribute__((packed)) block_q6_K
  90. {
  91. uint8_t ql[128];
  92. uint8_t qh[64];
  93. int8_t scales[16];
  94. half d;
  95. };
  96. __kernel void convert_fp16_to_fp32(__global half* x, __global float* y) {
  97. const uint i = get_global_id(0);
  98. y[i] = vload_half(0, &x[i]);
  99. }
  100. void dequantize_q4_0(__global const struct block_q4_0* x, const int ib, const int iqs, float* v0, float* v1) {
  101. const float d = vload_half(0, &x[ib].d);
  102. const uint8_t vui = x[ib].qs[iqs];
  103. const int8_t vi0 = vui & 0xF;
  104. const int8_t vi1 = vui >> 4;
  105. *v0 = (vi0 - 8)*d;
  106. *v1 = (vi1 - 8)*d;
  107. }
  108. void dequantize_q4_1(__global const struct block_q4_1* x, const int ib, const int iqs, float* v0, float* v1) {
  109. const float d = vload_half(0, &x[ib].d);
  110. const float m = vload_half(0, &x[ib].m);
  111. const uint8_t vui = x[ib].qs[iqs];
  112. const int8_t vi0 = vui & 0xF;
  113. const int8_t vi1 = vui >> 4;
  114. *v0 = vi0*d + m;
  115. *v1 = vi1*d + m;
  116. }
  117. void dequantize_q5_0(__global const struct block_q5_0* x, const int ib, const int iqs, float* v0, float* v1) {
  118. const float d = vload_half(0, &x[ib].d);
  119. uint32_t qh = x[ib].qh;
  120. const uint8_t xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
  121. const uint8_t xh_1 = ((qh >> (iqs + 12)) ) & 0x10;
  122. const int32_t x0 = ((x[ib].qs[iqs] & 0xf) | xh_0) - 16;
  123. const int32_t x1 = ((x[ib].qs[iqs] >> 4) | xh_1) - 16;
  124. *v0 = x0*d;
  125. *v1 = x1*d;
  126. }
  127. void dequantize_q5_1(__global const struct block_q5_1* x, const int ib, const int iqs, float* v0, float* v1) {
  128. const float d = vload_half(0, &x[ib].d);
  129. const float m = vload_half(0, &x[ib].m);
  130. uint32_t qh = x[ib].qh;
  131. const uint8_t xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
  132. const uint8_t xh_1 = ((qh >> (iqs + 12)) ) & 0x10;
  133. const int32_t x0 = ((x[ib].qs[iqs] & 0xf) | xh_0);
  134. const int32_t x1 = ((x[ib].qs[iqs] >> 4) | xh_1);
  135. *v0 = x0*d + m;
  136. *v1 = x1*d + m;
  137. }
  138. void dequantize_q8_0(__global const struct block_q8_0* x, const int ib, const int iqs, float* v0, float* v1) {
  139. const float d = vload_half(0, &x[ib].d);
  140. const int8_t vi0 = x[ib].qs[iqs + 0];
  141. const int8_t vi1 = x[ib].qs[iqs + 1];
  142. *v0 = vi0*d;
  143. *v1 = vi1*d;
  144. }
  145. void convert_f16(__global half* x, const int ib, const int iqs, float* v0, float* v1){
  146. *v0 = vload_half(0, &x[ib + 0]);
  147. *v1 = vload_half(0, &x[ib + 1]);
  148. }
  149. );
  150. static std::string k_quants_source = MULTILINE_QUOTE(
  151. inline void get_scale_min_k4(int j, const __global uint8_t *q, uint8_t *d, uint8_t *m)
  152. {
  153. if (j < 4)
  154. {
  155. *d = q[j] & 63;
  156. *m = q[j + 4] & 63;
  157. }
  158. else
  159. {
  160. *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
  161. *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
  162. }
  163. }
  164. __kernel void dequantize_block_q2_K(__global const struct block_q2_K *x, __global float *yy)
  165. {
  166. const int i = get_group_id(0) + get_global_offset(0);
  167. const int tid = get_local_id(0);
  168. const int n = tid / 32;
  169. const int l = tid - 32 * n;
  170. const int is = 8 * n + l / 16;
  171. const uint8_t q = x[i].qs[32 * n + l];
  172. __global float *y = yy + get_group_id(0) * QK_K + 128 * n;
  173. const float dall = vload_half(0, &x[i].d);
  174. const float dmin = vload_half(0, &x[i].dmin);
  175. y[l + 0] = dall * (x[i].scales[is + 0] & 0xF) * ((q >> 0) & 3) - dmin * (x[i].scales[is + 0] >> 4);
  176. y[l + 32] = dall * (x[i].scales[is + 2] & 0xF) * ((q >> 2) & 3) - dmin * (x[i].scales[is + 2] >> 4);
  177. y[l + 64] = dall * (x[i].scales[is + 4] & 0xF) * ((q >> 4) & 3) - dmin * (x[i].scales[is + 4] >> 4);
  178. y[l + 96] = dall * (x[i].scales[is + 6] & 0xF) * ((q >> 6) & 3) - dmin * (x[i].scales[is + 6] >> 4);
  179. }
  180. __kernel void dequantize_block_q3_K(__global const struct block_q3_K *x, __global float *yy)
  181. {
  182. int r = get_local_id(0) / 4;
  183. int i = get_group_id(0) + get_global_offset(0);
  184. int tid = r / 2;
  185. int is0 = r % 2;
  186. int l0 = 16 * is0 + 4 * (get_local_id(0) % 4);
  187. int n = tid / 4;
  188. int j = tid - 4 * n;
  189. uint8_t m = 1 << (4 * n + j);
  190. int is = 8 * n + 2 * j + is0;
  191. int shift = 2 * j;
  192. int8_t us = is < 4 ? (x[i].scales[is - 0] & 0xF) | (((x[i].scales[is + 8] >> 0) & 3) << 4)
  193. : is < 8 ? (x[i].scales[is - 0] & 0xF) | (((x[i].scales[is + 4] >> 2) & 3) << 4)
  194. : is < 12 ? (x[i].scales[is - 8] >> 4) | (((x[i].scales[is + 0] >> 4) & 3) << 4)
  195. : (x[i].scales[is - 8] >> 4) | (((x[i].scales[is - 4] >> 6) & 3) << 4);
  196. float d_all = vload_half(0, &x[i].d);
  197. float dl = d_all * (us - 32);
  198. __global float *y = yy + get_group_id(0) * QK_K + 128 * n + 32 * j;
  199. const __global uint8_t *q = x[i].qs + 32 * n;
  200. const __global uint8_t *hm = x[i].hmask;
  201. for (int l = l0; l < l0 + 4; ++l)
  202. y[l] = dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4));
  203. }
  204. __kernel void dequantize_block_q4_K(__global const struct block_q4_K *x, __global float *yy)
  205. {
  206. const int i = get_group_id(0) + get_global_offset(0);
  207. const int tid = get_local_id(0);
  208. const int il = tid / 8;
  209. const int ir = tid % 8;
  210. const int is = 2 * il;
  211. const int n = 4;
  212. __global float *y = yy + get_group_id(0) * QK_K + 64 * il + n * ir;
  213. const float dall = vload_half(0, &x[i].d);
  214. const float dmin = vload_half(0, &x[i].dmin);
  215. __global const uint8_t *q = x[i].qs + 32 * il + n * ir;
  216. uint8_t sc, m;
  217. get_scale_min_k4(is + 0, x[i].scales, &sc, &m);
  218. float d1 = dall * sc;
  219. float m1 = dmin * m;
  220. get_scale_min_k4(is + 1, x[i].scales, &sc, &m);
  221. float d2 = dall * sc;
  222. float m2 = dmin * m;
  223. for (int l = 0; l < n; ++l)
  224. {
  225. y[l + 0] = d1 * (q[l] & 0xF) - m1;
  226. y[l + 32] = d2 * (q[l] >> 4) - m2;
  227. }
  228. }
  229. __kernel void dequantize_block_q5_K(__global const struct block_q5_K *x, __global float *yy)
  230. {
  231. const int i = get_group_id(0) + get_global_offset(0);
  232. const int tid = get_local_id(0);
  233. const int il = tid / 16;
  234. const int ir = tid % 16;
  235. const int is = 2 * il;
  236. __global float *y = yy + get_group_id(0) * QK_K + 64 * il + 2 * ir;
  237. const float dall = vload_half(0, &x[i].d);
  238. const float dmin = vload_half(0, &x[i].dmin);
  239. __global const uint8_t *ql = x[i].qs + 32 * il + 2 * ir;
  240. __global const uint8_t *qh = x[i].qh + 2 * ir;
  241. uint8_t sc, m;
  242. get_scale_min_k4(is + 0, x[i].scales, &sc, &m);
  243. const float d1 = dall * sc;
  244. const float m1 = dmin * m;
  245. get_scale_min_k4(is + 1, x[i].scales, &sc, &m);
  246. const float d2 = dall * sc;
  247. const float m2 = dmin * m;
  248. uint8_t hm = 1 << (2 * il);
  249. y[0] = d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1;
  250. y[1] = d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1;
  251. hm <<= 1;
  252. y[32] = d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2;
  253. y[33] = d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2;
  254. }
  255. __kernel void dequantize_block_q6_K(__global const struct block_q6_K *x, __global float *yy)
  256. {
  257. const int i = get_group_id(0) + get_global_offset(0);
  258. const int tid = get_local_id(0);
  259. const int ip = tid / 32;
  260. const int il = tid - 32 * ip;
  261. const int is = 8 * ip + il / 16;
  262. __global float *y = yy + get_group_id(0) * QK_K + 128 * ip + il;
  263. const float d = vload_half(0, &x[i].d);
  264. __global const uint8_t *ql = x[i].ql + 64 * ip + il;
  265. const uint8_t qh = x[i].qh[32 * ip + il];
  266. __global const int8_t *sc = x[i].scales + is;
  267. y[0] = d * sc[0] * ((int8_t)((ql[0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32);
  268. y[32] = d * sc[2] * ((int8_t)((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32);
  269. y[64] = d * sc[4] * ((int8_t)((ql[0] >> 4) | (((qh >> 4) & 3) << 4)) - 32);
  270. y[96] = d * sc[6] * ((int8_t)((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32);
  271. }
  272. __kernel void dequantize_mul_mat_vec_q2_K(__global const struct block_q2_K * xx, __local float* tmp, __global float* yy, __global float* dst, const int ncols) {
  273. const int row = get_group_id(0);
  274. const int num_blocks_per_row = ncols / QK_K;
  275. const int ib0 = row*num_blocks_per_row + get_global_offset(0);
  276. __global const struct block_q2_K * x = xx + ib0;
  277. const int tid = get_local_id(0)/K_QUANTS_PER_ITERATION; // 0...31 or 0...15
  278. const int ix = get_local_id(0)%K_QUANTS_PER_ITERATION; // 0 or 0,1
  279. const int step = 16/K_QUANTS_PER_ITERATION;
  280. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  281. const int in = tid - step*im; // 0...15 or 0...7
  282. const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15 or 0...14 in steps of 2
  283. const int q_offset = 32*im + l0;
  284. const int s_offset = 8*im;
  285. const int y_offset = 128*im + l0;
  286. tmp[16 * ix + tid] = 0;
  287. uint32_t aux[4];
  288. const uint8_t * d = (const uint8_t *)aux;
  289. const uint8_t * m = (const uint8_t *)(aux + 2);
  290. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  291. __global const float * y = yy + i * QK_K + y_offset;
  292. __global const uint8_t * q = x[i].qs + q_offset;
  293. const float dall = vload_half(0, &x[i].d);
  294. const float dmin = vload_half(0, &x[i].dmin);
  295. __global const uint32_t * a = (__global const uint32_t *)(x[i].scales + s_offset);
  296. aux[0] = a[0] & 0x0f0f0f0f;
  297. aux[1] = a[1] & 0x0f0f0f0f;
  298. aux[2] = (a[0] >> 4) & 0x0f0f0f0f;
  299. aux[3] = (a[1] >> 4) & 0x0f0f0f0f;
  300. float sum1 = 0, sum2 = 0;
  301. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  302. sum1 += y[l+ 0] * d[0] * ((q[l+ 0] >> 0) & 3)
  303. + y[l+32] * d[2] * ((q[l+ 0] >> 2) & 3)
  304. + y[l+64] * d[4] * ((q[l+ 0] >> 4) & 3)
  305. + y[l+96] * d[6] * ((q[l+ 0] >> 6) & 3)
  306. + y[l+16] * d[1] * ((q[l+16] >> 0) & 3)
  307. + y[l+48] * d[3] * ((q[l+16] >> 2) & 3)
  308. + y[l+80] * d[5] * ((q[l+16] >> 4) & 3)
  309. +y[l+112] * d[7] * ((q[l+16] >> 6) & 3);
  310. sum2 += y[l+ 0] * m[0] + y[l+32] * m[2] + y[l+64] * m[4] + y[ l+96] * m[6]
  311. + y[l+16] * m[1] + y[l+48] * m[3] + y[l+80] * m[5] + y[l+112] * m[7];
  312. }
  313. tmp[16 * ix + tid] += dall * sum1 - dmin * sum2;
  314. }
  315. // sum up partial sums and write back result
  316. barrier(CLK_LOCAL_MEM_FENCE);
  317. for (int s=16; s>0; s>>=1) {
  318. if (tid < s) {
  319. tmp[tid] += tmp[tid + s];
  320. }
  321. barrier(CLK_LOCAL_MEM_FENCE);
  322. }
  323. if (tid == 0) {
  324. dst[row] = tmp[0];
  325. }
  326. }
  327. __kernel void dequantize_mul_mat_vec_q3_K(__global const struct block_q3_K * xx, __local float* tmp, __global float* yy, __global float* dst, const int ncols) {
  328. const uint16_t kmask1 = 0x0303;
  329. const uint16_t kmask2 = 0x0f0f;
  330. const int row = get_group_id(0);
  331. const int num_blocks_per_row = ncols / QK_K;
  332. const int ib0 = row*num_blocks_per_row + get_global_offset(0);
  333. __global const struct block_q3_K * x = xx + ib0;
  334. const int tid = get_local_id(0)/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  335. const int ix = get_local_id(0)%K_QUANTS_PER_ITERATION; // 0 or 0,1
  336. const int n = K_QUANTS_PER_ITERATION; // iterations in the inner loop
  337. const int step = 16/K_QUANTS_PER_ITERATION;
  338. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  339. const int in = tid - step*im; // 0....15 or 0...7
  340. const uint8_t m = 1 << (4*im);
  341. const int l0 = n*in; // 0...15 or 0...14 in steps of 2
  342. const int q_offset = 32*im + l0;
  343. const int y_offset = 128*im + l0;
  344. uint16_t utmp[4];
  345. const int8_t * s = (const int8_t *)utmp;
  346. const uint16_t s_shift = 4*im;
  347. tmp[16 * ix + tid] = 0;
  348. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  349. __global const float * y = yy + i * QK_K + y_offset;
  350. __global const uint8_t * q = x[i].qs + q_offset;
  351. __global const uint8_t * h = x[i].hmask + l0;
  352. __global const uint16_t * a = (__global const uint16_t *)x[i].scales;
  353. utmp[0] = ((a[0] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 0)) & kmask1) << 4);
  354. utmp[1] = ((a[1] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 0)) & kmask1) << 4);
  355. utmp[2] = ((a[2] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 2)) & kmask1) << 4);
  356. utmp[3] = ((a[3] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 2)) & kmask1) << 4);
  357. const float d = vload_half(0, &x[i].d);
  358. float sum = 0;
  359. for (int l = 0; l < n; ++l) {
  360. sum += y[l+ 0] * (s[0] - 32) * (((q[l] >> 0) & 3) - (h[l] & (m << 0) ? 0 : 4))
  361. + y[l+32] * (s[2] - 32) * (((q[l] >> 2) & 3) - (h[l] & (m << 1) ? 0 : 4))
  362. + y[l+64] * (s[4] - 32) * (((q[l] >> 4) & 3) - (h[l] & (m << 2) ? 0 : 4))
  363. + y[l+96] * (s[6] - 32) * (((q[l] >> 6) & 3) - (h[l] & (m << 3) ? 0 : 4));
  364. sum += y[l+16] * (s[1] - 32) * (((q[l+16] >> 0) & 3) - (h[l+16] & (m << 0) ? 0 : 4))
  365. + y[l+48] * (s[3] - 32) * (((q[l+16] >> 2) & 3) - (h[l+16] & (m << 1) ? 0 : 4))
  366. + y[l+80] * (s[5] - 32) * (((q[l+16] >> 4) & 3) - (h[l+16] & (m << 2) ? 0 : 4))
  367. + y[l+112] * (s[7] - 32) * (((q[l+16] >> 6) & 3) - (h[l+16] & (m << 3) ? 0 : 4));
  368. }
  369. tmp[16 * ix + tid] += d * sum;
  370. }
  371. // sum up partial sums and write back result
  372. barrier(CLK_LOCAL_MEM_FENCE);
  373. for (int s=16; s>0; s>>=1) {
  374. if (tid < s) {
  375. tmp[tid] += tmp[tid + s];
  376. }
  377. barrier(CLK_LOCAL_MEM_FENCE);
  378. }
  379. if (tid == 0) {
  380. dst[row] = tmp[0];
  381. }
  382. }
  383. __kernel void dequantize_mul_mat_vec_q4_K(__global const struct block_q4_K * xx, __local float* tmp, __global float* yy, __global float* dst, const int ncols) {
  384. //to rename it later, just to test now
  385. const uint16_t kmask1 = 0x3f3f;
  386. const uint16_t kmask2 = 0x0f0f;
  387. const uint16_t kmask3 = 0xc0c0;
  388. const int row = get_group_id(0);
  389. const int num_blocks_per_row = ncols / QK_K;
  390. const int ib0 = row*num_blocks_per_row + get_global_offset(0);
  391. const int tid = get_local_id(0)/K_QUANTS_PER_ITERATION; // 0...15
  392. const int ix = get_local_id(0)%K_QUANTS_PER_ITERATION;
  393. const int step = 8/K_QUANTS_PER_ITERATION;
  394. const int il = tid/step; // 0...3
  395. const int ir = tid - step*il;// 0...3
  396. const int n = 2*K_QUANTS_PER_ITERATION;
  397. const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  398. const int in = il%2;
  399. const int l0 = n*(2*ir + in);
  400. const int q_offset = 32*im + l0;
  401. const int y_offset = 64*im + l0;
  402. uint16_t aux[4];
  403. const uint8_t * sc = (const uint8_t *)aux;
  404. __global const struct block_q4_K * x = xx + ib0;
  405. tmp[16 * ix + tid] = 0;
  406. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  407. __global const uint8_t * q1 = x[i].qs + q_offset;
  408. __global const uint8_t * q2 = q1 + 64;
  409. __global const float * y1 = yy + i*QK_K + y_offset;
  410. __global const float * y2 = y1 + 128;
  411. const float dall = vload_half(0, &x[i].d);
  412. const float dmin = vload_half(0, &x[i].dmin);
  413. __global const uint16_t * a = (__global const uint16_t *)x[i].scales;
  414. aux[0] = a[im+0] & kmask1;
  415. aux[1] = a[im+2] & kmask1;
  416. aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2);
  417. aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2);
  418. float4 s = (float4)(0.f);
  419. float smin = 0;
  420. for (int l = 0; l < n; ++l) {
  421. s.x += y1[l] * (q1[l] & 0xF); s.y += y1[l+32] * (q1[l] >> 4);
  422. s.z += y2[l] * (q2[l] & 0xF); s.w += y2[l+32] * (q2[l] >> 4);
  423. smin += y1[l] * sc[2] + y1[l+32] * sc[3] + y2[l] * sc[6] + y2[l+32] * sc[7];
  424. }
  425. tmp[16 * ix + tid] += dall * (s.x * sc[0] + s.y * sc[1] + s.z * sc[4] + s.w * sc[5]) - dmin * smin;
  426. }
  427. // sum up partial sums and write back result
  428. barrier(CLK_LOCAL_MEM_FENCE);
  429. for (int s=16; s>0; s>>=1) {
  430. if (tid < s) {
  431. tmp[tid] += tmp[tid + s];
  432. }
  433. barrier(CLK_LOCAL_MEM_FENCE);
  434. }
  435. if (tid == 0) {
  436. dst[row] = tmp[0];
  437. }
  438. }
  439. __kernel void dequantize_mul_mat_vec_q5_K(__global const struct block_q5_K * xx, __local float* tmp, __global float* yy, __global float* dst, const int ncols) {
  440. const uint16_t kmask1 = 0x3f3f;
  441. const uint16_t kmask2 = 0x0f0f;
  442. const uint16_t kmask3 = 0xc0c0;
  443. const int row = get_group_id(0);
  444. const int num_blocks_per_row = ncols / QK_K;
  445. const int ib0 = row*num_blocks_per_row + get_global_offset(0);
  446. const int tid = get_local_id(0)/2; // 0...15
  447. const int ix = get_local_id(0)%2;
  448. const int il = tid/4; // 0...3
  449. const int ir = tid - 4*il;// 0...3
  450. const int n = 2;
  451. const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  452. const int in = il%2;
  453. const int l0 = n*(2*ir + in);
  454. const int q_offset = 32*im + l0;
  455. const int y_offset = 64*im + l0;
  456. const uint8_t hm1 = 1 << (2*im);
  457. const uint8_t hm2 = hm1 << 4;
  458. uint16_t aux[4];
  459. const uint8_t * sc = (const uint8_t *)aux;
  460. __global const struct block_q5_K * x = xx + ib0;
  461. tmp[16 * ix + tid] = 0;
  462. for (int i = ix; i < num_blocks_per_row; i += 2) {
  463. __global const uint8_t * ql1 = x[i].qs + q_offset;
  464. __global const uint8_t * ql2 = ql1 + 64;
  465. __global const uint8_t * qh = x[i].qh + l0;
  466. __global const float * y1 = yy + i*QK_K + y_offset;
  467. __global const float * y2 = y1 + 128;
  468. const float dall = vload_half(0, &x[i].d);
  469. const float dmin = vload_half(0, &x[i].dmin);
  470. __global const uint16_t * a = (__global const uint16_t *)x[i].scales;
  471. aux[0] = a[im+0] & kmask1;
  472. aux[1] = a[im+2] & kmask1;
  473. aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2);
  474. aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2);
  475. float4 sum = (float4)(0.f);
  476. float smin = 0;
  477. for (int l = 0; l < n; ++l) {
  478. sum.x += y1[l+ 0] * ((ql1[l+ 0] & 0xF) + (qh[l+ 0] & (hm1 << 0) ? 16 : 0))
  479. + y1[l+16] * ((ql1[l+16] & 0xF) + (qh[l+16] & (hm1 << 0) ? 16 : 0));
  480. sum.y += y1[l+32] * ((ql1[l+ 0] >> 4) + (qh[l+ 0] & (hm1 << 1) ? 16 : 0))
  481. + y1[l+48] * ((ql1[l+16] >> 4) + (qh[l+16] & (hm1 << 1) ? 16 : 0));
  482. sum.z += y2[l+ 0] * ((ql2[l+ 0] & 0xF) + (qh[l+ 0] & (hm2 << 0) ? 16 : 0))
  483. + y2[l+16] * ((ql2[l+16] & 0xF) + (qh[l+16] & (hm2 << 0) ? 16 : 0));
  484. sum.w += y2[l+32] * ((ql2[l+ 0] >> 4) + (qh[l+ 0] & (hm2 << 1) ? 16 : 0))
  485. + y2[l+48] * ((ql2[l+16] >> 4) + (qh[l+16] & (hm2 << 1) ? 16 : 0));
  486. smin += (y1[l] + y1[l+16]) * sc[2] + (y1[l+32] + y1[l+48]) * sc[3]
  487. + (y2[l] + y2[l+16]) * sc[6] + (y2[l+32] + y2[l+48]) * sc[7];
  488. }
  489. tmp[16 * ix + tid] += dall * (sum.x * sc[0] + sum.y * sc[1] + sum.z * sc[4] + sum.w * sc[5]) - dmin * smin;
  490. }
  491. // sum up partial sums and write back result
  492. barrier(CLK_LOCAL_MEM_FENCE);
  493. for (int s=16; s>0; s>>=1) {
  494. if (tid < s) {
  495. tmp[tid] += tmp[tid + s];
  496. }
  497. barrier(CLK_LOCAL_MEM_FENCE);
  498. }
  499. if (tid == 0) {
  500. dst[row] = tmp[0];
  501. }
  502. }
  503. __kernel void dequantize_mul_mat_vec_q6_K(__global const struct block_q6_K * xx, __local float* tmp, __global const float * yy, __global float * dst, const int ncols) {
  504. const int row = get_group_id(0);
  505. const int num_blocks_per_row = ncols / QK_K;
  506. const int ib0 = row*num_blocks_per_row + get_global_offset(0);
  507. __global const struct block_q6_K * x = xx + ib0;
  508. const int tid = get_local_id(0)/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  509. const int ix = get_local_id(0)%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  510. const int step = 16/K_QUANTS_PER_ITERATION; // 16 or 8
  511. const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  512. const int in = tid - step*im; // 0...15 or 0...7
  513. \n#if K_QUANTS_PER_ITERATION == 1\n
  514. const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15
  515. const int is = 0;
  516. \n#else\n
  517. const int l0 = 4 * in; // 0, 4, 8, ..., 28
  518. const int is = in / 4;
  519. \n#endif\n
  520. const int ql_offset = 64*im + l0;
  521. const int qh_offset = 32*im + l0;
  522. const int s_offset = 8*im + is;
  523. const int y_offset = 128*im + l0;
  524. tmp[16 * ix + tid] = 0; // partial sum for thread in warp
  525. for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  526. __global const float * y = yy + i * QK_K + y_offset;
  527. __global const uint8_t * ql = x[i].ql + ql_offset;
  528. __global const uint8_t * qh = x[i].qh + qh_offset;
  529. __global const int8_t * s = x[i].scales + s_offset;
  530. const float d = vload_half(0, &x[i].d);
  531. \n#if K_QUANTS_PER_ITERATION == 1\n
  532. float sum = y[ 0] * s[0] * d * ((int8_t)((ql[ 0] & 0xF) | ((qh[ 0] & 0x03) << 4)) - 32)
  533. + y[16] * s[1] * d * ((int8_t)((ql[16] & 0xF) | ((qh[16] & 0x03) << 4)) - 32)
  534. + y[32] * s[2] * d * ((int8_t)((ql[32] & 0xF) | ((qh[ 0] & 0x0c) << 2)) - 32)
  535. + y[48] * s[3] * d * ((int8_t)((ql[48] & 0xF) | ((qh[16] & 0x0c) << 2)) - 32)
  536. + y[64] * s[4] * d * ((int8_t)((ql[ 0] >> 4) | ((qh[ 0] & 0x30) >> 0)) - 32)
  537. + y[80] * s[5] * d * ((int8_t)((ql[16] >> 4) | ((qh[16] & 0x30) >> 0)) - 32)
  538. + y[96] * s[6] * d * ((int8_t)((ql[32] >> 4) | ((qh[ 0] & 0xc0) >> 2)) - 32)
  539. +y[112] * s[7] * d * ((int8_t)((ql[48] >> 4) | ((qh[16] & 0xc0) >> 2)) - 32);
  540. tmp[16 * ix + tid] += sum;
  541. \n#else\n
  542. float sum = 0;
  543. for (int l = 0; l < 4; ++l) {
  544. sum += y[l+ 0] * s[0] * d * ((int8_t)((ql[l+ 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32)
  545. + y[l+32] * s[2] * d * ((int8_t)((ql[l+32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32)
  546. + y[l+64] * s[4] * d * ((int8_t)((ql[l+ 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32)
  547. + y[l+96] * s[6] * d * ((int8_t)((ql[l+32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32);
  548. }
  549. tmp[16 * ix + tid] += sum;
  550. \n#endif\n
  551. }
  552. // sum up partial sums and write back result
  553. barrier(CLK_LOCAL_MEM_FENCE);
  554. for (int s=16; s>0; s>>=1) {
  555. if (tid < s) {
  556. tmp[tid] += tmp[tid + s];
  557. }
  558. barrier(CLK_LOCAL_MEM_FENCE);
  559. }
  560. if (tid == 0) {
  561. dst[row] = tmp[0];
  562. }
  563. }
  564. );
  565. std::string dequant_template = MULTILINE_QUOTE(
  566. __kernel void KERNEL_NAME(__global X_TYPE* x, __global float* y) {
  567. const int i = get_group_id(0)*get_local_size(0) + get_local_id(0)*2;
  568. if (i >= get_global_size(0)) {
  569. return;
  570. }
  571. const uint qk = QUANT_K;
  572. const uint qr = QUANT_R;
  573. const int ib = i/qk + get_global_offset(0); // block index
  574. const int iqs = (i%qk)/qr; // quant index
  575. const int iybs = i - i%qk; // y block start index
  576. const int y_offset = qr == 1 ? 1 : qk/2;
  577. // dequantize
  578. float v0, v1;
  579. DEQUANT_FUNC(x, ib, iqs, &v0, &v1);
  580. y[iybs + iqs + 0] = v0;
  581. y[iybs + iqs + y_offset] = v1;
  582. }
  583. );
  584. std::string dequant_mul_mat_vec_template = MULTILINE_QUOTE(
  585. __kernel void KERNEL_NAME(__global X_TYPE* x, __local float* tmp, __global float* y, __global float* dst, const int ncols) {
  586. const int local_size = get_local_size(0);
  587. const int row = get_group_id(0);
  588. const int tid = get_local_id(0);
  589. const uint qk = QUANT_K;
  590. const uint qr = QUANT_R;
  591. const int col_step = local_size * 2;
  592. const int y_offset = qr == 1 ? 1 : qk/2;
  593. x += get_global_offset(0);
  594. tmp[tid] = 0;
  595. for (int col = tid*2; col < ncols; col += col_step) {
  596. const int ib = (row*ncols + col)/qk; // block index
  597. const int iqs = (col%qk)/qr; // quant index
  598. const int iybs = col - col%qk; // y block start index
  599. // dequantize
  600. float v0, v1;
  601. DEQUANT_FUNC(x, ib, iqs, &v0, &v1);
  602. // matrix multiplication
  603. tmp[tid] += v0 * y[iybs + iqs + 0];
  604. tmp[tid] += v1 * y[iybs + iqs + y_offset];
  605. }
  606. // sum up partial sums and write back result
  607. barrier(CLK_LOCAL_MEM_FENCE);
  608. for (int s=local_size/2; s>0; s>>=1) {
  609. if (tid < s) {
  610. tmp[tid] += tmp[tid + s];
  611. }
  612. barrier(CLK_LOCAL_MEM_FENCE);
  613. }
  614. if (tid == 0) {
  615. dst[row] = tmp[0];
  616. }
  617. }
  618. );
  619. std::string mul_template = MULTILINE_QUOTE(
  620. __kernel void KERNEL_NAME(__global TYPE* x, const int x_offset, __global TYPE* y, const int y_offset, __global TYPE* dst, const int dst_offset, const int ky) {
  621. const int i = get_group_id(0)*get_local_size(0) + get_local_id(0);
  622. if (i >= get_global_size(0)) {
  623. return;
  624. }
  625. dst[dst_offset + i] = x[x_offset + i] * y[y_offset + i%ky];
  626. }
  627. );
  628. std::string add_template = MULTILINE_QUOTE(
  629. __kernel void add_f32(__global float * x, const int x_offset, __global float * y, const int y_offset, __global float * dst, const int dst_offset, const int ky) {
  630. const int i = get_group_id(0)*get_local_size(0) + get_local_id(0);
  631. if (i >= get_global_size(0)) {
  632. return;
  633. }
  634. dst[dst_offset + i] = x[x_offset + i] + y[y_offset + i%ky];
  635. }
  636. );
  637. #define CL_CHECK(err) \
  638. do { \
  639. cl_int err_ = (err); \
  640. if (err_ != CL_SUCCESS) { \
  641. fprintf(stderr, "ggml_opencl: %s error %d at %s:%d\n", \
  642. #err, err_, __FILE__, __LINE__); \
  643. exit(1); \
  644. } \
  645. } while (0)
  646. #define CLBLAST_CHECK(err) \
  647. do { \
  648. CLBlastStatusCode err_ = (err); \
  649. if (err_ != CLBlastSuccess) { \
  650. fprintf(stderr, "ggml_opencl: %s error %d at %s:%d\n", \
  651. #err, err_, __FILE__, __LINE__); \
  652. exit(1); \
  653. } \
  654. } while (0)
  655. std::array<std::string, 5> dequant_str_keys = {
  656. "KERNEL_NAME", "X_TYPE", "QUANT_K", "QUANT_R", "DEQUANT_FUNC"
  657. };
  658. std::array<std::string, 30> dequant_str_values = {
  659. "dequantize_row_q4_0", "struct block_q4_0", "QK4_0", "QR4_0", "dequantize_q4_0",
  660. "dequantize_row_q4_1", "struct block_q4_1", "QK4_1", "QR4_1", "dequantize_q4_1",
  661. "dequantize_row_q5_0", "struct block_q5_0", "QK5_0", "QR5_0", "dequantize_q5_0",
  662. "dequantize_row_q5_1", "struct block_q5_1", "QK5_1", "QR5_1", "dequantize_q5_1",
  663. "dequantize_row_q8_0", "struct block_q8_0", "QK8_0", "QR8_0", "dequantize_q8_0",
  664. "convert_row_f16", "half", "1", "1", "convert_f16"
  665. };
  666. std::array<std::string, 30> dequant_mul_mat_vec_str_values = {
  667. "dequantize_mul_mat_vec_q4_0", "struct block_q4_0", "QK4_0", "QR4_0", "dequantize_q4_0",
  668. "dequantize_mul_mat_vec_q4_1", "struct block_q4_1", "QK4_1", "QR4_1", "dequantize_q4_1",
  669. "dequantize_mul_mat_vec_q5_0", "struct block_q5_0", "QK5_0", "QR5_0", "dequantize_q5_0",
  670. "dequantize_mul_mat_vec_q5_1", "struct block_q5_1", "QK5_1", "QR5_1", "dequantize_q5_1",
  671. "dequantize_mul_mat_vec_q8_0", "struct block_q8_0", "QK8_0", "QR8_0", "dequantize_q8_0",
  672. "convert_mul_mat_vec_f16", "half", "1", "1", "convert_f16"
  673. };
  674. std::array<std::string, 2> mul_str_keys = {
  675. "KERNEL_NAME", "TYPE"
  676. };
  677. std::array<std::string, 2> mul_str_values = {
  678. "mul_f32", "float"
  679. };
  680. static std::string& replace(std::string& s, const std::string& from, const std::string& to) {
  681. size_t pos = 0;
  682. while ((pos = s.find(from, pos)) != std::string::npos) {
  683. s.replace(pos, from.length(), to);
  684. pos += to.length();
  685. }
  686. return s;
  687. }
  688. static std::string generate_kernels() {
  689. std::stringstream src;
  690. src << program_source << '\n';
  691. src << k_quants_source << '\n';
  692. for (size_t i = 0; i < dequant_str_values.size(); i += dequant_str_keys.size()) {
  693. std::string dequant_kernel = dequant_template;
  694. std::string dmmv_kernel = dequant_mul_mat_vec_template;
  695. for (size_t j = 0; j < dequant_str_keys.size(); j++) {
  696. replace(dequant_kernel, dequant_str_keys[j], dequant_str_values[i + j]);
  697. replace(dmmv_kernel, dequant_str_keys[j], dequant_mul_mat_vec_str_values[i + j]);
  698. }
  699. src << dequant_kernel << '\n';
  700. src << dmmv_kernel << '\n';
  701. }
  702. for (size_t i = 0; i < mul_str_values.size(); i += mul_str_keys.size()) {
  703. std::string mul_kernel = mul_template;
  704. for (size_t j = 0; j < mul_str_keys.size(); j++) {
  705. replace(mul_kernel, mul_str_keys[j], mul_str_values[i + j]);
  706. }
  707. src << mul_kernel << '\n';
  708. }
  709. src << add_template << '\n';
  710. return src.str();
  711. }
  712. static cl_platform_id platform;
  713. static cl_device_id device;
  714. static cl_context context;
  715. static cl_command_queue queue;
  716. static cl_program program;
  717. static cl_kernel convert_row_f16_cl;
  718. static cl_kernel dequantize_row_q4_0_cl, dequantize_row_q4_1_cl, dequantize_row_q5_0_cl, dequantize_row_q5_1_cl, dequantize_row_q8_0_cl;
  719. static cl_kernel dequantize_mul_mat_vec_q4_0_cl, dequantize_mul_mat_vec_q4_1_cl, dequantize_mul_mat_vec_q5_0_cl, dequantize_mul_mat_vec_q5_1_cl, dequantize_mul_mat_vec_q8_0_cl, convert_mul_mat_vec_f16_cl;
  720. static cl_kernel dequantize_block_q2_k_cl, dequantize_block_q3_k_cl, dequantize_block_q4_k_cl, dequantize_block_q5_k_cl, dequantize_block_q6_k_cl;
  721. static cl_kernel dequantize_mul_mat_vec_q2_K_cl, dequantize_mul_mat_vec_q3_K_cl, dequantize_mul_mat_vec_q4_K_cl, dequantize_mul_mat_vec_q5_K_cl, dequantize_mul_mat_vec_q6_K_cl;
  722. static cl_kernel mul_f32_cl;
  723. static cl_kernel add_f32_cl;
  724. static bool fp16_support;
  725. static cl_program build_program_from_source(cl_context ctx, cl_device_id dev, const char* program_buffer) {
  726. cl_program p;
  727. char *program_log;
  728. size_t program_size;
  729. size_t log_size;
  730. int err;
  731. program_size = strlen(program_buffer);
  732. p = clCreateProgramWithSource(ctx, 1, (const char**)&program_buffer, &program_size, &err);
  733. if(err < 0) {
  734. fprintf(stderr, "OpenCL error creating program");
  735. exit(1);
  736. }
  737. std::string compile_opts = "-cl-mad-enable -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math "
  738. "-DQK4_0=32 -DQR4_0=2 -DQK4_1=32 -DQR4_1=2 -DQK5_0=32 -DQR5_0=2 -DQK5_1=32 -DQR5_1=2 -DQK8_0=32 -DQR8_0=1 "
  739. "-DQK_K=256 -DK_QUANTS_PER_ITERATION=" + std::to_string(K_QUANTS_PER_ITERATION);
  740. err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL);
  741. if(err < 0) {
  742. clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
  743. program_log = (char*) malloc(log_size + 1);
  744. program_log[log_size] = '\0';
  745. clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL);
  746. fprintf(stderr, "ggml_opencl: kernel compile error:\n\n%s\n", program_log);
  747. free(program_log);
  748. exit(1);
  749. }
  750. return p;
  751. }
  752. void ggml_cl_init(void) {
  753. static bool initialized = false;
  754. if (initialized) {
  755. return;
  756. }
  757. initialized = true;
  758. cl_int err;
  759. struct cl_device;
  760. struct cl_platform {
  761. cl_platform_id id;
  762. unsigned number;
  763. char name[128];
  764. char vendor[128];
  765. struct cl_device * devices;
  766. unsigned n_devices;
  767. struct cl_device * default_device;
  768. };
  769. struct cl_device {
  770. struct cl_platform * platform;
  771. cl_device_id id;
  772. unsigned number;
  773. cl_device_type type;
  774. char name[128];
  775. };
  776. enum { NPLAT = 16, NDEV = 16 };
  777. struct cl_platform platforms[NPLAT];
  778. unsigned n_platforms = 0;
  779. struct cl_device devices[NDEV];
  780. unsigned n_devices = 0;
  781. struct cl_device * default_device = NULL;
  782. platform = NULL;
  783. device = NULL;
  784. cl_platform_id platform_ids[NPLAT];
  785. CL_CHECK(clGetPlatformIDs(NPLAT, platform_ids, &n_platforms));
  786. for (unsigned i = 0; i < n_platforms; i++) {
  787. struct cl_platform * p = &platforms[i];
  788. p->number = i;
  789. p->id = platform_ids[i];
  790. CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_NAME, sizeof(p->name), &p->name, NULL));
  791. CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_VENDOR, sizeof(p->vendor), &p->vendor, NULL));
  792. cl_device_id device_ids[NDEV];
  793. cl_int clGetDeviceIDsError = clGetDeviceIDs(p->id, CL_DEVICE_TYPE_ALL, NDEV, device_ids, &p->n_devices);
  794. if (clGetDeviceIDsError == CL_DEVICE_NOT_FOUND) {
  795. p->n_devices = 0;
  796. } else {
  797. CL_CHECK(clGetDeviceIDsError);
  798. }
  799. p->devices = p->n_devices > 0 ? &devices[n_devices] : NULL;
  800. p->default_device = NULL;
  801. for (unsigned j = 0; j < p->n_devices; j++) {
  802. struct cl_device * d = &devices[n_devices];
  803. d->number = n_devices++;
  804. d->id = device_ids[j];
  805. d->platform = p;
  806. CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_NAME, sizeof(d->name), &d->name, NULL));
  807. CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_TYPE, sizeof(d->type), &d->type, NULL));
  808. if (p->default_device == NULL && d->type == CL_DEVICE_TYPE_GPU) {
  809. p->default_device = d;
  810. }
  811. }
  812. if (default_device == NULL && p->default_device != NULL) {
  813. default_device = p->default_device;
  814. }
  815. }
  816. if (n_devices == 0) {
  817. fprintf(stderr, "ggml_opencl: could find any OpenCL devices.\n");
  818. exit(1);
  819. }
  820. char * user_platform_string = getenv("GGML_OPENCL_PLATFORM");
  821. char * user_device_string = getenv("GGML_OPENCL_DEVICE");
  822. int user_platform_number = -1;
  823. int user_device_number = -1;
  824. unsigned n;
  825. if (user_platform_string != NULL && sscanf(user_platform_string, " %u", &n) == 1 && n < n_platforms) {
  826. user_platform_number = (int)n;
  827. }
  828. if (user_device_string != NULL && sscanf(user_device_string, " %u", &n) == 1 && n < n_devices) {
  829. user_device_number = (int)n;
  830. }
  831. if (user_platform_number != -1 && user_device_number != -1) {
  832. cl_platform* platform = &platforms[user_platform_number];
  833. if ((unsigned)user_device_number >= platform->n_devices) {
  834. fprintf(stderr, "ggml_opencl: invalid device number %d\n", user_device_number);
  835. exit(1);
  836. }
  837. default_device = &platform->devices[user_device_number];
  838. } else {
  839. struct cl_device * selected_devices = devices;
  840. unsigned n_selected_devices = n_devices;
  841. if (user_platform_number == -1 && user_platform_string != NULL && user_platform_string[0] != 0) {
  842. for (unsigned i = 0; i < n_platforms; i++) {
  843. struct cl_platform * p = &platforms[i];
  844. if (strstr(p->name, user_platform_string) != NULL ||
  845. strstr(p->vendor, user_platform_string) != NULL) {
  846. user_platform_number = (int)i;
  847. break;
  848. }
  849. }
  850. if (user_platform_number == -1) {
  851. fprintf(stderr, "ggml_opencl: no platform matching '%s' was found.\n", user_platform_string);
  852. exit(1);
  853. }
  854. }
  855. if (user_platform_number != -1) {
  856. struct cl_platform * p = &platforms[user_platform_number];
  857. selected_devices = p->devices;
  858. n_selected_devices = p->n_devices;
  859. default_device = p->default_device;
  860. if (n_selected_devices == 0) {
  861. fprintf(stderr, "ggml_opencl: selected platform '%s' does not have any devices.\n", p->name);
  862. exit(1);
  863. }
  864. }
  865. if (user_device_number == -1 && user_device_string != NULL && user_device_string[0] != 0) {
  866. for (unsigned i = 0; i < n_selected_devices; i++) {
  867. struct cl_device * d = &selected_devices[i];
  868. if (strstr(d->name, user_device_string) != NULL) {
  869. user_device_number = d->number;
  870. break;
  871. }
  872. }
  873. if (user_device_number == -1) {
  874. fprintf(stderr, "ggml_opencl: no device matching '%s' was found.\n", user_device_string);
  875. exit(1);
  876. }
  877. }
  878. if (user_device_number != -1) {
  879. selected_devices = &devices[user_device_number];
  880. n_selected_devices = 1;
  881. default_device = &selected_devices[0];
  882. }
  883. GGML_ASSERT(n_selected_devices > 0);
  884. if (default_device == NULL) {
  885. default_device = &selected_devices[0];
  886. }
  887. }
  888. fprintf(stderr, "ggml_opencl: selecting platform: '%s'\n", default_device->platform->name);
  889. fprintf(stderr, "ggml_opencl: selecting device: '%s'\n", default_device->name);
  890. if (default_device->type != CL_DEVICE_TYPE_GPU) {
  891. fprintf(stderr, "ggml_opencl: warning, not a GPU: '%s'.\n", default_device->name);
  892. }
  893. platform = default_device->platform->id;
  894. device = default_device->id;
  895. size_t ext_str_size;
  896. clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size);
  897. char *ext_buffer = (char *)alloca(ext_str_size + 1);
  898. clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer, NULL);
  899. ext_buffer[ext_str_size] = '\0'; // ensure it is null terminated
  900. // Disabled due to faulty outputs
  901. // Check if ext_buffer contains cl_khr_fp16
  902. fp16_support = false; // strstr(ext_buffer, "cl_khr_fp16") != NULL;
  903. // fprintf(stderr, "ggml_opencl: device FP16 support: %s\n", fp16_support ? "true" : "false");
  904. cl_context_properties properties[] = {
  905. (intptr_t)CL_CONTEXT_PLATFORM, (intptr_t)platform, 0
  906. };
  907. CL_CHECK((context = clCreateContext(properties, 1, &device, NULL, NULL, &err), err));
  908. CL_CHECK((queue = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err),
  909. (err != CL_INVALID_QUEUE_PROPERTIES && err != CL_INVALID_VALUE ? err :
  910. (queue = clCreateCommandQueue(context, device, 0, &err), err)
  911. )));
  912. const std::string kernel_src = generate_kernels();
  913. program = build_program_from_source(context, device, kernel_src.c_str());
  914. // FP16 to FP32 kernel
  915. CL_CHECK((convert_row_f16_cl = clCreateKernel(program, "convert_row_f16", &err), err));
  916. // Dequantize kernels
  917. CL_CHECK((dequantize_row_q4_0_cl = clCreateKernel(program, "dequantize_row_q4_0", &err), err));
  918. CL_CHECK((dequantize_row_q4_1_cl = clCreateKernel(program, "dequantize_row_q4_1", &err), err));
  919. CL_CHECK((dequantize_row_q5_0_cl = clCreateKernel(program, "dequantize_row_q5_0", &err), err));
  920. CL_CHECK((dequantize_row_q5_1_cl = clCreateKernel(program, "dequantize_row_q5_1", &err), err));
  921. CL_CHECK((dequantize_row_q8_0_cl = clCreateKernel(program, "dequantize_row_q8_0", &err), err));
  922. CL_CHECK((dequantize_row_q8_0_cl = clCreateKernel(program, "dequantize_row_q8_0", &err), err));
  923. CL_CHECK((dequantize_block_q2_k_cl = clCreateKernel(program, "dequantize_block_q2_K", &err), err));
  924. CL_CHECK((dequantize_block_q3_k_cl = clCreateKernel(program, "dequantize_block_q3_K", &err), err));
  925. CL_CHECK((dequantize_block_q4_k_cl = clCreateKernel(program, "dequantize_block_q4_K", &err), err));
  926. CL_CHECK((dequantize_block_q5_k_cl = clCreateKernel(program, "dequantize_block_q5_K", &err), err));
  927. CL_CHECK((dequantize_block_q6_k_cl = clCreateKernel(program, "dequantize_block_q6_K", &err), err));
  928. // dequant mul mat kernel
  929. CL_CHECK((dequantize_mul_mat_vec_q4_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_0", &err), err));
  930. CL_CHECK((dequantize_mul_mat_vec_q4_1_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_1", &err), err));
  931. CL_CHECK((dequantize_mul_mat_vec_q5_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_0", &err), err));
  932. CL_CHECK((dequantize_mul_mat_vec_q5_1_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_1", &err), err));
  933. CL_CHECK((dequantize_mul_mat_vec_q8_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q8_0", &err), err));
  934. CL_CHECK((convert_mul_mat_vec_f16_cl = clCreateKernel(program, "convert_mul_mat_vec_f16", &err), err));
  935. CL_CHECK((dequantize_mul_mat_vec_q2_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q2_K", &err), err));
  936. CL_CHECK((dequantize_mul_mat_vec_q3_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q3_K", &err), err));
  937. CL_CHECK((dequantize_mul_mat_vec_q4_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_K", &err), err));
  938. CL_CHECK((dequantize_mul_mat_vec_q5_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_K", &err), err));
  939. CL_CHECK((dequantize_mul_mat_vec_q6_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q6_K", &err), err));
  940. // mul kernel
  941. CL_CHECK((mul_f32_cl = clCreateKernel(program, "mul_f32", &err), err));
  942. CL_CHECK((add_f32_cl = clCreateKernel(program, "add_f32", &err), err));
  943. }
  944. static cl_kernel* ggml_get_to_fp32_cl(ggml_type type) {
  945. switch (type) {
  946. case GGML_TYPE_Q4_0:
  947. return &dequantize_row_q4_0_cl;
  948. case GGML_TYPE_Q4_1:
  949. return &dequantize_row_q4_1_cl;
  950. case GGML_TYPE_Q5_0:
  951. return &dequantize_row_q5_0_cl;
  952. case GGML_TYPE_Q5_1:
  953. return &dequantize_row_q5_1_cl;
  954. case GGML_TYPE_Q8_0:
  955. return &dequantize_row_q8_0_cl;
  956. case GGML_TYPE_Q2_K:
  957. return &dequantize_block_q2_k_cl;
  958. case GGML_TYPE_Q3_K:
  959. return &dequantize_block_q3_k_cl;
  960. case GGML_TYPE_Q4_K:
  961. return &dequantize_block_q4_k_cl;
  962. case GGML_TYPE_Q5_K:
  963. return &dequantize_block_q5_k_cl;
  964. case GGML_TYPE_Q6_K:
  965. return &dequantize_block_q6_k_cl;
  966. case GGML_TYPE_F16:
  967. return &convert_row_f16_cl;
  968. default:
  969. return nullptr;
  970. }
  971. }
  972. static size_t ggml_cl_global_denom(ggml_type type) {
  973. switch (type) {
  974. case GGML_TYPE_Q4_0:
  975. case GGML_TYPE_Q4_1:
  976. case GGML_TYPE_Q5_0:
  977. case GGML_TYPE_Q5_1:
  978. case GGML_TYPE_Q8_0:
  979. return 1;
  980. case GGML_TYPE_Q2_K:
  981. case GGML_TYPE_Q3_K:
  982. return 4;
  983. case GGML_TYPE_Q4_K:
  984. return 8;
  985. case GGML_TYPE_Q5_K:
  986. case GGML_TYPE_Q6_K:
  987. return 4;
  988. case GGML_TYPE_F16:
  989. default:
  990. return 1;
  991. }
  992. }
  993. static size_t ggml_cl_local_size(ggml_type type) {
  994. switch (type) {
  995. case GGML_TYPE_Q4_0:
  996. case GGML_TYPE_Q4_1:
  997. case GGML_TYPE_Q5_0:
  998. case GGML_TYPE_Q5_1:
  999. case GGML_TYPE_Q8_0:
  1000. return 0;
  1001. case GGML_TYPE_Q2_K:
  1002. case GGML_TYPE_Q3_K:
  1003. return 64;
  1004. case GGML_TYPE_Q4_K:
  1005. return 32;
  1006. case GGML_TYPE_Q5_K:
  1007. case GGML_TYPE_Q6_K:
  1008. return 64;
  1009. case GGML_TYPE_F16:
  1010. default:
  1011. return 0;
  1012. }
  1013. }
  1014. static cl_kernel* ggml_get_dequantize_mul_mat_vec_cl(ggml_type type) {
  1015. switch (type) {
  1016. case GGML_TYPE_Q4_0:
  1017. return &dequantize_mul_mat_vec_q4_0_cl;
  1018. case GGML_TYPE_Q4_1:
  1019. return &dequantize_mul_mat_vec_q4_1_cl;
  1020. case GGML_TYPE_Q5_0:
  1021. return &dequantize_mul_mat_vec_q5_0_cl;
  1022. case GGML_TYPE_Q5_1:
  1023. return &dequantize_mul_mat_vec_q5_1_cl;
  1024. case GGML_TYPE_Q8_0:
  1025. return &dequantize_mul_mat_vec_q8_0_cl;
  1026. case GGML_TYPE_F16:
  1027. return &convert_mul_mat_vec_f16_cl;
  1028. case GGML_TYPE_Q2_K:
  1029. return &dequantize_mul_mat_vec_q2_K_cl;
  1030. case GGML_TYPE_Q3_K:
  1031. return &dequantize_mul_mat_vec_q3_K_cl;
  1032. case GGML_TYPE_Q4_K:
  1033. return &dequantize_mul_mat_vec_q4_K_cl;
  1034. case GGML_TYPE_Q5_K:
  1035. return &dequantize_mul_mat_vec_q5_K_cl;
  1036. case GGML_TYPE_Q6_K:
  1037. return &dequantize_mul_mat_vec_q6_K_cl;
  1038. default:
  1039. return nullptr;
  1040. }
  1041. }
  1042. // buffer pool for cl
  1043. #define MAX_CL_BUFFERS 256
  1044. struct scoped_spin_lock {
  1045. std::atomic_flag& lock;
  1046. scoped_spin_lock(std::atomic_flag& lock) : lock(lock) {
  1047. while (lock.test_and_set(std::memory_order_acquire)) {
  1048. ; // spin
  1049. }
  1050. }
  1051. ~scoped_spin_lock() {
  1052. lock.clear(std::memory_order_release);
  1053. }
  1054. scoped_spin_lock(const scoped_spin_lock&) = delete;
  1055. scoped_spin_lock& operator=(const scoped_spin_lock&) = delete;
  1056. };
  1057. struct cl_buffer {
  1058. cl_mem mem;
  1059. size_t size = 0;
  1060. };
  1061. static cl_buffer g_cl_buffer_pool[MAX_CL_BUFFERS];
  1062. static std::atomic_flag g_cl_pool_lock = ATOMIC_FLAG_INIT;
  1063. static cl_mem ggml_cl_pool_malloc(size_t size, size_t * actual_size) {
  1064. scoped_spin_lock lock(g_cl_pool_lock);
  1065. cl_int err;
  1066. int best_i = -1;
  1067. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  1068. int worst_i = -1;
  1069. size_t worst_size = 0; //largest unused buffer seen so far
  1070. for (int i = 0; i < MAX_CL_BUFFERS; ++i) {
  1071. cl_buffer &b = g_cl_buffer_pool[i];
  1072. if (b.size > 0 && b.size >= size && b.size < best_size)
  1073. {
  1074. best_i = i;
  1075. best_size = b.size;
  1076. }
  1077. if (b.size > 0 && b.size > worst_size)
  1078. {
  1079. worst_i = i;
  1080. worst_size = b.size;
  1081. }
  1082. }
  1083. if(best_i!=-1) //found the smallest buffer that fits our needs
  1084. {
  1085. cl_buffer& b = g_cl_buffer_pool[best_i];
  1086. cl_mem mem = b.mem;
  1087. *actual_size = b.size;
  1088. b.size = 0;
  1089. return mem;
  1090. }
  1091. if(worst_i!=-1) //no buffer that fits our needs, resize largest one to save memory
  1092. {
  1093. cl_buffer& b = g_cl_buffer_pool[worst_i];
  1094. cl_mem mem = b.mem;
  1095. b.size = 0;
  1096. clReleaseMemObject(mem);
  1097. }
  1098. cl_mem mem;
  1099. CL_CHECK((mem = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err), err));
  1100. *actual_size = size;
  1101. return mem;
  1102. }
  1103. static void ggml_cl_pool_free(cl_mem mem, size_t size) {
  1104. scoped_spin_lock lock(g_cl_pool_lock);
  1105. for (int i = 0; i < MAX_CL_BUFFERS; ++i) {
  1106. cl_buffer& b = g_cl_buffer_pool[i];
  1107. if (b.size == 0) {
  1108. b.mem = mem;
  1109. b.size = size;
  1110. return;
  1111. }
  1112. }
  1113. fprintf(stderr, "WARNING: cl buffer pool full, increase MAX_CL_BUFFERS\n");
  1114. clReleaseMemObject(mem);
  1115. }
  1116. void ggml_cl_free_data(const struct ggml_tensor* tensor) {
  1117. if (tensor->backend != GGML_BACKEND_TYPE_GPU) {
  1118. return;
  1119. }
  1120. cl_mem mem = (cl_mem)tensor->extra;
  1121. clReleaseMemObject(mem);
  1122. }
  1123. static cl_int ggml_cl_h2d_tensor_2d(cl_command_queue queue, cl_mem dst, size_t offset, const struct ggml_tensor * src, uint64_t i3, uint64_t i2, cl_event* ev) {
  1124. cl_int err;
  1125. const uint64_t ne0 = src->ne[0];
  1126. const uint64_t ne1 = src->ne[1];
  1127. const uint64_t nb0 = src->nb[0];
  1128. const uint64_t nb1 = src->nb[1];
  1129. const uint64_t nb2 = src->nb[2];
  1130. const uint64_t nb3 = src->nb[3];
  1131. const enum ggml_type type = src->type;
  1132. const size_t ts = ggml_type_size(type);
  1133. const size_t bs = ggml_blck_size(type);
  1134. const uint64_t row_size = ts*ne0/bs;
  1135. const char * x = (const char *) src->data + i2*nb2 + i3*nb3;
  1136. if (nb0 == ts && nb1 == row_size) {
  1137. return clEnqueueWriteBuffer(queue, dst, CL_FALSE, offset, ne1*row_size, x, 0, NULL, ev);
  1138. }
  1139. if (nb0 == ts) {
  1140. const size_t buffer_origin[3] = { offset, 0, 0 };
  1141. const size_t host_origin[3] = { 0, 0, 0 };
  1142. const size_t region[3] = { row_size, ne1, 1 };
  1143. return clEnqueueWriteBufferRect(queue, dst, CL_FALSE, buffer_origin, host_origin, region, row_size, 0, nb1, 0, x, 0, NULL, ev);
  1144. }
  1145. std::vector<cl_event> events;
  1146. if (ev && ne1>1) events.reserve(ne1-1);
  1147. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1148. // pretend the row is a matrix with cols=1
  1149. const size_t buffer_origin[3] = { offset + i1*row_size, 0, 0 };
  1150. const size_t host_origin[3] = { 0, 0, 0 };
  1151. const size_t region[3] = { ts, ne0/bs, 1 };
  1152. // if an event is requested, make the last write wait for all previous writes to complete
  1153. if (ev && i1) {
  1154. events.push_back(*ev);
  1155. }
  1156. cl_uint nevents = i1 == ne1-1 ? events.size() : 0U;
  1157. err = clEnqueueWriteBufferRect(queue, dst, CL_FALSE, buffer_origin, host_origin, region, ts, 0, nb0, 0, x + i1*nb1, nevents, nevents ? events.data() : nullptr, ev);
  1158. if (err != CL_SUCCESS) {
  1159. for (auto event : events) {
  1160. clReleaseEvent(event);
  1161. }
  1162. return err;
  1163. }
  1164. }
  1165. for (auto event : events) {
  1166. CL_CHECK(clReleaseEvent(event));
  1167. }
  1168. return CL_SUCCESS;
  1169. }
  1170. static void ggml_cl_mul_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1171. GGML_ASSERT(src1->backend == GGML_BACKEND_TYPE_GPU);
  1172. const int64_t ne00 = src0->ne[0];
  1173. const int64_t ne01 = src0->ne[1];
  1174. const int64_t ne02 = src0->ne[2];
  1175. const int64_t ne03 = src0->ne[3];
  1176. const int64_t ne10 = src1->ne[0];
  1177. const int64_t ne11 = src1->ne[1];
  1178. const int64_t ne12 = src1->ne[2];
  1179. const int64_t ne13 = src1->ne[3];
  1180. const int nb2 = dst->nb[2];
  1181. const int nb3 = dst->nb[3];
  1182. size_t x_size;
  1183. size_t d_size;
  1184. cl_mem d_X = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &x_size); // src0
  1185. cl_mem d_Y = (cl_mem) src1->extra; // src1 is already on device, broadcasted.
  1186. cl_mem d_D = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &d_size); // dst
  1187. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1188. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1189. cl_event ev;
  1190. // copy src0 to device
  1191. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, &ev));
  1192. const int64_t i13 = i03%ne13;
  1193. const int64_t i12 = i02%ne12;
  1194. const int i1 = i13*ne12*ne11 + i12*ne11;
  1195. cl_int x_offset = 0;
  1196. cl_int y_offset = i1*ne10;
  1197. cl_int d_offset = 0;
  1198. size_t global = ne00 * ne01;
  1199. cl_int ky = ne10 * ne11;
  1200. CL_CHECK(clSetKernelArg(mul_f32_cl, 0, sizeof(cl_mem), &d_X));
  1201. CL_CHECK(clSetKernelArg(mul_f32_cl, 1, sizeof(cl_int), &x_offset));
  1202. CL_CHECK(clSetKernelArg(mul_f32_cl, 2, sizeof(cl_mem), &d_Y));
  1203. CL_CHECK(clSetKernelArg(mul_f32_cl, 3, sizeof(cl_int), &y_offset));
  1204. CL_CHECK(clSetKernelArg(mul_f32_cl, 4, sizeof(cl_mem), &d_D));
  1205. CL_CHECK(clSetKernelArg(mul_f32_cl, 5, sizeof(cl_int), &d_offset));
  1206. CL_CHECK(clSetKernelArg(mul_f32_cl, 6, sizeof(cl_int), &ky));
  1207. CL_CHECK(clEnqueueNDRangeKernel(queue, mul_f32_cl, 1, NULL, &global, NULL, 1, &ev, NULL));
  1208. CL_CHECK(clReleaseEvent(ev));
  1209. CL_CHECK(clFinish(queue));
  1210. // copy dst to host
  1211. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  1212. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * ne00*ne01, d, 0, NULL, NULL));
  1213. }
  1214. }
  1215. ggml_cl_pool_free(d_X, x_size);
  1216. ggml_cl_pool_free(d_D, d_size);
  1217. }
  1218. void ggml_cl_mul(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  1219. GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  1220. ggml_cl_mul_f32(src0, src1, dst);
  1221. }
  1222. static void ggml_cl_add_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1223. GGML_ASSERT(src1->backend == GGML_BACKEND_TYPE_GPU);
  1224. const int64_t ne00 = src0->ne[0];
  1225. const int64_t ne01 = src0->ne[1];
  1226. const int64_t ne02 = src0->ne[2];
  1227. const int64_t ne03 = src0->ne[3];
  1228. const int64_t ne10 = src1->ne[0];
  1229. const int64_t ne11 = src1->ne[1];
  1230. const int64_t ne12 = src1->ne[2];
  1231. const int64_t ne13 = src1->ne[3];
  1232. const int nb2 = dst->nb[2];
  1233. const int nb3 = dst->nb[3];
  1234. size_t x_size;
  1235. size_t d_size;
  1236. cl_mem d_X = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &x_size); // src0
  1237. cl_mem d_Y = (cl_mem) src1->extra; // src1 is already on device, broadcasted.
  1238. cl_mem d_D = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &d_size); // dst
  1239. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1240. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1241. cl_event ev;
  1242. // copy src0 to device
  1243. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, &ev));
  1244. const int64_t i13 = i03%ne13;
  1245. const int64_t i12 = i02%ne12;
  1246. const int i1 = i13*ne12*ne11 + i12*ne11;
  1247. cl_int x_offset = 0;
  1248. cl_int y_offset = i1*ne10;
  1249. cl_int d_offset = 0;
  1250. size_t global = ne00 * ne01;
  1251. cl_int ky = ne10 * ne11;
  1252. CL_CHECK(clSetKernelArg(add_f32_cl, 0, sizeof(cl_mem), &d_X));
  1253. CL_CHECK(clSetKernelArg(add_f32_cl, 1, sizeof(cl_int), &x_offset));
  1254. CL_CHECK(clSetKernelArg(add_f32_cl, 2, sizeof(cl_mem), &d_Y));
  1255. CL_CHECK(clSetKernelArg(add_f32_cl, 3, sizeof(cl_int), &y_offset));
  1256. CL_CHECK(clSetKernelArg(add_f32_cl, 4, sizeof(cl_mem), &d_D));
  1257. CL_CHECK(clSetKernelArg(add_f32_cl, 5, sizeof(cl_int), &d_offset));
  1258. CL_CHECK(clSetKernelArg(add_f32_cl, 6, sizeof(cl_int), &ky));
  1259. CL_CHECK(clEnqueueNDRangeKernel(queue, add_f32_cl, 1, NULL, &global, NULL, 1, &ev, NULL));
  1260. CL_CHECK(clReleaseEvent(ev));
  1261. CL_CHECK(clFinish(queue));
  1262. // copy dst to host
  1263. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  1264. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * ne00*ne01, d, 0, NULL, NULL));
  1265. }
  1266. }
  1267. ggml_cl_pool_free(d_X, x_size);
  1268. ggml_cl_pool_free(d_D, d_size);
  1269. }
  1270. void ggml_cl_add(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  1271. GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  1272. ggml_cl_add_f32(src0, src1, dst);
  1273. }
  1274. static void ggml_cl_mul_mat_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1275. const int64_t ne00 = src0->ne[0];
  1276. const int64_t ne01 = src0->ne[1];
  1277. const int64_t ne02 = src0->ne[2];
  1278. const int64_t ne03 = src0->ne[3];
  1279. const int64_t ne10 = src1->ne[0];
  1280. const int64_t ne11 = src1->ne[1];
  1281. const int64_t ne12 = src1->ne[2];
  1282. const int64_t ne13 = src1->ne[3];
  1283. const int nb2 = dst->nb[2];
  1284. const int nb3 = dst->nb[3];
  1285. const int64_t r2 = ne12 / ne02;
  1286. const int64_t r3 = ne13 / ne03;
  1287. const float alpha = 1.0f;
  1288. const float beta = 0.0f;
  1289. const int x_ne = ne01 * ne00;
  1290. const int y_ne = ne11 * ne10;
  1291. const int d_ne = ne11 * ne01;
  1292. size_t x_size;
  1293. size_t y_size;
  1294. size_t d_size;
  1295. cl_mem d_X;
  1296. if (src0->backend == GGML_BACKEND_TYPE_GPU) { // NOLINT
  1297. d_X = (cl_mem) src0->extra;
  1298. } else {
  1299. d_X = ggml_cl_pool_malloc(sizeof(float) * x_ne, &x_size);
  1300. }
  1301. cl_mem d_Y = src1->backend == GGML_BACKEND_TYPE_GPU ? (cl_mem) src1->extra : ggml_cl_pool_malloc(sizeof(float) * y_ne, &y_size);
  1302. cl_mem d_D = dst->backend == GGML_BACKEND_TYPE_GPU ? (cl_mem) dst->extra : ggml_cl_pool_malloc(sizeof(float) * d_ne, &d_size);
  1303. size_t x_offset = 0;
  1304. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1305. // TODO: copy src0 here when r3>1
  1306. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1307. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1308. if (src0->backend == GGML_BACKEND_TYPE_GPU) {
  1309. x_offset = (i03 * ne02 + i02) * x_ne;
  1310. } else {
  1311. // copy src0 to device
  1312. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, NULL));
  1313. }
  1314. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1315. // copy src1 to device
  1316. if (src1->backend == GGML_BACKEND_TYPE_CPU) {
  1317. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, NULL));
  1318. }
  1319. CL_CHECK(clFinish(queue));
  1320. // compute
  1321. cl_event ev_sgemm;
  1322. clblast::StatusCode status = clblast::Gemm<cl_float>(clblast::Layout::kColMajor,
  1323. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1324. ne01, ne11, ne10,
  1325. alpha,
  1326. d_X, x_offset, ne00,
  1327. d_Y, 0, ne10,
  1328. beta,
  1329. d_D, 0, ne01,
  1330. &queue, &ev_sgemm);
  1331. if (status != clblast::StatusCode::kSuccess) {
  1332. GGML_ASSERT(false);
  1333. }
  1334. // copy dst to host
  1335. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  1336. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1337. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * d_ne, d, 1, &ev_sgemm, NULL));
  1338. }
  1339. }
  1340. }
  1341. }
  1342. }
  1343. if (src0->backend != GGML_BACKEND_TYPE_GPU) {
  1344. ggml_cl_pool_free(d_X, x_size);
  1345. }
  1346. if (src1->backend != GGML_BACKEND_TYPE_GPU) {
  1347. ggml_cl_pool_free(d_Y, y_size);
  1348. }
  1349. if (dst->backend != GGML_BACKEND_TYPE_GPU) {
  1350. ggml_cl_pool_free(d_D, d_size);
  1351. }
  1352. }
  1353. static void ggml_cl_mul_mat_f16(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, void * wdata, size_t wsize) {
  1354. GGML_ASSERT(fp16_support);
  1355. const int64_t ne00 = src0->ne[0];
  1356. const int64_t ne01 = src0->ne[1];
  1357. const int64_t ne02 = src0->ne[2];
  1358. const int64_t ne03 = src0->ne[3];
  1359. const int64_t ne10 = src1->ne[0];
  1360. const int64_t ne11 = src1->ne[1];
  1361. const int64_t ne12 = src1->ne[2];
  1362. const int64_t ne13 = src1->ne[3];
  1363. const int nb10 = src1->nb[0];
  1364. const int nb11 = src1->nb[1];
  1365. const int nb12 = src1->nb[2];
  1366. const int nb13 = src1->nb[3];
  1367. const int nb2 = dst->nb[2];
  1368. const int nb3 = dst->nb[3];
  1369. const int64_t r2 = ne12 / ne02;
  1370. const int64_t r3 = ne13 / ne03;
  1371. const ggml_fp16_t alpha = ggml_fp32_to_fp16(1.0f);
  1372. const ggml_fp16_t beta = ggml_fp32_to_fp16(0.0f);
  1373. const int x_ne = ne01 * ne00;
  1374. const int y_ne = ne11 * ne10;
  1375. const int d_ne = ne11 * ne01;
  1376. GGML_ASSERT(wsize >= sizeof(ggml_fp16_t) * y_ne);
  1377. GGML_ASSERT(wsize >= sizeof(ggml_fp16_t) * d_ne);
  1378. ggml_fp16_t * const tmp = (ggml_fp16_t *) wdata;
  1379. size_t x_size;
  1380. size_t y_size;
  1381. size_t d_size;
  1382. cl_mem d_X;
  1383. if (src0->backend == GGML_BACKEND_TYPE_GPU) { // NOLINT
  1384. d_X = (cl_mem) src0->extra;
  1385. } else {
  1386. d_X = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * x_ne, &x_size);
  1387. }
  1388. cl_mem d_Y = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * y_ne, &y_size);
  1389. cl_mem d_D = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * d_ne, &d_size);
  1390. bool src1_cont_rows = nb10 == sizeof(float);
  1391. bool src1_cont_cols = (size_t)nb11 == ne11*sizeof(float);
  1392. size_t x_offset = 0;
  1393. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1394. // TODO: copy src0 here when r3>1
  1395. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1396. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1397. if (src0->backend == GGML_BACKEND_TYPE_GPU) {
  1398. x_offset = (i03 * ne02 + i02) * x_ne;
  1399. } else {
  1400. // copy src0 to device
  1401. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, NULL));
  1402. }
  1403. // FIXME: convert on device
  1404. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1405. // convert src1 to fp16
  1406. // TODO: use multiple threads
  1407. char * src1i = (char *) src1->data + i13*nb13 + i12*nb12;
  1408. if (src1_cont_rows) {
  1409. if (src1_cont_cols) {
  1410. ggml_fp32_to_fp16_row((float *) src1i, tmp, ne10*ne11);
  1411. }
  1412. else {
  1413. for (int64_t i11 = 0; i11 < ne11; i11++) {
  1414. ggml_fp32_to_fp16_row((float *) (src1i + i11*nb11), tmp + i11*ne10, ne10);
  1415. }
  1416. }
  1417. }
  1418. else {
  1419. for (int64_t i11 = 0; i11 < ne11; i11++) {
  1420. for (int64_t i10 = 0; i10 < ne10; i10++) {
  1421. // very slow due to no inlining
  1422. tmp[i11*ne10 + i10] = ggml_fp32_to_fp16(*(float *) (src1i + i11*nb11 + i10*nb10));
  1423. }
  1424. }
  1425. }
  1426. // copy src1 to device
  1427. CL_CHECK(clEnqueueWriteBuffer(queue, d_Y, false, 0, sizeof(ggml_fp16_t) * y_ne, tmp, 0, NULL, NULL));
  1428. CL_CHECK(clFinish(queue));
  1429. // compute
  1430. cl_event ev_sgemm;
  1431. clblast::StatusCode status = clblast::Gemm<cl_half>(clblast::Layout::kColMajor,
  1432. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1433. ne01, ne11, ne10,
  1434. alpha,
  1435. d_X, x_offset, ne00,
  1436. d_Y, 0, ne10,
  1437. beta,
  1438. d_D, 0, ne01,
  1439. &queue, &ev_sgemm);
  1440. if (status != clblast::StatusCode::kSuccess) {
  1441. GGML_ASSERT(false);
  1442. }
  1443. // copy dst to host, then convert to float
  1444. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  1445. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(ggml_fp16_t) * d_ne, tmp, 1, &ev_sgemm, NULL));
  1446. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1447. ggml_fp16_to_fp32_row(tmp, d, d_ne);
  1448. } else {
  1449. // FIXME: convert dst to fp32 on device
  1450. }
  1451. }
  1452. }
  1453. }
  1454. }
  1455. if (src0->backend != GGML_BACKEND_TYPE_GPU) {
  1456. ggml_cl_pool_free(d_X, x_size);
  1457. }
  1458. ggml_cl_pool_free(d_Y, y_size);
  1459. ggml_cl_pool_free(d_D, d_size);
  1460. }
  1461. static void ggml_cl_mul_mat_q_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1462. const int64_t ne00 = src0->ne[0];
  1463. const int64_t ne01 = src0->ne[1];
  1464. const int64_t ne02 = src0->ne[2];
  1465. const int64_t ne03 = src0->ne[3];
  1466. const int64_t ne10 = src1->ne[0];
  1467. const int64_t ne11 = src1->ne[1];
  1468. const int64_t ne12 = src1->ne[2];
  1469. const int64_t ne13 = src1->ne[3];
  1470. const int nb2 = dst->nb[2];
  1471. const int nb3 = dst->nb[3];
  1472. const ggml_type type = src0->type;
  1473. const bool mul_mat_vec = ne11 == 1 && ne00%2 == 0;
  1474. const int64_t r2 = ne12 / ne02;
  1475. const int64_t r3 = ne13 / ne03;
  1476. const float alpha = 1.0f;
  1477. const float beta = 0.0f;
  1478. const int x_ne = ne01 * ne00;
  1479. const int y_ne = ne11 * ne10;
  1480. const int d_ne = ne11 * ne01;
  1481. const int x_bps = x_ne / ggml_blck_size(type); // blocks per 2D slice
  1482. const size_t q_sz = ggml_type_size(type) * x_bps;
  1483. size_t x_size;
  1484. size_t y_size;
  1485. size_t d_size;
  1486. size_t q_size;
  1487. cl_mem d_X;
  1488. if (!mul_mat_vec) {
  1489. d_X = ggml_cl_pool_malloc(sizeof(float) * x_ne, &x_size);
  1490. }
  1491. cl_mem d_Y = ggml_cl_pool_malloc(sizeof(float) * y_ne, &y_size);
  1492. cl_mem d_D = ggml_cl_pool_malloc(sizeof(float) * d_ne, &d_size);
  1493. cl_mem d_Q;
  1494. if (src0->backend == GGML_BACKEND_TYPE_CPU) {
  1495. d_Q = ggml_cl_pool_malloc(q_sz, &q_size);
  1496. }
  1497. cl_kernel* to_fp32_cl = ggml_get_to_fp32_cl(type);
  1498. cl_kernel* dmmv = ggml_get_dequantize_mul_mat_vec_cl(type);
  1499. GGML_ASSERT(to_fp32_cl != nullptr);
  1500. const size_t global_denom = ggml_cl_global_denom(type);
  1501. const size_t local = mul_mat_vec ? CL_DMMV_LOCAL_SIZE : ggml_cl_local_size(type);
  1502. size_t ev_idx = 0;
  1503. std::vector<cl_event> events;
  1504. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1505. // TODO: copy and dequantize src0 here when r3>1
  1506. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1507. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1508. // copy src0 to device if necessary
  1509. if (src0->backend == GGML_BACKEND_TYPE_CPU) {
  1510. events.emplace_back();
  1511. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Q, 0, src0, i03, i02, events.data() + ev_idx++));
  1512. } else if (src0->backend == GGML_BACKEND_TYPE_GPU) {
  1513. d_Q = (cl_mem) src0->extra;
  1514. } else {
  1515. GGML_ASSERT(false);
  1516. }
  1517. if (!mul_mat_vec) {
  1518. // convert src0 to fp32 on device
  1519. const size_t global = x_ne / global_denom;
  1520. const size_t offset = src0->backend == GGML_BACKEND_TYPE_GPU ? (i03 * ne02 + i02) * x_bps : 0;
  1521. CL_CHECK(clSetKernelArg(*to_fp32_cl, 0, sizeof(cl_mem), &d_Q));
  1522. CL_CHECK(clSetKernelArg(*to_fp32_cl, 1, sizeof(cl_mem), &d_X));
  1523. CL_CHECK(clEnqueueNDRangeKernel(queue, *to_fp32_cl, 1, &offset, &global, local > 0 ? &local : NULL, events.size(), !events.empty() ? events.data() : NULL, NULL));
  1524. }
  1525. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1526. if (mul_mat_vec) { // specialized dequantize_mul_mat_vec kernel
  1527. // copy src1 to device
  1528. events.emplace_back();
  1529. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, events.data() + ev_idx++));
  1530. // compute
  1531. const size_t global = ne01 * local;
  1532. const size_t offset = src0->backend == GGML_BACKEND_TYPE_GPU ? (i03 * ne02 + i02) * x_bps : 0;
  1533. const cl_int ncols = ne00;
  1534. events.emplace_back();
  1535. CL_CHECK(clSetKernelArg(*dmmv, 0, sizeof(cl_mem), &d_Q));
  1536. CL_CHECK(clSetKernelArg(*dmmv, 1, sizeof(float) * local, NULL));
  1537. CL_CHECK(clSetKernelArg(*dmmv, 2, sizeof(cl_mem), &d_Y));
  1538. CL_CHECK(clSetKernelArg(*dmmv, 3, sizeof(cl_mem), &d_D));
  1539. CL_CHECK(clSetKernelArg(*dmmv, 4, sizeof(cl_int), &ncols));
  1540. CL_CHECK(clEnqueueNDRangeKernel(queue, *dmmv, 1, &offset, &global, &local, events.size() - 1, events.data(), events.data() + ev_idx++));
  1541. } else { // CLBlast matrix matrix multiplication
  1542. // copy src1 to device
  1543. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, NULL));
  1544. // wait for conversion
  1545. CL_CHECK(clFinish(queue));
  1546. // compute
  1547. events.emplace_back();
  1548. clblast::StatusCode status = clblast::Gemm<cl_float>(clblast::Layout::kColMajor,
  1549. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1550. ne01, ne11, ne10,
  1551. alpha,
  1552. d_X, 0, ne00,
  1553. d_Y, 0, ne10,
  1554. beta,
  1555. d_D, 0, ne01,
  1556. &queue, events.data() + ev_idx++);
  1557. if (status != clblast::StatusCode::kSuccess) {
  1558. GGML_ASSERT(false);
  1559. }
  1560. }
  1561. // copy dst to host
  1562. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1563. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * d_ne, d, 1, &events[events.size() - 1], NULL));
  1564. for (auto *event : events) {
  1565. clReleaseEvent(event);
  1566. }
  1567. ev_idx = 0;
  1568. events.clear();
  1569. }
  1570. }
  1571. }
  1572. }
  1573. if (!mul_mat_vec) {
  1574. ggml_cl_pool_free(d_X, x_size);
  1575. }
  1576. ggml_cl_pool_free(d_Y, y_size);
  1577. ggml_cl_pool_free(d_D, d_size);
  1578. if (src0->backend == GGML_BACKEND_TYPE_CPU) {
  1579. ggml_cl_pool_free(d_Q, q_size);
  1580. }
  1581. }
  1582. bool ggml_cl_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) {
  1583. const int64_t ne10 = src1->ne[0];
  1584. const int64_t ne0 = dst->ne[0];
  1585. const int64_t ne1 = dst->ne[1];
  1586. // TODO: find the optimal values for these
  1587. if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) &&
  1588. src1->type == GGML_TYPE_F32 &&
  1589. dst->type == GGML_TYPE_F32 &&
  1590. ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32) || src0->backend == GGML_BACKEND_TYPE_GPU)) {
  1591. return true;
  1592. }
  1593. return false;
  1594. }
  1595. static bool ggml_cl_mul_mat_use_f16(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * /* dst */) {
  1596. // If device doesn't support FP16
  1597. if (!fp16_support) {
  1598. return false;
  1599. }
  1600. size_t src0_sz = ggml_nbytes(src0);
  1601. size_t src1_sz = ggml_nbytes(src1);
  1602. // mul_mat_q: src0 is converted to fp32 on device
  1603. size_t mul_mat_q_transfer = src0_sz + src1_sz;
  1604. // mul_mat_f16: src1 is converted to fp16 on cpu
  1605. size_t mul_mat_f16_transfer = src0_sz + sizeof(ggml_fp16_t) * ggml_nelements(src1);
  1606. // choose the smaller one to transfer to the device
  1607. // TODO: this is not always the best choice due to the overhead of converting to fp16
  1608. return mul_mat_f16_transfer < mul_mat_q_transfer;
  1609. }
  1610. void ggml_cl_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst, void * wdata, size_t wsize) {
  1611. GGML_ASSERT(ggml_cl_can_mul_mat(src0, src1, dst));
  1612. if (src0->type == GGML_TYPE_F32) {
  1613. ggml_cl_mul_mat_f32(src0, src1, dst);
  1614. }
  1615. else if (src0->type == GGML_TYPE_F16) {
  1616. if (ggml_cl_mul_mat_use_f16(src0, src1, dst)) {
  1617. ggml_cl_mul_mat_f16(src0, src1, dst, wdata, wsize);
  1618. }
  1619. else {
  1620. ggml_cl_mul_mat_q_f32(src0, src1, dst);
  1621. }
  1622. }
  1623. else if (ggml_is_quantized(src0->type)) {
  1624. ggml_cl_mul_mat_q_f32(src0, src1, dst);
  1625. }
  1626. else {
  1627. GGML_ASSERT(false);
  1628. }
  1629. }
  1630. size_t ggml_cl_mul_mat_get_wsize(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  1631. if (src0->type == GGML_TYPE_F16 && ggml_cl_mul_mat_use_f16(src0, src1, dst)) {
  1632. return sizeof(ggml_fp16_t) * std::max(src1->ne[0] * src1->ne[1], dst->ne[0] * dst->ne[1]);
  1633. }
  1634. return 0;
  1635. }
  1636. void ggml_cl_transform_tensor(void * data, ggml_tensor * tensor) {
  1637. const int64_t ne0 = tensor->ne[0];
  1638. const int64_t ne1 = tensor->ne[1];
  1639. const int64_t ne2 = tensor->ne[2];
  1640. const int64_t ne3 = tensor->ne[3];
  1641. const ggml_type type = tensor->type;
  1642. const size_t s_sz = ggml_type_size(type) * (size_t) (ne0 * ne1 / ggml_blck_size(type));
  1643. const size_t q_sz = s_sz * (size_t) (ne2 * ne3);
  1644. size_t q_size;
  1645. cl_mem dst = ggml_cl_pool_malloc(q_sz, &q_size);
  1646. tensor->data = data;
  1647. // copy tensor to device
  1648. size_t offset = 0;
  1649. for (int64_t i3 = 0; i3 < ne3; i3++) {
  1650. for (int64_t i2 = 0; i2 < ne2; i2++) {
  1651. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, dst, offset, tensor, i3, i2, NULL));
  1652. offset += s_sz;
  1653. }
  1654. }
  1655. CL_CHECK(clFinish(queue));
  1656. tensor->extra = dst;
  1657. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_GPU);
  1658. }
  1659. // ggml-backend
  1660. // buffer
  1661. struct ggml_backend_opencl_buffer_context {
  1662. ~ggml_backend_opencl_buffer_context() {
  1663. if (buffer) {
  1664. clReleaseMemObject(buffer);
  1665. }
  1666. for (auto * sub_buffer : sub_buffers) {
  1667. clReleaseMemObject(sub_buffer);
  1668. }
  1669. }
  1670. cl_mem buffer;
  1671. std::vector<cl_mem> sub_buffers;
  1672. };
  1673. static void * const cl_ptr_base = (void *)(uintptr_t) 0x1000;
  1674. static const char * ggml_backend_opencl_buffer_get_name(ggml_backend_buffer_t buffer) {
  1675. return "OpenCL";
  1676. GGML_UNUSED(buffer);
  1677. }
  1678. static void ggml_backend_opencl_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1679. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1680. delete ctx;
  1681. }
  1682. static void * ggml_backend_opencl_buffer_get_base(ggml_backend_buffer_t buffer) {
  1683. return cl_ptr_base;
  1684. GGML_UNUSED(buffer);
  1685. }
  1686. static void ggml_backend_opencl_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  1687. if (tensor->view_src != NULL && tensor->view_offs == 0) {
  1688. tensor->extra = tensor->view_src->extra;
  1689. } else {
  1690. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1691. cl_buffer_region region = {(size_t)((char *)tensor->data - (char *)cl_ptr_base), ggml_nbytes(tensor)};
  1692. cl_int err;
  1693. cl_mem sub_buffer = clCreateSubBuffer(ctx->buffer, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, &region, &err);
  1694. CL_CHECK(err);
  1695. ctx->sub_buffers.push_back(sub_buffer);
  1696. tensor->extra = sub_buffer;
  1697. }
  1698. tensor->backend = GGML_BACKEND_TYPE_GPU;
  1699. }
  1700. static void ggml_backend_opencl_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  1701. cl_mem tensor_buffer = (cl_mem) tensor->extra;
  1702. CL_CHECK(clEnqueueWriteBuffer(queue, tensor_buffer, true, offset, size, data, 0, NULL, NULL));
  1703. CL_CHECK(clFinish(queue));
  1704. GGML_UNUSED(buffer);
  1705. }
  1706. static void ggml_backend_opencl_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  1707. cl_mem tensor_buffer = (cl_mem) tensor->extra;
  1708. CL_CHECK(clEnqueueReadBuffer(queue, tensor_buffer, true, offset, size, data, 0, NULL, NULL));
  1709. CL_CHECK(clFinish(queue));
  1710. GGML_UNUSED(buffer);
  1711. }
  1712. static void ggml_backend_opencl_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  1713. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1714. CL_CHECK(clEnqueueFillBuffer(queue, ctx->buffer, &value, sizeof(value), 0, buffer->size, 0, NULL, NULL));
  1715. CL_CHECK(clFinish(queue));
  1716. }
  1717. static void ggml_backend_opencl_buffer_reset(ggml_backend_buffer_t buffer) {
  1718. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1719. for (auto * sub_buffer : ctx->sub_buffers) {
  1720. clReleaseMemObject(sub_buffer);
  1721. }
  1722. ctx->sub_buffers.clear();
  1723. }
  1724. static ggml_backend_buffer_i ggml_backend_opencl_buffer_interface = {
  1725. /* .get_name = */ ggml_backend_opencl_buffer_get_name,
  1726. /* .free_buffer = */ ggml_backend_opencl_buffer_free_buffer,
  1727. /* .get_base = */ ggml_backend_opencl_buffer_get_base,
  1728. /* .init_tensor = */ ggml_backend_opencl_buffer_init_tensor,
  1729. /* .set_tensor = */ ggml_backend_opencl_buffer_set_tensor,
  1730. /* .get_tensor = */ ggml_backend_opencl_buffer_get_tensor,
  1731. /* .cpy_tensor = */ NULL,
  1732. /* .clear = */ ggml_backend_opencl_buffer_clear,
  1733. /* .reset = */ ggml_backend_opencl_buffer_reset,
  1734. };
  1735. // buffer type
  1736. static const char * ggml_backend_opencl_buffer_type_name(ggml_backend_buffer_type_t buffer_type) {
  1737. return "OpenCL";
  1738. GGML_UNUSED(buffer_type);
  1739. }
  1740. static ggml_backend_buffer_t ggml_backend_opencl_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buffer_type, size_t size) {
  1741. ggml_cl_init();
  1742. cl_int err;
  1743. cl_mem mem = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err);
  1744. if (err != CL_SUCCESS) {
  1745. fprintf(stderr, "%s: failed to allocate %.2f MiB\n", __func__, size / 1024.0 / 1024.0);
  1746. return nullptr;
  1747. }
  1748. ggml_backend_opencl_buffer_context * ctx = new ggml_backend_opencl_buffer_context{mem, {}};
  1749. return ggml_backend_buffer_init(buffer_type, ggml_backend_opencl_buffer_interface, ctx, size);
  1750. }
  1751. static size_t ggml_backend_opencl_buffer_type_get_alignment(ggml_backend_buffer_type_t buffer_type) {
  1752. // FIXME: not thread safe, device may not be initialized yet
  1753. static cl_uint alignment = -1;
  1754. if (alignment == (cl_uint)-1) {
  1755. ggml_cl_init();
  1756. clGetDeviceInfo(device, CL_DEVICE_MEM_BASE_ADDR_ALIGN, sizeof(cl_uint), &alignment, NULL);
  1757. }
  1758. return alignment;
  1759. GGML_UNUSED(buffer_type);
  1760. }
  1761. static size_t ggml_backend_opencl_buffer_type_get_max_size(ggml_backend_buffer_type_t buffer_type) {
  1762. static size_t max_size = -1;
  1763. if (max_size == (size_t)-1) {
  1764. ggml_cl_init();
  1765. clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(size_t), &max_size, NULL);
  1766. }
  1767. return max_size;
  1768. }
  1769. static bool ggml_backend_opencl_buffer_type_supports_backend(ggml_backend_buffer_type_t buffer_type, ggml_backend_t backend) {
  1770. //return ggml_backend_is_opencl(backend); // opencl must be used through the cpu backend
  1771. return ggml_backend_is_cpu(backend);
  1772. GGML_UNUSED(buffer_type);
  1773. }
  1774. static ggml_backend_buffer_type_i ggml_backend_opencl_buffer_type_interface = {
  1775. /* .get_name = */ ggml_backend_opencl_buffer_type_name,
  1776. /* .alloc_buffer = */ ggml_backend_opencl_buffer_type_alloc_buffer,
  1777. /* .get_alignment = */ ggml_backend_opencl_buffer_type_get_alignment,
  1778. /* .get_max_size = */ ggml_backend_opencl_buffer_type_get_max_size,
  1779. /* .get_alloc_size = */ NULL,
  1780. /* .supports_backend = */ ggml_backend_opencl_buffer_type_supports_backend,
  1781. /* .is_host = */ NULL,
  1782. };
  1783. ggml_backend_buffer_type_t ggml_backend_opencl_buffer_type() {
  1784. static ggml_backend_buffer_type buffer_type = {
  1785. /* .iface = */ ggml_backend_opencl_buffer_type_interface,
  1786. /* .context = */ nullptr,
  1787. };
  1788. return &buffer_type;
  1789. }
  1790. #if 0
  1791. // host buffer type
  1792. static const char * ggml_backend_opencl_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  1793. return "CL_Host";
  1794. GGML_UNUSED(buft);
  1795. }
  1796. static const char * ggml_backend_opencl_host_buffer_name(ggml_backend_buffer_t buffer) {
  1797. return "CL_Host";
  1798. GGML_UNUSED(buffer);
  1799. }
  1800. static void ggml_backend_opencl_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1801. ggml_cl_host_free(buffer->context);
  1802. }
  1803. static ggml_backend_buffer_t ggml_backend_opencl_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1804. void * ptr = ggml_cl_host_malloc(size);
  1805. if (ptr == nullptr) {
  1806. // fallback to cpu buffer
  1807. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  1808. }
  1809. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  1810. buffer->buft = buft;
  1811. buffer->iface.get_name = ggml_backend_opencl_host_buffer_name;
  1812. buffer->iface.free_buffer = ggml_backend_opencl_host_buffer_free_buffer;
  1813. return buffer;
  1814. }
  1815. ggml_backend_buffer_type_t ggml_backend_opencl_host_buffer_type() {
  1816. static struct ggml_backend_buffer_type ggml_backend_opencl_buffer_type_host = {
  1817. /* .iface = */ {
  1818. /* .get_name = */ ggml_backend_opencl_host_buffer_type_name,
  1819. /* .alloc_buffer = */ ggml_backend_opencl_host_buffer_type_alloc_buffer,
  1820. /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment,
  1821. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  1822. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  1823. /* .supports_backend = */ ggml_backend_cpu_buffer_type()->iface.supports_backend,
  1824. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  1825. },
  1826. /* .context = */ nullptr,
  1827. };
  1828. return &ggml_backend_opencl_buffer_type_host;
  1829. }
  1830. // backend
  1831. static const char * ggml_backend_opencl_name(ggml_backend_t backend) {
  1832. return "OpenCL";
  1833. GGML_UNUSED(backend);
  1834. }
  1835. static void ggml_backend_opencl_free(ggml_backend_t backend) {
  1836. GGML_UNUSED(backend);
  1837. }
  1838. static ggml_backend_buffer_type_t ggml_backend_opencl_get_default_buffer_type(ggml_backend_t backend) {
  1839. return ggml_backend_opencl_buffer_type();
  1840. GGML_UNUSED(backend);
  1841. }
  1842. static bool ggml_backend_opencl_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
  1843. for (int i = 0; i < graph->n_nodes; ++i) {
  1844. ggml_tensor * node = graph->nodes[i];
  1845. switch (node->op) {
  1846. case GGML_OP_MUL_MAT:
  1847. ggml_cl_mul_mat(node->src[0], node->src[1], node, nullptr, 0);
  1848. break;
  1849. case GGML_OP_MUL:
  1850. ggml_cl_mul(node->src[0], node->src[1], node);
  1851. break;
  1852. default:
  1853. GGML_ASSERT(false);
  1854. }
  1855. }
  1856. return true;
  1857. GGML_UNUSED(backend);
  1858. }
  1859. static bool ggml_backend_opencl_supports_op(ggml_backend_t backend, const ggml_tensor * op) {
  1860. switch (op->op) {
  1861. case GGML_OP_MUL_MAT:
  1862. return ggml_cl_can_mul_mat(op->src[0], op->src[1], op);
  1863. case GGML_OP_MUL:
  1864. // return ggml_can_repeat_rows(op->src[1], op->src[0]);
  1865. return true;
  1866. default:
  1867. return false;
  1868. }
  1869. GGML_UNUSED(backend);
  1870. }
  1871. static ggml_backend_i opencl_backend_i = {
  1872. /* .get_name = */ ggml_backend_opencl_name,
  1873. /* .free = */ ggml_backend_opencl_free,
  1874. /* .get_default_buffer_type = */ ggml_backend_opencl_get_default_buffer_type,
  1875. /* .set_tensor_async = */ NULL,
  1876. /* .get_tensor_async = */ NULL,
  1877. /* .cpy_tensor_from_async = */ NULL,
  1878. /* .cpy_tensor_to_async = */ NULL,
  1879. /* .synchronize = */ NULL,
  1880. /* .graph_plan_create = */ NULL,
  1881. /* .graph_plan_free = */ NULL,
  1882. /* .graph_plan_compute = */ NULL,
  1883. /* .graph_compute = */ ggml_backend_opencl_graph_compute,
  1884. /* .supports_op = */ ggml_backend_opencl_supports_op,
  1885. };
  1886. ggml_backend_t ggml_backend_opencl_init() {
  1887. ggml_backend_t backend = new ggml_backend {
  1888. /* .interface = */ opencl_backend_i,
  1889. /* .context = */ nullptr
  1890. };
  1891. return backend;
  1892. }
  1893. bool ggml_backend_is_opencl(ggml_backend_t backend) {
  1894. return backend && backend->iface.get_name == ggml_backend_opencl_name;
  1895. }
  1896. #endif