ggml_vk_generate_shaders.py 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149
  1. #!/usr/bin/env python
  2. import logging
  3. import argparse
  4. import asyncio
  5. import os
  6. import sys
  7. from tempfile import gettempdir, NamedTemporaryFile
  8. logger = logging.getLogger("ggml-vk-generate-shaders")
  9. shader_f32 = """
  10. #define FLOAT_TYPE float
  11. """
  12. shader_f16 = """
  13. #extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
  14. #define FLOAT_TYPE float16_t
  15. """
  16. shader_int8_ext = """
  17. #extension GL_EXT_shader_explicit_arithmetic_types_int8 : require
  18. """
  19. # Type-specific defines
  20. shader_f32_defines = """
  21. #define QUANT_K 1
  22. #define QUANT_R 1
  23. #define A_TYPE float
  24. """
  25. shader_f16_defines = """
  26. #define QUANT_K 1
  27. #define QUANT_R 1
  28. #define A_TYPE float16_t
  29. """
  30. shader_q4_0_defines = """
  31. #define QUANT_K 32
  32. #define QUANT_R 2
  33. struct block_q4_0
  34. {
  35. float16_t d;
  36. uint8_t qs[16];
  37. };
  38. #define A_TYPE block_q4_0
  39. """
  40. shader_q4_1_defines = """
  41. #define QUANT_K 32
  42. #define QUANT_R 2
  43. struct block_q4_1
  44. {
  45. float16_t d;
  46. float16_t m;
  47. uint8_t qs[16];
  48. };
  49. #define A_TYPE block_q4_1
  50. """
  51. shader_q5_0_defines = """
  52. #extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
  53. #define QUANT_K 32
  54. #define QUANT_R 2
  55. struct block_q5_0
  56. {
  57. float16_t d;
  58. uint16_t qh[2];
  59. uint8_t qs[16];
  60. };
  61. #define A_TYPE block_q5_0
  62. """
  63. shader_q5_1_defines = """
  64. #extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
  65. #define QUANT_K 32
  66. #define QUANT_R 2
  67. struct block_q5_1
  68. {
  69. float16_t d;
  70. float16_t m;
  71. uint qh;
  72. uint8_t qs[16];
  73. };
  74. #define A_TYPE block_q5_1
  75. """
  76. shader_q8_0_defines = """
  77. #define QUANT_K 32
  78. #define QUANT_R 1
  79. struct block_q8_0
  80. {
  81. float16_t d;
  82. int8_t qs[32];
  83. };
  84. #define A_TYPE block_q8_0
  85. """
  86. # K-quants
  87. shader_q2_K_defines = """
  88. #define QUANT_K 256
  89. struct block_q2_K
  90. {
  91. uint8_t scales[QUANT_K/16];
  92. uint8_t qs[QUANT_K/4];
  93. f16vec2 d;
  94. };
  95. #define A_TYPE block_q2_K
  96. """
  97. shader_q3_K_defines = """
  98. #define QUANT_K 256
  99. struct block_q3_K
  100. {
  101. uint8_t hmask[QUANT_K/8];
  102. uint8_t qs[QUANT_K/4];
  103. uint8_t scales[12];
  104. float16_t d;
  105. };
  106. #define A_TYPE block_q3_K
  107. """
  108. shader_q4_K_defines = """
  109. #define QUANT_K 256
  110. struct block_q4_K
  111. {
  112. f16vec2 d;
  113. uint8_t scales[3*QUANT_K/64];
  114. uint8_t qs[QUANT_K/2];
  115. };
  116. #define A_TYPE block_q4_K
  117. """
  118. shader_q5_K_defines = """
  119. #define QUANT_K 256
  120. struct block_q5_K
  121. {
  122. f16vec2 d;
  123. uint8_t scales[12];
  124. uint8_t qh[QUANT_K/8];
  125. uint8_t qs[QUANT_K/2];
  126. };
  127. #define A_TYPE block_q5_K
  128. """
  129. shader_q6_K_defines = """
  130. #define QUANT_K 256
  131. struct block_q6_K
  132. {
  133. uint8_t ql[QUANT_K/2];
  134. uint8_t qh[QUANT_K/4];
  135. int8_t scales[QUANT_K/16];
  136. float16_t d;
  137. };
  138. #define A_TYPE block_q6_K
  139. """
  140. # Dequant functions
  141. shader_float_dequant_func = """
  142. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  143. return vec2(data_a[a_offset + ib], data_a[a_offset + ib + 1]);
  144. }
  145. """
  146. shader_q4_0_dequant_func = """
  147. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  148. const float d = float(data_a[a_offset + ib].d);
  149. const uint vui = uint(data_a[a_offset + ib].qs[iqs]);
  150. return (vec2(vui & 0xF, vui >> 4) - 8.0f) * d;
  151. }
  152. """
  153. shader_q4_1_dequant_func = """
  154. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  155. const float d = float(data_a[a_offset + ib].d);
  156. const float m = float(data_a[a_offset + ib].m);
  157. const uint vui = uint(data_a[a_offset + ib].qs[iqs]);
  158. return vec2(vui & 0xF, vui >> 4) * d + m;
  159. }
  160. """
  161. shader_q5_0_dequant_func = """
  162. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  163. const float d = float(data_a[a_offset + ib].d);
  164. const uint uint_qh = uint(data_a[a_offset + ib].qh[1]) << 16 | data_a[a_offset + ib].qh[0];
  165. const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10);
  166. const uint vui = uint(data_a[a_offset + ib].qs[iqs]);
  167. return (vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y) - 16.0f) * d;
  168. }
  169. """
  170. shader_q5_1_dequant_func = """
  171. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  172. const float d = float(data_a[a_offset + ib].d);
  173. const float m = float(data_a[a_offset + ib].m);
  174. const uint uint_qh = data_a[a_offset + ib].qh;
  175. const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10);
  176. const uint vui = uint(data_a[a_offset + ib].qs[iqs]);
  177. return vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y) * d + m;
  178. }
  179. """
  180. shader_q8_0_dequant_func = """
  181. vec2 dequantize(uint ib, uint iqs, uint a_offset) {
  182. const float d = float(data_a[a_offset + ib].d);
  183. return vec2(int(data_a[a_offset + ib].qs[iqs]), int(data_a[a_offset + ib].qs[iqs + 1])) * d;
  184. }
  185. """
  186. # MULMAT
  187. mulmat_head = """#version 450
  188. #extension GL_EXT_control_flow_attributes : enable
  189. #extension GL_EXT_shader_16bit_storage : require
  190. #ifdef MUL_MAT_ID
  191. #extension GL_EXT_buffer_reference2 : require
  192. #extension GL_EXT_nonuniform_qualifier : require
  193. #extension GL_EXT_scalar_block_layout : require
  194. #extension GL_EXT_shader_explicit_arithmetic_types_int8 : require
  195. #define EXPERT_COUNT 8
  196. #endif
  197. #ifndef LOAD_VEC_A
  198. #define LOAD_VEC_A 1
  199. #endif
  200. #ifndef LOAD_VEC_B
  201. #define LOAD_VEC_B 1
  202. #endif
  203. """
  204. mulmat_body1 = """
  205. layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
  206. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  207. layout (binding = 1) readonly buffer B {B_TYPE data_b[];};
  208. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  209. #ifdef MUL_MAT_ID
  210. layout (binding = 3) readonly buffer IDS {int data_ids[];};
  211. #endif
  212. layout (push_constant) uniform parameter
  213. {
  214. uint M;
  215. uint N;
  216. uint K;
  217. uint stride_a;
  218. uint stride_b;
  219. uint stride_d;
  220. uint k_split;
  221. uint ne02;
  222. uint ne12;
  223. uint broadcast2;
  224. uint broadcast3;
  225. uint batch_stride_a;
  226. uint batch_stride_b;
  227. uint batch_stride_d;
  228. #ifdef MUL_MAT_ID
  229. uint expert_stride_a;
  230. uint expert_stride_b0;
  231. uint expert_stride_b1;
  232. uint expert_stride_d;
  233. uint ids_stride;
  234. uint n_as;
  235. uint nei0;
  236. uint nei1;
  237. uint nbi1;
  238. uint ne11;
  239. #endif
  240. } p;
  241. layout (constant_id = 1) const uint BM = 64;
  242. layout (constant_id = 2) const uint BN = 64;
  243. layout (constant_id = 3) const uint BK = 16; // Assumed to be 32 if working with a quant
  244. layout (constant_id = 4) const uint WM = 32;
  245. layout (constant_id = 5) const uint WN = 32;
  246. layout (constant_id = 6) const uint WMITER = 2;
  247. layout (constant_id = 7) const uint TM = 4;
  248. layout (constant_id = 8) const uint TN = 2;
  249. layout (constant_id = 9) const uint WARP = 32;
  250. shared FLOAT_TYPE buf_a[BM * (BK+1)];
  251. shared FLOAT_TYPE buf_b[BN * (BK+1)];
  252. #ifdef MUL_MAT_ID
  253. shared u8vec2 rowids[2048];
  254. #endif
  255. void main() {
  256. #ifdef MUL_MAT_ID
  257. const uint batch_idx = gl_GlobalInvocationID.z / p.n_as;
  258. const uint expert_idx = gl_GlobalInvocationID.z % p.n_as;
  259. #else
  260. const uint batch_idx = gl_GlobalInvocationID.z;
  261. #endif
  262. const uint i13 = batch_idx / p.ne12;
  263. const uint i12 = batch_idx % p.ne12;
  264. const uint i03 = i13 / p.broadcast3;
  265. const uint i02 = i12 / p.broadcast2;
  266. const uint batch_idx_a = i03 * p.ne02 + i02;
  267. const uint blocks_m = (p.M + BM - 1) / BM;
  268. const uint ir = gl_WorkGroupID.x % blocks_m;
  269. const uint ik = gl_WorkGroupID.x / blocks_m;
  270. const uint ic = gl_WorkGroupID.y;
  271. const uint warp_i = gl_LocalInvocationID.x / WARP;
  272. const uint warp_r = warp_i % (BM / WM);
  273. const uint warp_c = warp_i / (BM / WM);
  274. const uint WNITER = (WM * WN) / (WARP * TM * TN * WMITER);
  275. const uint WSUBM = WM / WMITER;
  276. const uint WSUBN = WN / WNITER;
  277. const uint tiw = gl_LocalInvocationID.x % WARP;
  278. const uint tiwr = tiw % (WSUBM / TM);
  279. const uint tiwc = tiw / (WSUBM / TM);
  280. const uint loadr_a = gl_LocalInvocationID.x % (BK / LOAD_VEC_A);
  281. const uint loadc_a = gl_LocalInvocationID.x / (BK / LOAD_VEC_A);
  282. const uint loadr_b = gl_LocalInvocationID.x % (BK / LOAD_VEC_B);
  283. const uint loadc_b = gl_LocalInvocationID.x / (BK / LOAD_VEC_B);
  284. const uint loadstride_a = gl_WorkGroupSize.x * LOAD_VEC_A / BK;
  285. const uint loadstride_b = gl_WorkGroupSize.x * LOAD_VEC_B / BK;
  286. #ifdef MUL_MAT_ID
  287. uint _ne1 = 0;
  288. for (uint ii1 = 0; ii1 < p.nei1; ii1++) {
  289. for (uint ii0 = 0; ii0 < p.nei0; ii0++) {
  290. if (data_ids[ii1*p.nbi1 + ii0] == expert_idx) {
  291. rowids[_ne1] = u8vec2(ii0, ii1);
  292. _ne1++;
  293. }
  294. }
  295. }
  296. const u8vec2 id = rowids[ir * BN + ic];
  297. #endif
  298. const uint start_k = ik * p.k_split;
  299. const uint end_k = min(p.K, (ik + 1) * p.k_split);
  300. uint pos_a = (
  301. #ifdef MUL_MAT_ID
  302. expert_idx * p.expert_stride_a +
  303. #endif
  304. batch_idx_a * p.batch_stride_a + ir * BM * p.stride_a + start_k) / LOAD_VEC_A;
  305. uint pos_b = (
  306. #ifdef MUL_MAT_ID
  307. id.y * p.expert_stride_b1 +
  308. (id.x % p.ne11) * p.expert_stride_b0 +
  309. #endif
  310. batch_idx * p.batch_stride_b +
  311. ic * BN * p.stride_b + start_k) / LOAD_VEC_B;
  312. float sums[WMITER * TM * WNITER * TN];
  313. FLOAT_TYPE cache_a[WMITER * TM];
  314. FLOAT_TYPE cache_b[WNITER * TN];
  315. [[unroll]] for (uint i = 0; i < WMITER*TM*WNITER*TN; i++) {
  316. sums[i] = 0.0f;
  317. }
  318. [[unroll]] for (uint block = start_k; block < end_k; block += BK) {
  319. [[unroll]] for (uint l = 0; l < BM; l += loadstride_a) {"""
  320. mulmat_load_scalar = """
  321. #if LOAD_VEC_A == 8
  322. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  323. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  324. buf_a[buf_idx ] = FLOAT_TYPE(data_a[idx][0].x);
  325. buf_a[buf_idx + 1] = FLOAT_TYPE(data_a[idx][0].y);
  326. buf_a[buf_idx + 2] = FLOAT_TYPE(data_a[idx][0].z);
  327. buf_a[buf_idx + 3] = FLOAT_TYPE(data_a[idx][0].w);
  328. buf_a[buf_idx + 4] = FLOAT_TYPE(data_a[idx][1].x);
  329. buf_a[buf_idx + 5] = FLOAT_TYPE(data_a[idx][1].y);
  330. buf_a[buf_idx + 6] = FLOAT_TYPE(data_a[idx][1].z);
  331. buf_a[buf_idx + 7] = FLOAT_TYPE(data_a[idx][1].w);
  332. #elif LOAD_VEC_A == 4
  333. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  334. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  335. buf_a[buf_idx ] = FLOAT_TYPE(data_a[idx].x);
  336. buf_a[buf_idx + 1] = FLOAT_TYPE(data_a[idx].y);
  337. buf_a[buf_idx + 2] = FLOAT_TYPE(data_a[idx].z);
  338. buf_a[buf_idx + 3] = FLOAT_TYPE(data_a[idx].w);
  339. #else
  340. if (ir * BM + loadc_a + l < p.M && block + loadr_a < end_k) {
  341. buf_a[(loadc_a + l) * (BK+1) + loadr_a] = FLOAT_TYPE(data_a[pos_a + (loadc_a + l) * p.stride_a + loadr_a]);
  342. } else {
  343. buf_a[(loadc_a + l) * (BK+1) + loadr_a] = FLOAT_TYPE(0.0f);
  344. }
  345. #endif
  346. """
  347. mulmat_load_q4_0 = """
  348. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  349. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a;
  350. const uint ib = idx / 16;
  351. const uint iqs = idx & 0xF;
  352. const float d = float(data_a[ib].d);
  353. const uint vui = uint(data_a[ib].qs[iqs]);
  354. const vec2 v = (vec2(vui & 0xF, vui >> 4) - 8.0f) * d;
  355. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  356. buf_a[buf_idx + 16] = FLOAT_TYPE(v.y);"""
  357. mulmat_load_q4_1 = """
  358. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  359. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a;
  360. const uint ib = idx / 16;
  361. const uint iqs = idx & 0xF;
  362. const float d = float(data_a[ib].d);
  363. const float m = float(data_a[ib].m);
  364. const uint vui = uint(data_a[ib].qs[iqs]);
  365. const vec2 v = vec2(vui & 0xF, vui >> 4) * d + m;
  366. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  367. buf_a[buf_idx + 16] = FLOAT_TYPE(v.y);"""
  368. mulmat_load_q5_0 = """
  369. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  370. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a;
  371. const uint ib = idx / 16;
  372. const uint iqs = idx & 0xF;
  373. const float d = float(data_a[ib].d);
  374. const uint uint_qh = uint(data_a[ib].qh[1]) << 16 | data_a[ib].qh[0];
  375. const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10);
  376. const uint vui = uint(data_a[ib].qs[iqs]);
  377. const vec2 v = (vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y) - 16.0f) * d;
  378. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  379. buf_a[buf_idx + 16] = FLOAT_TYPE(v.y);"""
  380. mulmat_load_q5_1 = """
  381. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  382. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a;
  383. const uint ib = idx / 16;
  384. const uint iqs = idx & 0xF;
  385. const float d = float(data_a[ib].d);
  386. const float m = float(data_a[ib].m);
  387. const uint uint_qh = data_a[ib].qh;
  388. const ivec2 qh = ivec2(((uint_qh >> iqs) << 4) & 0x10, (uint_qh >> (iqs + 12)) & 0x10);
  389. const uint vui = uint(data_a[ib].qs[iqs]);
  390. const vec2 v = vec2((vui & 0xF) | qh.x, (vui >> 4) | qh.y) * d + m;
  391. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  392. buf_a[buf_idx + 16] = FLOAT_TYPE(v.y);"""
  393. mulmat_load_q8_0 = """
  394. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  395. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  396. const uint ib = idx / 16;
  397. const uint iqs = (idx & 0xF) * 2;
  398. const float d = float(data_a[ib].d);
  399. const vec2 v = vec2(int(data_a[ib].qs[iqs]), int(data_a[ib].qs[iqs + 1])) * d;
  400. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  401. buf_a[buf_idx + 1] = FLOAT_TYPE(v.y);"""
  402. mulmat_load_q2_K = """
  403. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  404. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  405. const uint ib = idx / 128; // 2 values per idx
  406. const uint iqs = idx % 128; // 0..127
  407. const uint qsi = (iqs / 64) * 32 + (iqs % 16) * 2; // 0,2,4..30
  408. const uint scalesi = iqs / 8; // 0..15
  409. const uint qsshift = ((iqs % 64) / 16) * 2; // 0,2,4,6
  410. const uvec2 qs = uvec2(data_a[ib].qs[qsi], data_a[ib].qs[qsi + 1]);
  411. const uint scales = data_a[ib].scales[scalesi];
  412. const vec2 d = vec2(data_a[ib].d);
  413. const vec2 v = d.x * float(scales & 0xF) * vec2((qs >> qsshift) & 3) - d.y * float(scales >> 4);
  414. buf_a[buf_idx ] = FLOAT_TYPE(v.x);
  415. buf_a[buf_idx + 1] = FLOAT_TYPE(v.y);"""
  416. mulmat_load_q3_K = """
  417. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  418. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  419. const uint ib = idx / 128; // 2 values per idx
  420. const uint iqs = idx % 128; // 0..127
  421. const uint n = iqs / 64; // 0,1
  422. const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..62
  423. const uint hmi = (iqs % 16) * 2; // 0,2,4..30
  424. const uint j = (iqs % 64) / 4; // 0..3
  425. const uint is = iqs / 8; // 0..15
  426. const uint halfsplit = ((iqs % 64) / 16); // 0,1,2,3
  427. const uint qsshift = halfsplit * 2; // 0,2,4,6
  428. const uint m = 1 << (4 * n + halfsplit); // 1,2,4,8,16,32,64,128
  429. const int8_t us = int8_t(is < 4 ? (data_a[ib].scales[is-0] & 0xF) | (((data_a[ib].scales[is+8] >> 0) & 3) << 4) :
  430. is < 8 ? (data_a[ib].scales[is-0] & 0xF) | (((data_a[ib].scales[is+4] >> 2) & 3) << 4) :
  431. is < 12 ? (data_a[ib].scales[is-8] >> 4) | (((data_a[ib].scales[is+0] >> 4) & 3) << 4) :
  432. (data_a[ib].scales[is-8] >> 4) | (((data_a[ib].scales[is-4] >> 6) & 3) << 4));
  433. const float dl = float(data_a[ib].d) * float(us - 32);
  434. buf_a[buf_idx ] = FLOAT_TYPE(dl * float(int8_t((data_a[ib].qs[qsi ] >> qsshift) & 3) - (((data_a[ib].hmask[hmi ] & m) != 0) ? 0 : 4)));
  435. buf_a[buf_idx + 1] = FLOAT_TYPE(dl * float(int8_t((data_a[ib].qs[qsi + 1] >> qsshift) & 3) - (((data_a[ib].hmask[hmi + 1] & m) != 0) ? 0 : 4)));"""
  436. mulmat_load_q4_K = """
  437. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  438. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  439. const uint ib = idx / 128; // 2 values per idx
  440. const uint iqs = idx % 128; // 0..127
  441. const uint n = iqs / 32; // 0,1,2,3
  442. const uint b = (iqs % 32) / 16; // 0,1
  443. const uint is = 2 * n + b; // 0..7
  444. const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126
  445. const vec2 loadd = vec2(data_a[ib].d);
  446. uint8_t sc;
  447. uint8_t mbyte;
  448. if (is < 4) {
  449. sc = uint8_t(data_a[ib].scales[is ] & 63);
  450. mbyte = uint8_t(data_a[ib].scales[is + 4] & 63);
  451. } else {
  452. sc = uint8_t((data_a[ib].scales[is + 4] & 0xF) | ((data_a[ib].scales[is - 4] >> 6) << 4));
  453. mbyte = uint8_t((data_a[ib].scales[is + 4] >> 4) | ((data_a[ib].scales[is ] >> 6) << 4));
  454. }
  455. const float d = loadd.x * sc;
  456. const float m = loadd.y * mbyte;
  457. buf_a[buf_idx ] = FLOAT_TYPE(d * float((data_a[ib].qs[qsi ] >> (b * 4)) & 0xF) - m);
  458. buf_a[buf_idx + 1] = FLOAT_TYPE(d * float((data_a[ib].qs[qsi + 1] >> (b * 4)) & 0xF) - m);"""
  459. mulmat_load_q5_K = """
  460. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  461. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  462. const uint ib = idx / 128; // 2 values per idx
  463. const uint iqs = idx % 128; // 0..127
  464. const uint n = iqs / 32; // 0,1,2,3
  465. const uint b = (iqs % 32) / 16; // 0,1
  466. const uint is = 2 * n + b; // 0..7
  467. const uint qsi = n * 32 + (iqs % 16) * 2; // 0,2,4..126
  468. const uint qhi = (iqs % 16) * 2; // 0,2,4..30
  469. const uint8_t hm = uint8_t(1 << (iqs / 16));
  470. const vec2 loadd = vec2(data_a[ib].d);
  471. uint8_t sc;
  472. uint8_t mbyte;
  473. if (is < 4) {
  474. sc = uint8_t(data_a[ib].scales[is ] & 63);
  475. mbyte = uint8_t(data_a[ib].scales[is + 4] & 63);
  476. } else {
  477. sc = uint8_t((data_a[ib].scales[is + 4] & 0xF) | ((data_a[ib].scales[is - 4] >> 6) << 4));
  478. mbyte = uint8_t((data_a[ib].scales[is + 4] >> 4) | ((data_a[ib].scales[is ] >> 6) << 4));
  479. }
  480. const float d = loadd.x * sc;
  481. const float m = loadd.y * mbyte;
  482. buf_a[buf_idx ] = FLOAT_TYPE(d * (float((data_a[ib].qs[qsi ] >> (b * 4)) & 0xF) + float((data_a[ib].qh[qhi ] & hm) != 0 ? 16 : 0)) - m);
  483. buf_a[buf_idx + 1] = FLOAT_TYPE(d * (float((data_a[ib].qs[qsi + 1] >> (b * 4)) & 0xF) + float((data_a[ib].qh[qhi + 1] & hm) != 0 ? 16 : 0)) - m);"""
  484. mulmat_load_q6_K = """
  485. const uint idx = pos_a + (loadc_a + l) * p.stride_a / LOAD_VEC_A + loadr_a;
  486. const uint buf_idx = (loadc_a + l) * (BK+1) + loadr_a * LOAD_VEC_A;
  487. const uint ib = idx / 128; // 2 values per idx
  488. const uint iqs = idx % 128; // 0..127
  489. const uint n = iqs / 64; // 0,1
  490. const uint b = (iqs % 64) / 32; // 0,1
  491. const uint is_b = (iqs % 16) / 8; // 0,1
  492. const uint qhshift = ((iqs % 64) / 16) * 2; // 0,2,4,6
  493. const uint is = 8 * n + qhshift + is_b; // 0..15
  494. const uint qsi = n * 64 + (iqs % 32) * 2; // 0,2,4..126
  495. const uint qhi = n * 32 + (iqs % 16) * 2; // 0,2,4..62
  496. const float dscale = float(data_a[ib].d) * float(data_a[ib].scales[is]);
  497. buf_a[buf_idx ] = FLOAT_TYPE(dscale * float(int8_t(((data_a[ib].ql[qsi ] >> (b * 4)) & 0xF) | (((data_a[ib].qh[qhi ] >> qhshift) & 3) << 4)) - 32));
  498. buf_a[buf_idx + 1] = FLOAT_TYPE(dscale * float(int8_t(((data_a[ib].ql[qsi + 1] >> (b * 4)) & 0xF) | (((data_a[ib].qh[qhi + 1] >> qhshift) & 3) << 4)) - 32));"""
  499. mulmat_body2 = """
  500. }
  501. [[unroll]] for (uint l = 0; l < BN; l += loadstride_b) {
  502. #if LOAD_VEC_B == 8
  503. const uint idx = pos_b + (loadc_b + l) * p.stride_b / LOAD_VEC_B + loadr_b;
  504. const uint buf_idx = (loadc_b + l) * (BK+1) + loadr_b * LOAD_VEC_B;
  505. buf_b[buf_idx + 0] = FLOAT_TYPE(data_b[idx][0].x);
  506. buf_b[buf_idx + 1] = FLOAT_TYPE(data_b[idx][0].y);
  507. buf_b[buf_idx + 2] = FLOAT_TYPE(data_b[idx][0].z);
  508. buf_b[buf_idx + 3] = FLOAT_TYPE(data_b[idx][0].w);
  509. buf_b[buf_idx + 4] = FLOAT_TYPE(data_b[idx][1].x);
  510. buf_b[buf_idx + 5] = FLOAT_TYPE(data_b[idx][1].y);
  511. buf_b[buf_idx + 6] = FLOAT_TYPE(data_b[idx][1].z);
  512. buf_b[buf_idx + 7] = FLOAT_TYPE(data_b[idx][1].w);
  513. #elif LOAD_VEC_B == 4
  514. const uint idx = pos_b + (loadc_b + l) * p.stride_b / LOAD_VEC_B + loadr_b;
  515. const uint buf_idx = (loadc_b + l) * (BK+1) + loadr_b * LOAD_VEC_B;
  516. buf_b[buf_idx + 0] = FLOAT_TYPE(data_b[idx].x);
  517. buf_b[buf_idx + 1] = FLOAT_TYPE(data_b[idx].y);
  518. buf_b[buf_idx + 2] = FLOAT_TYPE(data_b[idx].z);
  519. buf_b[buf_idx + 3] = FLOAT_TYPE(data_b[idx].w);
  520. #else
  521. if (ic * BN + loadc_b + l < p.N && block + loadr_b < end_k) {
  522. buf_b[(loadc_b + l) * (BK+1) + loadr_b] = FLOAT_TYPE(data_b[pos_b + (loadc_b + l) * p.stride_b + loadr_b]);
  523. } else {
  524. buf_b[(loadc_b + l) * (BK+1) + loadr_b] = FLOAT_TYPE(0.0f);
  525. }
  526. #endif
  527. }
  528. barrier();
  529. pos_a += BK / LOAD_VEC_A;
  530. pos_b += BK / LOAD_VEC_B;
  531. for (uint i = 0; i < BK; i++) {
  532. // Load from shared into cache
  533. [[unroll]] for (uint wsir = 0; wsir < WMITER; wsir++) {
  534. [[unroll]] for (uint j = 0; j < TM; j++) {
  535. cache_a[wsir * TM + j] = buf_a[(warp_r * WM + wsir * WSUBM + tiwr * TM + j) * (BK+1) + i];
  536. }
  537. }
  538. [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++) {
  539. [[unroll]] for (uint j = 0; j < TN; j++) {
  540. cache_b[wsic * TN + j] = buf_b[(warp_c * WN + wsic * WSUBN + tiwc * TN + j) * (BK+1) + i];
  541. }
  542. }
  543. [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++) {
  544. [[unroll]] for (uint wsir = 0; wsir < WMITER; wsir++) {
  545. [[unroll]] for (uint cc = 0; cc < TN; cc++) {
  546. [[unroll]] for (uint cr = 0; cr < TM; cr++) {
  547. sums[(wsic * TN + cc) * (WMITER * TM) + wsir * TM + cr] += float(cache_a[wsir * TM + cr]) * float(cache_b[wsic * TN + cc]);
  548. }
  549. }
  550. }
  551. }
  552. }
  553. barrier();
  554. }
  555. const uint dr = ir * BM + warp_r * WM;
  556. const uint dc = ic * BN + warp_c * WN;
  557. const uint offsets =
  558. #ifdef MUL_MAT_ID
  559. expert_idx * p.expert_stride_d +
  560. #endif
  561. batch_idx * p.batch_stride_d + ik * p.batch_stride_d * gl_NumWorkGroups.z;
  562. [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++) {
  563. [[unroll]] for (uint wsir = 0; wsir < WMITER; wsir++) {
  564. const uint dr_warp = dr + wsir * WSUBM + tiwr * TM;
  565. const uint dc_warp = dc + wsic * WSUBN + tiwc * TN;
  566. [[unroll]] for (uint cc = 0; cc < TN; cc++) {
  567. [[unroll]] for (uint cr = 0; cr < TM; cr++) {
  568. if (dr_warp + cr < p.M && dc_warp + cc < p.N) {
  569. data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + cr] = D_TYPE(sums[(wsic * TN + cc) * (WMITER * TM) + wsir * TM + cr]);
  570. }
  571. }
  572. }
  573. }
  574. }
  575. }
  576. """
  577. mulmat_split_k_reduce_src = """#version 450
  578. #extension GL_EXT_control_flow_attributes : enable
  579. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  580. layout (binding = 0) readonly buffer A {float data_a[];};
  581. layout (binding = 1) writeonly buffer D {float data_d[];};
  582. layout (push_constant) uniform parameter {
  583. uint ne;
  584. uint k_num;
  585. } p;
  586. void main() {
  587. const uint idx = gl_GlobalInvocationID.x;
  588. if (idx >= p.ne) {
  589. return;
  590. }
  591. float result = 0.0f;
  592. [[unroll]] for (uint i = 0; i < p.k_num; i++) {
  593. result += data_a[i * p.ne + idx];
  594. }
  595. data_d[idx] = result;
  596. }
  597. """
  598. # DEQUANT SHADER
  599. dequant_head = """#version 450
  600. #extension GL_EXT_control_flow_attributes : require
  601. #extension GL_EXT_shader_16bit_storage : require
  602. layout (push_constant) uniform parameter
  603. {
  604. uint M;
  605. uint K;
  606. uint stride_a;
  607. uint stride_b;
  608. uint nel;
  609. } p;
  610. """
  611. dequant_f32_body = """
  612. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  613. layout (binding = 0) readonly buffer A {float data_a[];};
  614. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  615. void main() {
  616. const uint i = gl_GlobalInvocationID.x * 16;
  617. if (i >= p.nel) {
  618. return;
  619. }
  620. [[unroll]] for (uint l = 0; l < 16; l++) {
  621. data_b[i + l] = D_TYPE(data_a[i + l]);
  622. }
  623. }
  624. """
  625. dequant_q4_0_body = """
  626. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  627. layout (binding = 0) readonly buffer A {block_q4_0 data_a[];};
  628. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  629. void main() {
  630. const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
  631. const uint tid = gl_LocalInvocationID.x % 64;
  632. const uint il = tid/32;
  633. const uint ir = tid%32;
  634. const uint ib = 32*i + ir;
  635. if (ib >= p.nel / 32) {
  636. return;
  637. }
  638. const uint b_idx = 1024*i + 32*ir + 8*il;
  639. const float d = float(data_a[ib].d);
  640. const float dm = -8.0f * d;
  641. const uint q_idx = 8*il;
  642. [[unroll]] for (uint l = 0; l < 8; ++l) {
  643. data_b[b_idx + l + 0] = D_TYPE(d * (data_a[ib].qs[q_idx + l] & 0xF) + dm);
  644. data_b[b_idx + l + 16] = D_TYPE(d * (data_a[ib].qs[q_idx + l] >> 4) + dm);
  645. }
  646. }
  647. """
  648. dequant_q4_1_body = """
  649. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  650. layout (binding = 0) readonly buffer A {block_q4_1 data_a[];};
  651. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  652. void main() {
  653. const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
  654. const uint tid = gl_LocalInvocationID.x % 64;
  655. const uint il = tid/32;
  656. const uint ir = tid%32;
  657. const uint ib = 32*i + ir;
  658. if (ib >= p.nel / 32) {
  659. return;
  660. }
  661. const uint b_idx = 1024*i + 32*ir + 8*il;
  662. const float d = float(data_a[ib].d);
  663. const float m = float(data_a[ib].m);
  664. const uint q_idx = 8*il;
  665. [[unroll]] for (uint l = 0; l < 8; ++l) {
  666. data_b[b_idx + l + 0] = D_TYPE(d * (data_a[ib].qs[q_idx + l] & 0xF) + m);
  667. data_b[b_idx + l + 16] = D_TYPE(d * (data_a[ib].qs[q_idx + l] >> 4) + m);
  668. }
  669. }
  670. """
  671. dequant_q5_0_body = """
  672. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  673. layout (binding = 0) readonly buffer A {block_q5_0 data_a[];};
  674. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  675. void main() {
  676. const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
  677. const uint tid = gl_LocalInvocationID.x % 64;
  678. const uint il = tid/32;
  679. const uint ir = tid%32;
  680. const uint ib = 32*i + ir;
  681. if (ib >= p.nel / 32) {
  682. return;
  683. }
  684. const uint b_idx = 1024*i + 32*ir + 8*il;
  685. const float d = float(data_a[ib].d);
  686. const uint qh = uint(data_a[ib].qh[1]) << 16 | data_a[ib].qh[0];
  687. const uint q_idx = 8*il;
  688. [[unroll]] for (uint l = 0; l < 8; ++l) {
  689. const uint iqs = q_idx + l;
  690. const uint vui = uint(data_a[ib].qs[iqs]);
  691. data_b[b_idx + l + 0] = D_TYPE(d * (((vui & 0xF) | (((qh >> iqs) << 4) & 0x10)) - 16.0f));
  692. data_b[b_idx + l + 16] = D_TYPE(d * (((vui >> 4) | ((qh >> (iqs + 12)) & 0x10)) - 16.0f));
  693. }
  694. }
  695. """
  696. dequant_q5_1_body = """
  697. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  698. layout (binding = 0) readonly buffer A {block_q5_1 data_a[];};
  699. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  700. void main() {
  701. const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
  702. const uint tid = gl_LocalInvocationID.x % 64;
  703. const uint il = tid/32;
  704. const uint ir = tid%32;
  705. const uint ib = 32*i + ir;
  706. if (ib >= p.nel / 32) {
  707. return;
  708. }
  709. const uint b_idx = 1024*i + 32*ir + 8*il;
  710. const float d = float(data_a[ib].d);
  711. const float m = float(data_a[ib].m);
  712. const uint qh = data_a[ib].qh;
  713. const uint q_idx = 8*il;
  714. [[unroll]] for (uint l = 0; l < 8; ++l) {
  715. const uint iqs = q_idx + l;
  716. const uint vui = uint(data_a[ib].qs[iqs]);
  717. data_b[b_idx + l + 0] = D_TYPE(d * (((vui & 0xF) | (((qh >> iqs) << 4) & 0x10))) + m);
  718. data_b[b_idx + l + 16] = D_TYPE(d * (((vui >> 4) | ((qh >> (iqs + 12)) & 0x10))) + m);
  719. }
  720. }
  721. """
  722. dequant_q8_0_body = """
  723. layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
  724. layout (binding = 0) readonly buffer A {block_q8_0 data_a[];};
  725. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  726. void main() {
  727. const uint i = gl_WorkGroupID.x * 4 + gl_LocalInvocationID.x / 64;
  728. const uint tid = gl_LocalInvocationID.x % 64;
  729. const uint il = tid/32;
  730. const uint ir = tid%32;
  731. const uint ib = 32*i + ir;
  732. if (ib >= p.nel / 32) {
  733. return;
  734. }
  735. const uint b_idx = 1024*i + 32*ir + 16*il;
  736. const float d = float(data_a[ib].d);
  737. const uint q_idx = 16*il;
  738. [[unroll]] for (uint l = 0; l < 16; l += 2) {
  739. data_b[b_idx + l ] = D_TYPE(d * data_a[ib].qs[q_idx + l ]);
  740. data_b[b_idx + l + 1] = D_TYPE(d * data_a[ib].qs[q_idx + l + 1]);
  741. }
  742. }
  743. """
  744. # K-quants
  745. dequant_q2_K_body = """
  746. layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
  747. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  748. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  749. void main() {
  750. [[unroll]] for (uint wgy = 0; wgy < 256; wgy++) {
  751. const uint i = gl_WorkGroupID.x * 256 + wgy;
  752. if (i >= p.M * p.K / QUANT_K) {
  753. return;
  754. }
  755. const uint tid = gl_LocalInvocationID.x;
  756. const uint ip = tid / 32;
  757. const uint il = tid - 32 * ip;
  758. const uint is = 8 * ip + il / 16;
  759. const uint y_idx = i * QUANT_K + 128 * ip + il;
  760. const uint ql_idx = 32 * ip + il;
  761. const uint8_t qs = data_a[i].qs[32 * ip + il];
  762. FLOAT_TYPE dall = FLOAT_TYPE(data_a[i].d.x);
  763. FLOAT_TYPE dmin = FLOAT_TYPE(data_a[i].d.y);
  764. data_b[y_idx + 0] = D_TYPE(dall * FLOAT_TYPE((data_a[i].scales[is+0] & 0xF) * ((qs >> 0) & 3)) - dmin * FLOAT_TYPE(data_a[i].scales[is+0] >> 4));
  765. data_b[y_idx + 32] = D_TYPE(dall * FLOAT_TYPE((data_a[i].scales[is+2] & 0xF) * ((qs >> 2) & 3)) - dmin * FLOAT_TYPE(data_a[i].scales[is+2] >> 4));
  766. data_b[y_idx + 64] = D_TYPE(dall * FLOAT_TYPE((data_a[i].scales[is+4] & 0xF) * ((qs >> 4) & 3)) - dmin * FLOAT_TYPE(data_a[i].scales[is+4] >> 4));
  767. data_b[y_idx + 96] = D_TYPE(dall * FLOAT_TYPE((data_a[i].scales[is+6] & 0xF) * ((qs >> 6) & 3)) - dmin * FLOAT_TYPE(data_a[i].scales[is+6] >> 4));
  768. }
  769. }
  770. """
  771. dequant_q3_K_body = """
  772. layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
  773. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  774. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  775. void main() {
  776. [[unroll]] for (uint wgy = 0; wgy < 256; wgy++) {
  777. const uint i = uint(gl_WorkGroupID.x * 256 + wgy);
  778. if (i >= p.M * p.K / QUANT_K) {
  779. return;
  780. }
  781. const uint r = gl_LocalInvocationID.x / 4;
  782. const uint tid = r / 2;
  783. const uint is0 = r % 2;
  784. const uint l0 = 16 * is0 + 4 * (gl_LocalInvocationID.x % 4);
  785. const uint n = tid / 4;
  786. const uint j = tid - 4*n;
  787. const uint8_t m = uint8_t(1 << (4*n + j));
  788. const uint is = 8*n + 2*j + is0;
  789. const uint shift = 2*j;
  790. const int8_t us = int8_t(is < 4 ? (data_a[i].scales[is-0] & 0xF) | (((data_a[i].scales[is+8] >> 0) & 3) << 4) :
  791. is < 8 ? (data_a[i].scales[is-0] & 0xF) | (((data_a[i].scales[is+4] >> 2) & 3) << 4) :
  792. is < 12 ? (data_a[i].scales[is-8] >> 4) | (((data_a[i].scales[is+0] >> 4) & 3) << 4) :
  793. (data_a[i].scales[is-8] >> 4) | (((data_a[i].scales[is-4] >> 6) & 3) << 4));
  794. const FLOAT_TYPE d_all = FLOAT_TYPE(data_a[i].d);
  795. const FLOAT_TYPE dl = d_all * FLOAT_TYPE(us - 32);
  796. const uint y_idx = i * QUANT_K + 128 * n + 32 * j;
  797. const uint qs_idx = 32*n;
  798. for (uint l = l0; l < l0 + 4; ++l) {
  799. data_b[y_idx + l] = D_TYPE(dl * FLOAT_TYPE(int8_t((data_a[i].qs[qs_idx + l] >> shift) & 3) - (((data_a[i].hmask[l] & m) != 0) ? 0 : 4)));
  800. }
  801. }
  802. }
  803. """
  804. dequant_q4_K_body = """
  805. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  806. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  807. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  808. void main() {
  809. [[unroll]] for (uint wgy = 0; wgy < 256; wgy++) {
  810. const uint i = gl_WorkGroupID.x * 256 + wgy;
  811. if (i >= p.M * p.K / QUANT_K) {
  812. return;
  813. }
  814. const uint tid = gl_LocalInvocationID.x;
  815. const uint il = tid / 8;
  816. const uint ir = tid % 8;
  817. const uint is = 2 * il;
  818. const uint n = 4;
  819. const FLOAT_TYPE dall = FLOAT_TYPE(data_a[i].d.x);
  820. const FLOAT_TYPE dmin = FLOAT_TYPE(data_a[i].d.y);
  821. const uint y_idx = i * QUANT_K + 64 * il + n * ir;
  822. const uint qs_idx = 32*il + n * ir;
  823. uint8_t sc;
  824. uint8_t m;
  825. if (is < 4) {
  826. sc = uint8_t(data_a[i].scales[is] & 63);
  827. m = uint8_t(data_a[i].scales[is + 4] & 63);
  828. } else {
  829. sc = uint8_t((data_a[i].scales[is + 4] & 0xF) | ((data_a[i].scales[is - 4] >> 6) << 4));
  830. m = uint8_t((data_a[i].scales[is + 4] >> 4) | ((data_a[i].scales[is ] >> 6) << 4));
  831. }
  832. const FLOAT_TYPE d1 = dall * sc;
  833. const FLOAT_TYPE m1 = dmin * m;
  834. if (is < 4) {
  835. sc = uint8_t(data_a[i].scales[is + 1] & 63);
  836. m = uint8_t(data_a[i].scales[is + 5] & 63);
  837. } else {
  838. sc = uint8_t((data_a[i].scales[is + 5] & 0xF) | ((data_a[i].scales[is - 3] >> 6) << 4));
  839. m = uint8_t((data_a[i].scales[is + 5] >> 4) | ((data_a[i].scales[is + 1] >> 6) << 4));
  840. }
  841. const FLOAT_TYPE d2 = dall * sc;
  842. const FLOAT_TYPE m2 = dmin * m;
  843. [[unroll]] for (uint l = 0; l < n; ++l) {
  844. data_b[y_idx + l ] = D_TYPE(d1 * FLOAT_TYPE(data_a[i].qs[qs_idx + l] & 0xF) - m1);
  845. data_b[y_idx + l + 32] = D_TYPE(d2 * FLOAT_TYPE(data_a[i].qs[qs_idx + l] >> 4) - m2);
  846. }
  847. }
  848. }
  849. """
  850. dequant_q5_K_body = """
  851. layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
  852. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  853. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  854. void main() {
  855. [[unroll]] for (uint wgy = 0; wgy < 256; wgy++) {
  856. const uint i = gl_WorkGroupID.x * 256 + wgy;
  857. if (i >= p.M * p.K / QUANT_K) {
  858. return;
  859. }
  860. const uint tid = gl_LocalInvocationID.x;
  861. const uint il = tid / 16;
  862. const uint ir = tid % 16;
  863. const uint is = 2 * il;
  864. const FLOAT_TYPE dall = FLOAT_TYPE(data_a[i].d.x);
  865. const FLOAT_TYPE dmin = FLOAT_TYPE(data_a[i].d.y);
  866. const uint y_idx = i * QUANT_K + 64 * il + 2 * ir;
  867. const uint qs_idx = 32*il + 2 * ir;
  868. const uint qh_idx = 2 * ir;
  869. uint8_t sc;
  870. uint8_t m;
  871. if (is < 4) {
  872. sc = uint8_t(data_a[i].scales[is] & 63);
  873. m = uint8_t(data_a[i].scales[is + 4] & 63);
  874. } else {
  875. sc = uint8_t((data_a[i].scales[is + 4] & 0xF) | ((data_a[i].scales[is - 4] >> 6) << 4));
  876. m = uint8_t((data_a[i].scales[is + 4] >> 4) | ((data_a[i].scales[is ] >> 6) << 4));
  877. }
  878. const FLOAT_TYPE d1 = dall * sc;
  879. const FLOAT_TYPE m1 = dmin * m;
  880. if (is < 4) {
  881. sc = uint8_t(data_a[i].scales[is + 1] & 63);
  882. m = uint8_t(data_a[i].scales[is + 5] & 63);
  883. } else {
  884. sc = uint8_t((data_a[i].scales[is + 5] & 0xF) | ((data_a[i].scales[is - 3] >> 6) << 4));
  885. m = uint8_t((data_a[i].scales[is + 5] >> 4) | ((data_a[i].scales[is + 1] >> 6) << 4));
  886. }
  887. const FLOAT_TYPE d2 = dall * sc;
  888. const FLOAT_TYPE m2 = dmin * m;
  889. const uint8_t hm1 = uint8_t(1 << (2 * il ));
  890. const uint8_t hm2 = uint8_t(1 << (2 * il + 1));
  891. data_b[y_idx ] = D_TYPE(d1 * FLOAT_TYPE((data_a[i].qs[qs_idx ] & 0xF) + (((data_a[i].qh[qh_idx ] & hm1) != 0) ? 16 : 0)) - m1);
  892. data_b[y_idx + 1] = D_TYPE(d1 * FLOAT_TYPE((data_a[i].qs[qs_idx + 1] & 0xF) + (((data_a[i].qh[qh_idx + 1] & hm1) != 0) ? 16 : 0)) - m1);
  893. data_b[y_idx + 32] = D_TYPE(d2 * FLOAT_TYPE((data_a[i].qs[qs_idx ] >> 4) + (((data_a[i].qh[qh_idx ] & hm2) != 0) ? 16 : 0)) - m2);
  894. data_b[y_idx + 33] = D_TYPE(d2 * FLOAT_TYPE((data_a[i].qs[qs_idx + 1] >> 4) + (((data_a[i].qh[qh_idx + 1] & hm2) != 0) ? 16 : 0)) - m2);
  895. }
  896. }
  897. """
  898. dequant_q6_K_body = """
  899. layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
  900. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  901. layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
  902. void main() {
  903. [[unroll]] for (uint wgy = 0; wgy < 256; wgy++) {
  904. const uint i = gl_WorkGroupID.x * 256 + wgy;
  905. if (i >= p.M * p.K / QUANT_K) {
  906. return;
  907. }
  908. const uint tid = gl_LocalInvocationID.x;
  909. const uint ip = tid / 32;
  910. const uint il = tid - 32 * ip;
  911. const uint is = 8 * ip + il / 16;
  912. const uint y_idx = i * QUANT_K + 128 * ip + il;
  913. const uint ql_idx = 64 * ip + il;
  914. const uint8_t qh = data_a[i].qh[32 * ip + il];
  915. const FLOAT_TYPE d = FLOAT_TYPE(data_a[i].d);
  916. data_b[y_idx + 0] = D_TYPE(d * FLOAT_TYPE(data_a[i].scales[is + 0] * (int8_t((data_a[i].ql[ql_idx + 0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32)));
  917. data_b[y_idx + 32] = D_TYPE(d * FLOAT_TYPE(data_a[i].scales[is + 2] * (int8_t((data_a[i].ql[ql_idx + 32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32)));
  918. data_b[y_idx + 64] = D_TYPE(d * FLOAT_TYPE(data_a[i].scales[is + 4] * (int8_t((data_a[i].ql[ql_idx + 0] >> 4) | (((qh >> 4) & 3) << 4)) - 32)));
  919. data_b[y_idx + 96] = D_TYPE(d * FLOAT_TYPE(data_a[i].scales[is + 6] * (int8_t((data_a[i].ql[ql_idx + 32] >> 4) | (((qh >> 6) & 3) << 4)) - 32)));
  920. }
  921. }
  922. """
  923. # Mul Mat Vec
  924. mul_mat_vec_head = """#version 450
  925. #extension GL_EXT_control_flow_attributes : enable
  926. #extension GL_EXT_shader_16bit_storage : require
  927. #extension GL_EXT_shader_8bit_storage : require
  928. #ifdef MUL_MAT_ID
  929. #define EXPERT_COUNT 8
  930. #endif
  931. """
  932. mul_mat_vec_layout = """
  933. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  934. layout (binding = 1) readonly buffer B {B_TYPE data_b[];};
  935. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  936. #ifdef MUL_MAT_ID
  937. layout (binding = 3) readonly buffer IDS {int data_ids[];};
  938. #endif
  939. layout (push_constant) uniform parameter
  940. {
  941. uint ncols;
  942. uint stride_a;
  943. uint stride_b;
  944. uint stride_d;
  945. uint ne02;
  946. uint ne12;
  947. uint broadcast2;
  948. uint broadcast3;
  949. uint batch_stride_a;
  950. uint batch_stride_b;
  951. uint batch_stride_d;
  952. #ifdef MUL_MAT_ID
  953. uint expert_stride_a;
  954. uint expert_stride_b0;
  955. uint expert_stride_b1;
  956. uint expert_stride_d0;
  957. uint expert_stride_d1;
  958. uint ne11;
  959. uint nei0;
  960. uint nbi1;
  961. uint n_as;
  962. #endif
  963. } p;
  964. """
  965. mul_mat_vec_body = """
  966. layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
  967. layout (constant_id = 0) const uint BLOCK_SIZE = 32;
  968. shared FLOAT_TYPE tmp[BLOCK_SIZE];
  969. void main() {
  970. const uint row = gl_WorkGroupID.x;
  971. const uint tid = gl_LocalInvocationID.x;
  972. const uint batch_idx = gl_GlobalInvocationID.y;
  973. #ifdef MUL_MAT_ID
  974. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  975. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  976. #endif
  977. const uint i13 = batch_idx / p.ne12;
  978. const uint i12 = batch_idx % p.ne12;
  979. const uint i03 = i13 / p.broadcast3;
  980. const uint i02 = i12 / p.broadcast2;
  981. const uint batch_idx_a = i03 * p.ne02 + i02;
  982. #ifdef MUL_MAT_ID
  983. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  984. #endif
  985. const uint a_offset =
  986. #ifdef MUL_MAT_ID
  987. expert_id * p.expert_stride_a +
  988. #endif
  989. batch_idx_a * p.batch_stride_a;
  990. const uint b_offset =
  991. #ifdef MUL_MAT_ID
  992. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  993. expert_idx1 * p.expert_stride_b1 +
  994. #endif
  995. batch_idx * p.batch_stride_b;
  996. const uint d_offset =
  997. #ifdef MUL_MAT_ID
  998. expert_idx0 * p.expert_stride_b0 +
  999. expert_idx1 * p.expert_stride_b1 +
  1000. #endif
  1001. batch_idx * p.batch_stride_d;
  1002. const uint y_offset = QUANT_R == 1 ? 1 : QUANT_K/2;
  1003. tmp[tid] = FLOAT_TYPE(0.0f);
  1004. [[unroll]] for (uint i = 0; i < p.ncols/BLOCK_SIZE; i += 2) {
  1005. const uint col = i*BLOCK_SIZE + 2*tid;
  1006. const uint ib = (row*p.ncols + col)/QUANT_K; // block index
  1007. const uint iqs = (col%QUANT_K)/QUANT_R; // quant index
  1008. const uint iybs = col - col%QUANT_K; // y block start index
  1009. vec2 v = dequantize(ib, iqs, a_offset / QUANT_K);
  1010. // matrix multiplication
  1011. tmp[tid] += FLOAT_TYPE(v.x) * FLOAT_TYPE(data_b[b_offset + iybs + iqs]) +
  1012. FLOAT_TYPE(v.y) * FLOAT_TYPE(data_b[b_offset + iybs + iqs + y_offset]);
  1013. }
  1014. // sum up partial sums and write back result
  1015. barrier();
  1016. [[unroll]] for (uint s = BLOCK_SIZE/2; s > 0; s >>= 1) {
  1017. if (tid < s) {
  1018. tmp[tid] += tmp[tid + s];
  1019. }
  1020. barrier();
  1021. }
  1022. if (tid == 0) {
  1023. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1024. }
  1025. }
  1026. """
  1027. # K-quants
  1028. mul_mat_vec_q2_K_body = """
  1029. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  1030. shared FLOAT_TYPE tmp[32];
  1031. void main() {
  1032. const uint row = gl_WorkGroupID.x;
  1033. const uint batch_idx = gl_GlobalInvocationID.y;
  1034. #ifdef MUL_MAT_ID
  1035. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  1036. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  1037. #endif
  1038. const uint i13 = batch_idx / p.ne12;
  1039. const uint i12 = batch_idx % p.ne12;
  1040. const uint i03 = i13 / p.broadcast3;
  1041. const uint i02 = i12 / p.broadcast2;
  1042. const uint batch_idx_a = i03 * p.ne02 + i02;
  1043. #ifdef MUL_MAT_ID
  1044. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  1045. #endif
  1046. const uint a_offset =
  1047. #ifdef MUL_MAT_ID
  1048. expert_id * p.expert_stride_a +
  1049. #endif
  1050. batch_idx_a * p.batch_stride_a;
  1051. const uint b_offset =
  1052. #ifdef MUL_MAT_ID
  1053. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  1054. expert_idx1 * p.expert_stride_b1 +
  1055. #endif
  1056. batch_idx * p.batch_stride_b;
  1057. const uint d_offset =
  1058. #ifdef MUL_MAT_ID
  1059. expert_idx0 * p.expert_stride_b0 +
  1060. expert_idx1 * p.expert_stride_b1 +
  1061. #endif
  1062. batch_idx * p.batch_stride_d;
  1063. const uint num_blocks_per_row = p.ncols / QUANT_K;
  1064. const uint ib0 = a_offset / QUANT_K + row*num_blocks_per_row;
  1065. const uint tid = gl_LocalInvocationID.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  1066. const uint ix = gl_LocalInvocationID.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  1067. const uint step = 16/K_QUANTS_PER_ITERATION; // 16 or 8
  1068. const uint v_im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  1069. const uint v_in = tid - step*v_im; // 0...15 or 0...7
  1070. const uint l0 = K_QUANTS_PER_ITERATION*v_in; // 0...15
  1071. const uint q_offset = 32*v_im + l0;
  1072. const uint s_offset = 8*v_im;
  1073. const uint y_offset = 128*v_im + l0;
  1074. tmp[16 * ix + tid] = FLOAT_TYPE(0.0); // partial sum for thread in warp
  1075. [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  1076. const uint y_idx = i * QUANT_K + y_offset;
  1077. const FLOAT_TYPE dall = FLOAT_TYPE(data_a[ib0 + i].d.x);
  1078. const FLOAT_TYPE dmin = FLOAT_TYPE(data_a[ib0 + i].d.y);
  1079. FLOAT_TYPE sum1 = FLOAT_TYPE(0.0);
  1080. FLOAT_TYPE sum2 = FLOAT_TYPE(0.0);
  1081. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  1082. sum1 += FLOAT_TYPE(data_b[b_offset + y_idx + l + 0]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 0] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l + 0] >> 0) & 3)
  1083. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 16]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 1] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l +16] >> 0) & 3)
  1084. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 32]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 2] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l + 0] >> 2) & 3)
  1085. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 48]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 3] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l +16] >> 2) & 3)
  1086. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 64]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 4] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l + 0] >> 4) & 3)
  1087. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 80]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 5] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l +16] >> 4) & 3)
  1088. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 96]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 6] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l + 0] >> 6) & 3)
  1089. + FLOAT_TYPE(data_b[b_offset + y_idx + l +112]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 7] & 0xF) * FLOAT_TYPE((data_a[ib0 + i].qs[q_offset + l +16] >> 6) & 3);
  1090. sum2 += FLOAT_TYPE(data_b[b_offset + y_idx + l + 0]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 0] >> 4) & 0xF)
  1091. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 16]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 1] >> 4) & 0xF)
  1092. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 32]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 2] >> 4) & 0xF)
  1093. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 48]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 3] >> 4) & 0xF)
  1094. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 64]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 4] >> 4) & 0xF)
  1095. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 80]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 5] >> 4) & 0xF)
  1096. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 96]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 6] >> 4) & 0xF)
  1097. + FLOAT_TYPE(data_b[b_offset + y_idx + l +112]) * FLOAT_TYPE((data_a[ib0 + i].scales[s_offset + 7] >> 4) & 0xF);
  1098. }
  1099. tmp[16 * ix + tid] += dall * sum1 - dmin * sum2;
  1100. }
  1101. // sum up partial sums and write back result
  1102. barrier();
  1103. [[unroll]] for (uint s = 16; s > 0; s >>= 1) {
  1104. if (tid < s) {
  1105. tmp[tid] += tmp[tid + s];
  1106. }
  1107. barrier();
  1108. }
  1109. if (tid == 0) {
  1110. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1111. }
  1112. }
  1113. """
  1114. mul_mat_vec_q3_K_body = """
  1115. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  1116. shared FLOAT_TYPE tmp[32];
  1117. void main() {
  1118. const uint row = gl_WorkGroupID.x;
  1119. const uint batch_idx = gl_GlobalInvocationID.y;
  1120. #ifdef MUL_MAT_ID
  1121. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  1122. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  1123. #endif
  1124. const uint i13 = batch_idx / p.ne12;
  1125. const uint i12 = batch_idx % p.ne12;
  1126. const uint i03 = i13 / p.broadcast3;
  1127. const uint i02 = i12 / p.broadcast2;
  1128. const uint batch_idx_a = i03 * p.ne02 + i02;
  1129. #ifdef MUL_MAT_ID
  1130. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  1131. #endif
  1132. const uint a_offset =
  1133. #ifdef MUL_MAT_ID
  1134. expert_id * p.expert_stride_a +
  1135. #endif
  1136. batch_idx_a * p.batch_stride_a;
  1137. const uint b_offset =
  1138. #ifdef MUL_MAT_ID
  1139. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  1140. expert_idx1 * p.expert_stride_b1 +
  1141. #endif
  1142. batch_idx * p.batch_stride_b;
  1143. const uint d_offset =
  1144. #ifdef MUL_MAT_ID
  1145. expert_idx0 * p.expert_stride_b0 +
  1146. expert_idx1 * p.expert_stride_b1 +
  1147. #endif
  1148. batch_idx * p.batch_stride_d;
  1149. const uint num_blocks_per_row = p.ncols / QUANT_K;
  1150. const uint ib0 = a_offset / QUANT_K + row*num_blocks_per_row;
  1151. const uint tid = gl_LocalInvocationID.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  1152. const uint ix = gl_LocalInvocationID.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  1153. const uint step = 16/K_QUANTS_PER_ITERATION; // 16 or 8
  1154. const uint v_im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  1155. const uint v_in = tid - step*v_im; // 0...15 or 0...7
  1156. const uint8_t m = uint8_t(1 << (4 * v_im));
  1157. const uint l0 = K_QUANTS_PER_ITERATION*v_in; // 0...15
  1158. const uint q_offset = 32*v_im + l0;
  1159. const uint y_offset = 128*v_im + l0;
  1160. tmp[16 * ix + tid] = FLOAT_TYPE(0.0); // partial sum for thread in warp
  1161. const uint s_shift = 4 * v_im;
  1162. [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  1163. const uint y_idx = i * QUANT_K + y_offset;
  1164. const FLOAT_TYPE d = FLOAT_TYPE(data_a[ib0 + i].d);
  1165. FLOAT_TYPE sum = FLOAT_TYPE(0.0);
  1166. for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) {
  1167. sum += FLOAT_TYPE(data_b[b_offset + y_idx + l + 0]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[0] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[ 8] >> (s_shift + 0) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l ] ) & 3) - (((data_a[ib0 + i].hmask[l0 + l ] & (m << 0)) != 0) ? 0 : 4))
  1168. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 32]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[2] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[10] >> (s_shift + 0) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l ] >> 2) & 3) - (((data_a[ib0 + i].hmask[l0 + l ] & (m << 1)) != 0) ? 0 : 4))
  1169. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 64]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[4] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[ 8] >> (s_shift + 2) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l ] >> 4) & 3) - (((data_a[ib0 + i].hmask[l0 + l ] & (m << 2)) != 0) ? 0 : 4))
  1170. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 96]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[6] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[10] >> (s_shift + 2) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l ] >> 6) & 3) - (((data_a[ib0 + i].hmask[l0 + l ] & (m << 3)) != 0) ? 0 : 4))
  1171. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 16]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[1] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[ 9] >> (s_shift + 0) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l+16] ) & 3) - (((data_a[ib0 + i].hmask[l0 + l+16] & (m << 0)) != 0) ? 0 : 4))
  1172. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 48]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[3] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[11] >> (s_shift + 0) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l+16] >> 2) & 3) - (((data_a[ib0 + i].hmask[l0 + l+16] & (m << 1)) != 0) ? 0 : 4))
  1173. + FLOAT_TYPE(data_b[b_offset + y_idx + l + 80]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[5] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[ 9] >> (s_shift + 2) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l+16] >> 4) & 3) - (((data_a[ib0 + i].hmask[l0 + l+16] & (m << 2)) != 0) ? 0 : 4))
  1174. + FLOAT_TYPE(data_b[b_offset + y_idx + l +112]) * FLOAT_TYPE(int8_t(((data_a[ib0 + i].scales[7] >> s_shift) & 0xF) | ((data_a[ib0 + i].scales[11] >> (s_shift + 2) & 0x3) << 4)) - 32) * FLOAT_TYPE(((data_a[ib0 + i].qs[q_offset + l+16] >> 6) & 3) - (((data_a[ib0 + i].hmask[l0 + l+16] & (m << 3)) != 0) ? 0 : 4));
  1175. }
  1176. tmp[16 * ix + tid] += d * sum;
  1177. }
  1178. // sum up partial sums and write back result
  1179. barrier();
  1180. [[unroll]] for (uint s = 16; s > 0; s >>= 1) {
  1181. if (tid < s) {
  1182. tmp[tid] += tmp[tid + s];
  1183. }
  1184. barrier();
  1185. }
  1186. if (tid == 0) {
  1187. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1188. }
  1189. }
  1190. """
  1191. mul_mat_vec_q4_K_body = """
  1192. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  1193. shared FLOAT_TYPE tmp[32];
  1194. void main() {
  1195. const uint row = gl_WorkGroupID.x;
  1196. const uint batch_idx = gl_GlobalInvocationID.y;
  1197. #ifdef MUL_MAT_ID
  1198. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  1199. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  1200. #endif
  1201. const uint i13 = batch_idx / p.ne12;
  1202. const uint i12 = batch_idx % p.ne12;
  1203. const uint i03 = i13 / p.broadcast3;
  1204. const uint i02 = i12 / p.broadcast2;
  1205. const uint batch_idx_a = i03 * p.ne02 + i02;
  1206. #ifdef MUL_MAT_ID
  1207. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  1208. #endif
  1209. const uint a_offset =
  1210. #ifdef MUL_MAT_ID
  1211. expert_id * p.expert_stride_a +
  1212. #endif
  1213. batch_idx_a * p.batch_stride_a;
  1214. const uint b_offset =
  1215. #ifdef MUL_MAT_ID
  1216. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  1217. expert_idx1 * p.expert_stride_b1 +
  1218. #endif
  1219. batch_idx * p.batch_stride_b;
  1220. const uint d_offset =
  1221. #ifdef MUL_MAT_ID
  1222. expert_idx0 * p.expert_stride_b0 +
  1223. expert_idx1 * p.expert_stride_b1 +
  1224. #endif
  1225. batch_idx * p.batch_stride_d;
  1226. const uint num_blocks_per_row = p.ncols / QUANT_K;
  1227. const uint ib0 = a_offset / QUANT_K + row*num_blocks_per_row;
  1228. const uint tid = gl_LocalInvocationID.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  1229. const uint ix = gl_LocalInvocationID.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  1230. const uint step = 8/K_QUANTS_PER_ITERATION; // 8 or 4
  1231. const uint il = tid/step; // 0...3
  1232. const uint ir = tid - step*il; // 0...7 or 0...3
  1233. const uint n = 2 * K_QUANTS_PER_ITERATION; // 2 or 4
  1234. const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  1235. const uint v_in = il % 2;
  1236. const uint l0 = n * (2 * ir + v_in); // 0...15
  1237. const uint q_offset = 32*v_im + l0;
  1238. const uint y_offset = 64*v_im + l0;
  1239. tmp[16 * ix + tid] = FLOAT_TYPE(0.0); // partial sum for thread in warp
  1240. [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  1241. const uint y1_idx = i * QUANT_K + y_offset;
  1242. const uint y2_idx = y1_idx + 128;
  1243. const FLOAT_TYPE dall = FLOAT_TYPE(data_a[ib0 + i].d.x);
  1244. const FLOAT_TYPE dmin = FLOAT_TYPE(data_a[ib0 + i].d.y);
  1245. const uint8_t sc0 = uint8_t( data_a[ib0 + i].scales[v_im * 2 ] & 0x3f);
  1246. const uint8_t sc1 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 1] & 0x3f);
  1247. const uint8_t sc2 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 4] & 0x3f);
  1248. const uint8_t sc3 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 5] & 0x3f);
  1249. const uint8_t sc4 = uint8_t(( data_a[ib0 + i].scales[v_im * 2 + 8] & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 ] & 0xc0) >> 2));
  1250. const uint8_t sc5 = uint8_t(( data_a[ib0 + i].scales[v_im * 2 + 9] & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 1] & 0xc0) >> 2));
  1251. const uint8_t sc6 = uint8_t(((data_a[ib0 + i].scales[v_im * 2 + 8] >> 4) & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 4] & 0xc0) >> 2));
  1252. const uint8_t sc7 = uint8_t(((data_a[ib0 + i].scales[v_im * 2 + 9] >> 4) & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 5] & 0xc0) >> 2));
  1253. #if K_QUANTS_PER_ITERATION == 2
  1254. const uint8_t q4_0 = uint8_t(data_a[ib0 + i].qs[q_offset ] & 0xf);
  1255. const uint8_t q4_1 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] & 0xf);
  1256. const uint8_t q4_2 = uint8_t(data_a[ib0 + i].qs[q_offset + 2] & 0xf);
  1257. const uint8_t q4_3 = uint8_t(data_a[ib0 + i].qs[q_offset + 3] & 0xf);
  1258. const uint8_t q4_4 = uint8_t(data_a[ib0 + i].qs[q_offset ] >> 4);
  1259. const uint8_t q4_5 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] >> 4);
  1260. const uint8_t q4_6 = uint8_t(data_a[ib0 + i].qs[q_offset + 2] >> 4);
  1261. const uint8_t q4_7 = uint8_t(data_a[ib0 + i].qs[q_offset + 3] >> 4);
  1262. const uint8_t q4_8 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] & 0xf);
  1263. const uint8_t q4_9 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] & 0xf);
  1264. const uint8_t q4_10 = uint8_t(data_a[ib0 + i].qs[q_offset + 66] & 0xf);
  1265. const uint8_t q4_11 = uint8_t(data_a[ib0 + i].qs[q_offset + 67] & 0xf);
  1266. const uint8_t q4_12 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] >> 4);
  1267. const uint8_t q4_13 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] >> 4);
  1268. const uint8_t q4_14 = uint8_t(data_a[ib0 + i].qs[q_offset + 66] >> 4);
  1269. const uint8_t q4_15 = uint8_t(data_a[ib0 + i].qs[q_offset + 67] >> 4);
  1270. const FLOAT_TYPE sx = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y1_idx]) * q4_0 + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) * q4_1 + FLOAT_TYPE(data_b[b_offset + y1_idx + 2]) * q4_2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 3]) * q4_3);
  1271. const FLOAT_TYPE sy = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) * q4_4 + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) * q4_5 + FLOAT_TYPE(data_b[b_offset + y1_idx + 34]) * q4_6 + FLOAT_TYPE(data_b[b_offset + y1_idx + 35]) * q4_7);
  1272. const FLOAT_TYPE sz = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y2_idx]) * q4_8 + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) * q4_9 + FLOAT_TYPE(data_b[b_offset + y2_idx + 2]) * q4_10 + FLOAT_TYPE(data_b[b_offset + y2_idx + 3]) * q4_11);
  1273. const FLOAT_TYPE sw = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) * q4_12 + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) * q4_13 + FLOAT_TYPE(data_b[b_offset + y2_idx + 34]) * q4_14 + FLOAT_TYPE(data_b[b_offset + y2_idx + 35]) * q4_15);
  1274. const FLOAT_TYPE smin = FLOAT_TYPE(
  1275. FLOAT_TYPE(data_b[b_offset + y1_idx ]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx ]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) * sc7
  1276. + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) * sc7
  1277. + FLOAT_TYPE(data_b[b_offset + y1_idx + 2]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 34]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx + 2]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 34]) * sc7
  1278. + FLOAT_TYPE(data_b[b_offset + y1_idx + 3]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 35]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx + 3]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 35]) * sc7
  1279. );
  1280. tmp[16 * ix + tid] += FLOAT_TYPE(dall * (sx * sc0 + sy * sc1 + sz * sc4 + sw * sc5) - dmin * smin);
  1281. #else
  1282. const uint8_t q4_0 = uint8_t(data_a[ib0 + i].qs[q_offset ] & 0xf);
  1283. const uint8_t q4_1 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] & 0xf);
  1284. const uint8_t q4_2 = uint8_t(data_a[ib0 + i].qs[q_offset ] >> 4);
  1285. const uint8_t q4_3 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] >> 4);
  1286. const uint8_t q4_4 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] & 0xf);
  1287. const uint8_t q4_5 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] & 0xf);
  1288. const uint8_t q4_6 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] >> 4);
  1289. const uint8_t q4_7 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] >> 4);
  1290. const FLOAT_TYPE sx = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y1_idx ]) * q4_0 + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) * q4_1);
  1291. const FLOAT_TYPE sy = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) * q4_2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) * q4_3);
  1292. const FLOAT_TYPE sz = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y2_idx ]) * q4_4 + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) * q4_5);
  1293. const FLOAT_TYPE sw = FLOAT_TYPE(FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) * q4_6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) * q4_7);
  1294. const FLOAT_TYPE smin = FLOAT_TYPE(
  1295. FLOAT_TYPE(data_b[b_offset + y1_idx]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) * sc7
  1296. + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) * sc2 + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) * sc3 + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) * sc6 + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) * sc7
  1297. );
  1298. tmp[16 * ix + tid] += FLOAT_TYPE(dall * (sx * FLOAT_TYPE(data_a[ib0 + i].scales[v_im] & 0x3f) + sy * FLOAT_TYPE(data_a[ib0 + i].scales[v_im + 1] & 0x3f) + sz * FLOAT_TYPE((data_a[ib0 + i].scales[v_im + 4] & 0x0f) | ((data_a[ib0 + i].scales[v_im] & 0xc0) >> 2)) + sw * FLOAT_TYPE((data_a[ib0 + i].scales[v_im + 5] & 0x0f) | ((data_a[ib0 + i].scales[v_im + 1] & 0xc0) >> 2))) - dmin * smin);
  1299. #endif
  1300. }
  1301. // sum up partial sums and write back result
  1302. barrier();
  1303. [[unroll]] for (uint s = 16; s > 0; s >>= 1) {
  1304. if (tid < s) {
  1305. tmp[tid] += tmp[tid + s];
  1306. }
  1307. barrier();
  1308. }
  1309. if (tid == 0) {
  1310. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1311. }
  1312. }
  1313. """
  1314. mul_mat_vec_q5_K_body = """
  1315. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  1316. shared FLOAT_TYPE tmp[32];
  1317. void main() {
  1318. const uint row = gl_WorkGroupID.x;
  1319. const uint batch_idx = gl_GlobalInvocationID.y;
  1320. #ifdef MUL_MAT_ID
  1321. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  1322. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  1323. #endif
  1324. const uint i13 = batch_idx / p.ne12;
  1325. const uint i12 = batch_idx % p.ne12;
  1326. const uint i03 = i13 / p.broadcast3;
  1327. const uint i02 = i12 / p.broadcast2;
  1328. const uint batch_idx_a = i03 * p.ne02 + i02;
  1329. #ifdef MUL_MAT_ID
  1330. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  1331. #endif
  1332. const uint a_offset =
  1333. #ifdef MUL_MAT_ID
  1334. expert_id * p.expert_stride_a +
  1335. #endif
  1336. batch_idx_a * p.batch_stride_a;
  1337. const uint b_offset =
  1338. #ifdef MUL_MAT_ID
  1339. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  1340. expert_idx1 * p.expert_stride_b1 +
  1341. #endif
  1342. batch_idx * p.batch_stride_b;
  1343. const uint d_offset =
  1344. #ifdef MUL_MAT_ID
  1345. expert_idx0 * p.expert_stride_b0 +
  1346. expert_idx1 * p.expert_stride_b1 +
  1347. #endif
  1348. batch_idx * p.batch_stride_d;
  1349. const uint num_blocks_per_row = p.ncols / QUANT_K;
  1350. const uint ib0 = a_offset / QUANT_K + row*num_blocks_per_row;
  1351. const uint tid = gl_LocalInvocationID.x/2; // 0...31 or 0...16
  1352. const uint ix = gl_LocalInvocationID.x%2; // 0 or 0, 1
  1353. const uint il = tid/4; // 0...3
  1354. const uint ir = tid - 4*il; // 0...7 or 0...3
  1355. const uint v_im = il / 2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224
  1356. const uint v_in = il % 2;
  1357. const uint l0 = 4*ir + 2*v_in; // 0...15
  1358. const uint q_offset = 32*v_im + l0;
  1359. const uint y_offset = 64*v_im + l0;
  1360. const uint8_t hm1 = uint8_t(1 << (2*v_im));
  1361. const uint8_t hm2 = uint8_t(hm1 << 4);
  1362. tmp[16 * ix + tid] = FLOAT_TYPE(0.0); // partial sum for thread in warp
  1363. [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += 2) {
  1364. const uint y1_idx = i * QUANT_K + y_offset;
  1365. const uint y2_idx = y1_idx + 128;
  1366. const FLOAT_TYPE dall = FLOAT_TYPE(data_a[ib0 + i].d.x);
  1367. const FLOAT_TYPE dmin = FLOAT_TYPE(data_a[ib0 + i].d.y);
  1368. const uint8_t sc0 = uint8_t( data_a[ib0 + i].scales[v_im * 2 ] & 0x3f);
  1369. const uint8_t sc1 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 1] & 0x3f);
  1370. const uint8_t sc2 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 4] & 0x3f);
  1371. const uint8_t sc3 = uint8_t( data_a[ib0 + i].scales[v_im * 2 + 5] & 0x3f);
  1372. const uint8_t sc4 = uint8_t(( data_a[ib0 + i].scales[v_im * 2 + 8] & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 ] & 0xc0) >> 2));
  1373. const uint8_t sc5 = uint8_t(( data_a[ib0 + i].scales[v_im * 2 + 9] & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 1] & 0xc0) >> 2));
  1374. const uint8_t sc6 = uint8_t(((data_a[ib0 + i].scales[v_im * 2 + 8] >> 4) & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 4] & 0xc0) >> 2));
  1375. const uint8_t sc7 = uint8_t(((data_a[ib0 + i].scales[v_im * 2 + 9] >> 4) & 0x0f) | ((data_a[ib0 + i].scales[v_im * 2 + 5] & 0xc0) >> 2));
  1376. const uint8_t q4_0 = uint8_t(data_a[ib0 + i].qs[q_offset ] & 0xf);
  1377. const uint8_t q4_1 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] & 0xf);
  1378. const uint8_t q4_2 = uint8_t(data_a[ib0 + i].qs[q_offset + 16] & 0xf);
  1379. const uint8_t q4_3 = uint8_t(data_a[ib0 + i].qs[q_offset + 17] & 0xf);
  1380. const uint8_t q4_4 = uint8_t(data_a[ib0 + i].qs[q_offset ] >> 4);
  1381. const uint8_t q4_5 = uint8_t(data_a[ib0 + i].qs[q_offset + 1] >> 4);
  1382. const uint8_t q4_6 = uint8_t(data_a[ib0 + i].qs[q_offset + 16] >> 4);
  1383. const uint8_t q4_7 = uint8_t(data_a[ib0 + i].qs[q_offset + 17] >> 4);
  1384. const uint8_t q4_8 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] & 0xf);
  1385. const uint8_t q4_9 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] & 0xf);
  1386. const uint8_t q4_10 = uint8_t(data_a[ib0 + i].qs[q_offset + 80] & 0xf);
  1387. const uint8_t q4_11 = uint8_t(data_a[ib0 + i].qs[q_offset + 81] & 0xf);
  1388. const uint8_t q4_12 = uint8_t(data_a[ib0 + i].qs[q_offset + 64] >> 4);
  1389. const uint8_t q4_13 = uint8_t(data_a[ib0 + i].qs[q_offset + 65] >> 4);
  1390. const uint8_t q4_14 = uint8_t(data_a[ib0 + i].qs[q_offset + 80] >> 4);
  1391. const uint8_t q4_15 = uint8_t(data_a[ib0 + i].qs[q_offset + 81] >> 4);
  1392. const FLOAT_TYPE sx = FLOAT_TYPE(
  1393. FLOAT_TYPE(data_b[b_offset + y1_idx ]) * (q4_0 + (((data_a[ib0 + i].qh[l0 ] & hm1) != 0) ? 16 : 0))
  1394. + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) * (q4_1 + (((data_a[ib0 + i].qh[l0 + 1] & hm1) != 0) ? 16 : 0))
  1395. + FLOAT_TYPE(data_b[b_offset + y1_idx + 16]) * (q4_2 + (((data_a[ib0 + i].qh[l0 + 16] & hm1) != 0) ? 16 : 0))
  1396. + FLOAT_TYPE(data_b[b_offset + y1_idx + 17]) * (q4_3 + (((data_a[ib0 + i].qh[l0 + 17] & hm1) != 0) ? 16 : 0))
  1397. );
  1398. const FLOAT_TYPE sy = FLOAT_TYPE(
  1399. FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) * (q4_4 + (((data_a[ib0 + i].qh[l0 ] & (hm1 << 1)) != 0) ? 16 : 0))
  1400. + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) * (q4_5 + (((data_a[ib0 + i].qh[l0 + 1] & (hm1 << 1)) != 0) ? 16 : 0))
  1401. + FLOAT_TYPE(data_b[b_offset + y1_idx + 48]) * (q4_6 + (((data_a[ib0 + i].qh[l0 + 16] & (hm1 << 1)) != 0) ? 16 : 0))
  1402. + FLOAT_TYPE(data_b[b_offset + y1_idx + 49]) * (q4_7 + (((data_a[ib0 + i].qh[l0 + 17] & (hm1 << 1)) != 0) ? 16 : 0))
  1403. );
  1404. const FLOAT_TYPE sz = FLOAT_TYPE(
  1405. FLOAT_TYPE(data_b[b_offset + y2_idx ]) * (q4_8 + (((data_a[ib0 + i].qh[l0 ] & hm2) != 0) ? 16 : 0))
  1406. + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) * (q4_9 + (((data_a[ib0 + i].qh[l0 + 1] & hm2) != 0) ? 16 : 0))
  1407. + FLOAT_TYPE(data_b[b_offset + y2_idx + 16]) * (q4_10 + (((data_a[ib0 + i].qh[l0 + 16] & hm2) != 0) ? 16 : 0))
  1408. + FLOAT_TYPE(data_b[b_offset + y2_idx + 17]) * (q4_11 + (((data_a[ib0 + i].qh[l0 + 17] & hm2) != 0) ? 16 : 0))
  1409. );
  1410. const FLOAT_TYPE sw = FLOAT_TYPE(
  1411. FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) * (q4_12 + (((data_a[ib0 + i].qh[l0 ] & (hm2 << 1)) != 0) ? 16 : 0))
  1412. + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) * (q4_13 + (((data_a[ib0 + i].qh[l0 + 1] & (hm2 << 1)) != 0) ? 16 : 0))
  1413. + FLOAT_TYPE(data_b[b_offset + y2_idx + 48]) * (q4_14 + (((data_a[ib0 + i].qh[l0 + 16] & (hm2 << 1)) != 0) ? 16 : 0))
  1414. + FLOAT_TYPE(data_b[b_offset + y2_idx + 49]) * (q4_15 + (((data_a[ib0 + i].qh[l0 + 17] & (hm2 << 1)) != 0) ? 16 : 0))
  1415. );
  1416. const FLOAT_TYPE smin = FLOAT_TYPE(
  1417. (FLOAT_TYPE(data_b[b_offset + y1_idx]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 1]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 16]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 17])) * sc2 + (FLOAT_TYPE(data_b[b_offset + y1_idx + 32]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 33]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 48]) + FLOAT_TYPE(data_b[b_offset + y1_idx + 49])) * sc3
  1418. + (FLOAT_TYPE(data_b[b_offset + y2_idx]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 1]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 16]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 17])) * sc6 + (FLOAT_TYPE(data_b[b_offset + y2_idx + 32]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 33]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 48]) + FLOAT_TYPE(data_b[b_offset + y2_idx + 49])) * sc7
  1419. );
  1420. tmp[16 * ix + tid] += FLOAT_TYPE(dall * (sx * sc0 + sy * sc1 + sz * sc4 + sw * sc5) - dmin * smin);
  1421. }
  1422. // sum up partial sums and write back result
  1423. barrier();
  1424. [[unroll]] for (uint s = 16; s > 0; s >>= 1) {
  1425. if (tid < s) {
  1426. tmp[tid] += tmp[tid + s];
  1427. }
  1428. barrier();
  1429. }
  1430. if (tid == 0) {
  1431. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1432. }
  1433. }
  1434. """
  1435. mul_mat_vec_q6_K_body = """
  1436. layout(local_size_x = 32, local_size_y = 1, local_size_z = 1) in;
  1437. shared FLOAT_TYPE tmp[32];
  1438. void main() {
  1439. const uint row = gl_WorkGroupID.x;
  1440. const uint batch_idx = gl_GlobalInvocationID.y;
  1441. #ifdef MUL_MAT_ID
  1442. const uint expert_idx1 = gl_GlobalInvocationID.z / p.nei0;
  1443. const uint expert_idx0 = gl_GlobalInvocationID.z % p.nei0;
  1444. #endif
  1445. const uint i13 = batch_idx / p.ne12;
  1446. const uint i12 = batch_idx % p.ne12;
  1447. const uint i03 = i13 / p.broadcast3;
  1448. const uint i02 = i12 / p.broadcast2;
  1449. const uint batch_idx_a = i03 * p.ne02 + i02;
  1450. #ifdef MUL_MAT_ID
  1451. const uint expert_id = data_ids[expert_idx1 * p.nbi1 + expert_idx0];
  1452. #endif
  1453. const uint a_offset =
  1454. #ifdef MUL_MAT_ID
  1455. expert_id * p.expert_stride_a +
  1456. #endif
  1457. batch_idx_a * p.batch_stride_a;
  1458. const uint b_offset =
  1459. #ifdef MUL_MAT_ID
  1460. (expert_idx0 % p.ne11) * p.expert_stride_b0 +
  1461. expert_idx1 * p.expert_stride_b1 +
  1462. #endif
  1463. batch_idx * p.batch_stride_b;
  1464. const uint d_offset =
  1465. #ifdef MUL_MAT_ID
  1466. expert_idx0 * p.expert_stride_b0 +
  1467. expert_idx1 * p.expert_stride_b1 +
  1468. #endif
  1469. batch_idx * p.batch_stride_d;
  1470. const uint num_blocks_per_row = p.ncols / QUANT_K;
  1471. const uint ib0 = a_offset / QUANT_K + row*num_blocks_per_row;
  1472. const uint tid = gl_LocalInvocationID.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16
  1473. const uint ix = gl_LocalInvocationID.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1
  1474. const uint step = 16/K_QUANTS_PER_ITERATION; // 16 or 8
  1475. const uint v_im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128...
  1476. const uint v_in = tid - step*v_im; // 0...15 or 0...7
  1477. #if K_QUANTS_PER_ITERATION == 1
  1478. const uint l0 = v_in; // 0...15
  1479. const uint is = 0;
  1480. #else
  1481. const uint l0 = 4 * v_in; // 0, 4, 8, ..., 28
  1482. const uint is = v_in / 4;
  1483. #endif
  1484. const uint ql_offset = 64*v_im + l0;
  1485. const uint qh_offset = 32*v_im + l0;
  1486. const uint s_offset = 8*v_im + is;
  1487. const uint y_offset = 128*v_im + l0;
  1488. tmp[16 * ix + tid] = FLOAT_TYPE(0.0); // partial sum for thread in warp
  1489. [[unroll]] for (uint i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) {
  1490. const uint y_idx = i * QUANT_K + y_offset;
  1491. const FLOAT_TYPE d = FLOAT_TYPE(data_a[ib0 + i].d);
  1492. #if K_QUANTS_PER_ITERATION == 1
  1493. FLOAT_TYPE sum = FLOAT_TYPE(data_b[b_offset + y_idx + 0]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 0]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 0] & 0xF) | ((data_a[ib0 + i].qh[qh_offset + 0] & 0x03) << 4)) - 32)
  1494. + FLOAT_TYPE(data_b[b_offset + y_idx + 16]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 1]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 16] & 0xF) | ((data_a[ib0 + i].qh[qh_offset + 16] & 0x03) << 4)) - 32)
  1495. + FLOAT_TYPE(data_b[b_offset + y_idx + 32]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 2]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 32] & 0xF) | ((data_a[ib0 + i].qh[qh_offset + 0] & 0x0c) << 2)) - 32)
  1496. + FLOAT_TYPE(data_b[b_offset + y_idx + 48]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 3]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 48] & 0xF) | ((data_a[ib0 + i].qh[qh_offset + 16] & 0x0c) << 2)) - 32)
  1497. + FLOAT_TYPE(data_b[b_offset + y_idx + 64]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 4]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 0] >> 4) | ((data_a[ib0 + i].qh[qh_offset + 0] & 0x30) >> 0)) - 32)
  1498. + FLOAT_TYPE(data_b[b_offset + y_idx + 80]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 5]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 16] >> 4) | ((data_a[ib0 + i].qh[qh_offset + 16] & 0x30) >> 0)) - 32)
  1499. + FLOAT_TYPE(data_b[b_offset + y_idx + 96]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 6]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 32] >> 4) | ((data_a[ib0 + i].qh[qh_offset + 0] & 0xc0) >> 2)) - 32)
  1500. + FLOAT_TYPE(data_b[b_offset + y_idx +112]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 7]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + 48] >> 4) | ((data_a[ib0 + i].qh[qh_offset + 16] & 0xc0) >> 2)) - 32);
  1501. tmp[16 * ix + tid] += sum;
  1502. #else
  1503. FLOAT_TYPE sum = FLOAT_TYPE(0.0);
  1504. [[unroll]] for (int l = 0; l < 4; ++l) {
  1505. sum += FLOAT_TYPE(data_b[b_offset + y_idx + l+ 0]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 0]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + l+ 0] & 0xF) | (((data_a[ib0 + i].qh[qh_offset + l] >> 0) & 3) << 4)) - 32)
  1506. + FLOAT_TYPE(data_b[b_offset + y_idx + l+32]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 2]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + l+32] & 0xF) | (((data_a[ib0 + i].qh[qh_offset + l] >> 2) & 3) << 4)) - 32)
  1507. + FLOAT_TYPE(data_b[b_offset + y_idx + l+64]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 4]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + l+ 0] >> 4) | (((data_a[ib0 + i].qh[qh_offset + l] >> 4) & 3) << 4)) - 32)
  1508. + FLOAT_TYPE(data_b[b_offset + y_idx + l+96]) * FLOAT_TYPE(data_a[ib0 + i].scales[s_offset + 6]) * d * FLOAT_TYPE(int8_t((data_a[ib0 + i].ql[ql_offset + l+32] >> 4) | (((data_a[ib0 + i].qh[qh_offset + l] >> 6) & 3) << 4)) - 32);
  1509. }
  1510. tmp[16 * ix + tid] += sum;
  1511. #endif
  1512. }
  1513. // sum up partial sums and write back result
  1514. barrier();
  1515. [[unroll]] for (uint s = 16; s > 0; s >>= 1) {
  1516. if (tid < s) {
  1517. tmp[tid] += tmp[tid + s];
  1518. }
  1519. barrier();
  1520. }
  1521. if (tid == 0) {
  1522. data_d[d_offset + row] = D_TYPE(tmp[0]);
  1523. }
  1524. }
  1525. """
  1526. mul_mat_p021_src = """#version 450
  1527. #extension GL_EXT_control_flow_attributes : enable
  1528. #extension GL_EXT_shader_16bit_storage : require
  1529. #define BLOCK_SIZE 32
  1530. #define FLOAT_TYPE float
  1531. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1532. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  1533. layout (binding = 1) readonly buffer B {B_TYPE data_b[];};
  1534. layout (binding = 2) writeonly buffer D {D_TYPE dst[];};
  1535. layout (push_constant) uniform parameter
  1536. {
  1537. uint ncols_x;
  1538. uint nrows_x;
  1539. uint nchannels_x;
  1540. uint nchannels_y;
  1541. uint b_offset;
  1542. uint d_offset;
  1543. } p;
  1544. shared FLOAT_TYPE tmp[BLOCK_SIZE];
  1545. void main() {
  1546. const uint tid = gl_LocalInvocationID.x;
  1547. const uint row_x = gl_GlobalInvocationID.y;
  1548. const uint channel = gl_GlobalInvocationID.z;
  1549. const uint channel_x = channel / (p.nchannels_y / p.nchannels_x);
  1550. const uint nrows_y = p.ncols_x;
  1551. const uint nrows_dst = p.nrows_x;
  1552. const uint row_dst = row_x;
  1553. tmp[tid] = FLOAT_TYPE(0.0f);
  1554. for (uint col_x0 = 0; col_x0 < p.ncols_x; col_x0 += BLOCK_SIZE) {
  1555. const uint col_x = col_x0 + tid;
  1556. if (col_x >= p.ncols_x) {
  1557. break;
  1558. }
  1559. // x is transposed and permuted
  1560. const uint ix = row_x*p.nchannels_x*p.ncols_x + channel_x*p.ncols_x + col_x;
  1561. const FLOAT_TYPE xi = FLOAT_TYPE(data_a[ix]);
  1562. const uint row_y = col_x;
  1563. // y is not transposed but permuted
  1564. const uint iy = channel*nrows_y + row_y;
  1565. tmp[tid] += xi * FLOAT_TYPE(data_b[iy]);
  1566. }
  1567. // dst is not transposed and not permuted
  1568. const uint idst = channel*nrows_dst + row_dst;
  1569. // sum up partial sums and write back result
  1570. barrier();
  1571. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  1572. if (tid < s) {
  1573. tmp[tid] += tmp[tid + s];
  1574. }
  1575. barrier();
  1576. }
  1577. if (tid == 0) {
  1578. dst[idst] = tmp[0];
  1579. }
  1580. }
  1581. """
  1582. mul_mat_nc_src = """#version 450
  1583. #extension GL_EXT_control_flow_attributes : enable
  1584. #extension GL_EXT_shader_16bit_storage : require
  1585. #define BLOCK_SIZE 32
  1586. #define FLOAT_TYPE float
  1587. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1588. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  1589. layout (binding = 1) readonly buffer B {B_TYPE data_b[];};
  1590. layout (binding = 2) writeonly buffer D {D_TYPE dst[];};
  1591. layout (push_constant) uniform parameter
  1592. {
  1593. uint ncols_x;
  1594. uint nrows_x;
  1595. uint row_stride_x;
  1596. uint channel_stride_x;
  1597. uint channel_x_divisor;
  1598. uint b_offset;
  1599. uint d_offset;
  1600. } p;
  1601. shared FLOAT_TYPE tmp[BLOCK_SIZE];
  1602. void main() {
  1603. const uint tid = gl_LocalInvocationID.x;
  1604. const uint row_x = gl_GlobalInvocationID.y;
  1605. const uint channel = gl_GlobalInvocationID.z;
  1606. const uint channel_x = channel / p.channel_x_divisor;
  1607. const uint nrows_y = p.ncols_x;
  1608. const uint nrows_dst = p.nrows_x;
  1609. const uint row_dst = row_x;
  1610. const uint idst = channel*nrows_dst + row_dst;
  1611. tmp[tid] = 0.0f;
  1612. for (uint col_x0 = 0; col_x0 < p.ncols_x; col_x0 += BLOCK_SIZE) {
  1613. const uint col_x = col_x0 + tid;
  1614. if (col_x >= p.ncols_x) {
  1615. break;
  1616. }
  1617. const uint row_y = col_x;
  1618. const uint ix = channel_x*p.channel_stride_x + row_x*p.row_stride_x + col_x;
  1619. const uint iy = channel*nrows_y + row_y;
  1620. const FLOAT_TYPE xi = FLOAT_TYPE(data_a[ix]);
  1621. tmp[tid] += xi * FLOAT_TYPE(data_b[iy]);
  1622. }
  1623. // sum up partial sums and write back result
  1624. barrier();
  1625. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  1626. if (tid < s) {
  1627. tmp[tid] += tmp[tid + s];
  1628. }
  1629. barrier();
  1630. }
  1631. if (tid == 0) {
  1632. dst[idst] = tmp[0];
  1633. }
  1634. }
  1635. """
  1636. generic_head = """
  1637. #version 450
  1638. #extension GL_EXT_shader_16bit_storage : require
  1639. layout (push_constant) uniform parameter
  1640. {
  1641. uint KX;
  1642. uint KY;
  1643. float param1;
  1644. float param2;
  1645. } p;
  1646. """
  1647. generic_unary_op_head = """#version 450
  1648. #extension GL_EXT_shader_16bit_storage : require
  1649. layout (push_constant) uniform parameter
  1650. {
  1651. uint ne;
  1652. uint ne00; uint ne01; uint ne02; uint ne03; uint nb00; uint nb01; uint nb02; uint nb03;
  1653. uint ne10; uint ne11; uint ne12; uint ne13; uint nb10; uint nb11; uint nb12; uint nb13;
  1654. uint d_offset;
  1655. float param1; float param2;
  1656. } p;"""
  1657. generic_unary_op_layout = """
  1658. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1659. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  1660. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};"""
  1661. generic_unary_op_funcs = """
  1662. uint src0_idx(uint idx) {
  1663. const uint i03 = idx / (p.ne02*p.ne01*p.ne00);
  1664. const uint i03_offset = i03 * p.ne02*p.ne01*p.ne00;
  1665. const uint i02 = (idx - i03_offset) / (p.ne01*p.ne00);
  1666. const uint i02_offset = i02*p.ne01*p.ne00;
  1667. const uint i01 = (idx - i03_offset - i02_offset) / p.ne00;
  1668. const uint i00 = idx - i03_offset - i02_offset - i01*p.ne00;
  1669. return i03*p.nb03 + i02*p.nb02 + i01*p.nb01 + i00*p.nb00;
  1670. }
  1671. uint dst_idx(uint idx) {
  1672. const uint i13 = idx / (p.ne12*p.ne11*p.ne10);
  1673. const uint i13_offset = i13 * p.ne12*p.ne11*p.ne10;
  1674. const uint i12 = (idx - i13_offset) / (p.ne11*p.ne10);
  1675. const uint i12_offset = i12*p.ne11*p.ne10;
  1676. const uint i11 = (idx - i13_offset - i12_offset) / p.ne10;
  1677. const uint i10 = idx - i13_offset - i12_offset - i11*p.ne10;
  1678. return i13*p.nb13 + i12*p.nb12 + i11*p.nb11 + i10*p.nb10;
  1679. }"""
  1680. generic_unary_op_main = """
  1681. void main() {
  1682. if (gl_GlobalInvocationID.x >= p.ne) {
  1683. return;
  1684. }
  1685. """
  1686. generic_unary_op_combined = f"{generic_unary_op_head}\n{generic_unary_op_layout}\n{generic_unary_op_funcs}\n{generic_unary_op_main}"
  1687. generic_binary_op_head = """#version 450
  1688. #extension GL_EXT_shader_16bit_storage : require
  1689. layout (push_constant) uniform parameter
  1690. {
  1691. uint ne;
  1692. uint ne00; uint ne01; uint ne02; uint ne03; uint nb00; uint nb01; uint nb02; uint nb03;
  1693. uint ne10; uint ne11; uint ne12; uint ne13; uint nb10; uint nb11; uint nb12; uint nb13;
  1694. uint ne20; uint ne21; uint ne22; uint ne23; uint nb20; uint nb21; uint nb22; uint nb23;
  1695. uint d_offset;
  1696. float param1; float param2;
  1697. } p;"""
  1698. generic_binary_op_layout = """
  1699. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1700. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  1701. layout (binding = 1) readonly buffer B {B_TYPE data_b[];};
  1702. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};"""
  1703. generic_binary_op_funcs = """
  1704. uint src0_idx(uint idx) {
  1705. const uint i03 = idx / (p.ne02*p.ne01*p.ne00);
  1706. const uint i03_offset = i03 * p.ne02*p.ne01*p.ne00;
  1707. const uint i02 = (idx - i03_offset) / (p.ne01*p.ne00);
  1708. const uint i02_offset = i02*p.ne01*p.ne00;
  1709. const uint i01 = (idx - i03_offset - i02_offset) / p.ne00;
  1710. const uint i00 = idx - i03_offset - i02_offset - i01*p.ne00;
  1711. return i03*p.nb03 + i02*p.nb02 + i01*p.nb01 + i00*p.nb00;
  1712. }
  1713. uint src1_idx(uint idx) {
  1714. const uint i03 = idx / (p.ne02*p.ne01*p.ne00);
  1715. const uint i03_offset = i03 * p.ne02*p.ne01*p.ne00;
  1716. const uint i02 = (idx - i03_offset) / (p.ne01*p.ne00);
  1717. const uint i02_offset = i02*p.ne01*p.ne00;
  1718. const uint i01 = (idx - i03_offset - i02_offset) / p.ne00;
  1719. const uint i00 = idx - i03_offset - i02_offset - i01*p.ne00;
  1720. return (i03 % p.ne13)*p.nb13 + (i02 % p.ne12)*p.nb12 + (i01 % p.ne11)*p.nb11 + (i00 % p.ne10)*p.nb10;
  1721. }
  1722. uint dst_idx(uint idx) {
  1723. const uint i23 = idx / (p.ne22*p.ne21*p.ne20);
  1724. const uint i23_offset = i23 * p.ne22*p.ne21*p.ne20;
  1725. const uint i22 = (idx - i23_offset) / (p.ne21*p.ne20);
  1726. const uint i22_offset = i22*p.ne21*p.ne20;
  1727. const uint i21 = (idx - i23_offset - i22_offset) / p.ne20;
  1728. const uint i20 = idx - i23_offset - i22_offset - i21*p.ne20;
  1729. return i23*p.nb23 + i22*p.nb22 + i21*p.nb21 + i20*p.nb20;
  1730. }"""
  1731. generic_binary_op_main = """
  1732. void main() {
  1733. if (gl_GlobalInvocationID.x >= p.ne) {
  1734. return;
  1735. }
  1736. """
  1737. generic_binary_op_combined = f"{generic_binary_op_head}\n{generic_binary_op_layout}\n{generic_binary_op_funcs}\n{generic_binary_op_main}"
  1738. # MUL F32
  1739. mul_body = """
  1740. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(FLOAT_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]) * FLOAT_TYPE(data_b[src1_idx(gl_GlobalInvocationID.x)]));
  1741. }
  1742. """
  1743. # ADD
  1744. add_body = """
  1745. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(FLOAT_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]) + FLOAT_TYPE(data_b[src1_idx(gl_GlobalInvocationID.x)]));
  1746. }
  1747. """
  1748. # SCALE
  1749. scale_body = """
  1750. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(FLOAT_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]) * FLOAT_TYPE(p.param1));
  1751. }
  1752. """
  1753. # SQR
  1754. sqr_body = """
  1755. const FLOAT_TYPE val = FLOAT_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]);
  1756. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(val * val);
  1757. }
  1758. """
  1759. # CLAMP
  1760. clamp_body = """
  1761. const FLOAT_TYPE val = FLOAT_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]);
  1762. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(val < p.param1 ? p.param1 : (val > p.param2 ? p.param2 : val));
  1763. }
  1764. """
  1765. # CPY
  1766. cpy_end = """
  1767. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = D_TYPE(data_a[src0_idx(gl_GlobalInvocationID.x)]);
  1768. }
  1769. """
  1770. # Causes an optimization error otherwise
  1771. cpy_f16_f16_end = """
  1772. data_d[p.d_offset + dst_idx(gl_GlobalInvocationID.x)] = data_a[src0_idx(gl_GlobalInvocationID.x)];
  1773. }
  1774. """
  1775. # GET_ROWS
  1776. get_rows_float_body = """
  1777. void main() {
  1778. const uint i00 = gl_GlobalInvocationID.x;
  1779. const uint i10 = gl_GlobalInvocationID.y;
  1780. const uint i11 = (gl_GlobalInvocationID.z)/p.ne12;
  1781. const uint i12 = (gl_GlobalInvocationID.z)%p.ne12;
  1782. if (i00 >= p.ne00) {
  1783. return;
  1784. }
  1785. const uint i01 = data_b[i10*p.nb10 + i11*p.nb11 + i12*p.nb12];
  1786. const uint a_offset = i01*p.nb01 + i11*p.nb02 + i12*p.nb03;
  1787. const uint d_offset = i10*p.nb21 + i11*p.nb22 + i12*p.nb23;
  1788. #ifndef OPTIMIZATION_ERROR_WORKAROUND
  1789. data_d[d_offset + i00] = D_TYPE(data_a[a_offset + i00]);
  1790. #else
  1791. data_d[d_offset + i00] = data_a[a_offset + i00];
  1792. #endif
  1793. }
  1794. """
  1795. get_rows_body = """
  1796. void main() {
  1797. const uint i00 = (gl_GlobalInvocationID.x)*2;
  1798. const uint i10 = gl_GlobalInvocationID.y;
  1799. const uint i11 = (gl_GlobalInvocationID.z)/p.ne12;
  1800. const uint i12 = (gl_GlobalInvocationID.z)%p.ne12;
  1801. if (i00 >= p.ne00) {
  1802. return;
  1803. }
  1804. const uint i01 = data_b[i10*p.nb10 + i11*p.nb11 + i12*p.nb12];
  1805. const uint a_offset = i01*p.nb01 + i11*p.nb02 + i12*p.nb03;
  1806. const uint d_offset = i10*p.nb21 + i11*p.nb22 + i12*p.nb23;
  1807. const uint ib = a_offset + i00/QUANT_K; // block index
  1808. const uint iqs = (i00%QUANT_K)/QUANT_R; // quant index
  1809. const uint iybs = i00 - i00%QUANT_K; // dst block start index
  1810. const uint y_offset = QUANT_R == 1 ? 1 : QUANT_K/2;
  1811. vec2 v = dequantize(ib, iqs, 0);
  1812. data_d[d_offset + iybs + iqs ] = D_TYPE(v.x);
  1813. data_d[d_offset + iybs + iqs + y_offset] = D_TYPE(v.y);
  1814. }
  1815. """
  1816. # UNARY
  1817. gelu_body = """
  1818. #extension GL_EXT_control_flow_attributes : enable
  1819. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1820. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1821. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1822. void main() {
  1823. const float GELU_COEF_A = 0.044715f;
  1824. const float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
  1825. const uint i = gl_GlobalInvocationID.x;
  1826. if (i >= p.KX) {
  1827. return;
  1828. }
  1829. const float xi = float(data_a[i]);
  1830. const float val = SQRT_2_OVER_PI*xi*(1.0f + GELU_COEF_A*xi*xi);
  1831. data_d[i] = D_TYPE(0.5f*xi*(2.0f - 2.0f / (exp(2 * val) + 1)));
  1832. }
  1833. """
  1834. silu_body = """
  1835. #extension GL_EXT_control_flow_attributes : enable
  1836. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1837. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1838. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1839. void main() {
  1840. const uint i = gl_GlobalInvocationID.x;
  1841. if (i >= p.KX) {
  1842. return;
  1843. }
  1844. const float xi = float(data_a[i]);
  1845. data_d[i] = D_TYPE(xi / (1.0f + exp(-xi)));
  1846. }
  1847. """
  1848. relu_body = """
  1849. #extension GL_EXT_control_flow_attributes : enable
  1850. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1851. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1852. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1853. void main() {
  1854. const uint i = gl_GlobalInvocationID.x;
  1855. if (i >= p.KX) {
  1856. return;
  1857. }
  1858. data_d[i] = max(float(data_a[i]), 0);
  1859. }
  1860. """
  1861. # DIAG_MASK_INF
  1862. diag_mask_inf_head = """#version 450
  1863. #extension GL_EXT_shader_16bit_storage : require
  1864. layout (push_constant) uniform parameter
  1865. {
  1866. uint ncols;
  1867. uint rows_per_channel;
  1868. uint n_past;
  1869. } p;
  1870. """
  1871. diag_mask_inf_body = """
  1872. #extension GL_EXT_control_flow_attributes : enable
  1873. layout(local_size_x = 512, local_size_y = 1, local_size_z = 1) in;
  1874. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1875. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1876. void main() {
  1877. const uint col = gl_GlobalInvocationID.y;
  1878. const uint row = gl_GlobalInvocationID.x;
  1879. if (col >= p.ncols) {
  1880. return;
  1881. }
  1882. const uint i = row*p.ncols + col;
  1883. if (col > p.n_past + row % p.rows_per_channel) {
  1884. data_d[i] = D_TYPE(uintBitsToFloat(0xFF800000));
  1885. } else {
  1886. data_d[i] = D_TYPE(data_a[i]);
  1887. }
  1888. }
  1889. """
  1890. # NORMS
  1891. norm_body = """
  1892. #extension GL_EXT_control_flow_attributes : enable
  1893. #define BLOCK_SIZE 512
  1894. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1895. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1896. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1897. shared vec2 sum[BLOCK_SIZE];
  1898. void main() {
  1899. const uint row = gl_WorkGroupID.x;
  1900. const uint tid = gl_LocalInvocationID.x;
  1901. sum[tid] = vec2(0.0f, 0.0f);
  1902. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  1903. const float xi = float(data_a[row*p.KX + col]);
  1904. sum[tid].x += xi;
  1905. sum[tid].y += xi * xi;
  1906. }
  1907. // sum up partial sums and write back result
  1908. barrier();
  1909. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  1910. if (tid < s) {
  1911. sum[tid] += sum[tid + s];
  1912. }
  1913. barrier();
  1914. }
  1915. const float mean = sum[0].x / p.KX;
  1916. const float var = sum[0].y / p.KX - mean * mean;
  1917. const float inv_std = inversesqrt(var + p.param1);
  1918. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  1919. data_d[row*p.KX + col] = D_TYPE((float(data_a[row*p.KX + col]) - mean) * inv_std);
  1920. }
  1921. }
  1922. """
  1923. rms_norm_body = """
  1924. #extension GL_EXT_control_flow_attributes : enable
  1925. #define BLOCK_SIZE 512
  1926. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1927. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1928. layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
  1929. shared FLOAT_TYPE sum[BLOCK_SIZE];
  1930. void main() {
  1931. const uint row = gl_WorkGroupID.x;
  1932. const uint tid = gl_LocalInvocationID.x;
  1933. sum[tid] = FLOAT_TYPE(0.0f); // partial sum for thread in warp
  1934. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  1935. const FLOAT_TYPE xi = FLOAT_TYPE(data_a[row*p.KX + col]);
  1936. sum[tid] += xi * xi;
  1937. }
  1938. // sum up partial sums and write back result
  1939. barrier();
  1940. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  1941. if (tid < s) {
  1942. sum[tid] += sum[tid + s];
  1943. }
  1944. barrier();
  1945. }
  1946. const FLOAT_TYPE mean = sum[0] / FLOAT_TYPE(p.KX);
  1947. const FLOAT_TYPE scale = inversesqrt(mean + FLOAT_TYPE(p.param1));
  1948. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  1949. data_d[row*p.KX + col] = D_TYPE(scale * FLOAT_TYPE(data_a[row*p.KX + col]));
  1950. }
  1951. }
  1952. """
  1953. # SOFT_MAX
  1954. soft_max_head = """
  1955. #version 450
  1956. #extension GL_EXT_shader_16bit_storage : require
  1957. layout (push_constant) uniform parameter
  1958. {
  1959. uint KX;
  1960. uint KY;
  1961. uint KZ;
  1962. float scale;
  1963. float max_bias;
  1964. float m0;
  1965. float m1;
  1966. uint n_head_log2;
  1967. } p;
  1968. """
  1969. soft_max_body = """
  1970. #extension GL_EXT_control_flow_attributes : enable
  1971. #define BLOCK_SIZE 512
  1972. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1973. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1974. layout (binding = 1) readonly buffer Y {B_TYPE data_b[];};
  1975. layout (binding = 2) readonly buffer Z {C_TYPE data_c[];};
  1976. layout (binding = 3) buffer D {D_TYPE data_d[];};
  1977. shared FLOAT_TYPE vals[BLOCK_SIZE];
  1978. void main() {
  1979. const uint tid = gl_LocalInvocationID.x;
  1980. const uint rowx = gl_WorkGroupID.x;
  1981. const uint rowy = rowx % p.KY;
  1982. float slope = 0.0f;
  1983. // ALiBi
  1984. if (p.max_bias > 0.0f) {
  1985. const uint h = rowx/p.KY; // head index
  1986. const float base = h < p.n_head_log2 ? p.m0 : p.m1;
  1987. const uint exp = h < p.n_head_log2 ? h + 1 : 2*(h - p.n_head_log2) + 1;
  1988. slope = pow(base, exp);
  1989. }
  1990. // Find max
  1991. vals[tid] = uintBitsToFloat(0xFF800000);
  1992. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  1993. vals[tid] = max(vals[tid], FLOAT_TYPE(data_a[rowx * p.KX + col]) * p.scale + (p.KY > 0 ? FLOAT_TYPE(data_b[rowy * p.KX + col]) : FLOAT_TYPE(0.0f)) + (p.KZ > 0 ? slope * FLOAT_TYPE(data_c[col]) : 0.0f));
  1994. }
  1995. barrier();
  1996. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  1997. if (tid < s) {
  1998. vals[tid] = max(vals[tid], vals[tid + s]);
  1999. }
  2000. barrier();
  2001. }
  2002. const FLOAT_TYPE max_val = vals[0];
  2003. barrier();
  2004. // Sum up values
  2005. vals[tid] = FLOAT_TYPE(0.0f);
  2006. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  2007. const uint i = rowx * p.KX + col;
  2008. const FLOAT_TYPE val = exp(FLOAT_TYPE(data_a[i]) * p.scale + (p.KY > 0 ? FLOAT_TYPE(data_b[rowy * p.KX + col]) : FLOAT_TYPE(0.0f)) - max_val);
  2009. vals[tid] += val;
  2010. data_d[i] = D_TYPE(val);
  2011. }
  2012. barrier();
  2013. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  2014. if (tid < s) {
  2015. vals[tid] += vals[tid + s];
  2016. }
  2017. barrier();
  2018. }
  2019. const D_TYPE divisor = D_TYPE(vals[0]);
  2020. [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
  2021. data_d[rowx*p.KX + col] /= divisor;
  2022. }
  2023. }
  2024. """
  2025. # ROPE
  2026. rope_src = """
  2027. #version 450
  2028. #extension GL_EXT_shader_16bit_storage : require
  2029. layout(local_size_x = 1, local_size_y = 256, local_size_z = 1) in;
  2030. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  2031. layout (binding = 1) readonly buffer Y {int data_b[];};
  2032. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  2033. layout (push_constant) uniform parameter {
  2034. uint ncols;
  2035. float freq_scale;
  2036. uint p_delta_rows;
  2037. float freq_base;
  2038. float ext_factor;
  2039. float attn_factor;
  2040. float corr_dims[4];
  2041. } p;
  2042. float rope_yarn_ramp(const float low, const float high, const uint i0) {
  2043. const float y = (i0 / 2 - low) / max(0.001f, high - low);
  2044. return 1.0f - min(1.0f, max(0.0f, y));
  2045. }
  2046. void rope_yarn(const float theta_extrap, const uint i0, out float cos_theta, out float sin_theta) {
  2047. float mscale = p.attn_factor;
  2048. // Get n-d rotational scaling corrected for extrapolation
  2049. float theta_interp = p.freq_scale * theta_extrap;
  2050. float theta = theta_interp;
  2051. if (p.ext_factor != 0.0f) {
  2052. float ramp_mix = rope_yarn_ramp(p.corr_dims[0], p.corr_dims[1], i0) * p.ext_factor;
  2053. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  2054. // Get n-d magnitude scaling corrected for interpolation
  2055. mscale *= 1.0f + 0.1f * log(1.0f / p.freq_scale);
  2056. }
  2057. cos_theta = cos(theta) * mscale;
  2058. sin_theta = sin(theta) * mscale;
  2059. }
  2060. void main() {
  2061. const uint col = gl_GlobalInvocationID.y * 2;
  2062. const uint row = gl_GlobalInvocationID.x;
  2063. if (col >= p.ncols) {
  2064. return;
  2065. }
  2066. const uint i = row*p.ncols + col;
  2067. const uint i2 = row/p.p_delta_rows;
  2068. const int pos = data_b[i2];
  2069. const float theta_base = pos * pow(p.freq_base, -float(col)/p.ncols);
  2070. float cos_theta, sin_theta;
  2071. rope_yarn(theta_base, col, cos_theta, sin_theta);
  2072. const float x0 = float(data_a[i + 0]);
  2073. const float x1 = float(data_a[i + 1]);
  2074. data_d[i + 0] = D_TYPE(x0*cos_theta - x1*sin_theta);
  2075. data_d[i + 1] = D_TYPE(x0*sin_theta + x1*cos_theta);
  2076. }
  2077. """
  2078. rope_neox_src = """
  2079. #version 450
  2080. #extension GL_EXT_shader_16bit_storage : require
  2081. layout(local_size_x = 1, local_size_y = 256, local_size_z = 1) in;
  2082. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  2083. layout (binding = 1) readonly buffer Y {int data_b[];};
  2084. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  2085. layout (push_constant) uniform parameter {
  2086. uint ncols;
  2087. uint ndims;
  2088. float freq_scale;
  2089. uint p_delta_rows;
  2090. float freq_base;
  2091. float ext_factor;
  2092. float attn_factor;
  2093. float corr_dims[4];
  2094. float theta_scale;
  2095. float inv_ndims;
  2096. } p;
  2097. float rope_yarn_ramp(const float low, const float high, const uint i0) {
  2098. const float y = (i0 / 2 - low) / max(0.001f, high - low);
  2099. return 1.0f - min(1.0f, max(0.0f, y));
  2100. }
  2101. void rope_yarn(const float theta_extrap, const uint i0, out float cos_theta, out float sin_theta) {
  2102. float mscale = p.attn_factor;
  2103. // Get n-d rotational scaling corrected for extrapolation
  2104. float theta_interp = p.freq_scale * theta_extrap;
  2105. float theta = theta_interp;
  2106. if (p.ext_factor != 0.0f) {
  2107. float ramp_mix = rope_yarn_ramp(p.corr_dims[0], p.corr_dims[1], i0) * p.ext_factor;
  2108. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  2109. // Get n-d magnitude scaling corrected for interpolation
  2110. mscale *= 1.0f + 0.1f * log(1.0f / p.freq_scale);
  2111. }
  2112. cos_theta = cos(theta) * mscale;
  2113. sin_theta = sin(theta) * mscale;
  2114. }
  2115. void main() {
  2116. const uint col = gl_GlobalInvocationID.y * 2;
  2117. const uint row = gl_GlobalInvocationID.x;
  2118. if (col >= p.ncols) {
  2119. return;
  2120. }
  2121. const uint ib = col / p.ndims;
  2122. const uint ic = col % p.ndims;
  2123. if (ib > 0) {
  2124. const uint i = row*p.ncols + ib*p.ndims + ic;
  2125. data_d[i + 0] = data_a[i + 0];
  2126. data_d[i + 1] = data_a[i + 1];
  2127. return;
  2128. }
  2129. const uint i = row*p.ncols + ib*p.ndims + ic/2;
  2130. const uint i2 = row/p.p_delta_rows;
  2131. const float cur_rot = p.inv_ndims * ic - ib;
  2132. const int pos = data_b[i2];
  2133. const float theta_base = pos*p.freq_scale*pow(p.theta_scale, col/2.0f);
  2134. float cos_theta, sin_theta;
  2135. rope_yarn(theta_base, uint(cur_rot), cos_theta, sin_theta);
  2136. const float x0 = float(data_a[i + 0]);
  2137. const float x1 = float(data_a[i + p.ndims/2]);
  2138. data_d[i + 0] = D_TYPE(x0*cos_theta - x1*sin_theta);
  2139. data_d[i + p.ndims/2] = D_TYPE(x0*sin_theta + x1*cos_theta);
  2140. }
  2141. """
  2142. argsort_src = """
  2143. #version 450
  2144. #extension GL_EXT_shader_16bit_storage : require
  2145. layout(local_size_x = 1024, local_size_y = 1, local_size_z = 1) in;
  2146. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  2147. layout (binding = 1) buffer D {int data_d[];};
  2148. layout (push_constant) uniform parameter {
  2149. uint ncols;
  2150. bool ascending;
  2151. } p;
  2152. void swap(uint idx0, uint idx1) {
  2153. int tmp = data_d[idx0];
  2154. data_d[idx0] = data_d[idx1];
  2155. data_d[idx1] = tmp;
  2156. }
  2157. void main() {
  2158. // bitonic sort
  2159. const int col = int(gl_LocalInvocationID.x);
  2160. const uint row = gl_WorkGroupID.y;
  2161. if (col >= p.ncols) {
  2162. return;
  2163. }
  2164. const uint a_idx = row * p.ncols;
  2165. const uint d_idx = row * p.ncols;
  2166. // initialize indices
  2167. if (col < p.ncols) {
  2168. data_d[col] = col;
  2169. }
  2170. barrier();
  2171. for (uint k = 2; k <= p.ncols; k *= 2) {
  2172. for (uint j = k / 2; j > 0; j /= 2) {
  2173. const uint ixj = col ^ j;
  2174. if (ixj > col) {
  2175. if ((col & k) == 0) {
  2176. if (p.ascending ? data_a[a_idx + data_d[d_idx + col]] > data_a[a_idx + data_d[d_idx + ixj]] : data_a[a_idx + data_d[d_idx + col]] < data_a[a_idx + data_d[d_idx + ixj]]) {
  2177. swap(d_idx + col, d_idx + ixj);
  2178. }
  2179. } else {
  2180. if (p.ascending ? data_a[a_idx + data_d[d_idx + col]] < data_a[a_idx + data_d[d_idx + ixj]] : data_a[a_idx + data_d[d_idx + col]] > data_a[a_idx + data_d[d_idx + ixj]]) {
  2181. swap(d_idx + col, d_idx + ixj);
  2182. }
  2183. }
  2184. }
  2185. barrier();
  2186. }
  2187. }
  2188. }
  2189. """
  2190. GLSLC = "glslc"
  2191. VK_NUM_TYPES = 16
  2192. GGML_TYPE_F32 = 0
  2193. GGML_TYPE_F16 = 1
  2194. GGML_TYPE_Q4_0 = 2
  2195. GGML_TYPE_Q4_1 = 3
  2196. GGML_TYPE_Q5_0 = 6
  2197. GGML_TYPE_Q5_1 = 7
  2198. GGML_TYPE_Q8_0 = 8
  2199. GGML_TYPE_Q8_1 = 9
  2200. GGML_TYPE_Q2_K = 10
  2201. GGML_TYPE_Q3_K = 11
  2202. GGML_TYPE_Q4_K = 12
  2203. GGML_TYPE_Q5_K = 13
  2204. GGML_TYPE_Q6_K = 14
  2205. GGML_TYPE_Q8_K = 15
  2206. type_names = {
  2207. GGML_TYPE_F32: "f32",
  2208. GGML_TYPE_F16: "f16",
  2209. GGML_TYPE_Q4_0: "q4_0",
  2210. GGML_TYPE_Q4_1: "q4_1",
  2211. GGML_TYPE_Q5_0: "q5_0",
  2212. GGML_TYPE_Q5_1: "q5_1",
  2213. GGML_TYPE_Q8_0: "q8_0",
  2214. GGML_TYPE_Q8_1: "q8_1",
  2215. GGML_TYPE_Q2_K: "q2_K",
  2216. GGML_TYPE_Q3_K: "q3_K",
  2217. GGML_TYPE_Q4_K: "q4_K",
  2218. GGML_TYPE_Q5_K: "q5_K",
  2219. GGML_TYPE_Q6_K: "q6_K",
  2220. GGML_TYPE_Q8_K: "q8_K",
  2221. }
  2222. K_QUANTS_PER_ITERATION = 2
  2223. ASYNCIO_CONCURRENCY = 64
  2224. output_dir = gettempdir()
  2225. lock = asyncio.Lock()
  2226. shader_fnames = []
  2227. async def string_to_spv(name, code, defines, fp16=True):
  2228. f = NamedTemporaryFile(mode="w", delete=False)
  2229. f.write(code)
  2230. f.flush()
  2231. name = f"{name}{'_fp32' if not fp16 else ''}"
  2232. fname = os.path.join(output_dir, f"{name}.comp")
  2233. cmd = [GLSLC, "-fshader-stage=compute", "--target-env=vulkan1.2", "-O", f.name, "-o", fname]
  2234. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2235. proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
  2236. stdout, stderr = await proc.communicate()
  2237. stdout = stdout.decode()
  2238. error = stderr.decode()
  2239. if proc.returncode:
  2240. # Generate preprocessed code
  2241. cmd = [GLSLC, "-E", f.name]
  2242. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2243. proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
  2244. stdout, stderr = await proc.communicate()
  2245. logger.info(" ".join(cmd))
  2246. if proc.returncode:
  2247. raise RuntimeError(f"{name=} {f.name=} {stdout=} {stderr=}")
  2248. preprocessed_code = stdout.decode()
  2249. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2250. code_with_lines = "\n".join([f"{i + 1}: {line}" for i, line in enumerate(preprocessed_code.splitlines())])
  2251. logger.error(f"cannot compile {name}\n\n{code_with_lines}\n\n{error}")
  2252. f.close()
  2253. os.remove(f.name)
  2254. sys.exit(proc.returncode)
  2255. f.close()
  2256. os.remove(f.name)
  2257. async with lock:
  2258. shader_fnames.append((name, fname))
  2259. async def main():
  2260. logger.info("ggml_vulkan: Generating and compiling shaders to SPIR-V")
  2261. tasks = []
  2262. stream = []
  2263. for fp16 in (False, True):
  2264. # mulmat
  2265. if fp16:
  2266. shader_float_type = shader_f16
  2267. load_vec = "8"
  2268. vec_type_f16 = "f16mat2x4"
  2269. vec_type = "mat2x4"
  2270. else:
  2271. shader_float_type = shader_f32
  2272. load_vec = "4"
  2273. vec_type_f16 = "f16vec4"
  2274. vec_type = "vec4"
  2275. stream.clear()
  2276. stream.extend((mulmat_head, shader_float_type, mulmat_body1, mulmat_load_scalar, mulmat_body2))
  2277. tasks.append(string_to_spv("matmul_f32", "".join(stream), {"A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2278. tasks.append(string_to_spv("matmul_f32_aligned", "".join(stream), {"LOAD_VEC_A": 1, "LOAD_VEC_B": load_vec, "A_TYPE": "float", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2279. tasks.append(string_to_spv("matmul_f16", "".join(stream), {"A_TYPE": "float16_t", "B_TYPE": "float16_t", "D_TYPE": "float"}, fp16))
  2280. tasks.append(string_to_spv("matmul_f16_aligned", "".join(stream), {"LOAD_VEC_A": 1, "LOAD_VEC_B": load_vec, "A_TYPE": "float16_t", "B_TYPE": vec_type_f16, "D_TYPE": "float"}, fp16))
  2281. tasks.append(string_to_spv("matmul_f16_f32", "".join(stream), {"A_TYPE": "float16_t", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2282. tasks.append(string_to_spv("matmul_f16_f32_aligned", "".join(stream), {"LOAD_VEC_A": 1, "LOAD_VEC_B": load_vec, "A_TYPE": "float16_t", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2283. stream.clear()
  2284. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_0_defines, mulmat_body1, mulmat_load_q4_0, mulmat_body2))
  2285. tasks.append(string_to_spv("matmul_q4_0_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q4_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2286. tasks.append(string_to_spv("matmul_q4_0_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2287. stream.clear()
  2288. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_1_defines, mulmat_body1, mulmat_load_q4_1, mulmat_body2))
  2289. tasks.append(string_to_spv("matmul_q4_1_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q4_1", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2290. tasks.append(string_to_spv("matmul_q4_1_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_1", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2291. stream.clear()
  2292. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_0_defines, mulmat_body1, mulmat_load_q5_0, mulmat_body2))
  2293. tasks.append(string_to_spv("matmul_q5_0_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q5_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2294. tasks.append(string_to_spv("matmul_q5_0_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2295. stream.clear()
  2296. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_1_defines, mulmat_body1, mulmat_load_q5_1, mulmat_body2))
  2297. tasks.append(string_to_spv("matmul_q5_1_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q5_1", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2298. tasks.append(string_to_spv("matmul_q5_1_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_1", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2299. stream.clear()
  2300. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q8_0_defines, mulmat_body1, mulmat_load_q8_0, mulmat_body2))
  2301. tasks.append(string_to_spv("matmul_q8_0_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q8_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2302. tasks.append(string_to_spv("matmul_q8_0_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q8_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2303. stream.clear()
  2304. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q2_K_defines, mulmat_body1, mulmat_load_q2_K, mulmat_body2))
  2305. tasks.append(string_to_spv("matmul_q2_k_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q2_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2306. tasks.append(string_to_spv("matmul_q2_k_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q2_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2307. stream.clear()
  2308. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q3_K_defines, mulmat_body1, mulmat_load_q3_K, mulmat_body2))
  2309. tasks.append(string_to_spv("matmul_q3_k_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q3_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2310. tasks.append(string_to_spv("matmul_q3_k_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q3_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2311. stream.clear()
  2312. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_K_defines, mulmat_body1, mulmat_load_q4_K, mulmat_body2))
  2313. tasks.append(string_to_spv("matmul_q4_k_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q4_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2314. tasks.append(string_to_spv("matmul_q4_k_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2315. stream.clear()
  2316. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_K_defines, mulmat_body1, mulmat_load_q5_K, mulmat_body2))
  2317. tasks.append(string_to_spv("matmul_q5_k_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q5_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2318. tasks.append(string_to_spv("matmul_q5_k_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2319. stream.clear()
  2320. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q6_K_defines, mulmat_body1, mulmat_load_q6_K, mulmat_body2))
  2321. tasks.append(string_to_spv("matmul_q6_k_f32", "".join(stream), {"LOAD_VEC_A": 2, "A_TYPE": "block_q6_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2322. tasks.append(string_to_spv("matmul_q6_k_f32_aligned", "".join(stream), {"LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q6_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2323. # MUL_MAT_ID
  2324. # stream.clear()
  2325. # stream.extend((mulmat_head, shader_float_type, mulmat_body1, mulmat_load_scalar, mulmat_body2))
  2326. # tasks.append(string_to_spv("matmul_id_f32", "".join(stream), {"MUL_MAT_ID": "1", "A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2327. # tasks.append(string_to_spv("matmul_id_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type, "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2328. # tasks.append(string_to_spv("matmul_id_f16", "".join(stream), {"MUL_MAT_ID": "1", "A_TYPE": "float16_t", "B_TYPE": "float16_t", "D_TYPE": "float"}, fp16))
  2329. # tasks.append(string_to_spv("matmul_id_f16_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type_f16, "B_TYPE": vec_type_f16, "D_TYPE": "float"}, fp16))
  2330. # tasks.append(string_to_spv("matmul_id_f16_f32", "".join(stream), {"MUL_MAT_ID": "1", "A_TYPE": "float16_t", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2331. # tasks.append(string_to_spv("matmul_id_f16_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type_f16, "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2332. # stream.clear()
  2333. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_0_defines, mulmat_body1, mulmat_load_q4_0, mulmat_body2))
  2334. # tasks.append(string_to_spv("matmul_id_q4_0_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q4_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2335. # tasks.append(string_to_spv("matmul_id_q4_0_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2336. # stream.clear()
  2337. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_1_defines, mulmat_body1, mulmat_load_q4_1, mulmat_body2))
  2338. # tasks.append(string_to_spv("matmul_id_q4_1_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q4_1", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2339. # tasks.append(string_to_spv("matmul_id_q4_1_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_1", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2340. # stream.clear()
  2341. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_0_defines, mulmat_body1, mulmat_load_q5_0, mulmat_body2))
  2342. # tasks.append(string_to_spv("matmul_id_q5_0_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q5_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2343. # tasks.append(string_to_spv("matmul_id_q5_0_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2344. # stream.clear()
  2345. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_1_defines, mulmat_body1, mulmat_load_q5_1, mulmat_body2))
  2346. # tasks.append(string_to_spv("matmul_id_q5_1_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q5_1", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2347. # tasks.append(string_to_spv("matmul_id_q5_1_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_1", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2348. # stream.clear()
  2349. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q8_0_defines, mulmat_body1, mulmat_load_q8_0, mulmat_body2))
  2350. # tasks.append(string_to_spv("matmul_id_q8_0_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q8_0", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2351. # tasks.append(string_to_spv("matmul_id_q8_0_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q8_0", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2352. # stream.clear()
  2353. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q2_K_defines, mulmat_body1, mulmat_load_q2_K, mulmat_body2))
  2354. # tasks.append(string_to_spv("matmul_id_q2_k_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q2_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2355. # tasks.append(string_to_spv("matmul_id_q2_k_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q2_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2356. # stream.clear()
  2357. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q3_K_defines, mulmat_body1, mulmat_load_q3_K, mulmat_body2))
  2358. # tasks.append(string_to_spv("matmul_id_q3_k_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q3_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2359. # tasks.append(string_to_spv("matmul_id_q3_k_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q3_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2360. # stream.clear()
  2361. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_K_defines, mulmat_body1, mulmat_load_q4_K, mulmat_body2))
  2362. # tasks.append(string_to_spv("matmul_id_q4_k_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q4_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2363. # tasks.append(string_to_spv("matmul_id_q4_k_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q4_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2364. # stream.clear()
  2365. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_K_defines, mulmat_body1, mulmat_load_q5_K, mulmat_body2))
  2366. # tasks.append(string_to_spv("matmul_id_q5_k_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q5_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2367. # tasks.append(string_to_spv("matmul_id_q5_k_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q5_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2368. # stream.clear()
  2369. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q6_K_defines, mulmat_body1, mulmat_load_q6_K, mulmat_body2))
  2370. # tasks.append(string_to_spv("matmul_id_q6_k_f32", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "A_TYPE": "block_q6_K", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2371. # tasks.append(string_to_spv("matmul_id_q6_k_f32_aligned", "".join(stream), {"MUL_MAT_ID": "1", "LOAD_VEC_A": 2, "LOAD_VEC_B": load_vec, "A_TYPE": "block_q6_K", "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2372. # Shaders where precision is needed, so no fp16 version
  2373. # mul mat vec
  2374. for i in range(0, VK_NUM_TYPES):
  2375. stream.clear()
  2376. stream.extend((mul_mat_vec_head, shader_int8_ext, shader_f32))
  2377. if i == GGML_TYPE_F16:
  2378. stream.extend((shader_f16_defines, mul_mat_vec_layout, shader_float_dequant_func, mul_mat_vec_body))
  2379. elif i == GGML_TYPE_Q4_0:
  2380. stream.extend((shader_q4_0_defines, mul_mat_vec_layout, shader_q4_0_dequant_func, mul_mat_vec_body))
  2381. elif i == GGML_TYPE_Q4_1:
  2382. stream.extend((shader_q4_1_defines, mul_mat_vec_layout, shader_q4_1_dequant_func, mul_mat_vec_body))
  2383. elif i == GGML_TYPE_Q5_0:
  2384. stream.extend((shader_q5_0_defines, mul_mat_vec_layout, shader_q5_0_dequant_func, mul_mat_vec_body))
  2385. elif i == GGML_TYPE_Q5_1:
  2386. stream.extend((shader_q5_1_defines, mul_mat_vec_layout, shader_q5_1_dequant_func, mul_mat_vec_body))
  2387. elif i == GGML_TYPE_Q8_0:
  2388. stream.extend((shader_q8_0_defines, mul_mat_vec_layout, shader_q8_0_dequant_func, mul_mat_vec_body))
  2389. elif i == GGML_TYPE_Q2_K:
  2390. stream.extend((shader_q2_K_defines, mul_mat_vec_layout, mul_mat_vec_q2_K_body))
  2391. elif i == GGML_TYPE_Q3_K:
  2392. stream.extend((shader_q3_K_defines, mul_mat_vec_layout, mul_mat_vec_q3_K_body))
  2393. elif i == GGML_TYPE_Q4_K:
  2394. stream.extend((shader_q4_K_defines, mul_mat_vec_layout, mul_mat_vec_q4_K_body))
  2395. elif i == GGML_TYPE_Q5_K:
  2396. stream.extend((shader_q5_K_defines, mul_mat_vec_layout, mul_mat_vec_q5_K_body))
  2397. elif i == GGML_TYPE_Q6_K:
  2398. stream.extend((shader_q6_K_defines, mul_mat_vec_layout, mul_mat_vec_q6_K_body))
  2399. else:
  2400. continue
  2401. tasks.append(string_to_spv(f"mul_mat_vec_{type_names[i]}_f32_f32", "".join(stream), {"B_TYPE": "float", "D_TYPE": "float", "K_QUANTS_PER_ITERATION": K_QUANTS_PER_ITERATION}))
  2402. tasks.append(string_to_spv(f"mul_mat_vec_{type_names[i]}_f16_f32", "".join(stream), {"B_TYPE": "float16_t", "D_TYPE": "float", "K_QUANTS_PER_ITERATION": K_QUANTS_PER_ITERATION}))
  2403. # tasks.append(string_to_spv(f"mul_mat_vec_id_{type_names[i]}_f32", "".join(stream), {"MUL_MAT_ID": "1", "B_TYPE": "float", "D_TYPE": "float", "K_QUANTS_PER_ITERATION": K_QUANTS_PER_ITERATION}))
  2404. # Dequant shaders
  2405. for i in range(0, VK_NUM_TYPES):
  2406. stream.clear()
  2407. stream.extend((dequant_head, shader_int8_ext, shader_f32))
  2408. if i == GGML_TYPE_F32:
  2409. stream.append(dequant_f32_body)
  2410. elif i == GGML_TYPE_Q4_0:
  2411. stream.extend((shader_q4_0_defines, dequant_q4_0_body))
  2412. elif i == GGML_TYPE_Q4_1:
  2413. stream.extend((shader_q4_1_defines, dequant_q4_1_body))
  2414. elif i == GGML_TYPE_Q5_0:
  2415. stream.extend((shader_q5_0_defines, dequant_q5_0_body))
  2416. elif i == GGML_TYPE_Q5_1:
  2417. stream.extend((shader_q5_1_defines, dequant_q5_1_body))
  2418. elif i == GGML_TYPE_Q8_0:
  2419. stream.extend((shader_q8_0_defines, dequant_q8_0_body))
  2420. elif i == GGML_TYPE_Q2_K:
  2421. stream.extend((shader_q2_K_defines, dequant_q2_K_body))
  2422. elif i == GGML_TYPE_Q3_K:
  2423. stream.extend((shader_q3_K_defines, dequant_q3_K_body))
  2424. elif i == GGML_TYPE_Q4_K:
  2425. stream.extend((shader_q4_K_defines, dequant_q4_K_body))
  2426. elif i == GGML_TYPE_Q5_K:
  2427. stream.extend((shader_q5_K_defines, dequant_q5_K_body))
  2428. elif i == GGML_TYPE_Q6_K:
  2429. stream.extend((shader_q6_K_defines, dequant_q6_K_body))
  2430. else:
  2431. continue
  2432. tasks.append(string_to_spv(f"dequant_{type_names[i]}", "".join(stream), {"D_TYPE": "float16_t"}))
  2433. # get_rows
  2434. for i in range(0, VK_NUM_TYPES):
  2435. stream.clear()
  2436. stream.extend((generic_binary_op_head, shader_int8_ext, shader_f32))
  2437. optimization_workaround = False
  2438. if i == GGML_TYPE_F32:
  2439. stream.extend((shader_f32_defines, generic_binary_op_layout, generic_binary_op_funcs, get_rows_float_body))
  2440. elif i == GGML_TYPE_F16:
  2441. stream.extend((shader_f16_defines, generic_binary_op_layout, generic_binary_op_funcs, get_rows_float_body))
  2442. optimization_workaround = True
  2443. elif i == GGML_TYPE_Q4_0:
  2444. stream.extend((shader_q4_0_defines, generic_binary_op_layout, shader_q4_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2445. elif i == GGML_TYPE_Q4_1:
  2446. stream.extend((shader_q4_1_defines, generic_binary_op_layout, shader_q4_1_dequant_func, generic_binary_op_funcs, get_rows_body))
  2447. elif i == GGML_TYPE_Q5_0:
  2448. stream.extend((shader_q5_0_defines, generic_binary_op_layout, shader_q5_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2449. elif i == GGML_TYPE_Q5_1:
  2450. stream.extend((shader_q5_1_defines, generic_binary_op_layout, shader_q5_1_dequant_func, generic_binary_op_funcs, get_rows_body))
  2451. elif i == GGML_TYPE_Q8_0:
  2452. stream.extend((shader_q8_0_defines, generic_binary_op_layout, shader_q8_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2453. else:
  2454. continue
  2455. if optimization_workaround:
  2456. tasks.append(string_to_spv(f"get_rows_{type_names[i]}", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float16_t", "OPTIMIZATION_ERROR_WORKAROUND": "1"}))
  2457. else:
  2458. tasks.append(string_to_spv(f"get_rows_{type_names[i]}", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float16_t"}))
  2459. tasks.append(string_to_spv(f"get_rows_{type_names[i]}_f32", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float"}))
  2460. tasks.append(string_to_spv("mul_mat_vec_p021_f16_f32", mul_mat_p021_src, {"A_TYPE": "float16_t", "B_TYPE": "float", "D_TYPE": "float"}))
  2461. tasks.append(string_to_spv("mul_mat_vec_nc_f16_f32", mul_mat_nc_src, {"A_TYPE": "float16_t", "B_TYPE": "float", "D_TYPE": "float"}))
  2462. # Norms
  2463. tasks.append(string_to_spv("norm_f32", f"{generic_head}\n{shader_f32}\n{norm_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2464. tasks.append(string_to_spv("rms_norm_f32", f"{generic_head}\n{shader_f32}\n{rms_norm_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2465. tasks.append(string_to_spv("cpy_f32_f32", f"{generic_unary_op_combined}\n{cpy_end}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2466. tasks.append(string_to_spv("cpy_f32_f16", f"{generic_unary_op_combined}\n{cpy_end}", {"A_TYPE": "float", "D_TYPE": "float16_t"}))
  2467. tasks.append(string_to_spv("cpy_f16_f16", f"{generic_unary_op_combined}\n{cpy_f16_f16_end}", {"A_TYPE": "float16_t", "D_TYPE": "float16_t"}))
  2468. tasks.append(string_to_spv("add_f32", f"{generic_binary_op_combined}\n{add_body}", {"A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2469. tasks.append(string_to_spv("split_k_reduce", mulmat_split_k_reduce_src, {}))
  2470. tasks.append(string_to_spv("mul_f32", f"{generic_binary_op_combined}\n{mul_body}", {"A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2471. tasks.append(string_to_spv("scale_f32", f"{generic_unary_op_combined}\n{scale_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2472. tasks.append(string_to_spv("sqr_f32", f"{generic_unary_op_combined}\n{sqr_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2473. tasks.append(string_to_spv("clamp_f32", f"{generic_unary_op_combined}\n{clamp_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2474. tasks.append(string_to_spv("gelu_f32", f"{generic_head}\n{shader_f32}\n{gelu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2475. tasks.append(string_to_spv("silu_f32", f"{generic_head}\n{shader_f32}\n{silu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2476. tasks.append(string_to_spv("relu_f32", f"{generic_head}\n{shader_f32}\n{relu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2477. tasks.append(string_to_spv("diag_mask_inf_f32", f"{diag_mask_inf_head}\n{shader_f32}\n{diag_mask_inf_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2478. tasks.append(string_to_spv("soft_max_f32", f"{soft_max_head}\n{shader_f32}\n{soft_max_body}", {"A_TYPE": "float", "B_TYPE": "float", "C_TYPE": "float", "D_TYPE": "float"}))
  2479. tasks.append(string_to_spv("soft_max_f32_f16", f"{soft_max_head}\n{shader_f32}\n{soft_max_body}", {"A_TYPE": "float", "B_TYPE": "float16_t", "C_TYPE": "float16_t", "D_TYPE": "float"}))
  2480. tasks.append(string_to_spv("rope_f32", rope_src, {"A_TYPE": "float", "D_TYPE": "float"}))
  2481. tasks.append(string_to_spv("rope_f16", rope_src, {"A_TYPE": "float16_t", "D_TYPE": "float16_t"}))
  2482. tasks.append(string_to_spv("rope_neox_f32", rope_neox_src, {"A_TYPE": "float", "D_TYPE": "float"}))
  2483. tasks.append(string_to_spv("rope_neox_f16", rope_neox_src, {"A_TYPE": "float16_t", "D_TYPE": "float16_t"}))
  2484. tasks.append(string_to_spv("argsort_f32", argsort_src, {"A_TYPE": "float"}))
  2485. # Helper to decorate tasks with semaphore acquisition.
  2486. async def withSemaphore(sem, task):
  2487. async with sem:
  2488. return await task
  2489. # Run tasks concurrently guarded by a concurrency limit.
  2490. sem = asyncio.Semaphore(ASYNCIO_CONCURRENCY)
  2491. await asyncio.gather(*(withSemaphore(sem, task) for task in tasks))
  2492. with open("ggml-vulkan-shaders.hpp", "w") as f:
  2493. f.write("#include <cstdint>\n\n")
  2494. for name, path in sorted(shader_fnames):
  2495. with open(path, "rb") as spv:
  2496. counter = 0
  2497. newline_counter = 0
  2498. f.write(f"unsigned char {name}_data[] = {{\n")
  2499. for val in spv.read():
  2500. f.write(f"0x{val:02x},")
  2501. newline_counter += 1
  2502. counter += 1
  2503. if newline_counter >= 12:
  2504. newline_counter = 0
  2505. f.write("\n")
  2506. f.write("\n};\n")
  2507. f.write(f"const uint64_t {name}_len = {counter};\n\n")
  2508. os.remove(path)
  2509. if __name__ == "__main__":
  2510. parser = argparse.ArgumentParser(description="GGML Vulkan Shader Generator")
  2511. parser.add_argument("--glslc", help="Path to glslc")
  2512. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  2513. args = parser.parse_args()
  2514. logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
  2515. if args.glslc:
  2516. GLSLC = args.glslc
  2517. asyncio.run(main())