ggml-vulkan.cpp 721 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <unordered_map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <future>
  36. #include <thread>
  37. #if defined(_MSC_VER)
  38. # define NOMINMAX 1
  39. # include <windows.h>
  40. # define YIELD() YieldProcessor()
  41. #elif defined(__clang__) || defined(__GNUC__)
  42. # if defined(__x86_64__) ||defined(__i386__)
  43. # include <immintrin.h>
  44. # define YIELD() _mm_pause()
  45. # elif defined(__arm__) || defined(__aarch64__)
  46. # if defined(__clang__)
  47. # include <arm_acle.h>
  48. # define YIELD() __yield()
  49. # else
  50. # define YIELD() asm volatile("yield")
  51. # endif
  52. # endif
  53. #endif
  54. #if !defined(YIELD)
  55. #define YIELD()
  56. #endif
  57. #include "ggml-impl.h"
  58. #include "ggml-backend-impl.h"
  59. #include "ggml-vulkan-shaders.hpp"
  60. // remove this once it's more widely available in the SDK
  61. #if !defined(VK_KHR_shader_bfloat16)
  62. #define VK_KHR_shader_bfloat16 1
  63. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  64. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  65. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  66. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  67. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  68. VkStructureType sType;
  69. void* pNext;
  70. VkBool32 shaderBFloat16Type;
  71. VkBool32 shaderBFloat16DotProduct;
  72. VkBool32 shaderBFloat16CooperativeMatrix;
  73. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  74. #endif
  75. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  76. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  77. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  78. #define VK_VENDOR_ID_AMD 0x1002
  79. #define VK_VENDOR_ID_APPLE 0x106b
  80. #define VK_VENDOR_ID_INTEL 0x8086
  81. #define VK_VENDOR_ID_NVIDIA 0x10de
  82. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  83. #define GGML_VK_MAX_NODES 8192
  84. #define VK_CHECK(err, msg) \
  85. do { \
  86. vk::Result err_ = (err); \
  87. if (err_ != vk::Result::eSuccess) { \
  88. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  89. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  90. exit(1); \
  91. } \
  92. } while (0)
  93. #ifdef GGML_VULKAN_DEBUG
  94. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  95. #else
  96. #define VK_LOG_DEBUG(msg) ((void) 0)
  97. #endif // GGML_VULKAN_DEBUG
  98. struct ggml_backend_vk_context;
  99. #define MAX_PARAMETER_COUNT 12
  100. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  101. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  102. struct vk_pipeline_struct {
  103. std::string name;
  104. vk::ShaderModule shader_module;
  105. vk::PipelineLayout layout;
  106. vk::Pipeline pipeline;
  107. uint32_t push_constant_size;
  108. uint32_t parameter_count;
  109. std::array<uint32_t, 3> wg_denoms;
  110. uint32_t align;
  111. // true if fields have been set by ggml_vk_create_pipeline
  112. bool initialized {};
  113. // set to true to request the pipeline is compiled
  114. std::atomic<bool> needed {};
  115. // set to true when the shader has been compiled
  116. std::atomic<bool> compiled {};
  117. // number of registers used, extracted from pipeline executable properties
  118. uint32_t register_count {};
  119. };
  120. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  121. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  122. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  123. struct vk_matmul_pipeline_struct {
  124. vk_pipeline l, m, s;
  125. vk_pipeline a_l, a_m, a_s;
  126. // Returns true when all unaligned pipelines are null.
  127. // We only check for unaligned variants since one of the unaligned pipelines must exist
  128. // while aligned pipelines are optional
  129. bool is_empty() const {
  130. return l == nullptr && m == nullptr && s == nullptr;
  131. }
  132. };
  133. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  134. struct vk_matmul_pipeline2 {
  135. vk_matmul_pipeline2() {
  136. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  137. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. }
  139. vk_matmul_pipeline f32acc;
  140. vk_matmul_pipeline f16acc;
  141. };
  142. struct vk_device_struct;
  143. typedef std::shared_ptr<vk_device_struct> vk_device;
  144. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  145. struct vk_buffer_struct;
  146. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  147. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  148. struct ggml_backend_vk_buffer_type_context {
  149. std::string name;
  150. vk_device device;
  151. };
  152. struct vk_queue;
  153. // Stores command pool/buffers. There's an instance of this
  154. // for each (context,queue) pair and for each (device,queue) pair.
  155. struct vk_command_pool {
  156. void init(vk_device& device, vk_queue *q_);
  157. void destroy(vk::Device& device);
  158. vk::CommandPool pool;
  159. uint32_t cmd_buffer_idx;
  160. std::vector<vk::CommandBuffer> cmd_buffers;
  161. vk_queue *q;
  162. };
  163. // Prevent simultaneous submissions to the same queue.
  164. // This could be per vk_queue if we stopped having two vk_queue structures
  165. // sharing the same vk::Queue.
  166. static std::mutex queue_mutex;
  167. struct vk_queue {
  168. uint32_t queue_family_index;
  169. vk::Queue queue;
  170. vk_command_pool cmd_pool;
  171. vk::PipelineStageFlags stage_flags;
  172. bool transfer_only;
  173. // copy everything except the cmd_pool
  174. void copyFrom(vk_queue &other) {
  175. queue_family_index = other.queue_family_index;
  176. queue = other.queue;
  177. stage_flags = other.stage_flags;
  178. transfer_only = other.transfer_only;
  179. }
  180. };
  181. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  182. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  183. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  184. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  186. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  187. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  188. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  189. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  190. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  191. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  192. /* .is_host = */ NULL,
  193. };
  194. #ifdef GGML_VULKAN_MEMORY_DEBUG
  195. class vk_memory_logger;
  196. #endif
  197. class vk_perf_logger;
  198. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  199. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  200. static constexpr uint32_t p021_max_gqa_ratio = 8;
  201. enum vk_device_architecture {
  202. OTHER,
  203. AMD_GCN,
  204. AMD_RDNA1,
  205. AMD_RDNA2,
  206. AMD_RDNA3,
  207. INTEL_XE2,
  208. NVIDIA_PRE_TURING,
  209. };
  210. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  211. vk::PhysicalDeviceProperties props = device.getProperties();
  212. if (props.vendorID == VK_VENDOR_ID_AMD) {
  213. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  214. bool amd_shader_core_properties = false;
  215. bool integer_dot_product = false;
  216. bool subgroup_size_control = false;
  217. for (const auto& properties : ext_props) {
  218. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  219. amd_shader_core_properties = true;
  220. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  221. integer_dot_product = true;
  222. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  223. subgroup_size_control = true;
  224. }
  225. }
  226. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  227. return vk_device_architecture::OTHER;
  228. }
  229. vk::PhysicalDeviceProperties2 props2;
  230. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  231. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  232. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  233. props2.pNext = &shader_core_props_amd;
  234. shader_core_props_amd.pNext = &integer_dot_props;
  235. integer_dot_props.pNext = &subgroup_size_control_props;
  236. device.getProperties2(&props2);
  237. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  238. return vk_device_architecture::AMD_GCN;
  239. }
  240. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  241. // RDNA
  242. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  243. return vk_device_architecture::AMD_RDNA1;
  244. }
  245. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  246. return vk_device_architecture::AMD_RDNA3;
  247. }
  248. return vk_device_architecture::AMD_RDNA2;
  249. }
  250. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  251. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  252. bool subgroup_size_control = false;
  253. for (const auto& properties : ext_props) {
  254. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  255. subgroup_size_control = true;
  256. }
  257. }
  258. if (!subgroup_size_control) {
  259. return vk_device_architecture::OTHER;
  260. }
  261. vk::PhysicalDeviceProperties2 props2;
  262. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  263. props2.pNext = &subgroup_size_control_props;
  264. device.getProperties2(&props2);
  265. if (subgroup_size_control_props.minSubgroupSize == 16) {
  266. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  267. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  268. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  269. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  270. return vk_device_architecture::INTEL_XE2;
  271. }
  272. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  273. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  274. bool cooperative_matrix = false;
  275. // Detect "pre-turing" based on lack of coopmat support.
  276. for (const auto& properties : ext_props) {
  277. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  278. cooperative_matrix = true;
  279. break;
  280. }
  281. }
  282. if (!cooperative_matrix) {
  283. return vk_device_architecture::NVIDIA_PRE_TURING;
  284. }
  285. }
  286. return vk_device_architecture::OTHER;
  287. }
  288. enum vk_conv_shapes {
  289. CONV_SHAPE_128x128,
  290. CONV_SHAPE_64x32,
  291. CONV_SHAPE_32x256,
  292. CONV_SHAPE_COUNT,
  293. };
  294. enum dmmv_wg_sizes {
  295. DMMV_WG_SIZE_SUBGROUP,
  296. DMMV_WG_SIZE_LARGE,
  297. DMMV_WG_SIZE_COUNT,
  298. };
  299. enum FaCodePath {
  300. FA_SCALAR,
  301. FA_COOPMAT1,
  302. FA_COOPMAT2,
  303. };
  304. struct vk_fa_pipeline_state {
  305. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  306. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  307. uint32_t HSK, HSV;
  308. bool small_rows;
  309. FaCodePath path;
  310. bool aligned;
  311. bool f32acc;
  312. bool operator<(const vk_fa_pipeline_state &b) const {
  313. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  314. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  315. }
  316. };
  317. enum shader_reduction_mode {
  318. SHADER_REDUCTION_MODE_SHMEM,
  319. SHADER_REDUCTION_MODE_HYBRID,
  320. SHADER_REDUCTION_MODE_SUBGROUP,
  321. SHADER_REDUCTION_MODE_COUNT,
  322. };
  323. static constexpr uint32_t num_argsort_pipelines = 11;
  324. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  325. static constexpr uint32_t num_topk_moe_pipelines = 10;
  326. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  327. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  328. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  329. GGML_OP_RESHAPE };
  330. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  331. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  332. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  333. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  334. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  335. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  336. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  337. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  338. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  339. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  340. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  341. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  342. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  343. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  344. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  345. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  346. { 1, 0, 0 }, // reshape->src[0] == softmax
  347. { 2, 0, 0 }, // argsort->src[0] == softmax
  348. { 3, 0, 2 }, // view->src[0] == argsort
  349. { 4, 0, 1 }, // get_rows->src[0] == reshape
  350. { 4, 1, 3 }, // get_rows->src[1] == view
  351. { 5, 0, 4 }, // reshape->src[0] == get_rows
  352. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  353. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  354. { 8, 0, 5 }, // div->src[0] == reshape
  355. { 8, 1, 7 }, // div->src[1] == clamp
  356. { 9, 0, 8 }, // reshape->src[0] == div
  357. };
  358. // same as early_softmax_norm but ending after the get_rows
  359. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  360. { 1, 0, 0 }, // reshape->src[0] == softmax
  361. { 2, 0, 0 }, // argsort->src[0] == softmax
  362. { 3, 0, 2 }, // view->src[0] == argsort
  363. { 4, 0, 1 }, // get_rows->src[0] == reshape
  364. { 4, 1, 3 }, // get_rows->src[1] == view
  365. };
  366. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  367. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  368. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  369. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  370. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  371. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  372. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  373. { 1, 0, 0 }, // view->src[0] == argsort
  374. { 2, 1, 1 }, // get_rows->src[1] == view
  375. { 3, 0, 2 }, // reshape->src[0] == get_rows
  376. { 4, 0, 3 }, // soft_max->src[0] == reshape
  377. { 5, 0, 4 }, // reshape->src[0] == soft_max
  378. };
  379. enum topk_moe_mode {
  380. TOPK_MOE_EARLY_SOFTMAX,
  381. TOPK_MOE_EARLY_SOFTMAX_NORM,
  382. TOPK_MOE_LATE_SOFTMAX,
  383. TOPK_MOE_COUNT,
  384. };
  385. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  386. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  387. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  388. TOPK_MOE_LATE_SOFTMAX;
  389. return mode;
  390. }
  391. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  392. { 1, 0, 0 }, // view->src[0] == rope
  393. { 2, 0, 1 }, // set_rows->src[0] == view
  394. };
  395. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  396. { 1, 0, 0 }, // mul->src[0] == rms
  397. { 2, 0, 1 }, // rope->src[0] == mul
  398. { 3, 0, 2 }, // view->src[0] == rope
  399. { 4, 0, 3 }, // set_rows->src[0] == view
  400. };
  401. struct vk_device_struct {
  402. std::recursive_mutex mutex;
  403. vk::PhysicalDevice physical_device;
  404. vk::PhysicalDeviceProperties properties;
  405. std::string name;
  406. uint64_t max_memory_allocation_size;
  407. uint64_t max_buffer_size;
  408. uint64_t suballocation_block_size;
  409. bool fp16;
  410. bool bf16;
  411. bool pipeline_robustness;
  412. vk::Device device;
  413. uint32_t vendor_id;
  414. vk::DriverId driver_id;
  415. vk_device_architecture architecture;
  416. vk_queue compute_queue;
  417. vk_queue transfer_queue;
  418. bool single_queue;
  419. uint32_t subgroup_size;
  420. uint32_t shader_core_count;
  421. bool uma;
  422. bool prefer_host_memory;
  423. bool float_controls_rte_fp16;
  424. bool subgroup_arithmetic;
  425. bool subgroup_shuffle;
  426. bool subgroup_ballot;
  427. bool subgroup_clustered;
  428. bool multi_add;
  429. bool shader_int64;
  430. bool buffer_device_address;
  431. bool add_rms_fusion;
  432. uint32_t partials_binding_alignment;
  433. bool integer_dot_product;
  434. // 0: default, 1: force mmvq, -1: disable mmvq
  435. int32_t mmvq_mode;
  436. bool subgroup_size_control;
  437. uint32_t subgroup_min_size;
  438. uint32_t subgroup_max_size;
  439. bool subgroup_require_full_support;
  440. bool coopmat_support;
  441. bool coopmat_acc_f32_support {};
  442. bool coopmat_acc_f16_support {};
  443. bool coopmat_bf16_support {};
  444. bool coopmat_support_16x16x16_f16acc {};
  445. bool coopmat_support_16x16x16_f32acc {};
  446. bool coopmat1_fa_support {};
  447. uint32_t coopmat_m;
  448. uint32_t coopmat_n;
  449. uint32_t coopmat_k;
  450. bool coopmat_int_support;
  451. uint32_t coopmat_int_m;
  452. uint32_t coopmat_int_n;
  453. uint32_t coopmat_int_k;
  454. bool coopmat2;
  455. bool pipeline_executable_properties_support {};
  456. size_t idx;
  457. bool mul_mat_l[GGML_TYPE_COUNT];
  458. bool mul_mat_m[GGML_TYPE_COUNT];
  459. bool mul_mat_s[GGML_TYPE_COUNT];
  460. bool mul_mat_id_l[GGML_TYPE_COUNT];
  461. bool mul_mat_id_m[GGML_TYPE_COUNT];
  462. bool mul_mat_id_s[GGML_TYPE_COUNT];
  463. vk::DescriptorSetLayout dsl;
  464. vk_matmul_pipeline pipeline_matmul_f32 {};
  465. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  466. vk_matmul_pipeline pipeline_matmul_bf16 {};
  467. vk_matmul_pipeline2 pipeline_matmul_f16;
  468. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  469. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  470. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  471. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  472. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  473. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  474. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  475. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  476. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  477. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  478. vk_pipeline pipeline_matmul_split_k_reduce;
  479. vk_pipeline pipeline_quantize_q8_1;
  480. vk_pipeline pipeline_quantize_q8_1_x4;
  481. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  482. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  483. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  484. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  485. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  486. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  487. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  488. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  489. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  490. vk_pipeline pipeline_acc_f32;
  491. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  492. vk_pipeline pipeline_add[2][2][2];
  493. vk_pipeline pipeline_add_norepeat[2][2][2];
  494. vk_pipeline pipeline_sub[2][2][2];
  495. vk_pipeline pipeline_sub_norepeat[2][2][2];
  496. vk_pipeline pipeline_mul[2][2][2];
  497. vk_pipeline pipeline_mul_norepeat[2][2][2];
  498. vk_pipeline pipeline_div[2][2][2];
  499. vk_pipeline pipeline_div_norepeat[2][2][2];
  500. vk_pipeline pipeline_add_rms[2][2][2];
  501. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  502. // indexed by num_additional_fused_ops == num_adds - 1
  503. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  504. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  505. vk_pipeline pipeline_add_id_f32;
  506. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  507. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32;
  508. vk_pipeline pipeline_scale_f32;
  509. vk_pipeline pipeline_sqr_f32;
  510. vk_pipeline pipeline_sqrt_f32;
  511. vk_pipeline pipeline_sin_f32;
  512. vk_pipeline pipeline_cos_f32;
  513. vk_pipeline pipeline_clamp_f32;
  514. vk_pipeline pipeline_pad_f32;
  515. vk_pipeline pipeline_roll_f32;
  516. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  517. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  518. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  519. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  520. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  521. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  522. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  523. vk_pipeline pipeline_norm_f32;
  524. vk_pipeline pipeline_group_norm_f32;
  525. vk_pipeline pipeline_rms_norm_f32;
  526. vk_pipeline pipeline_rms_norm_mul_f32;
  527. vk_pipeline pipeline_rms_norm_partials_f32;
  528. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  529. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  530. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  531. vk_pipeline pipeline_rms_norm_back_f32;
  532. vk_pipeline pipeline_l2_norm_f32;
  533. // [src/dst 0=fp32,1=fp16]
  534. vk_pipeline pipeline_exp[2];
  535. vk_pipeline pipeline_gelu[2];
  536. vk_pipeline pipeline_gelu_erf[2];
  537. vk_pipeline pipeline_gelu_quick[2];
  538. vk_pipeline pipeline_silu[2];
  539. vk_pipeline pipeline_relu[2];
  540. vk_pipeline pipeline_tanh[2];
  541. vk_pipeline pipeline_sigmoid[2];
  542. vk_pipeline pipeline_hardsigmoid[2];
  543. vk_pipeline pipeline_hardswish[2];
  544. vk_pipeline pipeline_geglu[2];
  545. vk_pipeline pipeline_reglu[2];
  546. vk_pipeline pipeline_swiglu[2];
  547. vk_pipeline pipeline_swiglu_oai[2];
  548. vk_pipeline pipeline_geglu_erf[2];
  549. vk_pipeline pipeline_geglu_quick[2];
  550. vk_pipeline pipeline_leaky_relu_f32;
  551. vk_pipeline pipeline_silu_back_f32;
  552. vk_pipeline pipeline_diag_mask_inf_f32;
  553. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  554. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  555. vk_pipeline pipeline_soft_max_back_f32;
  556. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  557. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  558. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  559. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  560. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  561. vk_pipeline pipeline_sum_rows_f32;
  562. vk_pipeline pipeline_argmax_f32;
  563. vk_pipeline pipeline_count_equal_i32;
  564. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  565. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  566. vk_pipeline pipeline_timestep_embedding_f32;
  567. vk_pipeline pipeline_conv_transpose_1d_f32;
  568. vk_pipeline pipeline_pool2d_f32;
  569. vk_pipeline pipeline_rwkv_wkv6_f32;
  570. vk_pipeline pipeline_rwkv_wkv7_f32;
  571. vk_pipeline pipeline_ssm_scan_f32_d128;
  572. vk_pipeline pipeline_ssm_scan_f32_d256;
  573. vk_pipeline pipeline_ssm_conv_f32;
  574. vk_pipeline pipeline_opt_step_adamw_f32;
  575. vk_pipeline pipeline_opt_step_sgd_f32;
  576. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  577. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  578. vk_pipeline pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  579. vk_pipeline pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  580. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  581. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  582. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  583. vk_pipeline pipeline_flash_attn_split_k_reduce;
  584. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  585. std::vector<vk_pipeline_ref> all_pipelines;
  586. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  587. vk::Fence fence;
  588. vk_buffer sync_staging;
  589. ggml_backend_buffer_type buffer_type;
  590. bool disable_fusion;
  591. bool disable_host_visible_vidmem;
  592. bool allow_sysmem_fallback;
  593. bool disable_graph_optimize;
  594. #ifdef GGML_VULKAN_MEMORY_DEBUG
  595. std::unique_ptr<vk_memory_logger> memory_logger;
  596. #endif
  597. // for GGML_VK_PERF_LOGGER
  598. std::unique_ptr<vk_perf_logger> perf_logger;
  599. vk::QueryPool query_pool;
  600. int32_t num_queries;
  601. ~vk_device_struct() {
  602. VK_LOG_DEBUG("destroy device " << name);
  603. device.destroyFence(fence);
  604. ggml_vk_destroy_buffer(sync_staging);
  605. compute_queue.cmd_pool.destroy(device);
  606. transfer_queue.cmd_pool.destroy(device);
  607. for (auto& pipeline : all_pipelines) {
  608. if (pipeline.expired()) {
  609. continue;
  610. }
  611. vk_pipeline pl = pipeline.lock();
  612. ggml_vk_destroy_pipeline(device, pl);
  613. }
  614. all_pipelines.clear();
  615. device.destroyDescriptorSetLayout(dsl);
  616. device.destroy();
  617. }
  618. };
  619. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  620. cmd_buffer_idx = 0;
  621. q = q_;
  622. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  623. pool = device->device.createCommandPool(command_pool_create_info);
  624. }
  625. void vk_command_pool::destroy(vk::Device& device) {
  626. device.destroyCommandPool(pool);
  627. pool = nullptr;
  628. cmd_buffers.clear();
  629. }
  630. struct vk_buffer_struct {
  631. vk::Buffer buffer = VK_NULL_HANDLE;
  632. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  633. vk::MemoryPropertyFlags memory_property_flags;
  634. void * ptr;
  635. size_t size = 0;
  636. vk::DeviceAddress bda_addr {};
  637. vk_device device;
  638. ~vk_buffer_struct() {
  639. if (size == 0) {
  640. return;
  641. }
  642. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  643. device->device.freeMemory(device_memory);
  644. device->device.destroyBuffer(buffer);
  645. }
  646. };
  647. struct vk_subbuffer {
  648. vk_buffer buffer;
  649. uint64_t offset;
  650. uint64_t size;
  651. operator vk::DescriptorBufferInfo() const {
  652. return { buffer->buffer, offset, size };
  653. }
  654. };
  655. struct vk_semaphore {
  656. vk::Semaphore s;
  657. uint64_t value;
  658. };
  659. struct vk_submission {
  660. vk::CommandBuffer buffer;
  661. std::vector<vk_semaphore> wait_semaphores;
  662. std::vector<vk_semaphore> signal_semaphores;
  663. };
  664. typedef std::vector<vk_submission> vk_sequence;
  665. struct vk_mat_mat_push_constants {
  666. uint32_t M; uint32_t N; uint32_t K;
  667. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  668. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  669. uint32_t k_split;
  670. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  671. uint32_t padded_N;
  672. };
  673. struct vk_mat_vec_push_constants {
  674. uint32_t ncols;
  675. uint32_t stride_a;
  676. uint32_t stride_b;
  677. uint32_t stride_d;
  678. uint32_t batch_stride_a;
  679. uint32_t batch_stride_b;
  680. uint32_t batch_stride_d;
  681. uint32_t enable_bias;
  682. uint32_t ne02;
  683. uint32_t ne12;
  684. uint32_t broadcast2;
  685. uint32_t broadcast3;
  686. };
  687. struct vk_mat_mat_id_push_constants {
  688. uint32_t M; uint32_t N; uint32_t K;
  689. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  690. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  691. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  692. uint32_t padded_N;
  693. };
  694. struct vk_mat_vec_id_push_constants {
  695. uint32_t ncols;
  696. uint32_t stride_a;
  697. uint32_t stride_b;
  698. uint32_t stride_d;
  699. uint32_t batch_stride_a;
  700. uint32_t batch_stride_b;
  701. uint32_t batch_stride_d;
  702. uint32_t enable_bias;
  703. uint32_t nei0;
  704. uint32_t ne11;
  705. };
  706. struct vk_flash_attn_push_constants {
  707. uint32_t N;
  708. uint32_t KV;
  709. uint32_t ne1;
  710. uint32_t ne2;
  711. uint32_t ne3;
  712. uint32_t neq2;
  713. uint32_t neq3;
  714. uint32_t nek2;
  715. uint32_t nek3;
  716. uint32_t nev2;
  717. uint32_t nev3;
  718. uint32_t nem1;
  719. uint32_t nem2;
  720. uint32_t nem3;
  721. uint32_t nb01;
  722. uint32_t nb02;
  723. uint32_t nb03;
  724. uint32_t nb11;
  725. uint32_t nb12;
  726. uint32_t nb13;
  727. uint32_t nb21;
  728. uint32_t nb22;
  729. uint32_t nb23;
  730. float scale;
  731. float max_bias;
  732. float logit_softcap;
  733. uint32_t mask_n_head_log2;
  734. float m0;
  735. float m1;
  736. uint32_t gqa_ratio;
  737. uint32_t split_kv;
  738. uint32_t k_num;
  739. };
  740. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  741. struct vk_op_push_constants {
  742. uint32_t KX;
  743. uint32_t KY;
  744. float param1;
  745. float param2;
  746. };
  747. struct vk_op_glu_push_constants {
  748. uint32_t N;
  749. uint32_t ne00;
  750. uint32_t ne20;
  751. uint32_t mode; // 0: default, 1: swapped, 2: split
  752. float alpha; // for swiglu_oai
  753. float limit;
  754. };
  755. struct vk_op_unary_push_constants {
  756. uint32_t ne;
  757. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  758. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  759. uint32_t misalign_offsets;
  760. float param1; float param2;
  761. uint32_t ne0_012mp; uint32_t ne0_012L;
  762. uint32_t ne0_01mp; uint32_t ne0_01L;
  763. uint32_t ne0_0mp; uint32_t ne0_0L;
  764. uint32_t ne1_012mp; uint32_t ne1_012L;
  765. uint32_t ne1_01mp; uint32_t ne1_01L;
  766. uint32_t ne1_0mp; uint32_t ne1_0L;
  767. };
  768. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  769. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  770. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  771. ne = ne != 0 ? ne : ggml_nelements(dst);
  772. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  773. vk_op_unary_push_constants p{};
  774. p.ne = (uint32_t)ne;
  775. size_t src0_tsize = ggml_type_size(src0->type);
  776. p.ne00 = (uint32_t)src0->ne[0];
  777. p.ne01 = (uint32_t)src0->ne[1];
  778. p.ne02 = (uint32_t)src0->ne[2];
  779. p.ne03 = (uint32_t)src0->ne[3];
  780. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  781. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  782. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  783. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  784. size_t dst_tsize = ggml_type_size(dst->type);
  785. p.ne10 = (uint32_t)dst->ne[0];
  786. p.ne11 = (uint32_t)dst->ne[1];
  787. p.ne12 = (uint32_t)dst->ne[2];
  788. p.ne13 = (uint32_t)dst->ne[3];
  789. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  790. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  791. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  792. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  793. return p; // offsets are initialized later in ggml_vk_op
  794. }
  795. struct vk_op_pad_push_constants {
  796. uint32_t ne;
  797. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  798. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  799. uint32_t misalign_offsets;
  800. uint32_t lp0; uint32_t rp0;
  801. uint32_t lp1; uint32_t rp1;
  802. uint32_t lp2; uint32_t rp2;
  803. uint32_t lp3; uint32_t rp3;
  804. };
  805. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  806. int64_t ne = ggml_nelements(dst);
  807. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  808. vk_op_pad_push_constants p{};
  809. p.ne = (uint32_t)ne;
  810. size_t src0_tsize = ggml_type_size(src0->type);
  811. p.ne00 = (uint32_t)src0->ne[0];
  812. p.ne01 = (uint32_t)src0->ne[1];
  813. p.ne02 = (uint32_t)src0->ne[2];
  814. p.ne03 = (uint32_t)src0->ne[3];
  815. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  816. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  817. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  818. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  819. size_t dst_tsize = ggml_type_size(dst->type);
  820. p.ne10 = (uint32_t)dst->ne[0];
  821. p.ne11 = (uint32_t)dst->ne[1];
  822. p.ne12 = (uint32_t)dst->ne[2];
  823. p.ne13 = (uint32_t)dst->ne[3];
  824. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  825. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  826. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  827. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  828. p.lp0 = dst->op_params[0];
  829. p.rp0 = dst->op_params[1];
  830. p.lp1 = dst->op_params[2];
  831. p.rp1 = dst->op_params[3];
  832. p.lp2 = dst->op_params[4];
  833. p.rp2 = dst->op_params[5];
  834. p.lp3 = dst->op_params[6];
  835. p.rp3 = dst->op_params[7];
  836. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  837. }
  838. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  839. // Precompute mp (m' in the paper) and L such that division
  840. // can be computed using a multiply (high 32b of 64b result)
  841. // and a shift:
  842. //
  843. // n/d = (mulhi(n, mp) + n) >> L;
  844. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  845. {
  846. // compute L = ceil(log2(d));
  847. L = 0;
  848. while (L < 32 && (uint32_t{1} << L) < d) {
  849. L++;
  850. }
  851. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  852. }
  853. template <typename T> void init_pushconst_fastdiv(T &p) {
  854. GGML_UNUSED(p);
  855. static_assert(!std::is_const<T>::value, "unexpected type");
  856. }
  857. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  858. // Compute magic values to divide by these six numbers.
  859. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  860. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  861. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  862. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  863. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  864. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  865. }
  866. struct vk_op_binary_push_constants {
  867. uint32_t ne;
  868. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  869. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  870. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  871. uint32_t misalign_offsets;
  872. float param1; float param2; int32_t param3;
  873. };
  874. struct vk_op_multi_add_push_constants {
  875. // shape for dst
  876. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  877. // strides for srcs+dst
  878. uint32_t nb[MAX_PARAMETER_COUNT][4];
  879. uint32_t rms_partials;
  880. };
  881. // update multi_add.comp if this changes
  882. static_assert(MAX_PARAMETER_COUNT == 12);
  883. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  884. struct vk_op_topk_moe_push_constants {
  885. uint32_t n_rows;
  886. uint32_t n_expert_used;
  887. float clamp_min;
  888. float clamp_max;
  889. };
  890. struct vk_op_add_id_push_constants {
  891. uint32_t ne0;
  892. uint32_t ne1;
  893. uint32_t s01;
  894. uint32_t s02;
  895. uint32_t s11;
  896. uint32_t s21;
  897. };
  898. struct vk_op_diag_mask_push_constants {
  899. uint32_t ncols;
  900. uint32_t rows_per_channel;
  901. int32_t n_past;
  902. };
  903. struct vk_op_rope_push_constants {
  904. uint32_t rope_mode;
  905. uint32_t ncols;
  906. uint32_t n_dims;
  907. float freq_scale;
  908. uint32_t p_delta_rows;
  909. float freq_base;
  910. float ext_factor;
  911. float attn_factor;
  912. float corr_dims[2];
  913. float theta_scale;
  914. uint32_t has_ff;
  915. uint32_t ne02;
  916. uint32_t s1;
  917. uint32_t s2;
  918. int32_t sections[4];
  919. uint32_t is_imrope;
  920. uint32_t is_back;
  921. uint32_t set_rows_stride;
  922. };
  923. // For fused rms_norm+mul+rope(+view+set_rows)
  924. struct vk_op_rms_norm_mul_rope_push_constants {
  925. vk_op_binary_push_constants bin;
  926. vk_op_rope_push_constants rope;
  927. };
  928. struct vk_op_soft_max_push_constants {
  929. uint32_t KX;
  930. uint32_t KY;
  931. uint32_t ne00;
  932. uint32_t ne01;
  933. uint32_t ne02;
  934. uint32_t ne12;
  935. uint32_t ne13;
  936. uint32_t nb11;
  937. uint32_t nb12;
  938. uint32_t nb13;
  939. float scale;
  940. float max_bias;
  941. float m0;
  942. float m1;
  943. uint32_t n_head_log2;
  944. uint32_t nrows_x;
  945. uint32_t has_sinks;
  946. };
  947. struct vk_op_argsort_push_constants {
  948. uint32_t ncols;
  949. uint32_t nrows;
  950. int32_t order;
  951. };
  952. struct vk_op_im2col_push_constants {
  953. uint64_t dst_addr;
  954. uint32_t batch_offset; uint32_t offset_delta;
  955. uint32_t IC;
  956. uint32_t IW; uint32_t IH;
  957. uint32_t OW; uint32_t OH;
  958. uint32_t KW; uint32_t KH;
  959. uint32_t pelements;
  960. uint32_t CHW;
  961. int32_t s0; int32_t s1;
  962. int32_t p0; int32_t p1;
  963. int32_t d0; int32_t d1;
  964. };
  965. struct vk_op_im2col_3d_push_constants {
  966. uint64_t dst_addr;
  967. uint32_t nb10;
  968. uint32_t nb11;
  969. uint32_t nb12;
  970. uint32_t nb13;
  971. uint32_t s0;
  972. uint32_t s1;
  973. uint32_t s2;
  974. uint32_t p0;
  975. uint32_t p1;
  976. uint32_t p2;
  977. uint32_t d0;
  978. uint32_t d1;
  979. uint32_t d2;
  980. uint32_t IW;
  981. uint32_t IH;
  982. uint32_t ID;
  983. uint32_t IC;
  984. uint32_t KW;
  985. uint32_t OH;
  986. uint32_t KD_KH_KW;
  987. uint32_t KH_KW;
  988. uint32_t IC_KD_KH_KW;
  989. uint32_t N_OD_OH;
  990. uint32_t OD_OH;
  991. uint32_t OD_OH_OW_IC_KD_KH_KW;
  992. uint32_t OH_OW_IC_KD_KH_KW;
  993. uint32_t OW_IC_KD_KH_KW;
  994. uint32_t misalign_offsets;
  995. };
  996. struct vk_op_timestep_embedding_push_constants {
  997. uint32_t nb1;
  998. uint32_t dim;
  999. uint32_t max_period;
  1000. };
  1001. struct vk_op_conv_transpose_1d_push_constants {
  1002. uint32_t Cout;
  1003. uint32_t Cin;
  1004. uint32_t K;
  1005. uint32_t L;
  1006. uint32_t KL;
  1007. uint32_t nb01;
  1008. uint32_t nb02;
  1009. uint32_t nb11;
  1010. uint32_t nb1;
  1011. int32_t s0;
  1012. };
  1013. struct vk_op_pool2d_push_constants {
  1014. uint32_t IW; uint32_t IH;
  1015. uint32_t OW; uint32_t OH;
  1016. uint32_t OC;
  1017. uint32_t pelements;
  1018. uint32_t op;
  1019. int32_t k0; int32_t k1;
  1020. int32_t s0; int32_t s1;
  1021. int32_t p0; int32_t p1;
  1022. };
  1023. struct vk_op_rwkv_wkv6_push_constants {
  1024. uint32_t B;
  1025. uint32_t T;
  1026. uint32_t C;
  1027. uint32_t H;
  1028. };
  1029. struct vk_op_rwkv_wkv7_push_constants {
  1030. uint32_t B;
  1031. uint32_t T;
  1032. uint32_t C;
  1033. uint32_t H;
  1034. };
  1035. struct vk_op_ssm_scan_push_constants {
  1036. uint32_t nb02, nb03, nb12, nb13;
  1037. uint32_t nb21, nb22, nb31;
  1038. uint32_t nb42, nb43, nb52, nb53;
  1039. uint32_t s_off;
  1040. uint32_t n_head, d_head, n_group, n_tok;
  1041. };
  1042. struct vk_op_ssm_conv_push_constants {
  1043. uint32_t nb01, nb02;
  1044. uint32_t nb11;
  1045. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1046. uint32_t nc, ncs, nr, n_t, n_s;
  1047. };
  1048. struct vk_op_conv2d_push_constants {
  1049. uint32_t Cout;
  1050. uint32_t Cin;
  1051. uint32_t N;
  1052. uint32_t KW;
  1053. uint32_t KH;
  1054. uint32_t W;
  1055. uint32_t H;
  1056. uint32_t OW;
  1057. uint32_t OH;
  1058. uint32_t s0;
  1059. uint32_t s1;
  1060. uint32_t p0;
  1061. uint32_t p1;
  1062. uint32_t d0;
  1063. uint32_t d1;
  1064. uint32_t nb01;
  1065. uint32_t nb02;
  1066. uint32_t nb03;
  1067. uint32_t nb11;
  1068. uint32_t nb12;
  1069. uint32_t nb13;
  1070. uint32_t nb1;
  1071. uint32_t nb2;
  1072. uint32_t nb3;
  1073. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  1074. uint32_t KWmp; uint32_t KWL;
  1075. uint32_t KWKHmp; uint32_t KWKHL;
  1076. uint32_t OWmp; uint32_t OWL;
  1077. uint32_t OWOHmp; uint32_t OWOHL;
  1078. };
  1079. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1080. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  1081. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1082. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1083. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1084. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1085. }
  1086. struct vk_op_conv_transpose_2d_push_constants {
  1087. uint32_t Cout;
  1088. uint32_t Cin;
  1089. uint32_t N;
  1090. uint32_t KW;
  1091. uint32_t KH;
  1092. uint32_t W;
  1093. uint32_t H;
  1094. uint32_t OW;
  1095. uint32_t OH;
  1096. uint32_t s0;
  1097. uint32_t s1;
  1098. uint32_t p0;
  1099. uint32_t p1;
  1100. uint32_t d0;
  1101. uint32_t d1;
  1102. uint32_t nb01;
  1103. uint32_t nb02;
  1104. uint32_t nb03;
  1105. uint32_t nb11;
  1106. uint32_t nb12;
  1107. uint32_t nb13;
  1108. uint32_t nb1;
  1109. uint32_t nb2;
  1110. uint32_t nb3;
  1111. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH, s0, s1
  1112. uint32_t KWmp; uint32_t KWL;
  1113. uint32_t KWKHmp; uint32_t KWKHL;
  1114. uint32_t OWmp; uint32_t OWL;
  1115. uint32_t OWOHmp; uint32_t OWOHL;
  1116. uint32_t s0mp; uint32_t s0L;
  1117. uint32_t s1mp; uint32_t s1L;
  1118. };
  1119. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1120. // Compute magic values to divide by KW, KW*KH, OW, OW*OH, s0, s1
  1121. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1122. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1123. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1124. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1125. init_fastdiv_values(p.s0, p.s0mp, p.s0L);
  1126. init_fastdiv_values(p.s1, p.s1mp, p.s1L);
  1127. }
  1128. struct vk_op_conv2d_dw_push_constants {
  1129. uint32_t ne;
  1130. uint32_t batches;
  1131. uint32_t channels;
  1132. uint32_t dst_w;
  1133. uint32_t dst_h;
  1134. uint32_t src_w;
  1135. uint32_t src_h;
  1136. uint32_t knl_w;
  1137. uint32_t knl_h;
  1138. int32_t stride_x;
  1139. int32_t stride_y;
  1140. int32_t pad_x;
  1141. int32_t pad_y;
  1142. int32_t dilation_x;
  1143. int32_t dilation_y;
  1144. };
  1145. struct vk_op_upscale_push_constants {
  1146. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1147. uint32_t ne00; uint32_t ne01;
  1148. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1149. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1150. float sf0; float sf1; float sf2; float sf3;
  1151. float pixel_offset;
  1152. };
  1153. struct vk_op_sum_rows_push_constants
  1154. {
  1155. uint32_t n_cols;
  1156. uint32_t ne01, ne02;
  1157. uint32_t nb01, nb02, nb03;
  1158. uint32_t nb11, nb12, nb13;
  1159. float weight;
  1160. uint32_t misalign_offsets;
  1161. uint32_t ne0_12mp, ne0_12L;
  1162. uint32_t ne0_1mp, ne0_1L;
  1163. };
  1164. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1165. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1166. vk_op_sum_rows_push_constants p = {};
  1167. p.n_cols = (uint32_t)n_cols;
  1168. p.ne01 = (uint32_t)src->ne[1];
  1169. p.ne02 = (uint32_t)src->ne[2];
  1170. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1171. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1172. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1173. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1174. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1175. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1176. p.weight = 1.0f;
  1177. return p;
  1178. }
  1179. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1180. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1181. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1182. }
  1183. // Allow pre-recording command buffers
  1184. struct vk_staging_memcpy {
  1185. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1186. void * dst;
  1187. const void * src;
  1188. size_t n;
  1189. };
  1190. struct vk_staging_memset {
  1191. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1192. void * dst;
  1193. uint32_t val;
  1194. size_t n;
  1195. };
  1196. struct vk_context_struct {
  1197. vk_submission * s;
  1198. std::vector<vk_sequence> seqs;
  1199. int exit_tensor_idx;
  1200. std::vector<vk_staging_memcpy> in_memcpys;
  1201. std::vector<vk_staging_memcpy> out_memcpys;
  1202. std::vector<vk_staging_memset> memsets;
  1203. vk_command_pool * p {};
  1204. };
  1205. typedef std::shared_ptr<vk_context_struct> vk_context;
  1206. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1207. struct ggml_vk_garbage_collector {
  1208. std::vector<vk_semaphore> tl_semaphores;
  1209. std::vector<vk_semaphore> semaphores;
  1210. std::vector<vk::Event> events;
  1211. std::vector<vk_context> contexts;
  1212. };
  1213. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1214. static void ggml_vk_load_shaders(vk_device& device);
  1215. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1216. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1217. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1218. static std::string format_size(size_t size) {
  1219. const size_t kib = 1024;
  1220. const size_t mib = kib * 1024;
  1221. const size_t gib = mib * 1024;
  1222. std::ostringstream oss;
  1223. oss << std::fixed << std::setprecision(2);
  1224. if (size >= gib) {
  1225. oss << static_cast<double>(size) / gib << " GiB";
  1226. } else if (size >= mib) {
  1227. oss << static_cast<double>(size) / mib << " MiB";
  1228. } else if (size >= kib) {
  1229. oss << static_cast<double>(size) / kib << " KiB";
  1230. } else {
  1231. oss << size << " B";
  1232. }
  1233. return oss.str();
  1234. }
  1235. class vk_memory_logger {
  1236. public:
  1237. vk_memory_logger(): total_device(0), total_host(0) {}
  1238. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1239. void log_deallocation(vk_buffer_ref buf_ref);
  1240. private:
  1241. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1242. size_t total_device;
  1243. size_t total_host;
  1244. };
  1245. #else
  1246. #define VK_LOG_MEMORY(msg) ((void) 0)
  1247. #endif // GGML_VULKAN_MEMORY_DEBUG
  1248. class vk_perf_logger {
  1249. public:
  1250. void print_timings() {
  1251. if (timings.empty()) {
  1252. return;
  1253. }
  1254. uint64_t total_all_op_times = 0;
  1255. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1256. for (const auto & t : timings) {
  1257. uint64_t total_op_times = 0;
  1258. for (const auto & time : t.second) {
  1259. total_op_times += time;
  1260. }
  1261. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1262. << " us";
  1263. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1264. auto it = flops.find(t.first);
  1265. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1266. uint64_t total_op_flops = 0;
  1267. for (const auto & elem : it->second) {
  1268. total_op_flops += elem;
  1269. }
  1270. std::cerr << " ("
  1271. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1272. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1273. << " GFLOPS/s)";
  1274. }
  1275. total_all_op_times += total_op_times;
  1276. std::cerr << std::endl;
  1277. }
  1278. if (timings.size() > 0) {
  1279. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1280. }
  1281. timings.clear();
  1282. flops.clear();
  1283. }
  1284. void log_timing(const ggml_tensor * node, uint64_t time) {
  1285. if (node->op == GGML_OP_UNARY) {
  1286. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1287. return;
  1288. }
  1289. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1290. const uint64_t m = node->src[0]->ne[1];
  1291. const uint64_t n = node->ne[1];
  1292. const uint64_t k = node->src[1]->ne[0];
  1293. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1294. std::string name = ggml_op_name(node->op);
  1295. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1296. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1297. name += "_VEC";
  1298. }
  1299. name += " ";
  1300. name += ggml_type_name(node->src[0]->type);
  1301. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1302. if (batch > 1) {
  1303. name += " batch=" + std::to_string(batch);
  1304. }
  1305. timings[name].push_back(time);
  1306. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1307. return;
  1308. }
  1309. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1310. std::string name = ggml_op_name(node->op);
  1311. ggml_tensor * knl = node->src[0];
  1312. uint64_t OW = node->ne[0];
  1313. uint64_t OH = node->ne[1];
  1314. uint64_t N = node->ne[3];
  1315. uint64_t Cout = node->ne[2];
  1316. uint64_t KW = knl->ne[0];
  1317. uint64_t KH = knl->ne[1];
  1318. uint64_t Cin = node->src[1]->ne[2];
  1319. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1320. uint64_t size_M = Cout;
  1321. uint64_t size_K = Cin * KW * KH;
  1322. uint64_t size_N = N * OW * OH;
  1323. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1324. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1325. ", N=N*OW*OH=" + std::to_string(size_N);
  1326. flops[name].push_back(n_flops);
  1327. timings[name].push_back(time);
  1328. return;
  1329. }
  1330. if (node->op == GGML_OP_RMS_NORM) {
  1331. std::string name = ggml_op_name(node->op);
  1332. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1333. timings[name].push_back(time);
  1334. return;
  1335. }
  1336. timings[ggml_op_name(node->op)].push_back(time);
  1337. }
  1338. private:
  1339. std::map<std::string, std::vector<uint64_t>> timings;
  1340. std::map<std::string, std::vector<uint64_t>> flops;
  1341. };
  1342. struct ggml_backend_vk_context {
  1343. std::string name;
  1344. vk_device device;
  1345. size_t semaphore_idx, event_idx;
  1346. ggml_vk_garbage_collector gc;
  1347. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1348. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1349. vk::Fence fence, almost_ready_fence;
  1350. bool almost_ready_fence_pending {};
  1351. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1352. // write partial sums to accumulate the square of the vector components
  1353. bool do_add_rms_partials_offset_calculation;
  1354. bool do_add_rms_partials;
  1355. uint64_t last_total_mul_mat_bytes {};
  1356. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1357. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1358. const ggml_tensor * prealloc_y_last_tensor_used {};
  1359. // Track which nodes have been used since the last sync, and whether they were written to
  1360. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1361. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1362. // Track which prealloc buffers have pending reads that need to be synchronized.
  1363. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1364. // and set to true after the buffer contents are consumed.
  1365. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1366. vk_context_ref compute_ctx;
  1367. vk_context_ref transfer_ctx;
  1368. std::vector<vk_context_ref> tensor_ctxs;
  1369. std::vector<vk::DescriptorPool> descriptor_pools;
  1370. std::vector<vk::DescriptorSet> descriptor_sets;
  1371. uint32_t descriptor_set_idx {};
  1372. uint32_t pipeline_descriptor_set_requirements {};
  1373. vk_command_pool compute_cmd_pool;
  1374. vk_command_pool transfer_cmd_pool;
  1375. // number of additional consecutive nodes that are being fused with the
  1376. // node currently being processed
  1377. int num_additional_fused_ops {};
  1378. // Bitmask of which fused ops need to write an intermediate value to memory.
  1379. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1380. // If there's no fusion, bit 0 is still set.
  1381. int fused_ops_write_mask {};
  1382. };
  1383. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1384. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1385. if (tensor->view_src) {
  1386. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1387. }
  1388. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1389. }
  1390. struct ggml_backend_vk_buffer_context {
  1391. vk_device_ref device;
  1392. vk_buffer dev_buffer;
  1393. std::string name;
  1394. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1395. device(device),
  1396. dev_buffer(dev_buffer),
  1397. name(name) {
  1398. }
  1399. ~ggml_backend_vk_buffer_context() {
  1400. ggml_vk_destroy_buffer(dev_buffer);
  1401. }
  1402. };
  1403. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1404. static std::mutex log_mutex;
  1405. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1406. std::lock_guard<std::mutex> guard(log_mutex);
  1407. vk_buffer buf = buf_ref.lock();
  1408. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1409. const std::string type = device ? "device" : "host";
  1410. allocations[buf->buffer] = size;
  1411. total_device += device ? size : 0;
  1412. total_host += device ? 0 : size;
  1413. VK_LOG_MEMORY(buf->device->name << ": +" << format_size(size) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  1414. }
  1415. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1416. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1417. return;
  1418. }
  1419. std::lock_guard<std::mutex> guard(log_mutex);
  1420. vk_buffer buf = buf_ref.lock();
  1421. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1422. std::string type = device ? "device" : "host";
  1423. auto it = allocations.find(buf->buffer);
  1424. total_device -= device ? it->second : 0;
  1425. total_host -= device ? 0 : it->second;
  1426. if (it != allocations.end()) {
  1427. VK_LOG_MEMORY(buf->device->name << ": -" << format_size(it->second) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  1428. allocations.erase(it);
  1429. } else {
  1430. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1431. }
  1432. }
  1433. #endif // GGML_VULKAN_MEMORY_DEBUG
  1434. struct vk_instance_t {
  1435. vk::Instance instance;
  1436. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1437. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1438. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1439. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1440. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1441. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1442. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1443. std::vector<size_t> device_indices;
  1444. std::vector<bool> device_supports_membudget;
  1445. vk_device devices[GGML_VK_MAX_DEVICES];
  1446. };
  1447. static bool vk_instance_initialized = false;
  1448. static vk_instance_t vk_instance;
  1449. static bool vk_perf_logger_enabled = false;
  1450. #ifdef GGML_VULKAN_CHECK_RESULTS
  1451. static size_t vk_skip_checks;
  1452. static size_t vk_output_tensor;
  1453. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1454. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1455. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1456. #endif
  1457. typedef void (*ggml_vk_func_t)(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
  1458. static void ggml_backend_vk_free(ggml_backend_t backend);
  1459. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1460. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1461. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1462. return range;
  1463. }
  1464. // Wait for ctx->fence to be signaled.
  1465. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1466. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1467. // during this wait.
  1468. if (ctx->almost_ready_fence_pending) {
  1469. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1470. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1471. ctx->almost_ready_fence_pending = false;
  1472. }
  1473. // Spin (w/pause) waiting for the graph to finish executing.
  1474. vk::Result result;
  1475. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1476. if (result != vk::Result::eNotReady) {
  1477. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1478. exit(1);
  1479. }
  1480. for (uint32_t i = 0; i < 100; ++i) {
  1481. YIELD();
  1482. YIELD();
  1483. YIELD();
  1484. YIELD();
  1485. YIELD();
  1486. YIELD();
  1487. YIELD();
  1488. YIELD();
  1489. YIELD();
  1490. YIELD();
  1491. }
  1492. }
  1493. ctx->device->device.resetFences({ ctx->fence });
  1494. }
  1495. // variables to track number of compiles in progress
  1496. static uint32_t compile_count = 0;
  1497. static std::mutex compile_count_mutex;
  1498. static std::condition_variable compile_count_cond;
  1499. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint,
  1500. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1501. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1502. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1503. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1504. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1505. GGML_ASSERT(parameter_count > 0);
  1506. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1507. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1508. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1509. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1510. vk::PushConstantRange pcr(
  1511. vk::ShaderStageFlagBits::eCompute,
  1512. 0,
  1513. pipeline->push_constant_size
  1514. );
  1515. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1516. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1517. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1518. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1519. specialization_entries[i].constantID = i;
  1520. specialization_entries[i].offset = i * sizeof(uint32_t);
  1521. specialization_entries[i].size = sizeof(uint32_t);
  1522. }
  1523. vk::SpecializationInfo specialization_info(
  1524. specialization_entries.size(),
  1525. specialization_entries.data(),
  1526. specialization_constants.size() * sizeof(uint32_t),
  1527. specialization_constants.data()
  1528. );
  1529. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1530. if (device->subgroup_require_full_support && require_full_subgroups) {
  1531. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1532. }
  1533. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1534. pipeline_shader_stage_create_flags,
  1535. vk::ShaderStageFlagBits::eCompute,
  1536. pipeline->shader_module,
  1537. entrypoint.c_str(),
  1538. &specialization_info);
  1539. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1540. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1541. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1542. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1543. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1544. }
  1545. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1546. device->pipeline_executable_properties_support ?
  1547. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1548. vk::PipelineCreateFlags{},
  1549. pipeline_shader_create_info,
  1550. pipeline->layout);
  1551. vk::PipelineRobustnessCreateInfoEXT rci;
  1552. if (device->pipeline_robustness && disable_robustness) {
  1553. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1554. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1555. compute_pipeline_create_info.setPNext(&rci);
  1556. }
  1557. try {
  1558. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1559. } catch (const vk::SystemError& e) {
  1560. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1561. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1562. throw e;
  1563. }
  1564. pipeline->compiled = true;
  1565. if (vk_instance.debug_utils_support) {
  1566. vk::DebugUtilsObjectNameInfoEXT duoni;
  1567. duoni.objectType = vk::ObjectType::ePipeline;
  1568. duoni.pObjectName = pipeline->name.c_str();
  1569. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1570. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1571. }
  1572. if (device->pipeline_executable_properties_support) {
  1573. vk::PipelineExecutableInfoKHR executableInfo;
  1574. executableInfo.pipeline = pipeline->pipeline;
  1575. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1576. for (auto & s : statistics) {
  1577. // "Register Count" is reported by NVIDIA drivers.
  1578. if (strcmp(s.name, "Register Count") == 0) {
  1579. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1580. pipeline->register_count = (uint32_t)s.value.u64;
  1581. }
  1582. }
  1583. }
  1584. device->all_pipelines.push_back(pipeline);
  1585. {
  1586. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1587. assert(compile_count > 0);
  1588. compile_count--;
  1589. }
  1590. compile_count_cond.notify_all();
  1591. }
  1592. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1593. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1594. device.destroyPipelineLayout(pipeline->layout);
  1595. device.destroyShaderModule(pipeline->shader_module);
  1596. device.destroyPipeline(pipeline->pipeline);
  1597. }
  1598. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1599. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1600. ctx->pipeline_descriptor_set_requirements += n;
  1601. if (!pipeline->compiled) {
  1602. pipeline->needed = true;
  1603. ggml_vk_load_shaders(ctx->device);
  1604. }
  1605. ggml_pipeline_allocate_descriptor_sets(ctx);
  1606. }
  1607. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1608. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1609. // Enough descriptors are available
  1610. return;
  1611. }
  1612. vk_device& device = ctx->device;
  1613. // Grow by 50% to avoid frequent allocations
  1614. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1615. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1616. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1617. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1618. while (to_alloc > 0) {
  1619. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1620. to_alloc -= alloc_count;
  1621. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1622. if (pool_idx >= ctx->descriptor_pools.size()) {
  1623. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1624. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1625. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1626. }
  1627. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1628. for (uint32_t i = 0; i < alloc_count; i++) {
  1629. layouts[i] = device->dsl;
  1630. }
  1631. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1632. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1633. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1634. pool_idx++;
  1635. }
  1636. }
  1637. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1638. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1639. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1640. // Reuse command buffer
  1641. return p.cmd_buffers[p.cmd_buffer_idx++];
  1642. }
  1643. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1644. p.pool,
  1645. vk::CommandBufferLevel::ePrimary,
  1646. 1);
  1647. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1648. auto buf = cmd_buffers.front();
  1649. p.cmd_buffers.push_back(buf);
  1650. p.cmd_buffer_idx++;
  1651. return buf;
  1652. }
  1653. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1654. if (ctx->seqs.empty()) {
  1655. if (fence) {
  1656. std::lock_guard<std::mutex> guard(queue_mutex);
  1657. ctx->p->q->queue.submit({}, fence);
  1658. }
  1659. return;
  1660. }
  1661. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1662. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1663. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1664. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1665. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1666. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1667. std::vector<vk::SubmitInfo> submit_infos;
  1668. int idx = -1;
  1669. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1670. size_t reserve = 0;
  1671. for (const auto& sequence : ctx->seqs) {
  1672. reserve += sequence.size();
  1673. }
  1674. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1675. tl_wait_semaphores.reserve(reserve);
  1676. tl_wait_vals.reserve(reserve);
  1677. tl_signal_semaphores.reserve(reserve);
  1678. tl_signal_vals.reserve(reserve);
  1679. tl_submit_infos.reserve(reserve);
  1680. submit_infos.reserve(reserve);
  1681. stage_flags.reserve(reserve);
  1682. for (const auto& sequence : ctx->seqs) {
  1683. for (const auto& submission : sequence) {
  1684. stage_flags.push_back({});
  1685. idx++;
  1686. tl_wait_vals.push_back({});
  1687. tl_wait_semaphores.push_back({});
  1688. tl_signal_vals.push_back({});
  1689. tl_signal_semaphores.push_back({});
  1690. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1691. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1692. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1693. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1694. }
  1695. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1696. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1697. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1698. }
  1699. tl_submit_infos.push_back({
  1700. (uint32_t) submission.wait_semaphores.size(),
  1701. tl_wait_vals[idx].data(),
  1702. (uint32_t) submission.signal_semaphores.size(),
  1703. tl_signal_vals[idx].data(),
  1704. });
  1705. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1706. tl_submit_infos[idx].pNext = nullptr;
  1707. vk::SubmitInfo si{
  1708. (uint32_t) submission.wait_semaphores.size(),
  1709. tl_wait_semaphores[idx].data(),
  1710. stage_flags[idx].data(),
  1711. 1,
  1712. &submission.buffer,
  1713. (uint32_t) submission.signal_semaphores.size(),
  1714. tl_signal_semaphores[idx].data(),
  1715. };
  1716. si.setPNext(&tl_submit_infos[idx]);
  1717. submit_infos.push_back(si);
  1718. }
  1719. }
  1720. std::lock_guard<std::mutex> guard(queue_mutex);
  1721. ctx->p->q->queue.submit(submit_infos, fence);
  1722. ctx->seqs.clear();
  1723. }
  1724. static uint32_t ggml_vk_find_queue_family_index(std::vector<vk::QueueFamilyProperties>& queue_family_props, const vk::QueueFlags& required, const vk::QueueFlags& avoid, int32_t compute_index, uint32_t min_num_queues) {
  1725. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1726. const uint32_t qfsize = queue_family_props.size();
  1727. // Try with avoid preferences first
  1728. for (uint32_t i = 0; i < qfsize; i++) {
  1729. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required && !(queue_family_props[i].queueFlags & avoid)) {
  1730. return i;
  1731. }
  1732. }
  1733. // Fall back to only required
  1734. for (size_t i = 0; i < qfsize; i++) {
  1735. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1736. return i;
  1737. }
  1738. }
  1739. // Fall back to reusing compute queue
  1740. for (size_t i = 0; i < qfsize; i++) {
  1741. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1742. return i;
  1743. }
  1744. }
  1745. // Fall back to ignoring min_num_queries
  1746. for (size_t i = 0; i < qfsize; i++) {
  1747. if (queue_family_props[i].queueFlags & required) {
  1748. return i;
  1749. }
  1750. }
  1751. // All commands that are allowed on a queue that supports transfer operations are also allowed on a queue that supports either graphics or compute operations.
  1752. // Thus, if the capabilities of a queue family include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT capability separately for that queue family is optional.
  1753. if (compute_index >= 0) {
  1754. return compute_index;
  1755. }
  1756. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1757. for(auto &q_family : queue_family_props) {
  1758. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1759. }
  1760. abort();
  1761. }
  1762. static void ggml_vk_create_queue(vk_device& device, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags, bool transfer_only) {
  1763. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1764. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1765. q.queue_family_index = queue_family_index;
  1766. q.transfer_only = transfer_only;
  1767. q.cmd_pool.init(device, &q);
  1768. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1769. q.stage_flags = stage_flags;
  1770. }
  1771. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1772. vk_context result = std::make_shared<vk_context_struct>();
  1773. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1774. ctx->gc.contexts.emplace_back(result);
  1775. result->p = &p;
  1776. return result;
  1777. }
  1778. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1779. vk_context result = std::make_shared<vk_context_struct>();
  1780. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1781. result->p = &p;
  1782. return result;
  1783. }
  1784. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1785. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1786. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1787. vk::SemaphoreCreateInfo ci{};
  1788. ci.setPNext(&tci);
  1789. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1790. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1791. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1792. }
  1793. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1794. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1795. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1796. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1797. vk::SemaphoreCreateInfo ci{};
  1798. ci.setPNext(&tci);
  1799. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1800. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1801. }
  1802. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1803. }
  1804. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1805. if (ctx->event_idx >= ctx->gc.events.size()) {
  1806. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1807. }
  1808. return ctx->gc.events[ctx->event_idx++];
  1809. }
  1810. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1811. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1812. // Requires command buffers to be done
  1813. device->device.resetCommandPool(p.pool);
  1814. p.cmd_buffer_idx = 0;
  1815. }
  1816. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1817. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1818. // Arbitrary frequency to cleanup/reuse command buffers
  1819. static constexpr uint32_t cleanup_frequency = 10;
  1820. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1821. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1822. }
  1823. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1824. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1825. }
  1826. }
  1827. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1828. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1829. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1830. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1831. (flags & memory_type.propertyFlags) == flags &&
  1832. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1833. return static_cast<int32_t>(i);
  1834. }
  1835. }
  1836. return UINT32_MAX;
  1837. }
  1838. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1839. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  1840. if (size > device->max_buffer_size) {
  1841. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1842. }
  1843. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1844. if (size == 0) {
  1845. buf->size = 0;
  1846. return buf;
  1847. }
  1848. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1849. vk::MemoryAllocateFlags mem_flags {};
  1850. if (device->buffer_device_address) {
  1851. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1852. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1853. }
  1854. vk::BufferCreateInfo buffer_create_info{
  1855. vk::BufferCreateFlags(),
  1856. size,
  1857. usage_flags,
  1858. vk::SharingMode::eExclusive,
  1859. 0,
  1860. nullptr,
  1861. };
  1862. buf->buffer = device->device.createBuffer(buffer_create_info);
  1863. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1864. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1865. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1866. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1867. const auto & req_flags = *it;
  1868. uint32_t memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1869. if (memory_type_index == UINT32_MAX) {
  1870. continue;
  1871. }
  1872. buf->memory_property_flags = req_flags;
  1873. try {
  1874. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index, &mem_flags_info });
  1875. break;
  1876. } catch (const vk::SystemError& e) {
  1877. // loop and retry
  1878. // during last attempt throw the exception
  1879. if (it + 1 == req_flags_list.end()) {
  1880. device->device.destroyBuffer(buf->buffer);
  1881. throw e;
  1882. }
  1883. }
  1884. }
  1885. if (!buf->device_memory) {
  1886. device->device.destroyBuffer(buf->buffer);
  1887. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1888. }
  1889. buf->ptr = nullptr;
  1890. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1891. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1892. }
  1893. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1894. buf->device = device;
  1895. buf->size = size;
  1896. if (device->buffer_device_address) {
  1897. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1898. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1899. }
  1900. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1901. device->memory_logger->log_allocation(buf, size);
  1902. #endif
  1903. return buf;
  1904. }
  1905. static vk_buffer ggml_vk_create_buffer_check(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  1906. try {
  1907. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1908. } catch (const vk::SystemError& e) {
  1909. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1910. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1911. throw e;
  1912. }
  1913. }
  1914. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1915. vk_buffer buf;
  1916. try {
  1917. if (device->prefer_host_memory) {
  1918. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1919. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1920. } else if (device->uma) {
  1921. // Fall back to host memory type
  1922. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1923. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1924. } else if (device->disable_host_visible_vidmem) {
  1925. if (device->allow_sysmem_fallback) {
  1926. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1927. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1928. } else {
  1929. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1930. }
  1931. } else {
  1932. // use rebar if available, otherwise fallback to device only visible memory
  1933. if (device->allow_sysmem_fallback) {
  1934. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1935. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1936. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1937. } else {
  1938. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1939. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1940. }
  1941. }
  1942. } catch (const vk::SystemError& e) {
  1943. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1944. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1945. throw e;
  1946. }
  1947. return buf;
  1948. }
  1949. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1950. if (buf == nullptr) {
  1951. return;
  1952. }
  1953. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1954. if (buf->device != nullptr) {
  1955. buf->device->memory_logger->log_deallocation(buf);
  1956. }
  1957. #endif
  1958. buf.reset();
  1959. }
  1960. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  1961. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  1962. }
  1963. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1964. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1965. const bool transfer_queue = subctx->p->q->transfer_only;
  1966. if (ctx) {
  1967. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1968. }
  1969. subctx->s->buffer.pipelineBarrier(
  1970. subctx->p->q->stage_flags,
  1971. subctx->p->q->stage_flags,
  1972. {},
  1973. { {
  1974. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1975. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1976. } },
  1977. {},
  1978. {}
  1979. );
  1980. }
  1981. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1982. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1983. if (events.empty()) {
  1984. return;
  1985. }
  1986. ctx->s->buffer.waitEvents(
  1987. events,
  1988. ctx->p->q->stage_flags,
  1989. ctx->p->q->stage_flags,
  1990. {},
  1991. {},
  1992. {}
  1993. );
  1994. }
  1995. // number of rows/cols for flash attention shader
  1996. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1997. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1998. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1999. if (hsv >= 192) {
  2000. return 2;
  2001. } else {
  2002. return 8;
  2003. }
  2004. }
  2005. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2006. // 128 threads split into four subgroups, each subgroup does 1/4
  2007. // of the Bc dimension.
  2008. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2009. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2010. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2011. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2012. if (path == FA_COOPMAT2) {
  2013. return flash_attention_num_small_rows;
  2014. } else {
  2015. return scalar_flash_attention_num_small_rows;
  2016. }
  2017. }
  2018. static std::array<uint32_t, 2> fa_rows_cols(FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) {
  2019. GGML_UNUSED(clamp);
  2020. GGML_UNUSED(hsv);
  2021. if (path == FA_SCALAR) {
  2022. if (small_rows) {
  2023. return {scalar_flash_attention_num_small_rows, 64};
  2024. } else {
  2025. if ((hsv | hsk) & 8) {
  2026. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2027. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2028. return {get_fa_scalar_num_large_rows(hsv), 64};
  2029. } else {
  2030. return {get_fa_scalar_num_large_rows(hsv), 32};
  2031. }
  2032. }
  2033. }
  2034. if (path == FA_COOPMAT1) {
  2035. if (small_rows) {
  2036. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2037. } else {
  2038. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2039. }
  2040. }
  2041. // small rows, large cols
  2042. if (small_rows) {
  2043. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2044. }
  2045. // small cols to reduce register count
  2046. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2047. if (hsk >= 512 || hsv >= 512) {
  2048. return {32, 32};
  2049. } else {
  2050. return {64, 32};
  2051. }
  2052. }
  2053. return {64, 64};
  2054. }
  2055. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2056. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2057. }
  2058. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
  2059. uint32_t lut_size = 0;
  2060. switch (src0_type) {
  2061. case GGML_TYPE_IQ1_S:
  2062. case GGML_TYPE_IQ1_M:
  2063. lut_size = 2*2048;
  2064. break;
  2065. case GGML_TYPE_IQ2_XXS:
  2066. lut_size = 8*256;
  2067. break;
  2068. case GGML_TYPE_IQ2_XS:
  2069. lut_size = 8*512;
  2070. break;
  2071. case GGML_TYPE_IQ2_S:
  2072. lut_size = 8*1024;
  2073. break;
  2074. case GGML_TYPE_IQ3_XXS:
  2075. lut_size = 4*256;
  2076. break;
  2077. case GGML_TYPE_IQ3_S:
  2078. lut_size = 4*512;
  2079. break;
  2080. case GGML_TYPE_IQ4_NL:
  2081. case GGML_TYPE_IQ4_XS:
  2082. case GGML_TYPE_MXFP4:
  2083. lut_size = 4*16;
  2084. break;
  2085. default:
  2086. break;
  2087. }
  2088. // Needs to be kept up to date on shader changes
  2089. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2090. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2091. const uint32_t warps = warptile[0] / warptile[10];
  2092. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2093. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2094. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2095. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2096. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2097. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2098. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2099. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2100. return supported;
  2101. }
  2102. struct GpuPipelineConfig {
  2103. // GPU architecture identifier.
  2104. // Example: vk_device_architecture::AMD_GCN
  2105. vk_device_architecture arch;
  2106. // Mapping of pipeline names to their specific subgroup sizes.
  2107. // Example: {"soft_max_f32", 64}
  2108. std::unordered_map<std::string, uint32_t> pipelines;
  2109. // Default subgroup size for this GPU.
  2110. // Defaults to 0 if not explicitly provided.
  2111. uint32_t default_subgroup_size = 0;
  2112. };
  2113. // Pipeline configuration for RDNA1 GPUs.
  2114. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2115. {"soft_max", 64}, {"im2col", 64},
  2116. {"argmax", 64}, {"mul_mat_vec", 64},
  2117. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2118. };
  2119. // Pipeline configuration for RDNA2 GPUs.
  2120. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2121. {"soft_max", 64}, {"im2col", 64},
  2122. };
  2123. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2124. // Define configurations for different GPUs.
  2125. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2126. {
  2127. vk_device_architecture::AMD_RDNA1,
  2128. {
  2129. rdna1_pipelines,
  2130. },
  2131. RDNA_DEFAULT_SUBGROUP_SIZE
  2132. },
  2133. {
  2134. vk_device_architecture::AMD_RDNA2,
  2135. {
  2136. rdna2_pipelines,
  2137. },
  2138. RDNA_DEFAULT_SUBGROUP_SIZE
  2139. },
  2140. };
  2141. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2142. for (const auto &config : gpu_pipeline_configs) {
  2143. if (config.arch == arch) {
  2144. auto pipIt = config.pipelines.find(pipeline_name);
  2145. if (pipIt != config.pipelines.end()) {
  2146. return pipIt->second;
  2147. }
  2148. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2149. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2150. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2151. for (const auto &entry : sorted_pipelines) {
  2152. if (pipeline_name.find(entry.first) != std::string::npos) {
  2153. return entry.second;
  2154. }
  2155. }
  2156. return config.default_subgroup_size;
  2157. }
  2158. }
  2159. return 0; // If no matching configuration is found
  2160. }
  2161. static void ggml_vk_load_shaders(vk_device& device) {
  2162. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2163. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2164. // some shaders have a minimum subgroup size
  2165. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2166. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2167. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2168. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2169. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2170. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2171. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2172. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2173. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2174. // mulmat
  2175. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2176. l_warptile_id, m_warptile_id, s_warptile_id,
  2177. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2178. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2179. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2180. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2181. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2182. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2183. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2184. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2185. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2186. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2187. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2188. uint32_t l_align, m_align, s_align;
  2189. if (device->coopmat2) {
  2190. // spec constants and tile sizes for non-quant matmul/matmul_id
  2191. l_warptile = { 256, 128, 256, 64, 1 };
  2192. m_warptile = { 256, 128, 128, 64, 0 };
  2193. s_warptile = { 128, 64, 64, 64, 0 };
  2194. l_wg_denoms = {128, 256, 1 };
  2195. m_wg_denoms = {128, 128, 1 };
  2196. s_wg_denoms = { 64, 64, 1 };
  2197. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2198. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2199. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2200. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2201. l_mmq_wg_denoms = { 128, 256, 1 };
  2202. m_mmq_wg_denoms = { 128, 128, 1 };
  2203. s_mmq_wg_denoms = { 32, 64, 1 };
  2204. // spec constants and tile sizes for quant matmul (Qi_K)
  2205. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2206. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2207. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2208. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2209. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2210. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2211. // spec constants and tile sizes for quant matmul_id
  2212. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2213. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2214. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2215. l_mmqid_wg_denoms = { 128, 128, 1 };
  2216. m_mmqid_wg_denoms = { 128, 64, 1 };
  2217. s_mmqid_wg_denoms = { 128, 64, 1 };
  2218. l_align = 128;
  2219. m_align = 64;
  2220. s_align = 32;
  2221. } else {
  2222. // Matrix cores require different warp group sizes
  2223. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2224. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2225. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2226. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2227. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2228. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2229. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2230. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2231. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2232. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2233. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2234. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2235. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2236. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2237. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2238. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2239. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2240. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2241. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2242. // K-quants use even more registers, mitigate by setting WMITER to 1
  2243. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2244. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2245. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2246. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2247. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2248. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2249. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2250. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2251. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2252. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2253. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2254. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2255. l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_subgroup_size_16 * 2, 64, 1, 4, 4, 1, mul_mat_subgroup_size_16 };
  2256. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2257. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2258. // chip specific tuning
  2259. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2260. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2261. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2262. }
  2263. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2264. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2265. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2266. l_align = 128;
  2267. m_align = 64;
  2268. s_align = 32;
  2269. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2270. ggml_type t = (ggml_type)i;
  2271. // Disable medium and large matrix multiplication if not enough shared memory is available
  2272. // Check mmq warptiles as the largest configuration
  2273. // Throw an error if not enough for any matrix multiplication is available
  2274. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2275. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2276. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2277. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2278. device->mul_mat_m[i] = false;
  2279. device->mul_mat_l[i] = false;
  2280. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2281. device->mul_mat_l[i] = false;
  2282. }
  2283. // Disable mul_mat_id if not enough shared memory is available
  2284. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2285. device->mul_mat_id_s[i] = false;
  2286. device->mul_mat_id_m[i] = false;
  2287. device->mul_mat_id_l[i] = false;
  2288. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2289. device->mul_mat_id_m[i] = false;
  2290. device->mul_mat_id_l[i] = false;
  2291. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2292. device->mul_mat_id_l[i] = false;
  2293. }
  2294. }
  2295. }
  2296. if (!device->pipeline_matmul_f32) {
  2297. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2298. }
  2299. if (!device->pipeline_matmul_f32_f16) {
  2300. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2301. }
  2302. if (!device->pipeline_matmul_id_f32) {
  2303. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2304. }
  2305. if (!device->pipeline_matmul_bf16) {
  2306. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2307. }
  2308. if (!device->pipeline_matmul_id_bf16) {
  2309. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2310. }
  2311. std::vector<std::future<void>> compiles;
  2312. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2313. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2314. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2315. if (!require_full_subgroups && required_subgroup_size == 0) {
  2316. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2317. }
  2318. if (!pipeline) {
  2319. pipeline = std::make_shared<vk_pipeline_struct>();
  2320. }
  2321. if (!pipeline->initialized) {
  2322. pipeline->name = name;
  2323. pipeline->parameter_count = parameter_count;
  2324. pipeline->push_constant_size = push_constant_size;
  2325. pipeline->wg_denoms = wg_denoms;
  2326. pipeline->align = align;
  2327. pipeline->initialized = true;
  2328. }
  2329. if (!pipeline->needed || pipeline->compiled) {
  2330. return;
  2331. }
  2332. // TODO: We're no longer benefitting from the async compiles (shaders are
  2333. // compiled individually, as needed) and this complexity can be removed.
  2334. {
  2335. // wait until fewer than N compiles are in progress
  2336. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2337. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2338. while (compile_count >= N) {
  2339. compile_count_cond.wait(guard);
  2340. }
  2341. compile_count++;
  2342. }
  2343. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2344. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2345. };
  2346. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2347. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2348. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2349. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2350. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2351. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2352. };
  2353. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  2354. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2355. };
  2356. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  2357. // For large number of rows, 128 invocations seems to work best.
  2358. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2359. // can't use 256 for D==80.
  2360. // For scalar, use 128 (arbitrary)
  2361. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2362. const uint32_t D = (hsk|hsv);
  2363. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2364. ? scalar_flash_attention_workgroup_size
  2365. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2366. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2367. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2368. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2369. const uint32_t D_lsb = D ^ (D & (D-1));
  2370. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2371. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2372. };
  2373. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2374. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2375. uint32_t HSK = fa.first.HSK; \
  2376. uint32_t HSV = fa.first.HSV; \
  2377. bool small_rows = fa.first.small_rows; \
  2378. FaCodePath path = fa.first.path; \
  2379. bool aligned = fa.first.aligned; \
  2380. bool f32acc = fa.first.f32acc; \
  2381. if (path == FAPATH) { \
  2382. if (aligned) { \
  2383. if (f32acc) { \
  2384. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2385. } else { \
  2386. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2387. } \
  2388. } else { \
  2389. if (f32acc) { \
  2390. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2391. } else { \
  2392. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2393. } \
  2394. } \
  2395. } \
  2396. }
  2397. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2398. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2399. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2400. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2401. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2402. if (device->coopmat1_fa_support) {
  2403. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2404. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2405. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2406. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2407. }
  2408. #endif
  2409. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2410. if (device->coopmat2) {
  2411. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2412. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2413. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2414. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2415. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2416. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2417. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2418. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2419. }
  2420. #endif
  2421. #undef CREATE_FA
  2422. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2423. if (device->coopmat2) {
  2424. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2425. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2426. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2427. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2428. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2429. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  2430. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  2431. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  2432. // Create 2 variants, {f16,f32} accumulator
  2433. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2434. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2435. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2436. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2437. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2438. if (device->coopmat_bf16_support) {
  2439. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2440. }
  2441. #endif
  2442. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0], matmul_q4_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2443. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1], matmul_q4_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2444. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0], matmul_q5_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2445. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1], matmul_q5_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2446. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0], matmul_q8_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2447. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K], matmul_q2_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2448. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K], matmul_q3_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2449. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K], matmul_q4_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2450. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K], matmul_q5_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2451. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K], matmul_q6_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2452. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_S], matmul_iq1_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2453. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_M], matmul_iq1_m_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2454. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2455. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2456. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_S], matmul_iq2_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2457. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2458. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_S], matmul_iq3_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2459. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2460. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2461. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_MXFP4], matmul_mxfp4_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2462. GGML_ASSERT(device->subgroup_ballot);
  2463. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2464. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2465. if (device->coopmat_bf16_support) {
  2466. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2467. }
  2468. #endif
  2469. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2470. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2471. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2472. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2473. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2474. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2475. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2476. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2477. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2478. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2479. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2480. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2481. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2482. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2483. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2484. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2485. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2486. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2487. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2488. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2489. #undef CREATE_MM
  2490. #undef CREATE_MM2
  2491. } else
  2492. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2493. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2494. if (device->coopmat_support) {
  2495. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2496. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2497. if (device->mul_mat ## ID ## _l[TYPE]) \
  2498. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  2499. if (device->mul_mat ## ID ## _m[TYPE]) \
  2500. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  2501. if (device->mul_mat ## ID ## _s[TYPE]) \
  2502. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  2503. if (device->mul_mat ## ID ## _l[TYPE]) \
  2504. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  2505. if (device->mul_mat ## ID ## _m[TYPE]) \
  2506. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  2507. if (device->mul_mat ## ID ## _s[TYPE]) \
  2508. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  2509. // Create 2 variants, {f16,f32} accumulator
  2510. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2511. if (device->coopmat_acc_f16_support) { \
  2512. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2513. } \
  2514. if (device->coopmat_acc_f32_support) { \
  2515. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2516. } \
  2517. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2518. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2519. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2520. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2521. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2522. if (device->coopmat_bf16_support) {
  2523. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2524. }
  2525. #endif
  2526. if (device->coopmat_acc_f16_support) {
  2527. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2528. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2529. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2530. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2531. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2532. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2533. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2534. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2535. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2536. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2537. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2538. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2539. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2540. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2541. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2542. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2543. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2544. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2545. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2546. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2547. } else {
  2548. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2549. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2550. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2551. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2552. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2553. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2554. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2555. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2556. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2557. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2558. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2559. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2560. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2561. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2562. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2563. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2564. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2565. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2566. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2567. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2568. }
  2569. GGML_ASSERT(device->subgroup_ballot);
  2570. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2571. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2572. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2573. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2574. if (device->coopmat_bf16_support) {
  2575. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2576. }
  2577. #endif
  2578. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2579. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2580. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2581. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2582. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2583. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2584. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2585. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2586. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2587. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2588. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2589. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2590. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2591. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2592. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2593. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2594. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2595. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2596. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2597. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2598. #undef CREATE_MM2
  2599. #undef CREATE_MM
  2600. } else
  2601. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2602. if (device->fp16) {
  2603. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2604. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2605. if (device->mul_mat ## ID ## _l[TYPE]) \
  2606. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2607. if (device->mul_mat ## ID ## _m[TYPE]) \
  2608. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2609. if (device->mul_mat ## ID ## _s[TYPE]) \
  2610. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2611. if (device->mul_mat ## ID ## _l[TYPE]) \
  2612. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2613. if (device->mul_mat ## ID ## _m[TYPE]) \
  2614. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2615. if (device->mul_mat ## ID ## _s[TYPE]) \
  2616. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2617. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2618. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2619. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2620. } \
  2621. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2622. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2623. } \
  2624. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2625. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2626. } \
  2627. // Create 2 variants, {f16,f32} accumulator
  2628. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2629. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2630. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2631. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2632. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2633. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2634. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2635. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2636. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2637. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2638. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2639. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2640. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2641. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2642. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2643. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2644. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2645. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2646. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2647. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2648. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2649. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2650. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2651. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2652. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2653. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2654. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2655. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2656. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2657. if (device->integer_dot_product) {
  2658. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2659. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2660. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2661. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2662. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2663. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_MXFP4], matmul_mxfp4_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2664. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K], matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2665. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K], matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2666. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K], matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2667. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K], matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2668. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K], matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2669. }
  2670. #endif
  2671. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2672. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2673. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2674. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2675. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2676. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2677. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2678. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2679. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2680. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2681. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2682. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2683. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2684. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2685. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2686. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2687. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2688. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2689. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2690. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2691. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2692. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2693. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2694. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2695. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2696. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2697. if (device->integer_dot_product) {
  2698. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2699. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2700. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2701. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2702. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2703. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2704. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2705. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2706. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2707. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2708. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2709. }
  2710. #endif
  2711. } else {
  2712. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2713. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2714. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2715. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2716. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2717. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2718. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2719. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2720. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2721. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2722. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2723. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2724. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2725. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2726. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2727. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2728. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2729. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2730. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2731. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2732. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2733. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2734. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2735. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2736. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2737. if (device->integer_dot_product) {
  2738. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2739. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2740. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2741. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2742. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2743. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2744. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2745. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2746. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2747. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2748. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2749. }
  2750. #endif
  2751. }
  2752. #undef CREATE_MM2
  2753. #undef CREATE_MMQ
  2754. #undef CREATE_MM
  2755. } else {
  2756. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2757. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2758. if (device->mul_mat ## ID ## _l[TYPE]) \
  2759. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2760. if (device->mul_mat ## ID ## _m[TYPE]) \
  2761. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2762. if (device->mul_mat ## ID ## _s[TYPE]) \
  2763. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2764. if (device->mul_mat ## ID ## _l[TYPE]) \
  2765. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2766. if (device->mul_mat ## ID ## _m[TYPE]) \
  2767. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2768. if (device->mul_mat ## ID ## _s[TYPE]) \
  2769. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2770. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2771. if (device->mul_mat ## ID ## _l[TYPE]) \
  2772. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC "_l", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2773. if (device->mul_mat ## ID ## _m[TYPE]) \
  2774. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC "_m", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2775. if (device->mul_mat ## ID ## _s[TYPE]) \
  2776. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC "_s", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2777. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2778. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2779. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2780. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2781. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2782. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2783. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2784. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2785. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2786. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2787. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2788. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2789. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2790. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2791. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2792. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2793. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2794. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2795. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2796. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2797. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2798. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2799. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2800. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2801. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2802. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2803. if (device->integer_dot_product) {
  2804. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2805. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2806. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2807. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2808. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2809. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2810. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2811. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2812. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2813. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2814. }
  2815. #endif
  2816. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2817. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2818. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2819. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2820. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2821. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2822. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2823. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2824. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2825. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2826. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2827. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2828. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2829. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2830. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2831. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2832. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2833. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2834. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2835. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2836. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2837. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2838. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2839. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2840. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2841. } else {
  2842. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2843. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2844. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2845. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2846. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2847. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2848. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2849. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2850. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2851. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2852. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2853. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2854. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2855. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2856. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2857. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2858. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2859. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2860. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2861. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2862. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2863. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2864. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2865. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2866. }
  2867. }
  2868. // reusing CREATE_MM from the fp32 path
  2869. if ((device->coopmat2 || device->coopmat_support)
  2870. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2871. && !device->coopmat_bf16_support
  2872. #endif
  2873. ) {
  2874. // use scalar tile sizes
  2875. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2876. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2877. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2878. l_wg_denoms = {128, 128, 1 };
  2879. m_wg_denoms = { 64, 64, 1 };
  2880. s_wg_denoms = { 32, 32, 1 };
  2881. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2882. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2883. }
  2884. #undef CREATE_MM
  2885. // mul mat vec
  2886. // the number of rows computed per shader depends on GPU model and quant
  2887. uint32_t rm_stdq = 1;
  2888. uint32_t rm_kq = 2;
  2889. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2890. if (device->architecture == AMD_GCN) {
  2891. rm_stdq = 2;
  2892. rm_kq = 4;
  2893. }
  2894. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2895. rm_stdq = 2;
  2896. uint32_t rm_iq = 2 * rm_kq;
  2897. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2898. // Ensure a subgroup size >= 16 is available
  2899. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2900. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  2901. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2902. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2903. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2904. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2905. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2906. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2907. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2908. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2909. SHADER_REDUCTION_MODE_SHMEM;
  2910. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2911. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2912. SHADER_REDUCTION_MODE_SHMEM;
  2913. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2914. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2915. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2916. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2917. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2918. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2919. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2920. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2921. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2922. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2923. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2924. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2925. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2926. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2927. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2928. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2929. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2930. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2931. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2932. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2933. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2934. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2935. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2936. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2937. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2938. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2939. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2940. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2941. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2942. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2943. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2944. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2945. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2946. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2947. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2948. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2949. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2950. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2951. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2952. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2953. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2954. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2955. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2956. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2957. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2958. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2959. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2960. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2961. if (device->integer_dot_product) {
  2962. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2963. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2964. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2965. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2966. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2967. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2968. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", 4, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2969. }
  2970. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2971. }
  2972. }
  2973. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", mul_mat_vec_id_f32_f32_len, mul_mat_vec_id_f32_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2974. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", mul_mat_vec_id_f16_f32_len, mul_mat_vec_id_f16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2975. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", mul_mat_vec_id_bf16_f32_len, mul_mat_vec_id_bf16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2976. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", mul_mat_vec_id_q4_0_f32_len, mul_mat_vec_id_q4_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2977. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", mul_mat_vec_id_q4_1_f32_len, mul_mat_vec_id_q4_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2978. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", mul_mat_vec_id_q5_0_f32_len, mul_mat_vec_id_q5_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2979. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", mul_mat_vec_id_q5_1_f32_len, mul_mat_vec_id_q5_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2980. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", mul_mat_vec_id_q8_0_f32_len, mul_mat_vec_id_q8_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  2981. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", mul_mat_vec_id_q2_k_f32_len, mul_mat_vec_id_q2_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2982. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", mul_mat_vec_id_q3_k_f32_len, mul_mat_vec_id_q3_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2983. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", mul_mat_vec_id_q4_k_f32_len, mul_mat_vec_id_q4_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2984. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", mul_mat_vec_id_q5_k_f32_len, mul_mat_vec_id_q5_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2985. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", mul_mat_vec_id_q6_k_f32_len, mul_mat_vec_id_q6_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2986. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", mul_mat_vec_id_iq1_s_f32_len, mul_mat_vec_id_iq1_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2987. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", mul_mat_vec_id_iq1_m_f32_len, mul_mat_vec_id_iq1_m_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2988. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", mul_mat_vec_id_iq2_xxs_f32_len, mul_mat_vec_id_iq2_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2989. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", mul_mat_vec_id_iq2_xs_f32_len, mul_mat_vec_id_iq2_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2990. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", mul_mat_vec_id_iq2_s_f32_len, mul_mat_vec_id_iq2_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2991. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", mul_mat_vec_id_iq3_xxs_f32_len, mul_mat_vec_id_iq3_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2992. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", mul_mat_vec_id_iq3_s_f32_len, mul_mat_vec_id_iq3_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2993. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", mul_mat_vec_id_iq4_xs_f32_len, mul_mat_vec_id_iq4_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2994. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2995. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", mul_mat_vec_id_mxfp4_f32_len, mul_mat_vec_id_mxfp4_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2996. // dequant shaders
  2997. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", dequant_f32_len, dequant_f32_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  2998. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  2999. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3000. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3001. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3002. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3003. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3004. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3005. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3006. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3007. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3008. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3009. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3010. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3011. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3012. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3013. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3014. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3015. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3016. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3017. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3018. // get_rows
  3019. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3020. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3021. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3022. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_0], "get_rows_q4_0", get_rows_q4_0_len, get_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3023. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_1], "get_rows_q4_1", get_rows_q4_1_len, get_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3024. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_0], "get_rows_q5_0", get_rows_q5_0_len, get_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3025. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_1], "get_rows_q5_1", get_rows_q5_1_len, get_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3026. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q8_0], "get_rows_q8_0", get_rows_q8_0_len, get_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3027. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3028. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3029. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3030. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3031. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3032. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3033. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3034. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3035. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3036. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3037. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3038. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3039. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3040. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3041. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3042. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3043. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F16 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3044. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_BF16], "get_rows_bf16_f32", get_rows_bf16_f32_len, get_rows_bf16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3045. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_0], "get_rows_q4_0_f32", get_rows_q4_0_f32_len, get_rows_q4_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3046. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_1], "get_rows_q4_1_f32", get_rows_q4_1_f32_len, get_rows_q4_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3047. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_0], "get_rows_q5_0_f32", get_rows_q5_0_f32_len, get_rows_q5_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3048. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_1], "get_rows_q5_1_f32", get_rows_q5_1_f32_len, get_rows_q5_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3049. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q8_0], "get_rows_q8_0_f32", get_rows_q8_0_f32_len, get_rows_q8_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3050. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3051. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3052. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3053. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3054. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3055. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_S], "get_rows_iq1_s_f32", get_rows_iq1_s_f32_len, get_rows_iq1_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3056. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_M], "get_rows_iq1_m_f32", get_rows_iq1_m_f32_len, get_rows_iq1_m_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3057. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs_f32", get_rows_iq2_xxs_f32_len, get_rows_iq2_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3058. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs_f32", get_rows_iq2_xs_f32_len, get_rows_iq2_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3059. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_S], "get_rows_iq2_s_f32", get_rows_iq2_s_f32_len, get_rows_iq2_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3060. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs_f32", get_rows_iq3_xxs_f32_len, get_rows_iq3_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3061. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_S], "get_rows_iq3_s_f32", get_rows_iq3_s_f32_len, get_rows_iq3_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3062. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs_f32", get_rows_iq4_xs_f32_len, get_rows_iq4_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3063. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3064. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3065. ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1);
  3066. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, 5 * sizeof(uint32_t), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true);
  3067. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3068. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_subgroup_len, quantize_q8_1_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3069. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3070. } else {
  3071. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_len, quantize_q8_1_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3072. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3073. }
  3074. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3075. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3076. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3077. } else {
  3078. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3079. }
  3080. }
  3081. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 4, 13 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  3082. ggml_vk_create_pipeline(device, device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3083. ggml_vk_create_pipeline(device, device->pipeline_group_norm_f32, "group_norm_f32", group_norm_f32_len, group_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3084. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3085. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3086. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3087. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3088. if (device->float_controls_rte_fp16 &&
  3089. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3090. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f32, "rms_norm_mul_rope_f32_f32", rms_norm_mul_rope_f32_f32_len, rms_norm_mul_rope_f32_f32_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3091. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f16, "rms_norm_mul_rope_f32_f16", rms_norm_mul_rope_f32_f16_rte_len, rms_norm_mul_rope_f32_f16_rte_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3092. }
  3093. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3094. ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3095. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f32, "cpy_f32_f32", cpy_f32_f32_len, cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3096. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3097. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f16, "cpy_f16_f16", cpy_f16_f16_len, cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3098. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3099. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3100. ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3101. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3102. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f32, "contig_cpy_f32_f32", contig_cpy_f32_f32_len, contig_cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3103. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3104. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f16, "contig_cpy_f16_f16", contig_cpy_f16_f16_len, contig_cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3105. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3106. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3107. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3108. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3109. if (device->float_controls_rte_fp16) {
  3110. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_rte_len, cpy_f32_q4_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3111. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_rte_len, cpy_f32_q4_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3112. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_rte_len, cpy_f32_q5_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3113. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_rte_len, cpy_f32_q5_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3114. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_rte_len, cpy_f32_q8_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3115. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_rte_len, cpy_f32_iq4_nl_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3116. } else {
  3117. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_len, cpy_f32_q4_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3118. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_len, cpy_f32_q4_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3119. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_len, cpy_f32_q5_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3120. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_len, cpy_f32_q5_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3121. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_len, cpy_f32_q8_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3122. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_len, cpy_f32_iq4_nl_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3123. }
  3124. #define SET_ROWS(itype, rte) \
  3125. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F32], "set_rows_f32" #itype, set_rows_f32 ## itype ## rte ## _len, set_rows_f32 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3126. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F16], "set_rows_f16" #itype, set_rows_f16 ## itype ## rte ## _len, set_rows_f16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3127. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_BF16], "set_rows_bf16" #itype, set_rows_bf16 ## itype ## rte ## _len, set_rows_bf16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3128. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_0], "set_rows_q4_0" #itype, set_rows_q4_0 ## itype ## rte ## _len, set_rows_q4_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3129. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_1], "set_rows_q4_1" #itype, set_rows_q4_1 ## itype ## rte ## _len, set_rows_q4_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3130. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_0], "set_rows_q5_0" #itype, set_rows_q5_0 ## itype ## rte ## _len, set_rows_q5_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3131. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_1], "set_rows_q5_1" #itype, set_rows_q5_1 ## itype ## rte ## _len, set_rows_q5_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3132. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q8_0], "set_rows_q8_0" #itype, set_rows_q8_0 ## itype ## rte ## _len, set_rows_q8_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3133. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_IQ4_NL], "set_rows_iq4_nl" #itype, set_rows_iq4_nl ## itype ## rte ## _len, set_rows_iq4_nl ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  3134. if (device->float_controls_rte_fp16) {
  3135. SET_ROWS(_i32, _rte)
  3136. SET_ROWS(_i64, _rte)
  3137. } else {
  3138. SET_ROWS(_i32, )
  3139. SET_ROWS(_i64, )
  3140. }
  3141. #undef SET_ROWS
  3142. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_0], "cpy_q4_0_f32", cpy_q4_0_f32_len, cpy_q4_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1);
  3143. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_1], "cpy_q4_1_f32", cpy_q4_1_f32_len, cpy_q4_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1);
  3144. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_0], "cpy_q5_0_f32", cpy_q5_0_f32_len, cpy_q5_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1);
  3145. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_1], "cpy_q5_1_f32", cpy_q5_1_f32_len, cpy_q5_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1);
  3146. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q8_0], "cpy_q8_0_f32", cpy_q8_0_f32_len, cpy_q8_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1);
  3147. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_IQ4_NL], "cpy_iq4_nl_f32", cpy_iq4_nl_f32_len, cpy_iq4_nl_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1);
  3148. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3149. std::string s;
  3150. s += std::string(src0_f16 ? "_f16" : "_f32");
  3151. s += std::string(src1_f16 ? "_f16" : "_f32");
  3152. s += std::string(dst_f16 ? "_f16" : "_f32");
  3153. return s;
  3154. };
  3155. bool rte = device->float_controls_rte_fp16;
  3156. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3157. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3158. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3159. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3160. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3161. CREATE_BINARY(add, , {0}, 4)
  3162. CREATE_BINARY(add, _norepeat, {1}, 4)
  3163. CREATE_BINARY(sub, , {0}, 3)
  3164. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3165. CREATE_BINARY(mul, , {0}, 3)
  3166. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3167. CREATE_BINARY(div, , {0}, 3)
  3168. CREATE_BINARY(div, _norepeat, {1}, 3)
  3169. CREATE_BINARY(add_rms, , {0}, 4)
  3170. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3171. #undef CREATE_BINARY
  3172. if (device->multi_add) {
  3173. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3174. ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3175. ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3176. }
  3177. }
  3178. ggml_vk_create_pipeline(device, device->pipeline_add_id_f32, "add_id_f32", add_id_f32_len, add_id_f32_data, "main", 4, sizeof(vk_op_add_id_push_constants), {1, 1, 1}, {}, 1);
  3179. ggml_vk_create_pipeline(device, device->pipeline_acc_f32, "acc_f32", acc_f32_len, acc_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3180. ggml_vk_create_pipeline(device, device->pipeline_concat_f32, "concat_f32", concat_f32_len, concat_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3181. ggml_vk_create_pipeline(device, device->pipeline_concat_f16, "concat_f16", concat_f16_len, concat_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3182. ggml_vk_create_pipeline(device, device->pipeline_concat_i32, "concat_i32", concat_i32_len, concat_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3183. ggml_vk_create_pipeline(device, device->pipeline_upscale_nearest_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_NEAREST}, 1);
  3184. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR}, 1);
  3185. ggml_vk_create_pipeline(device, device->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3186. ggml_vk_create_pipeline(device, device->pipeline_sqr_f32, "sqr_f32", sqr_f32_len, sqr_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3187. ggml_vk_create_pipeline(device, device->pipeline_sqrt_f32, "sqrt_f32", sqrt_f32_len, sqrt_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3188. ggml_vk_create_pipeline(device, device->pipeline_sin_f32, "sin_f32", sin_f32_len, sin_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3189. ggml_vk_create_pipeline(device, device->pipeline_cos_f32, "cos_f32", cos_f32_len, cos_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3190. ggml_vk_create_pipeline(device, device->pipeline_clamp_f32, "clamp_f32", clamp_f32_len, clamp_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3191. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
  3192. ggml_vk_create_pipeline(device, device->pipeline_roll_f32, "roll_f32", roll_f32_len, roll_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3193. ggml_vk_create_pipeline(device, device->pipeline_repeat_f32, "repeat_f32", repeat_f32_len, repeat_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3194. ggml_vk_create_pipeline(device, device->pipeline_repeat_back_f32, "repeat_back_f32", repeat_back_f32_len, repeat_back_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3195. #define CREATE_UNARY(name) \
  3196. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3197. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3198. CREATE_UNARY(gelu)
  3199. CREATE_UNARY(gelu_erf)
  3200. CREATE_UNARY(gelu_quick)
  3201. CREATE_UNARY(silu)
  3202. CREATE_UNARY(relu)
  3203. CREATE_UNARY(tanh)
  3204. CREATE_UNARY(sigmoid)
  3205. CREATE_UNARY(hardsigmoid)
  3206. CREATE_UNARY(hardswish)
  3207. #undef CREATE_UNARY
  3208. #define CREATE_UNARY_RTE(name) \
  3209. if (device->float_controls_rte_fp16) { \
  3210. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3211. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3212. } else { \
  3213. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3214. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3215. }
  3216. CREATE_UNARY_RTE(exp)
  3217. #undef CREATE_UNARY_RTE
  3218. #define CREATE_GLU(name) \
  3219. if (device->float_controls_rte_fp16) { \
  3220. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3221. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3222. } else { \
  3223. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3224. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3225. }
  3226. CREATE_GLU(geglu)
  3227. CREATE_GLU(reglu)
  3228. CREATE_GLU(swiglu)
  3229. CREATE_GLU(swiglu_oai)
  3230. CREATE_GLU(geglu_erf)
  3231. CREATE_GLU(geglu_quick)
  3232. #undef CREATE_GLU
  3233. ggml_vk_create_pipeline(device, device->pipeline_leaky_relu_f32, "leaky_relu_f32", leaky_relu_f32_len, leaky_relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3234. ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3235. ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {1, 512, 1}, {}, 1, true);
  3236. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3237. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3238. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3239. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3240. ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
  3241. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3242. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3243. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3244. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3245. if (device->float_controls_rte_fp16) {
  3246. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3247. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3248. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_rte_len, rope_multi_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3249. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_rte_len, rope_vision_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3250. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_rte_len, rope_norm_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3251. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_rte_len, rope_neox_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3252. } else {
  3253. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3254. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3255. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3256. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3257. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_len, rope_norm_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3258. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_len, rope_neox_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3259. }
  3260. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3261. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1u<<i, 1, 1}, {1u<<i, i}, 1, true);
  3262. }
  3263. ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3264. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3265. ggml_vk_create_pipeline(device, device->pipeline_count_equal_i32, "count_equal_i32", count_equal_i32_len, count_equal_i32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, { device->subgroup_size }, 1);
  3266. #define IM2COL(bda) \
  3267. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3268. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3269. if (device->float_controls_rte_fp16) { \
  3270. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte ## bda ## _len, im2col_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3271. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte ## bda ## _len, im2col_3d_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3272. } else { \
  3273. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3274. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3275. }
  3276. if (device->shader_int64 && device->buffer_device_address) {
  3277. IM2COL(_bda)
  3278. } else {
  3279. IM2COL()
  3280. }
  3281. ggml_vk_create_pipeline(device, device->pipeline_timestep_embedding_f32, "timestep_embedding_f32", timestep_embedding_f32_len, timestep_embedding_f32_data, "main", 2, sizeof(vk_op_timestep_embedding_push_constants), {256, 1, 1}, {}, 1);
  3282. ggml_vk_create_pipeline(device, device->pipeline_conv_transpose_1d_f32, "conv_transpose_1d_f32", conv_transpose_1d_f32_len, conv_transpose_1d_f32_data, "main", 3, sizeof(vk_op_conv_transpose_1d_push_constants), {1, 1, 1}, {}, 1);
  3283. ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {512, 1, 1}, {}, 1);
  3284. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv6_f32, "rwkv_wkv6_f32", rwkv_wkv6_f32_len, rwkv_wkv6_f32_data, "main", 7, sizeof(vk_op_rwkv_wkv6_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3285. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv7_f32, "rwkv_wkv7_f32", rwkv_wkv7_f32_len, rwkv_wkv7_f32_data, "main", 8, sizeof(vk_op_rwkv_wkv7_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3286. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3287. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3288. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3289. } else {
  3290. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3291. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3292. }
  3293. ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 3, sizeof(vk_op_ssm_conv_push_constants), {32, 1, 1}, {32}, 1);
  3294. ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3295. ggml_vk_create_pipeline(device, device->pipeline_opt_step_sgd_f32, "opt_step_sgd_f32", opt_step_sgd_f32_len, opt_step_sgd_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3296. // conv2d, conv_transpose_2d
  3297. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3298. uint32_t conv2d_WG_SIZE = 256;
  3299. uint32_t conv2d_BS_K = 128;
  3300. uint32_t conv2d_BS_CRS = 16;
  3301. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3302. uint32_t conv2d_BS_NPQ = 128;
  3303. uint32_t conv2d_TS_K = 8;
  3304. uint32_t conv2d_SHMEM_PAD = 4;
  3305. bool conv2d_UNROLL = true;
  3306. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3307. if (device->coopmat2) {
  3308. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3309. }
  3310. #endif
  3311. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3312. conv2d_SHMEM_PAD = 0;
  3313. conv2d_UNROLL = false;
  3314. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3315. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3316. }
  3317. switch (s) {
  3318. default:
  3319. case CONV_SHAPE_128x128:
  3320. conv2d_BS_K = 128;
  3321. conv2d_BS_NPQ = 128;
  3322. conv2d_BS_CRS = 16;
  3323. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3324. conv2d_UNROLL = false;
  3325. }
  3326. break;
  3327. case CONV_SHAPE_64x32:
  3328. conv2d_BS_K = 64;
  3329. conv2d_BS_NPQ = 32;
  3330. conv2d_BS_CRS = 32;
  3331. conv2d_TS_K = 4;
  3332. break;
  3333. case CONV_SHAPE_32x256:
  3334. conv2d_BS_K = 32;
  3335. conv2d_BS_NPQ = 256;
  3336. conv2d_BS_CRS = 16;
  3337. break;
  3338. }
  3339. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3340. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3341. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3342. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3343. device->architecture == vk_device_architecture::AMD_GCN;
  3344. if (device->subgroup_shuffle &&
  3345. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3346. allow_collectives_nv &&
  3347. allow_collectives_amd) {
  3348. use_collectives = 1;
  3349. conv2d_BS_CRS = std::min(
  3350. device->subgroup_size,
  3351. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3352. }
  3353. uint32_t conv2d_shmem_req =
  3354. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3355. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3356. conv2d_BS_CRS = 8;
  3357. if (use_collectives) {
  3358. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3359. }
  3360. }
  3361. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3362. std::vector<uint32_t> spec_constants = { conv2d_WG_SIZE, conv2d_BS_K, conv2d_BS_CRS, conv2d_BS_NPQ, conv2d_TS_K, use_collectives, conv2d_SHMEM_PAD };
  3363. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3364. ggml_vk_create_pipeline( \
  3365. device, device->pipeline_##name##type_suffix[s], #name #type_suffix, \
  3366. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3367. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  3368. #define CREATE_CONVS(spv_suffix) \
  3369. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3370. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3371. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3372. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3373. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3374. }
  3375. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3376. if (device->coopmat2) {
  3377. CREATE_CONVS(_cm2)
  3378. } else
  3379. #endif
  3380. if (conv2d_UNROLL) {
  3381. CREATE_CONVS(_unroll)
  3382. } else {
  3383. CREATE_CONVS( )
  3384. }
  3385. #undef CREATE_CONV
  3386. #undef CREATE_CONVS
  3387. }
  3388. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f32, "conv2d_dw_whcn_f32", conv2d_dw_whcn_f32_len, conv2d_dw_whcn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3389. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f32, "conv2d_dw_cwhn_f32", conv2d_dw_cwhn_f32_len, conv2d_dw_cwhn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3390. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3391. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3392. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3393. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0}, 1, true, true);
  3394. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0}, 1, true, true);
  3395. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1}, 1, true, true);
  3396. }
  3397. for (auto &c : compiles) {
  3398. c.wait();
  3399. }
  3400. }
  3401. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3402. static vk_device ggml_vk_get_device(size_t idx) {
  3403. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3404. if (vk_instance.devices[idx] == nullptr) {
  3405. VK_LOG_DEBUG("Initializing new vk_device");
  3406. vk_device device = std::make_shared<vk_device_struct>();
  3407. vk_instance.devices[idx] = device;
  3408. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3409. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3410. #endif
  3411. if (vk_perf_logger_enabled) {
  3412. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3413. }
  3414. size_t dev_num = vk_instance.device_indices[idx];
  3415. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3416. if (dev_num >= physical_devices.size()) {
  3417. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3418. throw std::runtime_error("Device not found");
  3419. }
  3420. device->physical_device = physical_devices[dev_num];
  3421. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3422. device->architecture = get_device_architecture(device->physical_device);
  3423. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3424. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3425. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3426. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3427. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3428. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3429. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3430. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3431. bool fp16_storage = false;
  3432. bool fp16_compute = false;
  3433. bool maintenance4_support = false;
  3434. bool sm_builtins = false;
  3435. bool amd_shader_core_properties2 = false;
  3436. bool pipeline_robustness = false;
  3437. bool coopmat2_support = false;
  3438. bool pipeline_executable_properties_support = false;
  3439. device->coopmat_support = false;
  3440. device->integer_dot_product = false;
  3441. bool bfloat16_support = false;
  3442. for (const auto& properties : ext_props) {
  3443. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3444. maintenance4_support = true;
  3445. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3446. fp16_storage = true;
  3447. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3448. fp16_compute = true;
  3449. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3450. sm_builtins = true;
  3451. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3452. amd_shader_core_properties2 = true;
  3453. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3454. pipeline_robustness = true;
  3455. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3456. device->subgroup_size_control = true;
  3457. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3458. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3459. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3460. device->coopmat_support = true;
  3461. device->coopmat_m = 0;
  3462. device->coopmat_n = 0;
  3463. device->coopmat_k = 0;
  3464. #endif
  3465. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3466. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3467. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3468. coopmat2_support = true;
  3469. #endif
  3470. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3471. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3472. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3473. device->integer_dot_product = true;
  3474. #endif
  3475. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3476. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3477. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3478. bfloat16_support = true;
  3479. #endif
  3480. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3481. pipeline_executable_properties_support = true;
  3482. }
  3483. }
  3484. vk::PhysicalDeviceProperties2 props2;
  3485. vk::PhysicalDeviceMaintenance3Properties props3;
  3486. vk::PhysicalDeviceMaintenance4Properties props4;
  3487. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3488. vk::PhysicalDeviceDriverProperties driver_props;
  3489. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3490. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3491. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3492. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3493. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3494. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3495. props2.pNext = &props3;
  3496. props3.pNext = &subgroup_props;
  3497. subgroup_props.pNext = &driver_props;
  3498. driver_props.pNext = &vk11_props;
  3499. vk11_props.pNext = &vk12_props;
  3500. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3501. if (maintenance4_support) {
  3502. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3503. last_struct = (VkBaseOutStructure *)&props4;
  3504. }
  3505. if (sm_builtins) {
  3506. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3507. last_struct = (VkBaseOutStructure *)&sm_props;
  3508. }
  3509. if (amd_shader_core_properties2) {
  3510. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3511. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3512. }
  3513. if (device->subgroup_size_control) {
  3514. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3515. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3516. }
  3517. #if defined(VK_NV_cooperative_matrix2)
  3518. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3519. if (coopmat2_support) {
  3520. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3521. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3522. }
  3523. #endif
  3524. if (device->integer_dot_product) {
  3525. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3526. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3527. }
  3528. device->physical_device.getProperties2(&props2);
  3529. device->properties = props2.properties;
  3530. device->vendor_id = device->properties.vendorID;
  3531. device->driver_id = driver_props.driverID;
  3532. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3533. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3534. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3535. } else if (maintenance4_support) {
  3536. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3537. } else {
  3538. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3539. }
  3540. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3541. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3542. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3543. } else if (maintenance4_support) {
  3544. device->max_buffer_size = props4.maxBufferSize;
  3545. } else {
  3546. device->max_buffer_size = device->max_memory_allocation_size;
  3547. }
  3548. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3549. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3550. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3551. } else {
  3552. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3553. device->suballocation_block_size = 1024*1024*1024;
  3554. }
  3555. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3556. device->subgroup_size = subgroup_props.subgroupSize;
  3557. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3558. if (sm_builtins) {
  3559. device->shader_core_count = sm_props.shaderSMCount;
  3560. } else if (amd_shader_core_properties2) {
  3561. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3562. } else {
  3563. device->shader_core_count = 0;
  3564. }
  3565. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3566. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3567. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3568. #ifdef __APPLE__
  3569. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3570. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3571. device->subgroup_arithmetic = false;
  3572. }
  3573. #endif
  3574. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3575. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3576. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3577. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3578. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3579. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3580. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3581. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3582. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3583. device->coopmat_support = false;
  3584. }
  3585. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3586. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3587. // Try to find a non-graphics compute queue and transfer-focused queues
  3588. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3589. const uint32_t transfer_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eTransfer, vk::QueueFlagBits::eCompute | vk::QueueFlagBits::eGraphics, compute_queue_family_index, 1);
  3590. const float priorities[] = { 1.0f, 1.0f };
  3591. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3592. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3593. if (compute_queue_family_index != transfer_queue_family_index) {
  3594. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3595. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3596. } else if(!device->single_queue) {
  3597. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3598. } else {
  3599. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3600. }
  3601. vk::DeviceCreateInfo device_create_info;
  3602. std::vector<const char *> device_extensions;
  3603. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3604. VkPhysicalDeviceFeatures2 device_features2;
  3605. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3606. device_features2.pNext = nullptr;
  3607. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3608. VkPhysicalDeviceVulkan11Features vk11_features;
  3609. vk11_features.pNext = nullptr;
  3610. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3611. device_features2.pNext = &vk11_features;
  3612. VkPhysicalDeviceVulkan12Features vk12_features;
  3613. vk12_features.pNext = nullptr;
  3614. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3615. vk11_features.pNext = &vk12_features;
  3616. last_struct = (VkBaseOutStructure *)&vk12_features;
  3617. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3618. pl_robustness_features.pNext = nullptr;
  3619. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3620. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3621. if (pipeline_robustness) {
  3622. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3623. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3624. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3625. }
  3626. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3627. subgroup_size_control_features.pNext = nullptr;
  3628. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3629. subgroup_size_control_features.computeFullSubgroups = false;
  3630. subgroup_size_control_features.subgroupSizeControl = false;
  3631. if (device->subgroup_size_control) {
  3632. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3633. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3634. }
  3635. #if defined(VK_KHR_cooperative_matrix)
  3636. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3637. coopmat_features.pNext = nullptr;
  3638. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3639. coopmat_features.cooperativeMatrix = VK_FALSE;
  3640. if (device->coopmat_support) {
  3641. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3642. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3643. }
  3644. #endif
  3645. #if defined(VK_NV_cooperative_matrix2)
  3646. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3647. coopmat2_features.pNext = nullptr;
  3648. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3649. if (coopmat2_support) {
  3650. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3651. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3652. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3653. }
  3654. #endif
  3655. #if defined(VK_KHR_shader_bfloat16)
  3656. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3657. bfloat16_features.pNext = nullptr;
  3658. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3659. if (bfloat16_support) {
  3660. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3661. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3662. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3663. }
  3664. #endif
  3665. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3666. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3667. if (maintenance4_support) {
  3668. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3669. last_struct = (VkBaseOutStructure *)&maint4_features;
  3670. device_extensions.push_back("VK_KHR_maintenance4");
  3671. }
  3672. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3673. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3674. if (device->integer_dot_product) {
  3675. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3676. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3677. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3678. }
  3679. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3680. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3681. if (pipeline_executable_properties_support) {
  3682. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3683. last_struct = (VkBaseOutStructure *)&pep_features;
  3684. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3685. }
  3686. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3687. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3688. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3689. #if defined(VK_KHR_shader_bfloat16)
  3690. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3691. #else
  3692. device->bf16 = false;
  3693. #endif
  3694. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3695. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3696. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3697. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3698. device->shader_int64 = device_features2.features.shaderInt64;
  3699. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3700. if (device->subgroup_size_control) {
  3701. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3702. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3703. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3704. }
  3705. device->subgroup_size_control = device->subgroup_size_control &&
  3706. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3707. subgroup_size_control_features.subgroupSizeControl;
  3708. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3709. #if defined(VK_KHR_cooperative_matrix)
  3710. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3711. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3712. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3713. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3714. device->subgroup_max_size >= 32;
  3715. #endif
  3716. if (coopmat2_support) {
  3717. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3718. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3719. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3720. coopmat2_features.cooperativeMatrixReductions &&
  3721. coopmat2_features.cooperativeMatrixConversions &&
  3722. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3723. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3724. coopmat2_features.cooperativeMatrixBlockLoads &&
  3725. vk12_features.bufferDeviceAddress) {
  3726. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3727. uint32_t count = 0;
  3728. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3729. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3730. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3731. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3732. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3733. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3734. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3735. flexible_dimensions.resize(count, empty_prop);
  3736. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3737. bool found_fp16_128 = false,
  3738. found_fp16_256 = false,
  3739. found_fp32_128 = false,
  3740. found_fp32_256 = false;
  3741. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3742. // with 32x16x16 and 256 with 32x32x16.
  3743. for (auto &prop : flexible_dimensions) {
  3744. if (prop.saturatingAccumulation == VK_FALSE &&
  3745. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3746. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3747. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3748. if (prop.workgroupInvocations == 128 &&
  3749. prop.MGranularity <= 32 &&
  3750. prop.NGranularity <= 16 &&
  3751. prop.KGranularity <= 16) {
  3752. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3753. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3754. found_fp16_128 = true;
  3755. }
  3756. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3757. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3758. found_fp32_128 = true;
  3759. }
  3760. }
  3761. if (prop.workgroupInvocations == 256 &&
  3762. prop.MGranularity <= 32 &&
  3763. prop.NGranularity <= 32 &&
  3764. prop.KGranularity <= 16) {
  3765. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3766. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3767. found_fp16_256 = true;
  3768. }
  3769. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3770. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3771. found_fp32_256 = true;
  3772. }
  3773. }
  3774. }
  3775. }
  3776. if (found_fp16_128 && found_fp16_256 &&
  3777. found_fp32_128 && found_fp32_256 &&
  3778. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3779. device->coopmat2 = true;
  3780. }
  3781. }
  3782. #endif
  3783. }
  3784. if (!vk11_features.storageBuffer16BitAccess) {
  3785. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3786. throw std::runtime_error("Unsupported device");
  3787. }
  3788. device_extensions.push_back("VK_KHR_16bit_storage");
  3789. #ifdef GGML_VULKAN_VALIDATE
  3790. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3791. #endif
  3792. if (device->fp16) {
  3793. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3794. }
  3795. #if defined(VK_KHR_cooperative_matrix)
  3796. if (device->coopmat_support) {
  3797. // Query supported shapes
  3798. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3799. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3800. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3801. uint32_t cm_props_num;
  3802. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3803. cm_props.resize(cm_props_num);
  3804. for (auto& prop : cm_props) {
  3805. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3806. }
  3807. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3808. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3809. for (auto& prop : cm_props) {
  3810. VK_LOG_DEBUG("ggml_vulkan: M: " << prop.MSize << " N: " << prop.NSize << " K: " << prop.KSize << " A: " << vk::to_string((vk::ComponentTypeKHR)prop.AType) << " B: " << vk::to_string((vk::ComponentTypeKHR)prop.BType) << " C: " << vk::to_string((vk::ComponentTypeKHR)prop.CType) << " Result: " << vk::to_string((vk::ComponentTypeKHR)prop.ResultType) << " saturatingAccumulation: " << prop.saturatingAccumulation << " scope: " << vk::to_string((vk::ScopeKHR)prop.scope));
  3811. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3812. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3813. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3814. ) {
  3815. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3816. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3817. // coopmat sizes not set yet
  3818. if (device->coopmat_m == 0) {
  3819. device->coopmat_acc_f32_support = true;
  3820. device->coopmat_m = prop.MSize;
  3821. device->coopmat_n = prop.NSize;
  3822. device->coopmat_k = prop.KSize;
  3823. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3824. // Only enable if shape is identical
  3825. device->coopmat_acc_f32_support = true;
  3826. }
  3827. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3828. device->coopmat_support_16x16x16_f32acc = true;
  3829. }
  3830. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3831. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3832. // coopmat sizes not set yet
  3833. if (device->coopmat_m == 0) {
  3834. device->coopmat_acc_f16_support = true;
  3835. device->coopmat_m = prop.MSize;
  3836. device->coopmat_n = prop.NSize;
  3837. device->coopmat_k = prop.KSize;
  3838. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3839. // Only enable if shape is identical
  3840. device->coopmat_acc_f16_support = true;
  3841. }
  3842. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3843. device->coopmat_support_16x16x16_f16acc = true;
  3844. }
  3845. }
  3846. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3847. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3848. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3849. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3850. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3851. device->coopmat_int_m == 0
  3852. ) {
  3853. device->coopmat_int_support = true;
  3854. device->coopmat_int_m = prop.MSize;
  3855. device->coopmat_int_n = prop.NSize;
  3856. device->coopmat_int_k = prop.KSize;
  3857. }
  3858. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3859. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3860. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3861. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3862. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3863. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3864. ) {
  3865. // coopmat sizes not set yet
  3866. if (device->coopmat_m == 0) {
  3867. device->coopmat_bf16_support = true;
  3868. device->coopmat_m = prop.MSize;
  3869. device->coopmat_n = prop.NSize;
  3870. device->coopmat_k = prop.KSize;
  3871. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3872. // Only enable if shape is identical
  3873. device->coopmat_bf16_support = true;
  3874. }
  3875. }
  3876. #endif
  3877. }
  3878. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3879. // No suitable matmul mode found
  3880. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3881. device->coopmat_support = false;
  3882. }
  3883. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3884. device->coopmat_bf16_support = false;
  3885. }
  3886. }
  3887. if (device->coopmat_support) {
  3888. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3889. }
  3890. #if defined(VK_KHR_shader_bfloat16)
  3891. if (device->coopmat_bf16_support) {
  3892. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3893. }
  3894. #endif
  3895. #endif
  3896. device->name = GGML_VK_NAME + std::to_string(idx);
  3897. device_create_info = {
  3898. vk::DeviceCreateFlags(),
  3899. device_queue_create_infos,
  3900. {},
  3901. device_extensions
  3902. };
  3903. device_create_info.setPNext(&device_features2);
  3904. device->device = device->physical_device.createDevice(device_create_info);
  3905. // Queues
  3906. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3907. // Shaders
  3908. // Disable matmul tile sizes early if performance low or not supported
  3909. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3910. switch (device->vendor_id) {
  3911. #ifndef GGML_VULKAN_RUN_TESTS
  3912. case VK_VENDOR_ID_AMD:
  3913. case VK_VENDOR_ID_INTEL:
  3914. device->mul_mat_l[i] = false;
  3915. device->mul_mat_m[i] = true;
  3916. device->mul_mat_s[i] = true;
  3917. device->mul_mat_id_l[i] = false;
  3918. device->mul_mat_id_m[i] = true;
  3919. device->mul_mat_id_s[i] = true;
  3920. break;
  3921. case VK_VENDOR_ID_APPLE:
  3922. device->mul_mat_l[i] = false;
  3923. device->mul_mat_m[i] = true;
  3924. device->mul_mat_s[i] = false;
  3925. device->mul_mat_id_l[i] = false;
  3926. device->mul_mat_id_m[i] = true;
  3927. device->mul_mat_id_s[i] = false;
  3928. break;
  3929. #endif
  3930. default:
  3931. device->mul_mat_l[i] = true;
  3932. device->mul_mat_m[i] = true;
  3933. device->mul_mat_s[i] = true;
  3934. device->mul_mat_id_l[i] = true;
  3935. device->mul_mat_id_m[i] = true;
  3936. device->mul_mat_id_s[i] = true;
  3937. break;
  3938. }
  3939. }
  3940. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3941. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3942. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3943. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3944. dsl_binding_flags.push_back({});
  3945. }
  3946. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3947. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3948. {},
  3949. dsl_binding);
  3950. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3951. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3952. ggml_vk_load_shaders(device);
  3953. if (!device->single_queue) {
  3954. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3955. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3956. } else {
  3957. // TODO: Use pointer or reference to avoid copy
  3958. device->transfer_queue.copyFrom(device->compute_queue);
  3959. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3960. }
  3961. device->buffer_type = {
  3962. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3963. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3964. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3965. };
  3966. device->fence = device->device.createFence({});
  3967. device->idx = idx;
  3968. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3969. device->add_rms_fusion = !device->disable_fusion &&
  3970. device->subgroup_arithmetic &&
  3971. device->vendor_id != VK_VENDOR_ID_INTEL;
  3972. device->partials_binding_alignment =
  3973. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3974. device->mmvq_mode = 0;
  3975. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3976. device->mmvq_mode = -1;
  3977. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3978. device->mmvq_mode = 1;
  3979. }
  3980. return device;
  3981. }
  3982. return vk_instance.devices[idx];
  3983. }
  3984. static void ggml_vk_print_gpu_info(size_t idx) {
  3985. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3986. size_t dev_num = vk_instance.device_indices[idx];
  3987. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3988. GGML_ASSERT(vk_instance_initialized);
  3989. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3990. if (dev_num >= devices.size()) {
  3991. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3992. throw std::runtime_error("Device not found");
  3993. }
  3994. vk::PhysicalDevice physical_device = devices[dev_num];
  3995. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3996. bool fp16_storage = false;
  3997. bool fp16_compute = false;
  3998. bool coopmat_support = false;
  3999. bool coopmat2_support = false;
  4000. bool integer_dot_product = false;
  4001. bool bfloat16_support = false;
  4002. for (auto properties : ext_props) {
  4003. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4004. fp16_storage = true;
  4005. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4006. fp16_compute = true;
  4007. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4008. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4009. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4010. coopmat_support = true;
  4011. #endif
  4012. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4013. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4014. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4015. coopmat2_support = true;
  4016. #endif
  4017. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4018. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4019. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4020. integer_dot_product = true;
  4021. #endif
  4022. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4023. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4024. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4025. bfloat16_support = true;
  4026. #endif
  4027. }
  4028. }
  4029. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4030. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4031. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4032. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4033. vk::PhysicalDeviceProperties2 props2;
  4034. vk::PhysicalDeviceMaintenance3Properties props3;
  4035. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4036. vk::PhysicalDeviceDriverProperties driver_props;
  4037. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4038. props2.pNext = &props3;
  4039. props3.pNext = &subgroup_props;
  4040. subgroup_props.pNext = &driver_props;
  4041. // Pointer to the last chain element
  4042. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4043. if (integer_dot_product) {
  4044. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4045. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4046. }
  4047. physical_device.getProperties2(&props2);
  4048. VkPhysicalDeviceFeatures2 device_features2;
  4049. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4050. device_features2.pNext = nullptr;
  4051. VkPhysicalDeviceVulkan11Features vk11_features;
  4052. vk11_features.pNext = nullptr;
  4053. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4054. device_features2.pNext = &vk11_features;
  4055. VkPhysicalDeviceVulkan12Features vk12_features;
  4056. vk12_features.pNext = nullptr;
  4057. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4058. vk11_features.pNext = &vk12_features;
  4059. // Pointer to the last chain element
  4060. last_struct = (VkBaseOutStructure *)&vk12_features;
  4061. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4062. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4063. coopmat_features.pNext = nullptr;
  4064. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4065. coopmat_features.cooperativeMatrix = VK_FALSE;
  4066. if (coopmat_support) {
  4067. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4068. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4069. }
  4070. #endif
  4071. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4072. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4073. if (integer_dot_product) {
  4074. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4075. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4076. }
  4077. #if defined(VK_KHR_shader_bfloat16)
  4078. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4079. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4080. if (bfloat16_support) {
  4081. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4082. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4083. }
  4084. #endif
  4085. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4086. fp16 = fp16 && vk12_features.shaderFloat16;
  4087. #if defined(VK_KHR_shader_bfloat16)
  4088. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4089. #else
  4090. bool bf16 = false;
  4091. #endif
  4092. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4093. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4094. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4095. integer_dot_product = integer_dot_product
  4096. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4097. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4098. coopmat_support = coopmat_support
  4099. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4100. && coopmat_features.cooperativeMatrix
  4101. #endif
  4102. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4103. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4104. std::string device_name = props2.properties.deviceName.data();
  4105. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | bf16: %d | warp size: %zu | shared memory: %d | int dot: %d | matrix cores: %s\n",
  4106. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4107. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4108. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4109. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4110. }
  4111. }
  4112. static bool ggml_vk_instance_validation_ext_available();
  4113. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4114. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4115. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4116. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4117. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4118. return ggml_vk_default_dispatcher_instance;
  4119. }
  4120. static void ggml_vk_instance_init() {
  4121. if (vk_instance_initialized) {
  4122. return;
  4123. }
  4124. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4125. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4126. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4127. uint32_t api_version = vk::enumerateInstanceVersion();
  4128. if (api_version < VK_API_VERSION_1_2) {
  4129. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4130. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4131. }
  4132. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4133. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4134. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4135. #ifdef __APPLE__
  4136. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4137. #endif
  4138. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4139. std::vector<const char*> layers;
  4140. if (validation_ext) {
  4141. layers.push_back("VK_LAYER_KHRONOS_validation");
  4142. }
  4143. std::vector<const char*> extensions;
  4144. if (validation_ext) {
  4145. extensions.push_back("VK_EXT_validation_features");
  4146. }
  4147. #ifdef __APPLE__
  4148. if (portability_enumeration_ext) {
  4149. extensions.push_back("VK_KHR_portability_enumeration");
  4150. }
  4151. #endif
  4152. if (debug_utils_ext) {
  4153. extensions.push_back("VK_EXT_debug_utils");
  4154. }
  4155. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4156. #ifdef __APPLE__
  4157. if (portability_enumeration_ext) {
  4158. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4159. }
  4160. #endif
  4161. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4162. vk::ValidationFeaturesEXT validation_features;
  4163. if (validation_ext) {
  4164. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4165. validation_features = {
  4166. features_enable,
  4167. {},
  4168. };
  4169. validation_features.setPNext(nullptr);
  4170. instance_create_info.setPNext(&validation_features);
  4171. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4172. }
  4173. vk_instance.instance = vk::createInstance(instance_create_info);
  4174. vk_instance_initialized = true;
  4175. if (debug_utils_ext) {
  4176. vk_instance.debug_utils_support = true;
  4177. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4178. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4179. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4180. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4181. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4182. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4183. }
  4184. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4185. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4186. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4187. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4188. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4189. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4190. if (devices_env != nullptr) {
  4191. size_t num_available_devices = devices.size();
  4192. std::string devices(devices_env);
  4193. std::replace(devices.begin(), devices.end(), ',', ' ');
  4194. std::stringstream ss(devices);
  4195. size_t tmp;
  4196. while (ss >> tmp) {
  4197. if(tmp >= num_available_devices) {
  4198. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4199. throw std::runtime_error("Invalid Vulkan device index");
  4200. }
  4201. vk_instance.device_indices.push_back(tmp);
  4202. }
  4203. } else {
  4204. // If no vulkan devices are found, return early
  4205. if (devices.empty()) {
  4206. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4207. return;
  4208. }
  4209. // Default to using all dedicated GPUs
  4210. for (size_t i = 0; i < devices.size(); i++) {
  4211. vk::PhysicalDeviceProperties2 new_props;
  4212. vk::PhysicalDeviceDriverProperties new_driver;
  4213. vk::PhysicalDeviceIDProperties new_id;
  4214. new_props.pNext = &new_driver;
  4215. new_driver.pNext = &new_id;
  4216. devices[i].getProperties2(&new_props);
  4217. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4218. // Check if there are two physical devices corresponding to the same GPU
  4219. auto old_device = std::find_if(
  4220. vk_instance.device_indices.begin(),
  4221. vk_instance.device_indices.end(),
  4222. [&devices, &new_id](const size_t k){
  4223. vk::PhysicalDeviceProperties2 old_props;
  4224. vk::PhysicalDeviceIDProperties old_id;
  4225. old_props.pNext = &old_id;
  4226. devices[k].getProperties2(&old_props);
  4227. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4228. equals = equals || (
  4229. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4230. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4231. );
  4232. return equals;
  4233. }
  4234. );
  4235. if (old_device == vk_instance.device_indices.end()) {
  4236. vk_instance.device_indices.push_back(i);
  4237. } else {
  4238. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4239. // This can cause error when splitting layers aross the devices, need to keep only 1
  4240. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4241. vk::PhysicalDeviceProperties2 old_props;
  4242. vk::PhysicalDeviceDriverProperties old_driver;
  4243. old_props.pNext = &old_driver;
  4244. devices[*old_device].getProperties2(&old_props);
  4245. std::map<vk::DriverId, int> driver_priorities {};
  4246. int old_priority = std::numeric_limits<int>::max();
  4247. int new_priority = std::numeric_limits<int>::max();
  4248. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4249. // Smaller number -> higher priority
  4250. switch (old_props.properties.vendorID) {
  4251. case VK_VENDOR_ID_AMD:
  4252. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4253. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4254. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4255. break;
  4256. case VK_VENDOR_ID_INTEL:
  4257. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4258. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4259. break;
  4260. case VK_VENDOR_ID_NVIDIA:
  4261. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4262. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4263. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4264. #endif
  4265. break;
  4266. }
  4267. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4268. if (driver_priorities.count(old_driver.driverID)) {
  4269. old_priority = driver_priorities[old_driver.driverID];
  4270. }
  4271. if (driver_priorities.count(new_driver.driverID)) {
  4272. new_priority = driver_priorities[new_driver.driverID];
  4273. }
  4274. if (new_priority < old_priority) {
  4275. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4276. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4277. vk_instance.device_indices.push_back(i);
  4278. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4279. }
  4280. else {
  4281. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4282. }
  4283. }
  4284. }
  4285. }
  4286. // If no GPUs found, fall back to the first non-CPU device.
  4287. // If only CPU devices are available, return without devices.
  4288. if (vk_instance.device_indices.empty()) {
  4289. for (size_t i = 0; i < devices.size(); i++) {
  4290. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4291. vk_instance.device_indices.push_back(i);
  4292. break;
  4293. }
  4294. }
  4295. }
  4296. if (vk_instance.device_indices.empty()) {
  4297. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4298. return;
  4299. }
  4300. }
  4301. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4302. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4303. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4304. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4305. bool membudget_supported = false;
  4306. for (const auto & ext : extensionprops) {
  4307. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4308. membudget_supported = true;
  4309. break;
  4310. }
  4311. }
  4312. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4313. ggml_vk_print_gpu_info(i);
  4314. }
  4315. }
  4316. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4317. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4318. ggml_vk_instance_init();
  4319. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4320. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4321. ctx->device = ggml_vk_get_device(idx);
  4322. ctx->semaphore_idx = 0;
  4323. ctx->event_idx = 0;
  4324. ctx->prealloc_size_x = 0;
  4325. ctx->prealloc_size_y = 0;
  4326. ctx->prealloc_size_split_k = 0;
  4327. ctx->prealloc_size_add_rms_partials = 0;
  4328. ctx->fence = ctx->device->device.createFence({});
  4329. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4330. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4331. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4332. #ifdef GGML_VULKAN_CHECK_RESULTS
  4333. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4334. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4335. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4336. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4337. #endif
  4338. }
  4339. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4340. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4341. switch (type) {
  4342. case GGML_TYPE_F32:
  4343. case GGML_TYPE_Q4_0:
  4344. case GGML_TYPE_Q4_1:
  4345. case GGML_TYPE_Q5_0:
  4346. case GGML_TYPE_Q5_1:
  4347. case GGML_TYPE_Q8_0:
  4348. case GGML_TYPE_Q2_K:
  4349. case GGML_TYPE_Q3_K:
  4350. case GGML_TYPE_Q4_K:
  4351. case GGML_TYPE_Q5_K:
  4352. case GGML_TYPE_Q6_K:
  4353. case GGML_TYPE_IQ1_S:
  4354. case GGML_TYPE_IQ1_M:
  4355. case GGML_TYPE_IQ2_XXS:
  4356. case GGML_TYPE_IQ2_XS:
  4357. case GGML_TYPE_IQ2_S:
  4358. case GGML_TYPE_IQ3_XXS:
  4359. case GGML_TYPE_IQ3_S:
  4360. case GGML_TYPE_IQ4_XS:
  4361. case GGML_TYPE_IQ4_NL:
  4362. case GGML_TYPE_MXFP4:
  4363. break;
  4364. default:
  4365. return nullptr;
  4366. }
  4367. return ctx->device->pipeline_dequant[type];
  4368. }
  4369. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  4370. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4371. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4372. return ctx->device->pipeline_matmul_f32;
  4373. }
  4374. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4375. return ctx->device->pipeline_matmul_f32_f16;
  4376. }
  4377. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4378. return ctx->device->pipeline_matmul_bf16;
  4379. }
  4380. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4381. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4382. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4383. }
  4384. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4385. return ctx->device->pipeline_matmul_f16.f16acc;
  4386. }
  4387. } else {
  4388. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4389. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4390. }
  4391. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4392. return ctx->device->pipeline_matmul_f16.f32acc;
  4393. }
  4394. }
  4395. // MMQ
  4396. if (src1_type == GGML_TYPE_Q8_1) {
  4397. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4398. if (pipelines->is_empty()) {
  4399. return nullptr;
  4400. }
  4401. return pipelines;
  4402. }
  4403. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4404. return nullptr;
  4405. }
  4406. switch (src0_type) {
  4407. case GGML_TYPE_Q4_0:
  4408. case GGML_TYPE_Q4_1:
  4409. case GGML_TYPE_Q5_0:
  4410. case GGML_TYPE_Q5_1:
  4411. case GGML_TYPE_Q8_0:
  4412. case GGML_TYPE_Q2_K:
  4413. case GGML_TYPE_Q3_K:
  4414. case GGML_TYPE_Q4_K:
  4415. case GGML_TYPE_Q5_K:
  4416. case GGML_TYPE_Q6_K:
  4417. case GGML_TYPE_IQ1_S:
  4418. case GGML_TYPE_IQ1_M:
  4419. case GGML_TYPE_IQ2_XXS:
  4420. case GGML_TYPE_IQ2_XS:
  4421. case GGML_TYPE_IQ2_S:
  4422. case GGML_TYPE_IQ3_XXS:
  4423. case GGML_TYPE_IQ3_S:
  4424. case GGML_TYPE_IQ4_XS:
  4425. case GGML_TYPE_IQ4_NL:
  4426. case GGML_TYPE_MXFP4:
  4427. break;
  4428. default:
  4429. return nullptr;
  4430. }
  4431. if (ctx->device->coopmat2) {
  4432. assert(src1_type == GGML_TYPE_F16);
  4433. return prec == GGML_PREC_DEFAULT ? ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f32acc;
  4434. }
  4435. if (ctx->device->coopmat_support) {
  4436. return (ctx->device->fp16 && ctx->device->coopmat_acc_f16_support && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4437. }
  4438. return (ctx->device->fp16 && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4439. }
  4440. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) {
  4441. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4442. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4443. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4444. if (b_type == GGML_TYPE_Q8_1) {
  4445. switch (a_type) {
  4446. case GGML_TYPE_Q4_0:
  4447. case GGML_TYPE_Q4_1:
  4448. case GGML_TYPE_Q5_0:
  4449. case GGML_TYPE_Q5_1:
  4450. case GGML_TYPE_Q8_0:
  4451. break;
  4452. default:
  4453. return nullptr;
  4454. }
  4455. }
  4456. switch (a_type) {
  4457. case GGML_TYPE_F32:
  4458. case GGML_TYPE_F16:
  4459. case GGML_TYPE_BF16:
  4460. case GGML_TYPE_Q4_0:
  4461. case GGML_TYPE_Q4_1:
  4462. case GGML_TYPE_Q5_0:
  4463. case GGML_TYPE_Q5_1:
  4464. case GGML_TYPE_Q8_0:
  4465. case GGML_TYPE_Q2_K:
  4466. case GGML_TYPE_Q3_K:
  4467. case GGML_TYPE_Q4_K:
  4468. case GGML_TYPE_Q5_K:
  4469. case GGML_TYPE_Q6_K:
  4470. case GGML_TYPE_IQ1_S:
  4471. case GGML_TYPE_IQ1_M:
  4472. case GGML_TYPE_IQ2_XXS:
  4473. case GGML_TYPE_IQ2_XS:
  4474. case GGML_TYPE_IQ2_S:
  4475. case GGML_TYPE_IQ3_XXS:
  4476. case GGML_TYPE_IQ3_S:
  4477. case GGML_TYPE_IQ4_XS:
  4478. case GGML_TYPE_IQ4_NL:
  4479. case GGML_TYPE_MXFP4:
  4480. break;
  4481. default:
  4482. return nullptr;
  4483. }
  4484. // heuristic to choose workgroup size
  4485. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4486. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4487. // Prefer larger workgroups when M is small, to spread the work out more
  4488. // and keep more SMs busy.
  4489. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4490. if (a_type == GGML_TYPE_Q6_K) {
  4491. if (m < 4096 && k >= 1024) {
  4492. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4493. }
  4494. } else {
  4495. if (m <= 8192 && k >= 1024) {
  4496. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4497. }
  4498. }
  4499. }
  4500. if (b_type == GGML_TYPE_Q8_1) {
  4501. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4502. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4503. }
  4504. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4505. }
  4506. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1];
  4507. }
  4508. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_id_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  4509. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4510. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4511. return ctx->device->pipeline_matmul_id_f32;
  4512. }
  4513. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4514. return ctx->device->pipeline_matmul_id_bf16;
  4515. }
  4516. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4517. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4518. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4519. }
  4520. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4521. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4522. }
  4523. } else {
  4524. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4525. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4526. }
  4527. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4528. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4529. }
  4530. }
  4531. // MMQ
  4532. if (src1_type == GGML_TYPE_Q8_1) {
  4533. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4534. if (pipelines->is_empty()) {
  4535. return nullptr;
  4536. }
  4537. return pipelines;
  4538. }
  4539. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4540. switch (src0_type) {
  4541. case GGML_TYPE_Q4_0:
  4542. case GGML_TYPE_Q4_1:
  4543. case GGML_TYPE_Q5_0:
  4544. case GGML_TYPE_Q5_1:
  4545. case GGML_TYPE_Q8_0:
  4546. case GGML_TYPE_Q2_K:
  4547. case GGML_TYPE_Q3_K:
  4548. case GGML_TYPE_Q4_K:
  4549. case GGML_TYPE_Q5_K:
  4550. case GGML_TYPE_Q6_K:
  4551. case GGML_TYPE_IQ1_S:
  4552. case GGML_TYPE_IQ1_M:
  4553. case GGML_TYPE_IQ2_XXS:
  4554. case GGML_TYPE_IQ2_XS:
  4555. case GGML_TYPE_IQ2_S:
  4556. case GGML_TYPE_IQ3_XXS:
  4557. case GGML_TYPE_IQ3_S:
  4558. case GGML_TYPE_IQ4_XS:
  4559. case GGML_TYPE_IQ4_NL:
  4560. case GGML_TYPE_MXFP4:
  4561. break;
  4562. default:
  4563. return nullptr;
  4564. }
  4565. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4566. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4567. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4568. bool support_fp16acc = !mmp.f16acc->is_empty();
  4569. bool support_fp32acc = !mmp.f32acc->is_empty();
  4570. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4571. return mmp.f16acc;
  4572. } else {
  4573. GGML_ASSERT(support_fp32acc);
  4574. return mmp.f32acc;
  4575. }
  4576. }
  4577. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4578. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4579. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4580. switch (a_type) {
  4581. case GGML_TYPE_F32:
  4582. case GGML_TYPE_F16:
  4583. case GGML_TYPE_BF16:
  4584. case GGML_TYPE_Q4_0:
  4585. case GGML_TYPE_Q4_1:
  4586. case GGML_TYPE_Q5_0:
  4587. case GGML_TYPE_Q5_1:
  4588. case GGML_TYPE_Q8_0:
  4589. case GGML_TYPE_Q2_K:
  4590. case GGML_TYPE_Q3_K:
  4591. case GGML_TYPE_Q4_K:
  4592. case GGML_TYPE_Q5_K:
  4593. case GGML_TYPE_Q6_K:
  4594. case GGML_TYPE_IQ1_S:
  4595. case GGML_TYPE_IQ1_M:
  4596. case GGML_TYPE_IQ2_XXS:
  4597. case GGML_TYPE_IQ2_XS:
  4598. case GGML_TYPE_IQ2_S:
  4599. case GGML_TYPE_IQ3_XXS:
  4600. case GGML_TYPE_IQ3_S:
  4601. case GGML_TYPE_IQ4_XS:
  4602. case GGML_TYPE_IQ4_NL:
  4603. case GGML_TYPE_MXFP4:
  4604. break;
  4605. default:
  4606. return nullptr;
  4607. }
  4608. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4609. }
  4610. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4611. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4612. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4613. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4614. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4615. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4616. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4617. size/1024.0/1024.0);
  4618. device->device.freeMemory(buf->device_memory);
  4619. device->device.destroyBuffer(buf->buffer);
  4620. return nullptr;
  4621. }
  4622. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4623. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4624. return buf->ptr;
  4625. }
  4626. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4627. if (ptr == nullptr) {
  4628. return;
  4629. }
  4630. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4631. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4632. vk_buffer buf;
  4633. size_t index;
  4634. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4635. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4636. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4637. if (ptr >= addr && ptr < endr) {
  4638. buf = std::get<2>(device->pinned_memory[i]);
  4639. index = i;
  4640. break;
  4641. }
  4642. }
  4643. if (buf == nullptr) {
  4644. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4645. return;
  4646. }
  4647. ggml_vk_destroy_buffer(buf);
  4648. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4649. }
  4650. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4651. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4652. buf = nullptr;
  4653. buf_offset = 0;
  4654. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4655. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4656. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4657. if (ptr >= addr && ptr < endr) {
  4658. buf = std::get<2>(device->pinned_memory[i]);
  4659. buf_offset = ((const uint8_t *)ptr) - addr;
  4660. break;
  4661. }
  4662. }
  4663. }
  4664. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4665. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4666. vk_buffer buffer = nullptr;
  4667. size_t offset = 0;
  4668. if (ctx->device->uma) {
  4669. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4670. }
  4671. if (!buffer) {
  4672. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4673. buffer = buf_ctx->dev_buffer;
  4674. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4675. }
  4676. GGML_ASSERT(buffer != nullptr);
  4677. size_t size = ggml_nbytes(tensor);
  4678. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4679. // The shader must support misaligned offsets when indexing into the buffer
  4680. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  4681. offset &= ~misalign_bytes;
  4682. size += misalign_bytes;
  4683. return vk_subbuffer{buffer, offset, size};
  4684. }
  4685. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4686. vk_submission s;
  4687. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4688. if (one_time) {
  4689. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4690. } else {
  4691. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4692. }
  4693. return s;
  4694. }
  4695. template <typename T> size_t push_constant_size(const T &t) {
  4696. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4697. GGML_UNUSED(t);
  4698. return sizeof(T);
  4699. }
  4700. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4701. GGML_UNUSED(t);
  4702. return sizeof(T) * t.size();
  4703. }
  4704. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4705. GGML_UNUSED(t);
  4706. return sizeof(T) * N;
  4707. }
  4708. template <typename T> const T *push_constant_data(const T &t) {
  4709. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4710. return &t;
  4711. }
  4712. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4713. return t.data();
  4714. }
  4715. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4716. return t.data();
  4717. }
  4718. template <typename T>
  4719. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& subctx, vk_pipeline& pipeline, std::initializer_list<vk::DescriptorBufferInfo> const& descriptor_buffer_infos, const T &push_constants, std::array<uint32_t, 3> elements) {
  4720. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4721. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4722. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4723. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4724. for (auto& buffer : descriptor_buffer_infos) {
  4725. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4726. }
  4727. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4728. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4729. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4730. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4731. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4732. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4733. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4734. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4735. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4736. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4737. pipeline->layout,
  4738. 0,
  4739. { descriptor_set },
  4740. {});
  4741. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4742. }
  4743. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4744. s.buffer.end();
  4745. s.wait_semaphores = std::move(wait_semaphores);
  4746. s.signal_semaphores = std::move(signal_semaphores);
  4747. }
  4748. static void ggml_vk_ctx_end(vk_context& ctx) {
  4749. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4750. if (ctx->s == nullptr) {
  4751. return;
  4752. }
  4753. ctx->s->buffer.end();
  4754. ctx->s = nullptr;
  4755. }
  4756. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4757. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4758. if (subctx->s != nullptr) {
  4759. ggml_vk_ctx_end(subctx);
  4760. }
  4761. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4762. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4763. }
  4764. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4765. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4766. return CEIL_DIV(width, align) * align;
  4767. }
  4768. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4769. if (memcpys == nullptr) {
  4770. memcpy(dst, src, size);
  4771. } else {
  4772. memcpys->emplace_back(dst, src, size);
  4773. }
  4774. }
  4775. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4776. if (memsets == nullptr) {
  4777. memset(dst, val, size);
  4778. } else {
  4779. memsets->emplace_back(dst, val, size);
  4780. }
  4781. }
  4782. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4783. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4784. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4785. ggml_vk_destroy_buffer(device->sync_staging);
  4786. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4787. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4788. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4789. }
  4790. }
  4791. static void ggml_vk_buffer_write_nc_async(ggml_backend_vk_context * ctx, vk_context& subctx, vk_buffer& dst, size_t offset, const ggml_tensor * tensor, bool sync_staging = false) {
  4792. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4793. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4794. // Buffer is already mapped
  4795. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4796. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4797. GGML_ABORT("fatal error");
  4798. }
  4799. // Check if src is pinned memory
  4800. vk_buffer buf = nullptr;
  4801. size_t buf_offset = 0;
  4802. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4803. const uint64_t ne0 = tensor->ne[0];
  4804. const uint64_t ne1 = tensor->ne[1];
  4805. const uint64_t ne2 = tensor->ne[2];
  4806. const uint64_t ne3 = tensor->ne[3];
  4807. const uint64_t nb0 = tensor->nb[0];
  4808. const uint64_t nb1 = tensor->nb[1];
  4809. const uint64_t nb2 = tensor->nb[2];
  4810. const uint64_t nb3 = tensor->nb[3];
  4811. const ggml_type type = tensor->type;
  4812. const uint64_t ts = ggml_type_size(type);
  4813. const uint64_t bs = ggml_blck_size(type);
  4814. const uint64_t dstnb0 = ts;
  4815. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4816. const uint64_t dstnb2 = dstnb1*ne1;
  4817. const uint64_t dstnb3 = dstnb2*ne2;
  4818. const uint64_t ne = ggml_nelements(tensor);
  4819. if (buf != nullptr) {
  4820. // Memory is pinned, use as staging buffer
  4821. std::vector<vk::BufferCopy> slices;
  4822. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4823. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4824. // Find longest contiguous slice
  4825. if (ne1*nb1 == dstnb2) {
  4826. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4827. } else {
  4828. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4829. if (ne0*nb0/bs == dstnb1) {
  4830. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4831. } else {
  4832. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4833. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4834. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4835. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4836. }
  4837. }
  4838. }
  4839. }
  4840. }
  4841. }
  4842. ggml_vk_sync_buffers(ctx, subctx);
  4843. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4844. return;
  4845. }
  4846. if (!sync_staging) {
  4847. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4848. }
  4849. // Staging buffer required
  4850. vk_buffer& staging = ctx->device->sync_staging;
  4851. const uint64_t copy_size = ts*ne/bs;
  4852. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4853. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4854. ggml_vk_sync_buffers(ctx, subctx);
  4855. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4856. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4857. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4858. // Find longest contiguous slice
  4859. if (ne1*nb1 == dstnb2) {
  4860. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2, dstnb2, &subctx->in_memcpys);
  4861. } else {
  4862. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4863. if (ne0*nb0/bs == dstnb1) {
  4864. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2 + i1*nb1, dstnb1, &subctx->in_memcpys);
  4865. } else {
  4866. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4867. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4868. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4869. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4870. }
  4871. }
  4872. }
  4873. }
  4874. }
  4875. }
  4876. }
  4877. static void ggml_vk_buffer_write_2d_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height, bool sync_staging = false) {
  4878. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4879. // Buffer is already mapped
  4880. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4881. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4882. GGML_ABORT("fatal error");
  4883. }
  4884. // Check if src is pinned memory
  4885. vk_buffer buf = nullptr;
  4886. size_t buf_offset = 0;
  4887. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4888. if (buf != nullptr) {
  4889. // Memory is pinned, use as staging buffer
  4890. std::vector<vk::BufferCopy> slices(1);
  4891. if (width == spitch) {
  4892. // Only do single write if stride is equal
  4893. slices[0].srcOffset = buf_offset;
  4894. slices[0].dstOffset = offset;
  4895. slices[0].size = width * height;
  4896. } else {
  4897. slices.resize(height);
  4898. for (size_t i = 0; i < height; i++) {
  4899. slices[i].srcOffset = buf_offset + i * spitch;
  4900. slices[i].dstOffset = offset + i * width;
  4901. slices[i].size = width;
  4902. }
  4903. }
  4904. ggml_vk_sync_buffers(nullptr, subctx);
  4905. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4906. return;
  4907. }
  4908. VK_LOG_DEBUG("STAGING");
  4909. if (!sync_staging) {
  4910. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4911. }
  4912. // Staging buffer required
  4913. const size_t copy_size = width*height;
  4914. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4915. vk_buffer& staging_buffer = dst->device->sync_staging;
  4916. VkBufferCopy buf_copy = {
  4917. 0,
  4918. offset,
  4919. copy_size};
  4920. ggml_vk_sync_buffers(nullptr, subctx);
  4921. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4922. if (width == spitch) {
  4923. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4924. } else {
  4925. for (size_t i = 0; i < height; i++) {
  4926. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4927. }
  4928. }
  4929. }
  4930. static void ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  4931. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4932. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4933. }
  4934. static void ggml_vk_buffer_write_2d(vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height) {
  4935. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4936. // Buffer is already mapped
  4937. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4938. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4939. for (size_t i = 0; i < height; i++) {
  4940. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4941. }
  4942. } else {
  4943. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4944. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4945. ggml_vk_ctx_begin(dst->device, subctx);
  4946. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4947. ggml_vk_ctx_end(subctx);
  4948. for (auto& cpy : subctx->in_memcpys) {
  4949. memcpy(cpy.dst, cpy.src, cpy.n);
  4950. }
  4951. for (auto& mset : subctx->memsets) {
  4952. memset(mset.dst, mset.val, mset.n);
  4953. }
  4954. ggml_vk_submit(subctx, dst->device->fence);
  4955. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4956. dst->device->device.resetFences({ dst->device->fence });
  4957. ggml_vk_queue_command_pools_cleanup(dst->device);
  4958. }
  4959. }
  4960. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4961. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4962. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4963. }
  4964. static void ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  4965. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4966. GGML_ASSERT(width > 0);
  4967. GGML_ASSERT(height > 0);
  4968. GGML_ASSERT(src != nullptr);
  4969. // TODO: staging_offset is not used
  4970. // Check if dst is pinned memory
  4971. vk_buffer buf = nullptr;
  4972. size_t buf_offset = 0;
  4973. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4974. std::vector<vk::BufferCopy> slices(1);
  4975. if (width == spitch && width == dpitch) {
  4976. // Only do single write if stride is equal
  4977. slices[0].srcOffset = offset;
  4978. slices[0].dstOffset = buf_offset;
  4979. slices[0].size = width * height;
  4980. } else {
  4981. slices.resize(height);
  4982. for (size_t i = 0; i < height; i++) {
  4983. slices[i].srcOffset = offset + i * spitch;
  4984. slices[i].dstOffset = buf_offset + i * dpitch;
  4985. slices[i].size = width;
  4986. }
  4987. }
  4988. if (buf != nullptr) {
  4989. // Memory is pinned, use as staging buffer
  4990. ggml_vk_sync_buffers(nullptr, subctx);
  4991. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4992. return;
  4993. }
  4994. VK_LOG_DEBUG("STAGING");
  4995. if (!sync_staging) {
  4996. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4997. }
  4998. // Fall back to staging buffer
  4999. const size_t copy_size = dpitch * height;
  5000. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5001. vk_buffer& staging_buffer = src->device->sync_staging;
  5002. ggml_vk_sync_buffers(nullptr, subctx);
  5003. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5004. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5005. }
  5006. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5007. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5008. }
  5009. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5010. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5011. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5012. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5013. // the HW device to host copy path.
  5014. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5015. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5016. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5017. } else {
  5018. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5019. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5020. ggml_vk_ctx_begin(src->device, subctx);
  5021. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5022. ggml_vk_ctx_end(subctx);
  5023. ggml_vk_submit(subctx, src->device->fence);
  5024. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5025. src->device->device.resetFences({ src->device->fence });
  5026. ggml_vk_queue_command_pools_cleanup(src->device);
  5027. for (auto& cpy : subctx->out_memcpys) {
  5028. memcpy(cpy.dst, cpy.src, cpy.n);
  5029. }
  5030. }
  5031. }
  5032. static void ggml_vk_buffer_copy_async(vk_context& ctx, vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5033. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5034. // Make sure both buffers are on same device
  5035. GGML_ASSERT(src->device == dst->device);
  5036. VkBufferCopy bc{ src_offset, dst_offset, size };
  5037. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5038. }
  5039. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5040. if (src->device == dst->device) {
  5041. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5042. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5043. // Copy within the device
  5044. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5045. ggml_vk_ctx_begin(src->device, subctx);
  5046. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5047. ggml_vk_ctx_end(subctx);
  5048. ggml_vk_submit(subctx, src->device->fence);
  5049. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5050. src->device->device.resetFences({ src->device->fence });
  5051. ggml_vk_queue_command_pools_cleanup(src->device);
  5052. } else {
  5053. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5054. // Copy device to device
  5055. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5056. // Copy to src staging buffer
  5057. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5058. // Copy to dst buffer
  5059. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5060. }
  5061. }
  5062. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5063. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5064. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5065. dst->device->uma) {
  5066. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5067. return;
  5068. }
  5069. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5070. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5071. }
  5072. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5073. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5074. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5075. dst->device->uma) {
  5076. memset((uint8_t*)dst->ptr + offset, c, size);
  5077. return;
  5078. }
  5079. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5080. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5081. ggml_vk_ctx_begin(dst->device, subctx);
  5082. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5083. ggml_vk_ctx_end(subctx);
  5084. ggml_vk_submit(subctx, dst->device->fence);
  5085. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5086. dst->device->device.resetFences({ dst->device->fence });
  5087. ggml_vk_queue_command_pools_cleanup(dst->device);
  5088. }
  5089. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) {
  5090. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5091. if (disable_split_k) {
  5092. return 1;
  5093. }
  5094. uint32_t split_k = 1;
  5095. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5096. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5097. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5098. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5099. if (k >= 2048) {
  5100. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5101. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5102. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5103. split_k = 3;
  5104. }
  5105. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5106. split_k = std::min(split_k, 8u);
  5107. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5108. // If this rounded up size would cause the last split to be empty,
  5109. // then reduce the split count.
  5110. while (true) {
  5111. if (split_k == 1) {
  5112. break;
  5113. }
  5114. uint32_t k_split = CEIL_DIV(k, split_k);
  5115. k_split = ROUNDUP_POW2(k_split, 256);
  5116. if (k_split * (split_k - 1) < k) {
  5117. break;
  5118. }
  5119. split_k--;
  5120. }
  5121. }
  5122. }
  5123. return split_k;
  5124. }
  5125. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type, ggml_type src1_type) {
  5126. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5127. if (ctx->device->coopmat2) {
  5128. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5129. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5130. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5131. // Use large shader when the N dimension is greater than the medium shader's tile size
  5132. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5133. // Prefer large over medium if either:
  5134. // - medium or large tiles would overfill the GPU
  5135. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5136. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5137. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5138. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5139. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5140. if ((ctx->device->mul_mat_l[src0_type] && (n > crossover_large && prefer_large)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_s[src0_type])) {
  5141. return aligned ? mmp->a_l : mmp->l;
  5142. }
  5143. // Use medium shader when the N dimension is greater than the small shader's tile size
  5144. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5145. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5146. return aligned ? mmp->a_m : mmp->m;
  5147. }
  5148. return aligned ? mmp->a_s : mmp->s;
  5149. }
  5150. if ((ctx->device->mul_mat_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_l[src0_type])) {
  5151. return aligned ? mmp->a_s : mmp->s;
  5152. }
  5153. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5154. return aligned ? mmp->a_m : mmp->m;
  5155. }
  5156. return aligned ? mmp->a_l : mmp->l;
  5157. GGML_UNUSED(src1_type);
  5158. }
  5159. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type, ggml_type src1_type) {
  5160. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5161. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5162. }
  5163. static void ggml_vk_matmul(
  5164. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5165. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5166. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5167. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5168. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5169. uint32_t padded_n) {
  5170. VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", padded_n: " << padded_n << ")");
  5171. if (split_k == 1) {
  5172. const vk_mat_mat_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k, ne02, ne12, broadcast2, broadcast3, padded_n };
  5173. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5174. return;
  5175. }
  5176. if (ctx->prealloc_split_k_need_sync) {
  5177. ggml_vk_sync_buffers(ctx, subctx);
  5178. }
  5179. GGML_ASSERT(batch_stride_d == m * n);
  5180. // Round the split size up to a multiple of 256 (k-quant alignment)
  5181. uint32_t k_split = CEIL_DIV(k, split_k);
  5182. k_split = ROUNDUP_POW2(k_split, 256);
  5183. const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k_split, ne02, ne12, broadcast2, broadcast3, padded_n };
  5184. // Make sure enough workgroups get assigned for split k to work
  5185. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  5186. ggml_vk_sync_buffers(ctx, subctx);
  5187. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5188. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5189. ctx->prealloc_split_k_need_sync = true;
  5190. }
  5191. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type) {
  5192. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5193. if (ctx->device->coopmat2) {
  5194. // Use large shader when the N dimension is greater than the medium shader's tile size
  5195. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5196. if ((ctx->device->mul_mat_id_l[src0_type] && (n > crossover_large)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_s[src0_type])) {
  5197. return aligned ? mmp->a_l : mmp->l;
  5198. }
  5199. // Use medium shader when the N dimension is greater than the small shader's tile size
  5200. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5201. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5202. return aligned ? mmp->a_m : mmp->m;
  5203. }
  5204. return aligned ? mmp->a_s : mmp->s;
  5205. }
  5206. if ((ctx->device->mul_mat_id_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_l[src0_type])) {
  5207. return aligned ? mmp->a_s : mmp->s;
  5208. }
  5209. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5210. return aligned ? mmp->a_m : mmp->m;
  5211. }
  5212. return aligned ? mmp->a_l : mmp->l;
  5213. }
  5214. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type) {
  5215. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5216. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5217. }
  5218. static void ggml_vk_matmul_id(
  5219. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5220. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5221. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5222. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5223. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5224. uint32_t padded_n) {
  5225. VK_LOG_DEBUG("ggml_vk_matmul_id(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), ids: (" << ids.buffer->buffer << ", " << ids.offset << ", " << ids.size << "), " <<
  5226. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5227. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5228. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5229. const vk_mat_mat_id_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d,
  5230. nei0, nei1, nbi1, ne11, padded_n };
  5231. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5232. }
  5233. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5234. return
  5235. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5236. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5237. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5238. }
  5239. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5240. // Choose "contiguous copy" shader if src/dst are contiguous
  5241. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5242. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5243. if (contig) {
  5244. return ctx->device->pipeline_contig_cpy_f32_f32;
  5245. } else {
  5246. return ctx->device->pipeline_cpy_f32_f32;
  5247. }
  5248. }
  5249. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5250. if (contig) {
  5251. return ctx->device->pipeline_contig_cpy_f32_f16;
  5252. } else {
  5253. return ctx->device->pipeline_cpy_f32_f16;
  5254. }
  5255. }
  5256. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5257. if (contig) {
  5258. return ctx->device->pipeline_contig_cpy_f16_f16;
  5259. } else {
  5260. return ctx->device->pipeline_cpy_f16_f16;
  5261. }
  5262. }
  5263. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5264. if (contig) {
  5265. return ctx->device->pipeline_contig_cpy_f16_f32;
  5266. } else {
  5267. return ctx->device->pipeline_cpy_f16_f32;
  5268. }
  5269. }
  5270. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5271. if (contig) {
  5272. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5273. } else {
  5274. return ctx->device->pipeline_cpy_f32_bf16;
  5275. }
  5276. }
  5277. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5278. if (contig) {
  5279. return ctx->device->pipeline_contig_cpy_f32_i32;
  5280. } else {
  5281. return ctx->device->pipeline_cpy_f32_i32;
  5282. }
  5283. }
  5284. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5285. if (contig) {
  5286. return ctx->device->pipeline_contig_cpy_i32_f32;
  5287. } else {
  5288. return ctx->device->pipeline_cpy_i32_f32;
  5289. }
  5290. }
  5291. if (src->type == GGML_TYPE_F32) {
  5292. switch (to) {
  5293. case GGML_TYPE_Q4_0:
  5294. case GGML_TYPE_Q4_1:
  5295. case GGML_TYPE_Q5_0:
  5296. case GGML_TYPE_Q5_1:
  5297. case GGML_TYPE_Q8_0:
  5298. case GGML_TYPE_IQ4_NL:
  5299. return ctx->device->pipeline_cpy_f32_quant[to];
  5300. default:
  5301. break;
  5302. }
  5303. }
  5304. if (to == GGML_TYPE_F32) {
  5305. switch (src->type) {
  5306. case GGML_TYPE_Q4_0:
  5307. case GGML_TYPE_Q4_1:
  5308. case GGML_TYPE_Q5_0:
  5309. case GGML_TYPE_Q5_1:
  5310. case GGML_TYPE_Q8_0:
  5311. case GGML_TYPE_IQ4_NL:
  5312. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5313. default:
  5314. break;
  5315. }
  5316. }
  5317. if (src->type == to) {
  5318. // Copy two or four bytes at a time, depending on block size.
  5319. // For quantized types, we scale by block size/type size. But
  5320. // this path is also used for bf16->bf16 for example, where the
  5321. // type size must be exactly 2 or 4.
  5322. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5323. if ((ggml_type_size(src->type) % 4) == 0) {
  5324. if (contig) {
  5325. return ctx->device->pipeline_contig_cpy_f32_f32;
  5326. } else {
  5327. return ctx->device->pipeline_cpy_f32_f32;
  5328. }
  5329. } else {
  5330. if (contig) {
  5331. return ctx->device->pipeline_contig_cpy_f16_f16;
  5332. } else {
  5333. return ctx->device->pipeline_cpy_f16_f16;
  5334. }
  5335. }
  5336. }
  5337. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5338. GGML_ABORT("fatal error");
  5339. }
  5340. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, vk_subbuffer&& in, vk_subbuffer&& out) {
  5341. VK_LOG_DEBUG("ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << "), ";
  5342. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5343. const int tensor_type_size = ggml_type_size(tensor->type);
  5344. const uint32_t ne = ggml_nelements(tensor);
  5345. std::array<uint32_t, 3> elements;
  5346. if (ne > 262144) {
  5347. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5348. } else if (ne > 512) {
  5349. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5350. } else {
  5351. elements = { ne, 1, 1 };
  5352. }
  5353. vk_op_unary_push_constants pc = {
  5354. (uint32_t)ne,
  5355. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], (uint32_t)tensor->ne[2], (uint32_t)tensor->ne[3], (uint32_t)tensor->nb[0] / tensor_type_size, (uint32_t)tensor->nb[1] / tensor_type_size, (uint32_t)tensor->nb[2] / tensor_type_size, (uint32_t)tensor->nb[3] / tensor_type_size,
  5356. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], (uint32_t)tensor->ne[2], (uint32_t)tensor->ne[3], 1 , (uint32_t)tensor->ne[0] , (uint32_t)(tensor->ne[0] * tensor->ne[1]) , (uint32_t)(tensor->ne[0] * tensor->ne[1] * tensor->ne[2]),
  5357. 0,
  5358. 0.0f, 0.0f,
  5359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5360. };
  5361. init_pushconst_fastdiv(pc);
  5362. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5363. ggml_vk_sync_buffers(ctx, subctx);
  5364. }
  5365. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type, bool use_x4_blocks) {
  5366. switch(type) {
  5367. case GGML_TYPE_Q8_1:
  5368. return use_x4_blocks ? ctx->device->pipeline_quantize_q8_1_x4 : ctx->device->pipeline_quantize_q8_1;
  5369. default:
  5370. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5371. GGML_ABORT("fatal error");
  5372. }
  5373. }
  5374. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne, bool use_x4_blocks = false) {
  5375. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5376. vk_pipeline pipeline = use_x4_blocks ? ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true) : ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, false);
  5377. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5378. ggml_vk_sync_buffers(ctx, subctx);
  5379. }
  5380. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k) {
  5381. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(src0->type) << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  5382. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  5383. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  5384. std::cerr << "))");
  5385. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5386. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5387. const uint64_t ne00 = src0->ne[0];
  5388. const uint64_t ne01 = src0->ne[1];
  5389. const uint64_t ne02 = src0->ne[2];
  5390. const uint64_t ne03 = src0->ne[3];
  5391. const uint64_t ne10 = src1->ne[0];
  5392. const uint64_t ne11 = src1->ne[1];
  5393. const uint64_t ne12 = src1->ne[2];
  5394. const uint64_t ne13 = src1->ne[3];
  5395. const uint64_t ne21 = dst->ne[1];
  5396. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5397. const uint32_t stride_batch_d = stride_d*ne21;
  5398. const uint64_t r2 = ne12 / ne02;
  5399. const uint64_t r3 = ne13 / ne03;
  5400. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5401. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5402. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5403. vk_buffer d_Qx = nullptr;
  5404. size_t qx_buf_offset = 0;
  5405. vk_buffer d_Qy = nullptr;
  5406. size_t qy_buf_offset = 0;
  5407. bool src0_uma = false;
  5408. bool src1_uma = false;
  5409. if (ctx->device->uma) {
  5410. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5411. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5412. src0_uma = d_Qx != nullptr;
  5413. src1_uma = d_Qy != nullptr;
  5414. }
  5415. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5416. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5417. !ggml_vk_dim01_contiguous(src0);
  5418. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5419. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5420. !ggml_vk_dim01_contiguous(src1);
  5421. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5422. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5423. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5424. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5425. // Check for mmq first
  5426. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  5427. if (mmp == nullptr) {
  5428. // Fall back to f16 dequant mul mat
  5429. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5430. quantize_y = false;
  5431. }
  5432. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5433. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5434. if (qx_needs_dequant) {
  5435. // Fall back to dequant + f16 mulmat
  5436. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  5437. }
  5438. // Not implemented
  5439. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5440. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type)));
  5441. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5442. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type));
  5443. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5444. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5445. const int x_ne = ne01 * ne00;
  5446. const int y_ne = padded_n * ne10;
  5447. const int d_ne = ne11 * ne01;
  5448. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5449. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5450. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5451. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5452. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5453. const uint64_t d_sz = sizeof(float) * d_ne;
  5454. vk_pipeline to_fp16_vk_0 = nullptr;
  5455. vk_pipeline to_fp16_vk_1 = nullptr;
  5456. vk_pipeline to_q8_1 = nullptr;
  5457. if (x_non_contig) {
  5458. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5459. } else {
  5460. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5461. }
  5462. if (y_non_contig) {
  5463. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5464. } else {
  5465. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5466. }
  5467. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5468. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5469. if (quantize_y) {
  5470. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5471. }
  5472. {
  5473. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5474. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5475. if (quantize_y) {
  5476. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5477. }
  5478. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  5479. if (
  5480. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5481. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5482. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5483. GGML_ABORT("Requested preallocation size is too large");
  5484. }
  5485. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5486. ctx->prealloc_size_x = x_sz_upd;
  5487. ggml_vk_preallocate_buffers(ctx, subctx);
  5488. }
  5489. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5490. ctx->prealloc_size_y = y_sz_upd;
  5491. ggml_vk_preallocate_buffers(ctx, subctx);
  5492. }
  5493. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5494. ctx->prealloc_size_split_k = split_k_size;
  5495. ggml_vk_preallocate_buffers(ctx, subctx);
  5496. }
  5497. // Request descriptor sets
  5498. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5499. if (qx_needs_dequant) {
  5500. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5501. }
  5502. if (qy_needs_dequant) {
  5503. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5504. }
  5505. if (quantize_y) {
  5506. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5507. }
  5508. if (split_k > 1) {
  5509. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5510. }
  5511. }
  5512. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5513. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5514. GGML_ASSERT(d_D != nullptr);
  5515. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  5516. vk_buffer d_X;
  5517. uint64_t x_buf_offset = 0;
  5518. vk_buffer d_Y;
  5519. uint64_t y_buf_offset = 0;
  5520. if (!src0_uma) {
  5521. d_Qx = src0_buf_ctx->dev_buffer;
  5522. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5523. GGML_ASSERT(d_Qx != nullptr);
  5524. }
  5525. if (!src1_uma) {
  5526. d_Qy = src1_buf_ctx->dev_buffer;
  5527. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5528. GGML_ASSERT(d_Qy != nullptr);
  5529. }
  5530. if (qx_needs_dequant) {
  5531. d_X = ctx->prealloc_x;
  5532. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5533. } else {
  5534. d_X = d_Qx;
  5535. x_buf_offset = qx_buf_offset;
  5536. GGML_ASSERT(qx_sz == x_sz);
  5537. }
  5538. if (qy_needs_dequant) {
  5539. d_Y = ctx->prealloc_y;
  5540. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5541. } else if (quantize_y) {
  5542. d_Y = ctx->prealloc_y;
  5543. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5544. } else {
  5545. d_Y = d_Qy;
  5546. y_buf_offset = qy_buf_offset;
  5547. GGML_ASSERT(qy_sz == y_sz);
  5548. }
  5549. if (x_non_contig || qx_needs_dequant) {
  5550. if (ctx->prealloc_x_need_sync) {
  5551. ggml_vk_sync_buffers(ctx, subctx);
  5552. }
  5553. }
  5554. if (x_non_contig) {
  5555. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  5556. } else if (qx_needs_dequant) {
  5557. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5558. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  5559. ggml_vk_sync_buffers(ctx, subctx);
  5560. }
  5561. if (y_non_contig) {
  5562. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5563. ctx->prealloc_y_last_tensor_used != src1) {
  5564. if (ctx->prealloc_y_need_sync) {
  5565. ggml_vk_sync_buffers(ctx, subctx);
  5566. }
  5567. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  5568. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5569. ctx->prealloc_y_last_tensor_used = src1;
  5570. }
  5571. }
  5572. if (quantize_y) {
  5573. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5574. ctx->prealloc_y_last_tensor_used != src1) {
  5575. if (ctx->prealloc_y_need_sync) {
  5576. ggml_vk_sync_buffers(ctx, subctx);
  5577. }
  5578. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne * ne12 * ne13, true);
  5579. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5580. ctx->prealloc_y_last_tensor_used = src1;
  5581. }
  5582. }
  5583. uint32_t stride_batch_x = ne00*ne01;
  5584. uint32_t stride_batch_y = ne10*ne11;
  5585. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5586. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5587. }
  5588. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5589. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5590. }
  5591. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5592. if (quantize_y) {
  5593. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5594. }
  5595. // compute
  5596. ggml_vk_matmul(
  5597. ctx, subctx, pipeline,
  5598. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  5599. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  5600. ne01, ne11, ne10,
  5601. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5602. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5603. ); // NOLINT
  5604. if (x_non_contig || qx_needs_dequant) {
  5605. ctx->prealloc_x_need_sync = true;
  5606. }
  5607. if (y_non_contig || quantize_y) {
  5608. ctx->prealloc_y_need_sync = true;
  5609. }
  5610. }
  5611. // Device tuning
  5612. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5613. if (device->mmvq_mode == 1) {
  5614. return true;
  5615. } else if (device->mmvq_mode == -1) {
  5616. return false;
  5617. }
  5618. // MMVQ is generally good for batches
  5619. if (n > 1) {
  5620. return true;
  5621. }
  5622. switch (device->vendor_id) {
  5623. case VK_VENDOR_ID_NVIDIA:
  5624. switch (src0_type) {
  5625. case GGML_TYPE_Q8_0:
  5626. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5627. default:
  5628. return true;
  5629. }
  5630. case VK_VENDOR_ID_AMD:
  5631. switch (src0_type) {
  5632. case GGML_TYPE_Q8_0:
  5633. return device->architecture == vk_device_architecture::AMD_GCN;
  5634. default:
  5635. return true;
  5636. }
  5637. case VK_VENDOR_ID_INTEL:
  5638. switch (src0_type) {
  5639. // From tests on A770 Linux, may need more tuning
  5640. case GGML_TYPE_Q4_0:
  5641. case GGML_TYPE_Q5_1:
  5642. return false;
  5643. default:
  5644. return true;
  5645. }
  5646. default:
  5647. return true;
  5648. }
  5649. GGML_UNUSED(m);
  5650. GGML_UNUSED(k);
  5651. }
  5652. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  5653. ggml_tensor * dst = cgraph->nodes[node_idx];
  5654. const ggml_tensor * src0 = dst->src[0];
  5655. const ggml_tensor * src1 = dst->src[1];
  5656. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  5657. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  5658. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  5659. std::cerr << ")),)");
  5660. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5661. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5662. const uint64_t ne00 = src0->ne[0];
  5663. const uint64_t ne01 = src0->ne[1];
  5664. const uint64_t ne02 = src0->ne[2];
  5665. const uint64_t ne03 = src0->ne[3];
  5666. const uint64_t ne10 = src1->ne[0];
  5667. const uint64_t ne11 = src1->ne[1];
  5668. const uint64_t ne12 = src1->ne[2];
  5669. const uint64_t ne13 = src1->ne[3];
  5670. const uint64_t ne20 = dst->ne[0];
  5671. const uint64_t ne21 = dst->ne[1];
  5672. const uint64_t ne22 = dst->ne[2];
  5673. const uint64_t ne23 = dst->ne[3];
  5674. const uint64_t r2 = ne12 / ne02;
  5675. const uint64_t r3 = ne13 / ne03;
  5676. // batch_n indicates that we need to compute a few vector results, and this assumes
  5677. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5678. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5679. bool batch_n = ne11 > 1;
  5680. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5681. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5682. vk_buffer d_Qx = nullptr;
  5683. size_t qx_buf_offset = 0;
  5684. vk_buffer d_Qy = nullptr;
  5685. size_t qy_buf_offset = 0;
  5686. bool src0_uma = false;
  5687. bool src1_uma = false;
  5688. if (ctx->device->uma) {
  5689. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5690. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5691. src0_uma = d_Qx != nullptr;
  5692. src1_uma = d_Qy != nullptr;
  5693. }
  5694. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5695. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5696. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5697. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5698. vk_pipeline to_fp16_vk_0 = nullptr;
  5699. vk_pipeline to_fp16_vk_1 = nullptr;
  5700. if (x_non_contig) {
  5701. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5702. }
  5703. if (y_non_contig) {
  5704. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5705. } else {
  5706. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5707. }
  5708. // Check for mmq first
  5709. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5710. vk_pipeline to_q8_1 = nullptr;
  5711. if (dmmv == nullptr) {
  5712. // Fall back to f16 dequant mul mat
  5713. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5714. quantize_y = false;
  5715. }
  5716. if (quantize_y) {
  5717. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5718. }
  5719. const bool qx_needs_dequant = x_non_contig;
  5720. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5721. // Not implemented
  5722. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5723. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5724. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5725. GGML_ASSERT(dmmv != nullptr);
  5726. const uint64_t x_ne = ne01 * ne00;
  5727. const uint64_t y_ne = ne11 * ne10;
  5728. const uint64_t d_ne = ne11 * ne01;
  5729. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  5730. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5731. const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz;
  5732. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5733. const uint64_t d_sz = sizeof(float) * d_ne;
  5734. {
  5735. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5736. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5737. if (quantize_y) {
  5738. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5739. }
  5740. if (
  5741. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5742. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  5743. GGML_ABORT("Requested preallocation size is too large");
  5744. }
  5745. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5746. ctx->prealloc_size_x = x_sz_upd;
  5747. ggml_vk_preallocate_buffers(ctx, subctx);
  5748. }
  5749. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5750. ctx->prealloc_size_y = y_sz_upd;
  5751. ggml_vk_preallocate_buffers(ctx, subctx);
  5752. }
  5753. // Request descriptor sets
  5754. if (qx_needs_dequant) {
  5755. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5756. }
  5757. if (qy_needs_dequant) {
  5758. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5759. }
  5760. if (quantize_y) {
  5761. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5762. }
  5763. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5764. }
  5765. vk_buffer d_D;
  5766. uint64_t d_buf_offset = 0;
  5767. if (ctx->num_additional_fused_ops > 0) {
  5768. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5769. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5770. d_D = dst_buf_ctx->dev_buffer;
  5771. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5772. } else {
  5773. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5774. d_D = dst_buf_ctx->dev_buffer;
  5775. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5776. }
  5777. GGML_ASSERT(d_D != nullptr);
  5778. vk_buffer d_X;
  5779. uint64_t x_buf_offset = 0;
  5780. vk_buffer d_Y;
  5781. uint64_t y_buf_offset = 0;
  5782. if(!src0_uma) {
  5783. d_Qx = src0_buf_ctx->dev_buffer;
  5784. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5785. GGML_ASSERT(d_Qx != nullptr);
  5786. }
  5787. if(!src1_uma) {
  5788. d_Qy = src1_buf_ctx->dev_buffer;
  5789. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5790. GGML_ASSERT(d_Qy != nullptr);
  5791. }
  5792. if (qx_needs_dequant) {
  5793. d_X = ctx->prealloc_x;
  5794. } else {
  5795. d_X = d_Qx;
  5796. x_buf_offset = qx_buf_offset;
  5797. GGML_ASSERT(qx_sz == x_sz);
  5798. }
  5799. if (qy_needs_dequant) {
  5800. d_Y = ctx->prealloc_y;
  5801. } else if (quantize_y) {
  5802. d_Y = ctx->prealloc_y;
  5803. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5804. } else {
  5805. d_Y = d_Qy;
  5806. y_buf_offset = qy_buf_offset;
  5807. GGML_ASSERT(qy_sz == y_sz);
  5808. }
  5809. if (x_non_contig) {
  5810. if (ctx->prealloc_x_need_sync) {
  5811. ggml_vk_sync_buffers(ctx, subctx);
  5812. }
  5813. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5814. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  5815. }
  5816. if (y_non_contig) {
  5817. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5818. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5819. ctx->prealloc_y_last_tensor_used != src1) {
  5820. if (ctx->prealloc_y_need_sync) {
  5821. ggml_vk_sync_buffers(ctx, subctx);
  5822. }
  5823. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  5824. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5825. ctx->prealloc_y_last_tensor_used = src1;
  5826. }
  5827. }
  5828. if (quantize_y) {
  5829. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5830. ctx->prealloc_y_last_tensor_used != src1) {
  5831. if (ctx->prealloc_y_need_sync) {
  5832. ggml_vk_sync_buffers(ctx, subctx);
  5833. }
  5834. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne * ne12 * ne13, true);
  5835. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5836. ctx->prealloc_y_last_tensor_used = src1;
  5837. }
  5838. }
  5839. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5840. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5841. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5842. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5843. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5844. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5845. }
  5846. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5847. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5848. }
  5849. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5850. uint32_t groups_x = ne01;
  5851. uint32_t groups_z = 1;
  5852. if (ne01 > max_groups_x) {
  5853. groups_z = 64;
  5854. groups_x = CEIL_DIV(groups_x, groups_z);
  5855. }
  5856. // TODO: Clean up this whole sz * ne_2 * ne_3 thing, it hasn't been necessary for a long time
  5857. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5858. if (quantize_y) {
  5859. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5860. }
  5861. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5862. vk_buffer d_B = d_D;
  5863. size_t b_buf_offset = 0;
  5864. uint64_t b_sz = 0;
  5865. if (enable_bias) {
  5866. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5867. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5868. bool b_uma = false;
  5869. if (ctx->device->uma) {
  5870. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5871. b_uma = d_B != nullptr;
  5872. }
  5873. if(!b_uma) {
  5874. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5875. d_B = bias_buf_ctx->dev_buffer;
  5876. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5877. GGML_ASSERT(d_B != nullptr);
  5878. b_sz = ggml_nbytes(bias);
  5879. }
  5880. }
  5881. // compute
  5882. const vk_mat_vec_push_constants pc = {
  5883. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5884. stride_batch_x, stride_batch_y, stride_batch_d, enable_bias,
  5885. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5886. };
  5887. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5888. {
  5889. vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  5890. vk_subbuffer{ d_Y, y_buf_offset, y_sz_total },
  5891. vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23},
  5892. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  5893. },
  5894. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5895. if (x_non_contig) {
  5896. ctx->prealloc_x_need_sync = true;
  5897. }
  5898. if (y_non_contig || quantize_y) {
  5899. ctx->prealloc_y_need_sync = true;
  5900. }
  5901. }
  5902. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  5903. ggml_tensor * dst = cgraph->nodes[node_idx];
  5904. const ggml_tensor * src0 = dst->src[0];
  5905. const ggml_tensor * src1 = dst->src[1];
  5906. VK_LOG_DEBUG("ggml_vk_mul_mat_p021_f16_f32(" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  5907. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  5908. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  5909. std::cerr << "))");
  5910. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5911. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5912. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5913. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5914. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5915. const uint64_t ne00 = src0->ne[0];
  5916. const uint64_t ne01 = src0->ne[1];
  5917. const uint64_t ne02 = src0->ne[2];
  5918. // const uint64_t ne03 = src0->ne[3];
  5919. const uint64_t ne10 = src1->ne[0];
  5920. const uint64_t ne11 = src1->ne[1];
  5921. const uint64_t ne12 = src1->ne[2];
  5922. // const uint64_t ne13 = src1->ne[3];
  5923. GGML_ASSERT(ne11 == 1);
  5924. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5925. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5926. vk_buffer d_Qy = nullptr;
  5927. size_t qy_buf_offset = 0;
  5928. bool src1_uma = false;
  5929. if (ctx->device->uma) {
  5930. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5931. src1_uma = d_Qy != nullptr;
  5932. }
  5933. const uint64_t x_ne = ne00 * ne01 * ne02;
  5934. const uint64_t y_ne = ne10 * ne11 * ne12;
  5935. const uint64_t d_ne = ne01 * ne11 * ne12;
  5936. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  5937. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5938. const uint64_t d_sz = sizeof(float) * d_ne;
  5939. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5940. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5941. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5942. gqa_ratio = 1;
  5943. }
  5944. {
  5945. // Request descriptor sets
  5946. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5947. }
  5948. vk_buffer d_D;
  5949. uint64_t d_buf_offset = 0;
  5950. if (ctx->num_additional_fused_ops > 0) {
  5951. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5952. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5953. d_D = dst_buf_ctx->dev_buffer;
  5954. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5955. } else {
  5956. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5957. d_D = dst_buf_ctx->dev_buffer;
  5958. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5959. }
  5960. GGML_ASSERT(d_D != nullptr);
  5961. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5962. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5963. GGML_ASSERT(d_Qx != nullptr);
  5964. if (!src1_uma) {
  5965. d_Qy = src1_buf_ctx->dev_buffer;
  5966. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5967. GGML_ASSERT(d_Qx != nullptr);
  5968. }
  5969. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5970. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5971. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5972. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5973. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5974. vk_buffer d_B = d_D;
  5975. size_t b_buf_offset = 0;
  5976. uint64_t b_sz = 0;
  5977. if (enable_bias) {
  5978. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5979. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5980. bool b_uma = false;
  5981. if (ctx->device->uma) {
  5982. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5983. b_uma = d_B != nullptr;
  5984. }
  5985. if(!b_uma) {
  5986. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5987. d_B = bias_buf_ctx->dev_buffer;
  5988. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5989. GGML_ASSERT(d_B != nullptr);
  5990. b_sz = ggml_nbytes(bias);
  5991. }
  5992. }
  5993. // compute
  5994. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), enable_bias };
  5995. uint32_t workgroups_z = (uint32_t)ne12;
  5996. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5997. if (gqa_ratio > 1) {
  5998. workgroups_z /= gqa_ratio;
  5999. }
  6000. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6001. {
  6002. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  6003. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  6004. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  6005. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6006. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6007. }
  6008. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6009. ggml_tensor * dst = cgraph->nodes[node_idx];
  6010. const ggml_tensor * src0 = dst->src[0];
  6011. const ggml_tensor * src1 = dst->src[1];
  6012. VK_LOG_DEBUG("ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  6013. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  6014. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  6015. std::cerr << "))");
  6016. GGML_ASSERT(!ggml_is_transposed(src0));
  6017. GGML_ASSERT(!ggml_is_transposed(src1));
  6018. GGML_ASSERT(!ggml_is_permuted(src0));
  6019. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6020. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6021. const uint64_t ne00 = src0->ne[0];
  6022. const uint64_t ne01 = src0->ne[1];
  6023. const uint64_t ne02 = src0->ne[2];
  6024. const uint64_t ne03 = src0->ne[3];
  6025. const uint64_t nb01 = src0->nb[1];
  6026. const uint64_t nb02 = src0->nb[2];
  6027. const uint64_t nb12 = src1->nb[2];
  6028. // const uint64_t ne10 = src1->ne[0];
  6029. const uint64_t ne11 = src1->ne[1];
  6030. const uint64_t ne12 = src1->ne[2];
  6031. // const uint64_t ne13 = src1->ne[3];
  6032. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6033. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6034. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6035. GGML_ASSERT(ne11 == 1);
  6036. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6037. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6038. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6039. vk_buffer d_Qy = nullptr;
  6040. size_t qy_buf_offset = 0;
  6041. bool src1_uma = false;
  6042. if (ctx->device->uma) {
  6043. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6044. src1_uma = d_Qy != nullptr;
  6045. }
  6046. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  6047. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6048. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6049. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6050. const uint64_t qx_sz = ggml_nbytes(src0);
  6051. const uint64_t qy_sz = ggml_nbytes(src1);
  6052. const uint64_t d_sz = sizeof(float) * d_ne;
  6053. {
  6054. // Request descriptor sets
  6055. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6056. }
  6057. vk_buffer d_D;
  6058. uint64_t d_buf_offset = 0;
  6059. if (ctx->num_additional_fused_ops > 0) {
  6060. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6061. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6062. d_D = dst_buf_ctx->dev_buffer;
  6063. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6064. } else {
  6065. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6066. d_D = dst_buf_ctx->dev_buffer;
  6067. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6068. }
  6069. GGML_ASSERT(d_D != nullptr);
  6070. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  6071. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6072. GGML_ASSERT(d_Qx != nullptr);
  6073. if (!src1_uma) {
  6074. d_Qy = src1_buf_ctx->dev_buffer;
  6075. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6076. GGML_ASSERT(d_Qx != nullptr);
  6077. }
  6078. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6079. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  6080. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6081. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  6082. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  6083. vk_buffer d_B = d_D;
  6084. size_t b_buf_offset = 0;
  6085. uint64_t b_sz = 0;
  6086. if (enable_bias) {
  6087. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6088. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6089. bool b_uma = false;
  6090. if (ctx->device->uma) {
  6091. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6092. b_uma = d_B != nullptr;
  6093. }
  6094. if(!b_uma) {
  6095. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6096. d_B = bias_buf_ctx->dev_buffer;
  6097. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6098. GGML_ASSERT(d_B != nullptr);
  6099. b_sz = ggml_nbytes(bias);
  6100. }
  6101. }
  6102. // compute
  6103. const std::array<uint32_t, 13> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, channel_stride_y, (uint32_t)(ne12 / ne02), (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), nb03, nb13, nb23, enable_bias };
  6104. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6105. {
  6106. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  6107. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  6108. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  6109. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6110. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6111. }
  6112. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6113. ggml_tensor * dst = cgraph->nodes[node_idx];
  6114. ggml_tensor * src0 = dst->src[0];
  6115. ggml_tensor * src1 = dst->src[1];
  6116. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6117. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6118. // where the M dimension is very large.
  6119. // Split_k doesn't work with M splitting.
  6120. const size_t nbytes = ggml_nbytes(src0);
  6121. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6122. if (needs_split) {
  6123. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6124. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6125. uint32_t m_offset = 0;
  6126. while (m_offset < dst->ne[0]) {
  6127. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6128. ggml_tensor dst2 = *dst;
  6129. ggml_tensor src02 = *src0;
  6130. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6131. src02.view_src = src0->view_src ? src0->view_src : src0;
  6132. dst2.view_offs += m_offset * dst->nb[0];
  6133. src02.view_offs += m_offset * src0->nb[1];
  6134. dst2.ne[0] = cur_M_size;
  6135. src02.ne[1] = cur_M_size;
  6136. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6137. m_offset += cur_M_size;
  6138. }
  6139. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6140. // detect 0213 permutation, and batch size of 1
  6141. src0->nb[0] <= src0->nb[2] &&
  6142. src0->nb[2] <= src0->nb[1] &&
  6143. src0->nb[1] <= src0->nb[3] &&
  6144. src1->nb[0] <= src1->nb[2] &&
  6145. src1->nb[2] <= src1->nb[1] &&
  6146. src1->nb[1] <= src1->nb[3] &&
  6147. src0->ne[3] == 1 &&
  6148. src1->ne[3] == 1) {
  6149. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6150. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6151. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6152. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6153. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6154. // when ne12 and ne13 are one.
  6155. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6156. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6157. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6158. } else {
  6159. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6160. }
  6161. }
  6162. static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
  6163. VK_LOG_DEBUG("ggml_vk_mul_mat_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  6164. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  6165. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  6166. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3] << "),)");
  6167. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6168. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6169. const uint64_t ne00 = src0->ne[0];
  6170. const uint64_t ne01 = src0->ne[1];
  6171. const uint64_t ne02 = src0->ne[2];
  6172. const uint64_t ne03 = src0->ne[3];
  6173. const uint64_t ne10 = src1->ne[0];
  6174. const uint64_t ne11 = src1->ne[1];
  6175. const uint64_t ne12 = src1->ne[2];
  6176. const uint64_t ne13 = src1->ne[3];
  6177. const uint64_t nei0 = ids->ne[0];
  6178. const uint64_t nei1 = ids->ne[1];
  6179. const uint32_t nbi1 = ids->nb[1];
  6180. const uint32_t nbi2 = ids->nb[2];
  6181. const uint64_t ne20 = dst->ne[0];
  6182. const uint64_t ne21 = dst->ne[1];
  6183. const uint64_t ne22 = dst->ne[2];
  6184. const uint64_t ne23 = dst->ne[3];
  6185. const uint64_t n_as = ne02;
  6186. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6187. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6188. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6189. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6190. vk_buffer d_Qx = nullptr;
  6191. size_t qx_buf_offset = 0;
  6192. vk_buffer d_Qy = nullptr;
  6193. size_t qy_buf_offset = 0;
  6194. vk_buffer d_ids = nullptr;
  6195. size_t ids_buf_offset = 0;
  6196. bool src0_uma = false;
  6197. bool src1_uma = false;
  6198. bool ids_uma = false;
  6199. if (ctx->device->uma) {
  6200. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6201. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6202. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6203. src0_uma = d_Qx != nullptr;
  6204. src1_uma = d_Qy != nullptr;
  6205. ids_uma = d_ids != nullptr;
  6206. }
  6207. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6208. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6209. !ggml_vk_dim01_contiguous(src0);
  6210. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6211. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6212. !ggml_vk_dim01_contiguous(src1);
  6213. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6214. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6215. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6216. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  6217. // Check for mmq first
  6218. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  6219. if (mmp == nullptr) {
  6220. // Fall back to f16 dequant mul mat
  6221. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  6222. quantize_y = false;
  6223. }
  6224. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6225. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6226. if (qx_needs_dequant) {
  6227. // Fall back to dequant + f16 mulmat
  6228. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  6229. }
  6230. // Not implemented
  6231. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6232. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1, qx_needs_dequant ? f16_type : src0->type));
  6233. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6234. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6235. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6236. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6237. const uint64_t x_ne = ne01 * ne00;
  6238. const uint64_t y_ne = padded_n * ne10;
  6239. const uint64_t d_ne = ne21 * ne20;
  6240. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6241. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6242. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6243. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6244. const uint64_t ids_sz = nbi2;
  6245. const uint64_t d_sz = sizeof(float) * d_ne;
  6246. vk_pipeline to_fp16_vk_0 = nullptr;
  6247. vk_pipeline to_fp16_vk_1 = nullptr;
  6248. vk_pipeline to_q8_1 = nullptr;
  6249. if (x_non_contig) {
  6250. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6251. } else {
  6252. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6253. }
  6254. if (y_non_contig) {
  6255. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6256. } else {
  6257. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6258. }
  6259. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6260. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6261. if (quantize_y) {
  6262. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  6263. }
  6264. {
  6265. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6266. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6267. if (quantize_y) {
  6268. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  6269. }
  6270. if (
  6271. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6272. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6273. GGML_ABORT("Requested preallocation size is too large");
  6274. }
  6275. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6276. ctx->prealloc_size_x = x_sz_upd;
  6277. ggml_vk_preallocate_buffers(ctx, subctx);
  6278. }
  6279. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  6280. ctx->prealloc_size_y = y_sz_upd;
  6281. ggml_vk_preallocate_buffers(ctx, subctx);
  6282. }
  6283. // Request descriptor sets
  6284. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6285. if (qx_needs_dequant) {
  6286. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6287. }
  6288. if (qy_needs_dequant) {
  6289. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6290. }
  6291. if (quantize_y) {
  6292. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6293. }
  6294. }
  6295. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6296. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6297. GGML_ASSERT(d_D != nullptr);
  6298. vk_buffer d_X;
  6299. uint64_t x_buf_offset = 0;
  6300. vk_buffer d_Y;
  6301. uint64_t y_buf_offset = 0;
  6302. if (!src0_uma) {
  6303. d_Qx = src0_buf_ctx->dev_buffer;
  6304. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6305. GGML_ASSERT(d_Qx != nullptr);
  6306. }
  6307. if (!src1_uma) {
  6308. d_Qy = src1_buf_ctx->dev_buffer;
  6309. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6310. GGML_ASSERT(d_Qy != nullptr);
  6311. }
  6312. if (!ids_uma) {
  6313. d_ids = ids_buf_ctx->dev_buffer;
  6314. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6315. GGML_ASSERT(d_ids != nullptr);
  6316. }
  6317. if (qx_needs_dequant) {
  6318. d_X = ctx->prealloc_x;
  6319. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  6320. } else {
  6321. d_X = d_Qx;
  6322. x_buf_offset = qx_buf_offset;
  6323. GGML_ASSERT(qx_sz == x_sz);
  6324. }
  6325. if (qy_needs_dequant) {
  6326. d_Y = ctx->prealloc_y;
  6327. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  6328. } else if (quantize_y) {
  6329. d_Y = ctx->prealloc_y;
  6330. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  6331. } else {
  6332. d_Y = d_Qy;
  6333. y_buf_offset = qy_buf_offset;
  6334. GGML_ASSERT(qy_sz == y_sz);
  6335. }
  6336. if (x_non_contig || qx_needs_dequant) {
  6337. if (ctx->prealloc_x_need_sync) {
  6338. ggml_vk_sync_buffers(ctx, subctx);
  6339. }
  6340. }
  6341. if (x_non_contig) {
  6342. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6343. } else if (qx_needs_dequant) {
  6344. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6345. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6346. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  6347. ggml_vk_sync_buffers(ctx, subctx);
  6348. }
  6349. if (y_non_contig) {
  6350. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6351. ctx->prealloc_y_last_tensor_used != src1) {
  6352. if (ctx->prealloc_y_need_sync) {
  6353. ggml_vk_sync_buffers(ctx, subctx);
  6354. }
  6355. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6356. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6357. ctx->prealloc_y_last_tensor_used = src1;
  6358. }
  6359. }
  6360. if (quantize_y) {
  6361. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6362. ctx->prealloc_y_last_tensor_used != src1) {
  6363. if (ctx->prealloc_y_need_sync) {
  6364. ggml_vk_sync_buffers(ctx, subctx);
  6365. }
  6366. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne * ne12 * ne13, true);
  6367. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6368. ctx->prealloc_y_last_tensor_used = src1;
  6369. }
  6370. }
  6371. uint32_t stride_batch_x = ne00*ne01;
  6372. uint32_t stride_batch_y = ne10*ne11;
  6373. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6374. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6375. }
  6376. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6377. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6378. }
  6379. uint32_t y_sz_total = y_sz * ne12 * ne13;
  6380. if (quantize_y) {
  6381. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  6382. }
  6383. // compute
  6384. ggml_vk_matmul_id(
  6385. ctx, subctx, pipeline,
  6386. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  6387. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  6388. ne01, ne21, ne10, ne10, ne10, ne01,
  6389. stride_batch_x, stride_batch_y, ne20*ne21,
  6390. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6391. ); // NOLINT
  6392. if (x_non_contig || qx_needs_dequant) {
  6393. ctx->prealloc_x_need_sync = true;
  6394. }
  6395. if (y_non_contig) {
  6396. ctx->prealloc_y_need_sync = true;
  6397. }
  6398. }
  6399. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6400. ggml_tensor * dst = cgraph->nodes[node_idx];
  6401. ggml_tensor * src0 = dst->src[0];
  6402. ggml_tensor * src1 = dst->src[1];
  6403. ggml_tensor * ids = dst->src[2];
  6404. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  6405. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  6406. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  6407. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  6408. std::cerr << "))");
  6409. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6410. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6411. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6412. const uint64_t ne00 = src0->ne[0];
  6413. const uint64_t ne01 = src0->ne[1];
  6414. const uint64_t ne02 = src0->ne[2];
  6415. const uint64_t ne03 = src0->ne[3];
  6416. const uint64_t ne10 = src1->ne[0];
  6417. const uint64_t ne11 = src1->ne[1];
  6418. const uint64_t ne12 = src1->ne[2];
  6419. const uint64_t ne13 = src1->ne[3];
  6420. const uint64_t nei0 = ids->ne[0];
  6421. const uint64_t nei1 = ids->ne[1];
  6422. const uint64_t nbi2 = ids->nb[2];
  6423. GGML_ASSERT(nei1 == 1);
  6424. const uint64_t ne20 = dst->ne[0];
  6425. const uint64_t ne21 = dst->ne[1];
  6426. const uint64_t ne22 = dst->ne[2];
  6427. const uint64_t ne23 = dst->ne[3];
  6428. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6429. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6430. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6431. vk_buffer d_Qx = nullptr;
  6432. size_t qx_buf_offset = 0;
  6433. vk_buffer d_Qy = nullptr;
  6434. size_t qy_buf_offset = 0;
  6435. vk_buffer d_ids = nullptr;
  6436. size_t ids_buf_offset = 0;
  6437. bool src0_uma = false;
  6438. bool src1_uma = false;
  6439. bool ids_uma = false;
  6440. if (ctx->device->uma) {
  6441. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6442. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6443. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6444. src0_uma = d_Qx != nullptr;
  6445. src1_uma = d_Qy != nullptr;
  6446. ids_uma = d_ids != nullptr;
  6447. }
  6448. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6449. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6450. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6451. const bool qx_needs_dequant = x_non_contig;
  6452. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6453. // Not implemented
  6454. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6455. const uint64_t x_ne = ne01 * ne00;
  6456. const uint64_t y_ne = ne11 * ne10;
  6457. const uint64_t d_ne = ne21 * ne20;
  6458. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  6459. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6460. const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz;
  6461. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6462. const uint64_t ids_sz = nbi2;
  6463. const uint64_t d_sz = sizeof(float) * d_ne;
  6464. vk_pipeline to_fp16_vk_0 = nullptr;
  6465. vk_pipeline to_fp16_vk_1 = nullptr;
  6466. if (x_non_contig) {
  6467. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6468. }
  6469. if (y_non_contig) {
  6470. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6471. } else {
  6472. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6473. }
  6474. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6475. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6476. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6477. GGML_ASSERT(dmmv != nullptr);
  6478. {
  6479. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6480. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6481. if (
  6482. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6483. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6484. GGML_ABORT("Requested preallocation size is too large");
  6485. }
  6486. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6487. ctx->prealloc_size_x = x_sz_upd;
  6488. ggml_vk_preallocate_buffers(ctx, subctx);
  6489. }
  6490. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  6491. ctx->prealloc_size_y = y_sz_upd;
  6492. ggml_vk_preallocate_buffers(ctx, subctx);
  6493. }
  6494. // Request descriptor sets
  6495. if (qx_needs_dequant) {
  6496. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6497. }
  6498. if (qy_needs_dequant) {
  6499. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6500. }
  6501. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6502. }
  6503. vk_buffer d_D;
  6504. uint64_t d_buf_offset = 0;
  6505. if (ctx->num_additional_fused_ops > 0) {
  6506. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6507. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6508. d_D = dst_buf_ctx->dev_buffer;
  6509. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6510. } else {
  6511. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6512. d_D = dst_buf_ctx->dev_buffer;
  6513. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6514. }
  6515. GGML_ASSERT(d_D != nullptr);
  6516. vk_buffer d_X;
  6517. uint64_t x_buf_offset = 0;
  6518. vk_buffer d_Y;
  6519. uint64_t y_buf_offset = 0;
  6520. if(!src0_uma) {
  6521. d_Qx = src0_buf_ctx->dev_buffer;
  6522. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6523. GGML_ASSERT(d_Qx != nullptr);
  6524. }
  6525. if(!src1_uma) {
  6526. d_Qy = src1_buf_ctx->dev_buffer;
  6527. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6528. GGML_ASSERT(d_Qy != nullptr);
  6529. }
  6530. if(!ids_uma) {
  6531. d_ids = ids_buf_ctx->dev_buffer;
  6532. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6533. GGML_ASSERT(d_ids != nullptr);
  6534. }
  6535. if (qx_needs_dequant) {
  6536. d_X = ctx->prealloc_x;
  6537. } else {
  6538. d_X = d_Qx;
  6539. x_buf_offset = qx_buf_offset;
  6540. GGML_ASSERT(qx_sz == x_sz);
  6541. }
  6542. if (qy_needs_dequant) {
  6543. d_Y = ctx->prealloc_y;
  6544. } else {
  6545. d_Y = d_Qy;
  6546. y_buf_offset = qy_buf_offset;
  6547. GGML_ASSERT(qy_sz == y_sz);
  6548. }
  6549. if (x_non_contig) {
  6550. if (ctx->prealloc_x_need_sync) {
  6551. ggml_vk_sync_buffers(ctx, subctx);
  6552. }
  6553. }
  6554. if (x_non_contig) {
  6555. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6556. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6557. }
  6558. if (y_non_contig) {
  6559. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6560. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6561. ctx->prealloc_y_last_tensor_used != src1) {
  6562. if (ctx->prealloc_y_need_sync) {
  6563. ggml_vk_sync_buffers(ctx, subctx);
  6564. }
  6565. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6566. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6567. ctx->prealloc_y_last_tensor_used = src1;
  6568. }
  6569. }
  6570. uint32_t stride_batch_y = ne10*ne11;
  6571. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6572. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6573. }
  6574. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6575. uint32_t groups_x = ne01;
  6576. uint32_t groups_z = 1;
  6577. if (ne01 > max_groups_x) {
  6578. groups_z = 64;
  6579. groups_x = CEIL_DIV(groups_x, groups_z);
  6580. }
  6581. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  6582. vk_buffer d_B = d_D;
  6583. size_t b_buf_offset = 0;
  6584. uint64_t b_sz = 0;
  6585. if (enable_bias) {
  6586. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6587. bool b_uma = false;
  6588. if (ctx->device->uma) {
  6589. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6590. b_uma = d_B != nullptr;
  6591. }
  6592. if(!b_uma) {
  6593. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6594. d_B = bias_buf_ctx->dev_buffer;
  6595. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6596. GGML_ASSERT(d_B != nullptr);
  6597. b_sz = ggml_nbytes(bias);
  6598. }
  6599. }
  6600. // compute
  6601. const vk_mat_vec_id_push_constants pc = {
  6602. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6603. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  6604. enable_bias,
  6605. (uint32_t)nei0, (uint32_t)ne11,
  6606. };
  6607. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6608. {
  6609. vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  6610. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  6611. vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23},
  6612. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6613. vk_subbuffer{ d_ids, ids_buf_offset, ids_sz },
  6614. },
  6615. pc, { groups_x, (uint32_t)nei0, groups_z });
  6616. if (x_non_contig) {
  6617. ctx->prealloc_x_need_sync = true;
  6618. }
  6619. if (y_non_contig) {
  6620. ctx->prealloc_y_need_sync = true;
  6621. }
  6622. }
  6623. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6624. ggml_tensor * dst = cgraph->nodes[node_idx];
  6625. ggml_tensor * src0 = dst->src[0];
  6626. ggml_tensor * src2 = dst->src[2];
  6627. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6628. }
  6629. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6630. ggml_tensor * dst = cgraph->nodes[node_idx];
  6631. ggml_tensor * src0 = dst->src[0];
  6632. ggml_tensor * src1 = dst->src[1];
  6633. ggml_tensor * src2 = dst->src[2];
  6634. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6635. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6636. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6637. } else {
  6638. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6639. }
  6640. }
  6641. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6642. // Needs to be kept up to date on shader changes
  6643. GGML_UNUSED(hsv);
  6644. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6645. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6646. const uint32_t Bc = scalar_flash_attention_Bc;
  6647. const uint32_t tmpsh = wg_size * sizeof(float);
  6648. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6649. const uint32_t masksh = Bc * Br * sizeof(float);
  6650. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6651. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6652. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6653. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6654. return supported;
  6655. }
  6656. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6657. // Needs to be kept up to date on shader changes
  6658. GGML_UNUSED(hsv);
  6659. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6660. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6661. const uint32_t Bc = scalar_flash_attention_Bc;
  6662. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6663. const uint32_t acctype = f32acc ? 4 : 2;
  6664. const uint32_t f16vec4 = 8;
  6665. const uint32_t tmpsh = wg_size * sizeof(float);
  6666. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6667. const uint32_t qstride = hsk_pad / 4 + 2;
  6668. const uint32_t Qf = Br * qstride * f16vec4;
  6669. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6670. const uint32_t sfsh = Bc * sfshstride * acctype;
  6671. const uint32_t kshstride = hsk_pad / 4 + 2;
  6672. const uint32_t ksh = Bc * kshstride * f16vec4;
  6673. const uint32_t slope = Br * sizeof(float);
  6674. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6675. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6676. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6677. return supported;
  6678. }
  6679. static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst) {
  6680. VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3];
  6681. std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3];
  6682. std::cerr << "), (" << v << ", name=" << v->name << ", type=" << v->type << ", ne0=" << v->ne[0] << ", ne1=" << v->ne[1] << ", ne2=" << v->ne[2] << ", ne3=" << v->ne[3] << ", nb0=" << v->nb[0] << ", nb1=" << v->nb[1] << ", nb2=" << v->nb[2] << ", nb3=" << v->nb[3];
  6683. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  6684. if (sinks) {
  6685. std::cerr << "), (" << sinks << ", name=" << sinks->name << ", type=" << sinks->type << ", ne0=" << sinks->ne[0] << ", ne1=" << sinks->ne[1] << ", ne2=" << sinks->ne[2] << ", ne3=" << sinks->ne[3] << ", nb0=" << sinks->nb[0] << ", nb1=" << sinks->nb[1] << ", nb2=" << sinks->nb[2] << ", nb3=" << sinks->nb[3];
  6686. }
  6687. std::cerr << "))");
  6688. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6689. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6690. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6691. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6692. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6693. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6694. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6695. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6696. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6697. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6698. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6699. const uint32_t HSK = nek0;
  6700. const uint32_t HSV = nev0;
  6701. uint32_t N = neq1;
  6702. const uint32_t KV = nek1;
  6703. GGML_ASSERT(ne0 == HSV);
  6704. GGML_ASSERT(ne2 == N);
  6705. // input tensor rows must be contiguous
  6706. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6707. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6708. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6709. GGML_ASSERT(neq0 == HSK);
  6710. GGML_ASSERT(neq1 == N);
  6711. GGML_ASSERT(nev1 == nek1);
  6712. // dst cannot be transposed or permuted
  6713. GGML_ASSERT(nb0 == sizeof(float));
  6714. GGML_ASSERT(nb0 <= nb1);
  6715. GGML_ASSERT(nb1 <= nb2);
  6716. GGML_ASSERT(nb2 <= nb3);
  6717. assert(dst->type == GGML_TYPE_F32);
  6718. assert(q->type == GGML_TYPE_F32);
  6719. assert(k->type == v->type);
  6720. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6721. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6722. if (path == FA_COOPMAT1) {
  6723. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6724. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6725. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6726. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6727. path = FA_SCALAR;
  6728. }
  6729. }
  6730. uint32_t gqa_ratio = 1;
  6731. uint32_t qk_ratio = neq2 / nek2;
  6732. uint32_t workgroups_x = (uint32_t)neq1;
  6733. uint32_t workgroups_y = (uint32_t)neq2;
  6734. uint32_t workgroups_z = (uint32_t)neq3;
  6735. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6736. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6737. uint32_t max_gqa;
  6738. switch (path) {
  6739. case FA_SCALAR:
  6740. case FA_COOPMAT1:
  6741. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6742. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6743. break;
  6744. case FA_COOPMAT2:
  6745. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6746. break;
  6747. default:
  6748. GGML_ASSERT(0);
  6749. }
  6750. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6751. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6752. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6753. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6754. // and change addressing calculations to index Q's dimension 2.
  6755. gqa_ratio = qk_ratio;
  6756. N = gqa_ratio;
  6757. workgroups_y /= N;
  6758. }
  6759. bool small_rows = N <= get_fa_num_small_rows(path);
  6760. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6761. // So use scalar instead.
  6762. if (small_rows && path == FA_COOPMAT1) {
  6763. path = FA_SCALAR;
  6764. }
  6765. // scalar is faster than coopmat2 when N==1
  6766. if (N == 1 && path == FA_COOPMAT2) {
  6767. path = FA_SCALAR;
  6768. }
  6769. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6770. if (path == FA_SCALAR &&
  6771. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6772. small_rows = true;
  6773. }
  6774. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6775. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6776. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6777. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6778. if (k->type == GGML_TYPE_F32) {
  6779. k_stride /= 4;
  6780. }
  6781. if (v->type == GGML_TYPE_F32) {
  6782. v_stride /= 4;
  6783. }
  6784. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6785. bool aligned = (KV % alignment) == 0 &&
  6786. // the "aligned" shader variant will forcibly align strides, for performance
  6787. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6788. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6789. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6790. aligned = false;
  6791. }
  6792. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6793. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6794. vk_pipeline pipeline = nullptr;
  6795. {
  6796. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6797. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6798. auto it = pipelines.find(fa_pipeline_state);
  6799. if (it != pipelines.end()) {
  6800. pipeline = it->second;
  6801. } else {
  6802. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6803. }
  6804. }
  6805. assert(pipeline);
  6806. uint32_t split_kv = KV;
  6807. uint32_t split_k = 1;
  6808. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6809. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6810. // Try to use split_k when KV is large enough to be worth the overhead
  6811. if (workgroups_x == 1 && shader_core_count > 0) {
  6812. // Try to run two workgroups per SM.
  6813. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6814. if (split_k > 1) {
  6815. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6816. // of "align", so recompute split_k based on that.
  6817. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6818. split_k = CEIL_DIV(KV, split_kv);
  6819. workgroups_x = split_k;
  6820. }
  6821. }
  6822. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6823. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6824. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6825. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6826. GGML_ABORT("Requested preallocation size is too large");
  6827. }
  6828. if (ctx->prealloc_size_split_k < split_k_size) {
  6829. ctx->prealloc_size_split_k = split_k_size;
  6830. ggml_vk_preallocate_buffers(ctx, subctx);
  6831. }
  6832. {
  6833. // Request descriptor sets
  6834. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6835. if (split_k > 1) {
  6836. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6837. }
  6838. }
  6839. float scale = 1.0f;
  6840. float max_bias = 0.0f;
  6841. float logit_softcap = 0.0f;
  6842. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6843. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6844. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6845. if (logit_softcap != 0) {
  6846. scale /= logit_softcap;
  6847. }
  6848. const uint32_t n_head_kv = neq2;
  6849. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6850. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6851. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6852. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  6853. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  6854. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  6855. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  6856. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  6857. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  6858. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6859. const vk_flash_attn_push_constants pc = { N, KV,
  6860. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6861. (uint32_t)neq2, (uint32_t)neq3,
  6862. (uint32_t)nek2, (uint32_t)nek3,
  6863. (uint32_t)nev2, (uint32_t)nev3,
  6864. nem1, nem2, nem3,
  6865. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6866. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6867. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6868. scale, max_bias, logit_softcap,
  6869. mask_n_head_log2, m0, m1,
  6870. gqa_ratio, split_kv, split_k };
  6871. if (split_k > 1) {
  6872. if (ctx->prealloc_split_k_need_sync) {
  6873. ggml_vk_sync_buffers(ctx, subctx);
  6874. }
  6875. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6876. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6877. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  6878. // We only use split_k when group query attention is enabled, which means
  6879. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6880. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6881. // cancel out the divide by wg_denoms[0].
  6882. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6883. ggml_vk_sync_buffers(ctx, subctx);
  6884. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6885. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6886. {split_k_buf, sinks_buf, dst_buf},
  6887. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6888. ctx->prealloc_split_k_need_sync = true;
  6889. } else {
  6890. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6891. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  6892. pc, { workgroups_x, workgroups_y, workgroups_z });
  6893. }
  6894. }
  6895. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6896. const ggml_tensor *src0 = dst->src[0];
  6897. const ggml_tensor *src1 = dst->src[1];
  6898. // src0 - kernel: [KW, KH, Cin, Cout]
  6899. // src1 - input: [W, H, Cin, N]
  6900. // dst - result: [OW, OH, Cout, N]
  6901. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6902. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6903. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6904. };
  6905. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6906. int64_t W = src1->ne[0];
  6907. int64_t H = src1->ne[1];
  6908. int64_t KW = src0->ne[0];
  6909. int64_t KH = src0->ne[1];
  6910. int64_t Cout = src0->ne[3];
  6911. int64_t N = src1->ne[3];
  6912. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6913. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6914. int64_t NPQ = N * OW * OH;
  6915. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6916. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6917. return elements;
  6918. }
  6919. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6920. const ggml_tensor *src0 = dst->src[0];
  6921. const ggml_tensor *src1 = dst->src[1];
  6922. // src0 - kernel: [KW, KH, Cout, Cin]
  6923. // src1 - input: [W, H, Cin, N]
  6924. // dst - result: [OW, OH, Cout, N]
  6925. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6926. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6927. };
  6928. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6929. int64_t W = src1->ne[0];
  6930. int64_t H = src1->ne[1];
  6931. int64_t KW = src0->ne[0];
  6932. int64_t KH = src0->ne[1];
  6933. int64_t Cout = src0->ne[2];
  6934. int64_t N = src1->ne[3];
  6935. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6936. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6937. int64_t NPQ = N * OW * OH;
  6938. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6939. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6940. return elements;
  6941. }
  6942. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) {
  6943. switch (op) {
  6944. case GGML_OP_GET_ROWS:
  6945. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6946. if (dst->type == GGML_TYPE_F16) {
  6947. return ctx->device->pipeline_get_rows[src0->type];
  6948. }
  6949. if (dst->type == GGML_TYPE_F32) {
  6950. return ctx->device->pipeline_get_rows_f32[src0->type];
  6951. }
  6952. return nullptr;
  6953. case GGML_OP_ACC:
  6954. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6955. return ctx->device->pipeline_acc_f32;
  6956. }
  6957. return nullptr;
  6958. case GGML_OP_ADD:
  6959. case GGML_OP_SUB:
  6960. case GGML_OP_MUL:
  6961. case GGML_OP_DIV:
  6962. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6963. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6964. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6965. return nullptr;
  6966. }
  6967. switch (op) {
  6968. case GGML_OP_ADD:
  6969. {
  6970. if (ctx->num_additional_fused_ops > 0) {
  6971. if (ctx->do_add_rms_partials) {
  6972. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6973. } else {
  6974. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6975. }
  6976. }
  6977. if (ctx->do_add_rms_partials) {
  6978. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6979. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6980. } else {
  6981. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6982. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6983. }
  6984. }
  6985. case GGML_OP_SUB:
  6986. {
  6987. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6988. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6989. }
  6990. case GGML_OP_MUL:
  6991. {
  6992. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6993. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6994. }
  6995. case GGML_OP_DIV:
  6996. {
  6997. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6998. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6999. }
  7000. default:
  7001. break;
  7002. }
  7003. return nullptr;
  7004. case GGML_OP_ADD_ID:
  7005. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7006. return ctx->device->pipeline_add_id_f32;
  7007. }
  7008. return nullptr;
  7009. case GGML_OP_CONCAT:
  7010. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7011. return ctx->device->pipeline_concat_f32;
  7012. }
  7013. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7014. return ctx->device->pipeline_concat_f16;
  7015. }
  7016. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7017. return ctx->device->pipeline_concat_i32;
  7018. }
  7019. return nullptr;
  7020. case GGML_OP_UPSCALE:
  7021. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7022. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  7023. switch (mode) {
  7024. case GGML_SCALE_MODE_NEAREST:
  7025. return ctx->device->pipeline_upscale_nearest_f32;
  7026. case GGML_SCALE_MODE_BILINEAR:
  7027. return ctx->device->pipeline_upscale_bilinear_f32;
  7028. default:
  7029. return nullptr;
  7030. }
  7031. }
  7032. return nullptr;
  7033. case GGML_OP_SCALE:
  7034. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7035. return ctx->device->pipeline_scale_f32;
  7036. }
  7037. return nullptr;
  7038. case GGML_OP_SQR:
  7039. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7040. return ctx->device->pipeline_sqr_f32;
  7041. }
  7042. return nullptr;
  7043. case GGML_OP_SQRT:
  7044. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7045. return ctx->device->pipeline_sqrt_f32;
  7046. }
  7047. return nullptr;
  7048. case GGML_OP_SIN:
  7049. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7050. return ctx->device->pipeline_sin_f32;
  7051. }
  7052. return nullptr;
  7053. case GGML_OP_COS:
  7054. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7055. return ctx->device->pipeline_cos_f32;
  7056. }
  7057. return nullptr;
  7058. case GGML_OP_CLAMP:
  7059. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7060. return ctx->device->pipeline_clamp_f32;
  7061. }
  7062. return nullptr;
  7063. case GGML_OP_PAD:
  7064. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7065. return ctx->device->pipeline_pad_f32;
  7066. }
  7067. return nullptr;
  7068. case GGML_OP_ROLL:
  7069. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7070. return ctx->device->pipeline_roll_f32;
  7071. }
  7072. return nullptr;
  7073. case GGML_OP_REPEAT:
  7074. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7075. return ctx->device->pipeline_repeat_f32;
  7076. }
  7077. return nullptr;
  7078. case GGML_OP_REPEAT_BACK:
  7079. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7080. return ctx->device->pipeline_repeat_back_f32;
  7081. }
  7082. return nullptr;
  7083. case GGML_OP_CPY:
  7084. case GGML_OP_CONT:
  7085. case GGML_OP_DUP:
  7086. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7087. case GGML_OP_SET_ROWS:
  7088. if (src1->type == GGML_TYPE_I64) {
  7089. return ctx->device->pipeline_set_rows_i64[dst->type];
  7090. } else {
  7091. return ctx->device->pipeline_set_rows_i32[dst->type];
  7092. }
  7093. case GGML_OP_SILU_BACK:
  7094. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7095. return ctx->device->pipeline_silu_back_f32;
  7096. }
  7097. return nullptr;
  7098. case GGML_OP_NORM:
  7099. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7100. return ctx->device->pipeline_norm_f32;
  7101. }
  7102. return nullptr;
  7103. case GGML_OP_GROUP_NORM:
  7104. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7105. return ctx->device->pipeline_group_norm_f32;
  7106. }
  7107. return nullptr;
  7108. case GGML_OP_RMS_NORM:
  7109. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7110. if (ctx->do_add_rms_partials) {
  7111. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7112. } else {
  7113. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7114. }
  7115. }
  7116. return nullptr;
  7117. case GGML_OP_RMS_NORM_BACK:
  7118. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7119. return ctx->device->pipeline_rms_norm_back_f32;
  7120. }
  7121. return nullptr;
  7122. case GGML_OP_L2_NORM:
  7123. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7124. return ctx->device->pipeline_l2_norm_f32;
  7125. }
  7126. return nullptr;
  7127. case GGML_OP_UNARY:
  7128. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7129. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7130. (src0->type != dst->type)) {
  7131. return nullptr;
  7132. }
  7133. switch (ggml_get_unary_op(dst)) {
  7134. case GGML_UNARY_OP_EXP:
  7135. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7136. case GGML_UNARY_OP_SILU:
  7137. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7138. case GGML_UNARY_OP_GELU:
  7139. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7140. case GGML_UNARY_OP_GELU_ERF:
  7141. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7142. case GGML_UNARY_OP_GELU_QUICK:
  7143. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7144. case GGML_UNARY_OP_RELU:
  7145. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7146. case GGML_UNARY_OP_TANH:
  7147. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7148. case GGML_UNARY_OP_SIGMOID:
  7149. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7150. case GGML_UNARY_OP_HARDSIGMOID:
  7151. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7152. case GGML_UNARY_OP_HARDSWISH:
  7153. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7154. default:
  7155. break;
  7156. }
  7157. return nullptr;
  7158. case GGML_OP_GLU:
  7159. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7160. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7161. (src0->type != dst->type)) {
  7162. return nullptr;
  7163. }
  7164. switch (ggml_get_glu_op(dst)) {
  7165. case GGML_GLU_OP_GEGLU:
  7166. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7167. case GGML_GLU_OP_REGLU:
  7168. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7169. case GGML_GLU_OP_SWIGLU:
  7170. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7171. case GGML_GLU_OP_SWIGLU_OAI:
  7172. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7173. case GGML_GLU_OP_GEGLU_ERF:
  7174. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7175. case GGML_GLU_OP_GEGLU_QUICK:
  7176. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7177. default:
  7178. break;
  7179. }
  7180. return nullptr;
  7181. case GGML_OP_DIAG_MASK_INF:
  7182. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7183. return ctx->device->pipeline_diag_mask_inf_f32;
  7184. }
  7185. return nullptr;
  7186. case GGML_OP_SOFT_MAX:
  7187. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7188. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7189. if (ctx->num_additional_fused_ops) {
  7190. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7191. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7192. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7193. return ctx->device->pipeline_topk_moe[idx][mode];
  7194. }
  7195. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7196. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7197. }
  7198. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7199. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7200. }
  7201. return nullptr;
  7202. case GGML_OP_SOFT_MAX_BACK:
  7203. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7204. return ctx->device->pipeline_soft_max_back_f32;
  7205. }
  7206. return nullptr;
  7207. case GGML_OP_ROPE:
  7208. case GGML_OP_ROPE_BACK:
  7209. {
  7210. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7211. const int mode = ((const int32_t *) rope->op_params)[2];
  7212. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7213. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7214. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7215. if (is_neox) {
  7216. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7217. return ctx->device->pipeline_rope_neox_f32;
  7218. }
  7219. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7220. return ctx->device->pipeline_rope_neox_f32_f16;
  7221. }
  7222. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7223. return ctx->device->pipeline_rope_neox_f16;
  7224. }
  7225. } else if (is_mrope && !is_vision) {
  7226. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7227. return ctx->device->pipeline_rope_multi_f32;
  7228. }
  7229. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7230. return ctx->device->pipeline_rope_multi_f16;
  7231. }
  7232. } else if (is_vision) {
  7233. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7234. return ctx->device->pipeline_rope_vision_f32;
  7235. }
  7236. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7237. return ctx->device->pipeline_rope_vision_f16;
  7238. }
  7239. } else {
  7240. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7241. return ctx->device->pipeline_rope_norm_f32;
  7242. }
  7243. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7244. return ctx->device->pipeline_rope_norm_f32_f16;
  7245. }
  7246. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7247. return ctx->device->pipeline_rope_norm_f16;
  7248. }
  7249. }
  7250. return nullptr;
  7251. }
  7252. case GGML_OP_ARGSORT:
  7253. if (ctx->num_additional_fused_ops) {
  7254. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7255. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7256. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7257. return ctx->device->pipeline_topk_moe[idx][mode];
  7258. }
  7259. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7260. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7261. return ctx->device->pipeline_argsort_f32[idx];
  7262. }
  7263. return nullptr;
  7264. case GGML_OP_SUM:
  7265. case GGML_OP_SUM_ROWS:
  7266. case GGML_OP_MEAN:
  7267. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7268. return ctx->device->pipeline_sum_rows_f32;
  7269. }
  7270. return nullptr;
  7271. case GGML_OP_ARGMAX:
  7272. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7273. return ctx->device->pipeline_argmax_f32;
  7274. }
  7275. return nullptr;
  7276. case GGML_OP_COUNT_EQUAL:
  7277. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7278. return ctx->device->pipeline_count_equal_i32;
  7279. }
  7280. return nullptr;
  7281. case GGML_OP_IM2COL:
  7282. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7283. return ctx->device->pipeline_im2col_f32;
  7284. }
  7285. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7286. return ctx->device->pipeline_im2col_f32_f16;
  7287. }
  7288. return nullptr;
  7289. case GGML_OP_IM2COL_3D:
  7290. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7291. return ctx->device->pipeline_im2col_3d_f32;
  7292. }
  7293. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7294. return ctx->device->pipeline_im2col_3d_f32_f16;
  7295. }
  7296. return nullptr;
  7297. case GGML_OP_TIMESTEP_EMBEDDING:
  7298. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7299. return ctx->device->pipeline_timestep_embedding_f32;
  7300. }
  7301. return nullptr;
  7302. case GGML_OP_CONV_TRANSPOSE_1D:
  7303. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7304. return ctx->device->pipeline_conv_transpose_1d_f32;
  7305. }
  7306. return nullptr;
  7307. case GGML_OP_POOL_2D:
  7308. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7309. return ctx->device->pipeline_pool2d_f32;
  7310. }
  7311. return nullptr;
  7312. case GGML_OP_RWKV_WKV6:
  7313. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7314. return ctx->device->pipeline_rwkv_wkv6_f32;
  7315. }
  7316. return nullptr;
  7317. case GGML_OP_RWKV_WKV7:
  7318. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7319. return ctx->device->pipeline_rwkv_wkv7_f32;
  7320. }
  7321. return nullptr;
  7322. case GGML_OP_SSM_SCAN:
  7323. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7324. const uint32_t d_state = src0->ne[0];
  7325. if (d_state == 128) {
  7326. return ctx->device->pipeline_ssm_scan_f32_d128;
  7327. } else if (d_state == 256) {
  7328. return ctx->device->pipeline_ssm_scan_f32_d256;
  7329. }
  7330. }
  7331. return nullptr;
  7332. case GGML_OP_SSM_CONV:
  7333. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7334. return ctx->device->pipeline_ssm_conv_f32;
  7335. }
  7336. return nullptr;
  7337. case GGML_OP_OPT_STEP_ADAMW:
  7338. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7339. return ctx->device->pipeline_opt_step_adamw_f32;
  7340. }
  7341. return nullptr;
  7342. case GGML_OP_OPT_STEP_SGD:
  7343. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7344. return ctx->device->pipeline_opt_step_sgd_f32;
  7345. }
  7346. return nullptr;
  7347. case GGML_OP_LEAKY_RELU:
  7348. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7349. return ctx->device->pipeline_leaky_relu_f32;
  7350. }
  7351. return nullptr;
  7352. case GGML_OP_CONV_2D:
  7353. case GGML_OP_CONV_TRANSPOSE_2D:
  7354. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7355. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7356. std::array<uint32_t, 3> elements;
  7357. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7358. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7359. vk_conv_shapes shape;
  7360. uint32_t tiles[CONV_SHAPE_COUNT];
  7361. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7362. tiles[i] = CEIL_DIV(elements[0], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[0]) * CEIL_DIV(elements[1], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[1]);
  7363. }
  7364. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7365. // so small convolutions will still choose a smaller tile.
  7366. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7367. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7368. shape = CONV_SHAPE_128x128;
  7369. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7370. shape = CONV_SHAPE_32x256;
  7371. } else {
  7372. shape = CONV_SHAPE_64x32;
  7373. }
  7374. if (op == GGML_OP_CONV_2D) {
  7375. if (src0->type == GGML_TYPE_F32) {
  7376. return ctx->device->pipeline_conv2d_f32[shape];
  7377. } else if (src0->type == GGML_TYPE_F16) {
  7378. return ctx->device->pipeline_conv2d_f16_f32[shape];
  7379. }
  7380. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7381. if (src0->type == GGML_TYPE_F32) {
  7382. return ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7383. } else if (src0->type == GGML_TYPE_F16) {
  7384. return ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7385. }
  7386. }
  7387. }
  7388. return nullptr;
  7389. case GGML_OP_CONV_2D_DW:
  7390. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7391. if (ggml_is_contiguous(src1)) {
  7392. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7393. } else if (ggml_is_contiguous_channels(src1)) {
  7394. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7395. }
  7396. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7397. if (ggml_is_contiguous(src1)) {
  7398. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7399. } else if (ggml_is_contiguous_channels(src1)) {
  7400. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7401. }
  7402. }
  7403. return nullptr;
  7404. default:
  7405. return nullptr;
  7406. }
  7407. GGML_UNUSED(src2);
  7408. }
  7409. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7410. switch (op) {
  7411. case GGML_OP_CPY:
  7412. case GGML_OP_GET_ROWS:
  7413. case GGML_OP_ADD:
  7414. case GGML_OP_SUB:
  7415. case GGML_OP_MUL:
  7416. case GGML_OP_DIV:
  7417. case GGML_OP_ADD_ID:
  7418. case GGML_OP_CONCAT:
  7419. case GGML_OP_UPSCALE:
  7420. case GGML_OP_SQR:
  7421. case GGML_OP_SQRT:
  7422. case GGML_OP_SIN:
  7423. case GGML_OP_COS:
  7424. case GGML_OP_CLAMP:
  7425. case GGML_OP_PAD:
  7426. case GGML_OP_REPEAT:
  7427. case GGML_OP_REPEAT_BACK:
  7428. case GGML_OP_ROPE:
  7429. case GGML_OP_RMS_NORM:
  7430. case GGML_OP_CONV_2D_DW:
  7431. case GGML_OP_IM2COL:
  7432. case GGML_OP_IM2COL_3D:
  7433. case GGML_OP_SET_ROWS:
  7434. case GGML_OP_SUM:
  7435. case GGML_OP_SUM_ROWS:
  7436. case GGML_OP_MEAN:
  7437. return true;
  7438. default:
  7439. return false;
  7440. }
  7441. }
  7442. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  7443. {
  7444. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  7445. }
  7446. template <typename T> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, T &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7447. GGML_UNUSED(p);
  7448. GGML_UNUSED(src0);
  7449. GGML_UNUSED(src1);
  7450. GGML_UNUSED(src2);
  7451. GGML_UNUSED(src3);
  7452. GGML_UNUSED(dst);
  7453. static_assert(!std::is_const<T>::value, "unexpected type");
  7454. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7455. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7456. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7457. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  7458. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7459. }
  7460. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_unary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7461. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7462. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7463. p.misalign_offsets = (a_offset << 16) | d_offset;
  7464. GGML_UNUSED(src1);
  7465. GGML_UNUSED(src2);
  7466. GGML_UNUSED(src3);
  7467. }
  7468. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_sum_rows_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7469. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7470. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7471. p.misalign_offsets = (a_offset << 16) | d_offset;
  7472. GGML_UNUSED(src1);
  7473. GGML_UNUSED(src2);
  7474. GGML_UNUSED(src3);
  7475. }
  7476. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_pad_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7477. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7478. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7479. p.misalign_offsets = (a_offset << 16) | d_offset;
  7480. GGML_UNUSED(src1);
  7481. GGML_UNUSED(src2);
  7482. GGML_UNUSED(src3);
  7483. }
  7484. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_im2col_3d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7485. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7486. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7487. p.misalign_offsets = (a_offset << 16) | d_offset;
  7488. GGML_UNUSED(src0);
  7489. GGML_UNUSED(src2);
  7490. GGML_UNUSED(src3);
  7491. }
  7492. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_binary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7493. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7494. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7495. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7496. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7497. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7498. GGML_UNUSED(src2);
  7499. GGML_UNUSED(src3);
  7500. }
  7501. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_upscale_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7502. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7503. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7504. p.a_offset = a_offset;
  7505. p.d_offset = d_offset;
  7506. GGML_UNUSED(src1);
  7507. GGML_UNUSED(src2);
  7508. GGML_UNUSED(src3);
  7509. }
  7510. template<typename PC>
  7511. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst, ggml_op op, PC&& pc) {
  7512. VK_LOG_DEBUG("ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  7513. if (src1 != nullptr) {
  7514. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  7515. }
  7516. if (src2 != nullptr) {
  7517. std::cerr << "), (" << src2 << ", name=" << src2->name << ", type=" << src2->type << ", ne0=" << src2->ne[0] << ", ne1=" << src2->ne[1] << ", ne2=" << src2->ne[2] << ", ne3=" << src2->ne[3] << ", nb0=" << src2->nb[0] << ", nb1=" << src2->nb[1] << ", nb2=" << src2->nb[2] << ", nb3=" << src2->nb[3];
  7518. }
  7519. if (src3 != nullptr) {
  7520. std::cerr << "), (" << src3 << ", name=" << src3->name << ", type=" << src3->type << ", ne0=" << src3->ne[0] << ", ne1=" << src3->ne[1] << ", ne2=" << src3->ne[2] << ", ne3=" << src3->ne[3] << ", nb0=" << src3->nb[0] << ", nb1=" << src3->nb[1] << ", nb2=" << src3->nb[2] << ", nb3=" << src3->nb[3];
  7521. }
  7522. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  7523. std::cerr << "), " << ggml_op_name(op) << ")");
  7524. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7525. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7526. GGML_ASSERT(dst->buffer != nullptr);
  7527. const uint64_t ne00 = src0->ne[0];
  7528. const uint64_t ne01 = src0->ne[1];
  7529. const uint64_t ne02 = src0->ne[2];
  7530. const uint64_t ne03 = src0->ne[3];
  7531. const bool use_src1 = src1 != nullptr;
  7532. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7533. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7534. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7535. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7536. const bool use_src2 = src2 != nullptr;
  7537. const bool use_src3 = src3 != nullptr;
  7538. init_pushconst_fastdiv(pc);
  7539. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7540. if (pipeline == nullptr) {
  7541. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7542. if (src1 != nullptr) {
  7543. std::cerr << " and " << ggml_type_name(src1->type);
  7544. }
  7545. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7546. GGML_ABORT("fatal error");
  7547. }
  7548. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7549. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7550. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, op_supports_incontiguous);
  7551. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, op_supports_incontiguous) : vk_subbuffer{};
  7552. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, op_supports_incontiguous) : vk_subbuffer{};
  7553. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, op_supports_incontiguous) : vk_subbuffer{};
  7554. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, op_supports_incontiguous);
  7555. // Compute misalignment offset for descriptors and store it in in push constants.
  7556. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7557. std::array<uint32_t, 3> elements;
  7558. // Single call if dimension 2 is contiguous
  7559. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7560. switch (op) {
  7561. case GGML_OP_NORM:
  7562. case GGML_OP_RMS_NORM_BACK:
  7563. case GGML_OP_L2_NORM:
  7564. case GGML_OP_SOFT_MAX:
  7565. case GGML_OP_SOFT_MAX_BACK:
  7566. case GGML_OP_SUM_ROWS:
  7567. case GGML_OP_MEAN:
  7568. case GGML_OP_ARGMAX:
  7569. {
  7570. const uint32_t nr = ggml_nrows(src0);
  7571. if (nr > 262144) {
  7572. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7573. } else if (nr > 512) {
  7574. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7575. } else {
  7576. elements = { nr, 1, 1 };
  7577. }
  7578. } break;
  7579. case GGML_OP_RMS_NORM:
  7580. if (ctx->do_add_rms_partials) {
  7581. // Run one element per thread, 128 threads per workgroup
  7582. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7583. } else {
  7584. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7585. }
  7586. break;
  7587. case GGML_OP_SUM:
  7588. // We use GGML_OP_SUM_ROWS with 1 row.
  7589. elements = { 1, 1, 1 };
  7590. break;
  7591. case GGML_OP_GROUP_NORM:
  7592. {
  7593. const uint32_t num_groups = dst->op_params[0];
  7594. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7595. } break;
  7596. case GGML_OP_DIAG_MASK_INF:
  7597. case GGML_OP_ROPE:
  7598. case GGML_OP_ROPE_BACK:
  7599. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7600. break;
  7601. case GGML_OP_GET_ROWS:
  7602. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7603. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7604. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7605. break;
  7606. case GGML_OP_ARGSORT:
  7607. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7608. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7609. break;
  7610. case GGML_OP_IM2COL:
  7611. {
  7612. const bool is_2D = dst->op_params[6] == 1;
  7613. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7614. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7615. const uint32_t KW = src0->ne[0];
  7616. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7617. const uint32_t OW = dst->ne[1];
  7618. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7619. elements = { OW * KW * KH, OH, batch * IC };
  7620. } break;
  7621. case GGML_OP_IM2COL_3D:
  7622. {
  7623. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7624. const uint32_t N = ne13 / IC;
  7625. const uint32_t KD = ne02;
  7626. const uint32_t KH = ne01;
  7627. const uint32_t KW = ne00;
  7628. const uint32_t OD = dst->ne[3] / N;
  7629. const uint32_t OH = dst->ne[2];
  7630. const uint32_t OW = dst->ne[1];
  7631. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7632. const uint32_t N_OD_OH = N*OD*OH;
  7633. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7634. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7635. } break;
  7636. case GGML_OP_TIMESTEP_EMBEDDING:
  7637. {
  7638. const uint32_t dim = dst->op_params[0];
  7639. uint32_t half_ceil = (dim + 1) / 2;
  7640. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7641. } break;
  7642. case GGML_OP_CONV_TRANSPOSE_1D:
  7643. {
  7644. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7645. } break;
  7646. case GGML_OP_POOL_2D:
  7647. {
  7648. const uint32_t N = dst->ne[3];
  7649. const uint32_t OC = dst->ne[2];
  7650. const uint32_t OH = dst->ne[1];
  7651. const uint32_t OW = dst->ne[0];
  7652. elements = { N * OC * OH * OW, 1, 1};
  7653. } break;
  7654. case GGML_OP_CONV_2D:
  7655. {
  7656. elements = ggml_vk_get_conv_elements(dst);
  7657. } break;
  7658. case GGML_OP_CONV_TRANSPOSE_2D:
  7659. {
  7660. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7661. } break;
  7662. case GGML_OP_ADD:
  7663. case GGML_OP_SUB:
  7664. case GGML_OP_DIV:
  7665. case GGML_OP_MUL:
  7666. case GGML_OP_SCALE:
  7667. case GGML_OP_SQR:
  7668. case GGML_OP_SQRT:
  7669. case GGML_OP_SIN:
  7670. case GGML_OP_COS:
  7671. case GGML_OP_CLAMP:
  7672. case GGML_OP_PAD:
  7673. case GGML_OP_ROLL:
  7674. case GGML_OP_REPEAT:
  7675. case GGML_OP_REPEAT_BACK:
  7676. case GGML_OP_CPY:
  7677. case GGML_OP_CONCAT:
  7678. case GGML_OP_UPSCALE:
  7679. case GGML_OP_UNARY:
  7680. case GGML_OP_GLU:
  7681. case GGML_OP_CONV_2D_DW:
  7682. {
  7683. uint32_t ne = ggml_nelements(dst);
  7684. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7685. // Convert from number of logical elements to 2- or 4-byte units.
  7686. ne /= ggml_blck_size(src0->type);
  7687. if ((ggml_type_size(src0->type) % 4) == 0) {
  7688. ne *= ggml_type_size(src0->type) / 4;
  7689. } else {
  7690. ne *= ggml_type_size(src0->type) / 2;
  7691. }
  7692. }
  7693. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7694. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7695. // So divide by block size here before splitting into 512x512 groups.
  7696. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7697. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7698. }
  7699. if (ne > 262144) {
  7700. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7701. } else if (ne > 512) {
  7702. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7703. } else {
  7704. elements = { ne, 1, 1 };
  7705. }
  7706. } break;
  7707. case GGML_OP_ADD_ID:
  7708. {
  7709. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7710. } break;
  7711. case GGML_OP_SET_ROWS:
  7712. {
  7713. uint32_t ne = ggml_nelements(src0);
  7714. if (ggml_is_quantized(dst->type)) {
  7715. // quants run 32 threads each doing QUANT_K elements
  7716. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7717. } else {
  7718. // scalar types do one element per thread, running 512 threads
  7719. ne = CEIL_DIV(ne, 512);
  7720. }
  7721. if (ne > 262144) {
  7722. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7723. } else if (ne > 512) {
  7724. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7725. } else {
  7726. elements = { ne, 1, 1 };
  7727. }
  7728. }
  7729. break;
  7730. case GGML_OP_SSM_CONV:
  7731. {
  7732. const uint32_t nr = src0->ne[1];
  7733. const uint32_t n_t = dst->ne[1];
  7734. const uint32_t n_s = dst->ne[2];
  7735. elements = { nr, n_t, n_s };
  7736. }
  7737. break;
  7738. default:
  7739. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7740. break;
  7741. }
  7742. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7743. vk_subbuffer a_buf = src0_buf;
  7744. if (ctx->do_add_rms_partials) {
  7745. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7746. }
  7747. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7748. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7749. } else if (op == GGML_OP_GLU) {
  7750. // Empty src1 is possible in glu, but the shader needs a buffer
  7751. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7752. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7753. } else if (op == GGML_OP_SOFT_MAX) {
  7754. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7755. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7756. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7757. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7758. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7759. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7760. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7761. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7762. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7763. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7764. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7765. // buffer device address path doesn't use dst buffer
  7766. dst_buf.size = 1;
  7767. }
  7768. // im2col uses only src1 and dst buffers
  7769. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7770. } else if (op == GGML_OP_COUNT_EQUAL) {
  7771. // count_equal assumes that destination buffer is initialized with zeroes
  7772. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7773. ggml_vk_sync_buffers(ctx, subctx);
  7774. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7775. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7776. // OPT_STEP_SGD works on src0, it does not need dst
  7777. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7778. } else if (use_src3) {
  7779. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7780. } else if (use_src2) {
  7781. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7782. } else if (use_src1) {
  7783. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7784. } else {
  7785. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7786. }
  7787. }
  7788. static void ggml_vk_get_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7789. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7790. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7791. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7792. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7793. (uint32_t)ggml_nelements(src0),
  7794. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7795. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7796. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7797. 0,
  7798. 0.0f, 0.0f, 0,
  7799. });
  7800. }
  7801. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7802. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7803. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7804. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7805. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7806. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7807. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7808. int offset = dst->op_params[3] / 4; // offset in bytes
  7809. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7810. (uint32_t)ggml_nelements(src0),
  7811. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t)src0->nb[3] / src0_type_size,
  7812. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7813. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t) dst->nb[3] / dst_type_size,
  7814. 0,
  7815. 0.0f, 0.0f, offset,
  7816. });
  7817. }
  7818. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  7819. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7820. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7821. // Make a list of all the tensors used by the op.
  7822. // Last element of the list is the dest tensor.
  7823. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7824. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7825. uint32_t num_tensors = num_srcs + 1;
  7826. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7827. tensors[0] = first_node->src[0];
  7828. tensors[1] = first_node->src[1];
  7829. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7830. // check whether the previous result is src[0] or src[1]
  7831. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7832. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7833. } else {
  7834. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7835. }
  7836. }
  7837. tensors[num_srcs] = dst;
  7838. vk_op_multi_add_push_constants pc;
  7839. pc.ne20 = (uint32_t)dst->ne[0];
  7840. pc.ne21 = (uint32_t)dst->ne[1];
  7841. pc.ne22 = (uint32_t)dst->ne[2];
  7842. pc.ne23 = (uint32_t)dst->ne[3];
  7843. for (uint32_t i = 0; i < num_tensors; ++i) {
  7844. const ggml_tensor *t = tensors[i];
  7845. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7846. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7847. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7848. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7849. }
  7850. pc.rms_partials = ctx->do_add_rms_partials;
  7851. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7852. if (pipeline == nullptr) {
  7853. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7854. GGML_ABORT("fatal error");
  7855. }
  7856. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7857. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7858. vk_buffer buf[MAX_PARAMETER_COUNT];
  7859. size_t offset[MAX_PARAMETER_COUNT];
  7860. bool uma[MAX_PARAMETER_COUNT];
  7861. for (uint32_t i = 0; i < num_tensors; ++i) {
  7862. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7863. buf[i] = nullptr;
  7864. offset[i] = 0;
  7865. uma[i] = false;
  7866. if (ctx->device->uma) {
  7867. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7868. uma[i] = buf[i] != nullptr;
  7869. }
  7870. if (!uma[i]) {
  7871. buf[i] = buf_ctx[i]->dev_buffer;
  7872. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7873. }
  7874. GGML_ASSERT(buf[i] != nullptr);
  7875. }
  7876. // If any remaining descriptors are unused, just point them at src[0]
  7877. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7878. buf[i] = buf[0];
  7879. offset[i] = 0;
  7880. }
  7881. if (ctx->do_add_rms_partials) {
  7882. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7883. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7884. }
  7885. std::array<uint32_t, 3> elements;
  7886. uint32_t ne = ggml_nelements(dst);
  7887. if (ne > 262144) {
  7888. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7889. } else if (ne > 512) {
  7890. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7891. } else {
  7892. elements = { ne, 1, 1 };
  7893. }
  7894. static_assert(MAX_PARAMETER_COUNT == 12);
  7895. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7896. {
  7897. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  7898. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  7899. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  7900. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  7901. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  7902. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  7903. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  7904. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  7905. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  7906. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  7907. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  7908. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  7909. }, pc, elements);
  7910. }
  7911. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7912. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7913. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7914. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7915. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  7916. (uint32_t)ggml_nelements(src0),
  7917. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7918. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7919. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7920. 0,
  7921. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7922. });
  7923. }
  7924. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7925. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7926. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7927. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7928. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  7929. (uint32_t)ggml_nelements(src0),
  7930. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7931. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7932. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7933. 0,
  7934. 0.0f, 0.0f, 0,
  7935. });
  7936. }
  7937. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7938. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7939. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7940. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7941. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  7942. (uint32_t)ggml_nelements(src0),
  7943. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7944. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7945. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7946. 0,
  7947. 0.0f, 0.0f, 0,
  7948. });
  7949. }
  7950. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7951. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7952. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7953. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7954. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  7955. (uint32_t)ggml_nelements(src0),
  7956. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7957. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7958. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7959. 0,
  7960. 0.0f, 0.0f, 0,
  7961. });
  7962. }
  7963. static void ggml_vk_add_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  7964. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7965. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7966. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7967. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  7968. (uint32_t)dst->ne[0],
  7969. (uint32_t)dst->ne[1],
  7970. (uint32_t)src0->nb[1] / src0_type_size,
  7971. (uint32_t)src0->nb[2] / src0_type_size,
  7972. (uint32_t)src1->nb[1] / src1_type_size,
  7973. (uint32_t)src2->nb[1] / src2_type_size,
  7974. });
  7975. }
  7976. static void ggml_vk_op_f32_wkv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, int version) {
  7977. GGML_ASSERT(version == 6 || version == 7);
  7978. int num_srcs = version == 6 ? 6 : 7;
  7979. for (int i = 0; i < num_srcs; i++) {
  7980. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7981. }
  7982. GGML_ASSERT(dst->buffer != nullptr);
  7983. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  7984. GGML_ASSERT(pipeline != nullptr);
  7985. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7986. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7987. vk_subbuffer src_buf[7] = {};
  7988. for (int i = 0; i < num_srcs; i++) {
  7989. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  7990. }
  7991. std::array<uint32_t, 3> elements = {
  7992. (uint32_t)(pc.B * pc.H),
  7993. 1,
  7994. 1
  7995. };
  7996. if (version == 6) {
  7997. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7998. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  7999. pc, elements);
  8000. } else if (version == 7) {
  8001. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8002. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8003. pc, elements);
  8004. } else {
  8005. // shouldn't happen
  8006. GGML_ASSERT(false);
  8007. }
  8008. }
  8009. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8010. const size_t seq_length = dst->src[0]->ne[2];
  8011. const size_t n_embed = dst->ne[0];
  8012. const size_t n_heads = dst->src[0]->ne[1];
  8013. const size_t n_seqs = dst->src[5]->ne[1];
  8014. ggml_vk_op_f32_wkv(
  8015. ctx, subctx, dst,
  8016. {
  8017. (uint32_t)n_seqs,
  8018. (uint32_t)seq_length,
  8019. (uint32_t)n_embed,
  8020. (uint32_t)n_heads,
  8021. },
  8022. 6
  8023. );
  8024. }
  8025. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8026. const size_t seq_length = dst->src[0]->ne[2];
  8027. const size_t n_embed = dst->ne[0];
  8028. const size_t n_heads = dst->src[0]->ne[1];
  8029. const size_t n_seqs = dst->src[6]->ne[1];
  8030. ggml_vk_op_f32_wkv(
  8031. ctx, subctx, dst,
  8032. {
  8033. (uint32_t)n_seqs,
  8034. (uint32_t)seq_length,
  8035. (uint32_t)n_embed,
  8036. (uint32_t)n_heads,
  8037. },
  8038. 7
  8039. );
  8040. }
  8041. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8042. const ggml_tensor * src0 = dst->src[0];
  8043. const ggml_tensor * src1 = dst->src[1];
  8044. const ggml_tensor * src2 = dst->src[2];
  8045. const ggml_tensor * src3 = dst->src[3];
  8046. const ggml_tensor * src4 = dst->src[4];
  8047. const ggml_tensor * src5 = dst->src[5];
  8048. GGML_ASSERT(dst->buffer != nullptr);
  8049. const uint32_t head_dim = src0->ne[1];
  8050. const uint32_t n_head = src1->ne[1];
  8051. const uint32_t n_group = src4->ne[1];
  8052. const uint32_t n_tok = src1->ne[2];
  8053. const uint32_t n_seq = src1->ne[3];
  8054. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8055. GGML_ASSERT(is_mamba2);
  8056. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8057. GGML_ASSERT(pipeline != nullptr);
  8058. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8059. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8060. const vk_op_ssm_scan_push_constants pc = {
  8061. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8062. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8063. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8064. (uint32_t)src3->nb[1],
  8065. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8066. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8067. (uint32_t)s_off,
  8068. n_head, head_dim, n_group, n_tok
  8069. };
  8070. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8071. vk_subbuffer src_buf[7] = {};
  8072. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8073. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8074. }
  8075. std::array<uint32_t, 3> elements;
  8076. const int splitH = 16;
  8077. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8078. const uint32_t num_workgroups_y = n_seq;
  8079. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8080. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8081. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8082. pc, elements);
  8083. }
  8084. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8085. const ggml_tensor * src0 = dst->src[0];
  8086. const ggml_tensor * src1 = dst->src[1];
  8087. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8088. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8089. (uint32_t)src1->nb[1],
  8090. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8091. (uint32_t)src1->ne[0],
  8092. (uint32_t)src0->ne[0],
  8093. (uint32_t)src0->ne[1],
  8094. (uint32_t)dst->ne[1],
  8095. (uint32_t)dst->ne[2],
  8096. });
  8097. }
  8098. static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc) {
  8099. const ggml_tensor * x = dst->src[0];
  8100. const ggml_tensor * g = dst->src[1];
  8101. const ggml_tensor * gm = dst->src[2];
  8102. const ggml_tensor * gv = dst->src[3];
  8103. const ggml_tensor * p = dst->src[4];
  8104. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8105. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8106. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8107. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8108. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8109. GGML_ASSERT(dst->buffer != nullptr);
  8110. GGML_ASSERT(ggml_is_contiguous(x));
  8111. GGML_ASSERT(ggml_is_contiguous(g));
  8112. GGML_ASSERT(ggml_is_contiguous(gm));
  8113. GGML_ASSERT(ggml_is_contiguous(gv));
  8114. GGML_ASSERT(ggml_is_contiguous(p));
  8115. GGML_ASSERT(ggml_are_same_shape(x, g));
  8116. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8117. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8118. GGML_ASSERT(ggml_nelements(p) == 7);
  8119. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8120. GGML_ASSERT(pipeline != nullptr);
  8121. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8122. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8123. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8124. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8125. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8126. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8127. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8128. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8129. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8130. pc, elements);
  8131. }
  8132. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8133. const size_t n = ggml_nelements(dst->src[0]);
  8134. ggml_vk_op_f32_opt_step_adamw(
  8135. ctx, subctx, dst,
  8136. { (uint32_t)n, 0, 0.0f, 0.0f }
  8137. );
  8138. }
  8139. static void ggml_vk_opt_step_sgd(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8140. const size_t n = ggml_nelements(dst->src[0]);
  8141. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f });
  8142. }
  8143. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8144. int * op_params = (int *)dst->op_params;
  8145. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8146. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8147. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8148. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8149. (uint32_t)ggml_nelements(dst),
  8150. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  8151. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  8152. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  8153. 0,
  8154. 0.0f, 0.0f, op_params[0],
  8155. });
  8156. }
  8157. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8158. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8159. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8160. GGML_TENSOR_UNARY_OP_LOCALS
  8161. float sf0 = (float)ne0 / ne00;
  8162. float sf1 = (float)ne1 / ne01;
  8163. float sf2 = (float)ne2 / ne02;
  8164. float sf3 = (float)ne3 / ne03;
  8165. float pixel_offset = 0.5f;
  8166. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8167. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8168. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8169. pixel_offset = 0.0f;
  8170. }
  8171. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8172. (uint32_t)ggml_nelements(dst), 0, 0,
  8173. (uint32_t)ne00, (uint32_t)ne01,
  8174. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8175. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8176. sf0, sf1, sf2, sf3, pixel_offset
  8177. });
  8178. }
  8179. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8180. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8181. p.param1 = ggml_get_op_params_f32(dst, 0);
  8182. p.param2 = ggml_get_op_params_f32(dst, 1);
  8183. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8184. }
  8185. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8186. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8187. }
  8188. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8189. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8190. }
  8191. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8192. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8193. }
  8194. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8195. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8196. }
  8197. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8198. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8199. p.param1 = ggml_get_op_params_f32(dst, 0);
  8200. p.param2 = ggml_get_op_params_f32(dst, 1);
  8201. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8202. }
  8203. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8204. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8205. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8206. }
  8207. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8208. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8209. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8210. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8211. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8212. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8213. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8214. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8215. memcpy(&p.param1, &s01_packed, sizeof(float));
  8216. memcpy(&p.param2, &s23_packed, sizeof(float));
  8217. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8218. }
  8219. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8220. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8221. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8222. }
  8223. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8224. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8225. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8226. }
  8227. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8228. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8229. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8230. // Convert from number of logical elements to 2- or 4-byte units.
  8231. ne /= ggml_blck_size(src0->type);
  8232. if ((ggml_type_size(src0->type) % 4) == 0) {
  8233. ne *= ggml_type_size(src0->type) / 4;
  8234. } else {
  8235. ne *= ggml_type_size(src0->type) / 2;
  8236. }
  8237. }
  8238. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8239. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8240. }
  8241. static void ggml_vk_set_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8242. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8243. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8244. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8245. // Skip empty skip_rows operations. For most ops the empty check at the start
  8246. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8247. // with empty srcs.
  8248. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8249. return;
  8250. }
  8251. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8252. (uint32_t)ggml_nelements(src0),
  8253. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  8254. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  8255. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  8256. 0,
  8257. 0.0f, 0.0f, 0,
  8258. });
  8259. }
  8260. static void ggml_vk_silu_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8261. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8262. }
  8263. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8264. float * op_params = (float *)dst->op_params;
  8265. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8266. }
  8267. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8268. const int * int_op_params = (const int *)dst->op_params;
  8269. const float * float_op_params = (const float *)dst->op_params;
  8270. const uint32_t num_groups = int_op_params[0];
  8271. const float eps = float_op_params[1];
  8272. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8273. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f });
  8274. }
  8275. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8276. const uint32_t ne = (uint32_t)node->ne[0];
  8277. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8278. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8279. return num_partials;
  8280. }
  8281. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8282. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8283. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8284. return num_bytes;
  8285. }
  8286. static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) {
  8287. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8288. const int mode = ((const int32_t *) dst->op_params)[2];
  8289. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8290. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8291. const float freq_base = ((const float *) dst->op_params)[5];
  8292. const float freq_scale = ((const float *) dst->op_params)[6];
  8293. const float ext_factor = ((const float *) dst->op_params)[7];
  8294. const float attn_factor = ((const float *) dst->op_params)[8];
  8295. const float beta_fast = ((const float *) dst->op_params)[9];
  8296. const float beta_slow = ((const float *) dst->op_params)[10];
  8297. int sections[4] {};
  8298. if (mode & GGML_ROPE_TYPE_MROPE) {
  8299. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8300. }
  8301. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8302. float corr_dims[2];
  8303. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8304. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8305. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8306. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8307. vk_op_rope_push_constants rope {
  8308. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8309. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8310. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8311. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8312. };
  8313. return rope;
  8314. }
  8315. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, float * op_params) {
  8316. ggml_tensor * dst;
  8317. const ggml_tensor * src0;
  8318. const ggml_tensor * src1;
  8319. if (ctx->num_additional_fused_ops > 0) {
  8320. // fused rms_norm + mul
  8321. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8322. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8323. dst = mul;
  8324. src0 = cgraph->nodes[node_idx]->src[0];
  8325. src1 = other_src;
  8326. } else {
  8327. dst = cgraph->nodes[node_idx];
  8328. src0 = src1 = dst->src[0];
  8329. }
  8330. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8331. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8332. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8333. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8334. vk_op_binary_push_constants bin {
  8335. (uint32_t)ggml_nelements(src0),
  8336. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  8337. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  8338. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  8339. 0,
  8340. op_params[0], 0.0f, (int32_t)param3,
  8341. };
  8342. // more than one fused op means rms_norm+mul+rope
  8343. if (ctx->num_additional_fused_ops > 1) {
  8344. static constexpr uint32_t max_tensors = 7;
  8345. const ggml_tensor *tensors[max_tensors] {};
  8346. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8347. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8348. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8349. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8350. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8351. tensors[0] = rms->src[0];
  8352. tensors[1] = other_src;
  8353. tensors[2] = mul;
  8354. tensors[3] = rope->src[1]; // pos
  8355. tensors[4] = rope->src[2]; // ff
  8356. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8357. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8358. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8359. vk_op_rms_norm_mul_rope_push_constants pc;
  8360. pc.bin = bin;
  8361. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8362. vk_pipeline pipeline = tensors[5]->type == GGML_TYPE_F16 ? ctx->device->pipeline_rms_norm_mul_rope_f32_f16 : ctx->device->pipeline_rms_norm_mul_rope_f32_f32;
  8363. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8364. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8365. vk_buffer buf[max_tensors];
  8366. size_t offset[max_tensors];
  8367. bool uma[max_tensors];
  8368. for (uint32_t i = 0; i < max_tensors; ++i) {
  8369. if (!tensors[i]) {
  8370. // If any remaining descriptors are unused, just point them at src[0]
  8371. buf[i] = buf[0];
  8372. offset[i] = 0;
  8373. continue;
  8374. }
  8375. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8376. buf[i] = nullptr;
  8377. offset[i] = 0;
  8378. uma[i] = false;
  8379. if (ctx->device->uma) {
  8380. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8381. uma[i] = buf[i] != nullptr;
  8382. }
  8383. if (!uma[i]) {
  8384. buf[i] = buf_ctx[i]->dev_buffer;
  8385. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8386. }
  8387. GGML_ASSERT(buf[i] != nullptr);
  8388. }
  8389. std::array<uint32_t, 3> elements;
  8390. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8391. static_assert(max_tensors == 7);
  8392. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8393. {
  8394. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8395. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8396. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8397. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8398. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8399. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8400. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8401. }, pc, elements);
  8402. } else {
  8403. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8404. }
  8405. if (ctx->do_add_rms_partials_offset_calculation) {
  8406. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8407. ctx->do_add_rms_partials = false;
  8408. ctx->do_add_rms_partials_offset_calculation = false;
  8409. }
  8410. }
  8411. static void ggml_vk_rms_norm_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8412. float * op_params = (float *)dst->op_params;
  8413. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8414. }
  8415. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8416. float * op_params = (float *)dst->op_params;
  8417. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_L2_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8418. }
  8419. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8420. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8421. }
  8422. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8423. const float * op_params_f = (const float *)dst->op_params;
  8424. const bool swapped = (bool)dst->op_params[1];
  8425. const bool split = src1 != nullptr;
  8426. const float alpha = op_params_f[2];
  8427. const float limit = op_params_f[3];
  8428. GGML_ASSERT(ggml_is_contiguous(src0));
  8429. if (!split) {
  8430. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8431. } else {
  8432. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8433. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8434. GGML_ASSERT(src0->type == src1->type);
  8435. }
  8436. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8437. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8438. {
  8439. (uint32_t)ggml_nelements(dst),
  8440. (uint32_t)src0->ne[0],
  8441. (uint32_t)dst->ne[0],
  8442. mode,
  8443. alpha,
  8444. limit
  8445. });
  8446. }
  8447. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8448. int32_t * op_params = (int32_t *)dst->op_params;
  8449. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  8450. }
  8451. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8452. float * op_params = (float *)dst->op_params;
  8453. float scale = op_params[0];
  8454. float max_bias = op_params[1];
  8455. const uint32_t ncols = (uint32_t)src0->ne[0];
  8456. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8457. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8458. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8459. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8460. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8461. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8462. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8463. const uint32_t n_head_kv = src0->ne[2];
  8464. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8465. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8466. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8467. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8468. ncols,
  8469. src1 != nullptr ? nrows_y : (uint32_t)0,
  8470. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8471. ne12, ne13,
  8472. nb11, nb12, nb13,
  8473. scale, max_bias,
  8474. m0, m1,
  8475. n_head_log2,
  8476. nrows_x,
  8477. src2 != nullptr
  8478. });
  8479. }
  8480. static void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8481. float * op_params = (float *)dst->op_params;
  8482. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1] });
  8483. }
  8484. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8485. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8486. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8487. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8488. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8489. cgraph->nodes[node_idx + 5];
  8490. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8491. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8492. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8493. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8494. const int n_experts = logits->ne[0];
  8495. const int n_rows = logits->ne[1];
  8496. const int n_expert_used = weights->ne[1];
  8497. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8498. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8499. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8500. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8501. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8502. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8503. vk_op_topk_moe_push_constants pc {};
  8504. pc.n_rows = n_rows;
  8505. pc.n_expert_used = n_expert_used;
  8506. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8507. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8508. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8509. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8510. }
  8511. GGML_ASSERT(n_expert_used <= n_experts);
  8512. const uint32_t rows_per_block = 4;
  8513. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8514. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8515. }
  8516. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8517. ggml_tensor * dst = cgraph->nodes[node_idx];
  8518. const ggml_tensor * src0 = dst->src[0];
  8519. const ggml_tensor * src1 = dst->src[1];
  8520. const ggml_tensor * src2 = dst->src[2];
  8521. const ggml_tensor * src3 = nullptr;
  8522. const int n_dims = ((int32_t *) dst->op_params)[1];
  8523. const int mode = ((int32_t *) dst->op_params)[2];
  8524. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8525. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8526. const float freq_base = ((float *) dst->op_params)[5];
  8527. const float beta_fast = ((float *) dst->op_params)[9];
  8528. const float beta_slow = ((float *) dst->op_params)[10];
  8529. int sections[4] {};
  8530. if (mode & GGML_ROPE_TYPE_MROPE) {
  8531. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8532. }
  8533. float corr_dims[2];
  8534. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8535. uint32_t set_rows_stride = 0;
  8536. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8537. // and overrides the dst and sets src3=row_indices
  8538. if (ctx->num_additional_fused_ops > 0) {
  8539. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8540. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8541. dst = cgraph->nodes[node_idx + 2];
  8542. }
  8543. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8544. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8545. }
  8546. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8547. int32_t * op_params = (int32_t *)dst->op_params;
  8548. uint32_t ncols = src0->ne[0];
  8549. uint32_t nrows = ggml_nrows(src0);
  8550. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8551. ncols,
  8552. nrows,
  8553. op_params[0],
  8554. });
  8555. }
  8556. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8557. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8558. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  8559. }
  8560. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8561. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8562. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  8563. }
  8564. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8565. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8566. p.weight = 1.0f / (float)src0->ne[0];
  8567. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  8568. }
  8569. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8570. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f });
  8571. }
  8572. static void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8573. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8574. }
  8575. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8576. const int32_t s0 = dst->op_params[0];
  8577. const int32_t s1 = dst->op_params[1];
  8578. const int32_t p0 = dst->op_params[2];
  8579. const int32_t p1 = dst->op_params[3];
  8580. const int32_t d0 = dst->op_params[4];
  8581. const int32_t d1 = dst->op_params[5];
  8582. const bool is_2D = dst->op_params[6] == 1;
  8583. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8584. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8585. const uint32_t IW = src1->ne[0];
  8586. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8587. const uint32_t KW = src0->ne[0];
  8588. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8589. const uint32_t OW = dst->ne[1];
  8590. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8591. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8592. const uint32_t pelements = OW * KW * KH;
  8593. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8594. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8595. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8596. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8597. dst_addr,
  8598. batch_offset, offset_delta,
  8599. IC, IW, IH, OW, OH, KW, KH,
  8600. pelements,
  8601. IC * KH * KW,
  8602. s0, s1, p0, p1, d0, d1,
  8603. });
  8604. }
  8605. static void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8606. GGML_TENSOR_BINARY_OP_LOCALS
  8607. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8608. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8609. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8610. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8611. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8612. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8613. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8614. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8615. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8616. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8617. const int64_t N = ne13 / IC;
  8618. const int64_t ID = ne12;
  8619. const int64_t IH = ne11;
  8620. const int64_t IW = ne10;
  8621. const int64_t KD = ne02;
  8622. const int64_t KH = ne01;
  8623. const int64_t KW = ne00;
  8624. const int64_t OD = ne3 / N;
  8625. const int64_t OH = ne2;
  8626. const int64_t OW = ne1;
  8627. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8628. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8629. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8630. vk_op_im2col_3d_push_constants pc {};
  8631. pc.dst_addr = dst_addr;
  8632. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8633. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8634. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8635. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8636. pc.s0 = s0;
  8637. pc.s1 = s1;
  8638. pc.s2 = s2;
  8639. pc.p0 = p0;
  8640. pc.p1 = p1;
  8641. pc.p2 = p2;
  8642. pc.d0 = d0;
  8643. pc.d1 = d1;
  8644. pc.d2 = d2;
  8645. pc.IW = IW;
  8646. pc.IH = IH;
  8647. pc.ID = ID;
  8648. pc.IC = IC;
  8649. pc.KW = KW;
  8650. pc.OH = OH;
  8651. pc.KD_KH_KW = KD*KH*KW;
  8652. pc.KH_KW = KH*KW;
  8653. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8654. pc.N_OD_OH = N*OD*OH;
  8655. pc.OD_OH = OD*OH;
  8656. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8657. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8658. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8659. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  8660. }
  8661. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8662. const uint32_t dim = dst->op_params[0];
  8663. const uint32_t max_period = dst->op_params[1];
  8664. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8665. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8666. nb1, dim, max_period,
  8667. });
  8668. }
  8669. static void ggml_vk_conv_transpose_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8670. // src0: (K, Cout, Cin, 1) -- kernel
  8671. // src1: (L, Cin, 1, 1) -- input
  8672. // dst: (*, Cout, 1, 1)
  8673. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8674. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8675. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8676. GGML_TENSOR_BINARY_OP_LOCALS
  8677. GGML_ASSERT(nb00 == sizeof(float));
  8678. GGML_ASSERT(nb10 == sizeof(float));
  8679. const int32_t s0 = dst->op_params[0];
  8680. vk_op_conv_transpose_1d_push_constants p{};
  8681. p.Cout = static_cast<uint32_t>(ne01);
  8682. p.Cin = static_cast<uint32_t>(ne02);
  8683. p.K = static_cast<uint32_t>(ne00);
  8684. p.L = static_cast<uint32_t>(ne10);
  8685. p.KL = static_cast<uint32_t>(ne0);
  8686. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8687. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8688. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8689. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8690. p.s0 = static_cast<uint32_t>(s0);
  8691. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  8692. }
  8693. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8694. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8695. const int32_t k1 = dst->op_params[1];
  8696. const int32_t k0 = dst->op_params[2];
  8697. const int32_t s1 = dst->op_params[3];
  8698. const int32_t s0 = dst->op_params[4];
  8699. const int32_t p1 = dst->op_params[5];
  8700. const int32_t p0 = dst->op_params[6];
  8701. const uint32_t IH = src0->ne[1];
  8702. const uint32_t IW = src0->ne[0];
  8703. const uint32_t N = dst->ne[3];
  8704. const uint32_t OC = dst->ne[2];
  8705. const uint32_t OH = dst->ne[1];
  8706. const uint32_t OW = dst->ne[0];
  8707. const uint32_t parallel_elements = N * OC * OH * OW;
  8708. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8709. IW, IH, OW, OH, OC,
  8710. parallel_elements,
  8711. op,
  8712. k0, k1, s0, s1, p0, p1,
  8713. });
  8714. }
  8715. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8716. const ggml_tensor * src1, ggml_tensor * dst) {
  8717. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8718. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8719. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8720. GGML_TENSOR_BINARY_OP_LOCALS
  8721. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8722. GGML_ASSERT(nb10 == sizeof(float));
  8723. GGML_ASSERT(nb0 == sizeof(float));
  8724. vk_op_conv2d_push_constants p{};
  8725. p.Cout = static_cast<uint32_t>(ne03);
  8726. p.Cin = static_cast<uint32_t>(ne02);
  8727. p.N = static_cast<uint32_t>(ne13);
  8728. p.KW = static_cast<uint32_t>(ne00);
  8729. p.KH = static_cast<uint32_t>(ne01);
  8730. p.W = static_cast<uint32_t>(ne10);
  8731. p.H = static_cast<uint32_t>(ne11);
  8732. p.OW = static_cast<uint32_t>(ne0);
  8733. p.OH = static_cast<uint32_t>(ne1);
  8734. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8735. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8736. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8737. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8738. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8739. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8740. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8741. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8742. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8743. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8744. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8745. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8746. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8747. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8748. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8749. GGML_ASSERT(ne03 == ne2);
  8750. GGML_ASSERT(ne02 == ne12);
  8751. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p));
  8752. }
  8753. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8754. const ggml_tensor * src1, ggml_tensor * dst) {
  8755. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8756. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8757. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8758. GGML_TENSOR_BINARY_OP_LOCALS
  8759. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8760. GGML_ASSERT(nb10 == sizeof(float));
  8761. GGML_ASSERT(nb0 == sizeof(float));
  8762. vk_op_conv_transpose_2d_push_constants p{};
  8763. p.Cout = static_cast<uint32_t>(ne02);
  8764. p.Cin = static_cast<uint32_t>(ne03);
  8765. p.N = static_cast<uint32_t>(ne13);
  8766. p.KW = static_cast<uint32_t>(ne00);
  8767. p.KH = static_cast<uint32_t>(ne01);
  8768. p.W = static_cast<uint32_t>(ne10);
  8769. p.H = static_cast<uint32_t>(ne11);
  8770. p.OW = static_cast<uint32_t>(ne0);
  8771. p.OH = static_cast<uint32_t>(ne1);
  8772. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8773. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8774. p.p0 = 0;
  8775. p.p1 = 0;
  8776. p.d0 = 1;
  8777. p.d1 = 1;
  8778. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8779. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8780. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8781. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8782. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8783. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8784. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8785. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8786. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8787. GGML_ASSERT(ne02 == ne2);
  8788. GGML_ASSERT(ne03 == ne12);
  8789. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p));
  8790. }
  8791. static void ggml_vk_conv_2d_dw(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8792. vk_op_conv2d_dw_push_constants p{};
  8793. p.ne = ggml_nelements(dst);
  8794. p.channels = dst->ne[2];
  8795. p.batches = dst->ne[3];
  8796. p.dst_w = dst->ne[0];
  8797. p.dst_h = dst->ne[1];
  8798. p.src_w = src1->ne[0];
  8799. p.src_h = src1->ne[1];
  8800. p.knl_w = src0->ne[0];
  8801. p.knl_h = src0->ne[1];
  8802. p.stride_x = dst->op_params[0];
  8803. p.stride_y = dst->op_params[1];
  8804. p.pad_x = dst->op_params[2];
  8805. p.pad_y = dst->op_params[3];
  8806. p.dilation_x = dst->op_params[4];
  8807. p.dilation_y = dst->op_params[5];
  8808. GGML_ASSERT(src0->ne[3] == p.channels);
  8809. GGML_ASSERT(src1->ne[3] == p.batches);
  8810. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  8811. }
  8812. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8813. const float * op_params = (const float *)dst->op_params;
  8814. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f });
  8815. }
  8816. #ifdef GGML_VULKAN_RUN_TESTS
  8817. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8818. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8819. return;
  8820. }
  8821. i0 = std::max(i0, 5);
  8822. i1 = std::max(i1, 5);
  8823. i2 = std::max(i2, 0);
  8824. fprintf(stderr, " ");
  8825. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8826. fprintf(stderr, "%7d ", idx1);
  8827. }
  8828. fprintf(stderr, "\n");
  8829. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8830. fprintf(stderr, "%7d: ", idx0);
  8831. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8832. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8833. float val;
  8834. if (type == GGML_TYPE_F32) {
  8835. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8836. } else if (type == GGML_TYPE_F16) {
  8837. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8838. } else {
  8839. GGML_ABORT("fatal error");
  8840. }
  8841. fprintf(stderr, "% 7.2f ", val);
  8842. } else {
  8843. fprintf(stderr, " ");
  8844. }
  8845. }
  8846. fprintf(stderr, "\n");
  8847. }
  8848. }
  8849. template <typename X_TYPE, typename Y_TYPE>
  8850. static void ggml_vk_test_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, int split_k, int shader_size) {
  8851. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8852. const size_t x_ne = m * k * batch;
  8853. const size_t y_ne = k * n * batch;
  8854. const size_t d_ne = m * n * batch;
  8855. vk_pipeline p;
  8856. std::string shname;
  8857. if (shader_size == 0) {
  8858. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8859. p = ctx->device->pipeline_matmul_f32->a_s;
  8860. shname = "F32_ALIGNED_S";
  8861. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8862. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8863. shname = "F32_F16_ALIGNED_S";
  8864. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8865. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8866. shname = "F16_F32_ALIGNED_S";
  8867. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8868. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8869. shname = "F16_ALIGNED_S";
  8870. } else {
  8871. GGML_ABORT("fatal error");
  8872. }
  8873. } else if (shader_size == 1) {
  8874. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8875. p = ctx->device->pipeline_matmul_f32->a_m;
  8876. shname = "F32_ALIGNED_M";
  8877. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8878. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8879. shname = "F32_F16_ALIGNED_M";
  8880. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8881. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8882. shname = "F16_F32_ALIGNED_M";
  8883. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8884. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8885. shname = "F16_ALIGNED_M";
  8886. } else {
  8887. GGML_ABORT("fatal error");
  8888. }
  8889. } else if (shader_size == 2) {
  8890. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8891. p = ctx->device->pipeline_matmul_f32->a_l;
  8892. shname = "F32_ALIGNED_L";
  8893. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8894. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8895. shname = "F32_F16_ALIGNED_L";
  8896. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8897. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8898. shname = "F16_F32_ALIGNED_L";
  8899. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8900. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8901. shname = "F16_ALIGNED_L";
  8902. } else {
  8903. GGML_ABORT("fatal error");
  8904. }
  8905. } else {
  8906. GGML_ASSERT(0);
  8907. }
  8908. const size_t kpad = ggml_vk_align_size(k, p->align);
  8909. if (k != kpad) {
  8910. if (shader_size == 0) {
  8911. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8912. p = ctx->device->pipeline_matmul_f32->s;
  8913. shname = "F32_S";
  8914. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8915. p = ctx->device->pipeline_matmul_f32_f16->s;
  8916. shname = "F32_F16_S";
  8917. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8918. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8919. shname = "F16_F32_S";
  8920. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8921. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8922. shname = "F16_S";
  8923. }
  8924. } else if (shader_size == 1) {
  8925. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8926. p = ctx->device->pipeline_matmul_f32->m;
  8927. shname = "F32_M";
  8928. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8929. p = ctx->device->pipeline_matmul_f32_f16->m;
  8930. shname = "F32_F16_M";
  8931. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8932. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8933. shname = "F16_F32_M";
  8934. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8935. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8936. shname = "F16_M";
  8937. }
  8938. } else if (shader_size == 2) {
  8939. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8940. p = ctx->device->pipeline_matmul_f32->l;
  8941. shname = "F32_L";
  8942. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8943. p = ctx->device->pipeline_matmul_f32_f16->l;
  8944. shname = "F32_F16_L";
  8945. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8946. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8947. shname = "F16_F32_L";
  8948. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8949. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8950. shname = "F16_L";
  8951. }
  8952. }
  8953. }
  8954. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8955. if (split_k > 1) {
  8956. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8957. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8958. // Resize buffer
  8959. if (ctx->prealloc_split_k != nullptr) {
  8960. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8961. }
  8962. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8963. }
  8964. }
  8965. ggml_pipeline_allocate_descriptor_sets(ctx);
  8966. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8967. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8968. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8969. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  8970. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  8971. float* d = (float *) malloc(sizeof(float) * d_ne);
  8972. for (size_t i = 0; i < x_ne; i++) {
  8973. if (std::is_same<float, X_TYPE>()) {
  8974. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8975. // x[i] = 1.0f;
  8976. // x[i] = i + 1;
  8977. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8978. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8979. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8980. // x[i] = ggml_fp32_to_fp16(1.0f);
  8981. // x[i] = ggml_fp32_to_fp16(i + 1);
  8982. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8983. } else {
  8984. GGML_ABORT("fatal error");
  8985. }
  8986. }
  8987. for (size_t i = 0; i < y_ne; i++) {
  8988. if (std::is_same<float, Y_TYPE>()) {
  8989. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8990. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8991. // y[i] = i + 1;
  8992. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8993. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8994. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8995. // y[i] = ggml_fp32_to_fp16(i + 1);
  8996. } else {
  8997. GGML_ABORT("fatal error");
  8998. }
  8999. }
  9000. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9001. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9002. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9003. ggml_vk_ctx_begin(ctx->device, subctx);
  9004. for (size_t i = 0; i < num_it; i++) {
  9005. ggml_vk_matmul(
  9006. ctx, subctx, p, ggml_vk_subbuffer(ctx, d_X), ggml_vk_subbuffer(ctx, d_Y), ggml_vk_subbuffer(ctx, d_D), ggml_vk_subbuffer(ctx, ctx->prealloc_split_k),
  9007. m, n, k,
  9008. k, k, m, k*m, k*n, m*n,
  9009. split_k, batch, batch, batch, 1, 1, n
  9010. );
  9011. }
  9012. ggml_vk_ctx_end(subctx);
  9013. auto begin = std::chrono::high_resolution_clock::now();
  9014. ggml_vk_submit(subctx, ctx->fence);
  9015. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9016. ctx->device->device.resetFences({ ctx->fence });
  9017. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9018. auto end = std::chrono::high_resolution_clock::now();
  9019. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9020. // copy dst to host
  9021. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9022. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9023. ggml_init_params iparams = {
  9024. /*.mem_size =*/ 1024*1024*1024,
  9025. /*.mem_buffer =*/ NULL,
  9026. /*.no_alloc =*/ true,
  9027. };
  9028. ggml_context * ggml_ctx = ggml_init(iparams);
  9029. ggml_type src0_type;
  9030. ggml_type src1_type;
  9031. if (std::is_same<float, X_TYPE>()) {
  9032. src0_type = GGML_TYPE_F32;
  9033. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9034. src0_type = GGML_TYPE_F16;
  9035. } else {
  9036. GGML_ABORT("fatal error");
  9037. }
  9038. if (std::is_same<float, Y_TYPE>()) {
  9039. src1_type = GGML_TYPE_F32;
  9040. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9041. src1_type = GGML_TYPE_F16;
  9042. } else {
  9043. GGML_ABORT("fatal error");
  9044. }
  9045. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9046. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9047. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9048. src0_ggml->data = x;
  9049. src1_ggml->data = y;
  9050. tensor_ggml->data = d_chk;
  9051. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9052. ggml_build_forward_expand(cgraph, tensor_ggml);
  9053. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9054. ggml_free(ggml_ctx);
  9055. double avg_err = 0.0;
  9056. int first_err_n = -1;
  9057. int first_err_m = -1;
  9058. int first_err_b = -1;
  9059. for (size_t i = 0; i < m*n*batch; i++) {
  9060. double err = std::fabs(d[i] - d_chk[i]);
  9061. avg_err += err;
  9062. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9063. first_err_b = i / (m * n);
  9064. first_err_n = (i % (m * n)) / m;
  9065. first_err_m = (i % (m * n)) % m;
  9066. }
  9067. }
  9068. avg_err /= m * n;
  9069. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9070. std::cerr << "TEST " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  9071. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9072. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9073. std::cerr << "Actual result: " << std::endl << std::endl;
  9074. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9075. std::cerr << "Expected result: " << std::endl << std::endl;
  9076. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9077. if (split_k > 1) {
  9078. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9079. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9080. std::cerr << "d_buf0: " << std::endl << std::endl;
  9081. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9082. std::cerr << "d_buf1: " << std::endl << std::endl;
  9083. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9084. std::cerr << "d_buf2: " << std::endl << std::endl;
  9085. ggml_vk_print_matrix_area(split_k_buf + 2 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9086. std::cerr << "d_buf3: " << std::endl << std::endl;
  9087. ggml_vk_print_matrix_area(split_k_buf + 3 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9088. free(split_k_buf);
  9089. }
  9090. }
  9091. free(d_chk);
  9092. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9093. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9094. ggml_vk_destroy_buffer(d_X);
  9095. ggml_vk_destroy_buffer(d_Y);
  9096. ggml_vk_destroy_buffer(d_D);
  9097. free(x);
  9098. free(y);
  9099. free(d);
  9100. }
  9101. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9102. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9103. return;
  9104. }
  9105. i0 = std::max(i0, 5);
  9106. i1 = std::max(i1, 5);
  9107. i2 = std::max(i2, 0);
  9108. i3 = std::max(i3, 0);
  9109. fprintf(stderr, " ");
  9110. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9111. fprintf(stderr, "%7d ", idx1);
  9112. }
  9113. fprintf(stderr, "\n");
  9114. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9115. fprintf(stderr, "%7d: ", idx0);
  9116. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9117. if (idx0 >= 0 && idx0 < tensor->ne[0] && idx1 >= 0 && idx1 < tensor->ne[1] && i2 >= 0 && i2 < tensor->ne[2] && i3 >= 0 && i3 < tensor->ne[3]) {
  9118. float val;
  9119. if (tensor->type == GGML_TYPE_F32) {
  9120. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9121. } else if (tensor->type == GGML_TYPE_F16) {
  9122. val = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]));
  9123. } else {
  9124. GGML_ABORT("fatal error");
  9125. }
  9126. fprintf(stderr, "% 7.2f ", val);
  9127. } else {
  9128. fprintf(stderr, " ");
  9129. }
  9130. }
  9131. fprintf(stderr, "\n");
  9132. }
  9133. }
  9134. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9135. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9136. }
  9137. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9138. if (quant == GGML_TYPE_F32) {
  9139. memcpy(to, from, sizeof(float) * ne);
  9140. return;
  9141. }
  9142. const auto * tt = ggml_get_type_traits(quant);
  9143. ggml_to_float_t dequant_fn = tt->to_float;
  9144. dequant_fn(from, to, ne);
  9145. }
  9146. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9147. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9148. const size_t x_sz = sizeof(float) * ne;
  9149. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9150. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9151. float * x = (float *) malloc(x_sz);
  9152. void * qx = malloc(qx_sz);
  9153. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9154. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9155. float * x_ref = (float *) malloc(x_sz);
  9156. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9157. for (size_t i = 0; i < ne; i++) {
  9158. x[i] = rand() / (float)RAND_MAX;
  9159. }
  9160. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9161. ggml_vk_quantize_data(x, qx, ne, quant);
  9162. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9163. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9164. ggml_pipeline_allocate_descriptor_sets(ctx);
  9165. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9166. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9167. ggml_vk_ctx_begin(ctx->device, subctx);
  9168. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9169. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc, { (uint32_t)ne, 1, 1});
  9170. ggml_vk_ctx_end(subctx);
  9171. auto begin = std::chrono::high_resolution_clock::now();
  9172. ggml_vk_submit(subctx, ctx->fence);
  9173. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9174. ctx->device->device.resetFences({ ctx->fence });
  9175. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9176. auto end = std::chrono::high_resolution_clock::now();
  9177. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9178. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9179. int first_err = -1;
  9180. double avg_err = 0.0;
  9181. for (size_t i = 0; i < ne; i++) {
  9182. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9183. avg_err += error;
  9184. if (first_err < 0 && error > 0.05) {
  9185. first_err = i;
  9186. }
  9187. }
  9188. avg_err /= ne;
  9189. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9190. if (avg_err > 0.1) {
  9191. std::cerr << "first_error = " << first_err << std::endl;
  9192. std::cerr << "Actual result: " << std::endl << std::endl;
  9193. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9194. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9195. }
  9196. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9197. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9198. std::cerr << x_ref[i] << ", ";
  9199. }
  9200. std::cerr << std::endl;
  9201. }
  9202. ggml_vk_destroy_buffer(x_buf);
  9203. ggml_vk_destroy_buffer(qx_buf);
  9204. free(x);
  9205. free(qx);
  9206. free(x_ref);
  9207. free(x_chk);
  9208. }
  9209. // This does not work without ggml q8_1 quantization support
  9210. //
  9211. // typedef uint16_t ggml_half;
  9212. // typedef uint32_t ggml_half2;
  9213. //
  9214. // #define QK8_1 32
  9215. // typedef struct {
  9216. // union {
  9217. // struct {
  9218. // ggml_half d; // delta
  9219. // ggml_half s; // d * sum(qs[i])
  9220. // } GGML_COMMON_AGGR_S;
  9221. // ggml_half2 ds;
  9222. // } GGML_COMMON_AGGR_U;
  9223. // int8_t qs[QK8_1]; // quants
  9224. // } block_q8_1;
  9225. //
  9226. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9227. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9228. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9229. //
  9230. // const size_t x_sz = sizeof(float) * ne;
  9231. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9232. // float * x = (float *) malloc(x_sz);
  9233. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9234. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9235. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9236. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9237. //
  9238. // for (size_t i = 0; i < ne; i++) {
  9239. // x[i] = rand() / (float)RAND_MAX;
  9240. // }
  9241. //
  9242. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9243. //
  9244. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9245. //
  9246. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9247. //
  9248. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9249. //
  9250. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9251. // ggml_vk_ctx_begin(ctx->device, subctx);
  9252. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9253. // ggml_vk_ctx_end(subctx);
  9254. //
  9255. // auto begin = std::chrono::high_resolution_clock::now();
  9256. //
  9257. // ggml_vk_submit(subctx, ctx->fence);
  9258. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9259. // ctx->device->device.resetFences({ ctx->fence });
  9260. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9261. //
  9262. // auto end = std::chrono::high_resolution_clock::now();
  9263. //
  9264. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9265. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9266. //
  9267. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9268. //
  9269. // int first_err = -1;
  9270. //
  9271. // for (size_t i = 0; i < ne / 32; i++) {
  9272. // double error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d));
  9273. //
  9274. // if (first_err < 0 && error > 0.1) {
  9275. // first_err = i;
  9276. // }
  9277. //
  9278. // error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s));
  9279. //
  9280. // if (first_err < 0 && error > 0.1) {
  9281. // first_err = i;
  9282. // }
  9283. //
  9284. // for (size_t j = 0; j < 32; j++) {
  9285. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9286. //
  9287. // if (first_err < 0 && error > 1) {
  9288. // first_err = i;
  9289. // }
  9290. // }
  9291. // }
  9292. //
  9293. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9294. //
  9295. // if (first_err != -1) {
  9296. // std::cerr << "first_error = " << first_err << std::endl;
  9297. // std::cerr << "Actual result: " << std::endl << std::endl;
  9298. // std::cout << "d=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  9299. // for (size_t j = 0; j < 32; j++) {
  9300. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9301. // }
  9302. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9303. // std::cout << "d=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  9304. // for (size_t j = 0; j < 32; j++) {
  9305. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9306. // }
  9307. // std::cerr << std::endl;
  9308. // }
  9309. //
  9310. // ggml_vk_destroy_buffer(x_buf);
  9311. // ggml_vk_destroy_buffer(qx_buf);
  9312. //
  9313. // free(x);
  9314. // free(qx);
  9315. // free(qx_res);
  9316. // }
  9317. static void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, size_t split_k, size_t shader_size, ggml_type quant, bool mmq = false) {
  9318. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9319. const size_t x_ne = m * k * batch;
  9320. const size_t y_ne = k * n * batch;
  9321. const size_t d_ne = m * n * batch;
  9322. vk_matmul_pipeline2 * pipelines;
  9323. if (mmq) {
  9324. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9325. } else {
  9326. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9327. }
  9328. const bool fp16acc = ctx->device->fp16;
  9329. vk_pipeline p;
  9330. std::string shname;
  9331. if (shader_size == 0) {
  9332. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9333. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9334. } else if (shader_size == 1) {
  9335. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9336. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9337. } else if (shader_size == 2) {
  9338. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9339. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9340. } else {
  9341. GGML_ASSERT(0);
  9342. }
  9343. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9344. if (mmq || k != kpad) {
  9345. if (shader_size == 0) {
  9346. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9347. shname = std::string(ggml_type_name(quant)) + "_S";
  9348. } else if (shader_size == 1) {
  9349. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9350. shname = std::string(ggml_type_name(quant)) + "_M";
  9351. } else if (shader_size == 2) {
  9352. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9353. shname = std::string(ggml_type_name(quant)) + "_L";
  9354. } else {
  9355. GGML_ASSERT(0);
  9356. }
  9357. }
  9358. if (p == nullptr) {
  9359. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9360. return;
  9361. }
  9362. const size_t x_sz = sizeof(float) * x_ne;
  9363. const size_t y_sz = sizeof(float) * y_ne;
  9364. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9365. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9366. const size_t d_sz = sizeof(float) * d_ne;
  9367. float * x = (float *) malloc(x_sz);
  9368. float * y = (float *) malloc(y_sz);
  9369. void * qx = malloc(qx_sz);
  9370. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9371. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9372. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9373. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9374. float * d = (float *) malloc(d_sz);
  9375. float * d_chk = (float *) malloc(d_sz);
  9376. for (size_t i = 0; i < x_ne; i++) {
  9377. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9378. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9379. // x[i] = i % k;
  9380. }
  9381. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9382. for (size_t i = 0; i < y_ne; i++) {
  9383. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9384. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9385. // y[i] = i % k;
  9386. }
  9387. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9388. if (split_k > 1) {
  9389. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9390. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9391. // Resize buffer
  9392. if (ctx->prealloc_split_k != nullptr) {
  9393. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9394. }
  9395. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9396. }
  9397. }
  9398. if (mmq) {
  9399. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9400. }
  9401. ggml_pipeline_allocate_descriptor_sets(ctx);
  9402. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9403. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9404. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9405. ggml_vk_ctx_begin(ctx->device, subctx);
  9406. if (mmq) {
  9407. for (size_t i = 0; i < num_it; i++) {
  9408. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9409. ggml_vk_matmul(
  9410. ctx, subctx, p, { qx_buf, 0, qx_sz }, { qy_buf, 0, qy_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  9411. m, n, k,
  9412. k, k, m, k*m, k*n, m*n,
  9413. split_k, batch, batch, batch, 1, 1, n
  9414. );
  9415. }
  9416. } else {
  9417. for (size_t i = 0; i < num_it; i++) {
  9418. ggml_vk_matmul(
  9419. ctx, subctx, p, { qx_buf, 0, qx_sz }, { y_buf, 0, y_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  9420. m, n, k,
  9421. k, k, m, k*m, k*n, m*n,
  9422. split_k, batch, batch, batch, 1, 1, n
  9423. );
  9424. }
  9425. }
  9426. ggml_vk_ctx_end(subctx);
  9427. auto begin = std::chrono::high_resolution_clock::now();
  9428. ggml_vk_submit(subctx, ctx->fence);
  9429. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9430. ctx->device->device.resetFences({ ctx->fence });
  9431. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9432. auto end = std::chrono::high_resolution_clock::now();
  9433. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9434. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9435. ggml_init_params iparams = {
  9436. /*.mem_size =*/ 1024*1024*1024,
  9437. /*.mem_buffer =*/ NULL,
  9438. /*.no_alloc =*/ true,
  9439. };
  9440. ggml_context * ggml_ctx = ggml_init(iparams);
  9441. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9442. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9443. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9444. src0_ggml->data = qx;
  9445. src1_ggml->data = y;
  9446. tensor_ggml->data = d_chk;
  9447. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9448. ggml_build_forward_expand(cgraph, tensor_ggml);
  9449. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9450. ggml_free(ggml_ctx);
  9451. double avg_err = 0.0;
  9452. int first_err_n = -1;
  9453. int first_err_m = -1;
  9454. int first_err_b = -1;
  9455. for (size_t i = 0; i < m*n*batch; i++) {
  9456. double err = std::fabs(d[i] - d_chk[i]);
  9457. avg_err += err;
  9458. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9459. first_err_b = i / (m * n);
  9460. first_err_n = (i % (m * n)) / m;
  9461. first_err_m = (i % (m * n)) % m;
  9462. }
  9463. }
  9464. avg_err /= m * n;
  9465. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9466. std::cerr << "TEST dequant matmul " << shname;
  9467. if (mmq) {
  9468. std::cerr << " mmq";
  9469. }
  9470. std::cerr << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  9471. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9472. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9473. std::cerr << "Actual result: " << std::endl << std::endl;
  9474. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9475. std::cerr << std::endl;
  9476. std::cerr << "Expected result: " << std::endl << std::endl;
  9477. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9478. std::cerr << "src0: " << std::endl << std::endl;
  9479. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9480. std::cerr << std::endl;
  9481. std::cerr << "src1: " << std::endl << std::endl;
  9482. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9483. if (split_k > 1) {
  9484. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9485. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9486. std::cerr << "d_buf0: " << std::endl << std::endl;
  9487. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9488. std::cerr << "d_buf1: " << std::endl << std::endl;
  9489. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9490. std::cerr << "d_buf2: " << std::endl << std::endl;
  9491. ggml_vk_print_matrix_area(split_k_buf + 2 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9492. std::cerr << "d_buf3: " << std::endl << std::endl;
  9493. ggml_vk_print_matrix_area(split_k_buf + 3 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9494. free(split_k_buf);
  9495. }
  9496. }
  9497. ggml_vk_destroy_buffer(qx_buf);
  9498. ggml_vk_destroy_buffer(y_buf);
  9499. ggml_vk_destroy_buffer(qy_buf);
  9500. ggml_vk_destroy_buffer(d_buf);
  9501. free(x);
  9502. free(qx);
  9503. free(y);
  9504. free(d);
  9505. free(d_chk);
  9506. }
  9507. #endif
  9508. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9509. #if defined(GGML_VULKAN_RUN_TESTS)
  9510. const std::vector<size_t> vals {
  9511. 512, 512, 128,
  9512. 128, 512, 512,
  9513. 4096, 512, 4096,
  9514. 11008, 512, 4096,
  9515. 4096, 512, 11008,
  9516. 32000, 512, 4096,
  9517. 8, 8, 8,
  9518. 100, 46, 576,
  9519. 623, 111, 128,
  9520. 100, 46, 558,
  9521. 512, 1, 256,
  9522. 128, 110, 622,
  9523. 511, 511, 127,
  9524. 511, 511, 7,
  9525. 511, 511, 17,
  9526. 49, 49, 128,
  9527. 128, 49, 49,
  9528. 4096, 49, 4096,
  9529. };
  9530. const size_t num_it = 100;
  9531. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9532. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9533. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9534. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9535. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9536. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9537. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9538. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9539. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9540. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9541. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9542. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9543. abort();
  9544. for (size_t i = 0; i < vals.size(); i += 3) {
  9545. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9546. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9547. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9548. std::cerr << '\n';
  9549. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9550. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9551. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9552. std::cerr << '\n';
  9553. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9554. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9555. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9556. std::cerr << '\n' << std::endl;
  9557. if (vals[i + 2] % 32 == 0) {
  9558. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9559. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9560. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9561. std::cerr << '\n';
  9562. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9563. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9564. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9565. std::cerr << '\n';
  9566. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9567. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9568. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9569. std::cerr << '\n' << std::endl;
  9570. }
  9571. if (vals[i + 2] % 256 == 0) {
  9572. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9573. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9574. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9575. std::cerr << '\n';
  9576. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9577. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9578. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9579. std::cerr << '\n';
  9580. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9581. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9582. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9583. std::cerr << '\n' << std::endl;
  9584. }
  9585. }
  9586. GGML_ABORT("fatal error");
  9587. #endif
  9588. if (subctx) {
  9589. // Submit and wait for any pending work before reallocating the buffers
  9590. ggml_vk_ctx_end(subctx);
  9591. ggml_vk_submit(subctx, ctx->fence);
  9592. ggml_vk_wait_for_fence(ctx);
  9593. ggml_vk_ctx_begin(ctx->device, subctx);
  9594. }
  9595. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9596. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9597. // Resize buffer
  9598. if (ctx->prealloc_x != nullptr) {
  9599. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9600. }
  9601. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9602. }
  9603. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9604. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9605. // Resize buffer
  9606. if (ctx->prealloc_y != nullptr) {
  9607. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9608. }
  9609. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9610. }
  9611. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9612. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9613. // Resize buffer
  9614. if (ctx->prealloc_split_k != nullptr) {
  9615. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9616. }
  9617. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9618. }
  9619. if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) {
  9620. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9621. // Resize buffer
  9622. if (ctx->prealloc_add_rms_partials != nullptr) {
  9623. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9624. }
  9625. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9626. }
  9627. }
  9628. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool use_fence, bool almost_ready);
  9629. // Returns true if node has enqueued work into the queue, false otherwise
  9630. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9631. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool last_node, bool almost_ready, bool submit){
  9632. ggml_tensor * node = cgraph->nodes[node_idx];
  9633. if (ggml_is_empty(node) || !node->buffer) {
  9634. return false;
  9635. }
  9636. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9637. ctx->semaphore_idx = 0;
  9638. ggml_tensor * src0 = node->src[0];
  9639. ggml_tensor * src1 = node->src[1];
  9640. ggml_tensor * src2 = node->src[2];
  9641. ggml_tensor * src3 = node->src[3];
  9642. switch (node->op) {
  9643. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9644. case GGML_OP_RESHAPE:
  9645. case GGML_OP_VIEW:
  9646. case GGML_OP_PERMUTE:
  9647. case GGML_OP_TRANSPOSE:
  9648. case GGML_OP_NONE:
  9649. return false;
  9650. case GGML_OP_UNARY:
  9651. switch (ggml_get_unary_op(node)) {
  9652. case GGML_UNARY_OP_EXP:
  9653. case GGML_UNARY_OP_SILU:
  9654. case GGML_UNARY_OP_GELU:
  9655. case GGML_UNARY_OP_GELU_ERF:
  9656. case GGML_UNARY_OP_GELU_QUICK:
  9657. case GGML_UNARY_OP_RELU:
  9658. case GGML_UNARY_OP_TANH:
  9659. case GGML_UNARY_OP_SIGMOID:
  9660. case GGML_UNARY_OP_HARDSIGMOID:
  9661. case GGML_UNARY_OP_HARDSWISH:
  9662. break;
  9663. default:
  9664. return false;
  9665. }
  9666. break;
  9667. case GGML_OP_GLU:
  9668. switch (ggml_get_glu_op(node)) {
  9669. case GGML_GLU_OP_GEGLU:
  9670. case GGML_GLU_OP_REGLU:
  9671. case GGML_GLU_OP_SWIGLU:
  9672. case GGML_GLU_OP_SWIGLU_OAI:
  9673. case GGML_GLU_OP_GEGLU_ERF:
  9674. case GGML_GLU_OP_GEGLU_QUICK:
  9675. break;
  9676. default:
  9677. return false;
  9678. }
  9679. break;
  9680. case GGML_OP_ADD:
  9681. {
  9682. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9683. if (next_node_idx < cgraph->n_nodes &&
  9684. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9685. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9686. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9687. ctx->device->add_rms_fusion) {
  9688. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9689. ctx->do_add_rms_partials_offset_calculation = true;
  9690. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  9691. ctx->do_add_rms_partials = true;
  9692. }
  9693. }
  9694. } break;
  9695. case GGML_OP_REPEAT:
  9696. case GGML_OP_REPEAT_BACK:
  9697. case GGML_OP_GET_ROWS:
  9698. case GGML_OP_ADD_ID:
  9699. case GGML_OP_ACC:
  9700. case GGML_OP_SUB:
  9701. case GGML_OP_MUL:
  9702. case GGML_OP_DIV:
  9703. case GGML_OP_CONCAT:
  9704. case GGML_OP_UPSCALE:
  9705. case GGML_OP_SCALE:
  9706. case GGML_OP_SQR:
  9707. case GGML_OP_SQRT:
  9708. case GGML_OP_SIN:
  9709. case GGML_OP_COS:
  9710. case GGML_OP_CLAMP:
  9711. case GGML_OP_PAD:
  9712. case GGML_OP_ROLL:
  9713. case GGML_OP_CPY:
  9714. case GGML_OP_SET_ROWS:
  9715. case GGML_OP_CONT:
  9716. case GGML_OP_DUP:
  9717. case GGML_OP_SILU_BACK:
  9718. case GGML_OP_NORM:
  9719. case GGML_OP_GROUP_NORM:
  9720. case GGML_OP_RMS_NORM:
  9721. case GGML_OP_RMS_NORM_BACK:
  9722. case GGML_OP_L2_NORM:
  9723. case GGML_OP_DIAG_MASK_INF:
  9724. case GGML_OP_SOFT_MAX:
  9725. case GGML_OP_SOFT_MAX_BACK:
  9726. case GGML_OP_ROPE:
  9727. case GGML_OP_ROPE_BACK:
  9728. case GGML_OP_MUL_MAT:
  9729. case GGML_OP_MUL_MAT_ID:
  9730. case GGML_OP_ARGSORT:
  9731. case GGML_OP_SUM:
  9732. case GGML_OP_SUM_ROWS:
  9733. case GGML_OP_MEAN:
  9734. case GGML_OP_ARGMAX:
  9735. case GGML_OP_COUNT_EQUAL:
  9736. case GGML_OP_IM2COL:
  9737. case GGML_OP_IM2COL_3D:
  9738. case GGML_OP_TIMESTEP_EMBEDDING:
  9739. case GGML_OP_CONV_TRANSPOSE_1D:
  9740. case GGML_OP_POOL_2D:
  9741. case GGML_OP_CONV_2D:
  9742. case GGML_OP_CONV_TRANSPOSE_2D:
  9743. case GGML_OP_CONV_2D_DW:
  9744. case GGML_OP_RWKV_WKV6:
  9745. case GGML_OP_RWKV_WKV7:
  9746. case GGML_OP_SSM_SCAN:
  9747. case GGML_OP_SSM_CONV:
  9748. case GGML_OP_LEAKY_RELU:
  9749. case GGML_OP_FLASH_ATTN_EXT:
  9750. case GGML_OP_OPT_STEP_ADAMW:
  9751. case GGML_OP_OPT_STEP_SGD:
  9752. break;
  9753. default:
  9754. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9755. GGML_ABORT("fatal error");
  9756. }
  9757. vk_context compute_ctx;
  9758. if (ctx->compute_ctx.expired()) {
  9759. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9760. ctx->compute_ctx = compute_ctx;
  9761. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9762. } else {
  9763. compute_ctx = ctx->compute_ctx.lock();
  9764. }
  9765. {
  9766. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9767. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9768. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9769. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9770. // dequantization or split_k, additional synchronization is needed between those passes.
  9771. bool need_sync = false;
  9772. // Check whether "node" requires synchronization. The node requires synchronization if it
  9773. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9774. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9775. // checked against the written list. Two nodes overlap in memory if they come from the same
  9776. // buffer and the tensor or view ranges overlap.
  9777. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9778. if (unsynced_nodes.size() == 0) {
  9779. return false;
  9780. }
  9781. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9782. auto n_size = ggml_nbytes(node);
  9783. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9784. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9785. for (auto &other : unsynced_nodes) {
  9786. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9787. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9788. if (a_buf == o_buf) {
  9789. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9790. auto o_size = ggml_nbytes(other);
  9791. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9792. (n_base <= o_base && o_base < n_base + n_size)) {
  9793. return true;
  9794. }
  9795. }
  9796. }
  9797. return false;
  9798. };
  9799. // For all fused ops, check if the destination node or any of the source
  9800. // nodes require synchronization.
  9801. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9802. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9803. // If the node actually writes to memory, then check if it needs to sync
  9804. if (ctx->fused_ops_write_mask & (1 << i)) {
  9805. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9806. need_sync = true;
  9807. break;
  9808. }
  9809. }
  9810. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9811. if (!cur_node->src[j]) {
  9812. continue;
  9813. }
  9814. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9815. need_sync = true;
  9816. break;
  9817. }
  9818. }
  9819. }
  9820. #define ENABLE_SYNC_LOGGING 0
  9821. if (need_sync) {
  9822. #if ENABLE_SYNC_LOGGING
  9823. std::cerr << "sync" << std::endl;
  9824. #endif
  9825. ctx->unsynced_nodes_written.clear();
  9826. ctx->unsynced_nodes_read.clear();
  9827. ggml_vk_sync_buffers(ctx, compute_ctx);
  9828. }
  9829. // Add all fused nodes to the unsynchronized lists.
  9830. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9831. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9832. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  9833. if (ctx->fused_ops_write_mask & (1 << i)) {
  9834. ctx->unsynced_nodes_written.push_back(cur_node);
  9835. }
  9836. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9837. if (!cur_node->src[j]) {
  9838. continue;
  9839. }
  9840. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9841. }
  9842. }
  9843. }
  9844. #if ENABLE_SYNC_LOGGING
  9845. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9846. auto *n = cgraph->nodes[node_idx + i];
  9847. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  9848. if (n->op == GGML_OP_GLU) {
  9849. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  9850. }
  9851. if (n->op == GGML_OP_ROPE) {
  9852. const int mode = ((const int32_t *) n->op_params)[2];
  9853. std::cerr << " rope mode: " << mode;
  9854. }
  9855. std::cerr << std::endl;
  9856. }
  9857. #endif
  9858. switch (node->op) {
  9859. case GGML_OP_REPEAT:
  9860. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  9861. break;
  9862. case GGML_OP_REPEAT_BACK:
  9863. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  9864. break;
  9865. case GGML_OP_ACC:
  9866. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  9867. break;
  9868. case GGML_OP_GET_ROWS:
  9869. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  9870. break;
  9871. case GGML_OP_ADD:
  9872. if (ctx->num_additional_fused_ops) {
  9873. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  9874. } else {
  9875. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  9876. }
  9877. break;
  9878. case GGML_OP_SUB:
  9879. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  9880. break;
  9881. case GGML_OP_MUL:
  9882. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  9883. break;
  9884. case GGML_OP_DIV:
  9885. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  9886. break;
  9887. case GGML_OP_ADD_ID:
  9888. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  9889. break;
  9890. case GGML_OP_CONCAT:
  9891. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  9892. break;
  9893. case GGML_OP_UPSCALE:
  9894. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  9895. break;
  9896. case GGML_OP_SCALE:
  9897. ggml_vk_scale(ctx, compute_ctx, src0, node);
  9898. break;
  9899. case GGML_OP_SQR:
  9900. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  9901. break;
  9902. case GGML_OP_SQRT:
  9903. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  9904. break;
  9905. case GGML_OP_SIN:
  9906. ggml_vk_sin(ctx, compute_ctx, src0, node);
  9907. break;
  9908. case GGML_OP_COS:
  9909. ggml_vk_cos(ctx, compute_ctx, src0, node);
  9910. break;
  9911. case GGML_OP_CLAMP:
  9912. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  9913. break;
  9914. case GGML_OP_PAD:
  9915. ggml_vk_pad(ctx, compute_ctx, src0, node);
  9916. break;
  9917. case GGML_OP_ROLL:
  9918. ggml_vk_roll(ctx, compute_ctx, src0, node);
  9919. break;
  9920. case GGML_OP_CPY:
  9921. case GGML_OP_CONT:
  9922. case GGML_OP_DUP:
  9923. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  9924. break;
  9925. case GGML_OP_SET_ROWS:
  9926. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  9927. break;
  9928. case GGML_OP_SILU_BACK:
  9929. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  9930. break;
  9931. case GGML_OP_NORM:
  9932. ggml_vk_norm(ctx, compute_ctx, src0, node);
  9933. break;
  9934. case GGML_OP_GROUP_NORM:
  9935. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  9936. break;
  9937. case GGML_OP_RMS_NORM:
  9938. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  9939. break;
  9940. case GGML_OP_RMS_NORM_BACK:
  9941. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  9942. break;
  9943. case GGML_OP_L2_NORM:
  9944. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  9945. break;
  9946. case GGML_OP_UNARY:
  9947. switch (ggml_get_unary_op(node)) {
  9948. case GGML_UNARY_OP_EXP:
  9949. case GGML_UNARY_OP_SILU:
  9950. case GGML_UNARY_OP_GELU:
  9951. case GGML_UNARY_OP_GELU_ERF:
  9952. case GGML_UNARY_OP_GELU_QUICK:
  9953. case GGML_UNARY_OP_RELU:
  9954. case GGML_UNARY_OP_TANH:
  9955. case GGML_UNARY_OP_SIGMOID:
  9956. case GGML_UNARY_OP_HARDSIGMOID:
  9957. case GGML_UNARY_OP_HARDSWISH:
  9958. ggml_vk_unary(ctx, compute_ctx, src0, node);
  9959. break;
  9960. default:
  9961. return false;
  9962. }
  9963. break;
  9964. case GGML_OP_GLU:
  9965. switch (ggml_get_glu_op(node)) {
  9966. case GGML_GLU_OP_GEGLU:
  9967. case GGML_GLU_OP_REGLU:
  9968. case GGML_GLU_OP_SWIGLU:
  9969. case GGML_GLU_OP_SWIGLU_OAI:
  9970. case GGML_GLU_OP_GEGLU_ERF:
  9971. case GGML_GLU_OP_GEGLU_QUICK:
  9972. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  9973. break;
  9974. default:
  9975. return false;
  9976. }
  9977. break;
  9978. case GGML_OP_DIAG_MASK_INF:
  9979. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  9980. break;
  9981. case GGML_OP_SOFT_MAX:
  9982. if (ctx->num_additional_fused_ops) {
  9983. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  9984. } else {
  9985. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  9986. }
  9987. break;
  9988. case GGML_OP_SOFT_MAX_BACK:
  9989. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  9990. break;
  9991. case GGML_OP_ROPE:
  9992. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  9993. break;
  9994. case GGML_OP_ROPE_BACK:
  9995. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  9996. break;
  9997. case GGML_OP_ARGSORT:
  9998. if (ctx->num_additional_fused_ops) {
  9999. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10000. } else {
  10001. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10002. }
  10003. break;
  10004. case GGML_OP_SUM:
  10005. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10006. break;
  10007. case GGML_OP_SUM_ROWS:
  10008. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10009. break;
  10010. case GGML_OP_MEAN:
  10011. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10012. break;
  10013. case GGML_OP_ARGMAX:
  10014. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10015. break;
  10016. case GGML_OP_COUNT_EQUAL:
  10017. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10018. break;
  10019. case GGML_OP_IM2COL:
  10020. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10021. break;
  10022. case GGML_OP_IM2COL_3D:
  10023. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10024. break;
  10025. case GGML_OP_TIMESTEP_EMBEDDING:
  10026. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10027. break;
  10028. case GGML_OP_CONV_TRANSPOSE_1D:
  10029. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10030. break;
  10031. case GGML_OP_POOL_2D:
  10032. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10033. break;
  10034. case GGML_OP_CONV_2D:
  10035. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10036. break;
  10037. case GGML_OP_CONV_TRANSPOSE_2D:
  10038. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node);
  10039. break;
  10040. case GGML_OP_CONV_2D_DW:
  10041. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10042. break;
  10043. case GGML_OP_LEAKY_RELU:
  10044. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10045. break;
  10046. case GGML_OP_MUL_MAT:
  10047. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10048. break;
  10049. case GGML_OP_MUL_MAT_ID:
  10050. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10051. break;
  10052. case GGML_OP_FLASH_ATTN_EXT:
  10053. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10054. break;
  10055. case GGML_OP_RWKV_WKV6:
  10056. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10057. break;
  10058. case GGML_OP_RWKV_WKV7:
  10059. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10060. break;
  10061. case GGML_OP_SSM_SCAN:
  10062. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10063. break;
  10064. case GGML_OP_SSM_CONV:
  10065. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10066. break;
  10067. case GGML_OP_OPT_STEP_ADAMW:
  10068. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10069. break;
  10070. case GGML_OP_OPT_STEP_SGD:
  10071. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10072. break;
  10073. default:
  10074. return false;
  10075. }
  10076. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10077. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10078. // Force context reset on each node so that each tensor ends up in its own context
  10079. // and can be run and compared to its CPU equivalent separately
  10080. last_node = true;
  10081. #endif
  10082. if (submit || last_node) {
  10083. ggml_vk_ctx_end(compute_ctx);
  10084. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10085. if (last_node) {
  10086. compute_ctx->exit_tensor_idx = node_idx_begin;
  10087. }
  10088. else {
  10089. compute_ctx->exit_tensor_idx = -1;
  10090. }
  10091. ctx->compute_ctx.reset();
  10092. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  10093. if (!ok) {
  10094. if (node->op == GGML_OP_UNARY) {
  10095. std::cerr << __func__ << ": error: op not supported UNARY " << node->name << " (" << ggml_unary_op_name(static_cast<ggml_unary_op>(node->op_params[0])) << ")" << std::endl;
  10096. } else if (node->op == GGML_OP_GLU) {
  10097. std::cerr << __func__ << ": error: op not supported GLU " << node->name << " (" << ggml_glu_op_name(static_cast<ggml_glu_op>(node->op_params[0])) << ")" << std::endl;
  10098. } else {
  10099. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10100. }
  10101. }
  10102. }
  10103. return true;
  10104. }
  10105. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool use_fence = true, bool almost_ready = false) {
  10106. GGML_UNUSED(cgraph);
  10107. ggml_backend_buffer * buf = nullptr;
  10108. switch (tensor->op) {
  10109. case GGML_OP_ADD:
  10110. case GGML_OP_ACC:
  10111. case GGML_OP_GET_ROWS:
  10112. case GGML_OP_SUB:
  10113. case GGML_OP_MUL:
  10114. case GGML_OP_DIV:
  10115. case GGML_OP_ADD_ID:
  10116. case GGML_OP_CONCAT:
  10117. case GGML_OP_UPSCALE:
  10118. case GGML_OP_SCALE:
  10119. case GGML_OP_SQR:
  10120. case GGML_OP_SQRT:
  10121. case GGML_OP_SIN:
  10122. case GGML_OP_COS:
  10123. case GGML_OP_CLAMP:
  10124. case GGML_OP_PAD:
  10125. case GGML_OP_ROLL:
  10126. case GGML_OP_CPY:
  10127. case GGML_OP_SET_ROWS:
  10128. case GGML_OP_CONT:
  10129. case GGML_OP_DUP:
  10130. case GGML_OP_SILU_BACK:
  10131. case GGML_OP_NORM:
  10132. case GGML_OP_GROUP_NORM:
  10133. case GGML_OP_RMS_NORM:
  10134. case GGML_OP_RMS_NORM_BACK:
  10135. case GGML_OP_L2_NORM:
  10136. case GGML_OP_DIAG_MASK_INF:
  10137. case GGML_OP_SOFT_MAX:
  10138. case GGML_OP_SOFT_MAX_BACK:
  10139. case GGML_OP_ROPE:
  10140. case GGML_OP_ROPE_BACK:
  10141. case GGML_OP_RESHAPE:
  10142. case GGML_OP_VIEW:
  10143. case GGML_OP_PERMUTE:
  10144. case GGML_OP_TRANSPOSE:
  10145. case GGML_OP_NONE:
  10146. case GGML_OP_ARGSORT:
  10147. case GGML_OP_SUM:
  10148. case GGML_OP_SUM_ROWS:
  10149. case GGML_OP_MEAN:
  10150. case GGML_OP_ARGMAX:
  10151. case GGML_OP_COUNT_EQUAL:
  10152. case GGML_OP_IM2COL:
  10153. case GGML_OP_IM2COL_3D:
  10154. case GGML_OP_TIMESTEP_EMBEDDING:
  10155. case GGML_OP_CONV_TRANSPOSE_1D:
  10156. case GGML_OP_POOL_2D:
  10157. case GGML_OP_CONV_2D:
  10158. case GGML_OP_CONV_TRANSPOSE_2D:
  10159. case GGML_OP_CONV_2D_DW:
  10160. case GGML_OP_RWKV_WKV6:
  10161. case GGML_OP_RWKV_WKV7:
  10162. case GGML_OP_SSM_SCAN:
  10163. case GGML_OP_SSM_CONV:
  10164. case GGML_OP_LEAKY_RELU:
  10165. case GGML_OP_REPEAT:
  10166. case GGML_OP_REPEAT_BACK:
  10167. case GGML_OP_OPT_STEP_ADAMW:
  10168. case GGML_OP_OPT_STEP_SGD:
  10169. buf = tensor->buffer;
  10170. break;
  10171. case GGML_OP_UNARY:
  10172. switch (ggml_get_unary_op(tensor)) {
  10173. case GGML_UNARY_OP_EXP:
  10174. case GGML_UNARY_OP_SILU:
  10175. case GGML_UNARY_OP_GELU:
  10176. case GGML_UNARY_OP_GELU_ERF:
  10177. case GGML_UNARY_OP_GELU_QUICK:
  10178. case GGML_UNARY_OP_RELU:
  10179. case GGML_UNARY_OP_TANH:
  10180. case GGML_UNARY_OP_SIGMOID:
  10181. case GGML_UNARY_OP_HARDSIGMOID:
  10182. case GGML_UNARY_OP_HARDSWISH:
  10183. buf = tensor->buffer;
  10184. break;
  10185. default:
  10186. return false;
  10187. }
  10188. break;
  10189. case GGML_OP_GLU:
  10190. switch (ggml_get_glu_op(tensor)) {
  10191. case GGML_GLU_OP_GEGLU:
  10192. case GGML_GLU_OP_REGLU:
  10193. case GGML_GLU_OP_SWIGLU:
  10194. case GGML_GLU_OP_SWIGLU_OAI:
  10195. case GGML_GLU_OP_GEGLU_ERF:
  10196. case GGML_GLU_OP_GEGLU_QUICK:
  10197. buf = tensor->buffer;
  10198. break;
  10199. default:
  10200. return false;
  10201. }
  10202. break;
  10203. case GGML_OP_MUL_MAT:
  10204. case GGML_OP_MUL_MAT_ID:
  10205. case GGML_OP_FLASH_ATTN_EXT:
  10206. buf = tensor->buffer;
  10207. break;
  10208. default:
  10209. return false;
  10210. }
  10211. if (buf == nullptr) {
  10212. return false;
  10213. }
  10214. VK_LOG_DEBUG("ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << ", view_src=" << tensor->view_src << ", view_offs=" << tensor->view_offs << ")");
  10215. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10216. // always wait for the GPU work to be done for the last submit
  10217. if (tensor_idx == subctx->exit_tensor_idx) {
  10218. use_fence = true;
  10219. }
  10220. // Only run if ctx hasn't been submitted yet
  10221. if (!subctx->seqs.empty()) {
  10222. #ifdef GGML_VULKAN_CHECK_RESULTS
  10223. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10224. use_fence = true;
  10225. #endif
  10226. // Do staging buffer copies
  10227. for (auto& cpy : subctx->in_memcpys) {
  10228. memcpy(cpy.dst, cpy.src, cpy.n);
  10229. }
  10230. for (auto& mset : subctx->memsets) {
  10231. memset(mset.dst, mset.val, mset.n);
  10232. }
  10233. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  10234. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10235. ctx->almost_ready_fence_pending = true;
  10236. } else {
  10237. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  10238. }
  10239. if (use_fence) {
  10240. ggml_vk_wait_for_fence(ctx);
  10241. }
  10242. #ifdef GGML_VULKAN_CHECK_RESULTS
  10243. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10244. #endif
  10245. }
  10246. if (tensor_idx == subctx->exit_tensor_idx) {
  10247. // Do staging buffer copies
  10248. for (auto& cpy : subctx->out_memcpys) {
  10249. memcpy(cpy.dst, cpy.src, cpy.n);
  10250. }
  10251. subctx->in_memcpys.clear();
  10252. subctx->out_memcpys.clear();
  10253. subctx->memsets.clear();
  10254. }
  10255. return true;
  10256. }
  10257. // Clean up after graph processing is done
  10258. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10259. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10260. ctx->prealloc_y_last_pipeline_used = {};
  10261. ctx->unsynced_nodes_written.clear();
  10262. ctx->unsynced_nodes_read.clear();
  10263. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10264. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10265. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10266. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10267. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10268. }
  10269. ctx->gc.semaphores.clear();
  10270. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10271. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10272. }
  10273. ctx->gc.tl_semaphores.clear();
  10274. ctx->semaphore_idx = 0;
  10275. ctx->event_idx = 0;
  10276. for (auto& event : ctx->gc.events) {
  10277. ctx->device->device.resetEvent(event);
  10278. }
  10279. ctx->tensor_ctxs.clear();
  10280. ctx->gc.contexts.clear();
  10281. ctx->pipeline_descriptor_set_requirements = 0;
  10282. ctx->descriptor_set_idx = 0;
  10283. }
  10284. // Clean up on backend free
  10285. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10286. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10287. ggml_vk_graph_cleanup(ctx);
  10288. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10289. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10290. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10291. ctx->prealloc_y_last_pipeline_used = nullptr;
  10292. ctx->prealloc_size_x = 0;
  10293. ctx->prealloc_size_y = 0;
  10294. ctx->prealloc_size_split_k = 0;
  10295. for (auto& event : ctx->gc.events) {
  10296. ctx->device->device.destroyEvent(event);
  10297. }
  10298. ctx->gc.events.clear();
  10299. ctx->device->device.destroyFence(ctx->fence);
  10300. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10301. for (auto& pool : ctx->descriptor_pools) {
  10302. ctx->device->device.destroyDescriptorPool(pool);
  10303. }
  10304. ctx->descriptor_pools.clear();
  10305. ctx->descriptor_sets.clear();
  10306. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10307. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10308. }
  10309. static int ggml_vk_get_device_count() {
  10310. ggml_vk_instance_init();
  10311. return vk_instance.device_indices.size();
  10312. }
  10313. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10314. ggml_vk_instance_init();
  10315. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10316. vk::PhysicalDeviceProperties props;
  10317. devices[device].getProperties(&props);
  10318. snprintf(description, description_size, "%s", props.deviceName.data());
  10319. }
  10320. // backend interface
  10321. #define UNUSED GGML_UNUSED
  10322. // device backend
  10323. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10324. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10325. }
  10326. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10327. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10328. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10329. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10330. delete ctx;
  10331. }
  10332. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10333. return vk_ptr_base;
  10334. UNUSED(buffer);
  10335. }
  10336. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10337. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10338. if (tensor->view_src != nullptr) {
  10339. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10340. }
  10341. return GGML_STATUS_SUCCESS;
  10342. }
  10343. static void ggml_backend_vk_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
  10344. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10345. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10346. vk_buffer buf = buf_ctx->dev_buffer;
  10347. uint32_t val32 = (uint32_t)value * 0x01010101;
  10348. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10349. }
  10350. static void ggml_backend_vk_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10351. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10352. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10353. vk_buffer buf = buf_ctx->dev_buffer;
  10354. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10355. }
  10356. static void ggml_backend_vk_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10357. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10358. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10359. vk_buffer buf = buf_ctx->dev_buffer;
  10360. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10361. }
  10362. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10363. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10364. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10365. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10366. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10367. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10368. ggml_vk_buffer_copy(dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  10369. return true;
  10370. }
  10371. return false;
  10372. UNUSED(buffer);
  10373. }
  10374. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10375. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10376. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10377. }
  10378. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10379. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10380. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10381. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10382. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10383. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10384. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10385. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10386. /* .clear = */ ggml_backend_vk_buffer_clear,
  10387. /* .reset = */ NULL,
  10388. };
  10389. // vk buffer type
  10390. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10391. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10392. return ctx->name.c_str();
  10393. }
  10394. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10395. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10396. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10397. vk_buffer dev_buffer = nullptr;
  10398. try {
  10399. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10400. } catch (const vk::SystemError& e) {
  10401. return nullptr;
  10402. }
  10403. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10404. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10405. }
  10406. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10407. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10408. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10409. }
  10410. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10411. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10412. return ctx->device->suballocation_block_size;
  10413. }
  10414. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10415. return ggml_nbytes(tensor);
  10416. UNUSED(buft);
  10417. }
  10418. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10419. ggml_vk_instance_init();
  10420. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10421. vk_device dev = ggml_vk_get_device(dev_num);
  10422. return &dev->buffer_type;
  10423. }
  10424. // host buffer type
  10425. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10426. return GGML_VK_NAME "_Host";
  10427. UNUSED(buft);
  10428. }
  10429. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10430. return GGML_VK_NAME "_Host";
  10431. UNUSED(buffer);
  10432. }
  10433. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10434. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10435. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10436. }
  10437. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10438. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10439. size += 32; // Behave like the CPU buffer type
  10440. void * ptr = nullptr;
  10441. try {
  10442. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10443. } catch (vk::SystemError& e) {
  10444. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10445. // fallback to cpu buffer
  10446. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10447. }
  10448. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10449. buffer->buft = buft;
  10450. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10451. return buffer;
  10452. UNUSED(buft);
  10453. }
  10454. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10455. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10456. UNUSED(buft);
  10457. }
  10458. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10459. return vk_instance.devices[0]->suballocation_block_size;
  10460. UNUSED(buft);
  10461. }
  10462. // Should be changed to return device-specific host buffer type
  10463. // but that probably requires changes in llama.cpp
  10464. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10465. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10466. /* .iface = */ {
  10467. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10468. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10469. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10470. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10471. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10472. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10473. },
  10474. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10475. /* .context = */ nullptr,
  10476. };
  10477. // Make sure device 0 is initialized
  10478. ggml_vk_instance_init();
  10479. ggml_vk_get_device(0);
  10480. return &ggml_backend_vk_buffer_type_host;
  10481. }
  10482. // backend
  10483. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10484. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10485. return ctx->name.c_str();
  10486. }
  10487. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10488. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10489. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10490. ggml_vk_cleanup(ctx);
  10491. delete ctx;
  10492. delete backend;
  10493. }
  10494. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10495. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10496. return &ctx->device->buffer_type;
  10497. }
  10498. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10499. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10500. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10501. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  10502. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10503. vk_context transfer_ctx;
  10504. if (ctx->transfer_ctx.expired()) {
  10505. // Initialize new transfer context
  10506. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10507. ctx->transfer_ctx = transfer_ctx;
  10508. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10509. } else {
  10510. transfer_ctx = ctx->transfer_ctx.lock();
  10511. }
  10512. vk_buffer buf = buf_ctx->dev_buffer;
  10513. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10514. }
  10515. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10516. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10517. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10518. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  10519. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10520. vk_context transfer_ctx;
  10521. if (ctx->transfer_ctx.expired()) {
  10522. // Initialize new transfer context
  10523. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10524. ctx->transfer_ctx = transfer_ctx;
  10525. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10526. } else {
  10527. transfer_ctx = ctx->transfer_ctx.lock();
  10528. }
  10529. vk_buffer buf = buf_ctx->dev_buffer;
  10530. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10531. }
  10532. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10533. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10534. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10535. if ((dst->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || dst->buffer->buft == ggml_backend_vk_host_buffer_type()) && ggml_backend_buffer_is_vk(src->buffer)) {
  10536. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10537. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10538. vk_context transfer_ctx;
  10539. if (ctx->transfer_ctx.expired()) {
  10540. // Initialize new transfer context
  10541. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10542. ctx->transfer_ctx = transfer_ctx;
  10543. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10544. } else {
  10545. transfer_ctx = ctx->transfer_ctx.lock();
  10546. }
  10547. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10548. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10549. ggml_vk_buffer_copy_async(transfer_ctx, dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  10550. return true;
  10551. }
  10552. return false;
  10553. }
  10554. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10555. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10556. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10557. if(ctx->transfer_ctx.expired()) {
  10558. return;
  10559. }
  10560. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10561. ggml_vk_ctx_end(transfer_ctx);
  10562. for (auto& cpy : transfer_ctx->in_memcpys) {
  10563. memcpy(cpy.dst, cpy.src, cpy.n);
  10564. }
  10565. ggml_vk_submit(transfer_ctx, ctx->fence);
  10566. ggml_vk_wait_for_fence(ctx);
  10567. for (auto& cpy : transfer_ctx->out_memcpys) {
  10568. memcpy(cpy.dst, cpy.src, cpy.n);
  10569. }
  10570. ctx->transfer_ctx.reset();
  10571. }
  10572. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10573. return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  10574. }
  10575. static bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10576. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10577. return false;
  10578. }
  10579. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10580. // additional constraints specific to this fusion
  10581. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10582. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10583. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10584. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10585. // rms_norm only supports f32
  10586. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10587. mul->src[1]->type != GGML_TYPE_F32 ||
  10588. mul->type != GGML_TYPE_F32) {
  10589. return false;
  10590. }
  10591. // if rms_norm is the B operand, then we don't handle broadcast
  10592. if (rms_norm == mul->src[1] &&
  10593. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10594. return false;
  10595. }
  10596. // rms_norm shader assumes contiguous rows
  10597. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10598. return false;
  10599. }
  10600. }
  10601. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10602. // additional constraints specific to this fusion
  10603. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10604. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10605. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10606. // mat-vec only
  10607. if (ggml_nrows(mul) != 1) {
  10608. return false;
  10609. }
  10610. // shaders assume the types match
  10611. if (mul->type != bias->type) {
  10612. return false;
  10613. }
  10614. // shaders reuse the D shape for bias
  10615. if (!ggml_are_same_shape(mul, bias) ||
  10616. !ggml_are_same_stride(mul, bias)) {
  10617. return false;
  10618. }
  10619. // unaligned bias isn't handled
  10620. if (get_misalign_bytes(ctx, bias) != 0) {
  10621. return false;
  10622. }
  10623. }
  10624. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10625. // additional constraints specific to this fusion
  10626. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10627. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10628. const ggml_tensor *bias = add->src[1];
  10629. if (mul != add->src[0]) {
  10630. return false;
  10631. }
  10632. // mat-vec only
  10633. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10634. return false;
  10635. }
  10636. // shaders assume the types match
  10637. if (mul->type != bias->type) {
  10638. return false;
  10639. }
  10640. // shaders assume the bias is contiguous
  10641. if (!ggml_is_contiguous(bias)) {
  10642. return false;
  10643. }
  10644. // the ID tensor must be the same for mul_mat_id and add_id
  10645. if (mul->src[2] != add->src[2]) {
  10646. return false;
  10647. }
  10648. // unaligned bias isn't handled
  10649. if (get_misalign_bytes(ctx, bias) != 0) {
  10650. return false;
  10651. }
  10652. }
  10653. return true;
  10654. }
  10655. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10656. int node_idx, topk_moe_mode mode) {
  10657. const ggml_tensor * softmax;
  10658. const ggml_tensor * weights;
  10659. switch (mode) {
  10660. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10661. softmax = cgraph->nodes[node_idx + 0];
  10662. weights = cgraph->nodes[node_idx + 9];
  10663. break;
  10664. case TOPK_MOE_EARLY_SOFTMAX:
  10665. softmax = cgraph->nodes[node_idx + 0];
  10666. weights = cgraph->nodes[node_idx + 4];
  10667. break;
  10668. case TOPK_MOE_LATE_SOFTMAX:
  10669. softmax = cgraph->nodes[node_idx + 4];
  10670. weights = cgraph->nodes[node_idx + 5];
  10671. break;
  10672. default:
  10673. return false;
  10674. }
  10675. const float * op_params = (const float *)softmax->op_params;
  10676. float scale = op_params[0];
  10677. float max_bias = op_params[1];
  10678. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10679. return false;
  10680. }
  10681. if (scale != 1.0f || max_bias != 0.0f) {
  10682. return false;
  10683. }
  10684. // don't fuse when masks or sinks are present
  10685. if (softmax->src[1] || softmax->src[2]) {
  10686. return false;
  10687. }
  10688. const int n_expert = softmax->ne[0];
  10689. // n_expert must be a power of 2
  10690. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10691. return false;
  10692. }
  10693. if (!ctx->device->subgroup_arithmetic ||
  10694. !ctx->device->subgroup_shuffle ||
  10695. !ctx->device->subgroup_require_full_support ||
  10696. ctx->device->disable_fusion) {
  10697. return false;
  10698. }
  10699. return true;
  10700. }
  10701. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10702. int node_idx) {
  10703. GGML_UNUSED(ctx);
  10704. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  10705. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  10706. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  10707. // ne3 not tested
  10708. if (rope->src[0]->ne[3] != 1) {
  10709. return false;
  10710. }
  10711. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  10712. return false;
  10713. }
  10714. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  10715. return false;
  10716. }
  10717. // The view should flatten two dims of rope into one dim
  10718. if (!ggml_is_contiguous(view) ||
  10719. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  10720. return false;
  10721. }
  10722. // Only norm/neox shaders have the fusion code
  10723. const int mode = ((const int32_t *) rope->op_params)[2];
  10724. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  10725. return false;
  10726. }
  10727. return true;
  10728. }
  10729. // Check whether the tensors overlap in memory but are not equal.
  10730. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  10731. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  10732. // to overlap if they are exactly equal.
  10733. // XXX TODO this check is probably missing from several fusion optimizations.
  10734. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  10735. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  10736. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10737. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  10738. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  10739. if (a_buf == b_buf) {
  10740. auto a_base = vk_tensor_offset(a) + a->view_offs;
  10741. auto a_size = ggml_nbytes(a);
  10742. auto b_base = vk_tensor_offset(b) + b->view_offs;
  10743. auto b_size = ggml_nbytes(b);
  10744. if (a_base == b_base && a_size == b_size) {
  10745. return false;
  10746. }
  10747. if ((b_base <= a_base && a_base < b_base + b_size) ||
  10748. (a_base <= b_base && b_base < a_base + a_size)) {
  10749. return true;
  10750. }
  10751. }
  10752. return false;
  10753. }
  10754. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10755. int node_idx) {
  10756. GGML_UNUSED(ctx);
  10757. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  10758. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10759. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  10760. const int mode = ((const int32_t *) rope->op_params)[2];
  10761. // noncontig tensors aren't tested, and don't seem common in practice
  10762. if (!ggml_is_contiguous(rms) ||
  10763. !ggml_is_contiguous(mul) ||
  10764. !ggml_is_contiguous(rope)) {
  10765. return false;
  10766. }
  10767. // only norm/neox are handled in the shader
  10768. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  10769. return false;
  10770. }
  10771. // shared memory size for passing data from mul->rope
  10772. if (mul->ne[0] > 1024) {
  10773. return false;
  10774. }
  10775. // must not overwrite srcs in a way that's not elementwise
  10776. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  10777. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  10778. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  10779. return false;
  10780. }
  10781. return true;
  10782. }
  10783. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10784. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10785. if (first_node->op != GGML_OP_ADD) {
  10786. return 0;
  10787. }
  10788. if (!ctx->device->multi_add) {
  10789. return 0;
  10790. }
  10791. int32_t num_adds = 1;
  10792. while (node_idx + num_adds < cgraph->n_nodes &&
  10793. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10794. num_adds < MAX_FUSED_ADDS) {
  10795. num_adds++;
  10796. }
  10797. // The shader currently requires same shapes (but different strides are allowed),
  10798. // everything f32, and no misalignment
  10799. for (int32_t i = 0; i < num_adds; ++i) {
  10800. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10801. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10802. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10803. next_node->type != GGML_TYPE_F32 ||
  10804. next_node->src[0]->type != GGML_TYPE_F32 ||
  10805. next_node->src[1]->type != GGML_TYPE_F32 ||
  10806. get_misalign_bytes(ctx, next_node) ||
  10807. get_misalign_bytes(ctx, next_node->src[0]) ||
  10808. get_misalign_bytes(ctx, next_node->src[1])) {
  10809. num_adds = i;
  10810. }
  10811. }
  10812. // Verify we can fuse these
  10813. ggml_op adds[MAX_FUSED_ADDS];
  10814. for (int32_t i = 0; i < num_adds; ++i) {
  10815. adds[i] = GGML_OP_ADD;
  10816. }
  10817. // decrease num_adds if they can't all be fused
  10818. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10819. num_adds--;
  10820. }
  10821. // a single add is not "fused", so just return zero
  10822. if (num_adds == 1) {
  10823. return 0;
  10824. }
  10825. return num_adds;
  10826. }
  10827. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10828. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10829. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10830. if (vk_instance.debug_utils_support) {
  10831. vk::DebugUtilsLabelEXT dul = {};
  10832. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10833. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10834. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10835. }
  10836. ctx->prealloc_size_add_rms_partials_offset = 0;
  10837. ctx->do_add_rms_partials = false;
  10838. ctx->do_add_rms_partials_offset_calculation = false;
  10839. int last_node = cgraph->n_nodes - 1;
  10840. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10841. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10842. last_node -= 1;
  10843. }
  10844. // Reserve tensor context space for all nodes
  10845. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10846. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10847. int submit_node_idx = 0; // index to first node in a batch
  10848. vk_context compute_ctx;
  10849. if (vk_perf_logger_enabled) {
  10850. // allocate/resize the query pool
  10851. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10852. if (ctx->device->query_pool) {
  10853. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10854. }
  10855. vk::QueryPoolCreateInfo query_create_info;
  10856. query_create_info.queryType = vk::QueryType::eTimestamp;
  10857. query_create_info.queryCount = cgraph->n_nodes + 100;
  10858. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10859. ctx->device->num_queries = query_create_info.queryCount;
  10860. }
  10861. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10862. GGML_ASSERT(ctx->compute_ctx.expired());
  10863. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10864. ctx->compute_ctx = compute_ctx;
  10865. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10866. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10867. }
  10868. ctx->prealloc_y_last_pipeline_used = nullptr;
  10869. ctx->prealloc_y_last_tensor_used = nullptr;
  10870. if (ctx->prealloc_size_add_rms_partials) {
  10871. ggml_vk_preallocate_buffers(ctx, nullptr);
  10872. if (ctx->compute_ctx.expired()) {
  10873. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10874. ctx->compute_ctx = compute_ctx;
  10875. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10876. } else {
  10877. compute_ctx = ctx->compute_ctx.lock();
  10878. }
  10879. // initialize partial sums to zero.
  10880. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10881. ggml_vk_sync_buffers(ctx, compute_ctx);
  10882. }
  10883. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10884. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10885. // (and scaled down based on model size, so smaller models submit earlier).
  10886. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10887. int nodes_per_submit = 100;
  10888. int submitted_nodes = 0;
  10889. int submit_count = 0;
  10890. uint64_t mul_mat_bytes = 0;
  10891. uint64_t total_mul_mat_bytes = 0;
  10892. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  10893. for (int i = 0; i < cgraph->n_nodes; i++) {
  10894. if (first_node_in_batch) {
  10895. submit_node_idx = i;
  10896. }
  10897. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10898. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  10899. mul_mat_bytes += bytes;
  10900. total_mul_mat_bytes += bytes;
  10901. }
  10902. if (!ctx->device->disable_fusion) {
  10903. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10904. if (num_adds) {
  10905. ctx->num_additional_fused_ops = num_adds - 1;
  10906. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  10907. ctx->num_additional_fused_ops = 1;
  10908. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  10909. ctx->num_additional_fused_ops = 1;
  10910. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 4 }) &&
  10911. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  10912. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  10913. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  10914. ctx->num_additional_fused_ops = 4;
  10915. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  10916. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  10917. ctx->num_additional_fused_ops = 2;
  10918. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10919. ctx->num_additional_fused_ops = 1;
  10920. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  10921. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  10922. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  10923. ctx->num_additional_fused_ops = 2;
  10924. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  10925. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  10926. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  10927. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  10928. // view of argsort writes to memory
  10929. ctx->fused_ops_write_mask |= 1 << 3;
  10930. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  10931. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  10932. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  10933. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  10934. // view of argsort writes to memory
  10935. ctx->fused_ops_write_mask |= 1 << 3;
  10936. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  10937. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  10938. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  10939. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  10940. // view of argsort writes to memory
  10941. ctx->fused_ops_write_mask |= 1 << 1;
  10942. }
  10943. }
  10944. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  10945. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10946. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10947. bool submit = (submitted_nodes >= nodes_per_submit) ||
  10948. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  10949. (i + ctx->num_additional_fused_ops >= last_node) ||
  10950. (almost_ready && !ctx->almost_ready_fence_pending);
  10951. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  10952. if (vk_perf_logger_enabled) {
  10953. if (ctx->compute_ctx.expired()) {
  10954. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10955. ctx->compute_ctx = compute_ctx;
  10956. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10957. } else {
  10958. compute_ctx = ctx->compute_ctx.lock();
  10959. }
  10960. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  10961. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  10962. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  10963. }
  10964. }
  10965. if (enqueued) {
  10966. ++submitted_nodes;
  10967. #ifndef GGML_VULKAN_CHECK_RESULTS
  10968. if (first_node_in_batch) {
  10969. first_node_in_batch = false;
  10970. }
  10971. #endif
  10972. }
  10973. if (submit && enqueued) {
  10974. first_node_in_batch = true;
  10975. submitted_nodes = 0;
  10976. mul_mat_bytes = 0;
  10977. if (submit_count < 3) {
  10978. mul_mat_bytes_per_submit *= 2;
  10979. }
  10980. submit_count++;
  10981. }
  10982. i += ctx->num_additional_fused_ops;
  10983. ctx->num_additional_fused_ops = 0;
  10984. ctx->fused_ops_write_mask = 0;
  10985. }
  10986. ctx->prealloc_size_add_rms_partials = std::max(ctx->prealloc_size_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  10987. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  10988. if (vk_perf_logger_enabled) {
  10989. // End the command buffer and submit/wait
  10990. GGML_ASSERT(!ctx->compute_ctx.expired());
  10991. compute_ctx = ctx->compute_ctx.lock();
  10992. ggml_vk_ctx_end(compute_ctx);
  10993. ggml_vk_submit(compute_ctx, ctx->device->fence);
  10994. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  10995. ctx->device->device.resetFences({ ctx->device->fence });
  10996. // Get the results and pass them to the logger
  10997. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  10998. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->device->query_pool, 0, cgraph->n_nodes + 1, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  10999. for (int i = 0; i < cgraph->n_nodes; i++) {
  11000. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11001. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11002. }
  11003. }
  11004. ctx->device->perf_logger->print_timings();
  11005. }
  11006. ggml_vk_graph_cleanup(ctx);
  11007. return GGML_STATUS_SUCCESS;
  11008. UNUSED(backend);
  11009. }
  11010. // Sort the graph for improved parallelism.
  11011. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11012. {
  11013. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11014. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11015. if (ctx->device->disable_graph_optimize) {
  11016. return;
  11017. }
  11018. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11019. return node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  11020. };
  11021. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11022. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11023. if (dst->src[s] == src) {
  11024. return true;
  11025. }
  11026. }
  11027. // implicit dependency if they view the same tensor
  11028. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11029. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11030. if (dst2 == src2) {
  11031. return true;
  11032. }
  11033. return false;
  11034. };
  11035. // This function tries to reorder the graph to allow nodes to run in parallel.
  11036. // This helps with small batches, but for large batches its a slowdown, probably
  11037. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11038. int num_small_nodes = 0;
  11039. int num_counted_nodes = 0;
  11040. for (int i = 0; i < graph->n_nodes; ++i) {
  11041. if (!is_empty(graph->nodes[i]) &&
  11042. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11043. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11044. num_small_nodes++;
  11045. }
  11046. num_counted_nodes++;
  11047. }
  11048. }
  11049. if (num_small_nodes < num_counted_nodes / 2) {
  11050. return;
  11051. }
  11052. std::vector<ggml_tensor *> new_order;
  11053. std::vector<bool> used(graph->n_nodes, false);
  11054. int first_unused = 0;
  11055. while (first_unused < graph->n_nodes) {
  11056. std::vector<int> current_set;
  11057. // Check for fusion patterns and avoid reordering them
  11058. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11059. if (start + (int)pattern.size() <= graph->n_nodes) {
  11060. bool is_pattern = true;
  11061. for (size_t j = 0; j < pattern.size(); ++j) {
  11062. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11063. is_pattern = false;
  11064. }
  11065. }
  11066. return is_pattern;
  11067. }
  11068. return false;
  11069. };
  11070. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11071. if (match_pattern(pattern, first_unused)) {
  11072. for (size_t j = 0; j < pattern.size(); ++j) {
  11073. new_order.push_back(graph->nodes[first_unused + j]);
  11074. used[first_unused + j] = true;
  11075. }
  11076. while (first_unused < graph->n_nodes && used[first_unused]) {
  11077. first_unused++;
  11078. }
  11079. return true;
  11080. }
  11081. return false;
  11082. };
  11083. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11084. continue;
  11085. }
  11086. if (keep_pattern(topk_moe_early_softmax)) {
  11087. continue;
  11088. }
  11089. if (keep_pattern(topk_moe_late_softmax)) {
  11090. continue;
  11091. }
  11092. // First, grab the next unused node.
  11093. current_set.push_back(first_unused);
  11094. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11095. // haven't already been run. Nodes that have already been run have used[i] set
  11096. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11097. // that we support (e.g. RMS_NORM + MUL).
  11098. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11099. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11100. const int NUM_TO_CHECK = 20;
  11101. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11102. if (used[j]) {
  11103. continue;
  11104. }
  11105. if (is_empty(graph->nodes[j])) {
  11106. continue;
  11107. }
  11108. // Don't pull forward nodes from fusion patterns
  11109. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11110. match_pattern(topk_moe_early_softmax, j) ||
  11111. match_pattern(topk_moe_late_softmax, j)) {
  11112. continue;
  11113. }
  11114. bool ok = true;
  11115. for (int c = first_unused; c < j; ++c) {
  11116. if (!used[c] &&
  11117. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11118. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11119. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11120. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID)) {
  11121. ok = false;
  11122. break;
  11123. }
  11124. }
  11125. if (ok) {
  11126. current_set.push_back(j);
  11127. int rope_idx = j;
  11128. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11129. if (j > 0 &&
  11130. graph->nodes[j]->op == GGML_OP_MUL &&
  11131. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11132. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11133. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11134. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11135. // Check that other srcs are already valid
  11136. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11137. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11138. rope_idx = k;
  11139. current_set.push_back(rope_idx);
  11140. used[rope_idx] = true;
  11141. break;
  11142. }
  11143. }
  11144. }
  11145. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11146. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11147. int view_idx = -1;
  11148. int set_rows_idx = -1;
  11149. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11150. if (view_idx == -1 &&
  11151. graph->nodes[k]->op == GGML_OP_VIEW &&
  11152. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11153. view_idx = k;
  11154. continue;
  11155. }
  11156. if (view_idx != -1 &&
  11157. set_rows_idx == -1 &&
  11158. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11159. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11160. set_rows_idx = k;
  11161. break;
  11162. }
  11163. }
  11164. if (set_rows_idx != -1) {
  11165. current_set.push_back(view_idx);
  11166. current_set.push_back(set_rows_idx);
  11167. used[view_idx] = true;
  11168. used[set_rows_idx] = true;
  11169. }
  11170. }
  11171. }
  11172. }
  11173. // Second pass grabs view nodes.
  11174. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11175. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11176. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11177. if (used[j]) {
  11178. continue;
  11179. }
  11180. if (!is_empty(graph->nodes[j])) {
  11181. continue;
  11182. }
  11183. bool ok = true;
  11184. for (int c = first_unused; c < j; ++c) {
  11185. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11186. // skip views whose srcs haven't been processed.
  11187. if (!used[c] &&
  11188. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11189. !c_in_current_set) {
  11190. ok = false;
  11191. break;
  11192. }
  11193. }
  11194. if (ok) {
  11195. current_set.push_back(j);
  11196. }
  11197. }
  11198. }
  11199. // Push the current set into new_order
  11200. for (auto c : current_set) {
  11201. new_order.push_back(graph->nodes[c]);
  11202. used[c] = true;
  11203. }
  11204. while (first_unused < graph->n_nodes && used[first_unused]) {
  11205. first_unused++;
  11206. }
  11207. }
  11208. // Replace the graph with the new order.
  11209. for (int i = 0; i < graph->n_nodes; ++i) {
  11210. graph->nodes[i] = new_order[i];
  11211. }
  11212. }
  11213. // TODO: enable async and synchronize
  11214. static ggml_backend_i ggml_backend_vk_interface = {
  11215. /* .get_name = */ ggml_backend_vk_name,
  11216. /* .free = */ ggml_backend_vk_free,
  11217. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11218. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  11219. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11220. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  11221. /* .graph_plan_create = */ NULL,
  11222. /* .graph_plan_free = */ NULL,
  11223. /* .graph_plan_update = */ NULL,
  11224. /* .graph_plan_compute = */ NULL,
  11225. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11226. /* .event_record = */ NULL,
  11227. /* .event_wait = */ NULL,
  11228. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11229. };
  11230. static ggml_guid_t ggml_backend_vk_guid() {
  11231. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11232. return &guid;
  11233. }
  11234. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11235. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11236. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11237. ggml_vk_init(ctx, dev_num);
  11238. ggml_backend_t vk_backend = new ggml_backend {
  11239. /* .guid = */ ggml_backend_vk_guid(),
  11240. /* .iface = */ ggml_backend_vk_interface,
  11241. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11242. /* .context = */ ctx,
  11243. };
  11244. return vk_backend;
  11245. }
  11246. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11247. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11248. }
  11249. int ggml_backend_vk_get_device_count() {
  11250. return ggml_vk_get_device_count();
  11251. }
  11252. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11253. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11254. int dev_idx = vk_instance.device_indices[device];
  11255. ggml_vk_get_device_description(dev_idx, description, description_size);
  11256. }
  11257. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11258. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11259. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11260. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11261. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11262. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11263. bool membudget_supported = vk_instance.device_supports_membudget[device];
  11264. if (membudget_supported) {
  11265. memprops.pNext = &budgetprops;
  11266. }
  11267. vkdev.getMemoryProperties2(&memprops);
  11268. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11269. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11270. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  11271. *total = heap.size;
  11272. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11273. *free = budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11274. } else {
  11275. *free = heap.size;
  11276. }
  11277. break;
  11278. }
  11279. }
  11280. }
  11281. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11282. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11283. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11284. vk::PhysicalDeviceProperties2 props = {};
  11285. device.getProperties2(&props);
  11286. return props.properties.deviceType;
  11287. }
  11288. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11289. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11290. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11291. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11292. bool ext_support = false;
  11293. for (const auto& properties : ext_props) {
  11294. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11295. ext_support = true;
  11296. break;
  11297. }
  11298. }
  11299. if (!ext_support) {
  11300. return "";
  11301. }
  11302. vk::PhysicalDeviceProperties2 props = {};
  11303. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11304. props.pNext = &pci_bus_info;
  11305. device.getProperties2(&props);
  11306. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11307. const uint32_t pci_bus = pci_bus_info.pciBus;
  11308. const uint32_t pci_device = pci_bus_info.pciDevice;
  11309. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11310. char pci_bus_id[16] = {};
  11311. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11312. return std::string(pci_bus_id);
  11313. }
  11314. //////////////////////////
  11315. struct ggml_backend_vk_device_context {
  11316. size_t device;
  11317. std::string name;
  11318. std::string description;
  11319. bool is_integrated_gpu;
  11320. std::string pci_bus_id;
  11321. };
  11322. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11323. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11324. return ctx->name.c_str();
  11325. }
  11326. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11327. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11328. return ctx->description.c_str();
  11329. }
  11330. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11331. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11332. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11333. }
  11334. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11335. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11336. return ggml_backend_vk_buffer_type(ctx->device);
  11337. }
  11338. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11339. UNUSED(dev);
  11340. return ggml_backend_vk_host_buffer_type();
  11341. }
  11342. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11343. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11344. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11345. }
  11346. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11347. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11348. props->name = ggml_backend_vk_device_get_name(dev);
  11349. props->description = ggml_backend_vk_device_get_description(dev);
  11350. props->type = ggml_backend_vk_device_get_type(dev);
  11351. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11352. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11353. props->caps = {
  11354. /* .async = */ false,
  11355. /* .host_buffer = */ true,
  11356. /* .buffer_from_host_ptr = */ false,
  11357. /* .events = */ false,
  11358. };
  11359. }
  11360. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11361. UNUSED(params);
  11362. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11363. return ggml_backend_vk_init(ctx->device);
  11364. }
  11365. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11366. switch (op->op) {
  11367. case GGML_OP_UNARY:
  11368. switch (ggml_get_unary_op(op)) {
  11369. case GGML_UNARY_OP_EXP:
  11370. case GGML_UNARY_OP_GELU:
  11371. case GGML_UNARY_OP_GELU_ERF:
  11372. case GGML_UNARY_OP_GELU_QUICK:
  11373. case GGML_UNARY_OP_SILU:
  11374. case GGML_UNARY_OP_RELU:
  11375. case GGML_UNARY_OP_TANH:
  11376. case GGML_UNARY_OP_SIGMOID:
  11377. case GGML_UNARY_OP_HARDSIGMOID:
  11378. case GGML_UNARY_OP_HARDSWISH:
  11379. return ggml_is_contiguous(op->src[0]) &&
  11380. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11381. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11382. (op->src[0]->type == op->type);
  11383. default:
  11384. return false;
  11385. }
  11386. case GGML_OP_GLU:
  11387. switch (ggml_get_glu_op(op)) {
  11388. case GGML_GLU_OP_GEGLU:
  11389. case GGML_GLU_OP_REGLU:
  11390. case GGML_GLU_OP_SWIGLU:
  11391. case GGML_GLU_OP_SWIGLU_OAI:
  11392. case GGML_GLU_OP_GEGLU_ERF:
  11393. case GGML_GLU_OP_GEGLU_QUICK:
  11394. return ggml_is_contiguous(op->src[0]) &&
  11395. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11396. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11397. (op->src[0]->type == op->type);
  11398. default:
  11399. return false;
  11400. }
  11401. case GGML_OP_MUL_MAT:
  11402. case GGML_OP_MUL_MAT_ID:
  11403. {
  11404. ggml_type src0_type = op->src[0]->type;
  11405. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11406. const vk_device& device = ggml_vk_get_device(ctx->device);
  11407. if (op->op == GGML_OP_MUL_MAT_ID) {
  11408. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11409. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11410. return false;
  11411. }
  11412. }
  11413. switch (src0_type) {
  11414. case GGML_TYPE_F32:
  11415. case GGML_TYPE_F16:
  11416. case GGML_TYPE_BF16:
  11417. case GGML_TYPE_Q4_0:
  11418. case GGML_TYPE_Q4_1:
  11419. case GGML_TYPE_Q5_0:
  11420. case GGML_TYPE_Q5_1:
  11421. case GGML_TYPE_Q8_0:
  11422. case GGML_TYPE_Q2_K:
  11423. case GGML_TYPE_Q3_K:
  11424. case GGML_TYPE_Q4_K:
  11425. case GGML_TYPE_Q5_K:
  11426. case GGML_TYPE_Q6_K:
  11427. case GGML_TYPE_IQ1_S:
  11428. case GGML_TYPE_IQ1_M:
  11429. case GGML_TYPE_IQ2_XXS:
  11430. case GGML_TYPE_IQ2_XS:
  11431. case GGML_TYPE_IQ2_S:
  11432. case GGML_TYPE_IQ3_XXS:
  11433. case GGML_TYPE_IQ3_S:
  11434. case GGML_TYPE_IQ4_XS:
  11435. case GGML_TYPE_IQ4_NL:
  11436. case GGML_TYPE_MXFP4:
  11437. break;
  11438. default:
  11439. return false;
  11440. }
  11441. struct ggml_tensor * a;
  11442. struct ggml_tensor * b;
  11443. if (op->op == GGML_OP_MUL_MAT) {
  11444. a = op->src[0];
  11445. b = op->src[1];
  11446. } else {
  11447. a = op->src[2];
  11448. b = op->src[1];
  11449. }
  11450. if (a->ne[3] != b->ne[3]) {
  11451. return false;
  11452. }
  11453. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
  11454. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11455. return false;
  11456. }
  11457. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11458. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11459. // So don't support this combination for now.
  11460. return false;
  11461. }
  11462. return true;
  11463. }
  11464. case GGML_OP_FLASH_ATTN_EXT:
  11465. {
  11466. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11467. auto device = ggml_vk_get_device(ctx->device);
  11468. bool coopmat2 = device->coopmat2;
  11469. uint32_t HSK = op->src[1]->ne[0];
  11470. uint32_t HSV = op->src[2]->ne[0];
  11471. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11472. return false;
  11473. }
  11474. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11475. return false;
  11476. }
  11477. if (op->src[0]->type != GGML_TYPE_F32) {
  11478. return false;
  11479. }
  11480. if (op->type != GGML_TYPE_F32) {
  11481. return false;
  11482. }
  11483. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11484. return false;
  11485. }
  11486. // It's straightforward to support different K/V dequant, but would
  11487. // significantly increase the number of pipelines
  11488. if (op->src[1]->type != op->src[2]->type) {
  11489. return false;
  11490. }
  11491. switch (op->src[1]->type) {
  11492. case GGML_TYPE_F16:
  11493. case GGML_TYPE_F32:
  11494. case GGML_TYPE_Q4_0:
  11495. case GGML_TYPE_Q8_0:
  11496. // supported in scalar and coopmat2 paths
  11497. break;
  11498. case GGML_TYPE_Q4_1:
  11499. case GGML_TYPE_Q5_0:
  11500. case GGML_TYPE_Q5_1:
  11501. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11502. //case GGML_TYPE_Q2_K:
  11503. //case GGML_TYPE_Q3_K:
  11504. //case GGML_TYPE_Q4_K:
  11505. //case GGML_TYPE_Q5_K:
  11506. //case GGML_TYPE_Q6_K:
  11507. //case GGML_TYPE_IQ1_S:
  11508. //case GGML_TYPE_IQ1_M:
  11509. //case GGML_TYPE_IQ2_XXS:
  11510. //case GGML_TYPE_IQ2_XS:
  11511. //case GGML_TYPE_IQ2_S:
  11512. //case GGML_TYPE_IQ3_XXS:
  11513. //case GGML_TYPE_IQ3_S:
  11514. //case GGML_TYPE_IQ4_XS:
  11515. case GGML_TYPE_IQ4_NL:
  11516. // currently supported only in coopmat2 path
  11517. if (!coopmat2) {
  11518. return false;
  11519. }
  11520. break;
  11521. default:
  11522. return false;
  11523. }
  11524. if (!coopmat2 && !device->subgroup_shuffle) {
  11525. // scalar FA uses subgroupShuffle
  11526. return false;
  11527. }
  11528. return true;
  11529. }
  11530. case GGML_OP_GET_ROWS:
  11531. {
  11532. switch (op->src[0]->type) {
  11533. case GGML_TYPE_F32:
  11534. case GGML_TYPE_F16:
  11535. case GGML_TYPE_BF16:
  11536. case GGML_TYPE_Q4_0:
  11537. case GGML_TYPE_Q4_1:
  11538. case GGML_TYPE_Q5_0:
  11539. case GGML_TYPE_Q5_1:
  11540. case GGML_TYPE_Q8_0:
  11541. case GGML_TYPE_Q2_K:
  11542. case GGML_TYPE_Q3_K:
  11543. case GGML_TYPE_Q4_K:
  11544. case GGML_TYPE_Q5_K:
  11545. case GGML_TYPE_Q6_K:
  11546. case GGML_TYPE_IQ1_S:
  11547. case GGML_TYPE_IQ1_M:
  11548. case GGML_TYPE_IQ2_XXS:
  11549. case GGML_TYPE_IQ2_XS:
  11550. case GGML_TYPE_IQ2_S:
  11551. case GGML_TYPE_IQ3_XXS:
  11552. case GGML_TYPE_IQ3_S:
  11553. case GGML_TYPE_IQ4_XS:
  11554. case GGML_TYPE_IQ4_NL:
  11555. case GGML_TYPE_MXFP4:
  11556. return true;
  11557. default:
  11558. return false;
  11559. }
  11560. }
  11561. case GGML_OP_SET_ROWS:
  11562. {
  11563. switch (op->type) {
  11564. case GGML_TYPE_F32:
  11565. case GGML_TYPE_F16:
  11566. case GGML_TYPE_BF16:
  11567. case GGML_TYPE_Q4_0:
  11568. case GGML_TYPE_Q4_1:
  11569. case GGML_TYPE_Q5_0:
  11570. case GGML_TYPE_Q5_1:
  11571. case GGML_TYPE_Q8_0:
  11572. case GGML_TYPE_IQ4_NL:
  11573. return true;
  11574. default:
  11575. return false;
  11576. }
  11577. }
  11578. case GGML_OP_CONT:
  11579. case GGML_OP_CPY:
  11580. case GGML_OP_DUP:
  11581. {
  11582. ggml_type src0_type = op->src[0]->type;
  11583. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11584. if (src0_type == GGML_TYPE_F32) {
  11585. switch (src1_type) {
  11586. case GGML_TYPE_F32:
  11587. case GGML_TYPE_F16:
  11588. case GGML_TYPE_BF16:
  11589. case GGML_TYPE_Q4_0:
  11590. case GGML_TYPE_Q4_1:
  11591. case GGML_TYPE_Q5_0:
  11592. case GGML_TYPE_Q5_1:
  11593. case GGML_TYPE_Q8_0:
  11594. case GGML_TYPE_IQ4_NL:
  11595. return true;
  11596. default:
  11597. break;
  11598. }
  11599. }
  11600. if (src1_type == GGML_TYPE_F32) {
  11601. switch (src0_type) {
  11602. case GGML_TYPE_F16:
  11603. case GGML_TYPE_Q4_0:
  11604. case GGML_TYPE_Q4_1:
  11605. case GGML_TYPE_Q5_0:
  11606. case GGML_TYPE_Q5_1:
  11607. case GGML_TYPE_Q8_0:
  11608. case GGML_TYPE_IQ4_NL:
  11609. return true;
  11610. default:
  11611. break;
  11612. }
  11613. }
  11614. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11615. return true;
  11616. }
  11617. if (
  11618. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11619. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11620. ) {
  11621. return true;
  11622. }
  11623. // We can handle copying from a type to the same type if it's
  11624. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  11625. // so the type/block size must be a multiple of 4.
  11626. if (src0_type == src1_type &&
  11627. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  11628. (ggml_type_size(src0_type) % 2) == 0) {
  11629. return true;
  11630. }
  11631. return false;
  11632. }
  11633. case GGML_OP_REPEAT:
  11634. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11635. case GGML_OP_REPEAT_BACK:
  11636. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11637. case GGML_OP_ROPE:
  11638. case GGML_OP_ROPE_BACK:
  11639. case GGML_OP_NONE:
  11640. case GGML_OP_RESHAPE:
  11641. case GGML_OP_VIEW:
  11642. case GGML_OP_PERMUTE:
  11643. case GGML_OP_TRANSPOSE:
  11644. case GGML_OP_RMS_NORM:
  11645. return true;
  11646. case GGML_OP_NORM:
  11647. case GGML_OP_GROUP_NORM:
  11648. case GGML_OP_L2_NORM:
  11649. return ggml_is_contiguous(op->src[0]);
  11650. case GGML_OP_ADD:
  11651. case GGML_OP_SUB:
  11652. case GGML_OP_MUL:
  11653. case GGML_OP_DIV:
  11654. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11655. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11656. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11657. case GGML_OP_ADD_ID:
  11658. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11659. op->type == GGML_TYPE_F32;
  11660. case GGML_OP_SILU_BACK:
  11661. case GGML_OP_RMS_NORM_BACK:
  11662. case GGML_OP_SQR:
  11663. case GGML_OP_SQRT:
  11664. case GGML_OP_SIN:
  11665. case GGML_OP_COS:
  11666. case GGML_OP_CLAMP:
  11667. case GGML_OP_LEAKY_RELU:
  11668. case GGML_OP_OPT_STEP_ADAMW:
  11669. case GGML_OP_OPT_STEP_SGD:
  11670. return op->src[0]->type == GGML_TYPE_F32;
  11671. case GGML_OP_ARGSORT:
  11672. return op->ne[0] <= max_argsort_cols;
  11673. case GGML_OP_UPSCALE:
  11674. case GGML_OP_ACC:
  11675. case GGML_OP_CONCAT:
  11676. case GGML_OP_SCALE:
  11677. case GGML_OP_PAD:
  11678. case GGML_OP_ROLL:
  11679. case GGML_OP_DIAG_MASK_INF:
  11680. case GGML_OP_SOFT_MAX:
  11681. case GGML_OP_SOFT_MAX_BACK:
  11682. return true;
  11683. case GGML_OP_SUM:
  11684. case GGML_OP_SUM_ROWS:
  11685. case GGML_OP_MEAN:
  11686. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11687. case GGML_OP_ARGMAX:
  11688. case GGML_OP_COUNT_EQUAL:
  11689. case GGML_OP_IM2COL:
  11690. case GGML_OP_IM2COL_3D:
  11691. case GGML_OP_TIMESTEP_EMBEDDING:
  11692. case GGML_OP_CONV_2D_DW:
  11693. case GGML_OP_POOL_2D:
  11694. case GGML_OP_RWKV_WKV6:
  11695. case GGML_OP_RWKV_WKV7:
  11696. return true;
  11697. case GGML_OP_SSM_SCAN:
  11698. {
  11699. for (int i = 0; i < 6; i++) {
  11700. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  11701. return false;
  11702. }
  11703. }
  11704. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  11705. return false;
  11706. }
  11707. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  11708. return false;
  11709. }
  11710. const uint32_t d_state = op->src[0]->ne[0];
  11711. const uint32_t head_dim = op->src[0]->ne[1];
  11712. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  11713. if (!is_mamba2) {
  11714. return false;
  11715. }
  11716. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  11717. return false;
  11718. }
  11719. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11720. const vk_device& device = ggml_vk_get_device(ctx->device);
  11721. const uint32_t SPLIT_H = 16;
  11722. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  11723. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  11724. return false;
  11725. }
  11726. return true;
  11727. }
  11728. case GGML_OP_SSM_CONV:
  11729. return true;
  11730. case GGML_OP_CONV_TRANSPOSE_1D:
  11731. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11732. case GGML_OP_CONV_2D:
  11733. case GGML_OP_CONV_TRANSPOSE_2D:
  11734. {
  11735. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  11736. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11737. const vk_device& device = ggml_vk_get_device(ctx->device);
  11738. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  11739. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  11740. return false;
  11741. }
  11742. // Channel-contiguous format is not supported yet.
  11743. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11744. op->src[1]->type == GGML_TYPE_F32 &&
  11745. op->type == GGML_TYPE_F32 &&
  11746. ggml_is_contiguous(op->src[0]) &&
  11747. ggml_is_contiguous(op->src[1]) &&
  11748. ggml_is_contiguous(op));
  11749. }
  11750. default:
  11751. return false;
  11752. }
  11753. UNUSED(dev);
  11754. }
  11755. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11756. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11757. return false;
  11758. }
  11759. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11760. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11761. return buft_ctx->device->idx == ctx->device;
  11762. }
  11763. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11764. const int min_batch_size = 32;
  11765. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11766. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11767. UNUSED(dev);
  11768. }
  11769. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11770. /* .get_name = */ ggml_backend_vk_device_get_name,
  11771. /* .get_description = */ ggml_backend_vk_device_get_description,
  11772. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11773. /* .get_type = */ ggml_backend_vk_device_get_type,
  11774. /* .get_props = */ ggml_backend_vk_device_get_props,
  11775. /* .init_backend = */ ggml_backend_vk_device_init,
  11776. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11777. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11778. /* .buffer_from_host_ptr = */ NULL,
  11779. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11780. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11781. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11782. /* .event_new = */ NULL,
  11783. /* .event_free = */ NULL,
  11784. /* .event_synchronize = */ NULL,
  11785. };
  11786. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11787. UNUSED(reg);
  11788. return GGML_VK_NAME;
  11789. }
  11790. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11791. UNUSED(reg);
  11792. return ggml_backend_vk_get_device_count();
  11793. }
  11794. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11795. static std::vector<ggml_backend_dev_t> devices;
  11796. static bool initialized = false;
  11797. {
  11798. static std::mutex mutex;
  11799. std::lock_guard<std::mutex> lock(mutex);
  11800. if (!initialized) {
  11801. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11802. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11803. char desc[256];
  11804. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11805. ctx->device = i;
  11806. ctx->name = GGML_VK_NAME + std::to_string(i);
  11807. ctx->description = desc;
  11808. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11809. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11810. devices.push_back(new ggml_backend_device {
  11811. /* .iface = */ ggml_backend_vk_device_i,
  11812. /* .reg = */ reg,
  11813. /* .context = */ ctx,
  11814. });
  11815. }
  11816. initialized = true;
  11817. }
  11818. }
  11819. GGML_ASSERT(device < devices.size());
  11820. return devices[device];
  11821. }
  11822. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11823. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11824. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11825. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11826. /* .get_proc_address = */ NULL,
  11827. };
  11828. ggml_backend_reg_t ggml_backend_vk_reg() {
  11829. static ggml_backend_reg reg = {
  11830. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11831. /* .iface = */ ggml_backend_vk_reg_i,
  11832. /* .context = */ nullptr,
  11833. };
  11834. try {
  11835. ggml_vk_instance_init();
  11836. return &reg;
  11837. } catch (const vk::SystemError& e) {
  11838. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11839. return nullptr;
  11840. } catch (const std::exception &e) {
  11841. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  11842. return nullptr;
  11843. } catch (...) {
  11844. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  11845. return nullptr;
  11846. }
  11847. }
  11848. // Extension availability
  11849. static bool ggml_vk_instance_validation_ext_available() {
  11850. #ifdef GGML_VULKAN_VALIDATE
  11851. // Check if validation layer provides the extension
  11852. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11853. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11854. if (layer_name == layer.layerName.data()) {
  11855. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11856. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11857. return true;
  11858. }
  11859. }
  11860. }
  11861. }
  11862. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11863. #endif
  11864. return false;
  11865. }
  11866. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11867. #ifdef __APPLE__
  11868. // Check for portability enumeration extension for MoltenVK support
  11869. for (const auto& properties : instance_extensions) {
  11870. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11871. return true;
  11872. }
  11873. }
  11874. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11875. #endif
  11876. return false;
  11877. UNUSED(instance_extensions);
  11878. }
  11879. // Extension availability
  11880. static bool ggml_vk_instance_debug_utils_ext_available(
  11881. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11882. // Check for portability enumeration extension for MoltenVK support
  11883. for (const auto & properties : instance_extensions) {
  11884. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11885. return true;
  11886. }
  11887. }
  11888. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11889. return false;
  11890. UNUSED(instance_extensions);
  11891. }
  11892. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11893. VkPhysicalDeviceFeatures2 device_features2;
  11894. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11895. VkPhysicalDeviceVulkan11Features vk11_features;
  11896. vk11_features.pNext = nullptr;
  11897. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11898. device_features2.pNext = &vk11_features;
  11899. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11900. return vk11_features.storageBuffer16BitAccess;
  11901. }
  11902. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11903. switch (props.vendorID) {
  11904. case VK_VENDOR_ID_INTEL:
  11905. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11906. // while some older hardware (ex. Arc A770) has performance regressions
  11907. return arch == vk_device_architecture::INTEL_XE2;
  11908. case VK_VENDOR_ID_AMD:
  11909. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11910. // Workaround for AMD proprietary driver reporting support on all GPUs
  11911. return arch == vk_device_architecture::AMD_RDNA3;
  11912. }
  11913. return true;
  11914. default:
  11915. return true;
  11916. }
  11917. }
  11918. // checks
  11919. #ifdef GGML_VULKAN_CHECK_RESULTS
  11920. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  11921. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  11922. return;
  11923. }
  11924. for (int j = 0; j < level; j++) {
  11925. std::cerr << " ";
  11926. }
  11927. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  11928. done.push_back(tensor);
  11929. for (int i = 0; i < GGML_MAX_SRC; i++) {
  11930. if (tensor->src[i] != nullptr) {
  11931. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  11932. }
  11933. }
  11934. }
  11935. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  11936. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  11937. return;
  11938. }
  11939. i0 = std::max(i0, 5);
  11940. i1 = std::max(i1, 5);
  11941. i2 = std::max(i2, 0);
  11942. i3 = std::max(i3, 0);
  11943. fprintf(stderr, " ");
  11944. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11945. fprintf(stderr, "%7d ", idx1);
  11946. }
  11947. fprintf(stderr, "\n");
  11948. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  11949. fprintf(stderr, "%7d: ", idx0);
  11950. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11951. if (idx0 >= 0 && idx0 < tensor->ne[0] && idx1 >= 0 && idx1 < tensor->ne[1] && i2 >= 0 && i2 < tensor->ne[2] && i3 >= 0 && i3 < tensor->ne[3]) {
  11952. float val;
  11953. if (tensor->type == GGML_TYPE_F32) {
  11954. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11955. } else if (tensor->type == GGML_TYPE_F16) {
  11956. val = ggml_fp16_to_fp32(*(const ggml_fp16_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]));
  11957. } else if (tensor->type == GGML_TYPE_I32) {
  11958. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11959. } else {
  11960. GGML_ABORT("fatal error");
  11961. }
  11962. fprintf(stderr, "% 7.2f ", val);
  11963. } else {
  11964. fprintf(stderr, " ");
  11965. }
  11966. }
  11967. fprintf(stderr, "\n");
  11968. }
  11969. }
  11970. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  11971. void * tensor_data = tensor->data;
  11972. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  11973. if (is_gpu) {
  11974. const size_t tensor_size = ggml_nbytes(tensor);
  11975. tensor_data = malloc(tensor_size);
  11976. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11977. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  11978. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  11979. }
  11980. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  11981. std::cerr << "tensor=" << tensor << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << std::endl;
  11982. if (tensor->src[0] != nullptr) {
  11983. std::cerr << "tensor->src[0]=" << tensor->src[0] << " name=" << tensor->src[0]->name << " op=" << ggml_op_name(tensor->src[0]->op) << " type=" << ggml_type_name(tensor->src[0]->type) << " ne0=" << tensor->src[0]->ne[0] << " nb0=" << tensor->src[0]->nb[0] << " ne1=" << tensor->src[0]->ne[1] << " nb1=" << tensor->src[0]->nb[1] << " ne2=" << tensor->src[0]->ne[2] << " nb2=" << tensor->src[0]->nb[2] << " ne3=" << tensor->src[0]->ne[3] << " nb3=" << tensor->src[0]->nb[3] << std::endl;
  11984. }
  11985. if (tensor->src[1] != nullptr) {
  11986. std::cerr << "tensor->src[1]=" << tensor->src[1] << " name=" << tensor->src[1]->name << " op=" << ggml_op_name(tensor->src[1]->op) << " type=" << ggml_type_name(tensor->src[1]->type) << " ne0=" << tensor->src[1]->ne[0] << " nb0=" << tensor->src[1]->nb[0] << " ne1=" << tensor->src[1]->ne[1] << " nb1=" << tensor->src[1]->nb[1] << " ne2=" << tensor->src[1]->ne[2] << " nb2=" << tensor->src[1]->nb[2] << " ne3=" << tensor->src[1]->ne[3] << " nb3=" << tensor->src[1]->nb[3] << std::endl;
  11987. }
  11988. std::cerr << std::endl << "Result:" << std::endl;
  11989. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  11990. std::cerr << std::endl;
  11991. std::vector<const ggml_tensor *> done;
  11992. ggml_vk_print_graph_origin(tensor, done);
  11993. if (is_gpu) {
  11994. free(tensor_data);
  11995. }
  11996. }
  11997. void * comp_result;
  11998. size_t comp_size;
  11999. size_t comp_nb[GGML_MAX_DIMS];
  12000. size_t check_counter = 0;
  12001. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12002. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12003. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12004. return;
  12005. }
  12006. check_counter++;
  12007. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12008. return;
  12009. }
  12010. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12011. struct ggml_init_params iparams = {
  12012. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12013. /*.mem_buffer =*/ NULL,
  12014. /*.no_alloc =*/ false,
  12015. };
  12016. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12017. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12018. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12019. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12020. std::vector<void *> cloned_mallocs;
  12021. struct ggml_tensor * tensor_clone = nullptr;
  12022. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12023. tensor = cgraph->nodes[tensor_idx + f];
  12024. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12025. ggml_tensor * srci = tensor->src[i];
  12026. if (srci == nullptr) {
  12027. continue;
  12028. }
  12029. // If a src tensor has been cloned, use that one
  12030. auto it = cloned_tensors.find(srci);
  12031. if (it != cloned_tensors.end()) {
  12032. src_clone[i] = it->second;
  12033. continue;
  12034. }
  12035. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12036. size_t srci_size = ggml_nbytes(srci);
  12037. src_clone[i] = srci_clone;
  12038. void *src_buffer = malloc(srci_size);
  12039. cloned_mallocs.push_back(src_buffer);
  12040. srci_clone->data = src_buffer;
  12041. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12042. memcpy(srci_clone->data, srci->data, srci_size);
  12043. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12044. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12045. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12046. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12047. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12048. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12049. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12050. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12051. const int idx = i3*srci->ne[2] + i2;
  12052. ggml_vk_buffer_read(buffer_gpu, offset + idx * srci->nb[2], ((char *)srci_clone->data + idx * srci_clone->nb[2]), srci->ne[1] * srci->nb[1]);
  12053. }
  12054. }
  12055. srci_clone->nb[0] = srci->nb[0];
  12056. srci_clone->nb[1] = srci->nb[1];
  12057. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12058. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12059. }
  12060. } else {
  12061. if (offset + srci_size >= buffer_gpu->size) {
  12062. srci_size = buffer_gpu->size - offset;
  12063. }
  12064. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12065. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12066. }
  12067. } else {
  12068. GGML_ABORT("fatal error");
  12069. }
  12070. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12071. ggml_vk_print_tensor(srci, srci_name[i]);
  12072. }
  12073. }
  12074. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12075. const float * params = (const float *)tensor->op_params;
  12076. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], params[0], params[1], params[2]);
  12077. if (src_clone[4]) {
  12078. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12079. }
  12080. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12081. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12082. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12083. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12084. } else if (tensor->op == GGML_OP_SUB) {
  12085. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12086. } else if (tensor->op == GGML_OP_MUL) {
  12087. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12088. } else if (tensor->op == GGML_OP_DIV) {
  12089. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12090. } else if (tensor->op == GGML_OP_CONCAT) {
  12091. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12092. } else if (tensor->op == GGML_OP_UPSCALE) {
  12093. tensor_clone = ggml_interpolate(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  12094. } else if (tensor->op == GGML_OP_SCALE) {
  12095. const float * params = (const float *)tensor->op_params;
  12096. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12097. } else if (tensor->op == GGML_OP_SQR) {
  12098. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12099. } else if (tensor->op == GGML_OP_SQRT) {
  12100. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12101. } else if (tensor->op == GGML_OP_SIN) {
  12102. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12103. } else if (tensor->op == GGML_OP_COS) {
  12104. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12105. } else if (tensor->op == GGML_OP_CLAMP) {
  12106. const float * params = (const float *)tensor->op_params;
  12107. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12108. } else if (tensor->op == GGML_OP_PAD) {
  12109. tensor_clone = ggml_pad_ext(ggml_ctx, src_clone[0], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3],
  12110. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12111. } else if (tensor->op == GGML_OP_REPEAT) {
  12112. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12113. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12114. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12115. } else if (tensor->op == GGML_OP_ADD) {
  12116. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12117. } else if (tensor->op == GGML_OP_ACC) {
  12118. tensor_clone = ggml_acc(ggml_ctx, src_clone[0], src_clone[1], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  12119. } else if (tensor->op == GGML_OP_NORM) {
  12120. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12121. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12122. const float * float_params = (const float *)tensor->op_params;
  12123. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12124. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12125. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12126. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12127. const float eps = ((float *) tensor->op_params)[0];
  12128. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12129. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12130. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12131. } else if (tensor->op == GGML_OP_L2_NORM) {
  12132. const float eps = ((float *) tensor->op_params)[0];
  12133. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12134. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12135. if (tensor->src[1] != nullptr) {
  12136. const float * params = (const float *)tensor->op_params;
  12137. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12138. } else {
  12139. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12140. }
  12141. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12142. tensor_clone = ggml_soft_max_ext_back(ggml_ctx, src_clone[0], src_clone[1], ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  12143. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12144. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12145. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12146. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12147. const int mode = ((int32_t *) tensor->op_params)[2];
  12148. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12149. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12150. const float freq_base = ((float *) tensor->op_params)[5];
  12151. const float freq_scale = ((float *) tensor->op_params)[6];
  12152. const float ext_factor = ((float *) tensor->op_params)[7];
  12153. const float attn_factor = ((float *) tensor->op_params)[8];
  12154. const float beta_fast = ((float *) tensor->op_params)[9];
  12155. const float beta_slow = ((float *) tensor->op_params)[10];
  12156. if (mode & GGML_ROPE_TYPE_MROPE) {
  12157. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12158. if (tensor->op == GGML_OP_ROPE) {
  12159. tensor_clone = ggml_rope_multi(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12160. } else {
  12161. tensor_clone = ggml_rope_multi_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12162. }
  12163. } else {
  12164. if (tensor->op == GGML_OP_ROPE) {
  12165. tensor_clone = ggml_rope_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12166. } else {
  12167. tensor_clone = ggml_rope_ext_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12168. }
  12169. }
  12170. } else if (tensor->op == GGML_OP_UNARY) {
  12171. switch (ggml_get_unary_op(tensor)) {
  12172. case GGML_UNARY_OP_EXP:
  12173. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12174. break;
  12175. case GGML_UNARY_OP_SILU:
  12176. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12177. break;
  12178. case GGML_UNARY_OP_GELU:
  12179. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12180. break;
  12181. case GGML_UNARY_OP_GELU_ERF:
  12182. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12183. break;
  12184. case GGML_UNARY_OP_GELU_QUICK:
  12185. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12186. break;
  12187. case GGML_UNARY_OP_RELU:
  12188. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12189. break;
  12190. case GGML_UNARY_OP_TANH:
  12191. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12192. break;
  12193. case GGML_UNARY_OP_SIGMOID:
  12194. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12195. break;
  12196. case GGML_UNARY_OP_HARDSIGMOID:
  12197. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12198. break;
  12199. case GGML_UNARY_OP_HARDSWISH:
  12200. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12201. break;
  12202. default:
  12203. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12204. GGML_ABORT("fatal error");
  12205. }
  12206. } else if (tensor->op == GGML_OP_GLU) {
  12207. if (src_clone[1] == nullptr) {
  12208. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12209. } else {
  12210. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12211. }
  12212. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12213. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12214. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12215. if (tensor->src[1] == nullptr) {
  12216. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12217. tensor_clone->type = tensor->type;
  12218. } else {
  12219. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12220. }
  12221. } else if (tensor->op == GGML_OP_CONT) {
  12222. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12223. } else if (tensor->op == GGML_OP_RESHAPE) {
  12224. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12225. } else if (tensor->op == GGML_OP_VIEW) {
  12226. tensor_clone = ggml_view_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], tensor->nb[1], tensor->nb[2], tensor->nb[3], ((int32_t *) tensor->op_params)[0]);
  12227. } else if (tensor->op == GGML_OP_PERMUTE) {
  12228. int32_t * params = (int32_t *)tensor->op_params;
  12229. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12230. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12231. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12232. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12233. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12234. } else if (tensor->op == GGML_OP_ARGSORT) {
  12235. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12236. } else if (tensor->op == GGML_OP_SUM) {
  12237. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12238. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12239. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12240. } else if (tensor->op == GGML_OP_MEAN) {
  12241. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12242. } else if (tensor->op == GGML_OP_ARGMAX) {
  12243. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12244. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12245. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12246. } else if (tensor->op == GGML_OP_IM2COL) {
  12247. const int32_t s0 = tensor->op_params[0];
  12248. const int32_t s1 = tensor->op_params[1];
  12249. const int32_t p0 = tensor->op_params[2];
  12250. const int32_t p1 = tensor->op_params[3];
  12251. const int32_t d0 = tensor->op_params[4];
  12252. const int32_t d1 = tensor->op_params[5];
  12253. const bool is_2D = tensor->op_params[6] == 1;
  12254. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12255. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12256. const int32_t s0 = tensor->op_params[0];
  12257. const int32_t s1 = tensor->op_params[1];
  12258. const int32_t s2 = tensor->op_params[2];
  12259. const int32_t p0 = tensor->op_params[3];
  12260. const int32_t p1 = tensor->op_params[4];
  12261. const int32_t p2 = tensor->op_params[5];
  12262. const int32_t d0 = tensor->op_params[6];
  12263. const int32_t d1 = tensor->op_params[7];
  12264. const int32_t d2 = tensor->op_params[8];
  12265. const int32_t IC = tensor->op_params[9];
  12266. tensor_clone = ggml_im2col_3d(ggml_ctx, src_clone[0], src_clone[1], IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, tensor->type);
  12267. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12268. const int32_t dim = tensor->op_params[0];
  12269. const int32_t max_period = tensor->op_params[1];
  12270. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12271. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12272. const int32_t s0 = tensor->op_params[0];
  12273. const int32_t p0 = tensor->op_params[1];
  12274. const int32_t d0 = tensor->op_params[2];
  12275. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12276. } else if (tensor->op == GGML_OP_POOL_2D) {
  12277. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12278. const int32_t k0 = tensor->op_params[1];
  12279. const int32_t k1 = tensor->op_params[2];
  12280. const int32_t s0 = tensor->op_params[3];
  12281. const int32_t s1 = tensor->op_params[4];
  12282. const int32_t p0 = tensor->op_params[5];
  12283. const int32_t p1 = tensor->op_params[6];
  12284. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12285. } else if (tensor->op == GGML_OP_CONV_2D) {
  12286. const int32_t s0 = tensor->op_params[0];
  12287. const int32_t s1 = tensor->op_params[1];
  12288. const int32_t p0 = tensor->op_params[2];
  12289. const int32_t p1 = tensor->op_params[3];
  12290. const int32_t d0 = tensor->op_params[4];
  12291. const int32_t d1 = tensor->op_params[5];
  12292. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12293. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12294. const int32_t s0 = tensor->op_params[0];
  12295. const int32_t s1 = tensor->op_params[1];
  12296. const int32_t p0 = tensor->op_params[2];
  12297. const int32_t p1 = tensor->op_params[3];
  12298. const int32_t d0 = tensor->op_params[4];
  12299. const int32_t d1 = tensor->op_params[5];
  12300. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12301. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12302. const int32_t s = tensor->op_params[0];
  12303. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12304. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12305. const float * op_params = (const float *)tensor->op_params;
  12306. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12307. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12308. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12309. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12310. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12311. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12312. src_clone[4], src_clone[5], src_clone[6]);
  12313. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12314. src_clone[0]->flags = tensor->src[0]->flags;
  12315. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12316. src_clone[2], src_clone[3], src_clone[4]);
  12317. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12318. src_clone[0]->flags = tensor->src[0]->flags;
  12319. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12320. src_clone[2]);
  12321. } else if (tensor->op == GGML_OP_ADD_ID) {
  12322. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12323. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12324. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12325. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12326. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12327. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12328. } else if (tensor->op == GGML_OP_ROLL) {
  12329. const int32_t s0 = tensor->op_params[0];
  12330. const int32_t s1 = tensor->op_params[1];
  12331. const int32_t s2 = tensor->op_params[2];
  12332. const int32_t s3 = tensor->op_params[3];
  12333. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12334. }
  12335. else {
  12336. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12337. GGML_ABORT("fatal error");
  12338. }
  12339. cloned_tensors[tensor] = tensor_clone;
  12340. }
  12341. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12342. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12343. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12344. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12345. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12346. }
  12347. comp_size = ggml_nbytes(tensor_clone);
  12348. comp_result = malloc(comp_size);
  12349. memcpy(comp_result, tensor_clone->data, comp_size);
  12350. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12351. for (auto m : cloned_mallocs) {
  12352. free(m);
  12353. }
  12354. ggml_free(ggml_ctx);
  12355. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12356. }
  12357. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12358. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12359. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12360. return;
  12361. }
  12362. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12363. return;
  12364. }
  12365. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12366. ggml_tensor * src0 = tensor->src[0];
  12367. ggml_tensor * src1 = tensor->src[1];
  12368. ggml_tensor * src2 = tensor->src[2];
  12369. ggml_tensor * src3 = tensor->src[3];
  12370. void * tensor_data = tensor->data;
  12371. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12372. size_t tensor_size = ggml_nbytes(tensor);
  12373. tensor_data = malloc(tensor_size);
  12374. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12375. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12376. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12377. if (offset + tensor_size >= buffer_gpu->size) {
  12378. tensor_size = buffer_gpu->size - offset;
  12379. }
  12380. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12381. }
  12382. float first_error_result = -1.0f;
  12383. float first_error_correct = -1.0f;
  12384. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12385. double avg_err = 0.0;
  12386. size_t counter = 0;
  12387. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12388. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12389. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12390. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12391. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12392. float correct = 0.0f;
  12393. float result = 0.0f;
  12394. if (buffer_size_fit) {
  12395. if (tensor->type == GGML_TYPE_F32) {
  12396. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12397. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12398. } else if (tensor->type == GGML_TYPE_F16) {
  12399. correct = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  12400. result = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  12401. } else if (tensor->type == GGML_TYPE_BF16) {
  12402. correct = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  12403. result = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  12404. } else if (tensor->type == GGML_TYPE_I32) {
  12405. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12406. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12407. } else if (tensor->type == GGML_TYPE_I64) {
  12408. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12409. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12410. } else {
  12411. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12412. }
  12413. } else {
  12414. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12415. GGML_ABORT("fatal error");
  12416. }
  12417. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12418. std::cerr << "ERROR: Invalid value in " << ggml_op_name(tensor->op) << " i3=" << i3 << " i2=" << i2 << " i1=" << i1 << " i0=" << i0 << " result=" << result << " correct=" << correct << " avg_err=" << (avg_err / counter) << std::endl;
  12419. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  12420. if (src0 != nullptr) {
  12421. std::cerr << "src0=" << src0 << " src0->name=" << src0->name << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  12422. }
  12423. if (src1 != nullptr) {
  12424. std::cerr << "src1=" << src1 << " src1->name=" << src1->name << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  12425. }
  12426. if (src2 != nullptr) {
  12427. std::cerr << "src2=" << src2 << " src2->name=" << src2->name << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  12428. }
  12429. if (src3 != nullptr) {
  12430. std::cerr << "src3=" << src3 << " src3->name=" << src3->name << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  12431. }
  12432. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  12433. std::cerr << std::endl << "Result:" << std::endl;
  12434. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12435. std::cerr << std::endl << "Correct:" << std::endl;
  12436. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12437. std::cerr << std::endl;
  12438. std::vector<const ggml_tensor *> done;
  12439. ggml_vk_print_graph_origin(tensor, done);
  12440. GGML_ABORT("fatal error");
  12441. }
  12442. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12443. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12444. first_error[0] = i0;
  12445. first_error[1] = i1;
  12446. first_error[2] = i2;
  12447. first_error[3] = i3;
  12448. first_error_result = result;
  12449. first_error_correct = correct;
  12450. }
  12451. // Special case, value is infinite, avoid NaN result in avg_err
  12452. // NaN also appears in results, if both are nan error is 0
  12453. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12454. avg_err += std::fabs(correct - result) / denom;
  12455. }
  12456. counter++;
  12457. }
  12458. }
  12459. }
  12460. }
  12461. avg_err /= counter;
  12462. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12463. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12464. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  12465. if (src0 != nullptr) {
  12466. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  12467. }
  12468. if (src1 != nullptr) {
  12469. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  12470. }
  12471. if (src2 != nullptr) {
  12472. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  12473. }
  12474. if (src3 != nullptr) {
  12475. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  12476. }
  12477. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  12478. std::cerr << std::endl << "Result:" << std::endl;
  12479. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12480. std::cerr << std::endl << "Correct:" << std::endl;
  12481. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12482. std::cerr << std::endl;
  12483. std::vector<const ggml_tensor *> done;
  12484. ggml_vk_print_graph_origin(tensor, done);
  12485. }
  12486. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12487. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12488. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  12489. if (src0 != nullptr) {
  12490. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  12491. }
  12492. if (src1 != nullptr) {
  12493. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  12494. }
  12495. if (src2 != nullptr) {
  12496. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  12497. }
  12498. if (src3 != nullptr) {
  12499. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  12500. }
  12501. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  12502. std::cerr << std::endl << "Result:" << std::endl;
  12503. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12504. std::cerr << std::endl << "Correct:" << std::endl;
  12505. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12506. std::cerr << std::endl;
  12507. std::vector<const ggml_tensor *> done;
  12508. ggml_vk_print_graph_origin(tensor, done);
  12509. GGML_ABORT("fatal error");
  12510. } else {
  12511. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12512. }
  12513. free(comp_result);
  12514. comp_result = nullptr;
  12515. comp_size = 0;
  12516. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12517. free(tensor_data);
  12518. }
  12519. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12520. }
  12521. #endif
  12522. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)