ggml-opencl.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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. #define CL_CHECK(err) \
  629. do { \
  630. cl_int err_ = (err); \
  631. if (err_ != CL_SUCCESS) { \
  632. fprintf(stderr, "ggml_opencl: %s error %d at %s:%d\n", \
  633. #err, err_, __FILE__, __LINE__); \
  634. exit(1); \
  635. } \
  636. } while (0)
  637. #define CLBLAST_CHECK(err) \
  638. do { \
  639. CLBlastStatusCode err_ = (err); \
  640. if (err_ != CLBlastSuccess) { \
  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. std::array<std::string, 5> dequant_str_keys = {
  647. "KERNEL_NAME", "X_TYPE", "QUANT_K", "QUANT_R", "DEQUANT_FUNC"
  648. };
  649. std::array<std::string, 30> dequant_str_values = {
  650. "dequantize_row_q4_0", "struct block_q4_0", "QK4_0", "QR4_0", "dequantize_q4_0",
  651. "dequantize_row_q4_1", "struct block_q4_1", "QK4_1", "QR4_1", "dequantize_q4_1",
  652. "dequantize_row_q5_0", "struct block_q5_0", "QK5_0", "QR5_0", "dequantize_q5_0",
  653. "dequantize_row_q5_1", "struct block_q5_1", "QK5_1", "QR5_1", "dequantize_q5_1",
  654. "dequantize_row_q8_0", "struct block_q8_0", "QK8_0", "QR8_0", "dequantize_q8_0",
  655. "convert_row_f16", "half", "1", "1", "convert_f16"
  656. };
  657. std::array<std::string, 30> dequant_mul_mat_vec_str_values = {
  658. "dequantize_mul_mat_vec_q4_0", "struct block_q4_0", "QK4_0", "QR4_0", "dequantize_q4_0",
  659. "dequantize_mul_mat_vec_q4_1", "struct block_q4_1", "QK4_1", "QR4_1", "dequantize_q4_1",
  660. "dequantize_mul_mat_vec_q5_0", "struct block_q5_0", "QK5_0", "QR5_0", "dequantize_q5_0",
  661. "dequantize_mul_mat_vec_q5_1", "struct block_q5_1", "QK5_1", "QR5_1", "dequantize_q5_1",
  662. "dequantize_mul_mat_vec_q8_0", "struct block_q8_0", "QK8_0", "QR8_0", "dequantize_q8_0",
  663. "convert_mul_mat_vec_f16", "half", "1", "1", "convert_f16"
  664. };
  665. std::array<std::string, 2> mul_str_keys = {
  666. "KERNEL_NAME", "TYPE"
  667. };
  668. std::array<std::string, 2> mul_str_values = {
  669. "mul_f32", "float"
  670. };
  671. static std::string& replace(std::string& s, const std::string& from, const std::string& to) {
  672. size_t pos = 0;
  673. while ((pos = s.find(from, pos)) != std::string::npos) {
  674. s.replace(pos, from.length(), to);
  675. pos += to.length();
  676. }
  677. return s;
  678. }
  679. static std::string generate_kernels() {
  680. std::stringstream src;
  681. src << program_source << '\n';
  682. src << k_quants_source << '\n';
  683. for (size_t i = 0; i < dequant_str_values.size(); i += dequant_str_keys.size()) {
  684. std::string dequant_kernel = dequant_template;
  685. std::string dmmv_kernel = dequant_mul_mat_vec_template;
  686. for (size_t j = 0; j < dequant_str_keys.size(); j++) {
  687. replace(dequant_kernel, dequant_str_keys[j], dequant_str_values[i + j]);
  688. replace(dmmv_kernel, dequant_str_keys[j], dequant_mul_mat_vec_str_values[i + j]);
  689. }
  690. src << dequant_kernel << '\n';
  691. src << dmmv_kernel << '\n';
  692. }
  693. for (size_t i = 0; i < mul_str_values.size(); i += mul_str_keys.size()) {
  694. std::string mul_kernel = mul_template;
  695. for (size_t j = 0; j < mul_str_keys.size(); j++) {
  696. replace(mul_kernel, mul_str_keys[j], mul_str_values[i + j]);
  697. }
  698. src << mul_kernel << '\n';
  699. }
  700. return src.str();
  701. }
  702. static cl_platform_id platform;
  703. static cl_device_id device;
  704. static cl_context context;
  705. static cl_command_queue queue;
  706. static cl_program program;
  707. static cl_kernel convert_row_f16_cl;
  708. 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;
  709. 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;
  710. 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;
  711. 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;
  712. static cl_kernel mul_f32_cl;
  713. static bool fp16_support;
  714. static cl_program build_program_from_source(cl_context ctx, cl_device_id dev, const char* program_buffer) {
  715. cl_program p;
  716. char *program_log;
  717. size_t program_size;
  718. size_t log_size;
  719. int err;
  720. program_size = strlen(program_buffer);
  721. p = clCreateProgramWithSource(ctx, 1, (const char**)&program_buffer, &program_size, &err);
  722. if(err < 0) {
  723. fprintf(stderr, "OpenCL error creating program");
  724. exit(1);
  725. }
  726. std::string compile_opts = "-cl-mad-enable -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math "
  727. "-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 "
  728. "-DQK_K=256 -DK_QUANTS_PER_ITERATION=" + std::to_string(K_QUANTS_PER_ITERATION);
  729. err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL);
  730. if(err < 0) {
  731. clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
  732. program_log = (char*) malloc(log_size + 1);
  733. program_log[log_size] = '\0';
  734. clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL);
  735. fprintf(stderr, "ggml_opencl: kernel compile error:\n\n%s\n", program_log);
  736. free(program_log);
  737. exit(1);
  738. }
  739. return p;
  740. }
  741. void ggml_cl_init(void) {
  742. static bool initialized = false;
  743. if (initialized) {
  744. return;
  745. }
  746. initialized = true;
  747. cl_int err;
  748. struct cl_device;
  749. struct cl_platform {
  750. cl_platform_id id;
  751. unsigned number;
  752. char name[128];
  753. char vendor[128];
  754. struct cl_device * devices;
  755. unsigned n_devices;
  756. struct cl_device * default_device;
  757. };
  758. struct cl_device {
  759. struct cl_platform * platform;
  760. cl_device_id id;
  761. unsigned number;
  762. cl_device_type type;
  763. char name[128];
  764. };
  765. enum { NPLAT = 16, NDEV = 16 };
  766. struct cl_platform platforms[NPLAT];
  767. unsigned n_platforms = 0;
  768. struct cl_device devices[NDEV];
  769. unsigned n_devices = 0;
  770. struct cl_device * default_device = NULL;
  771. platform = NULL;
  772. device = NULL;
  773. cl_platform_id platform_ids[NPLAT];
  774. CL_CHECK(clGetPlatformIDs(NPLAT, platform_ids, &n_platforms));
  775. for (unsigned i = 0; i < n_platforms; i++) {
  776. struct cl_platform * p = &platforms[i];
  777. p->number = i;
  778. p->id = platform_ids[i];
  779. CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_NAME, sizeof(p->name), &p->name, NULL));
  780. CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_VENDOR, sizeof(p->vendor), &p->vendor, NULL));
  781. cl_device_id device_ids[NDEV];
  782. cl_int clGetDeviceIDsError = clGetDeviceIDs(p->id, CL_DEVICE_TYPE_ALL, NDEV, device_ids, &p->n_devices);
  783. if (clGetDeviceIDsError == CL_DEVICE_NOT_FOUND) {
  784. p->n_devices = 0;
  785. } else {
  786. CL_CHECK(clGetDeviceIDsError);
  787. }
  788. p->devices = p->n_devices > 0 ? &devices[n_devices] : NULL;
  789. p->default_device = NULL;
  790. for (unsigned j = 0; j < p->n_devices; j++) {
  791. struct cl_device * d = &devices[n_devices];
  792. d->number = n_devices++;
  793. d->id = device_ids[j];
  794. d->platform = p;
  795. CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_NAME, sizeof(d->name), &d->name, NULL));
  796. CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_TYPE, sizeof(d->type), &d->type, NULL));
  797. if (p->default_device == NULL && d->type == CL_DEVICE_TYPE_GPU) {
  798. p->default_device = d;
  799. }
  800. }
  801. if (default_device == NULL && p->default_device != NULL) {
  802. default_device = p->default_device;
  803. }
  804. }
  805. if (n_devices == 0) {
  806. fprintf(stderr, "ggml_opencl: could find any OpenCL devices.\n");
  807. exit(1);
  808. }
  809. char * user_platform_string = getenv("GGML_OPENCL_PLATFORM");
  810. char * user_device_string = getenv("GGML_OPENCL_DEVICE");
  811. int user_platform_number = -1;
  812. int user_device_number = -1;
  813. unsigned n;
  814. if (user_platform_string != NULL && sscanf(user_platform_string, " %u", &n) == 1 && n < n_platforms) {
  815. user_platform_number = (int)n;
  816. }
  817. if (user_device_string != NULL && sscanf(user_device_string, " %u", &n) == 1 && n < n_devices) {
  818. user_device_number = (int)n;
  819. }
  820. if (user_platform_number != -1 && user_device_number != -1) {
  821. cl_platform* platform = &platforms[user_platform_number];
  822. if ((unsigned)user_device_number >= platform->n_devices) {
  823. fprintf(stderr, "ggml_opencl: invalid device number %d\n", user_device_number);
  824. exit(1);
  825. }
  826. default_device = &platform->devices[user_device_number];
  827. } else {
  828. struct cl_device * selected_devices = devices;
  829. unsigned n_selected_devices = n_devices;
  830. if (user_platform_number == -1 && user_platform_string != NULL && user_platform_string[0] != 0) {
  831. for (unsigned i = 0; i < n_platforms; i++) {
  832. struct cl_platform * p = &platforms[i];
  833. if (strstr(p->name, user_platform_string) != NULL ||
  834. strstr(p->vendor, user_platform_string) != NULL) {
  835. user_platform_number = (int)i;
  836. break;
  837. }
  838. }
  839. if (user_platform_number == -1) {
  840. fprintf(stderr, "ggml_opencl: no platform matching '%s' was found.\n", user_platform_string);
  841. exit(1);
  842. }
  843. }
  844. if (user_platform_number != -1) {
  845. struct cl_platform * p = &platforms[user_platform_number];
  846. selected_devices = p->devices;
  847. n_selected_devices = p->n_devices;
  848. default_device = p->default_device;
  849. if (n_selected_devices == 0) {
  850. fprintf(stderr, "ggml_opencl: selected platform '%s' does not have any devices.\n", p->name);
  851. exit(1);
  852. }
  853. }
  854. if (user_device_number == -1 && user_device_string != NULL && user_device_string[0] != 0) {
  855. for (unsigned i = 0; i < n_selected_devices; i++) {
  856. struct cl_device * d = &selected_devices[i];
  857. if (strstr(d->name, user_device_string) != NULL) {
  858. user_device_number = d->number;
  859. break;
  860. }
  861. }
  862. if (user_device_number == -1) {
  863. fprintf(stderr, "ggml_opencl: no device matching '%s' was found.\n", user_device_string);
  864. exit(1);
  865. }
  866. }
  867. if (user_device_number != -1) {
  868. selected_devices = &devices[user_device_number];
  869. n_selected_devices = 1;
  870. default_device = &selected_devices[0];
  871. }
  872. GGML_ASSERT(n_selected_devices > 0);
  873. if (default_device == NULL) {
  874. default_device = &selected_devices[0];
  875. }
  876. }
  877. fprintf(stderr, "ggml_opencl: selecting platform: '%s'\n", default_device->platform->name);
  878. fprintf(stderr, "ggml_opencl: selecting device: '%s'\n", default_device->name);
  879. if (default_device->type != CL_DEVICE_TYPE_GPU) {
  880. fprintf(stderr, "ggml_opencl: warning, not a GPU: '%s'.\n", default_device->name);
  881. }
  882. platform = default_device->platform->id;
  883. device = default_device->id;
  884. size_t ext_str_size;
  885. clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size);
  886. char *ext_buffer = (char *)alloca(ext_str_size + 1);
  887. clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer, NULL);
  888. ext_buffer[ext_str_size] = '\0'; // ensure it is null terminated
  889. // Check if ext_buffer contains cl_khr_fp16
  890. fp16_support = strstr(ext_buffer, "cl_khr_fp16") != NULL;
  891. fprintf(stderr, "ggml_opencl: device FP16 support: %s\n", fp16_support ? "true" : "false");
  892. cl_context_properties properties[] = {
  893. (intptr_t)CL_CONTEXT_PLATFORM, (intptr_t)platform, 0
  894. };
  895. CL_CHECK((context = clCreateContext(properties, 1, &device, NULL, NULL, &err), err));
  896. CL_CHECK((queue = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err),
  897. (err != CL_INVALID_QUEUE_PROPERTIES && err != CL_INVALID_VALUE ? err :
  898. (queue = clCreateCommandQueue(context, device, 0, &err), err)
  899. )));
  900. const std::string kernel_src = generate_kernels();
  901. program = build_program_from_source(context, device, kernel_src.c_str());
  902. // FP16 to FP32 kernel
  903. CL_CHECK((convert_row_f16_cl = clCreateKernel(program, "convert_row_f16", &err), err));
  904. // Dequantize kernels
  905. CL_CHECK((dequantize_row_q4_0_cl = clCreateKernel(program, "dequantize_row_q4_0", &err), err));
  906. CL_CHECK((dequantize_row_q4_1_cl = clCreateKernel(program, "dequantize_row_q4_1", &err), err));
  907. CL_CHECK((dequantize_row_q5_0_cl = clCreateKernel(program, "dequantize_row_q5_0", &err), err));
  908. CL_CHECK((dequantize_row_q5_1_cl = clCreateKernel(program, "dequantize_row_q5_1", &err), err));
  909. CL_CHECK((dequantize_row_q8_0_cl = clCreateKernel(program, "dequantize_row_q8_0", &err), err));
  910. CL_CHECK((dequantize_row_q8_0_cl = clCreateKernel(program, "dequantize_row_q8_0", &err), err));
  911. CL_CHECK((dequantize_block_q2_k_cl = clCreateKernel(program, "dequantize_block_q2_K", &err), err));
  912. CL_CHECK((dequantize_block_q3_k_cl = clCreateKernel(program, "dequantize_block_q3_K", &err), err));
  913. CL_CHECK((dequantize_block_q4_k_cl = clCreateKernel(program, "dequantize_block_q4_K", &err), err));
  914. CL_CHECK((dequantize_block_q5_k_cl = clCreateKernel(program, "dequantize_block_q5_K", &err), err));
  915. CL_CHECK((dequantize_block_q6_k_cl = clCreateKernel(program, "dequantize_block_q6_K", &err), err));
  916. // dequant mul mat kernel
  917. CL_CHECK((dequantize_mul_mat_vec_q4_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_0", &err), err));
  918. CL_CHECK((dequantize_mul_mat_vec_q4_1_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_1", &err), err));
  919. CL_CHECK((dequantize_mul_mat_vec_q5_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_0", &err), err));
  920. CL_CHECK((dequantize_mul_mat_vec_q5_1_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_1", &err), err));
  921. CL_CHECK((dequantize_mul_mat_vec_q8_0_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q8_0", &err), err));
  922. CL_CHECK((convert_mul_mat_vec_f16_cl = clCreateKernel(program, "convert_mul_mat_vec_f16", &err), err));
  923. CL_CHECK((dequantize_mul_mat_vec_q2_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q2_K", &err), err));
  924. CL_CHECK((dequantize_mul_mat_vec_q3_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q3_K", &err), err));
  925. CL_CHECK((dequantize_mul_mat_vec_q4_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q4_K", &err), err));
  926. CL_CHECK((dequantize_mul_mat_vec_q5_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q5_K", &err), err));
  927. CL_CHECK((dequantize_mul_mat_vec_q6_K_cl = clCreateKernel(program, "dequantize_mul_mat_vec_q6_K", &err), err));
  928. // mul kernel
  929. CL_CHECK((mul_f32_cl = clCreateKernel(program, "mul_f32", &err), err));
  930. }
  931. static cl_kernel* ggml_get_to_fp32_cl(ggml_type type) {
  932. switch (type) {
  933. case GGML_TYPE_Q4_0:
  934. return &dequantize_row_q4_0_cl;
  935. case GGML_TYPE_Q4_1:
  936. return &dequantize_row_q4_1_cl;
  937. case GGML_TYPE_Q5_0:
  938. return &dequantize_row_q5_0_cl;
  939. case GGML_TYPE_Q5_1:
  940. return &dequantize_row_q5_1_cl;
  941. case GGML_TYPE_Q8_0:
  942. return &dequantize_row_q8_0_cl;
  943. case GGML_TYPE_Q2_K:
  944. return &dequantize_block_q2_k_cl;
  945. case GGML_TYPE_Q3_K:
  946. return &dequantize_block_q3_k_cl;
  947. case GGML_TYPE_Q4_K:
  948. return &dequantize_block_q4_k_cl;
  949. case GGML_TYPE_Q5_K:
  950. return &dequantize_block_q5_k_cl;
  951. case GGML_TYPE_Q6_K:
  952. return &dequantize_block_q6_k_cl;
  953. case GGML_TYPE_F16:
  954. return &convert_row_f16_cl;
  955. default:
  956. return nullptr;
  957. }
  958. }
  959. static size_t ggml_cl_global_denom(ggml_type type) {
  960. switch (type) {
  961. case GGML_TYPE_Q4_0:
  962. case GGML_TYPE_Q4_1:
  963. case GGML_TYPE_Q5_0:
  964. case GGML_TYPE_Q5_1:
  965. case GGML_TYPE_Q8_0:
  966. return 1;
  967. case GGML_TYPE_Q2_K:
  968. case GGML_TYPE_Q3_K:
  969. return 4;
  970. case GGML_TYPE_Q4_K:
  971. return 8;
  972. case GGML_TYPE_Q5_K:
  973. case GGML_TYPE_Q6_K:
  974. return 4;
  975. case GGML_TYPE_F16:
  976. default:
  977. return 1;
  978. }
  979. }
  980. static size_t ggml_cl_local_size(ggml_type type) {
  981. switch (type) {
  982. case GGML_TYPE_Q4_0:
  983. case GGML_TYPE_Q4_1:
  984. case GGML_TYPE_Q5_0:
  985. case GGML_TYPE_Q5_1:
  986. case GGML_TYPE_Q8_0:
  987. return 0;
  988. case GGML_TYPE_Q2_K:
  989. case GGML_TYPE_Q3_K:
  990. return 64;
  991. case GGML_TYPE_Q4_K:
  992. return 32;
  993. case GGML_TYPE_Q5_K:
  994. case GGML_TYPE_Q6_K:
  995. return 64;
  996. case GGML_TYPE_F16:
  997. default:
  998. return 0;
  999. }
  1000. }
  1001. static cl_kernel* ggml_get_dequantize_mul_mat_vec_cl(ggml_type type) {
  1002. switch (type) {
  1003. case GGML_TYPE_Q4_0:
  1004. return &dequantize_mul_mat_vec_q4_0_cl;
  1005. case GGML_TYPE_Q4_1:
  1006. return &dequantize_mul_mat_vec_q4_1_cl;
  1007. case GGML_TYPE_Q5_0:
  1008. return &dequantize_mul_mat_vec_q5_0_cl;
  1009. case GGML_TYPE_Q5_1:
  1010. return &dequantize_mul_mat_vec_q5_1_cl;
  1011. case GGML_TYPE_Q8_0:
  1012. return &dequantize_mul_mat_vec_q8_0_cl;
  1013. case GGML_TYPE_F16:
  1014. return &convert_mul_mat_vec_f16_cl;
  1015. case GGML_TYPE_Q2_K:
  1016. return &dequantize_mul_mat_vec_q2_K_cl;
  1017. case GGML_TYPE_Q3_K:
  1018. return &dequantize_mul_mat_vec_q3_K_cl;
  1019. case GGML_TYPE_Q4_K:
  1020. return &dequantize_mul_mat_vec_q4_K_cl;
  1021. case GGML_TYPE_Q5_K:
  1022. return &dequantize_mul_mat_vec_q5_K_cl;
  1023. case GGML_TYPE_Q6_K:
  1024. return &dequantize_mul_mat_vec_q6_K_cl;
  1025. default:
  1026. return nullptr;
  1027. }
  1028. }
  1029. // buffer pool for cl
  1030. #define MAX_CL_BUFFERS 256
  1031. struct scoped_spin_lock {
  1032. std::atomic_flag& lock;
  1033. scoped_spin_lock(std::atomic_flag& lock) : lock(lock) {
  1034. while (lock.test_and_set(std::memory_order_acquire)) {
  1035. ; // spin
  1036. }
  1037. }
  1038. ~scoped_spin_lock() {
  1039. lock.clear(std::memory_order_release);
  1040. }
  1041. scoped_spin_lock(const scoped_spin_lock&) = delete;
  1042. scoped_spin_lock& operator=(const scoped_spin_lock&) = delete;
  1043. };
  1044. struct cl_buffer {
  1045. cl_mem mem;
  1046. size_t size = 0;
  1047. };
  1048. static cl_buffer g_cl_buffer_pool[MAX_CL_BUFFERS];
  1049. static std::atomic_flag g_cl_pool_lock = ATOMIC_FLAG_INIT;
  1050. static cl_mem ggml_cl_pool_malloc(size_t size, size_t * actual_size) {
  1051. scoped_spin_lock lock(g_cl_pool_lock);
  1052. cl_int err;
  1053. int best_i = -1;
  1054. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  1055. int worst_i = -1;
  1056. size_t worst_size = 0; //largest unused buffer seen so far
  1057. for (int i = 0; i < MAX_CL_BUFFERS; ++i) {
  1058. cl_buffer &b = g_cl_buffer_pool[i];
  1059. if (b.size > 0 && b.size >= size && b.size < best_size)
  1060. {
  1061. best_i = i;
  1062. best_size = b.size;
  1063. }
  1064. if (b.size > 0 && b.size > worst_size)
  1065. {
  1066. worst_i = i;
  1067. worst_size = b.size;
  1068. }
  1069. }
  1070. if(best_i!=-1) //found the smallest buffer that fits our needs
  1071. {
  1072. cl_buffer& b = g_cl_buffer_pool[best_i];
  1073. cl_mem mem = b.mem;
  1074. *actual_size = b.size;
  1075. b.size = 0;
  1076. return mem;
  1077. }
  1078. if(worst_i!=-1) //no buffer that fits our needs, resize largest one to save memory
  1079. {
  1080. cl_buffer& b = g_cl_buffer_pool[worst_i];
  1081. cl_mem mem = b.mem;
  1082. b.size = 0;
  1083. clReleaseMemObject(mem);
  1084. }
  1085. cl_mem mem;
  1086. CL_CHECK((mem = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err), err));
  1087. *actual_size = size;
  1088. return mem;
  1089. }
  1090. static void ggml_cl_pool_free(cl_mem mem, size_t size) {
  1091. scoped_spin_lock lock(g_cl_pool_lock);
  1092. for (int i = 0; i < MAX_CL_BUFFERS; ++i) {
  1093. cl_buffer& b = g_cl_buffer_pool[i];
  1094. if (b.size == 0) {
  1095. b.mem = mem;
  1096. b.size = size;
  1097. return;
  1098. }
  1099. }
  1100. fprintf(stderr, "WARNING: cl buffer pool full, increase MAX_CL_BUFFERS\n");
  1101. clReleaseMemObject(mem);
  1102. }
  1103. void ggml_cl_free_data(const struct ggml_tensor* tensor) {
  1104. if (tensor->backend != GGML_BACKEND_GPU) {
  1105. return;
  1106. }
  1107. cl_mem mem = (cl_mem)tensor->extra;
  1108. clReleaseMemObject(mem);
  1109. }
  1110. 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) {
  1111. cl_int err;
  1112. const uint64_t ne0 = src->ne[0];
  1113. const uint64_t ne1 = src->ne[1];
  1114. const uint64_t nb0 = src->nb[0];
  1115. const uint64_t nb1 = src->nb[1];
  1116. const uint64_t nb2 = src->nb[2];
  1117. const uint64_t nb3 = src->nb[3];
  1118. const enum ggml_type type = src->type;
  1119. const size_t ts = ggml_type_size(type);
  1120. const size_t bs = ggml_blck_size(type);
  1121. const uint64_t row_size = ts*ne0/bs;
  1122. const char * x = (const char *) src->data + i2*nb2 + i3*nb3;
  1123. if (nb0 == ts && nb1 == row_size) {
  1124. return clEnqueueWriteBuffer(queue, dst, CL_FALSE, offset, ne1*row_size, x, 0, NULL, ev);
  1125. }
  1126. if (nb0 == ts) {
  1127. const size_t buffer_origin[3] = { offset, 0, 0 };
  1128. const size_t host_origin[3] = { 0, 0, 0 };
  1129. const size_t region[3] = { row_size, ne1, 1 };
  1130. return clEnqueueWriteBufferRect(queue, dst, CL_FALSE, buffer_origin, host_origin, region, row_size, 0, nb1, 0, x, 0, NULL, ev);
  1131. }
  1132. std::vector<cl_event> events;
  1133. if (ev && ne1>1) events.reserve(ne1-1);
  1134. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1135. // pretend the row is a matrix with cols=1
  1136. const size_t buffer_origin[3] = { offset + i1*row_size, 0, 0 };
  1137. const size_t host_origin[3] = { 0, 0, 0 };
  1138. const size_t region[3] = { ts, ne0/bs, 1 };
  1139. // if an event is requested, make the last write wait for all previous writes to complete
  1140. if (ev && i1) {
  1141. events.push_back(*ev);
  1142. }
  1143. cl_uint nevents = i1 == ne1-1 ? events.size() : 0U;
  1144. err = clEnqueueWriteBufferRect(queue, dst, CL_FALSE, buffer_origin, host_origin, region, ts, 0, nb0, 0, x + i1*nb1, nevents, nevents ? events.data() : nullptr, ev);
  1145. if (err != CL_SUCCESS) {
  1146. for (auto event : events) {
  1147. clReleaseEvent(event);
  1148. }
  1149. return err;
  1150. }
  1151. }
  1152. for (auto event : events) {
  1153. CL_CHECK(clReleaseEvent(event));
  1154. }
  1155. return CL_SUCCESS;
  1156. }
  1157. static void ggml_cl_mul_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1158. GGML_ASSERT(src1->backend == GGML_BACKEND_GPU);
  1159. const int64_t ne00 = src0->ne[0];
  1160. const int64_t ne01 = src0->ne[1];
  1161. const int64_t ne02 = src0->ne[2];
  1162. const int64_t ne03 = src0->ne[3];
  1163. const int64_t ne10 = src1->ne[0];
  1164. const int64_t ne11 = src1->ne[1];
  1165. const int64_t ne12 = src1->ne[2];
  1166. const int64_t ne13 = src1->ne[3];
  1167. const int nb2 = dst->nb[2];
  1168. const int nb3 = dst->nb[3];
  1169. size_t x_size;
  1170. size_t d_size;
  1171. cl_mem d_X = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &x_size); // src0
  1172. cl_mem d_Y = (cl_mem) src1->extra; // src1 is already on device, broadcasted.
  1173. cl_mem d_D = ggml_cl_pool_malloc(ne00 * ne01 * sizeof(float), &d_size); // dst
  1174. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1175. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1176. cl_event ev;
  1177. // copy src0 to device
  1178. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, &ev));
  1179. const int64_t i13 = i03%ne13;
  1180. const int64_t i12 = i02%ne12;
  1181. const int i1 = i13*ne12*ne11 + i12*ne11;
  1182. cl_int x_offset = 0;
  1183. cl_int y_offset = i1*ne10;
  1184. cl_int d_offset = 0;
  1185. size_t global = ne00 * ne01;
  1186. cl_int ky = ne10 * ne11;
  1187. CL_CHECK(clSetKernelArg(mul_f32_cl, 0, sizeof(cl_mem), &d_X));
  1188. CL_CHECK(clSetKernelArg(mul_f32_cl, 1, sizeof(cl_int), &x_offset));
  1189. CL_CHECK(clSetKernelArg(mul_f32_cl, 2, sizeof(cl_mem), &d_Y));
  1190. CL_CHECK(clSetKernelArg(mul_f32_cl, 3, sizeof(cl_int), &y_offset));
  1191. CL_CHECK(clSetKernelArg(mul_f32_cl, 4, sizeof(cl_mem), &d_D));
  1192. CL_CHECK(clSetKernelArg(mul_f32_cl, 5, sizeof(cl_int), &d_offset));
  1193. CL_CHECK(clSetKernelArg(mul_f32_cl, 6, sizeof(cl_int), &ky));
  1194. CL_CHECK(clEnqueueNDRangeKernel(queue, mul_f32_cl, 1, NULL, &global, NULL, 1, &ev, NULL));
  1195. CL_CHECK(clReleaseEvent(ev));
  1196. CL_CHECK(clFinish(queue));
  1197. // copy dst to host
  1198. float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
  1199. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * ne00*ne01, d, 0, NULL, NULL));
  1200. }
  1201. }
  1202. ggml_cl_pool_free(d_X, x_size);
  1203. ggml_cl_pool_free(d_D, d_size);
  1204. }
  1205. void ggml_cl_mul(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  1206. GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
  1207. ggml_cl_mul_f32(src0, src1, dst);
  1208. }
  1209. static void ggml_cl_mul_mat_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1210. const int64_t ne00 = src0->ne[0];
  1211. const int64_t ne01 = src0->ne[1];
  1212. const int64_t ne02 = src0->ne[2];
  1213. const int64_t ne03 = src0->ne[3];
  1214. const int64_t ne10 = src1->ne[0];
  1215. const int64_t ne11 = src1->ne[1];
  1216. const int64_t ne12 = src1->ne[2];
  1217. const int64_t ne13 = src1->ne[3];
  1218. const int nb2 = dst->nb[2];
  1219. const int nb3 = dst->nb[3];
  1220. const int64_t r2 = ne12 / ne02;
  1221. const int64_t r3 = ne13 / ne03;
  1222. const float alpha = 1.0f;
  1223. const float beta = 0.0f;
  1224. const int x_ne = ne01 * ne00;
  1225. const int y_ne = ne11 * ne10;
  1226. const int d_ne = ne11 * ne01;
  1227. size_t x_size;
  1228. size_t y_size;
  1229. size_t d_size;
  1230. cl_mem d_X;
  1231. if (src0->backend == GGML_BACKEND_GPU) { // NOLINT
  1232. d_X = (cl_mem) src0->extra;
  1233. } else {
  1234. d_X = ggml_cl_pool_malloc(sizeof(float) * x_ne, &x_size);
  1235. }
  1236. cl_mem d_Y = src1->backend == GGML_BACKEND_GPU ? (cl_mem) src1->extra : ggml_cl_pool_malloc(sizeof(float) * y_ne, &y_size);
  1237. cl_mem d_D = dst->backend == GGML_BACKEND_GPU ? (cl_mem) dst->extra : ggml_cl_pool_malloc(sizeof(float) * d_ne, &d_size);
  1238. size_t x_offset = 0;
  1239. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1240. // TODO: copy src0 here when r3>1
  1241. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1242. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1243. if (src0->backend == GGML_BACKEND_GPU) {
  1244. x_offset = (i03 * ne02 + i02) * x_ne;
  1245. } else {
  1246. // copy src0 to device
  1247. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, NULL));
  1248. }
  1249. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1250. // copy src1 to device
  1251. if (src1->backend == GGML_BACKEND_CPU) {
  1252. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, NULL));
  1253. }
  1254. CL_CHECK(clFinish(queue));
  1255. // compute
  1256. cl_event ev_sgemm;
  1257. clblast::StatusCode status = clblast::Gemm<cl_float>(clblast::Layout::kColMajor,
  1258. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1259. ne01, ne11, ne10,
  1260. alpha,
  1261. d_X, x_offset, ne00,
  1262. d_Y, 0, ne10,
  1263. beta,
  1264. d_D, 0, ne01,
  1265. &queue, &ev_sgemm);
  1266. if (status != clblast::StatusCode::kSuccess) {
  1267. GGML_ASSERT(false);
  1268. }
  1269. // copy dst to host
  1270. if (dst->backend == GGML_BACKEND_CPU) {
  1271. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1272. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * d_ne, d, 1, &ev_sgemm, NULL));
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. if (src0->backend != GGML_BACKEND_GPU) {
  1279. ggml_cl_pool_free(d_X, x_size);
  1280. }
  1281. if (src1->backend != GGML_BACKEND_GPU) {
  1282. ggml_cl_pool_free(d_Y, y_size);
  1283. }
  1284. if (dst->backend != GGML_BACKEND_GPU) {
  1285. ggml_cl_pool_free(d_D, d_size);
  1286. }
  1287. }
  1288. static void ggml_cl_mul_mat_f16(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, void * wdata, size_t wsize) {
  1289. GGML_ASSERT(fp16_support);
  1290. const int64_t ne00 = src0->ne[0];
  1291. const int64_t ne01 = src0->ne[1];
  1292. const int64_t ne02 = src0->ne[2];
  1293. const int64_t ne03 = src0->ne[3];
  1294. const int64_t ne10 = src1->ne[0];
  1295. const int64_t ne11 = src1->ne[1];
  1296. const int64_t ne12 = src1->ne[2];
  1297. const int64_t ne13 = src1->ne[3];
  1298. const int nb10 = src1->nb[0];
  1299. const int nb11 = src1->nb[1];
  1300. const int nb12 = src1->nb[2];
  1301. const int nb13 = src1->nb[3];
  1302. const int nb2 = dst->nb[2];
  1303. const int nb3 = dst->nb[3];
  1304. const int64_t r2 = ne12 / ne02;
  1305. const int64_t r3 = ne13 / ne03;
  1306. const ggml_fp16_t alpha = ggml_fp32_to_fp16(1.0f);
  1307. const ggml_fp16_t beta = ggml_fp32_to_fp16(0.0f);
  1308. const int x_ne = ne01 * ne00;
  1309. const int y_ne = ne11 * ne10;
  1310. const int d_ne = ne11 * ne01;
  1311. GGML_ASSERT(wsize >= sizeof(ggml_fp16_t) * y_ne);
  1312. GGML_ASSERT(wsize >= sizeof(ggml_fp16_t) * d_ne);
  1313. ggml_fp16_t * const tmp = (ggml_fp16_t *) wdata;
  1314. size_t x_size;
  1315. size_t y_size;
  1316. size_t d_size;
  1317. cl_mem d_X;
  1318. if (src0->backend == GGML_BACKEND_GPU) { // NOLINT
  1319. d_X = (cl_mem) src0->extra;
  1320. } else {
  1321. d_X = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * x_ne, &x_size);
  1322. }
  1323. cl_mem d_Y = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * y_ne, &y_size);
  1324. cl_mem d_D = ggml_cl_pool_malloc(sizeof(ggml_fp16_t) * d_ne, &d_size);
  1325. bool src1_cont_rows = nb10 == sizeof(float);
  1326. bool src1_cont_cols = (size_t)nb11 == ne11*sizeof(float);
  1327. size_t x_offset = 0;
  1328. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1329. // TODO: copy src0 here when r3>1
  1330. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1331. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1332. if (src0->backend == GGML_BACKEND_GPU) {
  1333. x_offset = (i03 * ne02 + i02) * x_ne;
  1334. } else {
  1335. // copy src0 to device
  1336. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_X, 0, src0, i03, i02, NULL));
  1337. }
  1338. // FIXME: convert on device
  1339. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1340. // convert src1 to fp16
  1341. // TODO: use multiple threads
  1342. char * src1i = (char *) src1->data + i13*nb13 + i12*nb12;
  1343. if (src1_cont_rows) {
  1344. if (src1_cont_cols) {
  1345. ggml_fp32_to_fp16_row((float *) src1i, tmp, ne10*ne11);
  1346. }
  1347. else {
  1348. for (int64_t i11 = 0; i11 < ne11; i11++) {
  1349. ggml_fp32_to_fp16_row((float *) (src1i + i11*nb11), tmp + i11*ne10, ne10);
  1350. }
  1351. }
  1352. }
  1353. else {
  1354. for (int64_t i11 = 0; i11 < ne11; i11++) {
  1355. for (int64_t i10 = 0; i10 < ne10; i10++) {
  1356. // very slow due to no inlining
  1357. tmp[i11*ne10 + i10] = ggml_fp32_to_fp16(*(float *) (src1i + i11*nb11 + i10*nb10));
  1358. }
  1359. }
  1360. }
  1361. // copy src1 to device
  1362. CL_CHECK(clEnqueueWriteBuffer(queue, d_Y, false, 0, sizeof(ggml_fp16_t) * y_ne, tmp, 0, NULL, NULL));
  1363. CL_CHECK(clFinish(queue));
  1364. // compute
  1365. cl_event ev_sgemm;
  1366. clblast::StatusCode status = clblast::Gemm<cl_half>(clblast::Layout::kColMajor,
  1367. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1368. ne01, ne11, ne10,
  1369. alpha,
  1370. d_X, x_offset, ne00,
  1371. d_Y, 0, ne10,
  1372. beta,
  1373. d_D, 0, ne01,
  1374. &queue, &ev_sgemm);
  1375. if (status != clblast::StatusCode::kSuccess) {
  1376. GGML_ASSERT(false);
  1377. }
  1378. // copy dst to host, then convert to float
  1379. if (dst->backend == GGML_BACKEND_CPU) {
  1380. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(ggml_fp16_t) * d_ne, tmp, 1, &ev_sgemm, NULL));
  1381. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1382. ggml_fp16_to_fp32_row(tmp, d, d_ne);
  1383. } else {
  1384. // FIXME: convert dst to fp32 on device
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. if (src0->backend != GGML_BACKEND_GPU) {
  1391. ggml_cl_pool_free(d_X, x_size);
  1392. }
  1393. ggml_cl_pool_free(d_Y, y_size);
  1394. ggml_cl_pool_free(d_D, d_size);
  1395. }
  1396. static void ggml_cl_mul_mat_q_f32(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  1397. const int64_t ne00 = src0->ne[0];
  1398. const int64_t ne01 = src0->ne[1];
  1399. const int64_t ne02 = src0->ne[2];
  1400. const int64_t ne03 = src0->ne[3];
  1401. const int64_t ne10 = src1->ne[0];
  1402. const int64_t ne11 = src1->ne[1];
  1403. const int64_t ne12 = src1->ne[2];
  1404. const int64_t ne13 = src1->ne[3];
  1405. const int nb2 = dst->nb[2];
  1406. const int nb3 = dst->nb[3];
  1407. const ggml_type type = src0->type;
  1408. const bool mul_mat_vec = ne11 == 1 && ne00%2 == 0;
  1409. const int64_t r2 = ne12 / ne02;
  1410. const int64_t r3 = ne13 / ne03;
  1411. const float alpha = 1.0f;
  1412. const float beta = 0.0f;
  1413. const int x_ne = ne01 * ne00;
  1414. const int y_ne = ne11 * ne10;
  1415. const int d_ne = ne11 * ne01;
  1416. const int x_bps = x_ne / ggml_blck_size(type); // blocks per 2D slice
  1417. const size_t q_sz = ggml_type_size(type) * x_bps;
  1418. size_t x_size;
  1419. size_t y_size;
  1420. size_t d_size;
  1421. size_t q_size;
  1422. cl_mem d_X;
  1423. if (!mul_mat_vec) {
  1424. d_X = ggml_cl_pool_malloc(sizeof(float) * x_ne, &x_size);
  1425. }
  1426. cl_mem d_Y = ggml_cl_pool_malloc(sizeof(float) * y_ne, &y_size);
  1427. cl_mem d_D = ggml_cl_pool_malloc(sizeof(float) * d_ne, &d_size);
  1428. cl_mem d_Q;
  1429. if (src0->backend == GGML_BACKEND_CPU) {
  1430. d_Q = ggml_cl_pool_malloc(q_sz, &q_size);
  1431. }
  1432. cl_kernel* to_fp32_cl = ggml_get_to_fp32_cl(type);
  1433. cl_kernel* dmmv = ggml_get_dequantize_mul_mat_vec_cl(type);
  1434. GGML_ASSERT(to_fp32_cl != nullptr);
  1435. const size_t global_denom = ggml_cl_global_denom(type);
  1436. const size_t local = mul_mat_vec ? CL_DMMV_LOCAL_SIZE : ggml_cl_local_size(type);
  1437. size_t ev_idx = 0;
  1438. std::vector<cl_event> events;
  1439. for (int64_t i03 = 0; i03 < ne03; i03++) {
  1440. // TODO: copy and dequantize src0 here when r3>1
  1441. for (int64_t i13 = i03 * r3, e13 = i13 + r3; i13 < e13; i13++) {
  1442. for (int64_t i02 = 0; i02 < ne02; i02++) {
  1443. // copy src0 to device if necessary
  1444. if (src0->backend == GGML_BACKEND_CPU) {
  1445. events.emplace_back();
  1446. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Q, 0, src0, i03, i02, events.data() + ev_idx++));
  1447. } else if (src0->backend == GGML_BACKEND_GPU) {
  1448. d_Q = (cl_mem) src0->extra;
  1449. } else {
  1450. GGML_ASSERT(false);
  1451. }
  1452. if (!mul_mat_vec) {
  1453. // convert src0 to fp32 on device
  1454. const size_t global = x_ne / global_denom;
  1455. const size_t offset = src0->backend == GGML_BACKEND_GPU ? (i03 * ne02 + i02) * x_bps : 0;
  1456. CL_CHECK(clSetKernelArg(*to_fp32_cl, 0, sizeof(cl_mem), &d_Q));
  1457. CL_CHECK(clSetKernelArg(*to_fp32_cl, 1, sizeof(cl_mem), &d_X));
  1458. CL_CHECK(clEnqueueNDRangeKernel(queue, *to_fp32_cl, 1, &offset, &global, local > 0 ? &local : NULL, events.size(), !events.empty() ? events.data() : NULL, NULL));
  1459. }
  1460. for (int64_t i12 = i02 * r2, e12 = i12 + r2; i12 < e12; i12++) {
  1461. if (mul_mat_vec) { // specialized dequantize_mul_mat_vec kernel
  1462. // copy src1 to device
  1463. events.emplace_back();
  1464. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, events.data() + ev_idx++));
  1465. // compute
  1466. const size_t global = ne01 * local;
  1467. const size_t offset = src0->backend == GGML_BACKEND_GPU ? (i03 * ne02 + i02) * x_bps : 0;
  1468. const cl_int ncols = ne00;
  1469. events.emplace_back();
  1470. CL_CHECK(clSetKernelArg(*dmmv, 0, sizeof(cl_mem), &d_Q));
  1471. CL_CHECK(clSetKernelArg(*dmmv, 1, sizeof(float) * local, NULL));
  1472. CL_CHECK(clSetKernelArg(*dmmv, 2, sizeof(cl_mem), &d_Y));
  1473. CL_CHECK(clSetKernelArg(*dmmv, 3, sizeof(cl_mem), &d_D));
  1474. CL_CHECK(clSetKernelArg(*dmmv, 4, sizeof(cl_int), &ncols));
  1475. CL_CHECK(clEnqueueNDRangeKernel(queue, *dmmv, 1, &offset, &global, &local, events.size() - 1, events.data(), events.data() + ev_idx++));
  1476. } else { // CLBlast matrix matrix multiplication
  1477. // copy src1 to device
  1478. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, d_Y, 0, src1, i13, i12, NULL));
  1479. // wait for conversion
  1480. CL_CHECK(clFinish(queue));
  1481. // compute
  1482. events.emplace_back();
  1483. clblast::StatusCode status = clblast::Gemm<cl_float>(clblast::Layout::kColMajor,
  1484. clblast::Transpose::kYes, clblast::Transpose::kNo,
  1485. ne01, ne11, ne10,
  1486. alpha,
  1487. d_X, 0, ne00,
  1488. d_Y, 0, ne10,
  1489. beta,
  1490. d_D, 0, ne01,
  1491. &queue, events.data() + ev_idx++);
  1492. if (status != clblast::StatusCode::kSuccess) {
  1493. GGML_ASSERT(false);
  1494. }
  1495. }
  1496. // copy dst to host
  1497. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  1498. CL_CHECK(clEnqueueReadBuffer(queue, d_D, true, 0, sizeof(float) * d_ne, d, 1, &events[events.size() - 1], NULL));
  1499. for (auto *event : events) {
  1500. clReleaseEvent(event);
  1501. }
  1502. ev_idx = 0;
  1503. events.clear();
  1504. }
  1505. }
  1506. }
  1507. }
  1508. if (!mul_mat_vec) {
  1509. ggml_cl_pool_free(d_X, x_size);
  1510. }
  1511. ggml_cl_pool_free(d_Y, y_size);
  1512. ggml_cl_pool_free(d_D, d_size);
  1513. if (src0->backend == GGML_BACKEND_CPU) {
  1514. ggml_cl_pool_free(d_Q, q_size);
  1515. }
  1516. }
  1517. bool ggml_cl_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) {
  1518. const int64_t ne10 = src1->ne[0];
  1519. const int64_t ne0 = dst->ne[0];
  1520. const int64_t ne1 = dst->ne[1];
  1521. // TODO: find the optimal values for these
  1522. if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) &&
  1523. src1->type == GGML_TYPE_F32 &&
  1524. dst->type == GGML_TYPE_F32 &&
  1525. ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32) || src0->backend == GGML_BACKEND_GPU)) {
  1526. return true;
  1527. }
  1528. return false;
  1529. }
  1530. static bool ggml_cl_mul_mat_use_f16(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * /* dst */) {
  1531. // If device doesn't support FP16
  1532. if (!fp16_support) {
  1533. return false;
  1534. }
  1535. size_t src0_sz = ggml_nbytes(src0);
  1536. size_t src1_sz = ggml_nbytes(src1);
  1537. // mul_mat_q: src0 is converted to fp32 on device
  1538. size_t mul_mat_q_transfer = src0_sz + src1_sz;
  1539. // mul_mat_f16: src1 is converted to fp16 on cpu
  1540. size_t mul_mat_f16_transfer = src0_sz + sizeof(ggml_fp16_t) * ggml_nelements(src1);
  1541. // choose the smaller one to transfer to the device
  1542. // TODO: this is not always the best choice due to the overhead of converting to fp16
  1543. return mul_mat_f16_transfer < mul_mat_q_transfer;
  1544. }
  1545. void ggml_cl_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst, void * wdata, size_t wsize) {
  1546. GGML_ASSERT(ggml_cl_can_mul_mat(src0, src1, dst));
  1547. if (src0->type == GGML_TYPE_F32) {
  1548. ggml_cl_mul_mat_f32(src0, src1, dst);
  1549. }
  1550. else if (src0->type == GGML_TYPE_F16) {
  1551. if (ggml_cl_mul_mat_use_f16(src0, src1, dst)) {
  1552. ggml_cl_mul_mat_f16(src0, src1, dst, wdata, wsize);
  1553. }
  1554. else {
  1555. ggml_cl_mul_mat_q_f32(src0, src1, dst);
  1556. }
  1557. }
  1558. else if (ggml_is_quantized(src0->type)) {
  1559. ggml_cl_mul_mat_q_f32(src0, src1, dst);
  1560. }
  1561. else {
  1562. GGML_ASSERT(false);
  1563. }
  1564. }
  1565. size_t ggml_cl_mul_mat_get_wsize(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  1566. if (src0->type == GGML_TYPE_F16 && ggml_cl_mul_mat_use_f16(src0, src1, dst)) {
  1567. return sizeof(ggml_fp16_t) * std::max(src1->ne[0] * src1->ne[1], dst->ne[0] * dst->ne[1]);
  1568. }
  1569. return 0;
  1570. }
  1571. void ggml_cl_transform_tensor(void * data, ggml_tensor * tensor) {
  1572. const int64_t ne0 = tensor->ne[0];
  1573. const int64_t ne1 = tensor->ne[1];
  1574. const int64_t ne2 = tensor->ne[2];
  1575. const int64_t ne3 = tensor->ne[3];
  1576. const ggml_type type = tensor->type;
  1577. const size_t s_sz = ggml_type_size(type) * (size_t) (ne0 * ne1 / ggml_blck_size(type));
  1578. const size_t q_sz = s_sz * (size_t) (ne2 * ne3);
  1579. size_t q_size;
  1580. cl_mem dst = ggml_cl_pool_malloc(q_sz, &q_size);
  1581. tensor->data = data;
  1582. // copy tensor to device
  1583. size_t offset = 0;
  1584. for (int64_t i3 = 0; i3 < ne3; i3++) {
  1585. for (int64_t i2 = 0; i2 < ne2; i2++) {
  1586. CL_CHECK(ggml_cl_h2d_tensor_2d(queue, dst, offset, tensor, i3, i2, NULL));
  1587. offset += s_sz;
  1588. }
  1589. }
  1590. CL_CHECK(clFinish(queue));
  1591. tensor->extra = dst;
  1592. GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
  1593. }
  1594. // ggml-backend
  1595. // buffer
  1596. struct ggml_backend_opencl_buffer_context {
  1597. ~ggml_backend_opencl_buffer_context() {
  1598. if (buffer) {
  1599. clReleaseMemObject(buffer);
  1600. }
  1601. for (auto * sub_buffer : sub_buffers) {
  1602. clReleaseMemObject(sub_buffer);
  1603. }
  1604. }
  1605. cl_mem buffer;
  1606. std::vector<cl_mem> sub_buffers;
  1607. };
  1608. static void * const cl_ptr_base = (void *)(uintptr_t) 0x1000;
  1609. static const char * ggml_backend_opencl_buffer_get_name(ggml_backend_buffer_t buffer) {
  1610. return "OpenCL";
  1611. GGML_UNUSED(buffer);
  1612. }
  1613. static void ggml_backend_opencl_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1614. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1615. delete ctx;
  1616. }
  1617. static void * ggml_backend_opencl_buffer_get_base(ggml_backend_buffer_t buffer) {
  1618. return cl_ptr_base;
  1619. GGML_UNUSED(buffer);
  1620. }
  1621. static void ggml_backend_opencl_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  1622. if (tensor->view_src != NULL && tensor->view_offs == 0) {
  1623. tensor->extra = tensor->view_src->extra;
  1624. } else {
  1625. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1626. cl_buffer_region region = {(size_t)((char *)tensor->data - (char *)cl_ptr_base), ggml_nbytes(tensor)};
  1627. cl_int err;
  1628. cl_mem sub_buffer = clCreateSubBuffer(ctx->buffer, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, &region, &err);
  1629. CL_CHECK(err);
  1630. ctx->sub_buffers.push_back(sub_buffer);
  1631. tensor->extra = sub_buffer;
  1632. }
  1633. tensor->backend = GGML_BACKEND_GPU;
  1634. }
  1635. 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) {
  1636. cl_mem tensor_buffer = (cl_mem) tensor->extra;
  1637. CL_CHECK(clEnqueueWriteBuffer(queue, tensor_buffer, true, offset, size, data, 0, NULL, NULL));
  1638. CL_CHECK(clFinish(queue));
  1639. GGML_UNUSED(buffer);
  1640. }
  1641. 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) {
  1642. cl_mem tensor_buffer = (cl_mem) tensor->extra;
  1643. CL_CHECK(clEnqueueReadBuffer(queue, tensor_buffer, true, offset, size, data, 0, NULL, NULL));
  1644. CL_CHECK(clFinish(queue));
  1645. GGML_UNUSED(buffer);
  1646. }
  1647. static void ggml_backend_opencl_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  1648. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1649. CL_CHECK(clEnqueueFillBuffer(queue, ctx->buffer, &value, sizeof(value), 0, buffer->size, 0, NULL, NULL));
  1650. CL_CHECK(clFinish(queue));
  1651. }
  1652. static void ggml_backend_opencl_buffer_reset(ggml_backend_buffer_t buffer) {
  1653. ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context;
  1654. for (auto * sub_buffer : ctx->sub_buffers) {
  1655. clReleaseMemObject(sub_buffer);
  1656. }
  1657. ctx->sub_buffers.clear();
  1658. }
  1659. static ggml_backend_buffer_i ggml_backend_opencl_buffer_interface = {
  1660. /* .get_name = */ ggml_backend_opencl_buffer_get_name,
  1661. /* .free_buffer = */ ggml_backend_opencl_buffer_free_buffer,
  1662. /* .get_base = */ ggml_backend_opencl_buffer_get_base,
  1663. /* .init_tensor = */ ggml_backend_opencl_buffer_init_tensor,
  1664. /* .set_tensor = */ ggml_backend_opencl_buffer_set_tensor,
  1665. /* .get_tensor = */ ggml_backend_opencl_buffer_get_tensor,
  1666. /* .cpy_tensor = */ NULL,
  1667. /* .clear = */ ggml_backend_opencl_buffer_clear,
  1668. /* .reset = */ ggml_backend_opencl_buffer_reset,
  1669. };
  1670. // buffer type
  1671. static const char * ggml_backend_opencl_buffer_type_name(ggml_backend_buffer_type_t buffer_type) {
  1672. return "OpenCL";
  1673. GGML_UNUSED(buffer_type);
  1674. }
  1675. static ggml_backend_buffer_t ggml_backend_opencl_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buffer_type, size_t size) {
  1676. ggml_cl_init();
  1677. cl_int err;
  1678. cl_mem mem = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err);
  1679. if (err != CL_SUCCESS) {
  1680. fprintf(stderr, "%s: failed to allocate %.2f MiB\n", __func__, size / 1024.0 / 1024.0);
  1681. return nullptr;
  1682. }
  1683. ggml_backend_opencl_buffer_context * ctx = new ggml_backend_opencl_buffer_context{mem, {}};
  1684. return ggml_backend_buffer_init(buffer_type, ggml_backend_opencl_buffer_interface, ctx, size);
  1685. }
  1686. static size_t ggml_backend_opencl_buffer_type_get_alignment(ggml_backend_buffer_type_t buffer_type) {
  1687. // FIXME: not thread safe, device may not be initialized yet
  1688. static cl_uint alignment = -1;
  1689. if (alignment == (cl_uint)-1) {
  1690. ggml_cl_init();
  1691. clGetDeviceInfo(device, CL_DEVICE_MEM_BASE_ADDR_ALIGN, sizeof(cl_uint), &alignment, NULL);
  1692. }
  1693. return alignment;
  1694. GGML_UNUSED(buffer_type);
  1695. }
  1696. static bool ggml_backend_opencl_buffer_type_supports_backend(ggml_backend_buffer_type_t buffer_type, ggml_backend_t backend) {
  1697. //return ggml_backend_is_opencl(backend); // opencl must be used through the cpu backend
  1698. return ggml_backend_is_cpu(backend);
  1699. GGML_UNUSED(buffer_type);
  1700. }
  1701. static ggml_backend_buffer_type_i ggml_backend_opencl_buffer_type_interface = {
  1702. /* .get_name = */ ggml_backend_opencl_buffer_type_name,
  1703. /* .alloc_buffer = */ ggml_backend_opencl_buffer_type_alloc_buffer,
  1704. /* .get_alignment = */ ggml_backend_opencl_buffer_type_get_alignment,
  1705. /* .get_alloc_size = */ NULL,
  1706. /* .supports_backend = */ ggml_backend_opencl_buffer_type_supports_backend,
  1707. /* .is_host = */ NULL,
  1708. };
  1709. ggml_backend_buffer_type_t ggml_backend_opencl_buffer_type() {
  1710. static ggml_backend_buffer_type buffer_type = {
  1711. /* .iface = */ ggml_backend_opencl_buffer_type_interface,
  1712. /* .context = */ nullptr,
  1713. };
  1714. return &buffer_type;
  1715. }
  1716. #if 0
  1717. // host buffer type
  1718. static const char * ggml_backend_opencl_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  1719. return "CL_Host";
  1720. GGML_UNUSED(buft);
  1721. }
  1722. static const char * ggml_backend_opencl_host_buffer_name(ggml_backend_buffer_t buffer) {
  1723. return "CL_Host";
  1724. GGML_UNUSED(buffer);
  1725. }
  1726. static void ggml_backend_opencl_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1727. ggml_cl_host_free(buffer->context);
  1728. }
  1729. static ggml_backend_buffer_t ggml_backend_opencl_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  1730. void * ptr = ggml_cl_host_malloc(size);
  1731. if (ptr == nullptr) {
  1732. // fallback to cpu buffer
  1733. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  1734. }
  1735. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  1736. buffer->buft = buft;
  1737. buffer->iface.get_name = ggml_backend_opencl_host_buffer_name;
  1738. buffer->iface.free_buffer = ggml_backend_opencl_host_buffer_free_buffer;
  1739. return buffer;
  1740. }
  1741. ggml_backend_buffer_type_t ggml_backend_opencl_host_buffer_type() {
  1742. static struct ggml_backend_buffer_type ggml_backend_opencl_buffer_type_host = {
  1743. /* .iface = */ {
  1744. /* .get_name = */ ggml_backend_opencl_host_buffer_type_name,
  1745. /* .alloc_buffer = */ ggml_backend_opencl_host_buffer_type_alloc_buffer,
  1746. /* .get_alignment = */ ggml_backend_cpu_buffer_type()->iface.get_alignment,
  1747. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  1748. /* .supports_backend = */ ggml_backend_cpu_buffer_type()->iface.supports_backend,
  1749. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  1750. },
  1751. /* .context = */ nullptr,
  1752. };
  1753. return &ggml_backend_opencl_buffer_type_host;
  1754. }
  1755. // backend
  1756. static const char * ggml_backend_opencl_name(ggml_backend_t backend) {
  1757. return "OpenCL";
  1758. GGML_UNUSED(backend);
  1759. }
  1760. static void ggml_backend_opencl_free(ggml_backend_t backend) {
  1761. GGML_UNUSED(backend);
  1762. }
  1763. static ggml_backend_buffer_type_t ggml_backend_opencl_get_default_buffer_type(ggml_backend_t backend) {
  1764. return ggml_backend_opencl_buffer_type();
  1765. GGML_UNUSED(backend);
  1766. }
  1767. static bool ggml_backend_opencl_graph_compute(ggml_backend_t backend, ggml_cgraph * graph) {
  1768. for (int i = 0; i < graph->n_nodes; ++i) {
  1769. ggml_tensor * node = graph->nodes[i];
  1770. switch (node->op) {
  1771. case GGML_OP_MUL_MAT:
  1772. ggml_cl_mul_mat(node->src[0], node->src[1], node, nullptr, 0);
  1773. break;
  1774. case GGML_OP_MUL:
  1775. ggml_cl_mul(node->src[0], node->src[1], node);
  1776. break;
  1777. default:
  1778. GGML_ASSERT(false);
  1779. }
  1780. }
  1781. return true;
  1782. GGML_UNUSED(backend);
  1783. }
  1784. static bool ggml_backend_opencl_supports_op(ggml_backend_t backend, const ggml_tensor * op) {
  1785. switch (op->op) {
  1786. case GGML_OP_MUL_MAT:
  1787. return ggml_cl_can_mul_mat(op->src[0], op->src[1], op);
  1788. case GGML_OP_MUL:
  1789. // return ggml_can_repeat_rows(op->src[1], op->src[0]);
  1790. return true;
  1791. default:
  1792. return false;
  1793. }
  1794. GGML_UNUSED(backend);
  1795. }
  1796. static ggml_backend_i opencl_backend_i = {
  1797. /* .get_name = */ ggml_backend_opencl_name,
  1798. /* .free = */ ggml_backend_opencl_free,
  1799. /* .get_default_buffer_type = */ ggml_backend_opencl_get_default_buffer_type,
  1800. /* .set_tensor_async = */ NULL,
  1801. /* .get_tensor_async = */ NULL,
  1802. /* .cpy_tensor_from_async = */ NULL,
  1803. /* .cpy_tensor_to_async = */ NULL,
  1804. /* .synchronize = */ NULL,
  1805. /* .graph_plan_create = */ NULL,
  1806. /* .graph_plan_free = */ NULL,
  1807. /* .graph_plan_compute = */ NULL,
  1808. /* .graph_compute = */ ggml_backend_opencl_graph_compute,
  1809. /* .supports_op = */ ggml_backend_opencl_supports_op,
  1810. };
  1811. ggml_backend_t ggml_backend_opencl_init() {
  1812. ggml_backend_t backend = new ggml_backend {
  1813. /* .interface = */ opencl_backend_i,
  1814. /* .context = */ nullptr
  1815. };
  1816. return backend;
  1817. }
  1818. bool ggml_backend_is_opencl(ggml_backend_t backend) {
  1819. return backend && backend->iface.get_name == ggml_backend_opencl_name;
  1820. }
  1821. #endif