ggml-vulkan.cpp 401 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_PERF) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. #include <vulkan/vulkan.hpp>
  8. #include <algorithm>
  9. #include <cmath>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <tuple>
  13. #include <vector>
  14. #include <sstream>
  15. #include <utility>
  16. #include <memory>
  17. #include <limits>
  18. #include <map>
  19. #include <unordered_map>
  20. #include <memory>
  21. #include <mutex>
  22. #include <future>
  23. #include <thread>
  24. #include "ggml-impl.h"
  25. #include "ggml-backend-impl.h"
  26. #include "ggml-vulkan-shaders.hpp"
  27. #define VK_API_VERSION VK_API_VERSION_1_2
  28. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  29. #define VK_VENDOR_ID_AMD 0x1002
  30. #define VK_VENDOR_ID_APPLE 0x106b
  31. #define VK_VENDOR_ID_INTEL 0x8086
  32. #define VK_VENDOR_ID_NVIDIA 0x10de
  33. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 32
  34. #define GGML_VK_MAX_NODES 8192
  35. #define MAX_VK_BUFFERS 256
  36. #ifndef K_QUANTS_PER_ITERATION
  37. #define K_QUANTS_PER_ITERATION 1
  38. #else
  39. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  40. #endif
  41. #define VK_CHECK(err, msg) \
  42. do { \
  43. vk::Result err_ = (err); \
  44. if (err_ != vk::Result::eSuccess) { \
  45. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  46. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  47. exit(1); \
  48. } \
  49. } while (0)
  50. #ifdef GGML_VULKAN_DEBUG
  51. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  52. #else
  53. #define VK_LOG_DEBUG(msg) ((void) 0)
  54. #endif // GGML_VULKAN_DEBUG
  55. struct ggml_backend_vk_context;
  56. struct vk_queue {
  57. uint32_t queue_family_index;
  58. vk::Queue queue;
  59. vk::CommandPool pool;
  60. uint32_t cmd_buffer_idx;
  61. std::vector<vk::CommandBuffer> cmd_buffers;
  62. vk::PipelineStageFlags stage_flags;
  63. bool transfer_only;
  64. };
  65. struct vk_pipeline_struct {
  66. std::string name;
  67. vk::ShaderModule shader_module;
  68. vk::DescriptorSetLayout dsl;
  69. std::vector<vk::DescriptorPool> descriptor_pools;
  70. std::vector<vk::DescriptorSet> descriptor_sets;
  71. uint32_t descriptor_set_idx;
  72. vk::PipelineLayout layout;
  73. vk::Pipeline pipeline;
  74. uint32_t push_constant_size;
  75. uint32_t parameter_count;
  76. std::array<uint32_t, 3> wg_denoms;
  77. uint32_t align;
  78. };
  79. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  80. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  81. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  82. struct vk_matmul_pipeline_struct {
  83. vk_pipeline l, m, s;
  84. vk_pipeline a_l, a_m, a_s;
  85. };
  86. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  87. struct vk_matmul_pipeline2 {
  88. vk_matmul_pipeline2() {
  89. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  90. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  91. }
  92. vk_matmul_pipeline f32acc;
  93. vk_matmul_pipeline f16acc;
  94. };
  95. struct vk_device_struct;
  96. typedef std::shared_ptr<vk_device_struct> vk_device;
  97. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  98. struct vk_buffer_struct;
  99. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  100. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  101. struct ggml_backend_vk_buffer_type_context {
  102. std::string name;
  103. vk_device device;
  104. };
  105. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  106. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  107. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  108. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  109. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  110. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  111. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  112. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  113. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  114. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  115. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  116. /* .is_host = */ NULL,
  117. };
  118. #ifdef GGML_VULKAN_MEMORY_DEBUG
  119. class vk_memory_logger;
  120. #endif
  121. #ifdef GGML_VULKAN_PERF
  122. class vk_perf_logger;
  123. #endif
  124. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  125. struct vk_device_struct {
  126. std::mutex mutex;
  127. vk::PhysicalDevice physical_device;
  128. vk::PhysicalDeviceProperties properties;
  129. std::string name;
  130. uint64_t max_memory_allocation_size;
  131. bool fp16;
  132. bool pipeline_robustness;
  133. vk::Device device;
  134. uint32_t vendor_id;
  135. vk_queue compute_queue;
  136. vk_queue transfer_queue;
  137. bool single_queue;
  138. uint32_t subgroup_size;
  139. uint32_t shader_core_count;
  140. bool uma;
  141. bool coopmat2;
  142. bool coopmat_support;
  143. bool coopmat_acc_f32_support;
  144. bool coopmat_acc_f16_support;
  145. uint32_t coopmat_m;
  146. uint32_t coopmat_n;
  147. uint32_t coopmat_k;
  148. size_t idx;
  149. bool mul_mat_l;
  150. bool mul_mat_m;
  151. bool mul_mat_s;
  152. bool mul_mat_id_l;
  153. bool mul_mat_id_m;
  154. bool mul_mat_id_s;
  155. vk_matmul_pipeline pipeline_matmul_f32;
  156. vk_matmul_pipeline pipeline_matmul_f32_f16;
  157. vk_matmul_pipeline2 pipeline_matmul_f16;
  158. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  159. vk_pipeline pipeline_matmul_split_k_reduce;
  160. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  161. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  162. vk_matmul_pipeline pipeline_matmul_id_f32;
  163. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  164. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  165. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  166. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  167. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_COUNT];
  168. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_COUNT];
  169. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  170. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  171. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  172. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  173. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  174. vk_pipeline pipeline_acc_f32;
  175. vk_pipeline pipeline_add_f32, pipeline_add_f32_norepeat;
  176. vk_pipeline pipeline_add_f16_f32_f16, pipeline_add_f16_f32_f16_norepeat;
  177. vk_pipeline pipeline_mul_f32, pipeline_mul_f32_norepeat;
  178. vk_pipeline pipeline_div_f32, pipeline_div_f32_norepeat;
  179. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  180. vk_pipeline pipeline_upscale_f32;
  181. vk_pipeline pipeline_scale_f32;
  182. vk_pipeline pipeline_sqr_f32;
  183. vk_pipeline pipeline_sin_f32;
  184. vk_pipeline pipeline_cos_f32;
  185. vk_pipeline pipeline_clamp_f32;
  186. vk_pipeline pipeline_pad_f32;
  187. vk_pipeline pipeline_repeat_f32;
  188. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  189. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16;
  190. vk_pipeline pipeline_norm_f32;
  191. vk_pipeline pipeline_group_norm_f32;
  192. vk_pipeline pipeline_rms_norm_f32;
  193. vk_pipeline pipeline_gelu_f32;
  194. vk_pipeline pipeline_gelu_quick_f32;
  195. vk_pipeline pipeline_silu_f32;
  196. vk_pipeline pipeline_relu_f32;
  197. vk_pipeline pipeline_leaky_relu_f32;
  198. vk_pipeline pipeline_tanh_f32;
  199. vk_pipeline pipeline_diag_mask_inf_f32;
  200. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  201. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  202. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  203. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  204. vk_pipeline pipeline_argsort_f32;
  205. vk_pipeline pipeline_sum_rows_f32;
  206. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  207. vk_pipeline pipeline_timestep_embedding_f32;
  208. vk_pipeline pipeline_pool2d_f32;
  209. // [2][2][2] is for {f16acc,f32acc}x{large,small_rows}x{unaligned, aligned}
  210. vk_pipeline pipeline_flash_attn_f32_f16_D64[GGML_TYPE_COUNT][2][2][2];
  211. vk_pipeline pipeline_flash_attn_f32_f16_D80[GGML_TYPE_COUNT][2][2][2];
  212. vk_pipeline pipeline_flash_attn_f32_f16_D96[GGML_TYPE_COUNT][2][2][2];
  213. vk_pipeline pipeline_flash_attn_f32_f16_D112[GGML_TYPE_COUNT][2][2][2];
  214. vk_pipeline pipeline_flash_attn_f32_f16_D128[GGML_TYPE_COUNT][2][2][2];
  215. vk_pipeline pipeline_flash_attn_f32_f16_D256[GGML_TYPE_COUNT][2][2][2];
  216. std::unordered_map<std::string, vk_pipeline_ref> pipelines;
  217. std::unordered_map<std::string, uint64_t> pipeline_descriptor_set_requirements;
  218. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  219. vk::Fence fence;
  220. vk_buffer sync_staging;
  221. ggml_backend_buffer_type buffer_type;
  222. #ifdef GGML_VULKAN_MEMORY_DEBUG
  223. std::unique_ptr<vk_memory_logger> memory_logger;
  224. #endif
  225. #ifdef GGML_VULKAN_PERF
  226. std::unique_ptr<vk_perf_logger> perf_logger;
  227. #endif
  228. ~vk_device_struct() {
  229. VK_LOG_DEBUG("destroy device " << name);
  230. device.destroyFence(fence);
  231. ggml_vk_destroy_buffer(sync_staging);
  232. device.destroyCommandPool(compute_queue.pool);
  233. if (!single_queue) {
  234. device.destroyCommandPool(transfer_queue.pool);
  235. }
  236. for (auto& pipeline : pipelines) {
  237. if (pipeline.second.expired()) {
  238. continue;
  239. }
  240. vk_pipeline pl = pipeline.second.lock();
  241. ggml_vk_destroy_pipeline(device, pl);
  242. }
  243. pipelines.clear();
  244. device.destroy();
  245. }
  246. };
  247. struct vk_buffer_struct {
  248. vk::Buffer buffer = VK_NULL_HANDLE;
  249. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  250. vk::MemoryPropertyFlags memory_property_flags;
  251. void * ptr;
  252. size_t size = 0;
  253. vk_device device;
  254. ~vk_buffer_struct() {
  255. if (size == 0) {
  256. return;
  257. }
  258. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  259. device->device.freeMemory(device_memory);
  260. device->device.destroyBuffer(buffer);
  261. }
  262. };
  263. struct vk_subbuffer {
  264. vk_buffer buffer;
  265. uint64_t offset;
  266. uint64_t size;
  267. operator vk::DescriptorBufferInfo() const {
  268. return { buffer->buffer, offset, size };
  269. }
  270. };
  271. struct vk_semaphore {
  272. vk::Semaphore s;
  273. uint64_t value;
  274. };
  275. struct vk_submission {
  276. vk::CommandBuffer buffer;
  277. std::vector<vk_semaphore> wait_semaphores;
  278. std::vector<vk_semaphore> signal_semaphores;
  279. };
  280. typedef std::vector<vk_submission> vk_sequence;
  281. struct vk_mat_mat_push_constants {
  282. uint32_t M; uint32_t N; uint32_t K;
  283. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  284. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  285. uint32_t k_split;
  286. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  287. };
  288. struct vk_mat_vec_push_constants {
  289. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  290. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  291. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  292. };
  293. struct vk_mat_mat_id_push_constants {
  294. uint32_t M; uint32_t N; uint32_t K;
  295. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  296. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  297. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  298. };
  299. struct vk_mat_vec_id_push_constants {
  300. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  301. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  302. uint32_t nei0; uint32_t ne11;
  303. };
  304. struct vk_flash_attn_push_constants {
  305. uint32_t N;
  306. uint32_t KV;
  307. uint32_t ne1;
  308. uint32_t ne2;
  309. uint32_t ne3;
  310. uint32_t neq2;
  311. uint32_t neq3;
  312. uint32_t nek2;
  313. uint32_t nek3;
  314. uint32_t nev2;
  315. uint32_t nev3;
  316. uint32_t nem1;
  317. uint32_t nb02;
  318. uint32_t nb03;
  319. uint32_t nb12;
  320. uint32_t nb13;
  321. uint32_t nb22;
  322. uint32_t nb23;
  323. uint32_t nb31;
  324. float scale;
  325. float max_bias;
  326. float logit_softcap;
  327. uint32_t mask;
  328. uint32_t n_head_log2;
  329. float m0;
  330. float m1;
  331. };
  332. struct vk_op_push_constants {
  333. uint32_t KX;
  334. uint32_t KY;
  335. float param1;
  336. float param2;
  337. };
  338. struct vk_op_unary_push_constants {
  339. uint32_t ne;
  340. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  341. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  342. uint32_t d_offset;
  343. float param1; float param2;
  344. uint32_t ne0_012mp; uint32_t ne0_012L;
  345. uint32_t ne0_01mp; uint32_t ne0_01L;
  346. uint32_t ne0_0mp; uint32_t ne0_0L;
  347. uint32_t ne1_012mp; uint32_t ne1_012L;
  348. uint32_t ne1_01mp; uint32_t ne1_01L;
  349. uint32_t ne1_0mp; uint32_t ne1_0L;
  350. };
  351. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  352. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  353. // Precompute mp (m' in the paper) and L such that division
  354. // can be computed using a multiply (high 32b of 64b result)
  355. // and a shift:
  356. //
  357. // n/d = (mulhi(n, mp) + n) >> L;
  358. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  359. {
  360. // compute L = ceil(log2(d));
  361. L = 0;
  362. while (L < 32 && (uint32_t{1} << L) < d) {
  363. L++;
  364. }
  365. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  366. }
  367. template <typename T> void init_pushconst_fastdiv(T &p) {
  368. GGML_UNUSED(p);
  369. static_assert(!std::is_const<T>::value, "unexpected type");
  370. }
  371. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  372. // Compute magic values to divide by these six numbers.
  373. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  374. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  375. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  376. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  377. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  378. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  379. }
  380. struct vk_op_binary_push_constants {
  381. uint32_t ne;
  382. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  383. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  384. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  385. uint32_t d_offset;
  386. float param1; float param2; int32_t param3;
  387. };
  388. struct vk_op_diag_mask_push_constants {
  389. uint32_t ncols;
  390. uint32_t rows_per_channel;
  391. int32_t n_past;
  392. };
  393. struct vk_op_rope_push_constants {
  394. uint32_t ncols;
  395. uint32_t n_dims;
  396. float freq_scale;
  397. uint32_t p_delta_rows;
  398. float freq_base;
  399. float ext_factor;
  400. float attn_factor;
  401. float corr_dims[2];
  402. float theta_scale;
  403. uint32_t has_ff;
  404. };
  405. struct vk_op_soft_max_push_constants {
  406. uint32_t KX;
  407. uint32_t KY;
  408. float scale;
  409. float max_bias;
  410. float m0;
  411. float m1;
  412. uint32_t n_head_log2;
  413. uint32_t nrows_x;
  414. };
  415. struct vk_op_argsort_push_constants {
  416. uint32_t ncols;
  417. uint32_t ncols_pad;
  418. int32_t order;
  419. };
  420. struct vk_op_im2col_push_constants {
  421. uint32_t batch_offset; uint32_t offset_delta;
  422. uint32_t IC;
  423. uint32_t IW; uint32_t IH;
  424. uint32_t OW; uint32_t OH;
  425. uint32_t KW; uint32_t KH;
  426. uint32_t pelements;
  427. uint32_t CHW;
  428. int32_t s0; int32_t s1;
  429. int32_t p0; int32_t p1;
  430. int32_t d0; int32_t d1;
  431. };
  432. struct vk_op_timestep_embedding_push_constants {
  433. uint32_t nb1;
  434. uint32_t dim;
  435. uint32_t max_period;
  436. };
  437. struct vk_op_pool2d_push_constants {
  438. uint32_t IW; uint32_t IH;
  439. uint32_t OW; uint32_t OH;
  440. uint32_t OC;
  441. uint32_t pelements;
  442. uint32_t op;
  443. int32_t k0; int32_t k1;
  444. int32_t s0; int32_t s1;
  445. int32_t p0; int32_t p1;
  446. };
  447. // Allow pre-recording command buffers
  448. struct vk_staging_memcpy {
  449. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  450. void * dst;
  451. const void * src;
  452. size_t n;
  453. };
  454. struct vk_op_upscale_push_constants {
  455. uint32_t ne; uint32_t d_offset;
  456. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  457. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  458. float sf0; float sf1; float sf2; float sf3;
  459. };
  460. struct vk_context_struct {
  461. vk_submission * s;
  462. std::vector<vk_sequence> seqs;
  463. int exit_tensor_idx;
  464. std::vector<vk_staging_memcpy> in_memcpys;
  465. std::vector<vk_staging_memcpy> out_memcpys;
  466. vk_queue * q;
  467. };
  468. typedef std::shared_ptr<vk_context_struct> vk_context;
  469. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  470. struct ggml_vk_garbage_collector {
  471. std::vector<vk_semaphore> tl_semaphores;
  472. std::vector<vk_semaphore> semaphores;
  473. std::vector<vk::Event> events;
  474. std::vector<vk_buffer> temp_buffers;
  475. std::vector<vk_context> contexts;
  476. };
  477. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  478. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  479. static std::string format_size(size_t size) {
  480. const size_t kib = 1024;
  481. const size_t mib = kib * 1024;
  482. const size_t gib = mib * 1024;
  483. std::ostringstream oss;
  484. oss << std::fixed << std::setprecision(2);
  485. if (size >= gib) {
  486. oss << static_cast<double>(size) / gib << " GiB";
  487. } else if (size >= mib) {
  488. oss << static_cast<double>(size) / mib << " MiB";
  489. } else if (size >= kib) {
  490. oss << static_cast<double>(size) / kib << " KiB";
  491. } else {
  492. oss << size << " B";
  493. }
  494. return oss.str();
  495. }
  496. static std::mutex log_mutex;
  497. class vk_memory_logger {
  498. public:
  499. vk_memory_logger(): total_device(0), total_host(0) {}
  500. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  501. void log_deallocation(vk_buffer_ref buf_ref);
  502. private:
  503. std::map<vk::Buffer, size_t> allocations; // Track allocations
  504. size_t total_device;
  505. size_t total_host;
  506. };
  507. #else
  508. #define VK_LOG_MEMORY(msg) ((void) 0)
  509. #endif // GGML_VULKAN_MEMORY_DEBUG
  510. #if defined(GGML_VULKAN_PERF)
  511. class vk_perf_logger {
  512. public:
  513. void print_timings() {
  514. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  515. for (const auto& t : timings) {
  516. uint64_t total = 0;
  517. for (const auto& time : t.second) {
  518. total += time;
  519. }
  520. std::cerr << t.first << ": " << t.second.size() << " x " << (total / t.second.size() / 1000.0) << " ms" << std::endl;
  521. }
  522. timings.clear();
  523. }
  524. void log_timing(const ggml_tensor * node, uint64_t time) {
  525. if (node->op == GGML_OP_UNARY) {
  526. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  527. return;
  528. }
  529. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  530. const uint64_t m = node->src[0]->ne[1];
  531. const uint64_t n = node->src[1]->ne[1];
  532. const uint64_t k = node->src[1]->ne[0];
  533. std::string name = ggml_op_name(node->op);
  534. if (n == 1) {
  535. name += "_VEC m=" + std::to_string(m) + " k=" + std::to_string(k);
  536. } else {
  537. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  538. }
  539. timings[name].push_back(time);
  540. return;
  541. }
  542. timings[ggml_op_name(node->op)].push_back(time);
  543. }
  544. private:
  545. std::map<std::string, std::vector<uint64_t>> timings;
  546. };
  547. #endif // GGML_VULKAN_PERF
  548. struct ggml_backend_vk_context {
  549. std::string name;
  550. vk_device device;
  551. size_t semaphore_idx, event_idx;
  552. ggml_vk_garbage_collector gc;
  553. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  554. vk_buffer prealloc_x, prealloc_y, prealloc_split_k;
  555. vk::Fence fence;
  556. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  557. vk_context_ref compute_ctx;
  558. vk_context_ref transfer_ctx;
  559. std::vector<vk_context_ref> tensor_ctxs;
  560. };
  561. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  562. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  563. if (tensor->view_src) {
  564. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  565. }
  566. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  567. }
  568. struct ggml_backend_vk_buffer_context {
  569. vk_device_ref device;
  570. vk_buffer dev_buffer;
  571. std::string name;
  572. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  573. device(device),
  574. dev_buffer(dev_buffer),
  575. name(name) {
  576. }
  577. ~ggml_backend_vk_buffer_context() {
  578. ggml_vk_destroy_buffer(dev_buffer);
  579. }
  580. };
  581. #ifdef GGML_VULKAN_MEMORY_DEBUG
  582. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  583. std::lock_guard<std::mutex> guard(log_mutex);
  584. vk_buffer buf = buf_ref.lock();
  585. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  586. const std::string type = device ? "device" : "host";
  587. allocations[buf->buffer] = size;
  588. total_device += device ? size : 0;
  589. total_host += device ? 0 : size;
  590. 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));
  591. }
  592. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  593. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  594. return;
  595. }
  596. std::lock_guard<std::mutex> guard(log_mutex);
  597. vk_buffer buf = buf_ref.lock();
  598. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  599. std::string type = device ? "device" : "host";
  600. auto it = allocations.find(buf->buffer);
  601. total_device -= device ? it->second : 0;
  602. total_host -= device ? 0 : it->second;
  603. if (it != allocations.end()) {
  604. 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));
  605. allocations.erase(it);
  606. } else {
  607. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  608. }
  609. }
  610. #endif // GGML_VULKAN_MEMORY_DEBUG
  611. struct vk_instance_t {
  612. vk::Instance instance;
  613. std::vector<size_t> device_indices;
  614. vk_device devices[GGML_VK_MAX_DEVICES];
  615. };
  616. static bool vk_instance_initialized = false;
  617. static vk_instance_t vk_instance;
  618. #ifdef GGML_VULKAN_CHECK_RESULTS
  619. static size_t vk_skip_checks;
  620. static size_t vk_output_tensor;
  621. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  622. static void ggml_vk_check_results_0(ggml_tensor * tensor);
  623. static void ggml_vk_check_results_1(ggml_tensor * tensor);
  624. #endif
  625. 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);
  626. static void ggml_backend_vk_free(ggml_backend_t backend);
  627. // variables to track number of compiles in progress
  628. static uint32_t compile_count = 0;
  629. static std::mutex compile_count_mutex;
  630. static std::condition_variable compile_count_cond;
  631. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, const std::string name, size_t spv_size, const void* spv_data, const std::string entrypoint, uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants, uint32_t align, bool disable_robustness) {
  632. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << name << ", " << entrypoint << ", " << parameter_count << ", " << push_constant_size << ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << align << ")");
  633. GGML_ASSERT(parameter_count > 0);
  634. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  635. pipeline = std::make_shared<vk_pipeline_struct>();
  636. pipeline->name = name;
  637. pipeline->parameter_count = parameter_count;
  638. pipeline->push_constant_size = push_constant_size;
  639. pipeline->wg_denoms = wg_denoms;
  640. pipeline->align = align;
  641. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  642. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  643. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  644. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  645. for (uint32_t i = 0; i < parameter_count; i++) {
  646. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  647. dsl_binding_flags.push_back({});
  648. }
  649. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  650. vk::PushConstantRange pcr(
  651. vk::ShaderStageFlagBits::eCompute,
  652. 0,
  653. pipeline->push_constant_size
  654. );
  655. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  656. {},
  657. dsl_binding);
  658. descriptor_set_layout_create_info.setPNext(&dslbfci);
  659. pipeline->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  660. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  661. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  662. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  663. pipeline->descriptor_set_idx = 0;
  664. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline->dsl, pcr);
  665. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  666. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  667. for (size_t i = 0; i < specialization_constants.size(); i++) {
  668. specialization_entries[i].constantID = i;
  669. specialization_entries[i].offset = i * sizeof(uint32_t);
  670. specialization_entries[i].size = sizeof(uint32_t);
  671. }
  672. vk::SpecializationInfo specialization_info(
  673. specialization_entries.size(),
  674. specialization_entries.data(),
  675. specialization_constants.size() * sizeof(uint32_t),
  676. specialization_constants.data()
  677. );
  678. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  679. vk::PipelineShaderStageCreateFlags(),
  680. vk::ShaderStageFlagBits::eCompute,
  681. pipeline->shader_module,
  682. entrypoint.c_str(),
  683. &specialization_info);
  684. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  685. vk::PipelineCreateFlags(),
  686. pipeline_shader_create_info,
  687. pipeline->layout);
  688. vk::PipelineRobustnessCreateInfoEXT rci;
  689. if (device->pipeline_robustness && disable_robustness) {
  690. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  691. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  692. compute_pipeline_create_info.setPNext(&rci);
  693. }
  694. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  695. {
  696. std::lock_guard<std::mutex> guard(device->mutex);
  697. device->pipelines.insert({ pipeline->name, pipeline });
  698. }
  699. {
  700. std::lock_guard<std::mutex> guard(compile_count_mutex);
  701. assert(compile_count > 0);
  702. compile_count--;
  703. // "Progress bar" for shader compiles
  704. static uint32_t total_compile_count = 0;
  705. if ((total_compile_count++ % 10) == 0) {
  706. std::cerr << ".";
  707. }
  708. }
  709. compile_count_cond.notify_all();
  710. }
  711. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  712. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  713. for (auto& pool : pipeline->descriptor_pools) {
  714. device.destroyDescriptorPool(pool);
  715. }
  716. pipeline->descriptor_pools.clear();
  717. pipeline->descriptor_sets.clear();
  718. pipeline->descriptor_set_idx = 0;
  719. device.destroyDescriptorSetLayout(pipeline->dsl);
  720. device.destroyPipelineLayout(pipeline->layout);
  721. device.destroyShaderModule(pipeline->shader_module);
  722. device.destroyPipeline(pipeline->pipeline);
  723. }
  724. static void ggml_pipeline_request_descriptor_sets(vk_device& device, vk_pipeline& pipeline, uint32_t n) {
  725. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  726. device->pipeline_descriptor_set_requirements[pipeline->name] += n;
  727. }
  728. static void ggml_pipeline_allocate_descriptor_sets(vk_device& device) {
  729. std::lock_guard<std::mutex> guard(device->mutex);
  730. for (auto& pair : device->pipeline_descriptor_set_requirements) {
  731. vk_pipeline pipeline = device->pipelines.at(pair.first).lock();
  732. const uint64_t n = pair.second;
  733. VK_LOG_DEBUG("ggml_pipeline_allocate_descriptor_sets(" << pipeline->name << ", " << n << ")");
  734. if (pipeline->descriptor_sets.size() >= pipeline->descriptor_set_idx + n) {
  735. // Enough descriptors are available
  736. continue;
  737. }
  738. uint32_t to_alloc = pipeline->descriptor_set_idx + n - pipeline->descriptor_sets.size();
  739. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - pipeline->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  740. uint32_t pool_idx = pipeline->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  741. while (to_alloc > 0) {
  742. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  743. to_alloc -= alloc_count;
  744. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  745. if (pool_idx >= pipeline->descriptor_pools.size()) {
  746. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  747. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  748. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  749. }
  750. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  751. for (uint32_t i = 0; i < alloc_count; i++) {
  752. layouts[i] = pipeline->dsl;
  753. }
  754. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[pool_idx], alloc_count, layouts.data());
  755. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  756. pipeline->descriptor_sets.insert(pipeline->descriptor_sets.end(), sets.begin(), sets.end());
  757. pool_idx++;
  758. }
  759. }
  760. }
  761. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  762. VK_LOG_DEBUG("ggml_pipeline_cleanup(" << pipeline->name << ")");
  763. pipeline->descriptor_set_idx = 0;
  764. }
  765. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_queue& q) {
  766. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  767. std::lock_guard<std::mutex> guard(device->mutex);
  768. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  769. // Reuse command buffer
  770. return q.cmd_buffers[q.cmd_buffer_idx++];
  771. }
  772. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  773. q.pool,
  774. vk::CommandBufferLevel::ePrimary,
  775. 1);
  776. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  777. auto buf = cmd_buffers.front();
  778. q.cmd_buffers.push_back(buf);
  779. q.cmd_buffer_idx++;
  780. return buf;
  781. }
  782. static vk_submission ggml_vk_create_submission(vk_device& device, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  783. VK_LOG_DEBUG("ggml_vk_create_submission()");
  784. vk_submission s;
  785. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  786. s.wait_semaphores = std::move(wait_semaphores);
  787. s.signal_semaphores = std::move(signal_semaphores);
  788. return s;
  789. }
  790. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  791. if (ctx->seqs.empty()) {
  792. if (fence) {
  793. ctx->q->queue.submit({}, fence);
  794. }
  795. return;
  796. }
  797. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  798. std::vector<std::vector<uint64_t>> tl_wait_vals;
  799. std::vector<std::vector<uint64_t>> tl_signal_vals;
  800. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  801. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  802. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  803. std::vector<vk::SubmitInfo> submit_infos;
  804. int idx = -1;
  805. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  806. size_t reserve = 0;
  807. for (const auto& sequence : ctx->seqs) {
  808. reserve += sequence.size();
  809. }
  810. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  811. tl_wait_semaphores.reserve(reserve);
  812. tl_wait_vals.reserve(reserve);
  813. tl_signal_semaphores.reserve(reserve);
  814. tl_signal_vals.reserve(reserve);
  815. tl_submit_infos.reserve(reserve);
  816. submit_infos.reserve(reserve);
  817. stage_flags.reserve(reserve);
  818. for (const auto& sequence : ctx->seqs) {
  819. for (const auto& submission : sequence) {
  820. stage_flags.push_back({});
  821. idx++;
  822. tl_wait_vals.push_back({});
  823. tl_wait_semaphores.push_back({});
  824. tl_signal_vals.push_back({});
  825. tl_signal_semaphores.push_back({});
  826. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  827. stage_flags[idx].push_back(ctx->q->stage_flags);
  828. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  829. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  830. }
  831. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  832. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  833. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  834. }
  835. tl_submit_infos.push_back({
  836. (uint32_t) submission.wait_semaphores.size(),
  837. tl_wait_vals[idx].data(),
  838. (uint32_t) submission.signal_semaphores.size(),
  839. tl_signal_vals[idx].data(),
  840. });
  841. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  842. tl_submit_infos[idx].pNext = nullptr;
  843. vk::SubmitInfo si{
  844. (uint32_t) submission.wait_semaphores.size(),
  845. tl_wait_semaphores[idx].data(),
  846. stage_flags[idx].data(),
  847. 1,
  848. &submission.buffer,
  849. (uint32_t) submission.signal_semaphores.size(),
  850. tl_signal_semaphores[idx].data(),
  851. };
  852. si.setPNext(&tl_submit_infos[idx]);
  853. submit_infos.push_back(si);
  854. }
  855. }
  856. ctx->q->queue.submit(submit_infos, fence);
  857. ctx->seqs.clear();
  858. }
  859. 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) {
  860. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  861. const uint32_t qfsize = queue_family_props.size();
  862. // Try with avoid preferences first
  863. for (uint32_t i = 0; i < qfsize; i++) {
  864. 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)) {
  865. return i;
  866. }
  867. }
  868. // Fall back to only required
  869. for (size_t i = 0; i < qfsize; i++) {
  870. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  871. return i;
  872. }
  873. }
  874. // Fall back to reusing compute queue
  875. for (size_t i = 0; i < qfsize; i++) {
  876. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  877. return i;
  878. }
  879. }
  880. // Fall back to ignoring min_num_queries
  881. for (size_t i = 0; i < qfsize; i++) {
  882. if (queue_family_props[i].queueFlags & required) {
  883. return i;
  884. }
  885. }
  886. // 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.
  887. // 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.
  888. if (compute_index >= 0) {
  889. return compute_index;
  890. }
  891. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  892. for(auto &q_family : queue_family_props) {
  893. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  894. }
  895. abort();
  896. }
  897. 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) {
  898. VK_LOG_DEBUG("ggml_vk_create_queue()");
  899. std::lock_guard<std::mutex> guard(device->mutex);
  900. q.queue_family_index = queue_family_index;
  901. q.transfer_only = transfer_only;
  902. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  903. q.pool = device->device.createCommandPool(command_pool_create_info_compute);
  904. q.cmd_buffer_idx = 0;
  905. q.queue = device->device.getQueue(queue_family_index, queue_index);
  906. q.stage_flags = stage_flags;
  907. }
  908. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  909. vk_context result = std::make_shared<vk_context_struct>();
  910. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  911. ctx->gc.contexts.emplace_back(result);
  912. result->q = &q;
  913. return result;
  914. }
  915. static vk_context ggml_vk_create_temporary_context(vk_queue& q) {
  916. vk_context result = std::make_shared<vk_context_struct>();
  917. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  918. result->q = &q;
  919. return result;
  920. }
  921. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  922. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  923. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  924. vk::SemaphoreCreateInfo ci{};
  925. ci.setPNext(&tci);
  926. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  927. ctx->gc.semaphores.push_back({ semaphore, 0 });
  928. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  929. }
  930. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  931. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  932. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  933. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  934. vk::SemaphoreCreateInfo ci{};
  935. ci.setPNext(&tci);
  936. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  937. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  938. }
  939. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  940. }
  941. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  942. if (ctx->event_idx >= ctx->gc.events.size()) {
  943. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  944. }
  945. return ctx->gc.events[ctx->event_idx++];
  946. }
  947. static void ggml_vk_queue_cleanup(vk_device& device, vk_queue& q) {
  948. VK_LOG_DEBUG("ggml_vk_queue_cleanup()");
  949. std::lock_guard<std::mutex> guard(device->mutex);
  950. // Requires command buffers to be done
  951. device->device.resetCommandPool(q.pool);
  952. q.cmd_buffer_idx = 0;
  953. }
  954. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  955. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  956. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  957. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  958. (flags & memory_type.propertyFlags) == flags &&
  959. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  960. return static_cast<int32_t>(i);
  961. }
  962. }
  963. return UINT32_MAX;
  964. }
  965. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  966. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")");
  967. if (size > device->max_memory_allocation_size) {
  968. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  969. }
  970. std::lock_guard<std::mutex> guard(device->mutex);
  971. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  972. if (size == 0) {
  973. buf->size = 0;
  974. return buf;
  975. }
  976. vk::BufferCreateInfo buffer_create_info{
  977. vk::BufferCreateFlags(),
  978. size,
  979. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  980. vk::SharingMode::eExclusive,
  981. 0,
  982. nullptr,
  983. };
  984. buf->buffer = device->device.createBuffer(buffer_create_info);
  985. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  986. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  987. uint32_t memory_type_index = UINT32_MAX;
  988. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  989. buf->memory_property_flags = req_flags;
  990. if (memory_type_index == UINT32_MAX && fallback_flags) {
  991. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  992. buf->memory_property_flags = fallback_flags;
  993. }
  994. if (memory_type_index == UINT32_MAX) {
  995. device->device.destroyBuffer(buf->buffer);
  996. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  997. }
  998. try {
  999. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1000. } catch (const vk::SystemError& e) {
  1001. if (buf->memory_property_flags != fallback_flags) {
  1002. // Try again with fallback flags
  1003. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1004. buf->memory_property_flags = fallback_flags;
  1005. try {
  1006. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1007. }
  1008. catch (const vk::SystemError& e) {
  1009. device->device.destroyBuffer(buf->buffer);
  1010. throw e;
  1011. }
  1012. } else {
  1013. // Out of Host/Device memory, clean up buffer
  1014. device->device.destroyBuffer(buf->buffer);
  1015. throw e;
  1016. }
  1017. }
  1018. buf->ptr = nullptr;
  1019. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1020. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1021. }
  1022. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1023. buf->device = device;
  1024. buf->size = size;
  1025. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1026. device->memory_logger->log_allocation(buf, size);
  1027. #endif
  1028. return buf;
  1029. }
  1030. 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)) {
  1031. try {
  1032. return ggml_vk_create_buffer(device, size, req_flags, fallback_flags);
  1033. } catch (const vk::SystemError& e) {
  1034. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1035. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1036. throw e;
  1037. }
  1038. }
  1039. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1040. vk_buffer buf;
  1041. try {
  1042. if (device->uma) {
  1043. // Fall back to host memory type
  1044. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1045. } else {
  1046. // use rebar if available, otherwise fallback to device only visible memory
  1047. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1048. }
  1049. } catch (const vk::SystemError& e) {
  1050. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1051. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1052. throw e;
  1053. }
  1054. return buf;
  1055. }
  1056. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1057. if (buf == nullptr) {
  1058. return;
  1059. }
  1060. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1061. if (buf->device != nullptr) {
  1062. buf->device->memory_logger->log_deallocation(buf);
  1063. }
  1064. #endif
  1065. buf.reset();
  1066. }
  1067. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1068. return { buf, 0, VK_WHOLE_SIZE };
  1069. }
  1070. static void ggml_vk_sync_buffers(vk_context& ctx) {
  1071. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1072. const bool transfer_queue = ctx->q->transfer_only;
  1073. ctx->s->buffer.pipelineBarrier(
  1074. ctx->q->stage_flags,
  1075. ctx->q->stage_flags,
  1076. {},
  1077. { {
  1078. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1079. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1080. } },
  1081. {},
  1082. {}
  1083. );
  1084. }
  1085. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1086. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1087. if (events.empty()) {
  1088. return;
  1089. }
  1090. ctx->s->buffer.waitEvents(
  1091. events,
  1092. ctx->q->stage_flags,
  1093. ctx->q->stage_flags,
  1094. {},
  1095. {},
  1096. {}
  1097. );
  1098. }
  1099. // number of rows/cols for flash attention shader
  1100. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1101. static std::array<uint32_t, 2> fa_rows_cols(uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) {
  1102. GGML_UNUSED(clamp);
  1103. // small rows, large cols
  1104. if (small_rows) {
  1105. return {flash_attention_num_small_rows, 128};
  1106. }
  1107. // small cols to reduce register count
  1108. if (ggml_is_quantized(type) || D == 256) {
  1109. return {64, 32};
  1110. }
  1111. return {64, 64};
  1112. };
  1113. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id) {
  1114. // Needs to be kept up to date on shader changes
  1115. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1116. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1117. const uint32_t warps = warptile[0] / device->subgroup_size;
  1118. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1119. const uint32_t mmid_row_ids = mul_mat_id ? 3072 * sizeof(uint32_t) : 0;
  1120. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1121. return (load_bufs + mmid_row_ids + coopmat_stage) <= device->properties.limits.maxComputeSharedMemorySize;
  1122. }
  1123. static void ggml_vk_load_shaders(vk_device& device) {
  1124. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1125. std::cerr << "ggml_vulkan: Compiling shaders";
  1126. // some shaders require the subgroup size to be 16 or larger
  1127. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1128. // mulmat
  1129. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  1130. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  1131. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  1132. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  1133. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  1134. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  1135. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  1136. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  1137. uint32_t l_align, m_align, s_align;
  1138. if (device->coopmat2) {
  1139. // spec constants and tile sizes for non-quant matmul/matmul_id
  1140. l_warptile = { 256, 128, 256, 64 };
  1141. m_warptile = { 256, 128, 128, 64 };
  1142. s_warptile = { 128, 32, 16, 64 };
  1143. l_wg_denoms = {128, 256, 1 };
  1144. m_wg_denoms = {128, 128, 1 };
  1145. s_wg_denoms = { 32, 16, 1 };
  1146. // spec constants and tile sizes for quant matmul (non-Qi_K)
  1147. l_warptile_mmq = { 256, 128, 256, 64 };
  1148. m_warptile_mmq = { 256, 128, 128, 64 };
  1149. s_warptile_mmq = { 256, 128, 128, 64 };
  1150. l_mmq_wg_denoms = { 128, 256, 1 };
  1151. m_mmq_wg_denoms = { 128, 128, 1 };
  1152. s_mmq_wg_denoms = { 128, 128, 1 };
  1153. // spec constants and tile sizes for quant matmul (Qi_K)
  1154. l_warptile_mmq_k = { 256, 128, 512, 16 };
  1155. m_warptile_mmq_k = { 256, 128, 256, 16 };
  1156. s_warptile_mmq_k = { 256, 32, 128, 64 };
  1157. l_mmq_wg_denoms_k = { 128, 512, 1 };
  1158. m_mmq_wg_denoms_k = { 128, 256, 1 };
  1159. s_mmq_wg_denoms_k = { 32, 128, 1 };
  1160. // spec constants and tile sizes for quant matmul_id
  1161. l_warptile_mmqid = { 256, 128, 128, 16 };
  1162. m_warptile_mmqid = { 256, 128, 64, 16 };
  1163. s_warptile_mmqid = { 256, 64, 64, 16 };
  1164. l_mmqid_wg_denoms = { 128, 128, 1 };
  1165. m_mmqid_wg_denoms = { 128, 64, 1 };
  1166. s_mmqid_wg_denoms = { 64, 64, 1 };
  1167. l_align = 128;
  1168. m_align = 64;
  1169. s_align = 32;
  1170. } else {
  1171. // Matrix cores require different warp group sizes
  1172. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  1173. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  1174. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  1175. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  1176. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  1177. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  1178. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  1179. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  1180. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  1181. l_warptile = { 128, 128, 128, 16, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1182. m_warptile = { 128, 64, 64, 16, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1183. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1184. l_warptile_mmq = { 128, 128, 128, 32, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1185. m_warptile_mmq = { 128, 64, 64, 32, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1186. s_warptile_mmq = { subgroup_size_16, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1187. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  1188. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  1189. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  1190. l_align = 128;
  1191. m_align = 64;
  1192. s_align = 32;
  1193. // Fallback to smaller sizes if there's not enough shared memory. Given the current shaders
  1194. // and tile sizes, this should handle 16KB, 32KB, and 48KB+.
  1195. // This logic doesn't explicitly account for the 12KB row_ids in the mul_mat_mat_id shaders.
  1196. // But the numbers happen to work out for 32KB shared memory size that when using the medium
  1197. // size there's enough room for everything, and we assert for this.
  1198. uint32_t shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1199. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1200. l_warptile = m_warptile;
  1201. l_wg_denoms = m_wg_denoms;
  1202. shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1203. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1204. }
  1205. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1206. // assert mul_mat_mat_id shaders will fit.
  1207. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1208. }
  1209. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1210. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1211. if (device->properties.limits.maxComputeSharedMemorySize == 32768) {
  1212. l_warptile_mmq = m_warptile_mmq;
  1213. l_mmq_wg_denoms = m_mmq_wg_denoms;
  1214. } else {
  1215. l_warptile_mmq = s_warptile_mmq;
  1216. l_mmq_wg_denoms = s_mmq_wg_denoms;
  1217. }
  1218. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1219. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1220. }
  1221. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1222. // assert mul_mat_mat_id shaders will fit.
  1223. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1224. }
  1225. // Disable medium and large matrix multiplication if not enough shared memory is available
  1226. // Check mmq warptiles as the largest configuration
  1227. // Throw an error if not enough for any matrix multiplication is available
  1228. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false)) {
  1229. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  1230. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  1231. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false)) {
  1232. device->mul_mat_m = false;
  1233. device->mul_mat_l = false;
  1234. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false)) {
  1235. device->mul_mat_l = false;
  1236. }
  1237. // Disable mul_mat_id if not enough shared memory is available
  1238. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, true)) {
  1239. device->mul_mat_id_s = false;
  1240. device->mul_mat_id_m = false;
  1241. device->mul_mat_id_l = false;
  1242. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, true)) {
  1243. device->mul_mat_id_m = false;
  1244. device->mul_mat_id_l = false;
  1245. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, true)) {
  1246. device->mul_mat_id_l = false;
  1247. }
  1248. }
  1249. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1250. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  1251. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1252. std::vector<std::future<void>> compiles;
  1253. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const std::string &entrypoint, uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants, uint32_t align, bool disable_robustness = false) {
  1254. {
  1255. // wait until fewer than N compiles are in progress
  1256. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  1257. std::unique_lock<std::mutex> guard(compile_count_mutex);
  1258. while (compile_count >= N) {
  1259. compile_count_cond.wait(guard);
  1260. }
  1261. compile_count++;
  1262. }
  1263. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), name, spv_size, spv_data, entrypoint, parameter_count, push_constant_size, wg_denoms, specialization_constants, align, disable_robustness));
  1264. };
  1265. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1266. if (device->coopmat2) {
  1267. auto const &fa_wg_denoms = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  1268. return {fa_rows_cols(D, clamp, type, small_rows)[0], 1, 1};
  1269. };
  1270. auto const &fa_spec_constants = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  1271. // For large number of rows, 128 invocations seems to work best.
  1272. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  1273. // can't use 256 for D==80.
  1274. uint32_t wg_size = (small_rows && (D % 32) == 0) ? 256 : 128;
  1275. auto rows_cols = fa_rows_cols(D, clamp, type, small_rows);
  1276. return {wg_size, rows_cols[0], rows_cols[1], (D), clamp};
  1277. };
  1278. #define CREATE_FA2(TYPE, NAMELC, D) \
  1279. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][0], "flash_attn_f32_f16_D" #D "_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1280. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1281. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][0], "flash_attn_f32_f16_D" #D "_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1282. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1283. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][0], "flash_attn_f32_f16_D" #D "_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1284. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1285. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][0], "flash_attn_f32_f16_D" #D "_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1286. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1287. #define CREATE_FA(TYPE, NAMELC) \
  1288. CREATE_FA2(TYPE, NAMELC, 64) \
  1289. CREATE_FA2(TYPE, NAMELC, 80) \
  1290. CREATE_FA2(TYPE, NAMELC, 96) \
  1291. CREATE_FA2(TYPE, NAMELC, 112) \
  1292. CREATE_FA2(TYPE, NAMELC, 128) \
  1293. CREATE_FA2(TYPE, NAMELC, 256)
  1294. CREATE_FA(GGML_TYPE_F16, f16)
  1295. CREATE_FA(GGML_TYPE_Q4_0, q4_0)
  1296. CREATE_FA(GGML_TYPE_Q4_1, q4_1)
  1297. CREATE_FA(GGML_TYPE_Q5_0, q5_0)
  1298. CREATE_FA(GGML_TYPE_Q5_1, q5_1)
  1299. CREATE_FA(GGML_TYPE_Q8_0, q8_0)
  1300. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  1301. //CREATE_FA(GGML_TYPE_Q2_K, q2_k)
  1302. //CREATE_FA(GGML_TYPE_Q3_K, q3_k)
  1303. //CREATE_FA(GGML_TYPE_Q4_K, q4_k)
  1304. //CREATE_FA(GGML_TYPE_Q5_K, q5_k)
  1305. //CREATE_FA(GGML_TYPE_Q6_K, q6_k)
  1306. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl)
  1307. #undef CREATE_FA
  1308. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1309. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1310. 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); \
  1311. 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); \
  1312. 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); \
  1313. 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); \
  1314. 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); \
  1315. 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); \
  1316. // Create 2 variants, {f16,f32} accumulator
  1317. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1318. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1319. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1320. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1321. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1322. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1323. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1324. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1325. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1326. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1327. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1328. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1329. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1330. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1331. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1332. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1333. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1334. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1335. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1336. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1337. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1338. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1339. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1340. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1341. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1342. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1343. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1344. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1345. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1346. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1347. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1348. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1349. #undef CREATE_MM
  1350. #undef CREATE_MM2
  1351. } else
  1352. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1353. if (device->coopmat_support) {
  1354. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1355. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1356. if (device->mul_mat ## ID ## _l) \
  1357. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1358. if (device->mul_mat ## ID ## _m) \
  1359. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1360. if (device->mul_mat ## ID ## _s) \
  1361. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1362. if (device->mul_mat ## ID ## _l) \
  1363. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1364. if (device->mul_mat ## ID ## _m) \
  1365. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1366. if (device->mul_mat ## ID ## _s) \
  1367. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1368. // Create 2 variants, {f16,f32} accumulator
  1369. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1370. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1371. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1372. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1373. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1374. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1375. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1376. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1377. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1378. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1379. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1380. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1381. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1382. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1383. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1384. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1385. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1386. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1387. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1388. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1389. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1390. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1391. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1392. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1393. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1394. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1395. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1396. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1397. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1398. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1399. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1400. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1401. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1402. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1403. }
  1404. #undef CREATE_MM
  1405. } else if (device->fp16) {
  1406. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1407. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1408. if (device->mul_mat ## ID ## _l) \
  1409. 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); \
  1410. if (device->mul_mat ## ID ## _m) \
  1411. 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); \
  1412. if (device->mul_mat ## ID ## _s) \
  1413. 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); \
  1414. if (device->mul_mat ## ID ## _l) \
  1415. 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); \
  1416. if (device->mul_mat ## ID ## _m) \
  1417. 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); \
  1418. if (device->mul_mat ## ID ## _s) \
  1419. 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); \
  1420. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1421. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1422. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1423. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1424. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1425. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1426. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1427. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1428. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1429. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1430. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1431. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1432. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1433. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1434. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1435. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1436. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1437. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1438. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1439. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1440. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1441. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1442. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1443. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1444. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1445. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1446. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1447. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1448. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1449. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1450. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1451. }
  1452. #undef CREATE_MM
  1453. } else {
  1454. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1455. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1456. if (device->mul_mat ## ID ## _l) \
  1457. 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); \
  1458. if (device->mul_mat ## ID ## _m) \
  1459. 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); \
  1460. if (device->mul_mat ## ID ## _s) \
  1461. 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); \
  1462. if (device->mul_mat ## ID ## _l) \
  1463. 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); \
  1464. if (device->mul_mat ## ID ## _m) \
  1465. 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); \
  1466. if (device->mul_mat ## ID ## _s) \
  1467. 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); \
  1468. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1469. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1470. CREATE_MM(pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1471. CREATE_MM(pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1472. CREATE_MM(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, );
  1473. CREATE_MM(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, );
  1474. CREATE_MM(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, );
  1475. CREATE_MM(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, );
  1476. CREATE_MM(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, );
  1477. CREATE_MM(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, );
  1478. CREATE_MM(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, );
  1479. CREATE_MM(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, );
  1480. CREATE_MM(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, );
  1481. CREATE_MM(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, );
  1482. CREATE_MM(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, );
  1483. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1484. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1485. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1486. CREATE_MM(pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1487. CREATE_MM(pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1488. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1489. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1490. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1491. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1492. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1493. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1494. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1495. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1496. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1497. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1498. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1499. }
  1500. #undef CREATE_MM2
  1501. #undef CREATE_MM
  1502. }
  1503. // mul mat vec
  1504. // computing two rows per workgroup is a benefit for Q4_0 -> Q5_1, but not for Q8_0.
  1505. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F32 ], "mul_mat_vec_f32_f32_f32", mul_mat_vec_f32_f32_f32_len, mul_mat_vec_f32_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1506. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f32_f32", mul_mat_vec_f16_f32_f32_len, mul_mat_vec_f16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1507. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f32_f32", mul_mat_vec_q4_0_f32_f32_len, mul_mat_vec_q4_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1508. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f32_f32", mul_mat_vec_q4_1_f32_f32_len, mul_mat_vec_q4_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1509. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f32_f32", mul_mat_vec_q5_0_f32_f32_len, mul_mat_vec_q5_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1510. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f32_f32", mul_mat_vec_q5_1_f32_f32_len, mul_mat_vec_q5_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1511. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f32_f32", mul_mat_vec_q8_0_f32_f32_len, mul_mat_vec_q8_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1512. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_k_f32_f32", mul_mat_vec_q2_k_f32_f32_len, mul_mat_vec_q2_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1513. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_k_f32_f32", mul_mat_vec_q3_k_f32_f32_len, mul_mat_vec_q3_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1514. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_k_f32_f32", mul_mat_vec_q4_k_f32_f32_len, mul_mat_vec_q4_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1515. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_k_f32_f32", mul_mat_vec_q5_k_f32_f32_len, mul_mat_vec_q5_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1516. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_k_f32_f32", mul_mat_vec_q6_k_f32_f32_len, mul_mat_vec_q6_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1517. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_iq4_nl_f32_f32", mul_mat_vec_iq4_nl_f32_f32_len, mul_mat_vec_iq4_nl_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1518. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F32 ], "mul_mat_vec_f32_f16_f32", mul_mat_vec_f32_f16_f32_len, mul_mat_vec_f32_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1519. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f16_f32", mul_mat_vec_f16_f16_f32_len, mul_mat_vec_f16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1520. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f16_f32", mul_mat_vec_q4_0_f16_f32_len, mul_mat_vec_q4_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1521. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f16_f32", mul_mat_vec_q4_1_f16_f32_len, mul_mat_vec_q4_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1522. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f16_f32", mul_mat_vec_q5_0_f16_f32_len, mul_mat_vec_q5_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1523. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f16_f32", mul_mat_vec_q5_1_f16_f32_len, mul_mat_vec_q5_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1524. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f16_f32", mul_mat_vec_q8_0_f16_f32_len, mul_mat_vec_q8_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1525. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_k_f16_f32", mul_mat_vec_q2_k_f16_f32_len, mul_mat_vec_q2_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1526. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_k_f16_f32", mul_mat_vec_q3_k_f16_f32_len, mul_mat_vec_q3_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1527. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_k_f16_f32", mul_mat_vec_q4_k_f16_f32_len, mul_mat_vec_q4_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1528. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_k_f16_f32", mul_mat_vec_q5_k_f16_f32_len, mul_mat_vec_q5_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1529. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_k_f16_f32", mul_mat_vec_q6_k_f16_f32_len, mul_mat_vec_q6_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1530. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_iq4_nl_f16_f32", mul_mat_vec_iq4_nl_f16_f32_len, mul_mat_vec_iq4_nl_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size}, 1, true);
  1531. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1532. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1533. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1534. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1535. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1536. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1537. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1538. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1539. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1540. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1541. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1542. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1543. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1544. // dequant shaders
  1545. 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);
  1546. 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);
  1547. 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);
  1548. 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);
  1549. 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);
  1550. 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);
  1551. 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);
  1552. 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);
  1553. 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);
  1554. 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);
  1555. 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);
  1556. 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);
  1557. // get_rows
  1558. 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);
  1559. 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);
  1560. 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);
  1561. 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);
  1562. 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);
  1563. 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);
  1564. 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);
  1565. 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);
  1566. 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);
  1567. 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);
  1568. 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);
  1569. 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);
  1570. 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);
  1571. 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);
  1572. 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);
  1573. 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);
  1574. 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);
  1575. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_p021_f16_f32, "mul_mat_vec_p021_f16_f32", mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1576. 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", 3, 7 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1577. 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);
  1578. 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);
  1579. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1580. 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);
  1581. 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);
  1582. 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);
  1583. 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);
  1584. 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);
  1585. 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);
  1586. ggml_vk_create_pipeline(device, device->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1587. ggml_vk_create_pipeline(device, device->pipeline_add_f32_norepeat, "add_f32_norepeat", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1588. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16, "add_f16_f32_f16", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1589. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16_norepeat, "add_f16_f32_f16_norepeat", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1590. 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);
  1591. ggml_vk_create_pipeline(device, device->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1592. ggml_vk_create_pipeline(device, device->pipeline_mul_f32_norepeat, "mul_f32_norepeat", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1593. ggml_vk_create_pipeline(device, device->pipeline_div_f32, "div_f32", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1594. ggml_vk_create_pipeline(device, device->pipeline_div_f32_norepeat, "div_f32_norepeat", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1595. 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);
  1596. 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);
  1597. 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);
  1598. ggml_vk_create_pipeline(device, device->pipeline_upscale_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {}, 1);
  1599. 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);
  1600. 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);
  1601. 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);
  1602. 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);
  1603. 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);
  1604. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1605. 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);
  1606. ggml_vk_create_pipeline(device, device->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1607. ggml_vk_create_pipeline(device, device->pipeline_gelu_quick_f32, "gelu_quick_f32", gelu_quick_f32_len, gelu_quick_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1608. ggml_vk_create_pipeline(device, device->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1609. ggml_vk_create_pipeline(device, device->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1610. 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);
  1611. ggml_vk_create_pipeline(device, device->pipeline_tanh_f32, "tanh_f32", tanh_f32_len, tanh_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1612. 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), {512, 1, 1}, {}, 1);
  1613. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1614. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1615. 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", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1616. 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", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1617. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1618. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1619. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1620. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1621. ggml_vk_create_pipeline(device, device->pipeline_argsort_f32, "argsort_f32", argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1024, 1, 1}, {}, 1);
  1622. 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_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1623. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32_len, im2col_f32_data, "main", 2, sizeof(vk_op_im2col_push_constants), {256, 1, 1}, {}, 1);
  1624. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_len, im2col_f32_f16_data, "main", 2, sizeof(vk_op_im2col_push_constants), {256, 1, 1}, {}, 1);
  1625. 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);
  1626. 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);
  1627. for (auto &c : compiles) {
  1628. c.wait();
  1629. }
  1630. std::cerr << "Done!" << std::endl;
  1631. }
  1632. static vk_device ggml_vk_get_device(size_t idx) {
  1633. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  1634. if (vk_instance.devices[idx] == nullptr) {
  1635. VK_LOG_DEBUG("Initializing new vk_device");
  1636. vk_device device = std::make_shared<vk_device_struct>();
  1637. vk_instance.devices[idx] = device;
  1638. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1639. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  1640. #endif
  1641. #ifdef GGML_VULKAN_PERF
  1642. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  1643. #endif
  1644. size_t dev_num = vk_instance.device_indices[idx];
  1645. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  1646. if (dev_num >= physical_devices.size()) {
  1647. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  1648. throw std::runtime_error("Device not found");
  1649. }
  1650. device->physical_device = physical_devices[dev_num];
  1651. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  1652. bool fp16_storage = false;
  1653. bool fp16_compute = false;
  1654. bool maintenance4_support = false;
  1655. bool sm_builtins = false;
  1656. bool amd_shader_core_properties2 = false;
  1657. bool pipeline_robustness = false;
  1658. bool coopmat2_support = false;
  1659. device->coopmat_support = false;
  1660. // Check if maintenance4 is supported
  1661. for (const auto& properties : ext_props) {
  1662. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  1663. maintenance4_support = true;
  1664. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1665. fp16_storage = true;
  1666. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1667. fp16_compute = true;
  1668. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  1669. sm_builtins = true;
  1670. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  1671. amd_shader_core_properties2 = true;
  1672. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  1673. pipeline_robustness = true;
  1674. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  1675. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  1676. device->coopmat_support = true;
  1677. device->coopmat_m = 0;
  1678. device->coopmat_n = 0;
  1679. device->coopmat_k = 0;
  1680. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  1681. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  1682. coopmat2_support = true;
  1683. }
  1684. }
  1685. vk::PhysicalDeviceProperties2 props2;
  1686. vk::PhysicalDeviceMaintenance3Properties props3;
  1687. vk::PhysicalDeviceMaintenance4Properties props4;
  1688. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  1689. vk::PhysicalDeviceDriverProperties driver_props;
  1690. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  1691. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  1692. props2.pNext = &props3;
  1693. props3.pNext = &subgroup_props;
  1694. subgroup_props.pNext = &driver_props;
  1695. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  1696. if (maintenance4_support) {
  1697. last_struct->pNext = (VkBaseOutStructure *)&props4;
  1698. last_struct = (VkBaseOutStructure *)&props4;
  1699. }
  1700. if (sm_builtins) {
  1701. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  1702. last_struct = (VkBaseOutStructure *)&sm_props;
  1703. }
  1704. if (amd_shader_core_properties2) {
  1705. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1706. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1707. }
  1708. #if defined(VK_NV_cooperative_matrix2)
  1709. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  1710. if (coopmat2_support) {
  1711. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  1712. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  1713. }
  1714. #endif
  1715. device->physical_device.getProperties2(&props2);
  1716. device->properties = props2.properties;
  1717. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  1718. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  1719. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  1720. } else if (maintenance4_support) {
  1721. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  1722. } else {
  1723. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  1724. }
  1725. device->vendor_id = device->properties.vendorID;
  1726. device->subgroup_size = subgroup_props.subgroupSize;
  1727. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1728. if (sm_builtins) {
  1729. device->shader_core_count = sm_props.shaderSMCount;
  1730. } else if (amd_shader_core_properties2) {
  1731. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  1732. } else {
  1733. device->shader_core_count = 0;
  1734. }
  1735. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  1736. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1737. if (device->vendor_id == VK_VENDOR_ID_INTEL || (props2.properties.vendorID == VK_VENDOR_ID_AMD && driver_props.driverID == vk::DriverId::eAmdProprietary)) {
  1738. // Intel drivers don't support coopmat properly yet
  1739. // Only RADV supports coopmat properly on AMD
  1740. device->coopmat_support = false;
  1741. }
  1742. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  1743. // Try to find a non-graphics compute queue and transfer-focused queues
  1744. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1745. 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);
  1746. const float priorities[] = { 1.0f, 1.0f };
  1747. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1748. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1749. if (compute_queue_family_index != transfer_queue_family_index) {
  1750. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1751. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1752. } else if(!device->single_queue) {
  1753. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1754. } else {
  1755. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1756. }
  1757. vk::DeviceCreateInfo device_create_info;
  1758. std::vector<const char *> device_extensions;
  1759. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  1760. VkPhysicalDeviceFeatures2 device_features2;
  1761. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1762. device_features2.pNext = nullptr;
  1763. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1764. VkPhysicalDeviceVulkan11Features vk11_features;
  1765. vk11_features.pNext = nullptr;
  1766. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1767. device_features2.pNext = &vk11_features;
  1768. VkPhysicalDeviceVulkan12Features vk12_features;
  1769. vk12_features.pNext = nullptr;
  1770. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1771. vk11_features.pNext = &vk12_features;
  1772. last_struct = (VkBaseOutStructure *)&vk12_features;
  1773. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  1774. pl_robustness_features.pNext = nullptr;
  1775. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  1776. pl_robustness_features.pipelineRobustness = VK_FALSE;
  1777. if (pipeline_robustness) {
  1778. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  1779. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  1780. device_extensions.push_back("VK_EXT_pipeline_robustness");
  1781. }
  1782. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  1783. coopmat_features.pNext = nullptr;
  1784. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  1785. coopmat_features.cooperativeMatrix = VK_FALSE;
  1786. if (device->coopmat_support) {
  1787. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  1788. last_struct = (VkBaseOutStructure *)&coopmat_features;
  1789. }
  1790. #if defined(VK_NV_cooperative_matrix2)
  1791. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  1792. coopmat2_features.pNext = nullptr;
  1793. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  1794. if (coopmat2_support) {
  1795. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  1796. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  1797. device_extensions.push_back("VK_NV_cooperative_matrix2");
  1798. }
  1799. #endif
  1800. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  1801. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  1802. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  1803. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  1804. if (coopmat2_support) {
  1805. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1806. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  1807. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  1808. coopmat2_features.cooperativeMatrixReductions &&
  1809. coopmat2_features.cooperativeMatrixConversions &&
  1810. coopmat2_features.cooperativeMatrixPerElementOperations &&
  1811. coopmat2_features.cooperativeMatrixTensorAddressing &&
  1812. coopmat2_features.cooperativeMatrixBlockLoads &&
  1813. vk12_features.bufferDeviceAddress) {
  1814. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  1815. uint32_t count = 0;
  1816. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  1817. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  1818. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  1819. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  1820. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  1821. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  1822. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  1823. flexible_dimensions.resize(count, empty_prop);
  1824. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  1825. bool found_fp16_128 = false,
  1826. found_fp16_256 = false,
  1827. found_fp32_128 = false,
  1828. found_fp32_256 = false;
  1829. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  1830. // with 32x16x16 and 256 with 32x32x16.
  1831. for (auto &prop : flexible_dimensions) {
  1832. if (prop.saturatingAccumulation == VK_FALSE &&
  1833. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  1834. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1835. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1836. if (prop.workgroupInvocations == 128 &&
  1837. prop.MGranularity <= 32 &&
  1838. prop.NGranularity <= 16 &&
  1839. prop.KGranularity <= 16) {
  1840. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1841. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1842. found_fp16_128 = true;
  1843. }
  1844. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1845. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1846. found_fp32_128 = true;
  1847. }
  1848. }
  1849. if (prop.workgroupInvocations == 256 &&
  1850. prop.MGranularity <= 32 &&
  1851. prop.NGranularity <= 32 &&
  1852. prop.KGranularity <= 16) {
  1853. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1854. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1855. found_fp16_256 = true;
  1856. }
  1857. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1858. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1859. found_fp32_256 = true;
  1860. }
  1861. }
  1862. }
  1863. }
  1864. if (found_fp16_128 && found_fp16_256 &&
  1865. found_fp32_128 && found_fp32_256 &&
  1866. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  1867. device->coopmat2 = true;
  1868. }
  1869. }
  1870. #endif
  1871. }
  1872. if (!vk11_features.storageBuffer16BitAccess) {
  1873. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  1874. throw std::runtime_error("Unsupported device");
  1875. }
  1876. device_extensions.push_back("VK_KHR_16bit_storage");
  1877. #ifdef GGML_VULKAN_VALIDATE
  1878. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  1879. #endif
  1880. if (device->fp16) {
  1881. device_extensions.push_back("VK_KHR_shader_float16_int8");
  1882. }
  1883. if (device->coopmat_support) {
  1884. // Query supported shapes
  1885. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  1886. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  1887. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  1888. uint32_t cm_props_num;
  1889. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  1890. cm_props.resize(cm_props_num);
  1891. for (auto& prop : cm_props) {
  1892. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  1893. }
  1894. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  1895. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  1896. for (auto& prop : cm_props) {
  1897. 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));
  1898. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  1899. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  1900. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  1901. ) {
  1902. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  1903. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  1904. // coopmat sizes not set yet
  1905. if (device->coopmat_m == 0) {
  1906. device->coopmat_acc_f32_support = true;
  1907. device->coopmat_m = prop.MSize;
  1908. device->coopmat_n = prop.NSize;
  1909. device->coopmat_k = prop.KSize;
  1910. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  1911. // Only enable if shape is identical
  1912. device->coopmat_acc_f32_support = true;
  1913. }
  1914. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  1915. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  1916. // coopmat sizes not set yet
  1917. if (device->coopmat_m == 0) {
  1918. device->coopmat_acc_f16_support = true;
  1919. device->coopmat_m = prop.MSize;
  1920. device->coopmat_n = prop.NSize;
  1921. device->coopmat_k = prop.KSize;
  1922. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  1923. // Only enable if shape is identical
  1924. device->coopmat_acc_f16_support = true;
  1925. }
  1926. }
  1927. }
  1928. }
  1929. if (device->coopmat_m == 0) {
  1930. // No suitable matmul mode found
  1931. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  1932. device->coopmat_support = false;
  1933. }
  1934. }
  1935. if (device->coopmat_support) {
  1936. device_extensions.push_back("VK_KHR_cooperative_matrix");
  1937. }
  1938. device->name = GGML_VK_NAME + std::to_string(idx);
  1939. device_create_info = {
  1940. vk::DeviceCreateFlags(),
  1941. device_queue_create_infos,
  1942. {},
  1943. device_extensions
  1944. };
  1945. device_create_info.setPNext(&device_features2);
  1946. device->device = device->physical_device.createDevice(device_create_info);
  1947. // Queues
  1948. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  1949. // Shaders
  1950. // Disable matmul tile sizes early if performance low or not supported
  1951. switch (device->vendor_id) {
  1952. #ifndef GGML_VULKAN_RUN_TESTS
  1953. case VK_VENDOR_ID_AMD:
  1954. case VK_VENDOR_ID_INTEL:
  1955. device->mul_mat_l = false;
  1956. device->mul_mat_m = true;
  1957. device->mul_mat_s = true;
  1958. device->mul_mat_id_l = false;
  1959. device->mul_mat_id_m = true;
  1960. device->mul_mat_id_s = true;
  1961. break;
  1962. case VK_VENDOR_ID_APPLE:
  1963. device->mul_mat_l = false;
  1964. device->mul_mat_m = true;
  1965. device->mul_mat_s = false;
  1966. device->mul_mat_id_l = false;
  1967. device->mul_mat_id_m = true;
  1968. device->mul_mat_id_s = false;
  1969. break;
  1970. #endif
  1971. default:
  1972. device->mul_mat_l = true;
  1973. device->mul_mat_m = true;
  1974. device->mul_mat_s = true;
  1975. device->mul_mat_id_l = true;
  1976. device->mul_mat_id_m = true;
  1977. device->mul_mat_id_s = true;
  1978. break;
  1979. }
  1980. ggml_vk_load_shaders(device);
  1981. if (!device->single_queue) {
  1982. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  1983. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  1984. } else {
  1985. // TODO: Use pointer or reference to avoid copy
  1986. device->transfer_queue = device->compute_queue;
  1987. }
  1988. device->buffer_type = {
  1989. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  1990. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  1991. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  1992. };
  1993. device->fence = device->device.createFence({});
  1994. device->idx = idx;
  1995. return device;
  1996. }
  1997. return vk_instance.devices[idx];
  1998. }
  1999. static void ggml_vk_print_gpu_info(size_t idx) {
  2000. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2001. size_t dev_num = vk_instance.device_indices[idx];
  2002. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  2003. GGML_ASSERT(vk_instance_initialized);
  2004. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2005. if (dev_num >= devices.size()) {
  2006. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  2007. throw std::runtime_error("Device not found");
  2008. }
  2009. vk::PhysicalDevice physical_device = devices[dev_num];
  2010. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  2011. vk::PhysicalDeviceProperties2 props2;
  2012. vk::PhysicalDeviceMaintenance3Properties props3;
  2013. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  2014. vk::PhysicalDeviceDriverProperties driver_props;
  2015. props2.pNext = &props3;
  2016. props3.pNext = &subgroup_props;
  2017. subgroup_props.pNext = &driver_props;
  2018. physical_device.getProperties2(&props2);
  2019. const size_t subgroup_size = subgroup_props.subgroupSize;
  2020. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  2021. bool fp16_storage = false;
  2022. bool fp16_compute = false;
  2023. bool coopmat_support = false;
  2024. bool coopmat2_support = false;
  2025. for (auto properties : ext_props) {
  2026. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  2027. fp16_storage = true;
  2028. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  2029. fp16_compute = true;
  2030. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  2031. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  2032. coopmat_support = true;
  2033. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  2034. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  2035. coopmat2_support = true;
  2036. }
  2037. }
  2038. if (props2.properties.vendorID == VK_VENDOR_ID_INTEL || (props2.properties.vendorID == VK_VENDOR_ID_AMD && driver_props.driverID == vk::DriverId::eAmdProprietary)) {
  2039. // Intel drivers don't support coopmat properly yet
  2040. // Only RADV supports coopmat properly on AMD
  2041. coopmat_support = false;
  2042. }
  2043. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  2044. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  2045. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  2046. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  2047. VkPhysicalDeviceFeatures2 device_features2;
  2048. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  2049. device_features2.pNext = nullptr;
  2050. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  2051. VkPhysicalDeviceVulkan11Features vk11_features;
  2052. vk11_features.pNext = nullptr;
  2053. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  2054. device_features2.pNext = &vk11_features;
  2055. VkPhysicalDeviceVulkan12Features vk12_features;
  2056. vk12_features.pNext = nullptr;
  2057. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  2058. vk11_features.pNext = &vk12_features;
  2059. // Pointer to the last chain element
  2060. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_features;
  2061. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  2062. coopmat_features.pNext = nullptr;
  2063. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  2064. coopmat_features.cooperativeMatrix = VK_FALSE;
  2065. if (coopmat_support) {
  2066. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  2067. last_struct = (VkBaseOutStructure *)&coopmat_features;
  2068. }
  2069. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  2070. fp16 = fp16 && vk12_features.shaderFloat16;
  2071. coopmat_support = coopmat_support && coopmat_features.cooperativeMatrix;
  2072. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  2073. std::string device_name = props2.properties.deviceName.data();
  2074. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | warp size: %zu | matrix cores: %s\n",
  2075. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, subgroup_size, matrix_cores.c_str());
  2076. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  2077. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  2078. }
  2079. }
  2080. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2081. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2082. void ggml_vk_instance_init() {
  2083. if (vk_instance_initialized) {
  2084. return;
  2085. }
  2086. VK_LOG_DEBUG("ggml_vk_instance_init()");
  2087. vk_instance_initialized = true;
  2088. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, VK_API_VERSION };
  2089. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  2090. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  2091. #ifdef __APPLE__
  2092. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  2093. #endif
  2094. std::vector<const char*> layers;
  2095. if (validation_ext) {
  2096. layers.push_back("VK_LAYER_KHRONOS_validation");
  2097. }
  2098. std::vector<const char*> extensions;
  2099. if (validation_ext) {
  2100. extensions.push_back("VK_EXT_validation_features");
  2101. }
  2102. #ifdef __APPLE__
  2103. if (portability_enumeration_ext) {
  2104. extensions.push_back("VK_KHR_portability_enumeration");
  2105. }
  2106. #endif
  2107. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  2108. #ifdef __APPLE__
  2109. if (portability_enumeration_ext) {
  2110. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  2111. }
  2112. #endif
  2113. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  2114. vk::ValidationFeaturesEXT validation_features;
  2115. if (validation_ext) {
  2116. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  2117. validation_features = {
  2118. features_enable,
  2119. {},
  2120. };
  2121. validation_features.setPNext(nullptr);
  2122. instance_create_info.setPNext(&validation_features);
  2123. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  2124. }
  2125. vk_instance.instance = vk::createInstance(instance_create_info);
  2126. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  2127. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  2128. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  2129. if (devices_env != nullptr) {
  2130. std::string devices(devices_env);
  2131. std::replace(devices.begin(), devices.end(), ',', ' ');
  2132. std::stringstream ss(devices);
  2133. size_t tmp;
  2134. while (ss >> tmp) {
  2135. if(tmp >= num_available_devices) {
  2136. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  2137. throw std::runtime_error("Invalid Vulkan device index");
  2138. }
  2139. vk_instance.device_indices.push_back(tmp);
  2140. }
  2141. } else {
  2142. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2143. // Make sure at least one device exists
  2144. if (devices.empty()) {
  2145. std::cerr << "ggml_vulkan: Error: No devices found." << std::endl;
  2146. GGML_ABORT("fatal error");
  2147. }
  2148. // Default to using all dedicated GPUs
  2149. for (size_t i = 0; i < devices.size(); i++) {
  2150. vk::PhysicalDeviceProperties2 new_props;
  2151. vk::PhysicalDeviceDriverProperties new_driver;
  2152. vk::PhysicalDeviceIDProperties new_id;
  2153. new_props.pNext = &new_driver;
  2154. new_driver.pNext = &new_id;
  2155. devices[i].getProperties2(&new_props);
  2156. if (new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
  2157. // Check if there are two physical devices corresponding to the same GPU
  2158. auto old_device = std::find_if(
  2159. vk_instance.device_indices.begin(),
  2160. vk_instance.device_indices.end(),
  2161. [&devices, &new_id](const size_t k){
  2162. vk::PhysicalDeviceProperties2 old_props;
  2163. vk::PhysicalDeviceIDProperties old_id;
  2164. old_props.pNext = &old_id;
  2165. devices[k].getProperties2(&old_props);
  2166. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  2167. }
  2168. );
  2169. if (old_device == vk_instance.device_indices.end()) {
  2170. vk_instance.device_indices.push_back(i);
  2171. } else {
  2172. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  2173. // This can cause error when splitting layers aross the devices, need to keep only 1
  2174. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  2175. vk::PhysicalDeviceProperties2 old_props;
  2176. vk::PhysicalDeviceDriverProperties old_driver;
  2177. old_props.pNext = &old_driver;
  2178. devices[*old_device].getProperties2(&old_props);
  2179. std::map<vk::DriverId, int> driver_priorities {};
  2180. int old_priority = std::numeric_limits<int>::max();
  2181. int new_priority = std::numeric_limits<int>::max();
  2182. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  2183. // Smaller number -> higher priority
  2184. switch (old_props.properties.vendorID) {
  2185. case VK_VENDOR_ID_AMD:
  2186. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  2187. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  2188. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  2189. break;
  2190. case VK_VENDOR_ID_INTEL:
  2191. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  2192. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  2193. break;
  2194. case VK_VENDOR_ID_NVIDIA:
  2195. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  2196. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  2197. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  2198. #endif
  2199. break;
  2200. }
  2201. if (driver_priorities.count(old_driver.driverID)) {
  2202. old_priority = driver_priorities[old_driver.driverID];
  2203. }
  2204. if (driver_priorities.count(new_driver.driverID)) {
  2205. new_priority = driver_priorities[new_driver.driverID];
  2206. }
  2207. if (new_priority < old_priority) {
  2208. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  2209. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  2210. vk_instance.device_indices.push_back(i);
  2211. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  2212. }
  2213. else {
  2214. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. // If no dedicated GPUs found, fall back to GPU 0
  2220. if (vk_instance.device_indices.empty()) {
  2221. vk_instance.device_indices.push_back(0);
  2222. }
  2223. }
  2224. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  2225. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  2226. ggml_vk_print_gpu_info(i);
  2227. }
  2228. }
  2229. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  2230. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  2231. ggml_vk_instance_init();
  2232. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2233. ctx->name = GGML_VK_NAME + std::to_string(idx);
  2234. ctx->device = ggml_vk_get_device(idx);
  2235. ctx->semaphore_idx = 0;
  2236. ctx->event_idx = 0;
  2237. ctx->prealloc_size_x = 0;
  2238. ctx->prealloc_size_y = 0;
  2239. ctx->prealloc_size_split_k = 0;
  2240. ctx->fence = ctx->device->device.createFence({});
  2241. #ifdef GGML_VULKAN_CHECK_RESULTS
  2242. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  2243. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  2244. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  2245. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  2246. #endif
  2247. }
  2248. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  2249. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  2250. switch (type) {
  2251. case GGML_TYPE_F32:
  2252. case GGML_TYPE_Q4_0:
  2253. case GGML_TYPE_Q4_1:
  2254. case GGML_TYPE_Q5_0:
  2255. case GGML_TYPE_Q5_1:
  2256. case GGML_TYPE_Q8_0:
  2257. case GGML_TYPE_Q2_K:
  2258. case GGML_TYPE_Q3_K:
  2259. case GGML_TYPE_Q4_K:
  2260. case GGML_TYPE_Q5_K:
  2261. case GGML_TYPE_Q6_K:
  2262. case GGML_TYPE_IQ4_NL:
  2263. break;
  2264. default:
  2265. return nullptr;
  2266. }
  2267. return ctx->device->pipeline_dequant[type];
  2268. }
  2269. 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) {
  2270. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  2271. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2272. return ctx->device->pipeline_matmul_f32;
  2273. }
  2274. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  2275. return ctx->device->pipeline_matmul_f32_f16;
  2276. }
  2277. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16) {
  2278. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2279. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  2280. }
  2281. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2282. return ctx->device->pipeline_matmul_f16.f16acc;
  2283. }
  2284. } else {
  2285. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2286. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  2287. }
  2288. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2289. return ctx->device->pipeline_matmul_f16.f32acc;
  2290. }
  2291. }
  2292. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  2293. return nullptr;
  2294. }
  2295. switch (src0_type) {
  2296. case GGML_TYPE_Q4_0:
  2297. case GGML_TYPE_Q4_1:
  2298. case GGML_TYPE_Q5_0:
  2299. case GGML_TYPE_Q5_1:
  2300. case GGML_TYPE_Q8_0:
  2301. case GGML_TYPE_Q2_K:
  2302. case GGML_TYPE_Q3_K:
  2303. case GGML_TYPE_Q4_K:
  2304. case GGML_TYPE_Q5_K:
  2305. case GGML_TYPE_Q6_K:
  2306. case GGML_TYPE_IQ4_NL:
  2307. break;
  2308. default:
  2309. return nullptr;
  2310. }
  2311. if (ctx->device->coopmat2) {
  2312. assert(src1_type == GGML_TYPE_F16);
  2313. return ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc;
  2314. }
  2315. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  2316. }
  2317. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2318. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2319. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16);
  2320. switch (a_type) {
  2321. case GGML_TYPE_F32:
  2322. case GGML_TYPE_F16:
  2323. case GGML_TYPE_Q4_0:
  2324. case GGML_TYPE_Q4_1:
  2325. case GGML_TYPE_Q5_0:
  2326. case GGML_TYPE_Q5_1:
  2327. case GGML_TYPE_Q8_0:
  2328. case GGML_TYPE_Q2_K:
  2329. case GGML_TYPE_Q3_K:
  2330. case GGML_TYPE_Q4_K:
  2331. case GGML_TYPE_Q5_K:
  2332. case GGML_TYPE_Q6_K:
  2333. case GGML_TYPE_IQ4_NL:
  2334. break;
  2335. default:
  2336. return nullptr;
  2337. }
  2338. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[a_type] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[a_type];
  2339. }
  2340. 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) {
  2341. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  2342. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2343. return ctx->device->pipeline_matmul_id_f32;
  2344. }
  2345. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16) {
  2346. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2347. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  2348. }
  2349. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2350. return ctx->device->pipeline_matmul_id_f16.f16acc;
  2351. }
  2352. } else {
  2353. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2354. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  2355. }
  2356. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2357. return ctx->device->pipeline_matmul_id_f16.f32acc;
  2358. }
  2359. }
  2360. GGML_ASSERT(src1_type == GGML_TYPE_F32);
  2361. switch (src0_type) {
  2362. case GGML_TYPE_Q4_0:
  2363. case GGML_TYPE_Q4_1:
  2364. case GGML_TYPE_Q5_0:
  2365. case GGML_TYPE_Q5_1:
  2366. case GGML_TYPE_Q8_0:
  2367. case GGML_TYPE_Q2_K:
  2368. case GGML_TYPE_Q3_K:
  2369. case GGML_TYPE_Q4_K:
  2370. case GGML_TYPE_Q5_K:
  2371. case GGML_TYPE_Q6_K:
  2372. case GGML_TYPE_IQ4_NL:
  2373. break;
  2374. default:
  2375. return nullptr;
  2376. }
  2377. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  2378. }
  2379. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2380. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2381. GGML_ASSERT(b_type == GGML_TYPE_F32);
  2382. switch (a_type) {
  2383. case GGML_TYPE_F32:
  2384. case GGML_TYPE_F16:
  2385. case GGML_TYPE_Q4_0:
  2386. case GGML_TYPE_Q4_1:
  2387. case GGML_TYPE_Q5_0:
  2388. case GGML_TYPE_Q5_1:
  2389. case GGML_TYPE_Q8_0:
  2390. case GGML_TYPE_Q2_K:
  2391. case GGML_TYPE_Q3_K:
  2392. case GGML_TYPE_Q4_K:
  2393. case GGML_TYPE_Q5_K:
  2394. case GGML_TYPE_Q6_K:
  2395. case GGML_TYPE_IQ4_NL:
  2396. break;
  2397. default:
  2398. return nullptr;
  2399. }
  2400. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  2401. }
  2402. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  2403. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  2404. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  2405. int best_i = -1;
  2406. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  2407. int worst_i = -1;
  2408. size_t worst_size = 0; //largest unused buffer seen so far
  2409. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2410. vk_buffer &b = ctx->buffer_pool[i];
  2411. if (b != nullptr && b->size >= size && b->size < best_size) {
  2412. best_i = i;
  2413. best_size = b->size;
  2414. }
  2415. if (b != nullptr && b->size > worst_size) {
  2416. worst_i = i;
  2417. worst_size = b->size;
  2418. }
  2419. }
  2420. if(best_i != -1) {
  2421. //found the smallest buffer that fits our needs
  2422. vk_buffer b = ctx->buffer_pool[best_i];
  2423. ctx->buffer_pool[best_i].reset();
  2424. return b;
  2425. }
  2426. if(worst_i != -1) {
  2427. //no buffer that fits our needs, resize largest one to save memory
  2428. vk_buffer& b = ctx->buffer_pool[worst_i];
  2429. ggml_vk_destroy_buffer(b);
  2430. }
  2431. return ggml_vk_create_buffer_device(ctx->device, size);
  2432. }
  2433. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  2434. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  2435. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2436. vk_buffer& b = ctx->buffer_pool[i];
  2437. if (b == nullptr) {
  2438. b = buffer;
  2439. return;
  2440. }
  2441. }
  2442. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  2443. ggml_vk_destroy_buffer(buffer);
  2444. }
  2445. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  2446. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  2447. // Try to find existing temp buffer with enough capacity
  2448. for (auto& buffer : ctx->gc.temp_buffers) {
  2449. if (buffer->size >= size) {
  2450. return buffer;
  2451. }
  2452. }
  2453. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  2454. // Otherwise create new buffer
  2455. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  2456. ctx->gc.temp_buffers.push_back(buf);
  2457. return buf;
  2458. }
  2459. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  2460. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  2461. vk_buffer buf = ggml_vk_create_buffer(device, size,
  2462. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2463. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2464. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  2465. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  2466. size/1024.0/1024.0);
  2467. device->device.freeMemory(buf->device_memory);
  2468. device->device.destroyBuffer(buf->buffer);
  2469. return nullptr;
  2470. }
  2471. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  2472. return buf->ptr;
  2473. }
  2474. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  2475. if (ptr == nullptr) {
  2476. return;
  2477. }
  2478. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  2479. vk_buffer buf;
  2480. size_t index;
  2481. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2482. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2483. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2484. if (ptr >= addr && ptr < endr) {
  2485. buf = std::get<2>(device->pinned_memory[i]);
  2486. index = i;
  2487. break;
  2488. }
  2489. }
  2490. if (buf == nullptr) {
  2491. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  2492. return;
  2493. }
  2494. ggml_vk_destroy_buffer(buf);
  2495. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  2496. }
  2497. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  2498. buf = nullptr;
  2499. buf_offset = 0;
  2500. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2501. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2502. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2503. if (ptr >= addr && ptr < endr) {
  2504. buf = std::get<2>(device->pinned_memory[i]);
  2505. buf_offset = ((const uint8_t *)ptr) - addr;
  2506. break;
  2507. }
  2508. }
  2509. }
  2510. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_queue& q, bool one_time = true) {
  2511. vk_submission s;
  2512. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  2513. if (one_time) {
  2514. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  2515. } else {
  2516. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  2517. }
  2518. return s;
  2519. }
  2520. 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, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  2521. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  2522. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  2523. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  2524. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  2525. for (auto& buffer : descriptor_buffer_infos) {
  2526. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  2527. }
  2528. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  2529. GGML_ASSERT(pipeline->descriptor_set_idx < pipeline->descriptor_sets.size());
  2530. GGML_ASSERT(descriptor_buffer_infos.size() == pipeline->parameter_count);
  2531. vk::DescriptorSet& descriptor_set = pipeline->descriptor_sets[pipeline->descriptor_set_idx++];
  2532. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  2533. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  2534. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  2535. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  2536. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  2537. pipeline->layout,
  2538. 0,
  2539. { descriptor_set },
  2540. {});
  2541. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  2542. }
  2543. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  2544. s.buffer.end();
  2545. s.wait_semaphores = std::move(wait_semaphores);
  2546. s.signal_semaphores = std::move(signal_semaphores);
  2547. }
  2548. static void ggml_vk_ctx_end(vk_context& ctx) {
  2549. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  2550. if (ctx->s == nullptr) {
  2551. return;
  2552. }
  2553. ctx->s->buffer.end();
  2554. ctx->s = nullptr;
  2555. }
  2556. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  2557. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  2558. if (subctx->s != nullptr) {
  2559. ggml_vk_ctx_end(subctx);
  2560. }
  2561. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->q) });
  2562. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  2563. }
  2564. static size_t ggml_vk_align_size(size_t width, size_t align) {
  2565. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  2566. return CEIL_DIV(width, align) * align;
  2567. }
  2568. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  2569. if (memcpys == nullptr) {
  2570. memcpy(dst, src, size);
  2571. } else {
  2572. memcpys->emplace_back(dst, src, size);
  2573. }
  2574. }
  2575. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  2576. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  2577. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  2578. ggml_vk_destroy_buffer(device->sync_staging);
  2579. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  2580. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2581. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2582. }
  2583. }
  2584. 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) {
  2585. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  2586. GGML_ASSERT(!ggml_is_contiguous(tensor));
  2587. // Buffer is already mapped
  2588. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2589. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2590. GGML_ABORT("fatal error");
  2591. }
  2592. // Check if src is pinned memory
  2593. vk_buffer buf;
  2594. size_t buf_offset;
  2595. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  2596. const uint64_t ne0 = tensor->ne[0];
  2597. const uint64_t ne1 = tensor->ne[1];
  2598. const uint64_t ne2 = tensor->ne[2];
  2599. const uint64_t ne3 = tensor->ne[3];
  2600. const uint64_t nb0 = tensor->nb[0];
  2601. const uint64_t nb1 = tensor->nb[1];
  2602. const uint64_t nb2 = tensor->nb[2];
  2603. const uint64_t nb3 = tensor->nb[3];
  2604. const ggml_type type = tensor->type;
  2605. const uint64_t ts = ggml_type_size(type);
  2606. const uint64_t bs = ggml_blck_size(type);
  2607. const uint64_t dstnb0 = ts;
  2608. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  2609. const uint64_t dstnb2 = dstnb1*ne1;
  2610. const uint64_t dstnb3 = dstnb2*ne2;
  2611. const uint64_t ne = ggml_nelements(tensor);
  2612. if (buf != nullptr) {
  2613. // Memory is pinned, use as staging buffer
  2614. std::vector<vk::BufferCopy> slices;
  2615. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2616. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2617. // Find longest contiguous slice
  2618. if (ne1*nb1 == dstnb2) {
  2619. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  2620. } else {
  2621. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2622. if (ne0*nb0/bs == dstnb1) {
  2623. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  2624. } else {
  2625. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2626. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2627. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2628. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. }
  2635. ggml_vk_sync_buffers(subctx);
  2636. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2637. return;
  2638. }
  2639. if (!sync_staging) {
  2640. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2641. }
  2642. // Staging buffer required
  2643. vk_buffer& staging = ctx->device->sync_staging;
  2644. const uint64_t copy_size = ts*ne/bs;
  2645. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  2646. VkBufferCopy buf_copy{ 0, offset, copy_size };
  2647. ggml_vk_sync_buffers(subctx);
  2648. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  2649. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2650. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2651. // Find longest contiguous slice
  2652. if (ne1*nb1 == dstnb2) {
  2653. 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);
  2654. } else {
  2655. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2656. if (ne0*nb0/bs == dstnb1) {
  2657. 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);
  2658. } else {
  2659. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2660. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2661. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2662. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  2663. }
  2664. }
  2665. }
  2666. }
  2667. }
  2668. }
  2669. }
  2670. 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) {
  2671. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  2672. // Buffer is already mapped
  2673. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2674. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2675. GGML_ABORT("fatal error");
  2676. }
  2677. // Check if src is pinned memory
  2678. vk_buffer buf = nullptr;
  2679. size_t buf_offset;
  2680. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  2681. if (buf != nullptr) {
  2682. // Memory is pinned, use as staging buffer
  2683. std::vector<vk::BufferCopy> slices(1);
  2684. if (width == spitch) {
  2685. // Only do single write if stride is equal
  2686. slices[0].srcOffset = buf_offset;
  2687. slices[0].dstOffset = offset;
  2688. slices[0].size = width * height;
  2689. } else {
  2690. slices.resize(height);
  2691. for (size_t i = 0; i < height; i++) {
  2692. slices[i].srcOffset = buf_offset + i * spitch;
  2693. slices[i].dstOffset = offset + i * width;
  2694. slices[i].size = width;
  2695. }
  2696. }
  2697. ggml_vk_sync_buffers(subctx);
  2698. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2699. return;
  2700. }
  2701. VK_LOG_DEBUG("STAGING");
  2702. if (!sync_staging) {
  2703. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2704. }
  2705. // Staging buffer required
  2706. const size_t copy_size = width*height;
  2707. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  2708. vk_buffer& staging_buffer = dst->device->sync_staging;
  2709. VkBufferCopy buf_copy = {
  2710. 0,
  2711. offset,
  2712. copy_size};
  2713. ggml_vk_sync_buffers(subctx);
  2714. vkCmdCopyBuffer(subctx->s->buffer, staging_buffer->buffer, dst->buffer, 1, &buf_copy);
  2715. if (width == spitch) {
  2716. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  2717. } else {
  2718. for (size_t i = 0; i < height; i++) {
  2719. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  2720. }
  2721. }
  2722. }
  2723. 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) {
  2724. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  2725. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  2726. }
  2727. 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) {
  2728. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  2729. // Buffer is already mapped
  2730. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2731. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2732. for (size_t i = 0; i < height; i++) {
  2733. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  2734. }
  2735. } else {
  2736. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2737. ggml_vk_ctx_begin(dst->device, subctx);
  2738. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  2739. ggml_vk_ctx_end(subctx);
  2740. for (auto& cpy : subctx->in_memcpys) {
  2741. memcpy(cpy.dst, cpy.src, cpy.n);
  2742. }
  2743. ggml_vk_submit(subctx, dst->device->fence);
  2744. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  2745. dst->device->device.resetFences({ dst->device->fence });
  2746. }
  2747. }
  2748. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  2749. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  2750. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  2751. }
  2752. 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) {
  2753. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  2754. GGML_ASSERT(width > 0);
  2755. GGML_ASSERT(height > 0);
  2756. GGML_ASSERT(src != nullptr);
  2757. // TODO: staging_offset is not used
  2758. // Check if dst is pinned memory
  2759. vk_buffer buf = nullptr;
  2760. size_t buf_offset;
  2761. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  2762. std::vector<vk::BufferCopy> slices(1);
  2763. if (width == spitch && width == dpitch) {
  2764. // Only do single write if stride is equal
  2765. slices[0].srcOffset = offset;
  2766. slices[0].dstOffset = buf_offset;
  2767. slices[0].size = width * height;
  2768. } else {
  2769. slices.resize(height);
  2770. for (size_t i = 0; i < height; i++) {
  2771. slices[i].srcOffset = offset + i * spitch;
  2772. slices[i].dstOffset = buf_offset + i * dpitch;
  2773. slices[i].size = width;
  2774. }
  2775. }
  2776. if (buf != nullptr) {
  2777. // Memory is pinned, use as staging buffer
  2778. ggml_vk_sync_buffers(subctx);
  2779. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  2780. return;
  2781. }
  2782. VK_LOG_DEBUG("STAGING");
  2783. if (!sync_staging) {
  2784. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  2785. }
  2786. // Fall back to staging buffer
  2787. const size_t copy_size = dpitch * height;
  2788. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  2789. vk_buffer& staging_buffer = src->device->sync_staging;
  2790. ggml_vk_sync_buffers(subctx);
  2791. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  2792. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  2793. }
  2794. 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) {
  2795. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  2796. }
  2797. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  2798. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  2799. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  2800. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  2801. // the HW device to host copy path.
  2802. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  2803. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2804. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  2805. } else {
  2806. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2807. ggml_vk_ctx_begin(src->device, subctx);
  2808. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  2809. ggml_vk_ctx_end(subctx);
  2810. ggml_vk_submit(subctx, src->device->fence);
  2811. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  2812. src->device->device.resetFences({ src->device->fence });
  2813. for (auto& cpy : subctx->out_memcpys) {
  2814. memcpy(cpy.dst, cpy.src, cpy.n);
  2815. }
  2816. }
  2817. }
  2818. 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) {
  2819. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  2820. // Make sure both buffers are on same device
  2821. GGML_ASSERT(src->device == dst->device);
  2822. VkBufferCopy bc{ src_offset, dst_offset, size };
  2823. vkCmdCopyBuffer(ctx->s->buffer, src->buffer, dst->buffer, 1, &bc);
  2824. }
  2825. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  2826. if (src->device == dst->device) {
  2827. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  2828. // Copy within the device
  2829. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2830. ggml_vk_ctx_begin(src->device, subctx);
  2831. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  2832. ggml_vk_ctx_end(subctx);
  2833. ggml_vk_submit(subctx, src->device->fence);
  2834. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  2835. src->device->device.resetFences({ src->device->fence });
  2836. } else {
  2837. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  2838. // Copy device to device
  2839. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  2840. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  2841. // Copy to src staging buffer
  2842. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  2843. // memcpy to dst staging buffer
  2844. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  2845. // Copy to dst buffer
  2846. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  2847. }
  2848. }
  2849. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  2850. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  2851. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2852. ggml_vk_ctx_begin(dst->device, subctx);
  2853. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  2854. ggml_vk_ctx_end(subctx);
  2855. ggml_vk_submit(subctx, dst->device->fence);
  2856. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  2857. dst->device->device.resetFences({ dst->device->fence });
  2858. }
  2859. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, int m, int n, int k, const vk_pipeline& pipeline) {
  2860. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  2861. uint32_t split_k = 1;
  2862. if (ctx->device->shader_core_count != 0 && m >= (int)pipeline->wg_denoms[0] && n >= (int)pipeline->wg_denoms[1]) {
  2863. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  2864. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  2865. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  2866. if (k >= 2048 && m_tiles * n_tiles < ctx->device->shader_core_count / 2) {
  2867. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  2868. // Clamp to 2 or 4
  2869. split_k = std::min(split_k, 4u);
  2870. if (split_k == 3) {
  2871. split_k = 2;
  2872. }
  2873. }
  2874. }
  2875. return split_k;
  2876. }
  2877. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  2878. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  2879. if (ctx->device->coopmat2) {
  2880. if ((ctx->device->mul_mat_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_s)) {
  2881. return aligned ? mmp->a_l : mmp->l;
  2882. }
  2883. if ((ctx->device->mul_mat_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_s) {
  2884. return aligned ? mmp->a_m : mmp->m;
  2885. }
  2886. return aligned ? mmp->a_s : mmp->s;
  2887. }
  2888. if ((ctx->device->mul_mat_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_l)) {
  2889. return aligned ? mmp->a_s : mmp->s;
  2890. }
  2891. if ((ctx->device->mul_mat_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l) {
  2892. return aligned ? mmp->a_m : mmp->m;
  2893. }
  2894. return aligned ? mmp->a_l : mmp->l;
  2895. }
  2896. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  2897. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  2898. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true)->align;
  2899. }
  2900. static void ggml_vk_matmul(
  2901. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  2902. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  2903. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  2904. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  2905. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3) {
  2906. 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 << ")");
  2907. ggml_vk_sync_buffers(subctx);
  2908. if (split_k == 1) {
  2909. 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 };
  2910. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, sizeof(vk_mat_mat_push_constants), &pc, { m, n, batch });
  2911. return;
  2912. }
  2913. GGML_ASSERT(batch_stride_d == m * n);
  2914. 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, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3 };
  2915. // Make sure enough workgroups get assigned for split k to work
  2916. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, sizeof(vk_mat_mat_push_constants), &pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  2917. ggml_vk_sync_buffers(subctx);
  2918. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  2919. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2.size() * sizeof(uint32_t), pc2.data(), { m * n * batch, 1, 1 });
  2920. }
  2921. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  2922. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  2923. if (ctx->device->coopmat2) {
  2924. if ((ctx->device->mul_mat_id_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_s)) {
  2925. return aligned ? mmp->a_l : mmp->l;
  2926. }
  2927. if ((ctx->device->mul_mat_id_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_id_s) {
  2928. return aligned ? mmp->a_m : mmp->m;
  2929. }
  2930. return aligned ? mmp->a_s : mmp->s;
  2931. }
  2932. if ((ctx->device->mul_mat_id_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_l)) {
  2933. return aligned ? mmp->a_s : mmp->s;
  2934. }
  2935. if ((ctx->device->mul_mat_id_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l) {
  2936. return aligned ? mmp->a_m : mmp->m;
  2937. }
  2938. return aligned ? mmp->a_l : mmp->l;
  2939. }
  2940. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  2941. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  2942. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true)->align;
  2943. }
  2944. static void ggml_vk_matmul_id(
  2945. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  2946. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  2947. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  2948. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  2949. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11) {
  2950. 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 << "), " <<
  2951. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  2952. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  2953. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  2954. ggml_vk_sync_buffers(subctx);
  2955. 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,
  2956. nei0, nei1, nbi1, ne11 };
  2957. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, sizeof(vk_mat_mat_id_push_constants), &pc, { m, nei1, n_as });
  2958. }
  2959. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  2960. return
  2961. tensor->nb[0] == ggml_type_size(tensor->type) &&
  2962. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  2963. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  2964. }
  2965. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  2966. // Choose "contiguous copy" shader if src/dst are contiguous
  2967. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  2968. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  2969. if (contig) {
  2970. return ctx->device->pipeline_contig_cpy_f32_f32;
  2971. } else {
  2972. return ctx->device->pipeline_cpy_f32_f32;
  2973. }
  2974. }
  2975. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  2976. if (contig) {
  2977. return ctx->device->pipeline_contig_cpy_f32_f16;
  2978. } else {
  2979. return ctx->device->pipeline_cpy_f32_f16;
  2980. }
  2981. }
  2982. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  2983. if (contig) {
  2984. return ctx->device->pipeline_contig_cpy_f16_f16;
  2985. } else {
  2986. return ctx->device->pipeline_cpy_f16_f16;
  2987. }
  2988. }
  2989. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  2990. GGML_ABORT("fatal error");
  2991. }
  2992. 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) {
  2993. 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] << "), ";
  2994. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  2995. const int tensor_type_size = ggml_type_size(tensor->type);
  2996. const uint32_t ne = ggml_nelements(tensor);
  2997. std::array<uint32_t, 3> elements;
  2998. if (ne > 262144) {
  2999. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  3000. } else if (ne > 512) {
  3001. elements = { 512, CEIL_DIV(ne, 512), 1 };
  3002. } else {
  3003. elements = { ne, 1, 1 };
  3004. }
  3005. vk_op_unary_push_constants pc = {
  3006. (uint32_t)ne,
  3007. (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,
  3008. (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]),
  3009. 0,
  3010. 0.0f, 0.0f,
  3011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3012. };
  3013. init_pushconst_fastdiv(pc);
  3014. ggml_vk_sync_buffers(subctx);
  3015. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, sizeof(vk_op_unary_push_constants), &pc, elements);
  3016. }
  3017. 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 dryrun = false) {
  3018. VK_LOG_DEBUG("ggml_vk_mul_mat_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];
  3019. 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];
  3020. 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];
  3021. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3022. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3023. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3024. const uint64_t ne00 = src0->ne[0];
  3025. const uint64_t ne01 = src0->ne[1];
  3026. const uint64_t ne02 = src0->ne[2];
  3027. const uint64_t ne03 = src0->ne[3];
  3028. const uint64_t ne10 = src1->ne[0];
  3029. const uint64_t ne11 = src1->ne[1];
  3030. const uint64_t ne12 = src1->ne[2];
  3031. const uint64_t ne13 = src1->ne[3];
  3032. const uint64_t ne20 = dst->ne[0];
  3033. const uint64_t ne21 = dst->ne[1];
  3034. const uint64_t r2 = ne12 / ne02;
  3035. const uint64_t r3 = ne13 / ne03;
  3036. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3037. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3038. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3039. vk_buffer d_Qx;
  3040. size_t qx_buf_offset = 0;
  3041. vk_buffer d_Qy;
  3042. size_t qy_buf_offset = 0;
  3043. bool src0_uma = false;
  3044. bool src1_uma = false;
  3045. if (ctx->device->uma) {
  3046. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3047. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3048. src0_uma = d_Qx != nullptr;
  3049. src1_uma = d_Qy != nullptr;
  3050. }
  3051. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3052. // Reformat and convert to fp16 if src1 is non-contiguous, or for coopmat2 for better perf
  3053. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3054. !ggml_vk_dim01_contiguous(src1);
  3055. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3056. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3057. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3058. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3059. if (qx_needs_dequant) {
  3060. // Fall back to dequant + f16 mulmat
  3061. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3062. }
  3063. // Not implemented
  3064. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3065. const int x_ne = ne01 * ne00;
  3066. const int y_ne = ne11 * ne10;
  3067. const int d_ne = ne11 * ne01;
  3068. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11));
  3069. const bool aligned = ne10 == kpad && ne01 > 8 && ne11 > 8;
  3070. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned);
  3071. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  3072. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3073. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3074. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3075. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3076. const uint64_t d_sz = sizeof(float) * d_ne;
  3077. vk_pipeline to_fp16_vk_0 = nullptr;
  3078. vk_pipeline to_fp16_vk_1 = nullptr;
  3079. if (x_non_contig) {
  3080. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3081. } else {
  3082. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3083. }
  3084. if (y_non_contig) {
  3085. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3086. } else {
  3087. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3088. }
  3089. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3090. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3091. if (dryrun) {
  3092. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3093. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3094. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  3095. if (
  3096. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3097. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  3098. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  3099. GGML_ABORT("Requested preallocation size is too large");
  3100. }
  3101. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3102. ctx->prealloc_size_x = x_sz_upd;
  3103. }
  3104. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3105. ctx->prealloc_size_y = y_sz_upd;
  3106. }
  3107. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  3108. ctx->prealloc_size_split_k = split_k_size;
  3109. }
  3110. // Request descriptor sets
  3111. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3112. if (qx_needs_dequant) {
  3113. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3114. }
  3115. if (qy_needs_dequant) {
  3116. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3117. }
  3118. if (split_k > 1) {
  3119. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, 1);
  3120. }
  3121. return;
  3122. }
  3123. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3124. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3125. GGML_ASSERT(d_D != nullptr);
  3126. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  3127. vk_buffer d_X;
  3128. uint64_t x_buf_offset = 0;
  3129. vk_buffer d_Y;
  3130. uint64_t y_buf_offset = 0;
  3131. if (!src0_uma) {
  3132. d_Qx = src0_buf_ctx->dev_buffer;
  3133. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3134. GGML_ASSERT(d_Qx != nullptr);
  3135. }
  3136. if (!src1_uma) {
  3137. d_Qy = src1_buf_ctx->dev_buffer;
  3138. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3139. GGML_ASSERT(d_Qy != nullptr);
  3140. }
  3141. if (qx_needs_dequant) {
  3142. d_X = ctx->prealloc_x;
  3143. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3144. } else {
  3145. d_X = d_Qx;
  3146. x_buf_offset = qx_buf_offset;
  3147. GGML_ASSERT(qx_sz == x_sz);
  3148. }
  3149. if (qy_needs_dequant) {
  3150. d_Y = ctx->prealloc_y;
  3151. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3152. } else {
  3153. d_Y = d_Qy;
  3154. y_buf_offset = qy_buf_offset;
  3155. GGML_ASSERT(qy_sz == y_sz);
  3156. }
  3157. if (x_non_contig) {
  3158. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3159. } else if (qx_needs_dequant) {
  3160. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3161. ggml_vk_sync_buffers(subctx);
  3162. 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.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3163. }
  3164. if (y_non_contig) {
  3165. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3166. }
  3167. uint32_t stride_batch_x = ne00*ne01;
  3168. uint32_t stride_batch_y = ne10*ne11;
  3169. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3170. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3171. }
  3172. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3173. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3174. }
  3175. // compute
  3176. ggml_vk_matmul(
  3177. ctx, subctx, pipeline,
  3178. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3179. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  3180. ne01, ne11, ne10,
  3181. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  3182. split_k, ne12*ne13, ne02, ne12, r2, r3
  3183. ); // NOLINT
  3184. }
  3185. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3186. 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];
  3187. 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];
  3188. 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];
  3189. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  3190. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3191. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3192. const uint64_t ne00 = src0->ne[0];
  3193. const uint64_t ne01 = src0->ne[1];
  3194. const uint64_t ne02 = src0->ne[2];
  3195. const uint64_t ne03 = src0->ne[3];
  3196. const uint64_t ne10 = src1->ne[0];
  3197. const uint64_t ne11 = src1->ne[1];
  3198. const uint64_t ne12 = src1->ne[2];
  3199. const uint64_t ne13 = src1->ne[3];
  3200. GGML_ASSERT(ne11 == 1);
  3201. const uint64_t ne20 = dst->ne[0];
  3202. const uint64_t ne21 = dst->ne[1];
  3203. const uint64_t ne22 = dst->ne[2];
  3204. const uint64_t ne23 = dst->ne[3];
  3205. const uint64_t r2 = ne12 / ne02;
  3206. const uint64_t r3 = ne13 / ne03;
  3207. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3208. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3209. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3210. vk_buffer d_Qx;
  3211. size_t qx_buf_offset = 0;
  3212. vk_buffer d_Qy;
  3213. size_t qy_buf_offset = 0;
  3214. bool src0_uma = false;
  3215. bool src1_uma = false;
  3216. if (ctx->device->uma) {
  3217. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3218. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3219. src0_uma = d_Qx != nullptr;
  3220. src1_uma = d_Qy != nullptr;
  3221. }
  3222. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3223. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3224. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3225. const bool qx_needs_dequant = x_non_contig;
  3226. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3227. // Not implemented
  3228. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3229. const uint64_t x_ne = ne01 * ne00;
  3230. const uint64_t y_ne = ne11 * ne10;
  3231. const uint64_t d_ne = ne11 * ne01;
  3232. 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);
  3233. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3234. 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;
  3235. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3236. const uint64_t d_sz = sizeof(float) * d_ne;
  3237. vk_pipeline to_fp16_vk_0 = nullptr;
  3238. vk_pipeline to_fp16_vk_1 = nullptr;
  3239. if (x_non_contig) {
  3240. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3241. }
  3242. if (y_non_contig) {
  3243. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3244. } else {
  3245. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3246. }
  3247. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type);
  3248. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3249. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3250. GGML_ASSERT(dmmv != nullptr);
  3251. if (dryrun) {
  3252. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3253. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3254. if (
  3255. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3256. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3257. GGML_ABORT("Requested preallocation size is too large");
  3258. }
  3259. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3260. ctx->prealloc_size_x = x_sz_upd;
  3261. }
  3262. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3263. ctx->prealloc_size_y = y_sz_upd;
  3264. }
  3265. // Request descriptor sets
  3266. if (qx_needs_dequant) {
  3267. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3268. }
  3269. if (qy_needs_dequant) {
  3270. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3271. }
  3272. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3273. return;
  3274. }
  3275. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3276. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3277. GGML_ASSERT(d_D != nullptr);
  3278. vk_buffer d_X;
  3279. uint64_t x_buf_offset = 0;
  3280. vk_buffer d_Y;
  3281. uint64_t y_buf_offset = 0;
  3282. if(!src0_uma) {
  3283. d_Qx = src0_buf_ctx->dev_buffer;
  3284. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3285. GGML_ASSERT(d_Qx != nullptr);
  3286. }
  3287. if(!src1_uma) {
  3288. d_Qy = src1_buf_ctx->dev_buffer;
  3289. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3290. GGML_ASSERT(d_Qy != nullptr);
  3291. }
  3292. if (qx_needs_dequant) {
  3293. d_X = ctx->prealloc_x;
  3294. } else {
  3295. d_X = d_Qx;
  3296. x_buf_offset = qx_buf_offset;
  3297. GGML_ASSERT(qx_sz == x_sz);
  3298. }
  3299. if (qy_needs_dequant) {
  3300. d_Y = ctx->prealloc_y;
  3301. } else {
  3302. d_Y = d_Qy;
  3303. y_buf_offset = qy_buf_offset;
  3304. GGML_ASSERT(qy_sz == y_sz);
  3305. }
  3306. if (x_non_contig) {
  3307. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3308. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3309. }
  3310. if (y_non_contig) {
  3311. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3312. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3313. }
  3314. uint32_t stride_batch_x = ne00*ne01;
  3315. uint32_t stride_batch_y = ne10*ne11;
  3316. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3317. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3318. }
  3319. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3320. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3321. }
  3322. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3323. uint32_t groups_x = ne01;
  3324. uint32_t groups_z = 1;
  3325. if (ne01 > max_groups_x) {
  3326. groups_z = 64;
  3327. groups_x = CEIL_DIV(groups_x, groups_z);
  3328. }
  3329. // compute
  3330. const vk_mat_vec_push_constants pc = {
  3331. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3332. stride_batch_x, stride_batch_y, (uint32_t)(ne20*ne21),
  3333. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  3334. };
  3335. ggml_vk_sync_buffers(subctx);
  3336. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3337. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  3338. sizeof(vk_mat_vec_push_constants), &pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  3339. }
  3340. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3341. 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];
  3342. 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];
  3343. 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];
  3344. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3345. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  3346. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  3347. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  3348. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3349. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3350. const uint64_t ne00 = src0->ne[0];
  3351. const uint64_t ne01 = src0->ne[1];
  3352. const uint64_t ne02 = src0->ne[2];
  3353. // const uint64_t ne03 = src0->ne[3];
  3354. const uint64_t ne10 = src1->ne[0];
  3355. const uint64_t ne11 = src1->ne[1];
  3356. const uint64_t ne12 = src1->ne[2];
  3357. // const uint64_t ne13 = src1->ne[3];
  3358. GGML_ASSERT(ne11 == 1);
  3359. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3360. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3361. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3362. vk_buffer d_Qy;
  3363. size_t qy_buf_offset = 0;
  3364. bool src1_uma = false;
  3365. if (ctx->device->uma) {
  3366. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3367. src1_uma = d_Qy != nullptr;
  3368. }
  3369. const uint64_t x_ne = ne00 * ne01 * ne02;
  3370. const uint64_t y_ne = ne10 * ne11 * ne12;
  3371. const uint64_t d_ne = ne01 * ne11 * ne12;
  3372. 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);
  3373. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3374. const uint64_t d_sz = sizeof(float) * d_ne;
  3375. if (dryrun) {
  3376. // Request descriptor sets
  3377. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, 1);
  3378. return;
  3379. }
  3380. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3381. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3382. GGML_ASSERT(d_D != nullptr);
  3383. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3384. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3385. GGML_ASSERT(d_Qx != nullptr);
  3386. if (!src1_uma) {
  3387. d_Qy = src1_buf_ctx->dev_buffer;
  3388. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3389. GGML_ASSERT(d_Qx != nullptr);
  3390. }
  3391. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3392. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3393. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3394. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3395. // compute
  3396. const std::array<uint32_t, 6> 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)) };
  3397. ggml_vk_sync_buffers(subctx);
  3398. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3399. }
  3400. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3401. 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];
  3402. 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];
  3403. 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];
  3404. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3405. GGML_ASSERT(!ggml_is_transposed(src0));
  3406. GGML_ASSERT(!ggml_is_transposed(src1));
  3407. GGML_ASSERT(!ggml_is_permuted(src0));
  3408. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3409. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3410. const uint64_t ne00 = src0->ne[0];
  3411. const uint64_t ne01 = src0->ne[1];
  3412. const uint64_t ne02 = src0->ne[2];
  3413. // const uint64_t ne03 = src0->ne[3];
  3414. const uint64_t nb01 = src0->nb[1];
  3415. const uint64_t nb02 = src0->nb[2];
  3416. // const uint64_t ne10 = src1->ne[0];
  3417. const uint64_t ne11 = src1->ne[1];
  3418. const uint64_t ne12 = src1->ne[2];
  3419. // const uint64_t ne13 = src1->ne[3];
  3420. GGML_ASSERT(ne11 == 1);
  3421. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3422. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3423. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3424. vk_buffer d_Qy = nullptr;
  3425. size_t qy_buf_offset = 0;
  3426. bool src1_uma = false;
  3427. if (ctx->device->uma) {
  3428. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3429. src1_uma = d_Qy != nullptr;
  3430. }
  3431. const uint64_t d_ne = ne01 * ne11 * ne12;
  3432. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  3433. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  3434. const uint64_t qx_sz = ggml_nbytes(src0);
  3435. const uint64_t qy_sz = ggml_nbytes(src1);
  3436. const uint64_t d_sz = sizeof(float) * d_ne;
  3437. if (dryrun) {
  3438. // Request descriptor sets
  3439. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  3440. return;
  3441. }
  3442. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3443. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3444. GGML_ASSERT(d_D != nullptr);
  3445. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3446. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3447. GGML_ASSERT(d_Qx != nullptr);
  3448. if (!src1_uma) {
  3449. d_Qy = src1_buf_ctx->dev_buffer;
  3450. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3451. GGML_ASSERT(d_Qx != nullptr);
  3452. }
  3453. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3454. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3455. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3456. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3457. // compute
  3458. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, (uint32_t)(ne12 / ne02), (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  3459. ggml_vk_sync_buffers(subctx);
  3460. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  3461. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3462. }
  3463. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3464. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  3465. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  3466. // detect 0213 permutation, and batch size of 1
  3467. src0->nb[0] <= src0->nb[2] &&
  3468. src0->nb[2] <= src0->nb[1] &&
  3469. src0->nb[1] <= src0->nb[3] &&
  3470. src1->nb[0] <= src1->nb[2] &&
  3471. src1->nb[2] <= src1->nb[1] &&
  3472. src1->nb[1] <= src1->nb[3] &&
  3473. src0->ne[3] == 1 &&
  3474. src1->ne[3] == 1) {
  3475. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3476. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  3477. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  3478. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3479. } else if (dst->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3480. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3481. } else {
  3482. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3483. }
  3484. }
  3485. 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, bool dryrun = false) {
  3486. 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];
  3487. 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];
  3488. 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];
  3489. 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] << "),)");
  3490. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3491. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3492. const uint64_t ne00 = src0->ne[0];
  3493. const uint64_t ne01 = src0->ne[1];
  3494. const uint64_t ne02 = src0->ne[2];
  3495. const uint64_t ne03 = src0->ne[3];
  3496. const uint64_t ne10 = src1->ne[0];
  3497. const uint64_t ne11 = src1->ne[1];
  3498. const uint64_t ne12 = src1->ne[2];
  3499. const uint64_t ne13 = src1->ne[3];
  3500. const uint64_t nei0 = ids->ne[0];
  3501. const uint64_t nei1 = ids->ne[1];
  3502. GGML_ASSERT(nei0 * nei1 <= 3072);
  3503. const uint32_t nbi1 = ids->nb[1];
  3504. const uint32_t nbi2 = ids->nb[2];
  3505. const uint64_t ne20 = dst->ne[0];
  3506. const uint64_t ne21 = dst->ne[1];
  3507. const uint64_t ne22 = dst->ne[2];
  3508. const uint64_t ne23 = dst->ne[3];
  3509. const uint64_t n_as = ne02;
  3510. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3511. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3512. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3513. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3514. vk_buffer d_Qx;
  3515. size_t qx_buf_offset = 0;
  3516. vk_buffer d_Qy;
  3517. size_t qy_buf_offset = 0;
  3518. vk_buffer d_ids;
  3519. size_t ids_buf_offset = 0;
  3520. bool src0_uma = false;
  3521. bool src1_uma = false;
  3522. bool ids_uma = false;
  3523. if (ctx->device->uma) {
  3524. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3525. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3526. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3527. src0_uma = d_Qx != nullptr;
  3528. src1_uma = d_Qy != nullptr;
  3529. ids_uma = d_ids != nullptr;
  3530. }
  3531. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3532. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3533. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3534. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3535. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3536. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3537. if (qx_needs_dequant) {
  3538. GGML_ABORT("fatal error");
  3539. }
  3540. // Not implemented
  3541. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3542. const uint64_t x_ne = ne01 * ne00;
  3543. const uint64_t y_ne = ne11 * ne10;
  3544. const uint64_t d_ne = ne21 * ne20;
  3545. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1));
  3546. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  3547. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned);
  3548. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3549. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3550. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3551. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3552. const uint64_t ids_sz = nbi2;
  3553. const uint64_t d_sz = sizeof(float) * d_ne;
  3554. vk_pipeline to_fp16_vk_0 = nullptr;
  3555. vk_pipeline to_fp16_vk_1 = nullptr;
  3556. if (x_non_contig) {
  3557. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3558. } else {
  3559. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3560. }
  3561. if (y_non_contig) {
  3562. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3563. } else {
  3564. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3565. }
  3566. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3567. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3568. if (dryrun) {
  3569. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3570. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3571. if (
  3572. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3573. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3574. GGML_ABORT("Requested preallocation size is too large");
  3575. }
  3576. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3577. ctx->prealloc_size_x = x_sz_upd;
  3578. }
  3579. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3580. ctx->prealloc_size_y = y_sz_upd;
  3581. }
  3582. // Request descriptor sets
  3583. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3584. if (qx_needs_dequant) {
  3585. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3586. }
  3587. if (qy_needs_dequant) {
  3588. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3589. }
  3590. return;
  3591. }
  3592. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3593. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3594. GGML_ASSERT(d_D != nullptr);
  3595. vk_buffer d_X;
  3596. uint64_t x_buf_offset = 0;
  3597. vk_buffer d_Y;
  3598. uint64_t y_buf_offset = 0;
  3599. if (!src0_uma) {
  3600. d_Qx = src0_buf_ctx->dev_buffer;
  3601. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3602. GGML_ASSERT(d_Qx != nullptr);
  3603. }
  3604. if (!src1_uma) {
  3605. d_Qy = src1_buf_ctx->dev_buffer;
  3606. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3607. GGML_ASSERT(d_Qy != nullptr);
  3608. }
  3609. if (!ids_uma) {
  3610. d_ids = ids_buf_ctx->dev_buffer;
  3611. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3612. GGML_ASSERT(d_ids != nullptr);
  3613. }
  3614. if (qx_needs_dequant) {
  3615. d_X = ctx->prealloc_x;
  3616. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3617. } else {
  3618. d_X = d_Qx;
  3619. x_buf_offset = qx_buf_offset;
  3620. GGML_ASSERT(qx_sz == x_sz);
  3621. }
  3622. if (qy_needs_dequant) {
  3623. d_Y = ctx->prealloc_y;
  3624. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3625. } else {
  3626. d_Y = d_Qy;
  3627. y_buf_offset = qy_buf_offset;
  3628. GGML_ASSERT(qy_sz == y_sz);
  3629. }
  3630. if (x_non_contig) {
  3631. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3632. } else if (qx_needs_dequant) {
  3633. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3634. ggml_vk_sync_buffers(subctx);
  3635. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  3636. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3637. }
  3638. if (y_non_contig) {
  3639. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3640. }
  3641. uint32_t stride_batch_x = ne00*ne01;
  3642. uint32_t stride_batch_y = ne10*ne11;
  3643. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3644. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3645. }
  3646. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3647. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3648. }
  3649. // compute
  3650. ggml_vk_matmul_id(
  3651. ctx, subctx, pipeline,
  3652. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3653. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  3654. ne01, ne21, ne10, ne10, ne10, ne01,
  3655. stride_batch_x, stride_batch_y, ne20*ne21,
  3656. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11
  3657. ); // NOLINT
  3658. }
  3659. static void ggml_vk_mul_mat_vec_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, bool dryrun = false) {
  3660. 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];
  3661. 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];
  3662. 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];
  3663. 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];
  3664. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3665. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3666. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3667. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3668. const uint64_t ne00 = src0->ne[0];
  3669. const uint64_t ne01 = src0->ne[1];
  3670. const uint64_t ne02 = src0->ne[2];
  3671. const uint64_t ne03 = src0->ne[3];
  3672. const uint64_t ne10 = src1->ne[0];
  3673. const uint64_t ne11 = src1->ne[1];
  3674. const uint64_t ne12 = src1->ne[2];
  3675. const uint64_t ne13 = src1->ne[3];
  3676. const uint64_t nei0 = ids->ne[0];
  3677. const uint64_t nei1 = ids->ne[1];
  3678. const uint64_t nbi2 = ids->nb[2];
  3679. GGML_ASSERT(nei1 == 1);
  3680. const uint64_t ne20 = dst->ne[0];
  3681. const uint64_t ne21 = dst->ne[1];
  3682. const uint64_t ne22 = dst->ne[2];
  3683. const uint64_t ne23 = dst->ne[3];
  3684. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3685. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3686. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3687. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3688. vk_buffer d_Qx;
  3689. size_t qx_buf_offset = 0;
  3690. vk_buffer d_Qy;
  3691. size_t qy_buf_offset = 0;
  3692. vk_buffer d_ids;
  3693. size_t ids_buf_offset = 0;
  3694. bool src0_uma = false;
  3695. bool src1_uma = false;
  3696. bool ids_uma = false;
  3697. if (ctx->device->uma) {
  3698. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3699. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3700. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3701. src0_uma = d_Qx != nullptr;
  3702. src1_uma = d_Qy != nullptr;
  3703. ids_uma = d_ids != nullptr;
  3704. }
  3705. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3706. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3707. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3708. const bool qx_needs_dequant = x_non_contig;
  3709. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3710. // Not implemented
  3711. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3712. const uint64_t x_ne = ne01 * ne00;
  3713. const uint64_t y_ne = ne11 * ne10;
  3714. const uint64_t d_ne = ne21 * ne20;
  3715. 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);
  3716. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3717. 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;
  3718. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3719. const uint64_t ids_sz = nbi2;
  3720. const uint64_t d_sz = sizeof(float) * d_ne;
  3721. vk_pipeline to_fp16_vk_0 = nullptr;
  3722. vk_pipeline to_fp16_vk_1 = nullptr;
  3723. if (x_non_contig) {
  3724. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3725. }
  3726. if (y_non_contig) {
  3727. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3728. } else {
  3729. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3730. }
  3731. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  3732. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3733. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3734. GGML_ASSERT(dmmv != nullptr);
  3735. if (dryrun) {
  3736. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3737. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3738. if (
  3739. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3740. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3741. GGML_ABORT("Requested preallocation size is too large");
  3742. }
  3743. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3744. ctx->prealloc_size_x = x_sz_upd;
  3745. }
  3746. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3747. ctx->prealloc_size_y = y_sz_upd;
  3748. }
  3749. // Request descriptor sets
  3750. if (qx_needs_dequant) {
  3751. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3752. }
  3753. if (qy_needs_dequant) {
  3754. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3755. }
  3756. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3757. return;
  3758. }
  3759. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3760. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3761. GGML_ASSERT(d_D != nullptr);
  3762. vk_buffer d_X;
  3763. uint64_t x_buf_offset = 0;
  3764. vk_buffer d_Y;
  3765. uint64_t y_buf_offset = 0;
  3766. if(!src0_uma) {
  3767. d_Qx = src0_buf_ctx->dev_buffer;
  3768. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3769. GGML_ASSERT(d_Qx != nullptr);
  3770. }
  3771. if(!src1_uma) {
  3772. d_Qy = src1_buf_ctx->dev_buffer;
  3773. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3774. GGML_ASSERT(d_Qy != nullptr);
  3775. }
  3776. if(!ids_uma) {
  3777. d_ids = ids_buf_ctx->dev_buffer;
  3778. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3779. GGML_ASSERT(d_ids != nullptr);
  3780. }
  3781. if (qx_needs_dequant) {
  3782. d_X = ctx->prealloc_x;
  3783. } else {
  3784. d_X = d_Qx;
  3785. x_buf_offset = qx_buf_offset;
  3786. GGML_ASSERT(qx_sz == x_sz);
  3787. }
  3788. if (qy_needs_dequant) {
  3789. d_Y = ctx->prealloc_y;
  3790. } else {
  3791. d_Y = d_Qy;
  3792. y_buf_offset = qy_buf_offset;
  3793. GGML_ASSERT(qy_sz == y_sz);
  3794. }
  3795. if (x_non_contig) {
  3796. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3797. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3798. }
  3799. if (y_non_contig) {
  3800. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3801. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3802. }
  3803. uint32_t stride_batch_y = ne10*ne11;
  3804. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3805. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3806. }
  3807. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3808. uint32_t groups_x = ne01;
  3809. uint32_t groups_z = 1;
  3810. if (ne01 > max_groups_x) {
  3811. groups_z = 64;
  3812. groups_x = CEIL_DIV(groups_x, groups_z);
  3813. }
  3814. // compute
  3815. const vk_mat_vec_id_push_constants pc = {
  3816. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3817. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  3818. (uint32_t)nei0, (uint32_t)ne11,
  3819. };
  3820. ggml_vk_sync_buffers(subctx);
  3821. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3822. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  3823. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23}, vk_subbuffer{ d_ids, ids_buf_offset, ids_sz } },
  3824. sizeof(vk_mat_vec_id_push_constants), &pc, { groups_x, (uint32_t)nei0, groups_z });
  3825. }
  3826. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  3827. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  3828. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3829. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  3830. } else {
  3831. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  3832. }
  3833. }
  3834. 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, ggml_tensor * dst, bool dryrun = false) {
  3835. 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];
  3836. 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];
  3837. 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];
  3838. 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];
  3839. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3840. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  3841. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  3842. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  3843. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  3844. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  3845. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  3846. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  3847. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  3848. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  3849. const uint32_t nbm1 = mask ? mask->nb[1] : 0;
  3850. const uint32_t D = neq0;
  3851. const uint32_t N = neq1;
  3852. const uint32_t KV = nek1;
  3853. GGML_ASSERT(ne0 == D);
  3854. GGML_ASSERT(ne2 == N);
  3855. // input tensor rows must be contiguous
  3856. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  3857. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  3858. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  3859. GGML_ASSERT(neq0 == D);
  3860. GGML_ASSERT(nek0 == D);
  3861. GGML_ASSERT(nev0 == D);
  3862. GGML_ASSERT(neq1 == N);
  3863. GGML_ASSERT(nev0 == D);
  3864. GGML_ASSERT(nev1 == nek1);
  3865. // dst cannot be transposed or permuted
  3866. GGML_ASSERT(nb0 == sizeof(float));
  3867. GGML_ASSERT(nb0 <= nb1);
  3868. GGML_ASSERT(nb1 <= nb2);
  3869. GGML_ASSERT(nb2 <= nb3);
  3870. assert(dst->type == GGML_TYPE_F32);
  3871. assert(q->type == GGML_TYPE_F32);
  3872. assert(k->type == v->type);
  3873. vk_pipeline *pipelines;
  3874. // XXX TODO other backends may be changing accumulator precision to default to f32 soon
  3875. bool f32acc = dst->op_params[3] == GGML_PREC_F32;
  3876. bool small_rows = N <= flash_attention_num_small_rows;
  3877. switch (D) {
  3878. case 64: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D64[k->type][f32acc][small_rows][0]; break;
  3879. case 80: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D80[k->type][f32acc][small_rows][0]; break;
  3880. case 96: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D96[k->type][f32acc][small_rows][0]; break;
  3881. case 112: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D112[k->type][f32acc][small_rows][0]; break;
  3882. case 128: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D128[k->type][f32acc][small_rows][0]; break;
  3883. case 256: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D256[k->type][f32acc][small_rows][0]; break;
  3884. default:
  3885. assert(!"unsupported D value");
  3886. return;
  3887. }
  3888. assert(pipelines);
  3889. bool aligned = (KV % pipelines[1]->align) == 0;
  3890. vk_pipeline pipeline = pipelines[aligned];
  3891. assert(pipeline);
  3892. if (dryrun) {
  3893. // Request descriptor sets
  3894. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3895. return;
  3896. }
  3897. float scale = 1.0f;
  3898. float max_bias = 0.0f;
  3899. float logit_softcap = 0.0f;
  3900. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  3901. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  3902. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  3903. if (logit_softcap != 0) {
  3904. scale /= logit_softcap;
  3905. }
  3906. const uint32_t n_head_kv = neq2;
  3907. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  3908. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  3909. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  3910. ggml_vk_sync_buffers(subctx);
  3911. vk_buffer d_Q, d_K, d_V, d_D, d_M;
  3912. uint64_t q_buf_offset, k_buf_offset, v_buf_offset, d_buf_offset, m_buf_offset;
  3913. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false;
  3914. if (ctx->device->uma) {
  3915. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  3916. ggml_vk_host_get(ctx->device, k->data, d_K, q_buf_offset);
  3917. ggml_vk_host_get(ctx->device, v->data, d_V, q_buf_offset);
  3918. ggml_vk_host_get(ctx->device, dst->data, d_D, q_buf_offset);
  3919. Q_uma = d_Q != nullptr;
  3920. K_uma = d_K != nullptr;
  3921. V_uma = d_V != nullptr;
  3922. D_uma = d_D != nullptr;
  3923. if (mask) {
  3924. ggml_vk_host_get(ctx->device, mask->data, d_M, q_buf_offset);
  3925. M_uma = d_M != nullptr;
  3926. }
  3927. }
  3928. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3929. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  3930. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  3931. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  3932. if (!Q_uma) {
  3933. d_Q = q_buf_ctx->dev_buffer;
  3934. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  3935. }
  3936. if (!K_uma) {
  3937. d_K = k_buf_ctx->dev_buffer;
  3938. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  3939. }
  3940. if (!V_uma) {
  3941. d_V = v_buf_ctx->dev_buffer;
  3942. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  3943. }
  3944. if (!D_uma) {
  3945. d_D = d_buf_ctx->dev_buffer;
  3946. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3947. }
  3948. if (!M_uma) {
  3949. d_M = d_Q;
  3950. m_buf_offset = q_buf_offset;
  3951. if (mask) {
  3952. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  3953. d_M = m_buf_ctx->dev_buffer;
  3954. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  3955. }
  3956. }
  3957. const vk_flash_attn_push_constants pc = { N, KV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, (uint32_t)neq2, (uint32_t)neq3, (uint32_t)nek2, (uint32_t)nek3, (uint32_t)nev2, (uint32_t)nev3, nem1, (uint32_t)nbq2, (uint32_t)nbq3, (uint32_t)nbk2, (uint32_t)nbk3, (uint32_t)nbv2, (uint32_t)nbv3, nbm1, scale, max_bias, logit_softcap, mask != nullptr, n_head_log2, m0, m1 };
  3958. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  3959. {
  3960. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  3961. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  3962. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  3963. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  3964. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  3965. },
  3966. sizeof(vk_flash_attn_push_constants), &pc, { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3 });
  3967. }
  3968. 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, ggml_tensor * dst, ggml_op op) {
  3969. switch (op) {
  3970. case GGML_OP_GET_ROWS:
  3971. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  3972. if (dst->type == GGML_TYPE_F16) {
  3973. return ctx->device->pipeline_get_rows[src0->type];
  3974. }
  3975. if (dst->type == GGML_TYPE_F32) {
  3976. return ctx->device->pipeline_get_rows_f32[src0->type];
  3977. }
  3978. return nullptr;
  3979. case GGML_OP_ACC:
  3980. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3981. return ctx->device->pipeline_acc_f32;
  3982. }
  3983. return nullptr;
  3984. case GGML_OP_ADD:
  3985. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3986. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f32_norepeat : ctx->device->pipeline_add_f32;
  3987. }
  3988. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  3989. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f16_f32_f16_norepeat : ctx->device->pipeline_add_f16_f32_f16;
  3990. }
  3991. return nullptr;
  3992. case GGML_OP_MUL:
  3993. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3994. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_f32_norepeat : ctx->device->pipeline_mul_f32;
  3995. }
  3996. return nullptr;
  3997. case GGML_OP_DIV:
  3998. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3999. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_f32_norepeat : ctx->device->pipeline_div_f32;
  4000. }
  4001. return nullptr;
  4002. case GGML_OP_CONCAT:
  4003. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4004. return ctx->device->pipeline_concat_f32;
  4005. }
  4006. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4007. return ctx->device->pipeline_concat_f16;
  4008. }
  4009. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  4010. return ctx->device->pipeline_concat_i32;
  4011. }
  4012. return nullptr;
  4013. case GGML_OP_UPSCALE:
  4014. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4015. return ctx->device->pipeline_upscale_f32;
  4016. }
  4017. return nullptr;
  4018. case GGML_OP_SCALE:
  4019. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4020. return ctx->device->pipeline_scale_f32;
  4021. }
  4022. return nullptr;
  4023. case GGML_OP_SQR:
  4024. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4025. return ctx->device->pipeline_sqr_f32;
  4026. }
  4027. return nullptr;
  4028. case GGML_OP_SIN:
  4029. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4030. return ctx->device->pipeline_sin_f32;
  4031. }
  4032. return nullptr;
  4033. case GGML_OP_COS:
  4034. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4035. return ctx->device->pipeline_cos_f32;
  4036. }
  4037. return nullptr;
  4038. case GGML_OP_CLAMP:
  4039. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4040. return ctx->device->pipeline_clamp_f32;
  4041. }
  4042. return nullptr;
  4043. case GGML_OP_PAD:
  4044. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4045. return ctx->device->pipeline_pad_f32;
  4046. }
  4047. return nullptr;
  4048. case GGML_OP_REPEAT:
  4049. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  4050. return ctx->device->pipeline_repeat_f32;
  4051. }
  4052. return nullptr;
  4053. case GGML_OP_CPY:
  4054. case GGML_OP_CONT:
  4055. case GGML_OP_DUP:
  4056. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  4057. case GGML_OP_NORM:
  4058. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4059. return ctx->device->pipeline_norm_f32;
  4060. }
  4061. return nullptr;
  4062. case GGML_OP_GROUP_NORM:
  4063. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4064. return ctx->device->pipeline_group_norm_f32;
  4065. }
  4066. return nullptr;
  4067. case GGML_OP_RMS_NORM:
  4068. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4069. return ctx->device->pipeline_rms_norm_f32;
  4070. }
  4071. return nullptr;
  4072. case GGML_OP_UNARY:
  4073. switch (ggml_get_unary_op(dst)) {
  4074. case GGML_UNARY_OP_SILU:
  4075. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4076. return ctx->device->pipeline_silu_f32;
  4077. }
  4078. break;
  4079. case GGML_UNARY_OP_GELU:
  4080. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4081. return ctx->device->pipeline_gelu_f32;
  4082. }
  4083. break;
  4084. case GGML_UNARY_OP_GELU_QUICK:
  4085. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4086. return ctx->device->pipeline_gelu_quick_f32;
  4087. }
  4088. break;
  4089. case GGML_UNARY_OP_RELU:
  4090. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4091. return ctx->device->pipeline_relu_f32;
  4092. }
  4093. break;
  4094. case GGML_UNARY_OP_TANH:
  4095. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4096. return ctx->device->pipeline_tanh_f32;
  4097. }
  4098. break;
  4099. default:
  4100. break;
  4101. }
  4102. return nullptr;
  4103. case GGML_OP_DIAG_MASK_INF:
  4104. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4105. return ctx->device->pipeline_diag_mask_inf_f32;
  4106. }
  4107. return nullptr;
  4108. case GGML_OP_SOFT_MAX:
  4109. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  4110. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  4111. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  4112. }
  4113. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  4114. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  4115. }
  4116. return nullptr;
  4117. case GGML_OP_ROPE:
  4118. {
  4119. const int mode = ((const int32_t *) dst->op_params)[2];
  4120. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  4121. if (is_neox) {
  4122. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4123. return ctx->device->pipeline_rope_neox_f32;
  4124. }
  4125. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4126. return ctx->device->pipeline_rope_neox_f16;
  4127. }
  4128. } else {
  4129. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4130. return ctx->device->pipeline_rope_norm_f32;
  4131. }
  4132. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4133. return ctx->device->pipeline_rope_norm_f16;
  4134. }
  4135. }
  4136. return nullptr;
  4137. }
  4138. case GGML_OP_ARGSORT:
  4139. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  4140. return ctx->device->pipeline_argsort_f32;
  4141. }
  4142. return nullptr;
  4143. case GGML_OP_SUM_ROWS:
  4144. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4145. return ctx->device->pipeline_sum_rows_f32;
  4146. }
  4147. return nullptr;
  4148. case GGML_OP_IM2COL:
  4149. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4150. return ctx->device->pipeline_im2col_f32;
  4151. }
  4152. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4153. return ctx->device->pipeline_im2col_f32_f16;
  4154. }
  4155. return nullptr;
  4156. case GGML_OP_TIMESTEP_EMBEDDING:
  4157. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4158. return ctx->device->pipeline_timestep_embedding_f32;
  4159. }
  4160. return nullptr;
  4161. case GGML_OP_POOL_2D:
  4162. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4163. return ctx->device->pipeline_pool2d_f32;
  4164. }
  4165. return nullptr;
  4166. case GGML_OP_LEAKY_RELU:
  4167. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4168. return ctx->device->pipeline_leaky_relu_f32;
  4169. }
  4170. return nullptr;
  4171. default:
  4172. return nullptr;
  4173. }
  4174. GGML_UNUSED(src2);
  4175. }
  4176. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  4177. switch (op) {
  4178. case GGML_OP_CPY:
  4179. case GGML_OP_GET_ROWS:
  4180. case GGML_OP_ADD:
  4181. case GGML_OP_MUL:
  4182. case GGML_OP_DIV:
  4183. case GGML_OP_CONCAT:
  4184. case GGML_OP_UPSCALE:
  4185. case GGML_OP_SQR:
  4186. case GGML_OP_SIN:
  4187. case GGML_OP_COS:
  4188. case GGML_OP_CLAMP:
  4189. case GGML_OP_PAD:
  4190. case GGML_OP_REPEAT:
  4191. return true;
  4192. default:
  4193. return false;
  4194. }
  4195. }
  4196. template<typename PC>
  4197. 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, ggml_tensor * dst, ggml_op op, PC&& pc, bool dryrun = false) {
  4198. 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];
  4199. if (src1 != nullptr) {
  4200. 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];
  4201. }
  4202. if (src2 != nullptr) {
  4203. 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];
  4204. }
  4205. 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];
  4206. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  4207. GGML_ASSERT(op == GGML_OP_GET_ROWS || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  4208. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  4209. GGML_ASSERT(dst->buffer != nullptr);
  4210. const uint64_t ne00 = src0->ne[0];
  4211. const uint64_t ne01 = src0->ne[1];
  4212. const uint64_t ne02 = src0->ne[2];
  4213. const uint64_t ne03 = src0->ne[3];
  4214. const uint64_t ne0 = ne00 * ne01;
  4215. const bool use_src1 = src1 != nullptr;
  4216. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  4217. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  4218. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  4219. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  4220. const uint64_t ne1 = ne10 * ne11;
  4221. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  4222. const bool use_src2 = src2 != nullptr;
  4223. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  4224. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  4225. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  4226. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  4227. const uint64_t ne2 = ne20 * ne21;
  4228. const uint64_t ned0 = dst->ne[0];
  4229. const uint64_t ned1 = dst->ne[1];
  4230. const uint64_t ned2 = dst->ne[2];
  4231. const uint64_t ned3 = dst->ne[3];
  4232. const uint64_t ned = ned0 * ned1;
  4233. init_pushconst_fastdiv(pc);
  4234. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  4235. if (pipeline == nullptr) {
  4236. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  4237. if (src1 != nullptr) {
  4238. std::cerr << " and " << ggml_type_name(src1->type);
  4239. }
  4240. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  4241. GGML_ABORT("fatal error");
  4242. }
  4243. if (dryrun) {
  4244. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4245. return;
  4246. }
  4247. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  4248. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4249. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4250. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  4251. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  4252. vk_buffer d_X = nullptr;
  4253. size_t x_buf_offset = 0;
  4254. vk_buffer d_Y = nullptr;
  4255. size_t y_buf_offset = 0;
  4256. vk_buffer d_Z = nullptr;
  4257. size_t z_buf_offset = 0;
  4258. bool src0_uma = false;
  4259. bool src1_uma = false;
  4260. bool src2_uma = false;
  4261. if (ctx->device->uma) {
  4262. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  4263. src0_uma = d_X != nullptr;
  4264. if (use_src1) {
  4265. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  4266. src1_uma = d_Y != nullptr;
  4267. }
  4268. if (use_src2) {
  4269. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  4270. src2_uma = d_Z != nullptr;
  4271. }
  4272. }
  4273. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  4274. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  4275. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  4276. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  4277. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4278. // Workaround for tiny tensor inputs on ROPE
  4279. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  4280. y_sz = VK_WHOLE_SIZE;
  4281. }
  4282. GGML_ASSERT(d_D != nullptr);
  4283. uint64_t d_buf_offset = ((vk_tensor_offset(dst) + dst->view_offs) / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  4284. GGML_ASSERT(d_buf_offset == vk_tensor_offset(dst) || op == GGML_OP_CPY); // NOLINT
  4285. if(!src0_uma) {
  4286. d_X = src0_buf_ctx->dev_buffer;
  4287. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4288. GGML_ASSERT(d_X != nullptr);
  4289. }
  4290. if (use_src1 && !src1_uma) {
  4291. d_Y = src1_buf_ctx->dev_buffer;
  4292. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4293. GGML_ASSERT(d_Y != nullptr);
  4294. }
  4295. if (use_src2 && !src2_uma) {
  4296. d_Z = src2_buf_ctx->dev_buffer;
  4297. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  4298. GGML_ASSERT(d_Z != nullptr);
  4299. }
  4300. if (op_supports_incontiguous) {
  4301. x_sz = ggml_nbytes(src0);
  4302. y_sz = use_src1 ? ggml_nbytes(src1) : 0;
  4303. z_sz = use_src2 ? ggml_nbytes(src2) : 0;
  4304. d_sz = ggml_nbytes(dst);
  4305. if (x_buf_offset + x_sz >= d_X->size) {
  4306. x_sz = VK_WHOLE_SIZE;
  4307. }
  4308. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  4309. y_sz = VK_WHOLE_SIZE;
  4310. }
  4311. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  4312. z_sz = VK_WHOLE_SIZE;
  4313. }
  4314. if (d_buf_offset + d_sz >= d_D->size) {
  4315. d_sz = VK_WHOLE_SIZE;
  4316. }
  4317. }
  4318. std::array<uint32_t, 3> elements;
  4319. // Single call if dimension 2 is contiguous
  4320. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  4321. switch (op) {
  4322. case GGML_OP_NORM:
  4323. case GGML_OP_RMS_NORM:
  4324. case GGML_OP_SOFT_MAX:
  4325. case GGML_OP_SUM_ROWS:
  4326. {
  4327. const uint32_t nr = ggml_nrows(src0);
  4328. if (nr > 262144) {
  4329. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  4330. } else if (nr > 512) {
  4331. elements = { 512, CEIL_DIV(nr, 512), 1 };
  4332. } else {
  4333. elements = { nr, 1, 1 };
  4334. }
  4335. } break;
  4336. case GGML_OP_GROUP_NORM:
  4337. {
  4338. const uint32_t num_groups = dst->op_params[0];
  4339. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  4340. } break;
  4341. case GGML_OP_DIAG_MASK_INF:
  4342. case GGML_OP_ROPE:
  4343. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  4344. break;
  4345. case GGML_OP_GET_ROWS:
  4346. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  4347. break;
  4348. case GGML_OP_ARGSORT:
  4349. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  4350. break;
  4351. case GGML_OP_IM2COL:
  4352. {
  4353. const bool is_2D = dst->op_params[6] == 1;
  4354. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4355. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4356. const uint32_t KW = src0->ne[0];
  4357. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4358. const uint32_t OW = dst->ne[1];
  4359. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  4360. elements = { OW * KW * KH, OH, batch * IC };
  4361. } break;
  4362. case GGML_OP_TIMESTEP_EMBEDDING:
  4363. {
  4364. const uint32_t dim = dst->op_params[0];
  4365. uint32_t half_ceil = (dim + 1) / 2;
  4366. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  4367. } break;
  4368. case GGML_OP_POOL_2D:
  4369. {
  4370. const uint32_t N = dst->ne[3];
  4371. const uint32_t OC = dst->ne[2];
  4372. const uint32_t OH = dst->ne[1];
  4373. const uint32_t OW = dst->ne[0];
  4374. elements = { N * OC * OH * OW, 1, 1};
  4375. } break;
  4376. case GGML_OP_ADD:
  4377. case GGML_OP_DIV:
  4378. case GGML_OP_MUL:
  4379. case GGML_OP_SCALE:
  4380. case GGML_OP_SQR:
  4381. case GGML_OP_SIN:
  4382. case GGML_OP_COS:
  4383. case GGML_OP_CLAMP:
  4384. case GGML_OP_PAD:
  4385. case GGML_OP_REPEAT:
  4386. case GGML_OP_CPY:
  4387. case GGML_OP_CONCAT:
  4388. case GGML_OP_UPSCALE:
  4389. case GGML_OP_UNARY:
  4390. {
  4391. const uint32_t ne = ggml_nelements(dst);
  4392. if (ne > 262144) {
  4393. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  4394. } else if (ne > 512) {
  4395. elements = { 512, CEIL_DIV(ne, 512), 1 };
  4396. } else {
  4397. elements = { ne, 1, 1 };
  4398. }
  4399. } break;
  4400. default:
  4401. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  4402. break;
  4403. }
  4404. if (!op_supports_incontiguous) {
  4405. if (x_sz != VK_WHOLE_SIZE) {
  4406. x_sz *= ne02 * ne03;
  4407. }
  4408. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  4409. y_sz *= ne12 * ne13;
  4410. }
  4411. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  4412. z_sz *= ne22 * ne23;
  4413. }
  4414. if (d_sz != VK_WHOLE_SIZE) {
  4415. d_sz *= ned2 * ned3;
  4416. }
  4417. }
  4418. if (op == GGML_OP_SOFT_MAX) {
  4419. // Empty src1 is possible in soft_max, but the shader needs a buffer
  4420. vk_subbuffer subbuf_y;
  4421. if (use_src1) {
  4422. subbuf_y = { d_Y, y_buf_offset, y_sz };
  4423. } else {
  4424. subbuf_y = { d_X, 0, x_sz };
  4425. }
  4426. ggml_vk_sync_buffers(subctx);
  4427. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4428. } else if (op == GGML_OP_ROPE) {
  4429. // Empty src2 is possible in rope, but the shader needs a buffer
  4430. vk_subbuffer subbuf_z;
  4431. if (use_src2) {
  4432. subbuf_z = { d_Z, z_buf_offset, z_sz };
  4433. } else {
  4434. subbuf_z = { d_X, 0, x_sz };
  4435. }
  4436. ggml_vk_sync_buffers(subctx);
  4437. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4438. } else if (op == GGML_OP_IM2COL) {
  4439. // im2col uses only src1 and dst buffers
  4440. ggml_vk_sync_buffers(subctx);
  4441. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4442. } else if (use_src2) {
  4443. ggml_vk_sync_buffers(subctx);
  4444. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4445. } else if (use_src1) {
  4446. ggml_vk_sync_buffers(subctx);
  4447. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4448. } else {
  4449. ggml_vk_sync_buffers(subctx);
  4450. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4451. }
  4452. }
  4453. 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, bool dryrun = false) {
  4454. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4455. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4456. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4457. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  4458. (uint32_t)ggml_nelements(src0),
  4459. (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,
  4460. (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,
  4461. (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,
  4462. 0,
  4463. 0.0f, 0.0f, 0,
  4464. }, dryrun);
  4465. }
  4466. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4467. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4468. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4469. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4470. const uint32_t d_offset = ((vk_tensor_offset(dst) + dst->view_offs) % ctx->device->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  4471. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  4472. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  4473. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  4474. int offset = dst->op_params[3] / 4; // offset in bytes
  4475. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  4476. (uint32_t)ggml_nelements(src0),
  4477. (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,
  4478. (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,
  4479. (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,
  4480. d_offset,
  4481. 0.0f, 0.0f, offset,
  4482. }, dryrun);
  4483. }
  4484. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4485. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4486. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4487. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4488. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  4489. (uint32_t)ggml_nelements(src0),
  4490. (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,
  4491. (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,
  4492. (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,
  4493. 0,
  4494. 0.0f, 0.0f, 0,
  4495. }, dryrun);
  4496. }
  4497. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4498. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4499. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4500. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4501. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  4502. (uint32_t)ggml_nelements(src0),
  4503. (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,
  4504. (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,
  4505. (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,
  4506. 0,
  4507. 0.0f, 0.0f, 0,
  4508. }, dryrun);
  4509. }
  4510. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4511. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4512. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4513. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4514. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  4515. (uint32_t)ggml_nelements(src0),
  4516. (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,
  4517. (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,
  4518. (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,
  4519. 0,
  4520. 0.0f, 0.0f, 0,
  4521. }, dryrun);
  4522. }
  4523. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4524. int * op_params = (int *)dst->op_params;
  4525. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4526. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4527. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4528. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  4529. (uint32_t)ggml_nelements(dst),
  4530. (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,
  4531. (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,
  4532. (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,
  4533. 0,
  4534. 0.0f, 0.0f, op_params[0],
  4535. }, dryrun);
  4536. }
  4537. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4538. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4539. const float sf0 = (float)dst->ne[0] / src0->ne[0];
  4540. const float sf1 = (float)dst->ne[1] / src0->ne[1];
  4541. const float sf2 = (float)dst->ne[2] / src0->ne[2];
  4542. const float sf3 = (float)dst->ne[3] / src0->ne[3];
  4543. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  4544. (uint32_t)ggml_nelements(dst), 0,
  4545. (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,
  4546. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  4547. sf0, sf1, sf2, sf3,
  4548. }, dryrun);
  4549. }
  4550. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4551. float * op_params = (float *)dst->op_params;
  4552. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4553. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4554. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, {
  4555. (uint32_t)ggml_nelements(src0),
  4556. (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,
  4557. (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,
  4558. 0,
  4559. op_params[0], 0.0f,
  4560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4561. }, dryrun);
  4562. }
  4563. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4564. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4565. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4566. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, {
  4567. (uint32_t)ggml_nelements(src0),
  4568. (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,
  4569. (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,
  4570. 0,
  4571. 0.0f, 0.0f,
  4572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4573. }, dryrun);
  4574. }
  4575. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4576. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4577. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4578. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, {
  4579. (uint32_t)ggml_nelements(src0),
  4580. (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,
  4581. (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,
  4582. 0,
  4583. 0.0f, 0.0f,
  4584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4585. }, dryrun);
  4586. }
  4587. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4588. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4589. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4590. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, {
  4591. (uint32_t)ggml_nelements(src0),
  4592. (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,
  4593. (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,
  4594. 0,
  4595. 0.0f, 0.0f,
  4596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4597. }, dryrun);
  4598. }
  4599. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4600. float * op_params = (float *)dst->op_params;
  4601. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4602. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4603. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, {
  4604. (uint32_t)ggml_nelements(src0),
  4605. (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,
  4606. (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,
  4607. 0,
  4608. op_params[0], op_params[1],
  4609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4610. }, dryrun);
  4611. }
  4612. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4613. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4614. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4615. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, {
  4616. (uint32_t)ggml_nelements(dst),
  4617. (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,
  4618. (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,
  4619. 0,
  4620. 0.0f, 0.0f,
  4621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4622. }, dryrun);
  4623. }
  4624. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4625. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4626. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4627. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, {
  4628. (uint32_t)ggml_nelements(dst),
  4629. (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,
  4630. (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,
  4631. 0,
  4632. 0.0f, 0.0f,
  4633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4634. }, dryrun);
  4635. }
  4636. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4637. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4638. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4639. const uint32_t d_offset = ((vk_tensor_offset(dst) + dst->view_offs) % ctx->device->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  4640. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, {
  4641. (uint32_t)ggml_nelements(src0),
  4642. (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,
  4643. (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,
  4644. d_offset,
  4645. 0.0f, 0.0f,
  4646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4647. }, dryrun);
  4648. }
  4649. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4650. float * op_params = (float *)dst->op_params;
  4651. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  4652. }
  4653. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4654. const int * int_op_params = (const int *)dst->op_params;
  4655. const float * float_op_params = (const float *)dst->op_params;
  4656. const uint32_t num_groups = int_op_params[0];
  4657. const float eps = float_op_params[1];
  4658. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  4659. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f }, dryrun);
  4660. }
  4661. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4662. float * op_params = (float *)dst->op_params;
  4663. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_RMS_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  4664. }
  4665. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4666. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  4667. }
  4668. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4669. int32_t * op_params = (int32_t *)dst->op_params;
  4670. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] }, dryrun);
  4671. }
  4672. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4673. float * op_params = (float *)dst->op_params;
  4674. float scale = op_params[0];
  4675. float max_bias = op_params[1];
  4676. const uint32_t ncols = (uint32_t)src0->ne[0];
  4677. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  4678. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  4679. const uint32_t n_head_kv = nrows_x/nrows_y;
  4680. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  4681. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  4682. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  4683. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SOFT_MAX, {
  4684. ncols,
  4685. src1 != nullptr ? nrows_y : (uint32_t)0,
  4686. scale, max_bias,
  4687. m0, m1,
  4688. n_head_log2,
  4689. nrows_x,
  4690. }, dryrun);
  4691. }
  4692. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  4693. const int n_dims = ((int32_t *) dst->op_params)[1];
  4694. // const int mode = ((int32_t *) dst->op_params)[2];
  4695. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  4696. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  4697. const float freq_base = ((float *) dst->op_params)[5];
  4698. const float freq_scale = ((float *) dst->op_params)[6];
  4699. const float ext_factor = ((float *) dst->op_params)[7];
  4700. const float attn_factor = ((float *) dst->op_params)[8];
  4701. const float beta_fast = ((float *) dst->op_params)[9];
  4702. const float beta_slow = ((float *) dst->op_params)[10];
  4703. float corr_dims[2];
  4704. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  4705. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  4706. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  4707. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  4708. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  4709. src2 != nullptr,
  4710. }, dryrun);
  4711. }
  4712. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4713. int32_t * op_params = (int32_t *)dst->op_params;
  4714. uint32_t ncols = src0->ne[0];
  4715. uint32_t ncols_pad = 1;
  4716. while (ncols_pad < ncols) {
  4717. ncols_pad *= 2;
  4718. }
  4719. GGML_ASSERT(ncols_pad <= 1024);
  4720. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  4721. ncols,
  4722. ncols_pad,
  4723. op_params[0],
  4724. }, dryrun);
  4725. }
  4726. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4727. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, { (uint32_t)src0->ne[0], 0, 0.0f, 0.0f }, dryrun);
  4728. }
  4729. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4730. const int32_t s0 = dst->op_params[0];
  4731. const int32_t s1 = dst->op_params[1];
  4732. const int32_t p0 = dst->op_params[2];
  4733. const int32_t p1 = dst->op_params[3];
  4734. const int32_t d0 = dst->op_params[4];
  4735. const int32_t d1 = dst->op_params[5];
  4736. const bool is_2D = dst->op_params[6] == 1;
  4737. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4738. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  4739. const uint32_t IW = src1->ne[0];
  4740. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4741. const uint32_t KW = src0->ne[0];
  4742. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4743. const uint32_t OW = dst->ne[1];
  4744. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  4745. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  4746. const uint32_t pelements = OW * KW * KH;
  4747. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  4748. batch_offset, offset_delta,
  4749. IC, IW, IH, OW, OH, KW, KH,
  4750. pelements,
  4751. IC * KH * KW,
  4752. s0, s1, p0, p1, d0, d1,
  4753. }, dryrun);
  4754. }
  4755. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4756. const uint32_t dim = dst->op_params[0];
  4757. const uint32_t max_period = dst->op_params[1];
  4758. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  4759. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  4760. nb1, dim, max_period,
  4761. }, dryrun);
  4762. }
  4763. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4764. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  4765. const int32_t k1 = dst->op_params[1];
  4766. const int32_t k0 = dst->op_params[2];
  4767. const int32_t s1 = dst->op_params[3];
  4768. const int32_t s0 = dst->op_params[4];
  4769. const int32_t p1 = dst->op_params[5];
  4770. const int32_t p0 = dst->op_params[6];
  4771. const uint32_t IH = src0->ne[1];
  4772. const uint32_t IW = src0->ne[0];
  4773. const uint32_t N = dst->ne[3];
  4774. const uint32_t OC = dst->ne[2];
  4775. const uint32_t OH = dst->ne[1];
  4776. const uint32_t OW = dst->ne[0];
  4777. const uint32_t parallel_elements = N * OC * OH * OW;
  4778. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  4779. IW, IH, OW, OH, OC,
  4780. parallel_elements,
  4781. op,
  4782. k0, k1, s0, s1, p0, p1,
  4783. }, dryrun);
  4784. }
  4785. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4786. const float * op_params = (const float *)dst->op_params;
  4787. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f }, dryrun);
  4788. }
  4789. #ifdef GGML_VULKAN_RUN_TESTS
  4790. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  4791. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  4792. return;
  4793. }
  4794. i0 = std::max(i0, 5);
  4795. i1 = std::max(i1, 5);
  4796. i2 = std::max(i2, 0);
  4797. fprintf(stderr, " ");
  4798. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4799. fprintf(stderr, "%7d ", idx1);
  4800. }
  4801. fprintf(stderr, "\n");
  4802. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  4803. fprintf(stderr, "%7d: ", idx0);
  4804. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4805. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  4806. float val;
  4807. if (type == GGML_TYPE_F32) {
  4808. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  4809. } else if (type == GGML_TYPE_F16) {
  4810. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  4811. } else {
  4812. GGML_ABORT("fatal error");
  4813. }
  4814. fprintf(stderr, "% 7.2f ", val);
  4815. } else {
  4816. fprintf(stderr, " ");
  4817. }
  4818. }
  4819. fprintf(stderr, "\n");
  4820. }
  4821. }
  4822. template <typename X_TYPE, typename Y_TYPE>
  4823. 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) {
  4824. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  4825. const size_t x_ne = m * k * batch;
  4826. const size_t y_ne = k * n * batch;
  4827. const size_t d_ne = m * n * batch;
  4828. vk_pipeline p;
  4829. std::string shname;
  4830. if (shader_size == 0) {
  4831. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4832. p = ctx->device->pipeline_matmul_f32->a_s;
  4833. shname = "F32_ALIGNED_S";
  4834. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4835. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  4836. shname = "F32_F16_ALIGNED_S";
  4837. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4838. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  4839. shname = "F16_F32_ALIGNED_S";
  4840. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4841. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  4842. shname = "F16_ALIGNED_S";
  4843. } else {
  4844. GGML_ABORT("fatal error");
  4845. }
  4846. } else if (shader_size == 1) {
  4847. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4848. p = ctx->device->pipeline_matmul_f32->a_m;
  4849. shname = "F32_ALIGNED_M";
  4850. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4851. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  4852. shname = "F32_F16_ALIGNED_M";
  4853. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4854. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  4855. shname = "F16_F32_ALIGNED_M";
  4856. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4857. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  4858. shname = "F16_ALIGNED_M";
  4859. } else {
  4860. GGML_ABORT("fatal error");
  4861. }
  4862. } else if (shader_size == 2) {
  4863. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4864. p = ctx->device->pipeline_matmul_f32->a_l;
  4865. shname = "F32_ALIGNED_L";
  4866. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4867. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  4868. shname = "F32_F16_ALIGNED_L";
  4869. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4870. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  4871. shname = "F16_F32_ALIGNED_L";
  4872. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4873. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  4874. shname = "F16_ALIGNED_L";
  4875. } else {
  4876. GGML_ABORT("fatal error");
  4877. }
  4878. } else {
  4879. GGML_ASSERT(0);
  4880. }
  4881. const size_t kpad = ggml_vk_align_size(k, p->align);
  4882. if (k != kpad) {
  4883. if (shader_size == 0) {
  4884. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4885. p = ctx->device->pipeline_matmul_f32->s;
  4886. shname = "F32_S";
  4887. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4888. p = ctx->device->pipeline_matmul_f32_f16->s;
  4889. shname = "F32_F16_S";
  4890. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4891. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  4892. shname = "F16_F32_S";
  4893. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4894. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  4895. shname = "F16_S";
  4896. }
  4897. } else if (shader_size == 1) {
  4898. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4899. p = ctx->device->pipeline_matmul_f32->m;
  4900. shname = "F32_M";
  4901. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4902. p = ctx->device->pipeline_matmul_f32_f16->m;
  4903. shname = "F32_F16_M";
  4904. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4905. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  4906. shname = "F16_F32_M";
  4907. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4908. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  4909. shname = "F16_M";
  4910. }
  4911. } else if (shader_size == 2) {
  4912. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4913. p = ctx->device->pipeline_matmul_f32->l;
  4914. shname = "F32_L";
  4915. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4916. p = ctx->device->pipeline_matmul_f32_f16->l;
  4917. shname = "F32_F16_L";
  4918. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4919. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  4920. shname = "F16_F32_L";
  4921. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4922. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  4923. shname = "F16_L";
  4924. }
  4925. }
  4926. }
  4927. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  4928. if (split_k > 1) {
  4929. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  4930. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  4931. // Resize buffer
  4932. if (ctx->prealloc_split_k != nullptr) {
  4933. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  4934. }
  4935. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4936. }
  4937. }
  4938. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  4939. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4940. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4941. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4942. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  4943. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  4944. float* d = (float *) malloc(sizeof(float) * d_ne);
  4945. for (size_t i = 0; i < x_ne; i++) {
  4946. if (std::is_same<float, X_TYPE>()) {
  4947. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  4948. // x[i] = 1.0f;
  4949. // x[i] = i + 1;
  4950. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  4951. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  4952. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  4953. // x[i] = ggml_fp32_to_fp16(1.0f);
  4954. // x[i] = ggml_fp32_to_fp16(i + 1);
  4955. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  4956. } else {
  4957. GGML_ABORT("fatal error");
  4958. }
  4959. }
  4960. for (size_t i = 0; i < y_ne; i++) {
  4961. if (std::is_same<float, Y_TYPE>()) {
  4962. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  4963. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  4964. // y[i] = i + 1;
  4965. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4966. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  4967. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  4968. // y[i] = ggml_fp32_to_fp16(i + 1);
  4969. } else {
  4970. GGML_ABORT("fatal error");
  4971. }
  4972. }
  4973. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  4974. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  4975. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  4976. ggml_vk_ctx_begin(ctx->device, subctx);
  4977. for (size_t i = 0; i < num_it; i++) {
  4978. ggml_vk_matmul(
  4979. ctx, subctx, p, ggml_vk_subbuffer(d_X), ggml_vk_subbuffer(d_Y), ggml_vk_subbuffer(d_D), ggml_vk_subbuffer(ctx->prealloc_split_k),
  4980. m, n, k,
  4981. k, k, m, k*m, k*n, m*n,
  4982. split_k, batch, batch, batch, 1, 1
  4983. );
  4984. }
  4985. ggml_vk_ctx_end(subctx);
  4986. auto begin = std::chrono::high_resolution_clock::now();
  4987. ggml_vk_submit(subctx, ctx->fence);
  4988. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  4989. ctx->device->device.resetFences({ ctx->fence });
  4990. auto end = std::chrono::high_resolution_clock::now();
  4991. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  4992. // copy dst to host
  4993. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  4994. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  4995. ggml_init_params iparams = {
  4996. /*.mem_size =*/ 1024*1024*1024,
  4997. /*.mem_buffer =*/ NULL,
  4998. /*.no_alloc =*/ true,
  4999. };
  5000. ggml_context * ggml_ctx = ggml_init(iparams);
  5001. ggml_type src0_type;
  5002. ggml_type src1_type;
  5003. if (std::is_same<float, X_TYPE>()) {
  5004. src0_type = GGML_TYPE_F32;
  5005. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  5006. src0_type = GGML_TYPE_F16;
  5007. } else {
  5008. GGML_ABORT("fatal error");
  5009. }
  5010. if (std::is_same<float, Y_TYPE>()) {
  5011. src1_type = GGML_TYPE_F32;
  5012. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5013. src1_type = GGML_TYPE_F16;
  5014. } else {
  5015. GGML_ABORT("fatal error");
  5016. }
  5017. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  5018. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  5019. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5020. src0_ggml->data = x;
  5021. src1_ggml->data = y;
  5022. tensor_ggml->data = d_chk;
  5023. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5024. ggml_build_forward_expand(cgraph, tensor_ggml);
  5025. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5026. ggml_free(ggml_ctx);
  5027. double avg_err = 0.0;
  5028. int first_err_n = -1;
  5029. int first_err_m = -1;
  5030. int first_err_b = -1;
  5031. for (size_t i = 0; i < m*n*batch; i++) {
  5032. double err = std::fabs(d[i] - d_chk[i]);
  5033. avg_err += err;
  5034. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5035. first_err_b = i / (m * n);
  5036. first_err_n = (i % (m * n)) / m;
  5037. first_err_m = (i % (m * n)) % m;
  5038. }
  5039. }
  5040. avg_err /= m * n;
  5041. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5042. 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;
  5043. if (avg_err > 0.1 || std::isnan(avg_err)) {
  5044. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5045. std::cerr << "Actual result: " << std::endl << std::endl;
  5046. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5047. std::cerr << "Expected result: " << std::endl << std::endl;
  5048. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5049. if (split_k > 1) {
  5050. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5051. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5052. std::cerr << "d_buf0: " << std::endl << std::endl;
  5053. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5054. std::cerr << "d_buf1: " << std::endl << std::endl;
  5055. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5056. std::cerr << "d_buf2: " << std::endl << std::endl;
  5057. 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);
  5058. std::cerr << "d_buf3: " << std::endl << std::endl;
  5059. 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);
  5060. free(split_k_buf);
  5061. }
  5062. }
  5063. free(d_chk);
  5064. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5065. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5066. ggml_vk_destroy_buffer(d_X);
  5067. ggml_vk_destroy_buffer(d_Y);
  5068. ggml_vk_destroy_buffer(d_D);
  5069. ggml_pipeline_cleanup(p);
  5070. ggml_pipeline_cleanup(ctx->device->pipeline_matmul_split_k_reduce);
  5071. free(x);
  5072. free(y);
  5073. free(d);
  5074. }
  5075. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  5076. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  5077. return;
  5078. }
  5079. i0 = std::max(i0, 5);
  5080. i1 = std::max(i1, 5);
  5081. i2 = std::max(i2, 0);
  5082. i3 = std::max(i3, 0);
  5083. fprintf(stderr, " ");
  5084. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5085. fprintf(stderr, "%7d ", idx1);
  5086. }
  5087. fprintf(stderr, "\n");
  5088. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5089. fprintf(stderr, "%7d: ", idx0);
  5090. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5091. 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]) {
  5092. float val;
  5093. if (tensor->type == GGML_TYPE_F32) {
  5094. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  5095. } else if (tensor->type == GGML_TYPE_F16) {
  5096. 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]));
  5097. } else {
  5098. GGML_ABORT("fatal error");
  5099. }
  5100. fprintf(stderr, "% 7.2f ", val);
  5101. } else {
  5102. fprintf(stderr, " ");
  5103. }
  5104. }
  5105. fprintf(stderr, "\n");
  5106. }
  5107. }
  5108. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  5109. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  5110. }
  5111. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  5112. if (quant == GGML_TYPE_F32) {
  5113. memcpy(to, from, sizeof(float) * ne);
  5114. return;
  5115. }
  5116. const auto * tt = ggml_get_type_traits(quant);
  5117. ggml_to_float_t dequant_fn = tt->to_float;
  5118. dequant_fn(from, to, ne);
  5119. }
  5120. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  5121. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  5122. const size_t x_sz = sizeof(float) * ne;
  5123. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  5124. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5125. float * x = (float *) malloc(x_sz);
  5126. void * qx = malloc(qx_sz);
  5127. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5128. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5129. float * x_ref = (float *) malloc(x_sz);
  5130. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  5131. for (size_t i = 0; i < ne; i++) {
  5132. x[i] = rand() / (float)RAND_MAX;
  5133. }
  5134. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  5135. ggml_vk_quantize_data(x, qx, ne, quant);
  5136. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  5137. ggml_pipeline_request_descriptor_sets(ctx->device, p, 1);
  5138. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5139. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5140. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5141. ggml_vk_ctx_begin(ctx->device, subctx);
  5142. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  5143. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  5144. ggml_vk_ctx_end(subctx);
  5145. auto begin = std::chrono::high_resolution_clock::now();
  5146. ggml_vk_submit(subctx, ctx->fence);
  5147. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5148. ctx->device->device.resetFences({ ctx->fence });
  5149. auto end = std::chrono::high_resolution_clock::now();
  5150. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5151. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  5152. int first_err = -1;
  5153. double avg_err = 0.0;
  5154. for (size_t i = 0; i < ne; i++) {
  5155. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  5156. avg_err += error;
  5157. if (first_err < 0 && error > 0.05) {
  5158. first_err = i;
  5159. }
  5160. }
  5161. avg_err /= ne;
  5162. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  5163. if (avg_err > 0.1) {
  5164. std::cerr << "first_error = " << first_err << std::endl;
  5165. std::cerr << "Actual result: " << std::endl << std::endl;
  5166. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5167. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  5168. }
  5169. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  5170. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5171. std::cerr << x_ref[i] << ", ";
  5172. }
  5173. std::cerr << std::endl;
  5174. }
  5175. ggml_vk_destroy_buffer(x_buf);
  5176. ggml_vk_destroy_buffer(qx_buf);
  5177. free(x);
  5178. free(qx);
  5179. free(x_ref);
  5180. free(x_chk);
  5181. }
  5182. 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) {
  5183. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  5184. const size_t x_ne = m * k * batch;
  5185. const size_t y_ne = k * n * batch;
  5186. const size_t d_ne = m * n * batch;
  5187. vk_pipeline p;
  5188. std::string shname;
  5189. if (shader_size == 0) {
  5190. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_s;
  5191. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  5192. } else if (shader_size == 1) {
  5193. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_m;
  5194. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  5195. } else if (shader_size == 2) {
  5196. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_l;
  5197. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  5198. } else {
  5199. GGML_ASSERT(0);
  5200. }
  5201. const size_t kpad = ggml_vk_align_size(k, p->align);
  5202. if (k != kpad) {
  5203. if (shader_size == 0) {
  5204. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->s;
  5205. shname = std::string(ggml_type_name(quant)) + "_S";
  5206. } else if (shader_size == 1) {
  5207. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->m;
  5208. shname = std::string(ggml_type_name(quant)) + "_M";
  5209. } else if (shader_size == 2) {
  5210. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->l;
  5211. shname = std::string(ggml_type_name(quant)) + "_L";
  5212. } else {
  5213. GGML_ASSERT(0);
  5214. }
  5215. }
  5216. const size_t x_sz = sizeof(float) * x_ne;
  5217. const size_t y_sz = sizeof(float) * y_ne;
  5218. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5219. const size_t d_sz = sizeof(float) * d_ne;
  5220. float * x = (float *) malloc(x_sz);
  5221. float * y = (float *) malloc(y_sz);
  5222. void * qx = malloc(qx_sz);
  5223. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5224. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5225. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5226. float * d = (float *) malloc(d_sz);
  5227. float * d_chk = (float *) malloc(d_sz);
  5228. for (size_t i = 0; i < x_ne; i++) {
  5229. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5230. }
  5231. ggml_vk_quantize_data(x, qx, x_ne, quant);
  5232. for (size_t i = 0; i < y_ne; i++) {
  5233. // y[i] = rand() / (float)RAND_MAX;
  5234. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5235. }
  5236. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5237. if (split_k > 1) {
  5238. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5239. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5240. // Resize buffer
  5241. if (ctx->prealloc_split_k != nullptr) {
  5242. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5243. }
  5244. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5245. }
  5246. }
  5247. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5248. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5249. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  5250. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5251. ggml_vk_ctx_begin(ctx->device, subctx);
  5252. for (size_t i = 0; i < num_it; i++) {
  5253. ggml_vk_matmul(
  5254. ctx, subctx, p, ggml_vk_subbuffer(qx_buf), ggml_vk_subbuffer(y_buf), ggml_vk_subbuffer(d_buf), ggml_vk_subbuffer(ctx->prealloc_split_k),
  5255. m, n, k,
  5256. k, k, m, k*m, k*n, m*n,
  5257. split_k, batch, batch, batch, 1, 1
  5258. );
  5259. }
  5260. ggml_vk_ctx_end(subctx);
  5261. auto begin = std::chrono::high_resolution_clock::now();
  5262. ggml_vk_submit(subctx, ctx->fence);
  5263. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5264. ctx->device->device.resetFences({ ctx->fence });
  5265. auto end = std::chrono::high_resolution_clock::now();
  5266. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5267. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  5268. ggml_init_params iparams = {
  5269. /*.mem_size =*/ 1024*1024*1024,
  5270. /*.mem_buffer =*/ NULL,
  5271. /*.no_alloc =*/ true,
  5272. };
  5273. ggml_context * ggml_ctx = ggml_init(iparams);
  5274. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  5275. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  5276. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5277. src0_ggml->data = qx;
  5278. src1_ggml->data = y;
  5279. tensor_ggml->data = d_chk;
  5280. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5281. ggml_build_forward_expand(cgraph, tensor_ggml);
  5282. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5283. ggml_free(ggml_ctx);
  5284. double avg_err = 0.0;
  5285. int first_err_n = -1;
  5286. int first_err_m = -1;
  5287. int first_err_b = -1;
  5288. for (size_t i = 0; i < m*n*batch; i++) {
  5289. double err = std::fabs(d[i] - d_chk[i]);
  5290. avg_err += err;
  5291. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5292. first_err_b = i / (m * n);
  5293. first_err_n = (i % (m * n)) / m;
  5294. first_err_m = (i % (m * n)) % m;
  5295. }
  5296. }
  5297. avg_err /= m * n;
  5298. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5299. std::cerr << "TEST MMQ " << shname << " 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;
  5300. if (avg_err > 0.01 || std::isnan(avg_err)) {
  5301. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5302. std::cerr << "Actual result: " << std::endl << std::endl;
  5303. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5304. std::cerr << std::endl;
  5305. std::cerr << "Expected result: " << std::endl << std::endl;
  5306. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5307. if (split_k > 1) {
  5308. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5309. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5310. std::cerr << "d_buf0: " << std::endl << std::endl;
  5311. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5312. std::cerr << "d_buf1: " << std::endl << std::endl;
  5313. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5314. std::cerr << "d_buf2: " << std::endl << std::endl;
  5315. 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);
  5316. std::cerr << "d_buf3: " << std::endl << std::endl;
  5317. 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);
  5318. free(split_k_buf);
  5319. }
  5320. }
  5321. ggml_vk_destroy_buffer(qx_buf);
  5322. ggml_vk_destroy_buffer(y_buf);
  5323. ggml_vk_destroy_buffer(d_buf);
  5324. free(x);
  5325. free(qx);
  5326. free(y);
  5327. free(d);
  5328. free(d_chk);
  5329. }
  5330. #endif
  5331. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  5332. #if defined(GGML_VULKAN_RUN_TESTS)
  5333. const std::vector<size_t> vals {
  5334. 512, 512, 128,
  5335. 128, 512, 512,
  5336. 4096, 512, 4096,
  5337. 11008, 512, 4096,
  5338. 4096, 512, 11008,
  5339. 32000, 512, 4096,
  5340. 8, 8, 8,
  5341. 100, 46, 576,
  5342. 623, 111, 128,
  5343. 100, 46, 558,
  5344. 512, 1, 256,
  5345. 128, 110, 622,
  5346. 511, 511, 127,
  5347. 511, 511, 7,
  5348. 511, 511, 17,
  5349. 49, 49, 128,
  5350. 128, 49, 49,
  5351. 4096, 49, 4096,
  5352. };
  5353. const size_t num_it = 100;
  5354. for (size_t i = 0; i < vals.size(); i += 3) {
  5355. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  5356. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  5357. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  5358. std::cerr << '\n';
  5359. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  5360. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  5361. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  5362. std::cerr << '\n';
  5363. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  5364. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  5365. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  5366. std::cerr << '\n' << std::endl;
  5367. if (vals[i + 2] % 32 == 0) {
  5368. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  5369. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  5370. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  5371. std::cerr << '\n';
  5372. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  5373. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  5374. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  5375. std::cerr << '\n';
  5376. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  5377. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  5378. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  5379. std::cerr << '\n' << std::endl;
  5380. }
  5381. if (vals[i + 2] % 256 == 0) {
  5382. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  5383. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  5384. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  5385. std::cerr << '\n';
  5386. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  5387. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  5388. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  5389. std::cerr << '\n';
  5390. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  5391. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  5392. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  5393. std::cerr << '\n' << std::endl;
  5394. }
  5395. }
  5396. GGML_ABORT("fatal error");
  5397. #endif
  5398. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  5399. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  5400. // Resize buffer
  5401. if (ctx->prealloc_x != nullptr) {
  5402. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5403. }
  5404. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  5405. }
  5406. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  5407. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  5408. // Resize buffer
  5409. if (ctx->prealloc_y != nullptr) {
  5410. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5411. }
  5412. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  5413. }
  5414. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  5415. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  5416. // Resize buffer
  5417. if (ctx->prealloc_split_k != nullptr) {
  5418. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5419. }
  5420. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  5421. }
  5422. }
  5423. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_tensor* tensor, int tensor_idx, bool use_fence);
  5424. // Returns true if node has enqueued work into the queue, false otherwise
  5425. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  5426. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool dryrun, bool last_node, bool submit){
  5427. if (ggml_is_empty(node) || !node->buffer) {
  5428. return false;
  5429. }
  5430. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  5431. ctx->semaphore_idx = 0;
  5432. const ggml_tensor * src0 = node->src[0];
  5433. const ggml_tensor * src1 = node->src[1];
  5434. const ggml_tensor * src2 = node->src[2];
  5435. const ggml_tensor * src3 = node->src[3];
  5436. switch (node->op) {
  5437. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  5438. case GGML_OP_RESHAPE:
  5439. case GGML_OP_VIEW:
  5440. case GGML_OP_PERMUTE:
  5441. case GGML_OP_TRANSPOSE:
  5442. case GGML_OP_NONE:
  5443. return false;
  5444. case GGML_OP_UNARY:
  5445. switch (ggml_get_unary_op(node)) {
  5446. case GGML_UNARY_OP_SILU:
  5447. case GGML_UNARY_OP_GELU:
  5448. case GGML_UNARY_OP_GELU_QUICK:
  5449. case GGML_UNARY_OP_RELU:
  5450. case GGML_UNARY_OP_TANH:
  5451. break;
  5452. default:
  5453. return false;
  5454. }
  5455. break;
  5456. case GGML_OP_REPEAT:
  5457. case GGML_OP_GET_ROWS:
  5458. case GGML_OP_ADD:
  5459. case GGML_OP_ACC:
  5460. case GGML_OP_MUL:
  5461. case GGML_OP_DIV:
  5462. case GGML_OP_CONCAT:
  5463. case GGML_OP_UPSCALE:
  5464. case GGML_OP_SCALE:
  5465. case GGML_OP_SQR:
  5466. case GGML_OP_SIN:
  5467. case GGML_OP_COS:
  5468. case GGML_OP_CLAMP:
  5469. case GGML_OP_PAD:
  5470. case GGML_OP_CPY:
  5471. case GGML_OP_CONT:
  5472. case GGML_OP_DUP:
  5473. case GGML_OP_NORM:
  5474. case GGML_OP_GROUP_NORM:
  5475. case GGML_OP_RMS_NORM:
  5476. case GGML_OP_DIAG_MASK_INF:
  5477. case GGML_OP_SOFT_MAX:
  5478. case GGML_OP_ROPE:
  5479. case GGML_OP_MUL_MAT:
  5480. case GGML_OP_MUL_MAT_ID:
  5481. case GGML_OP_ARGSORT:
  5482. case GGML_OP_SUM_ROWS:
  5483. case GGML_OP_IM2COL:
  5484. case GGML_OP_TIMESTEP_EMBEDDING:
  5485. case GGML_OP_POOL_2D:
  5486. case GGML_OP_LEAKY_RELU:
  5487. case GGML_OP_FLASH_ATTN_EXT:
  5488. break;
  5489. default:
  5490. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  5491. GGML_ABORT("fatal error");
  5492. return false;
  5493. }
  5494. vk_context compute_ctx;
  5495. if (!dryrun) {
  5496. if (ctx->compute_ctx.expired()) {
  5497. compute_ctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5498. ctx->compute_ctx = compute_ctx;
  5499. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  5500. } else {
  5501. compute_ctx = ctx->compute_ctx.lock();
  5502. }
  5503. } else {
  5504. switch (node->op) {
  5505. case GGML_OP_REPEAT:
  5506. case GGML_OP_ACC:
  5507. case GGML_OP_GET_ROWS:
  5508. case GGML_OP_ADD:
  5509. case GGML_OP_MUL:
  5510. case GGML_OP_DIV:
  5511. case GGML_OP_CONCAT:
  5512. case GGML_OP_UPSCALE:
  5513. case GGML_OP_SCALE:
  5514. case GGML_OP_SQR:
  5515. case GGML_OP_SIN:
  5516. case GGML_OP_COS:
  5517. case GGML_OP_CLAMP:
  5518. case GGML_OP_PAD:
  5519. case GGML_OP_CPY:
  5520. case GGML_OP_CONT:
  5521. case GGML_OP_DUP:
  5522. case GGML_OP_NORM:
  5523. case GGML_OP_GROUP_NORM:
  5524. case GGML_OP_RMS_NORM:
  5525. case GGML_OP_UNARY:
  5526. case GGML_OP_DIAG_MASK_INF:
  5527. case GGML_OP_SOFT_MAX:
  5528. case GGML_OP_ROPE:
  5529. case GGML_OP_ARGSORT:
  5530. case GGML_OP_SUM_ROWS:
  5531. case GGML_OP_IM2COL:
  5532. case GGML_OP_TIMESTEP_EMBEDDING:
  5533. case GGML_OP_POOL_2D:
  5534. case GGML_OP_LEAKY_RELU:
  5535. {
  5536. // These operations all go through ggml_vk_op_f32, so short-circuit and
  5537. // do the only thing needed for the dryrun.
  5538. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  5539. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  5540. return false;
  5541. }
  5542. default:
  5543. break;
  5544. }
  5545. }
  5546. switch (node->op) {
  5547. case GGML_OP_REPEAT:
  5548. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  5549. break;
  5550. case GGML_OP_ACC:
  5551. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  5552. break;
  5553. case GGML_OP_GET_ROWS:
  5554. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  5555. break;
  5556. case GGML_OP_ADD:
  5557. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  5558. break;
  5559. case GGML_OP_MUL:
  5560. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  5561. break;
  5562. case GGML_OP_DIV:
  5563. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  5564. break;
  5565. case GGML_OP_CONCAT:
  5566. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  5567. break;
  5568. case GGML_OP_UPSCALE:
  5569. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  5570. break;
  5571. case GGML_OP_SCALE:
  5572. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  5573. break;
  5574. case GGML_OP_SQR:
  5575. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  5576. break;
  5577. case GGML_OP_SIN:
  5578. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  5579. break;
  5580. case GGML_OP_COS:
  5581. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  5582. break;
  5583. case GGML_OP_CLAMP:
  5584. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  5585. break;
  5586. case GGML_OP_PAD:
  5587. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  5588. break;
  5589. case GGML_OP_CPY:
  5590. case GGML_OP_CONT:
  5591. case GGML_OP_DUP:
  5592. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  5593. break;
  5594. case GGML_OP_NORM:
  5595. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  5596. break;
  5597. case GGML_OP_GROUP_NORM:
  5598. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  5599. break;
  5600. case GGML_OP_RMS_NORM:
  5601. ggml_vk_rms_norm(ctx, compute_ctx, src0, node, dryrun);
  5602. break;
  5603. case GGML_OP_UNARY:
  5604. switch (ggml_get_unary_op(node)) {
  5605. case GGML_UNARY_OP_SILU:
  5606. case GGML_UNARY_OP_GELU:
  5607. case GGML_UNARY_OP_GELU_QUICK:
  5608. case GGML_UNARY_OP_RELU:
  5609. case GGML_UNARY_OP_TANH:
  5610. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  5611. break;
  5612. default:
  5613. return false;
  5614. }
  5615. break;
  5616. case GGML_OP_DIAG_MASK_INF:
  5617. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  5618. break;
  5619. case GGML_OP_SOFT_MAX:
  5620. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, node, dryrun);
  5621. break;
  5622. case GGML_OP_ROPE:
  5623. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  5624. break;
  5625. case GGML_OP_ARGSORT:
  5626. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  5627. break;
  5628. case GGML_OP_SUM_ROWS:
  5629. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  5630. break;
  5631. case GGML_OP_IM2COL:
  5632. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  5633. break;
  5634. case GGML_OP_TIMESTEP_EMBEDDING:
  5635. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  5636. break;
  5637. case GGML_OP_POOL_2D:
  5638. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  5639. break;
  5640. case GGML_OP_LEAKY_RELU:
  5641. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  5642. break;
  5643. case GGML_OP_MUL_MAT:
  5644. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  5645. break;
  5646. case GGML_OP_MUL_MAT_ID:
  5647. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  5648. break;
  5649. case GGML_OP_FLASH_ATTN_EXT:
  5650. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node, dryrun);
  5651. break;
  5652. default:
  5653. return false;
  5654. }
  5655. if (dryrun) {
  5656. return false;
  5657. }
  5658. ctx->tensor_ctxs[node_idx] = compute_ctx;
  5659. #if defined(GGML_VULKAN_CHECK_RESULTS) || defined(GGML_VULKAN_PERF)
  5660. // Force context reset on each node so that each tensor ends up in its own context
  5661. // and can be run and compared to its CPU equivalent separately
  5662. last_node = true;
  5663. #endif
  5664. if (submit || last_node) {
  5665. ggml_vk_ctx_end(compute_ctx);
  5666. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  5667. if (last_node) {
  5668. compute_ctx->exit_tensor_idx = node_idx_begin;
  5669. }
  5670. else {
  5671. compute_ctx->exit_tensor_idx = -1;
  5672. }
  5673. ctx->compute_ctx.reset();
  5674. bool ok = ggml_vk_compute_forward(ctx, node_begin, node_idx_begin, false);
  5675. if (!ok) {
  5676. if (node->op == GGML_OP_UNARY) {
  5677. 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;
  5678. }
  5679. else {
  5680. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  5681. }
  5682. }
  5683. }
  5684. return true;
  5685. }
  5686. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_tensor * tensor, int tensor_idx, bool use_fence = true){
  5687. ggml_backend_buffer * buf = nullptr;
  5688. switch (tensor->op) {
  5689. case GGML_OP_ADD:
  5690. case GGML_OP_ACC:
  5691. case GGML_OP_GET_ROWS:
  5692. case GGML_OP_MUL:
  5693. case GGML_OP_DIV:
  5694. case GGML_OP_CONCAT:
  5695. case GGML_OP_UPSCALE:
  5696. case GGML_OP_SCALE:
  5697. case GGML_OP_SQR:
  5698. case GGML_OP_SIN:
  5699. case GGML_OP_COS:
  5700. case GGML_OP_CLAMP:
  5701. case GGML_OP_PAD:
  5702. case GGML_OP_CPY:
  5703. case GGML_OP_CONT:
  5704. case GGML_OP_DUP:
  5705. case GGML_OP_NORM:
  5706. case GGML_OP_GROUP_NORM:
  5707. case GGML_OP_RMS_NORM:
  5708. case GGML_OP_DIAG_MASK_INF:
  5709. case GGML_OP_SOFT_MAX:
  5710. case GGML_OP_ROPE:
  5711. case GGML_OP_RESHAPE:
  5712. case GGML_OP_VIEW:
  5713. case GGML_OP_PERMUTE:
  5714. case GGML_OP_TRANSPOSE:
  5715. case GGML_OP_NONE:
  5716. case GGML_OP_ARGSORT:
  5717. case GGML_OP_SUM_ROWS:
  5718. case GGML_OP_IM2COL:
  5719. case GGML_OP_TIMESTEP_EMBEDDING:
  5720. case GGML_OP_POOL_2D:
  5721. case GGML_OP_LEAKY_RELU:
  5722. case GGML_OP_REPEAT:
  5723. buf = tensor->buffer;
  5724. break;
  5725. case GGML_OP_UNARY:
  5726. switch (ggml_get_unary_op(tensor)) {
  5727. case GGML_UNARY_OP_SILU:
  5728. case GGML_UNARY_OP_GELU:
  5729. case GGML_UNARY_OP_GELU_QUICK:
  5730. case GGML_UNARY_OP_RELU:
  5731. case GGML_UNARY_OP_TANH:
  5732. buf = tensor->buffer;
  5733. break;
  5734. default:
  5735. return false;
  5736. }
  5737. break;
  5738. case GGML_OP_MUL_MAT:
  5739. case GGML_OP_MUL_MAT_ID:
  5740. case GGML_OP_FLASH_ATTN_EXT:
  5741. buf = tensor->buffer;
  5742. break;
  5743. default:
  5744. return false;
  5745. }
  5746. if (buf == nullptr) {
  5747. return false;
  5748. }
  5749. 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 << ")");
  5750. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  5751. // always wait for the GPU work to be done for the last submit
  5752. if (tensor_idx == subctx->exit_tensor_idx) {
  5753. use_fence = true;
  5754. }
  5755. // Only run if ctx hasn't been submitted yet
  5756. if (!subctx->seqs.empty()) {
  5757. #ifdef GGML_VULKAN_CHECK_RESULTS
  5758. ggml_vk_check_results_0(tensor);
  5759. use_fence = true;
  5760. #endif
  5761. // Do staging buffer copies
  5762. for (auto& cpy : subctx->in_memcpys) {
  5763. memcpy(cpy.dst, cpy.src, cpy.n);
  5764. }
  5765. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  5766. if (use_fence) {
  5767. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  5768. ctx->device->device.resetFences({ ctx->fence });
  5769. }
  5770. #ifdef GGML_VULKAN_CHECK_RESULTS
  5771. ggml_vk_check_results_1(tensor);
  5772. #endif
  5773. }
  5774. if (tensor_idx == subctx->exit_tensor_idx) {
  5775. // Do staging buffer copies
  5776. for (auto& cpy : subctx->out_memcpys) {
  5777. memcpy(cpy.dst, cpy.src, cpy.n);
  5778. }
  5779. subctx->in_memcpys.clear();
  5780. subctx->out_memcpys.clear();
  5781. }
  5782. return true;
  5783. }
  5784. // Clean up after graph processing is done
  5785. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  5786. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  5787. for (auto& buffer : ctx->gc.temp_buffers) {
  5788. ggml_vk_pool_free(ctx, buffer);
  5789. }
  5790. ctx->gc.temp_buffers.clear();
  5791. for (auto& dsr : ctx->device->pipeline_descriptor_set_requirements) {
  5792. vk_pipeline_ref plr = ctx->device->pipelines[dsr.first];
  5793. if (plr.expired()) {
  5794. continue;
  5795. }
  5796. vk_pipeline pl = plr.lock();
  5797. ggml_pipeline_cleanup(pl);
  5798. }
  5799. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5800. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5801. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  5802. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  5803. }
  5804. ctx->gc.semaphores.clear();
  5805. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  5806. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  5807. }
  5808. ctx->gc.tl_semaphores.clear();
  5809. ctx->semaphore_idx = 0;
  5810. ctx->event_idx = 0;
  5811. for (auto& event : ctx->gc.events) {
  5812. ctx->device->device.resetEvent(event);
  5813. }
  5814. ctx->tensor_ctxs.clear();
  5815. ctx->gc.contexts.clear();
  5816. ctx->device->pipeline_descriptor_set_requirements.clear();
  5817. }
  5818. // Clean up on backend free
  5819. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  5820. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  5821. ggml_vk_graph_cleanup(ctx);
  5822. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5823. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5824. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5825. for (auto& buffer : ctx->buffer_pool) {
  5826. ggml_vk_destroy_buffer(buffer);
  5827. }
  5828. ctx->prealloc_size_x = 0;
  5829. ctx->prealloc_size_y = 0;
  5830. ctx->prealloc_size_split_k = 0;
  5831. for (auto& event : ctx->gc.events) {
  5832. ctx->device->device.destroyEvent(event);
  5833. }
  5834. ctx->gc.events.clear();
  5835. ctx->device->device.destroyFence(ctx->fence);
  5836. }
  5837. static int ggml_vk_get_device_count() {
  5838. ggml_vk_instance_init();
  5839. return vk_instance.device_indices.size();
  5840. }
  5841. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  5842. ggml_vk_instance_init();
  5843. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  5844. vk::PhysicalDeviceProperties props;
  5845. devices[device].getProperties(&props);
  5846. snprintf(description, description_size, "%s", props.deviceName.data());
  5847. }
  5848. // backend interface
  5849. #define UNUSED GGML_UNUSED
  5850. // device backend
  5851. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  5852. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  5853. }
  5854. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  5855. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  5856. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5857. ggml_vk_destroy_buffer(ctx->dev_buffer);
  5858. delete ctx;
  5859. }
  5860. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  5861. return vk_ptr_base;
  5862. UNUSED(buffer);
  5863. }
  5864. static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  5865. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  5866. if (tensor->view_src != nullptr) {
  5867. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  5868. }
  5869. }
  5870. 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) {
  5871. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  5872. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5873. vk_buffer buf = buf_ctx->dev_buffer;
  5874. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  5875. }
  5876. 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) {
  5877. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  5878. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5879. vk_buffer buf = buf_ctx->dev_buffer;
  5880. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  5881. }
  5882. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  5883. if (ggml_backend_buffer_is_vk(src->buffer)) {
  5884. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  5885. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5886. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  5887. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  5888. 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));
  5889. return true;
  5890. }
  5891. return false;
  5892. UNUSED(buffer);
  5893. }
  5894. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  5895. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5896. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  5897. }
  5898. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  5899. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  5900. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  5901. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  5902. /* .memset_tensor = */ NULL,
  5903. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  5904. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  5905. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  5906. /* .clear = */ ggml_backend_vk_buffer_clear,
  5907. /* .reset = */ NULL,
  5908. };
  5909. // vk buffer type
  5910. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  5911. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  5912. return ctx->name.c_str();
  5913. }
  5914. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  5915. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  5916. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5917. vk_buffer dev_buffer = nullptr;
  5918. try {
  5919. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  5920. } catch (const vk::SystemError& e) {
  5921. return nullptr;
  5922. }
  5923. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  5924. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  5925. }
  5926. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  5927. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5928. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5929. }
  5930. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  5931. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5932. return ctx->device->max_memory_allocation_size;
  5933. }
  5934. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  5935. return ggml_nbytes(tensor);
  5936. UNUSED(buft);
  5937. }
  5938. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  5939. ggml_vk_instance_init();
  5940. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  5941. vk_device dev = ggml_vk_get_device(dev_num);
  5942. return &dev->buffer_type;
  5943. }
  5944. // host buffer type
  5945. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  5946. return GGML_VK_NAME "_Host";
  5947. UNUSED(buft);
  5948. }
  5949. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  5950. return GGML_VK_NAME "_Host";
  5951. UNUSED(buffer);
  5952. }
  5953. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  5954. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  5955. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  5956. }
  5957. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  5958. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  5959. size += 32; // Behave like the CPU buffer type
  5960. void * ptr = nullptr;
  5961. try {
  5962. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  5963. } catch (vk::SystemError& e) {
  5964. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  5965. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  5966. // fallback to cpu buffer
  5967. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  5968. }
  5969. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  5970. buffer->buft = buft;
  5971. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  5972. return buffer;
  5973. UNUSED(buft);
  5974. }
  5975. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  5976. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  5977. UNUSED(buft);
  5978. }
  5979. // Should be changed to return device-specific host buffer type
  5980. // but that probably requires changes in llama.cpp
  5981. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  5982. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  5983. /* .iface = */ {
  5984. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  5985. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  5986. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  5987. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  5988. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  5989. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  5990. },
  5991. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  5992. /* .context = */ nullptr,
  5993. };
  5994. // Make sure device 0 is initialized
  5995. ggml_vk_instance_init();
  5996. ggml_vk_get_device(0);
  5997. return &ggml_backend_vk_buffer_type_host;
  5998. }
  5999. // backend
  6000. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  6001. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6002. return ctx->name.c_str();
  6003. }
  6004. static void ggml_backend_vk_free(ggml_backend_t backend) {
  6005. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6006. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  6007. ggml_vk_cleanup(ctx);
  6008. delete ctx;
  6009. delete backend;
  6010. }
  6011. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  6012. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6013. return &ctx->device->buffer_type;
  6014. }
  6015. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  6016. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  6017. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6018. 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");
  6019. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6020. vk_context transfer_ctx;
  6021. if (ctx->transfer_ctx.expired()) {
  6022. // Initialize new transfer context
  6023. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6024. ctx->transfer_ctx = transfer_ctx;
  6025. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6026. } else {
  6027. transfer_ctx = ctx->transfer_ctx.lock();
  6028. }
  6029. vk_buffer buf = buf_ctx->dev_buffer;
  6030. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6031. }
  6032. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  6033. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  6034. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6035. 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");
  6036. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6037. vk_context transfer_ctx;
  6038. if (ctx->transfer_ctx.expired()) {
  6039. // Initialize new transfer context
  6040. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6041. ctx->transfer_ctx = transfer_ctx;
  6042. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6043. } else {
  6044. transfer_ctx = ctx->transfer_ctx.lock();
  6045. }
  6046. vk_buffer buf = buf_ctx->dev_buffer;
  6047. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6048. }
  6049. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  6050. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  6051. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6052. 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)) {
  6053. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6054. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6055. vk_context transfer_ctx;
  6056. if (ctx->transfer_ctx.expired()) {
  6057. // Initialize new transfer context
  6058. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6059. ctx->transfer_ctx = transfer_ctx;
  6060. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6061. } else {
  6062. transfer_ctx = ctx->transfer_ctx.lock();
  6063. }
  6064. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6065. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6066. 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));
  6067. return true;
  6068. }
  6069. return false;
  6070. }
  6071. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  6072. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  6073. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6074. if(ctx->transfer_ctx.expired()) {
  6075. return;
  6076. }
  6077. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  6078. ggml_vk_ctx_end(transfer_ctx);
  6079. for (auto& cpy : transfer_ctx->in_memcpys) {
  6080. memcpy(cpy.dst, cpy.src, cpy.n);
  6081. }
  6082. ggml_vk_submit(transfer_ctx, ctx->fence);
  6083. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  6084. ctx->device->device.resetFences({ ctx->fence });
  6085. for (auto& cpy : transfer_ctx->out_memcpys) {
  6086. memcpy(cpy.dst, cpy.src, cpy.n);
  6087. }
  6088. ctx->transfer_ctx.reset();
  6089. }
  6090. static bool ggml_vk_is_empty(ggml_tensor * node) {
  6091. 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;
  6092. }
  6093. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  6094. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  6095. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6096. for (int i = 0; i < cgraph->n_nodes; i++) {
  6097. ggml_vk_build_graph(ctx, cgraph->nodes[i], i, nullptr, 0, true, false, false);
  6098. }
  6099. ggml_vk_preallocate_buffers(ctx);
  6100. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  6101. int last_node = cgraph->n_nodes - 1;
  6102. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  6103. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  6104. last_node -= 1;
  6105. }
  6106. // Reserve tensor context space for all nodes
  6107. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  6108. bool first_node_in_batch = true; // true if next node will be first node in a batch
  6109. int submit_node_idx = 0; // index to first node in a batch
  6110. // Submit work every nodes_per_submit nodes to overlap CPU cmdbuffer generation with GPU execution.
  6111. // Start with a smaller count to get work submitted right away, and increase it after each submit.
  6112. int nodes_per_submit = 20;
  6113. int submitted_nodes = 0;
  6114. int submit_count = 0;
  6115. for (int i = 0; i < cgraph->n_nodes; i++) {
  6116. if (first_node_in_batch) {
  6117. submit_node_idx = i;
  6118. }
  6119. bool submit = (submitted_nodes >= nodes_per_submit) || (i == last_node);
  6120. bool enqueued = ggml_vk_build_graph(ctx, cgraph->nodes[i], i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i == last_node, submit);
  6121. if (enqueued) {
  6122. ++submitted_nodes;
  6123. #ifndef GGML_VULKAN_CHECK_RESULTS
  6124. if (first_node_in_batch) {
  6125. first_node_in_batch = false;
  6126. }
  6127. #endif
  6128. }
  6129. if (submit) {
  6130. first_node_in_batch = true;
  6131. submitted_nodes = 0;
  6132. switch (submit_count) {
  6133. case 0:
  6134. nodes_per_submit = 50;
  6135. break;
  6136. default:
  6137. nodes_per_submit = 100;
  6138. break;
  6139. }
  6140. submit_count++;
  6141. }
  6142. }
  6143. #ifdef GGML_VULKAN_PERF
  6144. ctx->device->perf_logger->print_timings();
  6145. #endif
  6146. ggml_vk_graph_cleanup(ctx);
  6147. return GGML_STATUS_SUCCESS;
  6148. UNUSED(backend);
  6149. }
  6150. // TODO: enable async and synchronize
  6151. static ggml_backend_i ggml_backend_vk_interface = {
  6152. /* .get_name = */ ggml_backend_vk_name,
  6153. /* .free = */ ggml_backend_vk_free,
  6154. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  6155. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  6156. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  6157. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  6158. /* .graph_plan_create = */ NULL,
  6159. /* .graph_plan_free = */ NULL,
  6160. /* .graph_plan_update = */ NULL,
  6161. /* .graph_plan_compute = */ NULL,
  6162. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  6163. /* .event_record = */ NULL,
  6164. /* .event_wait = */ NULL,
  6165. };
  6166. static ggml_guid_t ggml_backend_vk_guid() {
  6167. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  6168. return &guid;
  6169. }
  6170. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  6171. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  6172. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  6173. ggml_vk_init(ctx, dev_num);
  6174. ggml_backend_t vk_backend = new ggml_backend {
  6175. /* .guid = */ ggml_backend_vk_guid(),
  6176. /* .interface = */ ggml_backend_vk_interface,
  6177. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  6178. /* .context = */ ctx,
  6179. };
  6180. return vk_backend;
  6181. }
  6182. bool ggml_backend_is_vk(ggml_backend_t backend) {
  6183. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  6184. }
  6185. int ggml_backend_vk_get_device_count() {
  6186. return ggml_vk_get_device_count();
  6187. }
  6188. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  6189. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6190. int dev_idx = vk_instance.device_indices[device];
  6191. ggml_vk_get_device_description(dev_idx, description, description_size);
  6192. }
  6193. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  6194. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6195. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  6196. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  6197. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  6198. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  6199. *total = heap.size;
  6200. *free = heap.size;
  6201. break;
  6202. }
  6203. }
  6204. }
  6205. //////////////////////////
  6206. struct ggml_backend_vk_device_context {
  6207. size_t device;
  6208. std::string name;
  6209. std::string description;
  6210. };
  6211. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  6212. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6213. return ctx->name.c_str();
  6214. }
  6215. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  6216. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6217. return ctx->description.c_str();
  6218. }
  6219. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  6220. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  6221. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  6222. }
  6223. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  6224. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6225. return ggml_backend_vk_buffer_type(ctx->device);
  6226. }
  6227. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  6228. UNUSED(dev);
  6229. return ggml_backend_vk_host_buffer_type();
  6230. }
  6231. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  6232. UNUSED(dev);
  6233. return GGML_BACKEND_DEVICE_TYPE_GPU;
  6234. }
  6235. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  6236. props->name = ggml_backend_vk_device_get_name(dev);
  6237. props->description = ggml_backend_vk_device_get_description(dev);
  6238. props->type = ggml_backend_vk_device_get_type(dev);
  6239. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  6240. props->caps = {
  6241. /* .async = */ false,
  6242. /* .host_buffer = */ true,
  6243. /* .buffer_from_host_ptr = */ false,
  6244. /* .events = */ false,
  6245. };
  6246. }
  6247. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  6248. UNUSED(params);
  6249. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6250. return ggml_backend_vk_init(ctx->device);
  6251. }
  6252. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6253. switch (op->op) {
  6254. case GGML_OP_UNARY:
  6255. switch (ggml_get_unary_op(op)) {
  6256. case GGML_UNARY_OP_GELU:
  6257. case GGML_UNARY_OP_GELU_QUICK:
  6258. case GGML_UNARY_OP_SILU:
  6259. case GGML_UNARY_OP_RELU:
  6260. case GGML_UNARY_OP_TANH:
  6261. return ggml_is_contiguous(op->src[0]);
  6262. default:
  6263. return false;
  6264. }
  6265. break;
  6266. case GGML_OP_MUL_MAT:
  6267. case GGML_OP_MUL_MAT_ID:
  6268. {
  6269. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6270. const vk_device& device = ggml_vk_get_device(ctx->device);
  6271. if (op->op == GGML_OP_MUL_MAT_ID && !device->mul_mat_id_s && !device->mul_mat_id_m && !device->mul_mat_id_l) {
  6272. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  6273. return false;
  6274. }
  6275. switch (op->src[0]->type) {
  6276. case GGML_TYPE_F32:
  6277. case GGML_TYPE_F16:
  6278. case GGML_TYPE_Q4_0:
  6279. case GGML_TYPE_Q4_1:
  6280. case GGML_TYPE_Q5_0:
  6281. case GGML_TYPE_Q5_1:
  6282. case GGML_TYPE_Q8_0:
  6283. case GGML_TYPE_Q2_K:
  6284. case GGML_TYPE_Q3_K:
  6285. case GGML_TYPE_Q4_K:
  6286. case GGML_TYPE_Q5_K:
  6287. case GGML_TYPE_Q6_K:
  6288. case GGML_TYPE_IQ4_NL:
  6289. break;
  6290. default:
  6291. return false;
  6292. }
  6293. struct ggml_tensor * a;
  6294. struct ggml_tensor * b;
  6295. if (op->op == GGML_OP_MUL_MAT) {
  6296. a = op->src[0];
  6297. b = op->src[1];
  6298. } else {
  6299. a = op->src[2];
  6300. b = op->src[1];
  6301. }
  6302. if (a->ne[3] != b->ne[3]) {
  6303. return false;
  6304. }
  6305. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) ||
  6306. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  6307. return false;
  6308. }
  6309. return true;
  6310. } break;
  6311. case GGML_OP_FLASH_ATTN_EXT:
  6312. {
  6313. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6314. if (!ggml_vk_get_device(ctx->device)->coopmat2) {
  6315. return false;
  6316. }
  6317. switch (op->src[0]->ne[0]) {
  6318. case 64:
  6319. case 80:
  6320. case 96:
  6321. case 112:
  6322. case 128:
  6323. case 256:
  6324. break;
  6325. default:
  6326. return false;
  6327. }
  6328. if (op->src[0]->type != GGML_TYPE_F32) {
  6329. return false;
  6330. }
  6331. if (op->type != GGML_TYPE_F32) {
  6332. return false;
  6333. }
  6334. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  6335. return false;
  6336. }
  6337. // It's straightforward to support different K/V dequant, but would
  6338. // significantly increase the number of pipelines
  6339. if (op->src[1]->type != op->src[2]->type) {
  6340. return false;
  6341. }
  6342. switch (op->src[1]->type) {
  6343. case GGML_TYPE_F16:
  6344. case GGML_TYPE_Q4_0:
  6345. case GGML_TYPE_Q4_1:
  6346. case GGML_TYPE_Q5_0:
  6347. case GGML_TYPE_Q5_1:
  6348. case GGML_TYPE_Q8_0:
  6349. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  6350. //case GGML_TYPE_Q2_K:
  6351. //case GGML_TYPE_Q3_K:
  6352. //case GGML_TYPE_Q4_K:
  6353. //case GGML_TYPE_Q5_K:
  6354. //case GGML_TYPE_Q6_K:
  6355. case GGML_TYPE_IQ4_NL:
  6356. break;
  6357. default:
  6358. return false;
  6359. }
  6360. return true;
  6361. }
  6362. case GGML_OP_GET_ROWS:
  6363. {
  6364. switch (op->src[0]->type) {
  6365. case GGML_TYPE_F32:
  6366. case GGML_TYPE_F16:
  6367. case GGML_TYPE_Q4_0:
  6368. case GGML_TYPE_Q4_1:
  6369. case GGML_TYPE_Q5_0:
  6370. case GGML_TYPE_Q5_1:
  6371. case GGML_TYPE_Q8_0:
  6372. case GGML_TYPE_IQ4_NL:
  6373. return true;
  6374. default:
  6375. return false;
  6376. }
  6377. } break;
  6378. case GGML_OP_CONT:
  6379. case GGML_OP_CPY:
  6380. case GGML_OP_DUP:
  6381. {
  6382. ggml_type src0_type = op->src[0]->type;
  6383. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  6384. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  6385. return true;
  6386. }
  6387. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  6388. return true;
  6389. }
  6390. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  6391. return true;
  6392. }
  6393. return false;
  6394. } break;
  6395. case GGML_OP_REPEAT:
  6396. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  6397. case GGML_OP_ROPE:
  6398. return ggml_is_contiguous(op->src[0]);
  6399. case GGML_OP_NONE:
  6400. case GGML_OP_RESHAPE:
  6401. case GGML_OP_VIEW:
  6402. case GGML_OP_PERMUTE:
  6403. case GGML_OP_TRANSPOSE:
  6404. case GGML_OP_NORM:
  6405. case GGML_OP_GROUP_NORM:
  6406. case GGML_OP_RMS_NORM:
  6407. case GGML_OP_ADD:
  6408. case GGML_OP_ACC:
  6409. case GGML_OP_MUL:
  6410. case GGML_OP_DIV:
  6411. case GGML_OP_CONCAT:
  6412. case GGML_OP_UPSCALE:
  6413. case GGML_OP_SCALE:
  6414. case GGML_OP_SQR:
  6415. case GGML_OP_SIN:
  6416. case GGML_OP_COS:
  6417. case GGML_OP_CLAMP:
  6418. case GGML_OP_PAD:
  6419. case GGML_OP_DIAG_MASK_INF:
  6420. case GGML_OP_SOFT_MAX:
  6421. case GGML_OP_ARGSORT:
  6422. case GGML_OP_SUM_ROWS:
  6423. case GGML_OP_IM2COL:
  6424. case GGML_OP_TIMESTEP_EMBEDDING:
  6425. case GGML_OP_POOL_2D:
  6426. case GGML_OP_LEAKY_RELU:
  6427. return true;
  6428. default:
  6429. return false;
  6430. }
  6431. UNUSED(dev);
  6432. }
  6433. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  6434. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  6435. return false;
  6436. }
  6437. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6438. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6439. return buft_ctx->device->idx == ctx->device;
  6440. }
  6441. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6442. const int min_batch_size = 32;
  6443. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  6444. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  6445. UNUSED(dev);
  6446. }
  6447. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  6448. /* .get_name = */ ggml_backend_vk_device_get_name,
  6449. /* .get_description = */ ggml_backend_vk_device_get_description,
  6450. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  6451. /* .get_type = */ ggml_backend_vk_device_get_type,
  6452. /* .get_props = */ ggml_backend_vk_device_get_props,
  6453. /* .init_backend = */ ggml_backend_vk_device_init,
  6454. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  6455. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  6456. /* .buffer_from_host_ptr = */ NULL,
  6457. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  6458. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  6459. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  6460. /* .event_new = */ NULL,
  6461. /* .event_free = */ NULL,
  6462. /* .event_synchronize = */ NULL,
  6463. };
  6464. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  6465. UNUSED(reg);
  6466. return GGML_VK_NAME;
  6467. }
  6468. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  6469. UNUSED(reg);
  6470. return ggml_backend_vk_get_device_count();
  6471. }
  6472. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  6473. static std::vector<ggml_backend_dev_t> devices;
  6474. static bool initialized = false;
  6475. {
  6476. static std::mutex mutex;
  6477. std::lock_guard<std::mutex> lock(mutex);
  6478. if (!initialized) {
  6479. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  6480. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  6481. char desc[256];
  6482. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  6483. ctx->device = i;
  6484. ctx->name = GGML_VK_NAME + std::to_string(i);
  6485. ctx->description = desc;
  6486. devices.push_back(new ggml_backend_device {
  6487. /* .iface = */ ggml_backend_vk_device_i,
  6488. /* .reg = */ reg,
  6489. /* .context = */ ctx,
  6490. });
  6491. }
  6492. initialized = true;
  6493. }
  6494. }
  6495. GGML_ASSERT(device < devices.size());
  6496. return devices[device];
  6497. }
  6498. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  6499. /* .get_name = */ ggml_backend_vk_reg_get_name,
  6500. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  6501. /* .get_device = */ ggml_backend_vk_reg_get_device,
  6502. /* .get_proc_address = */ NULL,
  6503. };
  6504. ggml_backend_reg_t ggml_backend_vk_reg() {
  6505. static ggml_backend_reg reg = {
  6506. /* .api_version = */ GGML_BACKEND_API_VERSION,
  6507. /* .iface = */ ggml_backend_vk_reg_i,
  6508. /* .context = */ nullptr,
  6509. };
  6510. return &reg;
  6511. }
  6512. // Extension availability
  6513. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6514. #ifdef GGML_VULKAN_VALIDATE
  6515. bool portability_enumeration_ext = false;
  6516. // Check for portability enumeration extension for MoltenVK support
  6517. for (const auto& properties : instance_extensions) {
  6518. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6519. return true;
  6520. }
  6521. }
  6522. if (!portability_enumeration_ext) {
  6523. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6524. }
  6525. #endif
  6526. return false;
  6527. UNUSED(instance_extensions);
  6528. }
  6529. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6530. #ifdef __APPLE__
  6531. bool portability_enumeration_ext = false;
  6532. // Check for portability enumeration extension for MoltenVK support
  6533. for (const auto& properties : instance_extensions) {
  6534. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6535. return true;
  6536. }
  6537. }
  6538. if (!portability_enumeration_ext) {
  6539. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6540. }
  6541. #endif
  6542. return false;
  6543. UNUSED(instance_extensions);
  6544. }
  6545. // checks
  6546. #ifdef GGML_VULKAN_CHECK_RESULTS
  6547. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  6548. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  6549. return;
  6550. }
  6551. for (int j = 0; j < level; j++) {
  6552. std::cerr << " ";
  6553. }
  6554. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  6555. done.push_back(tensor);
  6556. for (int i = 0; i < GGML_MAX_SRC; i++) {
  6557. if (tensor->src[i] != nullptr) {
  6558. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  6559. }
  6560. }
  6561. }
  6562. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  6563. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  6564. return;
  6565. }
  6566. i0 = std::max(i0, 5);
  6567. i1 = std::max(i1, 5);
  6568. i2 = std::max(i2, 0);
  6569. i3 = std::max(i3, 0);
  6570. fprintf(stderr, " ");
  6571. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6572. fprintf(stderr, "%7d ", idx1);
  6573. }
  6574. fprintf(stderr, "\n");
  6575. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  6576. fprintf(stderr, "%7d: ", idx0);
  6577. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6578. 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]) {
  6579. float val;
  6580. if (tensor->type == GGML_TYPE_F32) {
  6581. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  6582. } else if (tensor->type == GGML_TYPE_F16) {
  6583. 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]));
  6584. } else if (tensor->type == GGML_TYPE_I32) {
  6585. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  6586. } else {
  6587. GGML_ABORT("fatal error");
  6588. }
  6589. fprintf(stderr, "% 7.2f ", val);
  6590. } else {
  6591. fprintf(stderr, " ");
  6592. }
  6593. }
  6594. fprintf(stderr, "\n");
  6595. }
  6596. }
  6597. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  6598. void * tensor_data = tensor->data;
  6599. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  6600. if (is_gpu) {
  6601. const size_t tensor_size = ggml_nbytes(tensor);
  6602. tensor_data = malloc(tensor_size);
  6603. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6604. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  6605. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  6606. }
  6607. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  6608. 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;
  6609. if (tensor->src[0] != nullptr) {
  6610. 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;
  6611. }
  6612. if (tensor->src[1] != nullptr) {
  6613. 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;
  6614. }
  6615. std::cerr << std::endl << "Result:" << std::endl;
  6616. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  6617. std::cerr << std::endl;
  6618. std::vector<const ggml_tensor *> done;
  6619. ggml_vk_print_graph_origin(tensor, done);
  6620. if (is_gpu) {
  6621. free(tensor_data);
  6622. }
  6623. }
  6624. void * comp_result;
  6625. size_t comp_size;
  6626. size_t comp_nb[GGML_MAX_DIMS];
  6627. size_t check_counter = 0;
  6628. static void ggml_vk_check_results_0(ggml_tensor * tensor) {
  6629. if (tensor->op == GGML_OP_TRANSPOSE) {
  6630. return;
  6631. }
  6632. check_counter++;
  6633. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  6634. return;
  6635. }
  6636. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  6637. ggml_tensor * src0 = tensor->src[0];
  6638. ggml_tensor * src1 = tensor->src[1];
  6639. ggml_tensor * src2 = tensor->src[2];
  6640. ggml_tensor * src3 = tensor->src[3];
  6641. struct ggml_init_params iparams = {
  6642. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  6643. /*.mem_buffer =*/ NULL,
  6644. /*.no_alloc =*/ false,
  6645. };
  6646. struct ggml_context * ggml_ctx = ggml_init(iparams);
  6647. struct ggml_tensor * src0_clone = nullptr;
  6648. struct ggml_tensor * src1_clone = nullptr;
  6649. struct ggml_tensor * src2_clone = nullptr;
  6650. struct ggml_tensor * src3_clone = nullptr;
  6651. struct ggml_tensor * tensor_clone = nullptr;
  6652. size_t src0_size;
  6653. size_t src1_size;
  6654. size_t src2_size;
  6655. size_t src3_size;
  6656. void * src0_buffer = nullptr;
  6657. void * src1_buffer = nullptr;
  6658. void * src2_buffer = nullptr;
  6659. void * src3_buffer = nullptr;
  6660. if (src0 != nullptr) {
  6661. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  6662. src0_size = ggml_nbytes(src0);
  6663. src0_buffer = malloc(src0_size);
  6664. src0_clone->data = src0_buffer;
  6665. if (ggml_backend_buffer_is_host(src0->buffer)) {
  6666. memcpy(src0_clone->data, src0->data, src0_size);
  6667. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6668. } else if (ggml_backend_buffer_is_vk(src0->buffer)) {
  6669. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6670. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6671. uint64_t offset = vk_tensor_offset(src0) + src0->view_offs;
  6672. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  6673. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  6674. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  6675. const int idx = i3*src0->ne[2] + i2;
  6676. ggml_vk_buffer_read(buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  6677. }
  6678. }
  6679. src0_clone->nb[0] = src0->nb[0];
  6680. src0_clone->nb[1] = src0->nb[1];
  6681. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6682. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  6683. }
  6684. } else {
  6685. if (offset + src0_size >= buffer_gpu->size) {
  6686. src0_size = buffer_gpu->size - offset;
  6687. }
  6688. ggml_vk_buffer_read(buffer_gpu, offset, src0_clone->data, src0_size);
  6689. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6690. }
  6691. } else {
  6692. GGML_ABORT("fatal error");
  6693. }
  6694. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6695. ggml_vk_print_tensor(src0, "src0");
  6696. }
  6697. }
  6698. if (src1 != nullptr) {
  6699. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  6700. src1_size = ggml_nbytes(src1);
  6701. src1_buffer = malloc(src1_size);
  6702. src1_clone->data = src1_buffer;
  6703. if (ggml_backend_buffer_is_host(src1->buffer)) {
  6704. memcpy(src1_clone->data, src1->data, src1_size);
  6705. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6706. } else if (ggml_backend_buffer_is_vk(src1->buffer)) {
  6707. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6708. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6709. uint64_t offset = vk_tensor_offset(src1) + src1->view_offs;
  6710. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  6711. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  6712. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  6713. const int idx = i3*src1->ne[2] + i2;
  6714. ggml_vk_buffer_read(buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  6715. }
  6716. }
  6717. src1_clone->nb[0] = src1->nb[0];
  6718. src1_clone->nb[1] = src1->nb[1];
  6719. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6720. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  6721. }
  6722. } else {
  6723. if (offset + src1_size >= buffer_gpu->size) {
  6724. src1_size = buffer_gpu->size - offset;
  6725. }
  6726. ggml_vk_buffer_read(buffer_gpu, offset, src1_clone->data, src1_size);
  6727. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6728. }
  6729. } else {
  6730. GGML_ABORT("fatal error");
  6731. }
  6732. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6733. ggml_vk_print_tensor(src1, "src1");
  6734. }
  6735. }
  6736. if (src2 != nullptr) {
  6737. src2_clone = ggml_dup_tensor(ggml_ctx, src2);
  6738. src2_size = ggml_nbytes(src2);
  6739. src2_buffer = malloc(src2_size);
  6740. src2_clone->data = src2_buffer;
  6741. if (ggml_backend_buffer_is_host(src2->buffer)) {
  6742. memcpy(src2_clone->data, src2->data, src2_size);
  6743. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6744. } else if (ggml_backend_buffer_is_vk(src2->buffer)) {
  6745. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src2->buffer->context;
  6746. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6747. uint64_t offset = vk_tensor_offset(src2) + src2->view_offs;
  6748. if (!ggml_is_contiguous(src2) && ggml_vk_dim01_contiguous(src2)) {
  6749. for (int i3 = 0; i3 < src2->ne[3]; i3++) {
  6750. for (int i2 = 0; i2 < src2->ne[2]; i2++) {
  6751. const int idx = i3*src2->ne[2] + i2;
  6752. ggml_vk_buffer_read(buffer_gpu, offset + idx * src2->nb[2], ((char *)src2_clone->data + idx * src2_clone->nb[2]), src2->ne[1] * src2->nb[1]);
  6753. }
  6754. }
  6755. src2_clone->nb[0] = src2->nb[0];
  6756. src2_clone->nb[1] = src2->nb[1];
  6757. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6758. src2_clone->nb[i] = src2_clone->nb[i - 1]*src2_clone->ne[i - 1];
  6759. }
  6760. } else {
  6761. if (offset + src2_size >= buffer_gpu->size) {
  6762. src2_size = buffer_gpu->size - offset;
  6763. }
  6764. ggml_vk_buffer_read(buffer_gpu, offset, src2_clone->data, src2_size);
  6765. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6766. }
  6767. } else {
  6768. GGML_ABORT("fatal error");
  6769. }
  6770. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6771. ggml_vk_print_tensor(src2, "src2");
  6772. }
  6773. }
  6774. if (src3 != nullptr) {
  6775. src3_clone = ggml_dup_tensor(ggml_ctx, src3);
  6776. src3_size = ggml_nbytes(src3);
  6777. src3_buffer = malloc(src3_size);
  6778. src3_clone->data = src3_buffer;
  6779. if (ggml_backend_buffer_is_host(src3->buffer)) {
  6780. memcpy(src3_clone->data, src3->data, src3_size);
  6781. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6782. } else if (ggml_backend_buffer_is_vk(src3->buffer)) {
  6783. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src3->buffer->context;
  6784. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6785. uint64_t offset = vk_tensor_offset(src3) + src3->view_offs;
  6786. if (!ggml_is_contiguous(src3) && ggml_vk_dim01_contiguous(src3)) {
  6787. for (int i3 = 0; i3 < src3->ne[3]; i3++) {
  6788. for (int i2 = 0; i2 < src3->ne[2]; i2++) {
  6789. const int idx = i3*src3->ne[2] + i2;
  6790. ggml_vk_buffer_read(buffer_gpu, offset + idx * src3->nb[2], ((char *)src3_clone->data + idx * src3_clone->nb[2]), src3->ne[1] * src3->nb[1]);
  6791. }
  6792. }
  6793. src3_clone->nb[0] = src3->nb[0];
  6794. src3_clone->nb[1] = src3->nb[1];
  6795. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6796. src3_clone->nb[i] = src3_clone->nb[i - 1]*src3_clone->ne[i - 1];
  6797. }
  6798. } else {
  6799. if (offset + src3_size >= buffer_gpu->size) {
  6800. src3_size = buffer_gpu->size - offset;
  6801. }
  6802. ggml_vk_buffer_read(buffer_gpu, offset, src3_clone->data, src3_size);
  6803. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6804. }
  6805. } else {
  6806. GGML_ABORT("fatal error");
  6807. }
  6808. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6809. ggml_vk_print_tensor(src3, "src3");
  6810. }
  6811. }
  6812. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  6813. const float *params = (const float *)tensor->op_params;
  6814. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, src3_clone, params[0], params[1], params[2]);
  6815. } else if (tensor->op == GGML_OP_MUL_MAT) {
  6816. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  6817. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  6818. tensor_clone = ggml_mul_mat_id(ggml_ctx, src0_clone, src1_clone, src2_clone);
  6819. } else if (tensor->op == GGML_OP_MUL) {
  6820. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  6821. } else if (tensor->op == GGML_OP_DIV) {
  6822. tensor_clone = ggml_div(ggml_ctx, src0_clone, src1_clone);
  6823. } else if (tensor->op == GGML_OP_CONCAT) {
  6824. tensor_clone = ggml_concat(ggml_ctx, src0_clone, src1_clone, *(int *)tensor->op_params);
  6825. } else if (tensor->op == GGML_OP_UPSCALE) {
  6826. tensor_clone = ggml_upscale_ext(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6827. } else if (tensor->op == GGML_OP_SCALE) {
  6828. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  6829. } else if (tensor->op == GGML_OP_SQR) {
  6830. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  6831. } else if (tensor->op == GGML_OP_SIN) {
  6832. tensor_clone = ggml_sin(ggml_ctx, src0_clone);
  6833. } else if (tensor->op == GGML_OP_COS) {
  6834. tensor_clone = ggml_cos(ggml_ctx, src0_clone);
  6835. } else if (tensor->op == GGML_OP_CLAMP) {
  6836. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  6837. } else if (tensor->op == GGML_OP_PAD) {
  6838. tensor_clone = ggml_pad(ggml_ctx, src0_clone, tensor->ne[0] - src0_clone->ne[0], tensor->ne[1] - src0_clone->ne[1], tensor->ne[2] - src0_clone->ne[2], tensor->ne[3] - src0_clone->ne[3]);
  6839. } else if (tensor->op == GGML_OP_REPEAT) {
  6840. tensor_clone = ggml_repeat(ggml_ctx, src0_clone, tensor);
  6841. } else if (tensor->op == GGML_OP_ADD) {
  6842. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  6843. } else if (tensor->op == GGML_OP_ACC) {
  6844. tensor_clone = ggml_acc(ggml_ctx, src0_clone, src1_clone, tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  6845. } else if (tensor->op == GGML_OP_NORM) {
  6846. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  6847. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  6848. tensor_clone = ggml_group_norm(ggml_ctx, src0_clone, *(int *)tensor->op_params, ((float *)tensor->op_params)[1]);
  6849. } else if (tensor->op == GGML_OP_RMS_NORM) {
  6850. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  6851. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  6852. if (src1 != nullptr) {
  6853. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  6854. } else {
  6855. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  6856. }
  6857. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  6858. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(int *)tensor->op_params);
  6859. } else if (tensor->op == GGML_OP_ROPE) {
  6860. const int n_dims = ((int32_t *) tensor->op_params)[1];
  6861. const int mode = ((int32_t *) tensor->op_params)[2];
  6862. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  6863. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  6864. const float freq_base = ((float *) tensor->op_params)[5];
  6865. const float freq_scale = ((float *) tensor->op_params)[6];
  6866. const float ext_factor = ((float *) tensor->op_params)[7];
  6867. const float attn_factor = ((float *) tensor->op_params)[8];
  6868. const float beta_fast = ((float *) tensor->op_params)[9];
  6869. const float beta_slow = ((float *) tensor->op_params)[10];
  6870. tensor_clone = ggml_rope_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  6871. } else if (tensor->op == GGML_OP_UNARY) {
  6872. switch (ggml_get_unary_op(tensor)) {
  6873. case GGML_UNARY_OP_SILU:
  6874. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  6875. break;
  6876. case GGML_UNARY_OP_GELU:
  6877. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  6878. break;
  6879. case GGML_UNARY_OP_GELU_QUICK:
  6880. tensor_clone = ggml_gelu_quick(ggml_ctx, src0_clone);
  6881. break;
  6882. case GGML_UNARY_OP_RELU:
  6883. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  6884. break;
  6885. case GGML_UNARY_OP_TANH:
  6886. tensor_clone = ggml_tanh(ggml_ctx, src0_clone);
  6887. break;
  6888. default:
  6889. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  6890. GGML_ABORT("fatal error");
  6891. }
  6892. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  6893. if (src1 == nullptr) {
  6894. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  6895. tensor_clone->type = tensor->type;
  6896. } else {
  6897. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  6898. }
  6899. } else if (tensor->op == GGML_OP_CONT) {
  6900. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6901. } else if (tensor->op == GGML_OP_RESHAPE) {
  6902. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6903. } else if (tensor->op == GGML_OP_VIEW) {
  6904. tensor_clone = ggml_view_4d(ggml_ctx, src0_clone, 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]);
  6905. } else if (tensor->op == GGML_OP_PERMUTE) {
  6906. int32_t * params = (int32_t *)tensor->op_params;
  6907. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  6908. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  6909. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  6910. } else if (tensor->op == GGML_OP_GET_ROWS) {
  6911. tensor_clone = ggml_get_rows(ggml_ctx, src0_clone, src1_clone);
  6912. } else if (tensor->op == GGML_OP_ARGSORT) {
  6913. tensor_clone = ggml_argsort(ggml_ctx, src0_clone, (ggml_sort_order) *(int *)tensor->op_params);
  6914. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  6915. tensor_clone = ggml_sum_rows(ggml_ctx, src0_clone);
  6916. } else if (tensor->op == GGML_OP_IM2COL) {
  6917. const int32_t s0 = tensor->op_params[0];
  6918. const int32_t s1 = tensor->op_params[1];
  6919. const int32_t p0 = tensor->op_params[2];
  6920. const int32_t p1 = tensor->op_params[3];
  6921. const int32_t d0 = tensor->op_params[4];
  6922. const int32_t d1 = tensor->op_params[5];
  6923. const bool is_2D = tensor->op_params[6] == 1;
  6924. tensor_clone = ggml_im2col(ggml_ctx, src0_clone, src1_clone, s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  6925. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  6926. const int32_t dim = tensor->op_params[0];
  6927. const int32_t max_period = tensor->op_params[1];
  6928. tensor_clone = ggml_timestep_embedding(ggml_ctx, src0_clone, dim, max_period);
  6929. } else if (tensor->op == GGML_OP_POOL_2D) {
  6930. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  6931. const int32_t k0 = tensor->op_params[1];
  6932. const int32_t k1 = tensor->op_params[2];
  6933. const int32_t s0 = tensor->op_params[3];
  6934. const int32_t s1 = tensor->op_params[4];
  6935. const int32_t p0 = tensor->op_params[5];
  6936. const int32_t p1 = tensor->op_params[6];
  6937. tensor_clone = ggml_pool_2d(ggml_ctx, src0_clone, op, k0, k1, s0, s1, p0, p1);
  6938. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  6939. const float * op_params = (const float *)tensor->op_params;
  6940. tensor_clone = ggml_leaky_relu(ggml_ctx, src0_clone, op_params[0], false);
  6941. } else {
  6942. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  6943. GGML_ABORT("fatal error");
  6944. }
  6945. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  6946. ggml_build_forward_expand(cgraph, tensor_clone);
  6947. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  6948. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6949. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  6950. }
  6951. comp_size = ggml_nbytes(tensor_clone);
  6952. comp_result = malloc(comp_size);
  6953. memcpy(comp_result, tensor_clone->data, comp_size);
  6954. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6955. if (src0 != nullptr) {
  6956. free(src0_buffer);
  6957. }
  6958. if (src1 != nullptr) {
  6959. free(src1_buffer);
  6960. }
  6961. ggml_free(ggml_ctx);
  6962. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  6963. }
  6964. static void ggml_vk_check_results_1(ggml_tensor * tensor) {
  6965. if (tensor->op == GGML_OP_TRANSPOSE) {
  6966. return;
  6967. }
  6968. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  6969. return;
  6970. }
  6971. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  6972. ggml_tensor * src0 = tensor->src[0];
  6973. ggml_tensor * src1 = tensor->src[1];
  6974. ggml_tensor * src2 = tensor->src[2];
  6975. void * tensor_data = tensor->data;
  6976. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  6977. size_t tensor_size = ggml_nbytes(tensor);
  6978. tensor_data = malloc(tensor_size);
  6979. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6980. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6981. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  6982. if (offset + tensor_size >= buffer_gpu->size) {
  6983. tensor_size = buffer_gpu->size - offset;
  6984. }
  6985. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  6986. }
  6987. float first_error_result = -1.0f;
  6988. float first_error_correct = -1.0f;
  6989. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  6990. double avg_err = 0.0;
  6991. size_t counter = 0;
  6992. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  6993. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  6994. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  6995. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  6996. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  6997. float correct = 0.0f;
  6998. float result = 0.0f;
  6999. if (buffer_size_fit) {
  7000. if (tensor->type == GGML_TYPE_F32) {
  7001. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7002. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7003. } else if (tensor->type == GGML_TYPE_F16) {
  7004. 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]));
  7005. 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]));
  7006. } else if (tensor->type == GGML_TYPE_I32) {
  7007. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7008. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7009. } else {
  7010. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  7011. }
  7012. } else {
  7013. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  7014. GGML_ABORT("fatal error");
  7015. }
  7016. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  7017. 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;
  7018. 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;
  7019. if (src0 != nullptr) {
  7020. 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;
  7021. }
  7022. if (src1 != nullptr) {
  7023. 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;
  7024. }
  7025. if (src2 != nullptr) {
  7026. 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;
  7027. }
  7028. 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;
  7029. std::cerr << std::endl << "Result:" << std::endl;
  7030. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  7031. std::cerr << std::endl << "Correct:" << std::endl;
  7032. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  7033. std::cerr << std::endl;
  7034. std::vector<const ggml_tensor *> done;
  7035. ggml_vk_print_graph_origin(tensor, done);
  7036. GGML_ABORT("fatal error");
  7037. }
  7038. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  7039. first_error[0] = i0;
  7040. first_error[1] = i1;
  7041. first_error[2] = i2;
  7042. first_error[3] = i3;
  7043. first_error_result = result;
  7044. first_error_correct = correct;
  7045. }
  7046. // Special case, value is infinite, avoid NaN result in avg_err
  7047. // NaN also appears in results, if both are nan error is 0
  7048. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  7049. avg_err += std::fabs(correct - result);
  7050. }
  7051. counter++;
  7052. }
  7053. }
  7054. }
  7055. }
  7056. avg_err /= counter;
  7057. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7058. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7059. 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;
  7060. if (src0 != nullptr) {
  7061. 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;
  7062. }
  7063. if (src1 != nullptr) {
  7064. 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;
  7065. }
  7066. if (src2 != nullptr) {
  7067. 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;
  7068. }
  7069. 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;
  7070. std::cerr << std::endl << "Result:" << std::endl;
  7071. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7072. std::cerr << std::endl << "Correct:" << std::endl;
  7073. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  7074. std::cerr << std::endl;
  7075. std::vector<const ggml_tensor *> done;
  7076. ggml_vk_print_graph_origin(tensor, done);
  7077. }
  7078. if (avg_err > 0.05 || std::isnan(avg_err)) {
  7079. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7080. 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;
  7081. if (src0 != nullptr) {
  7082. 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;
  7083. }
  7084. if (src1 != nullptr) {
  7085. 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;
  7086. }
  7087. if (src2 != nullptr) {
  7088. 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;
  7089. }
  7090. 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;
  7091. std::cerr << std::endl << "Result:" << std::endl;
  7092. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  7093. std::cerr << std::endl << "Correct:" << std::endl;
  7094. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  7095. std::cerr << std::endl;
  7096. std::vector<const ggml_tensor *> done;
  7097. ggml_vk_print_graph_origin(tensor, done);
  7098. GGML_ABORT("fatal error");
  7099. } else {
  7100. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  7101. }
  7102. free(comp_result);
  7103. comp_result = nullptr;
  7104. comp_size = 0;
  7105. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7106. free(tensor_data);
  7107. }
  7108. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  7109. }
  7110. #endif
  7111. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)