ggml_vk_generate_shaders.py 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184
  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. float scale;
  1962. float max_bias;
  1963. float m0;
  1964. float m1;
  1965. uint n_head_log2;
  1966. } p;
  1967. """
  1968. soft_max_body = """
  1969. #extension GL_EXT_control_flow_attributes : enable
  1970. #define BLOCK_SIZE 512
  1971. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  1972. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  1973. layout (binding = 1) readonly buffer Y {B_TYPE data_b[];};
  1974. layout (binding = 2) buffer D {D_TYPE data_d[];};
  1975. shared FLOAT_TYPE vals[BLOCK_SIZE];
  1976. void main() {
  1977. const uint tid = gl_LocalInvocationID.x;
  1978. const uint rowx = gl_WorkGroupID.x;
  1979. const uint rowy = rowx % p.KY;
  1980. float slope = 1.0f;
  1981. // ALiBi
  1982. if (p.max_bias > 0.0f) {
  1983. const uint h = rowx/p.KY; // head index
  1984. const float base = h < p.n_head_log2 ? p.m0 : p.m1;
  1985. const uint exp = h < p.n_head_log2 ? h + 1 : 2*(h - p.n_head_log2) + 1;
  1986. slope = pow(base, exp);
  1987. }
  1988. // Find max
  1989. FLOAT_TYPE max_val = uintBitsToFloat(0xFF800000);
  1990. [[unroll]] for (uint col0 = 0; col0 < p.KX; col0 += BLOCK_SIZE) {
  1991. const uint col = col0 + tid;
  1992. if (col >= p.KX) {
  1993. break;
  1994. }
  1995. max_val = max(max_val, FLOAT_TYPE(data_a[rowx * p.KX + col]) * p.scale + (p.KY > 0 ? slope * FLOAT_TYPE(data_b[rowy * p.KX + col]) : FLOAT_TYPE(0.0f)));
  1996. }
  1997. vals[tid] = max_val;
  1998. barrier();
  1999. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  2000. if (tid < s) {
  2001. vals[tid] = max(vals[tid], vals[tid + s]);
  2002. }
  2003. barrier();
  2004. }
  2005. max_val = vals[0];
  2006. barrier();
  2007. // Sum up values
  2008. vals[tid] = FLOAT_TYPE(0.0f);
  2009. [[unroll]] for (uint col0 = 0; col0 < p.KX; col0 += BLOCK_SIZE) {
  2010. const uint col = col0 + tid;
  2011. if (col >= p.KX) {
  2012. break;
  2013. }
  2014. const uint i = rowx * p.KX + col;
  2015. const FLOAT_TYPE val = exp(FLOAT_TYPE(data_a[i]) * p.scale + (p.KY > 0 ? slope * FLOAT_TYPE(data_b[rowy * p.KX + col]) : FLOAT_TYPE(0.0f)) - max_val);
  2016. vals[tid] += val;
  2017. data_d[i] = D_TYPE(val);
  2018. }
  2019. barrier();
  2020. [[unroll]] for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
  2021. if (tid < s) {
  2022. vals[tid] += vals[tid + s];
  2023. }
  2024. barrier();
  2025. }
  2026. const D_TYPE divisor = D_TYPE(vals[0]);
  2027. [[unroll]] for (uint col0 = 0; col0 < p.KX; col0 += BLOCK_SIZE) {
  2028. const uint col = col0 + tid;
  2029. if (col >= p.KX) {
  2030. break;
  2031. }
  2032. data_d[rowx*p.KX + col] /= divisor;
  2033. }
  2034. }
  2035. """
  2036. # ROPE
  2037. rope_src = """
  2038. #version 450
  2039. #extension GL_EXT_shader_16bit_storage : require
  2040. layout(local_size_x = 1, local_size_y = 256, local_size_z = 1) in;
  2041. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  2042. layout (binding = 1) readonly buffer Y {int data_b[];};
  2043. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  2044. layout (push_constant) uniform parameter {
  2045. uint ncols;
  2046. float freq_scale;
  2047. uint p_delta_rows;
  2048. float freq_base;
  2049. float ext_factor;
  2050. float attn_factor;
  2051. float corr_dims[4];
  2052. } p;
  2053. float rope_yarn_ramp(const float low, const float high, const uint i0) {
  2054. const float y = (i0 / 2 - low) / max(0.001f, high - low);
  2055. return 1.0f - min(1.0f, max(0.0f, y));
  2056. }
  2057. void rope_yarn(const float theta_extrap, const uint i0, out float cos_theta, out float sin_theta) {
  2058. float mscale = p.attn_factor;
  2059. // Get n-d rotational scaling corrected for extrapolation
  2060. float theta_interp = p.freq_scale * theta_extrap;
  2061. float theta = theta_interp;
  2062. if (p.ext_factor != 0.0f) {
  2063. float ramp_mix = rope_yarn_ramp(p.corr_dims[0], p.corr_dims[1], i0) * p.ext_factor;
  2064. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  2065. // Get n-d magnitude scaling corrected for interpolation
  2066. mscale *= 1.0f + 0.1f * log(1.0f / p.freq_scale);
  2067. }
  2068. cos_theta = cos(theta) * mscale;
  2069. sin_theta = sin(theta) * mscale;
  2070. }
  2071. void main() {
  2072. const uint col = gl_GlobalInvocationID.y * 2;
  2073. const uint row = gl_GlobalInvocationID.x;
  2074. if (col >= p.ncols) {
  2075. return;
  2076. }
  2077. const uint i = row*p.ncols + col;
  2078. const uint i2 = row/p.p_delta_rows;
  2079. const int pos = data_b[i2];
  2080. const float theta_base = pos * pow(p.freq_base, -float(col)/p.ncols);
  2081. float cos_theta, sin_theta;
  2082. rope_yarn(theta_base, col, cos_theta, sin_theta);
  2083. const float x0 = float(data_a[i + 0]);
  2084. const float x1 = float(data_a[i + 1]);
  2085. data_d[i + 0] = D_TYPE(x0*cos_theta - x1*sin_theta);
  2086. data_d[i + 1] = D_TYPE(x0*sin_theta + x1*cos_theta);
  2087. }
  2088. """
  2089. rope_neox_src = """
  2090. #version 450
  2091. #extension GL_EXT_shader_16bit_storage : require
  2092. layout(local_size_x = 1, local_size_y = 256, local_size_z = 1) in;
  2093. layout (binding = 0) readonly buffer X {A_TYPE data_a[];};
  2094. layout (binding = 1) readonly buffer Y {int data_b[];};
  2095. layout (binding = 2) writeonly buffer D {D_TYPE data_d[];};
  2096. layout (push_constant) uniform parameter {
  2097. uint ncols;
  2098. uint ndims;
  2099. float freq_scale;
  2100. uint p_delta_rows;
  2101. float freq_base;
  2102. float ext_factor;
  2103. float attn_factor;
  2104. float corr_dims[4];
  2105. float theta_scale;
  2106. float inv_ndims;
  2107. } p;
  2108. float rope_yarn_ramp(const float low, const float high, const uint i0) {
  2109. const float y = (i0 / 2 - low) / max(0.001f, high - low);
  2110. return 1.0f - min(1.0f, max(0.0f, y));
  2111. }
  2112. void rope_yarn(const float theta_extrap, const uint i0, out float cos_theta, out float sin_theta) {
  2113. float mscale = p.attn_factor;
  2114. // Get n-d rotational scaling corrected for extrapolation
  2115. float theta_interp = p.freq_scale * theta_extrap;
  2116. float theta = theta_interp;
  2117. if (p.ext_factor != 0.0f) {
  2118. float ramp_mix = rope_yarn_ramp(p.corr_dims[0], p.corr_dims[1], i0) * p.ext_factor;
  2119. theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix;
  2120. // Get n-d magnitude scaling corrected for interpolation
  2121. mscale *= 1.0f + 0.1f * log(1.0f / p.freq_scale);
  2122. }
  2123. cos_theta = cos(theta) * mscale;
  2124. sin_theta = sin(theta) * mscale;
  2125. }
  2126. void main() {
  2127. const uint col = gl_GlobalInvocationID.y * 2;
  2128. const uint row = gl_GlobalInvocationID.x;
  2129. if (col >= p.ncols) {
  2130. return;
  2131. }
  2132. const uint ib = col / p.ndims;
  2133. const uint ic = col % p.ndims;
  2134. if (ib > 0) {
  2135. const uint i = row*p.ncols + ib*p.ndims + ic;
  2136. data_d[i + 0] = data_a[i + 0];
  2137. data_d[i + 1] = data_a[i + 1];
  2138. return;
  2139. }
  2140. const uint i = row*p.ncols + ib*p.ndims + ic/2;
  2141. const uint i2 = row/p.p_delta_rows;
  2142. const float cur_rot = p.inv_ndims * ic - ib;
  2143. const int pos = data_b[i2];
  2144. const float theta_base = pos*p.freq_scale*pow(p.theta_scale, col/2.0f);
  2145. float cos_theta, sin_theta;
  2146. rope_yarn(theta_base, uint(cur_rot), cos_theta, sin_theta);
  2147. const float x0 = float(data_a[i + 0]);
  2148. const float x1 = float(data_a[i + p.ndims/2]);
  2149. data_d[i + 0] = D_TYPE(x0*cos_theta - x1*sin_theta);
  2150. data_d[i + p.ndims/2] = D_TYPE(x0*sin_theta + x1*cos_theta);
  2151. }
  2152. """
  2153. argsort_src = """
  2154. #version 450
  2155. #extension GL_EXT_shader_16bit_storage : require
  2156. #define BLOCK_SIZE 1024
  2157. #define ASC 0
  2158. layout(local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in;
  2159. layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
  2160. layout (binding = 1) buffer D {int data_d[];};
  2161. layout (push_constant) uniform parameter {
  2162. uint ncols;
  2163. uint ncols_pad;
  2164. uint order;
  2165. } p;
  2166. shared int dst_row[BLOCK_SIZE];
  2167. void swap(uint idx0, uint idx1) {
  2168. int tmp = dst_row[idx0];
  2169. dst_row[idx0] = dst_row[idx1];
  2170. dst_row[idx1] = tmp;
  2171. }
  2172. void main() {
  2173. // bitonic sort
  2174. const int col = int(gl_LocalInvocationID.x);
  2175. const uint row = gl_WorkGroupID.y;
  2176. if (col >= p.ncols_pad) {
  2177. return;
  2178. }
  2179. const uint row_offset = row * p.ncols;
  2180. // initialize indices
  2181. dst_row[col] = col;
  2182. barrier();
  2183. for (uint k = 2; k <= p.ncols_pad; k *= 2) {
  2184. for (uint j = k / 2; j > 0; j /= 2) {
  2185. const uint ixj = col ^ j;
  2186. if (ixj > col) {
  2187. if ((col & k) == 0) {
  2188. if (dst_row[col] >= p.ncols ||
  2189. (dst_row[ixj] < p.ncols && (p.order == ASC ?
  2190. data_a[row_offset + dst_row[col]] > data_a[row_offset + dst_row[ixj]] :
  2191. data_a[row_offset + dst_row[col]] < data_a[row_offset + dst_row[ixj]]))
  2192. ) {
  2193. swap(col, ixj);
  2194. }
  2195. } else {
  2196. if (dst_row[ixj] >= p.ncols ||
  2197. (dst_row[col] < p.ncols && (p.order == ASC ?
  2198. data_a[row_offset + dst_row[col]] < data_a[row_offset + dst_row[ixj]] :
  2199. data_a[row_offset + dst_row[col]] > data_a[row_offset + dst_row[ixj]]))
  2200. ) {
  2201. swap(col, ixj);
  2202. }
  2203. }
  2204. }
  2205. barrier();
  2206. }
  2207. }
  2208. if (col < p.ncols) {
  2209. data_d[row_offset + col] = dst_row[col];
  2210. }
  2211. }
  2212. """
  2213. GLSLC = "glslc"
  2214. VK_NUM_TYPES = 16
  2215. GGML_TYPE_F32 = 0
  2216. GGML_TYPE_F16 = 1
  2217. GGML_TYPE_Q4_0 = 2
  2218. GGML_TYPE_Q4_1 = 3
  2219. GGML_TYPE_Q5_0 = 6
  2220. GGML_TYPE_Q5_1 = 7
  2221. GGML_TYPE_Q8_0 = 8
  2222. GGML_TYPE_Q8_1 = 9
  2223. GGML_TYPE_Q2_K = 10
  2224. GGML_TYPE_Q3_K = 11
  2225. GGML_TYPE_Q4_K = 12
  2226. GGML_TYPE_Q5_K = 13
  2227. GGML_TYPE_Q6_K = 14
  2228. GGML_TYPE_Q8_K = 15
  2229. type_names = {
  2230. GGML_TYPE_F32: "f32",
  2231. GGML_TYPE_F16: "f16",
  2232. GGML_TYPE_Q4_0: "q4_0",
  2233. GGML_TYPE_Q4_1: "q4_1",
  2234. GGML_TYPE_Q5_0: "q5_0",
  2235. GGML_TYPE_Q5_1: "q5_1",
  2236. GGML_TYPE_Q8_0: "q8_0",
  2237. GGML_TYPE_Q8_1: "q8_1",
  2238. GGML_TYPE_Q2_K: "q2_K",
  2239. GGML_TYPE_Q3_K: "q3_K",
  2240. GGML_TYPE_Q4_K: "q4_K",
  2241. GGML_TYPE_Q5_K: "q5_K",
  2242. GGML_TYPE_Q6_K: "q6_K",
  2243. GGML_TYPE_Q8_K: "q8_K",
  2244. }
  2245. K_QUANTS_PER_ITERATION = 2
  2246. ASYNCIO_CONCURRENCY = 64
  2247. output_dir = gettempdir()
  2248. lock = asyncio.Lock()
  2249. shader_fnames = []
  2250. async def string_to_spv(name, code, defines, fp16=True):
  2251. f = NamedTemporaryFile(mode="w", delete=False)
  2252. f.write(code)
  2253. f.flush()
  2254. name = f"{name}{'_fp32' if not fp16 else ''}"
  2255. fname = os.path.join(output_dir, f"{name}.comp")
  2256. cmd = [GLSLC, "-fshader-stage=compute", "--target-env=vulkan1.2", "-O", f.name, "-o", fname]
  2257. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2258. proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
  2259. stdout, stderr = await proc.communicate()
  2260. stdout = stdout.decode()
  2261. error = stderr.decode()
  2262. if proc.returncode:
  2263. # Generate preprocessed code
  2264. cmd = [GLSLC, "-E", f.name]
  2265. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2266. proc = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
  2267. stdout, stderr = await proc.communicate()
  2268. logger.info(" ".join(cmd))
  2269. if proc.returncode:
  2270. raise RuntimeError(f"{name=} {f.name=} {stdout=} {stderr=}")
  2271. preprocessed_code = stdout.decode()
  2272. cmd.extend([f"-D{key}={value}" for key, value in defines.items()])
  2273. code_with_lines = "\n".join([f"{i + 1}: {line}" for i, line in enumerate(preprocessed_code.splitlines())])
  2274. logger.error(f"cannot compile {name}\n\n{code_with_lines}\n\n{error}")
  2275. f.close()
  2276. os.remove(f.name)
  2277. sys.exit(proc.returncode)
  2278. f.close()
  2279. os.remove(f.name)
  2280. async with lock:
  2281. shader_fnames.append((name, fname))
  2282. async def main():
  2283. logger.info("ggml_vulkan: Generating and compiling shaders to SPIR-V")
  2284. tasks = []
  2285. stream = []
  2286. for fp16 in (False, True):
  2287. # mulmat
  2288. if fp16:
  2289. shader_float_type = shader_f16
  2290. load_vec = "8"
  2291. vec_type_f16 = "f16mat2x4"
  2292. vec_type = "mat2x4"
  2293. else:
  2294. shader_float_type = shader_f32
  2295. load_vec = "4"
  2296. vec_type_f16 = "f16vec4"
  2297. vec_type = "vec4"
  2298. stream.clear()
  2299. stream.extend((mulmat_head, shader_float_type, mulmat_body1, mulmat_load_scalar, mulmat_body2))
  2300. tasks.append(string_to_spv("matmul_f32", "".join(stream), {"A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2301. tasks.append(string_to_spv("matmul_f32_aligned", "".join(stream), {"LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type, "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2302. tasks.append(string_to_spv("matmul_f32_f16", "".join(stream), {"A_TYPE": "float", "B_TYPE": "float16_t", "D_TYPE": "float"}, fp16))
  2303. tasks.append(string_to_spv("matmul_f32_f16_aligned", "".join(stream), {"LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type, "B_TYPE": vec_type_f16, "D_TYPE": "float"}, fp16))
  2304. tasks.append(string_to_spv("matmul_f16", "".join(stream), {"A_TYPE": "float16_t", "B_TYPE": "float16_t", "D_TYPE": "float"}, fp16))
  2305. tasks.append(string_to_spv("matmul_f16_aligned", "".join(stream), {"LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type_f16, "B_TYPE": vec_type_f16, "D_TYPE": "float"}, fp16))
  2306. tasks.append(string_to_spv("matmul_f16_f32", "".join(stream), {"A_TYPE": "float16_t", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2307. tasks.append(string_to_spv("matmul_f16_f32_aligned", "".join(stream), {"LOAD_VEC_A": load_vec, "LOAD_VEC_B": load_vec, "A_TYPE": vec_type_f16, "B_TYPE": vec_type, "D_TYPE": "float"}, fp16))
  2308. stream.clear()
  2309. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_0_defines, mulmat_body1, mulmat_load_q4_0, mulmat_body2))
  2310. 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))
  2311. 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))
  2312. stream.clear()
  2313. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_1_defines, mulmat_body1, mulmat_load_q4_1, mulmat_body2))
  2314. 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))
  2315. 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))
  2316. stream.clear()
  2317. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_0_defines, mulmat_body1, mulmat_load_q5_0, mulmat_body2))
  2318. 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))
  2319. 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))
  2320. stream.clear()
  2321. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_1_defines, mulmat_body1, mulmat_load_q5_1, mulmat_body2))
  2322. 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))
  2323. 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))
  2324. stream.clear()
  2325. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q8_0_defines, mulmat_body1, mulmat_load_q8_0, mulmat_body2))
  2326. 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))
  2327. 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))
  2328. stream.clear()
  2329. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q2_K_defines, mulmat_body1, mulmat_load_q2_K, mulmat_body2))
  2330. 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))
  2331. 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))
  2332. stream.clear()
  2333. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q3_K_defines, mulmat_body1, mulmat_load_q3_K, mulmat_body2))
  2334. 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))
  2335. 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))
  2336. stream.clear()
  2337. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_K_defines, mulmat_body1, mulmat_load_q4_K, mulmat_body2))
  2338. 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))
  2339. 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))
  2340. stream.clear()
  2341. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_K_defines, mulmat_body1, mulmat_load_q5_K, mulmat_body2))
  2342. 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))
  2343. 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))
  2344. stream.clear()
  2345. stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q6_K_defines, mulmat_body1, mulmat_load_q6_K, mulmat_body2))
  2346. 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))
  2347. 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))
  2348. # MUL_MAT_ID
  2349. # stream.clear()
  2350. # stream.extend((mulmat_head, shader_float_type, mulmat_body1, mulmat_load_scalar, mulmat_body2))
  2351. # tasks.append(string_to_spv("matmul_id_f32", "".join(stream), {"MUL_MAT_ID": "1", "A_TYPE": "float", "B_TYPE": "float", "D_TYPE": "float"}, fp16))
  2352. # 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))
  2353. # 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))
  2354. # 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))
  2355. # 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))
  2356. # 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))
  2357. # stream.clear()
  2358. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_0_defines, mulmat_body1, mulmat_load_q4_0, mulmat_body2))
  2359. # 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))
  2360. # 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))
  2361. # stream.clear()
  2362. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_1_defines, mulmat_body1, mulmat_load_q4_1, mulmat_body2))
  2363. # 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))
  2364. # 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))
  2365. # stream.clear()
  2366. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_0_defines, mulmat_body1, mulmat_load_q5_0, mulmat_body2))
  2367. # 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))
  2368. # 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))
  2369. # stream.clear()
  2370. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_1_defines, mulmat_body1, mulmat_load_q5_1, mulmat_body2))
  2371. # 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))
  2372. # 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))
  2373. # stream.clear()
  2374. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q8_0_defines, mulmat_body1, mulmat_load_q8_0, mulmat_body2))
  2375. # 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))
  2376. # 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))
  2377. # stream.clear()
  2378. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q2_K_defines, mulmat_body1, mulmat_load_q2_K, mulmat_body2))
  2379. # 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))
  2380. # 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))
  2381. # stream.clear()
  2382. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q3_K_defines, mulmat_body1, mulmat_load_q3_K, mulmat_body2))
  2383. # 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))
  2384. # 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))
  2385. # stream.clear()
  2386. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q4_K_defines, mulmat_body1, mulmat_load_q4_K, mulmat_body2))
  2387. # 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))
  2388. # 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))
  2389. # stream.clear()
  2390. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q5_K_defines, mulmat_body1, mulmat_load_q5_K, mulmat_body2))
  2391. # 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))
  2392. # 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))
  2393. # stream.clear()
  2394. # stream.extend((mulmat_head, shader_int8_ext, shader_float_type, shader_q6_K_defines, mulmat_body1, mulmat_load_q6_K, mulmat_body2))
  2395. # 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))
  2396. # 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))
  2397. # Shaders where precision is needed, so no fp16 version
  2398. # mul mat vec
  2399. for i in range(0, VK_NUM_TYPES):
  2400. stream.clear()
  2401. stream.extend((mul_mat_vec_head, shader_int8_ext, shader_f32))
  2402. if i == GGML_TYPE_F16:
  2403. stream.extend((shader_f16_defines, mul_mat_vec_layout, shader_float_dequant_func, mul_mat_vec_body))
  2404. elif i == GGML_TYPE_Q4_0:
  2405. stream.extend((shader_q4_0_defines, mul_mat_vec_layout, shader_q4_0_dequant_func, mul_mat_vec_body))
  2406. elif i == GGML_TYPE_Q4_1:
  2407. stream.extend((shader_q4_1_defines, mul_mat_vec_layout, shader_q4_1_dequant_func, mul_mat_vec_body))
  2408. elif i == GGML_TYPE_Q5_0:
  2409. stream.extend((shader_q5_0_defines, mul_mat_vec_layout, shader_q5_0_dequant_func, mul_mat_vec_body))
  2410. elif i == GGML_TYPE_Q5_1:
  2411. stream.extend((shader_q5_1_defines, mul_mat_vec_layout, shader_q5_1_dequant_func, mul_mat_vec_body))
  2412. elif i == GGML_TYPE_Q8_0:
  2413. stream.extend((shader_q8_0_defines, mul_mat_vec_layout, shader_q8_0_dequant_func, mul_mat_vec_body))
  2414. elif i == GGML_TYPE_Q2_K:
  2415. stream.extend((shader_q2_K_defines, mul_mat_vec_layout, mul_mat_vec_q2_K_body))
  2416. elif i == GGML_TYPE_Q3_K:
  2417. stream.extend((shader_q3_K_defines, mul_mat_vec_layout, mul_mat_vec_q3_K_body))
  2418. elif i == GGML_TYPE_Q4_K:
  2419. stream.extend((shader_q4_K_defines, mul_mat_vec_layout, mul_mat_vec_q4_K_body))
  2420. elif i == GGML_TYPE_Q5_K:
  2421. stream.extend((shader_q5_K_defines, mul_mat_vec_layout, mul_mat_vec_q5_K_body))
  2422. elif i == GGML_TYPE_Q6_K:
  2423. stream.extend((shader_q6_K_defines, mul_mat_vec_layout, mul_mat_vec_q6_K_body))
  2424. else:
  2425. continue
  2426. 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}))
  2427. 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}))
  2428. # 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}))
  2429. # Dequant shaders
  2430. for i in range(0, VK_NUM_TYPES):
  2431. stream.clear()
  2432. stream.extend((dequant_head, shader_int8_ext, shader_f32))
  2433. if i == GGML_TYPE_F32:
  2434. stream.append(dequant_f32_body)
  2435. elif i == GGML_TYPE_Q4_0:
  2436. stream.extend((shader_q4_0_defines, dequant_q4_0_body))
  2437. elif i == GGML_TYPE_Q4_1:
  2438. stream.extend((shader_q4_1_defines, dequant_q4_1_body))
  2439. elif i == GGML_TYPE_Q5_0:
  2440. stream.extend((shader_q5_0_defines, dequant_q5_0_body))
  2441. elif i == GGML_TYPE_Q5_1:
  2442. stream.extend((shader_q5_1_defines, dequant_q5_1_body))
  2443. elif i == GGML_TYPE_Q8_0:
  2444. stream.extend((shader_q8_0_defines, dequant_q8_0_body))
  2445. elif i == GGML_TYPE_Q2_K:
  2446. stream.extend((shader_q2_K_defines, dequant_q2_K_body))
  2447. elif i == GGML_TYPE_Q3_K:
  2448. stream.extend((shader_q3_K_defines, dequant_q3_K_body))
  2449. elif i == GGML_TYPE_Q4_K:
  2450. stream.extend((shader_q4_K_defines, dequant_q4_K_body))
  2451. elif i == GGML_TYPE_Q5_K:
  2452. stream.extend((shader_q5_K_defines, dequant_q5_K_body))
  2453. elif i == GGML_TYPE_Q6_K:
  2454. stream.extend((shader_q6_K_defines, dequant_q6_K_body))
  2455. else:
  2456. continue
  2457. tasks.append(string_to_spv(f"dequant_{type_names[i]}", "".join(stream), {"D_TYPE": "float16_t"}))
  2458. # get_rows
  2459. for i in range(0, VK_NUM_TYPES):
  2460. stream.clear()
  2461. stream.extend((generic_binary_op_head, shader_int8_ext, shader_f32))
  2462. optimization_workaround = False
  2463. if i == GGML_TYPE_F32:
  2464. stream.extend((shader_f32_defines, generic_binary_op_layout, generic_binary_op_funcs, get_rows_float_body))
  2465. elif i == GGML_TYPE_F16:
  2466. stream.extend((shader_f16_defines, generic_binary_op_layout, generic_binary_op_funcs, get_rows_float_body))
  2467. optimization_workaround = True
  2468. elif i == GGML_TYPE_Q4_0:
  2469. stream.extend((shader_q4_0_defines, generic_binary_op_layout, shader_q4_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2470. elif i == GGML_TYPE_Q4_1:
  2471. stream.extend((shader_q4_1_defines, generic_binary_op_layout, shader_q4_1_dequant_func, generic_binary_op_funcs, get_rows_body))
  2472. elif i == GGML_TYPE_Q5_0:
  2473. stream.extend((shader_q5_0_defines, generic_binary_op_layout, shader_q5_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2474. elif i == GGML_TYPE_Q5_1:
  2475. stream.extend((shader_q5_1_defines, generic_binary_op_layout, shader_q5_1_dequant_func, generic_binary_op_funcs, get_rows_body))
  2476. elif i == GGML_TYPE_Q8_0:
  2477. stream.extend((shader_q8_0_defines, generic_binary_op_layout, shader_q8_0_dequant_func, generic_binary_op_funcs, get_rows_body))
  2478. else:
  2479. continue
  2480. if optimization_workaround:
  2481. tasks.append(string_to_spv(f"get_rows_{type_names[i]}", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float16_t", "OPTIMIZATION_ERROR_WORKAROUND": "1"}))
  2482. else:
  2483. tasks.append(string_to_spv(f"get_rows_{type_names[i]}", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float16_t"}))
  2484. tasks.append(string_to_spv(f"get_rows_{type_names[i]}_f32", "".join(stream), {"B_TYPE": "int", "D_TYPE": "float"}))
  2485. 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"}))
  2486. 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"}))
  2487. # Norms
  2488. tasks.append(string_to_spv("norm_f32", f"{generic_head}\n{shader_f32}\n{norm_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2489. tasks.append(string_to_spv("rms_norm_f32", f"{generic_head}\n{shader_f32}\n{rms_norm_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2490. tasks.append(string_to_spv("cpy_f32_f32", f"{generic_unary_op_combined}\n{cpy_end}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2491. tasks.append(string_to_spv("cpy_f32_f16", f"{generic_unary_op_combined}\n{cpy_end}", {"A_TYPE": "float", "D_TYPE": "float16_t"}))
  2492. 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"}))
  2493. 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"}))
  2494. tasks.append(string_to_spv("split_k_reduce", mulmat_split_k_reduce_src, {}))
  2495. 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"}))
  2496. tasks.append(string_to_spv("scale_f32", f"{generic_unary_op_combined}\n{scale_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2497. tasks.append(string_to_spv("sqr_f32", f"{generic_unary_op_combined}\n{sqr_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2498. tasks.append(string_to_spv("clamp_f32", f"{generic_unary_op_combined}\n{clamp_body}", {"A_TYPE": "float", "D_TYPE": "float", "FLOAT_TYPE": "float"}))
  2499. tasks.append(string_to_spv("gelu_f32", f"{generic_head}\n{shader_f32}\n{gelu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2500. tasks.append(string_to_spv("silu_f32", f"{generic_head}\n{shader_f32}\n{silu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2501. tasks.append(string_to_spv("relu_f32", f"{generic_head}\n{shader_f32}\n{relu_body}", {"A_TYPE": "float", "D_TYPE": "float"}))
  2502. 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"}))
  2503. 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"}))
  2504. 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"}))
  2505. tasks.append(string_to_spv("rope_f32", rope_src, {"A_TYPE": "float", "D_TYPE": "float"}))
  2506. tasks.append(string_to_spv("rope_f16", rope_src, {"A_TYPE": "float16_t", "D_TYPE": "float16_t"}))
  2507. tasks.append(string_to_spv("rope_neox_f32", rope_neox_src, {"A_TYPE": "float", "D_TYPE": "float"}))
  2508. tasks.append(string_to_spv("rope_neox_f16", rope_neox_src, {"A_TYPE": "float16_t", "D_TYPE": "float16_t"}))
  2509. tasks.append(string_to_spv("argsort_f32", argsort_src, {"A_TYPE": "float"}))
  2510. # Helper to decorate tasks with semaphore acquisition.
  2511. async def withSemaphore(sem, task):
  2512. async with sem:
  2513. return await task
  2514. # Run tasks concurrently guarded by a concurrency limit.
  2515. sem = asyncio.Semaphore(ASYNCIO_CONCURRENCY)
  2516. await asyncio.gather(*(withSemaphore(sem, task) for task in tasks))
  2517. with open("ggml-vulkan-shaders.hpp", "w") as f:
  2518. f.write("#include <cstdint>\n\n")
  2519. for name, path in sorted(shader_fnames):
  2520. with open(path, "rb") as spv:
  2521. counter = 0
  2522. newline_counter = 0
  2523. f.write(f"unsigned char {name}_data[] = {{\n")
  2524. for val in spv.read():
  2525. f.write(f"0x{val:02x},")
  2526. newline_counter += 1
  2527. counter += 1
  2528. if newline_counter >= 12:
  2529. newline_counter = 0
  2530. f.write("\n")
  2531. f.write("\n};\n")
  2532. f.write(f"const uint64_t {name}_len = {counter};\n\n")
  2533. os.remove(path)
  2534. if __name__ == "__main__":
  2535. parser = argparse.ArgumentParser(description="GGML Vulkan Shader Generator")
  2536. parser.add_argument("--glslc", help="Path to glslc")
  2537. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  2538. args = parser.parse_args()
  2539. logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
  2540. if args.glslc:
  2541. GLSLC = args.glslc
  2542. asyncio.run(main())