ggml-vulkan.cpp 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828
  1. #include "ggml-vulkan.h"
  2. #ifdef GGML_VULKAN_RUN_TESTS
  3. #include <chrono>
  4. #endif
  5. #include <vulkan/vulkan.hpp>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <iostream>
  9. #include <iomanip>
  10. #include <limits>
  11. #include <tuple>
  12. #include <vector>
  13. #include <sstream>
  14. #include <utility>
  15. #include <memory>
  16. #include "ggml.h"
  17. #include "ggml-backend-impl.h"
  18. #include "ggml-vulkan-shaders.hpp"
  19. #define VK_API_VERSION VK_API_VERSION_1_2
  20. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  21. #define VK_VENDOR_ID_AMD 0x1002
  22. #define VK_VENDOR_ID_APPLE 0x106b
  23. #define VK_VENDOR_ID_INTEL 0x8086
  24. #define VK_VENDOR_ID_NVIDIA 0x10de
  25. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN 0
  26. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI 1
  27. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_SINGLE 2
  28. #define VK_NUM_TYPES 16
  29. #define GGML_VK_MAX_NODES 8192
  30. #define MAX_VK_BUFFERS 256
  31. #ifndef K_QUANTS_PER_ITERATION
  32. #define K_QUANTS_PER_ITERATION 1
  33. #else
  34. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  35. #endif
  36. #define VK_CHECK(err, msg) \
  37. do { \
  38. vk::Result err_ = (err); \
  39. if (err_ != vk::Result::eSuccess) { \
  40. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  41. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  42. exit(1); \
  43. } \
  44. } while (0)
  45. struct ggml_backend_vk_context;
  46. struct vk_queue {
  47. uint32_t queue_family_index;
  48. vk::Queue queue;
  49. vk::CommandPool pool;
  50. uint32_t cmd_buffer_idx;
  51. std::vector<vk::CommandBuffer> cmd_buffers;
  52. vk::PipelineStageFlags stage_flags;
  53. };
  54. struct vk_device {
  55. vk::PhysicalDevice physical_device;
  56. vk::PhysicalDeviceProperties properties;
  57. std::string name;
  58. uint64_t max_memory_allocation_size;
  59. bool fp16;
  60. vk::Device device;
  61. uint32_t vendor_id;
  62. vk_queue compute_queue;
  63. vk_queue transfer_queue;
  64. bool single_queue;
  65. uint32_t descriptor_set_mode;
  66. uint32_t subgroup_size;
  67. bool uma;
  68. ~vk_device() {
  69. #ifdef GGML_VULKAN_DEBUG
  70. std::cerr << "destroy device " << name << std::endl;
  71. #endif
  72. device.destroy();
  73. }
  74. };
  75. struct vk_buffer_struct {
  76. vk::Buffer buffer;
  77. vk::DeviceMemory device_memory;
  78. vk::MemoryPropertyFlags memory_property_flags;
  79. void * ptr;
  80. size_t size = 0;
  81. ggml_backend_vk_context * ctx;
  82. std::shared_ptr<vk_device> device;
  83. ~vk_buffer_struct() {
  84. if (size == 0) {
  85. return;
  86. }
  87. #ifdef GGML_VULKAN_DEBUG
  88. std::cerr << "~vk_buffer_struct(" << buffer << ", " << size << ")" << std::endl;
  89. #endif
  90. device->device.freeMemory(device_memory);
  91. device->device.destroyBuffer(buffer);
  92. }
  93. };
  94. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  95. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  96. struct vk_subbuffer {
  97. vk_buffer buffer;
  98. uint64_t offset;
  99. uint64_t size;
  100. };
  101. struct vk_pipeline {
  102. std::string name;
  103. vk::ShaderModule shader_module;
  104. vk::DescriptorSetLayout dsl;
  105. std::vector<vk::DescriptorPool> descriptor_pools;
  106. std::vector<vk::DescriptorSet> descriptor_sets;
  107. uint32_t descriptor_set_idx;
  108. vk::PipelineLayout layout;
  109. vk::Pipeline pipeline;
  110. uint32_t push_constant_size;
  111. uint32_t parameter_count;
  112. std::array<uint32_t, 3> wg_denoms;
  113. uint32_t align;
  114. };
  115. struct vk_semaphore {
  116. vk::Semaphore s;
  117. uint64_t value;
  118. };
  119. struct vk_submission {
  120. vk::CommandBuffer buffer;
  121. std::vector<vk_semaphore> wait_semaphores;
  122. std::vector<vk_semaphore> signal_semaphores;
  123. };
  124. typedef std::vector<vk_submission> vk_sequence;
  125. struct vk_op_push_constants {
  126. uint32_t KX;
  127. uint32_t KY;
  128. float param1;
  129. float param2;
  130. };
  131. struct vk_op_cpy_push_constants {
  132. uint32_t ne;
  133. uint32_t ne00; uint32_t ne01; uint32_t nb00; uint32_t nb01; uint32_t nb02;
  134. uint32_t ne10; uint32_t ne11; uint32_t nb10; uint32_t nb11; uint32_t nb12;
  135. uint32_t d_offset;
  136. };
  137. struct vk_op_diag_mask_push_constants {
  138. uint32_t ncols;
  139. uint32_t rows_per_channel;
  140. int32_t n_past;
  141. };
  142. struct vk_op_rope_push_constants {
  143. uint32_t ncols;
  144. float freq_scale;
  145. uint32_t p_delta_rows;
  146. float freq_base;
  147. float ext_factor;
  148. float attn_factor;
  149. float corr_dims[4];
  150. };
  151. struct vk_op_rope_neox_push_constants {
  152. uint32_t ncols;
  153. uint32_t ndims;
  154. float freq_scale;
  155. uint32_t p_delta_rows;
  156. float freq_base;
  157. float ext_factor;
  158. float attn_factor;
  159. float corr_dims[4];
  160. float theta_scale;
  161. float inv_ndims;
  162. };
  163. // Allow pre-recording command buffers
  164. struct vk_staging_memcpy {
  165. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  166. void * dst;
  167. const void * src;
  168. size_t n;
  169. };
  170. struct vk_context {
  171. size_t idx;
  172. vk_submission * s;
  173. std::vector<vk_sequence> seqs;
  174. ggml_tensor * exit_tensor;
  175. std::vector<vk_staging_memcpy> in_memcpys;
  176. std::vector<vk_staging_memcpy> out_memcpys;
  177. vk_queue * q;
  178. };
  179. struct ggml_tensor_extra_gpu {
  180. bool ready;
  181. size_t ctx_idx;
  182. vk_buffer_ref buffer_gpu;
  183. uint64_t offset;
  184. void reset() {
  185. ready = false;
  186. ctx_idx = 0;
  187. buffer_gpu.reset();
  188. offset = 0;
  189. }
  190. };
  191. struct ggml_vk_garbage_collector {
  192. std::vector<vk_pipeline *> pipelines;
  193. std::vector<vk_semaphore> tl_semaphores;
  194. std::vector<vk_semaphore> semaphores;
  195. std::vector<vk::Event> events;
  196. std::vector<vk_buffer> temp_buffers;
  197. std::vector<vk_context> contexts;
  198. };
  199. struct ggml_backend_vk_context {
  200. std::string name;
  201. std::weak_ptr<vk_device> device;
  202. vk_pipeline pipeline_matmul_f32_l, pipeline_matmul_f32_m, pipeline_matmul_f32_s;
  203. vk_pipeline pipeline_matmul_f32_aligned_l, pipeline_matmul_f32_aligned_m, pipeline_matmul_f32_aligned_s;
  204. vk_pipeline pipeline_matmul_f16_l, pipeline_matmul_f16_m, pipeline_matmul_f16_s;
  205. vk_pipeline pipeline_matmul_f16_aligned_l, pipeline_matmul_f16_aligned_m, pipeline_matmul_f16_aligned_s;
  206. vk_pipeline pipeline_matmul_f16_f32_l, pipeline_matmul_f16_f32_m, pipeline_matmul_f16_f32_s;
  207. vk_pipeline pipeline_matmul_f16_f32_aligned_l, pipeline_matmul_f16_f32_aligned_m, pipeline_matmul_f16_f32_aligned_s;
  208. vk_pipeline pipeline_matmul_split_k_reduce;
  209. vk_pipeline pipeline_dequant[VK_NUM_TYPES];
  210. vk_pipeline pipeline_dequant_mul_mat_vec_f32[VK_NUM_TYPES];
  211. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  212. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  213. vk_pipeline pipeline_get_rows[VK_NUM_TYPES];
  214. vk_pipeline pipeline_get_rows_f32[VK_NUM_TYPES];
  215. vk_pipeline pipeline_mul_f32;
  216. vk_pipeline pipeline_add_f32;
  217. vk_pipeline pipeline_scale_f32;
  218. vk_pipeline pipeline_sqr_f32;
  219. vk_pipeline pipeline_clamp_f32;
  220. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  221. vk_pipeline pipeline_norm_f32;
  222. vk_pipeline pipeline_rms_norm_f32;
  223. vk_pipeline pipeline_gelu_f32;
  224. vk_pipeline pipeline_silu_f32;
  225. vk_pipeline pipeline_relu_f32;
  226. vk_pipeline pipeline_diag_mask_inf_f32;
  227. vk_pipeline pipeline_soft_max_f32;
  228. vk_pipeline pipeline_rope_f32, pipeline_rope_f16;
  229. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  230. size_t semaphore_idx, event_idx;
  231. ggml_vk_garbage_collector gc;
  232. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  233. size_t prealloc_size_qx, prealloc_size_qy, prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  234. vk_buffer prealloc_qx, prealloc_qy, prealloc_x, prealloc_y, prealloc_split_k;
  235. vk::Fence fence;
  236. vk_buffer staging;
  237. size_t staging_size;
  238. size_t staging_offset;
  239. vk_buffer sync_staging;
  240. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  241. vk_context * compute_ctx;
  242. vk_context * transfer_ctx;
  243. bool disable;
  244. bool initialized;
  245. size_t idx;
  246. };
  247. struct vk_instance {
  248. vk::Instance instance;
  249. std::vector<size_t> device_indices;
  250. std::shared_ptr<vk_device> devices[GGML_VK_MAX_DEVICES];
  251. ggml_backend_t backends[GGML_VK_MAX_DEVICES];
  252. ggml_backend_vk_context contexts[GGML_VK_MAX_DEVICES];
  253. ggml_backend_buffer_type buffer_types[GGML_VK_MAX_DEVICES];
  254. bool initialized[GGML_VK_MAX_DEVICES];
  255. };
  256. #ifdef GGML_VULKAN_CHECK_RESULTS
  257. static size_t vk_skip_checks;
  258. static size_t vk_output_tensor;
  259. static void ggml_vk_print_tensor(ggml_backend * ctx, const ggml_tensor * tensor, const char * name);
  260. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor);
  261. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor);
  262. #endif
  263. 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);
  264. static bool vk_instance_initialized = false;
  265. static vk_instance vk_instance;
  266. GGML_CALL static void ggml_backend_vk_free(ggml_backend_t backend);
  267. static void ggml_vk_create_pipeline(ggml_backend_vk_context * ctx, 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) {
  268. #ifdef GGML_VULKAN_DEBUG
  269. std::cerr << "ggml_vk_create_pipeline(" << name << ", " << entrypoint << ", " << parameter_count << ", " << push_constant_size << ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << align << ")" << std::endl;
  270. #endif
  271. GGML_ASSERT(parameter_count > 0);
  272. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  273. pipeline.name = name;
  274. pipeline.parameter_count = parameter_count;
  275. pipeline.push_constant_size = push_constant_size;
  276. pipeline.wg_denoms = wg_denoms;
  277. pipeline.align = align;
  278. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  279. pipeline.shader_module = ctx->device.lock()->device.createShaderModule(shader_module_create_info);
  280. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  281. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  282. for (uint32_t i = 0; i < parameter_count; i++) {
  283. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  284. dsl_binding_flags.push_back({});
  285. }
  286. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  287. vk::PushConstantRange pcr(
  288. vk::ShaderStageFlagBits::eCompute,
  289. 0,
  290. pipeline.push_constant_size
  291. );
  292. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  293. {},
  294. dsl_binding);
  295. descriptor_set_layout_create_info.setPNext(&dslbfci);
  296. pipeline.dsl = ctx->device.lock()->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  297. // Check if device supports multiple descriptors per pool
  298. if (ctx->device.lock()->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN) {
  299. const uint32_t alloc_count = 2;
  300. // Try allocating multiple sets from one pool
  301. // This fails on AMD for some reason, so add a fall back to allocating one pool per set
  302. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline.parameter_count);
  303. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, alloc_count, descriptor_pool_size);
  304. vk::DescriptorPool pool = ctx->device.lock()->device.createDescriptorPool(descriptor_pool_create_info);
  305. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  306. for (uint32_t i = 0; i < alloc_count; i++) {
  307. layouts[i] = pipeline.dsl;
  308. }
  309. try {
  310. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pool, alloc_count, layouts.data());
  311. std::vector<vk::DescriptorSet> sets = ctx->device.lock()->device.allocateDescriptorSets(descriptor_set_alloc_info);
  312. } catch(vk::OutOfPoolMemoryError const&) {
  313. ctx->device.lock()->descriptor_set_mode = VK_DEVICE_DESCRIPTOR_POOL_MODE_SINGLE;
  314. }
  315. ctx->device.lock()->device.destroyDescriptorPool(pool);
  316. }
  317. if (ctx->device.lock()->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI) {
  318. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline.parameter_count);
  319. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, 128, descriptor_pool_size);
  320. pipeline.descriptor_pools.push_back(ctx->device.lock()->device.createDescriptorPool(descriptor_pool_create_info));
  321. }
  322. pipeline.descriptor_set_idx = 0;
  323. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline.dsl, pcr);
  324. pipeline.layout = ctx->device.lock()->device.createPipelineLayout(pipeline_layout_create_info);
  325. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  326. for (size_t i = 0; i < specialization_constants.size(); i++) {
  327. specialization_entries[i].constantID = i;
  328. specialization_entries[i].offset = i * sizeof(uint32_t);
  329. specialization_entries[i].size = sizeof(uint32_t);
  330. }
  331. vk::SpecializationInfo specialization_info(
  332. specialization_entries.size(),
  333. specialization_entries.data(),
  334. specialization_constants.size() * sizeof(uint32_t),
  335. specialization_constants.data()
  336. );
  337. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  338. vk::PipelineShaderStageCreateFlags(),
  339. vk::ShaderStageFlagBits::eCompute,
  340. pipeline.shader_module,
  341. entrypoint.c_str(),
  342. &specialization_info);
  343. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  344. vk::PipelineCreateFlags(),
  345. pipeline_shader_create_info,
  346. pipeline.layout);
  347. pipeline.pipeline = ctx->device.lock()->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  348. ctx->gc.pipelines.push_back(&pipeline);
  349. }
  350. static void ggml_vk_destroy_pipeline(ggml_backend_vk_context * ctx, vk_pipeline * pipeline) {
  351. for (auto& pool : pipeline->descriptor_pools) {
  352. ctx->device.lock()->device.destroyDescriptorPool(pool);
  353. }
  354. pipeline->descriptor_pools.clear();
  355. pipeline->descriptor_sets.clear();
  356. pipeline->descriptor_set_idx = 0;
  357. ctx->device.lock()->device.destroyDescriptorSetLayout(pipeline->dsl);
  358. ctx->device.lock()->device.destroyPipelineLayout(pipeline->layout);
  359. ctx->device.lock()->device.destroyShaderModule(pipeline->shader_module);
  360. ctx->device.lock()->device.destroyPipeline(pipeline->pipeline);
  361. }
  362. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx, vk_pipeline& pipeline, uint32_t n) {
  363. #ifdef GGML_VULKAN_DEBUG
  364. std::cerr << "ggml_pipeline_allocate_descriptor_sets(" << pipeline.name << ", " << n << ")" << std::endl;
  365. #endif
  366. if (pipeline.descriptor_sets.size() >= pipeline.descriptor_set_idx + n) {
  367. // Enough descriptors are available
  368. return;
  369. }
  370. if (ctx->device.lock()->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI) {
  371. const uint32_t alloc_count = pipeline.descriptor_set_idx + n - pipeline.descriptor_sets.size();
  372. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  373. for (uint32_t i = 0; i < alloc_count; i++) {
  374. layouts[i] = pipeline.dsl;
  375. }
  376. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline.descriptor_pools[0], alloc_count, layouts.data());
  377. std::vector<vk::DescriptorSet> sets = ctx->device.lock()->device.allocateDescriptorSets(descriptor_set_alloc_info);
  378. pipeline.descriptor_sets.insert(pipeline.descriptor_sets.end(), sets.begin(), sets.end());
  379. } else {
  380. for (uint32_t i = pipeline.descriptor_sets.size(); i < pipeline.descriptor_set_idx + n; i++) {
  381. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline.parameter_count);
  382. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, 1, descriptor_pool_size);
  383. pipeline.descriptor_pools.push_back(ctx->device.lock()->device.createDescriptorPool(descriptor_pool_create_info));
  384. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline.descriptor_pools[i], 1, &pipeline.dsl);
  385. std::vector<vk::DescriptorSet> sets = ctx->device.lock()->device.allocateDescriptorSets(descriptor_set_alloc_info);
  386. pipeline.descriptor_sets.push_back(sets[0]);
  387. }
  388. }
  389. }
  390. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  391. #ifdef GGML_VULKAN_DEBUG
  392. std::cerr << "ggml_pipeline_cleanup(" << pipeline.name << ")" << std::endl;
  393. #endif
  394. pipeline.descriptor_set_idx = 0;
  395. }
  396. static vk::CommandBuffer ggml_vk_create_cmd_buffer(ggml_backend_vk_context * ctx, vk_queue& q) {
  397. #ifdef GGML_VULKAN_DEBUG
  398. std::cerr << "ggml_vk_create_cmd_buffer()" << std::endl;
  399. #endif
  400. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  401. // Reuse command buffer
  402. return q.cmd_buffers[q.cmd_buffer_idx++];
  403. }
  404. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  405. q.pool,
  406. vk::CommandBufferLevel::ePrimary,
  407. 1);
  408. const std::vector<vk::CommandBuffer> cmd_buffers = ctx->device.lock()->device.allocateCommandBuffers(command_buffer_alloc_info);
  409. auto buf = cmd_buffers.front();
  410. q.cmd_buffers.push_back(buf);
  411. q.cmd_buffer_idx++;
  412. return buf;
  413. }
  414. static vk_submission ggml_vk_create_submission(ggml_backend_vk_context * ctx, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  415. #ifdef GGML_VULKAN_DEBUG
  416. std::cerr << "ggml_vk_create_submission()" << std::endl;
  417. #endif
  418. vk_submission s;
  419. s.buffer = ggml_vk_create_cmd_buffer(ctx, q);
  420. s.wait_semaphores = std::move(wait_semaphores);
  421. s.signal_semaphores = std::move(signal_semaphores);
  422. return s;
  423. }
  424. static void ggml_vk_submit(vk_context * ctx, vk::Fence fence) {
  425. #ifdef GGML_VULKAN_DEBUG
  426. std::cerr << "ggml_vk_submit(" << ctx->seqs.size() << ", " << fence << ")" << std::endl;
  427. #endif
  428. if (ctx->seqs.empty()) {
  429. return;
  430. }
  431. std::vector<std::vector<uint64_t>> tl_wait_vals;
  432. std::vector<std::vector<uint64_t>> tl_signal_vals;
  433. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  434. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  435. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  436. std::vector<vk::SubmitInfo> submit_infos;
  437. int idx = -1;
  438. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  439. size_t reserve = 0;
  440. for (const auto& sequence : ctx->seqs) {
  441. reserve += sequence.size();
  442. }
  443. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  444. tl_wait_semaphores.reserve(reserve);
  445. tl_wait_vals.reserve(reserve);
  446. tl_signal_semaphores.reserve(reserve);
  447. tl_signal_vals.reserve(reserve);
  448. tl_submit_infos.reserve(reserve);
  449. submit_infos.reserve(reserve);
  450. stage_flags.reserve(reserve);
  451. for (const auto& sequence : ctx->seqs) {
  452. for (const auto& submission : sequence) {
  453. stage_flags.push_back({});
  454. idx++;
  455. tl_wait_vals.push_back({});
  456. tl_wait_semaphores.push_back({});
  457. tl_signal_vals.push_back({});
  458. tl_signal_semaphores.push_back({});
  459. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  460. stage_flags[idx].push_back(ctx->q->stage_flags);
  461. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  462. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  463. }
  464. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  465. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  466. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  467. }
  468. tl_submit_infos.push_back({
  469. (uint32_t) submission.wait_semaphores.size(),
  470. tl_wait_vals[idx].data(),
  471. (uint32_t) submission.signal_semaphores.size(),
  472. tl_signal_vals[idx].data(),
  473. });
  474. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  475. tl_submit_infos[idx].pNext = nullptr;
  476. vk::SubmitInfo si{
  477. (uint32_t) submission.wait_semaphores.size(),
  478. tl_wait_semaphores[idx].data(),
  479. stage_flags[idx].data(),
  480. 1,
  481. &submission.buffer,
  482. (uint32_t) submission.signal_semaphores.size(),
  483. tl_signal_semaphores[idx].data(),
  484. };
  485. si.setPNext(&tl_submit_infos[idx]);
  486. submit_infos.push_back(si);
  487. }
  488. }
  489. ctx->q->queue.submit(submit_infos, fence);
  490. ctx->seqs.clear();
  491. }
  492. 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) {
  493. #ifdef GGML_VULKAN_DEBUG
  494. std::cerr << "ggml_vk_find_queue_family_index()" << std::endl;
  495. #endif
  496. const uint32_t qfsize = queue_family_props.size();
  497. // Try with avoid preferences first
  498. for (uint32_t i = 0; i < qfsize; i++) {
  499. 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)) {
  500. return i;
  501. }
  502. }
  503. // Fall back to only required
  504. for (size_t i = 0; i < qfsize; i++) {
  505. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  506. return i;
  507. }
  508. }
  509. // Fall back to reusing compute queue
  510. for (size_t i = 0; i < qfsize; i++) {
  511. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  512. return i;
  513. }
  514. }
  515. // Fall back to ignoring min_num_queries
  516. for (size_t i = 0; i < qfsize; i++) {
  517. if (queue_family_props[i].queueFlags & required) {
  518. return i;
  519. }
  520. }
  521. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  522. for(auto &q_family : queue_family_props) {
  523. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  524. }
  525. abort();
  526. }
  527. static void ggml_vk_create_queue(ggml_backend_vk_context * ctx, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags) {
  528. #ifdef GGML_VULKAN_DEBUG
  529. std::cerr << "ggml_vk_create_queue()" << std::endl;
  530. #endif
  531. q.queue_family_index = queue_family_index;
  532. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  533. q.pool = ctx->device.lock()->device.createCommandPool(command_pool_create_info_compute);
  534. q.cmd_buffer_idx = 0;
  535. q.queue = ctx->device.lock()->device.getQueue(queue_family_index, queue_index);
  536. q.stage_flags = stage_flags;
  537. }
  538. static vk_context * ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  539. #ifdef GGML_VULKAN_DEBUG
  540. std::cerr << "ggml_vk_create_context()" << std::endl;
  541. #endif
  542. ctx->gc.contexts.emplace_back();
  543. vk_context * result = &ctx->gc.contexts[ctx->gc.contexts.size() - 1];
  544. memset((void *) result, 0, sizeof(vk_context));
  545. result->idx = ctx->gc.contexts.size() - 1;
  546. result->q = &q;
  547. return result;
  548. }
  549. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  550. #ifdef GGML_VULKAN_DEBUG
  551. std::cerr << "ggml_vk_create_timeline_semaphore()" << std::endl;
  552. #endif
  553. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  554. vk::SemaphoreCreateInfo ci{};
  555. ci.setPNext(&tci);
  556. vk::Semaphore semaphore = ctx->device.lock()->device.createSemaphore(ci);
  557. ctx->gc.semaphores.push_back({ semaphore, 0 });
  558. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  559. }
  560. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  561. #ifdef GGML_VULKAN_DEBUG
  562. std::cerr << "ggml_vk_create_timeline_semaphore()" << std::endl;
  563. #endif
  564. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  565. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  566. vk::SemaphoreCreateInfo ci{};
  567. ci.setPNext(&tci);
  568. vk::Semaphore semaphore = ctx->device.lock()->device.createSemaphore(ci);
  569. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  570. }
  571. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  572. }
  573. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  574. if (ctx->event_idx >= ctx->gc.events.size()) {
  575. ctx->gc.events.push_back(ctx->device.lock()->device.createEvent({}));
  576. }
  577. return ctx->gc.events[ctx->event_idx++];
  578. }
  579. static void ggml_vk_queue_cleanup(ggml_backend_vk_context * ctx, vk_queue& q) {
  580. #ifdef GGML_VULKAN_DEBUG
  581. std::cerr << "ggml_vk_queue_cleanup()" << std::endl;
  582. #endif
  583. // Requires command buffers to be done
  584. ctx->device.lock()->device.resetCommandPool(q.pool);
  585. q.cmd_buffer_idx = 0;
  586. }
  587. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  588. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  589. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  590. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  591. (flags & memory_type.propertyFlags) == flags &&
  592. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  593. return static_cast<int32_t>(i);
  594. }
  595. }
  596. return UINT32_MAX;
  597. }
  598. static vk_buffer ggml_vk_create_buffer(ggml_backend_vk_context * ctx, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  599. #ifdef GGML_VULKAN_DEBUG
  600. std::cerr << "ggml_vk_create_buffer(" << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")" << std::endl;
  601. #endif
  602. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  603. if (size == 0) {
  604. buf->size = 0;
  605. return buf;
  606. }
  607. buf->size = size;
  608. vk::BufferCreateInfo buffer_create_info{
  609. vk::BufferCreateFlags(),
  610. size,
  611. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  612. vk::SharingMode::eExclusive,
  613. 0,
  614. nullptr,
  615. };
  616. buf->buffer = ctx->device.lock()->device.createBuffer(buffer_create_info);
  617. vk::MemoryRequirements mem_req = ctx->device.lock()->device.getBufferMemoryRequirements(buf->buffer);
  618. vk::PhysicalDeviceMemoryProperties mem_props = ctx->device.lock()->physical_device.getMemoryProperties();
  619. uint32_t memory_type_index = UINT32_MAX;
  620. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  621. buf->memory_property_flags = req_flags;
  622. if (memory_type_index == UINT32_MAX && fallback_flags) {
  623. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  624. buf->memory_property_flags = fallback_flags;
  625. }
  626. if (memory_type_index == UINT32_MAX) {
  627. ctx->device.lock()->device.destroyBuffer(buf->buffer);
  628. buf->size = 0;
  629. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  630. }
  631. try {
  632. buf->device_memory = ctx->device.lock()->device.allocateMemory({ mem_req.size, memory_type_index });
  633. } catch (const vk::SystemError& e) {
  634. // Out of Host/Device memory, clean up buffer
  635. ctx->device.lock()->device.destroyBuffer(buf->buffer);
  636. buf->size = 0;
  637. throw e;
  638. }
  639. buf->ptr = nullptr;
  640. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  641. buf->ptr = ctx->device.lock()->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  642. }
  643. ctx->device.lock()->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  644. buf->ctx = ctx;
  645. buf->device = ctx->device.lock();
  646. #ifdef GGML_VULKAN_DEBUG
  647. std::cerr << "Created buffer " << buf->buffer << std::endl;
  648. #endif
  649. return buf;
  650. }
  651. static vk_buffer ggml_vk_create_buffer_check(ggml_backend_vk_context * ctx, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  652. try {
  653. return ggml_vk_create_buffer(ctx, size, req_flags, fallback_flags);
  654. } catch (const vk::SystemError& e) {
  655. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  656. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  657. throw e;
  658. }
  659. }
  660. static vk_buffer ggml_vk_create_buffer_device(ggml_backend_vk_context * ctx, size_t size) {
  661. vk_buffer buf;
  662. try {
  663. if (ctx->device.lock()->uma) {
  664. // Fall back to host memory type
  665. buf = ggml_vk_create_buffer(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  666. } else {
  667. buf = ggml_vk_create_buffer(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal);
  668. }
  669. } catch (const vk::SystemError& e) {
  670. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  671. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  672. throw e;
  673. }
  674. return buf;
  675. }
  676. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  677. buf.reset();
  678. }
  679. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  680. return { buf, 0, VK_WHOLE_SIZE };
  681. }
  682. static void ggml_vk_sync_buffers(vk_context * ctx) {
  683. #ifdef GGML_VULKAN_DEBUG
  684. std::cerr << "ggml_vk_sync_buffers()" << std::endl;
  685. #endif
  686. const std::vector<vk::MemoryBarrier> mem_barriers{ { { vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite }, { vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite } } };
  687. ctx->s->buffer.pipelineBarrier(
  688. ctx->q->stage_flags,
  689. ctx->q->stage_flags,
  690. {},
  691. mem_barriers,
  692. {},
  693. {}
  694. );
  695. }
  696. static void ggml_vk_wait_events(vk_context * ctx, std::vector<vk::Event>&& events) {
  697. #ifdef GGML_VULKAN_DEBUG
  698. std::cerr << "ggml_vk_wait_events()" << std::endl;
  699. #endif
  700. if (events.empty()) {
  701. return;
  702. }
  703. ctx->s->buffer.waitEvents(
  704. events,
  705. ctx->q->stage_flags,
  706. ctx->q->stage_flags,
  707. {},
  708. {},
  709. {}
  710. );
  711. }
  712. static bool ggml_vk_build_shader(ggml_type type) {
  713. switch(type) {
  714. case GGML_TYPE_F16:
  715. case GGML_TYPE_Q4_0:
  716. case GGML_TYPE_Q4_1:
  717. case GGML_TYPE_Q5_0:
  718. case GGML_TYPE_Q5_1:
  719. case GGML_TYPE_Q8_0:
  720. case GGML_TYPE_Q2_K:
  721. case GGML_TYPE_Q3_K:
  722. case GGML_TYPE_Q4_K:
  723. case GGML_TYPE_Q5_K:
  724. case GGML_TYPE_Q6_K:
  725. return true;
  726. default:
  727. return false;
  728. }
  729. }
  730. static void ggml_vk_load_shaders(ggml_backend_vk_context * ctx) {
  731. #ifdef GGML_VULKAN_DEBUG
  732. std::cerr << "ggml_vk_load_shaders(" << ctx->name << ")" << std::endl;
  733. #endif
  734. // mulmat
  735. std::initializer_list<uint32_t> warptile_l = { 128, 128, 128, 16, ctx->device.lock()->subgroup_size * 2, 64, 2, 4, 4, ctx->device.lock()->subgroup_size };
  736. std::initializer_list<uint32_t> warptile_m = { 128, 64, 64, 16, ctx->device.lock()->subgroup_size, 32, 2, 4, 2, ctx->device.lock()->subgroup_size };
  737. std::initializer_list<uint32_t> warptile_s = { ctx->device.lock()->subgroup_size, 32, 32, 16, 32, 32, 2, 2, 2, ctx->device.lock()->subgroup_size };
  738. std::array<uint32_t, 3> l_wg_denoms = {128, 128, 1 };
  739. std::array<uint32_t, 3> m_wg_denoms = { 64, 64, 1 };
  740. std::array<uint32_t, 3> s_wg_denoms = { 32, 32, 1 };
  741. uint32_t l_align = 128;
  742. uint32_t m_align = 64;
  743. uint32_t s_align = 32;
  744. if (ctx->device.lock()->fp16) {
  745. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_l, "matmul_f32_l", matmul_f32_l_len, matmul_f32_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  746. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_m, "matmul_f32_m", matmul_f32_m_len, matmul_f32_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  747. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_s, "matmul_f32_s", matmul_f32_s_len, matmul_f32_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  748. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_l, "matmul_f32_aligned_l", matmul_f32_aligned_l_len, matmul_f32_aligned_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  749. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_m, "matmul_f32_aligned_m", matmul_f32_aligned_m_len, matmul_f32_aligned_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  750. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_s, "matmul_f32_aligned_s", matmul_f32_aligned_s_len, matmul_f32_aligned_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  751. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_l, "matmul_f16_l", matmul_f16_l_len, matmul_f16_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  752. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_m, "matmul_f16_m", matmul_f16_m_len, matmul_f16_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  753. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_s, "matmul_f16_s", matmul_f16_s_len, matmul_f16_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  754. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_l, "matmul_f16_aligned_l", matmul_f16_aligned_l_len, matmul_f16_aligned_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  755. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_m, "matmul_f16_aligned_m", matmul_f16_aligned_m_len, matmul_f16_aligned_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  756. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_s, "matmul_f16_aligned_s", matmul_f16_aligned_s_len, matmul_f16_aligned_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  757. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_l, "matmul_f16_f32_l", matmul_f16_f32_l_len, matmul_f16_f32_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  758. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_m, "matmul_f16_f32_m", matmul_f16_f32_m_len, matmul_f16_f32_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  759. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_s, "matmul_f16_f32_s", matmul_f16_f32_s_len, matmul_f16_f32_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  760. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_l, "matmul_f16_f32_aligned_l", matmul_f16_f32_aligned_l_len, matmul_f16_f32_aligned_l_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  761. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_m, "matmul_f16_f32_aligned_m", matmul_f16_f32_aligned_m_len, matmul_f16_f32_aligned_m_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  762. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_s, "matmul_f16_f32_aligned_s", matmul_f16_f32_aligned_s_len, matmul_f16_f32_aligned_s_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  763. } else {
  764. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_l, "matmul_f32_l", matmul_f32_l_fp32_len, matmul_f32_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  765. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_m, "matmul_f32_m", matmul_f32_m_fp32_len, matmul_f32_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  766. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_s, "matmul_f32_s", matmul_f32_s_fp32_len, matmul_f32_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  767. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_l, "matmul_f32_aligned_l", matmul_f32_aligned_l_fp32_len, matmul_f32_aligned_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  768. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_m, "matmul_f32_aligned_m", matmul_f32_aligned_m_fp32_len, matmul_f32_aligned_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  769. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f32_aligned_s, "matmul_f32_aligned_s", matmul_f32_aligned_s_fp32_len, matmul_f32_aligned_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  770. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_l, "matmul_f16_l", matmul_f16_l_fp32_len, matmul_f16_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  771. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_m, "matmul_f16_m", matmul_f16_m_fp32_len, matmul_f16_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  772. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_s, "matmul_f16_s", matmul_f16_s_fp32_len, matmul_f16_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  773. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_l, "matmul_f16_aligned_l", matmul_f16_aligned_l_fp32_len, matmul_f16_aligned_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  774. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_m, "matmul_f16_aligned_m", matmul_f16_aligned_m_fp32_len, matmul_f16_aligned_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  775. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_aligned_s, "matmul_f16_aligned_s", matmul_f16_aligned_s_fp32_len, matmul_f16_aligned_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  776. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_l, "matmul_f16_f32_l", matmul_f16_f32_l_fp32_len, matmul_f16_f32_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  777. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_m, "matmul_f16_f32_m", matmul_f16_f32_m_fp32_len, matmul_f16_f32_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  778. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_s, "matmul_f16_f32_s", matmul_f16_f32_s_fp32_len, matmul_f16_f32_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  779. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_l, "matmul_f16_f32_aligned_l", matmul_f16_f32_aligned_l_fp32_len, matmul_f16_f32_aligned_l_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  780. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_m, "matmul_f16_f32_aligned_m", matmul_f16_f32_aligned_m_fp32_len, matmul_f16_f32_aligned_m_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  781. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_f16_f32_aligned_s, "matmul_f16_f32_aligned_s", matmul_f16_f32_aligned_s_fp32_len, matmul_f16_f32_aligned_s_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  782. }
  783. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f32", mul_mat_vec_f16_f32_len, mul_mat_vec_f16_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  784. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f32", mul_mat_vec_q4_0_f32_len, mul_mat_vec_q4_0_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  785. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f32", mul_mat_vec_q4_1_f32_len, mul_mat_vec_q4_1_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  786. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f32", mul_mat_vec_q5_0_f32_len, mul_mat_vec_q5_0_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  787. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f32", mul_mat_vec_q5_1_f32_len, mul_mat_vec_q5_1_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  788. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f32", mul_mat_vec_q8_0_f32_len, mul_mat_vec_q8_0_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  789. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_K_f32", mul_mat_vec_q2_K_f32_len, mul_mat_vec_q2_K_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  790. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_K_f32", mul_mat_vec_q3_K_f32_len, mul_mat_vec_q3_K_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  791. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_K_f32", mul_mat_vec_q4_K_f32_len, mul_mat_vec_q4_K_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  792. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_K_f32", mul_mat_vec_q5_K_f32_len, mul_mat_vec_q5_K_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  793. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_K_f32", mul_mat_vec_q6_K_f32_len, mul_mat_vec_q6_K_f32_data, "main", 3, 3 * sizeof(int), {1, 1, 1}, {}, 1);
  794. // dequant shaders
  795. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", f32_to_f16_len, f32_to_f16_data, "main", 2, 4 * sizeof(int), { 64, 1, 1}, {}, 1);
  796. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_F16 ], "dequant_f16", dequant_f16_len, dequant_f16_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  797. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  798. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  799. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  800. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  801. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  802. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_K", dequant_q2_K_len, dequant_q2_K_data, "main", 2, 4 * sizeof(int), {256 * 64, 1, 1}, {}, 1);
  803. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_K", dequant_q3_K_len, dequant_q3_K_data, "main", 2, 4 * sizeof(int), {256 * 64, 1, 1}, {}, 1);
  804. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_K", dequant_q4_K_len, dequant_q4_K_data, "main", 2, 4 * sizeof(int), {256 * 32, 1, 1}, {}, 1);
  805. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_K", dequant_q5_K_len, dequant_q5_K_data, "main", 2, 4 * sizeof(int), {256 * 64, 1, 1}, {}, 1);
  806. ggml_vk_create_pipeline(ctx, ctx->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_K", dequant_q6_K_len, dequant_q6_K_data, "main", 2, 4 * sizeof(int), {256 * 64, 1, 1}, {}, 1);
  807. // get_rows
  808. ggml_vk_create_pipeline(ctx, ctx->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  809. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  810. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  811. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  812. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  813. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  814. ggml_vk_create_pipeline(ctx, ctx->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  815. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  816. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  817. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  818. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  819. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  820. ggml_vk_create_pipeline(ctx, ctx->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256, 1, 1}, {}, 1);
  821. ggml_vk_create_pipeline(ctx, ctx->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);
  822. ggml_vk_create_pipeline(ctx, ctx->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);
  823. ggml_vk_create_pipeline(ctx, ctx->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  824. ggml_vk_create_pipeline(ctx, ctx->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);
  825. ggml_vk_create_pipeline(ctx, ctx->pipeline_cpy_f32_f32, "cpy_f32_f32", cpy_f32_f32_len, cpy_f32_f32_data, "main", 2, sizeof(vk_op_cpy_push_constants), {512, 1, 1}, {}, 1);
  826. ggml_vk_create_pipeline(ctx, ctx->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_cpy_push_constants), {512, 1, 1}, {}, 1);
  827. ggml_vk_create_pipeline(ctx, ctx->pipeline_cpy_f16_f16, "cpy_f16_f16", cpy_f16_f16_len, cpy_f16_f16_data, "main", 2, sizeof(vk_op_cpy_push_constants), {512, 1, 1}, {}, 1);
  828. ggml_vk_create_pipeline(ctx, ctx->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  829. ggml_vk_create_pipeline(ctx, ctx->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  830. ggml_vk_create_pipeline(ctx, ctx->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  831. ggml_vk_create_pipeline(ctx, ctx->pipeline_sqr_f32, "sqr_f32", sqr_f32_len, sqr_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  832. ggml_vk_create_pipeline(ctx, ctx->pipeline_clamp_f32, "clamp_f32", clamp_f32_len, clamp_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  833. ggml_vk_create_pipeline(ctx, ctx->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  834. ggml_vk_create_pipeline(ctx, ctx->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  835. ggml_vk_create_pipeline(ctx, ctx->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  836. ggml_vk_create_pipeline(ctx, ctx->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);
  837. ggml_vk_create_pipeline(ctx, ctx->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  838. ggml_vk_create_pipeline(ctx, ctx->pipeline_rope_f32, "rope_f32", rope_f32_len, rope_f32_data, "main", 3, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  839. ggml_vk_create_pipeline(ctx, ctx->pipeline_rope_f16, "rope_f16", rope_f16_len, rope_f16_data, "main", 3, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  840. ggml_vk_create_pipeline(ctx, ctx->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 3, sizeof(vk_op_rope_neox_push_constants), {1, 512, 1}, {}, 1);
  841. ggml_vk_create_pipeline(ctx, ctx->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 3, sizeof(vk_op_rope_neox_push_constants), {1, 512, 1}, {}, 1);
  842. }
  843. static void ggml_vk_print_gpu_info(size_t idx) {
  844. GGML_ASSERT(idx < vk_instance.device_indices.size());
  845. size_t dev_num = vk_instance.device_indices[idx];
  846. #ifdef GGML_VULKAN_DEBUG
  847. std::cerr << "ggml_vk_print_gpu_info(" << dev_num << ")" << std::endl;
  848. #endif
  849. GGML_ASSERT(vk_instance.initialized);
  850. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  851. if (dev_num >= devices.size()) {
  852. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  853. throw std::runtime_error("Device not found");
  854. }
  855. vk::PhysicalDevice physical_device = devices[dev_num];
  856. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  857. vk::PhysicalDeviceProperties2 props2;
  858. vk::PhysicalDeviceMaintenance3Properties props3;
  859. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  860. props2.pNext = &props3;
  861. props3.pNext = &subgroup_props;
  862. physical_device.getProperties2(&props2);
  863. const size_t subgroup_size = subgroup_props.subgroupSize;
  864. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  865. bool fp16_storage = false;
  866. bool fp16_compute = false;
  867. for (auto properties : ext_props) {
  868. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  869. fp16_storage = true;
  870. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  871. fp16_compute = true;
  872. }
  873. }
  874. const char* GGML_VULKAN_DISABLE_F16 = getenv("GGML_VULKAN_DISABLE_F16");
  875. bool force_disable_f16 = GGML_VULKAN_DISABLE_F16 != nullptr;
  876. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  877. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  878. VkPhysicalDeviceFeatures2 device_features2;
  879. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  880. device_features2.pNext = nullptr;
  881. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  882. VkPhysicalDeviceVulkan11Features vk11_features;
  883. vk11_features.pNext = nullptr;
  884. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  885. device_features2.pNext = &vk11_features;
  886. VkPhysicalDeviceVulkan12Features vk12_features;
  887. vk12_features.pNext = nullptr;
  888. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  889. vk11_features.pNext = &vk12_features;
  890. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  891. fp16 = fp16 && vk12_features.shaderFloat16;
  892. std::string device_name = props2.properties.deviceName.data();
  893. std::cerr << GGML_VK_NAME << idx << ": " << device_name << " | uma: " << uma << " | fp16: " << fp16 << " | warp size: " << subgroup_size << std::endl;
  894. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  895. std::cerr << "ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want." << std::endl;
  896. }
  897. }
  898. static void ggml_vk_instance_init() {
  899. if (vk_instance_initialized) {
  900. return;
  901. }
  902. #ifdef GGML_VULKAN_DEBUG
  903. std::cerr << "ggml_vk_instance_init()" << std::endl;
  904. #endif
  905. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, VK_API_VERSION };
  906. const std::vector<const char*> layers = {
  907. #ifdef GGML_VULKAN_VALIDATE
  908. "VK_LAYER_KHRONOS_validation",
  909. #endif
  910. };
  911. const std::vector<const char*> extensions = {
  912. #ifdef GGML_VULKAN_VALIDATE
  913. "VK_EXT_validation_features",
  914. #endif
  915. };
  916. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags(), &app_info, layers, extensions);
  917. #ifdef GGML_VULKAN_VALIDATE
  918. const std::vector<vk::ValidationFeatureEnableEXT> features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  919. vk::ValidationFeaturesEXT validation_features = {
  920. features_enable,
  921. {},
  922. };
  923. validation_features.setPNext(nullptr);
  924. instance_create_info.setPNext(&validation_features);
  925. std::cerr << "ggml_vulkan: Validation layers enabled" << std::endl;
  926. #endif
  927. vk_instance.instance = vk::createInstance(instance_create_info);
  928. memset(vk_instance.initialized, 0, sizeof(bool) * GGML_VK_MAX_DEVICES);
  929. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  930. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  931. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  932. if (devices_env != nullptr) {
  933. std::string devices(devices_env);
  934. std::replace(devices.begin(), devices.end(), ',', ' ');
  935. std::stringstream ss(devices);
  936. size_t tmp;
  937. while (ss >> tmp) {
  938. if(tmp >= num_available_devices) {
  939. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  940. throw std::runtime_error("Invalid Vulkan device index");
  941. }
  942. vk_instance.device_indices.push_back(tmp);
  943. }
  944. } else {
  945. vk_instance.device_indices.push_back(0);
  946. }
  947. vk_instance_initialized = true;
  948. }
  949. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  950. GGML_ASSERT(idx < vk_instance.device_indices.size());
  951. size_t dev_num = vk_instance.device_indices[idx];
  952. #ifdef GGML_VULKAN_DEBUG
  953. std::cerr << "ggml_vk_init(" << ctx->name << ", " << dev_num << ")" << std::endl;
  954. #endif
  955. ggml_vk_instance_init();
  956. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  957. if (dev_num >= devices.size()) {
  958. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  959. throw std::runtime_error("Device not found");
  960. }
  961. vk_instance.devices[idx] = std::make_shared<vk_device>();
  962. ctx->device = vk_instance.devices[idx];
  963. ctx->device.lock()->physical_device = devices[dev_num];
  964. std::vector<vk::ExtensionProperties> ext_props = ctx->device.lock()->physical_device.enumerateDeviceExtensionProperties();
  965. bool maintenance4_support = false;
  966. // Check if maintenance4 is supported
  967. for (auto properties : ext_props) {
  968. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  969. maintenance4_support = true;
  970. }
  971. }
  972. vk::PhysicalDeviceProperties2 props2;
  973. vk::PhysicalDeviceMaintenance3Properties props3;
  974. vk::PhysicalDeviceMaintenance4Properties props4;
  975. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  976. props2.pNext = &props3;
  977. props3.pNext = &subgroup_props;
  978. if (maintenance4_support) {
  979. subgroup_props.pNext = &props4;
  980. }
  981. ctx->device.lock()->physical_device.getProperties2(&props2);
  982. ctx->device.lock()->properties = props2.properties;
  983. if (maintenance4_support) {
  984. ctx->device.lock()->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  985. } else {
  986. ctx->device.lock()->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  987. }
  988. ctx->device.lock()->vendor_id = ctx->device.lock()->properties.vendorID;
  989. ctx->device.lock()->subgroup_size = subgroup_props.subgroupSize;
  990. ctx->device.lock()->uma = ctx->device.lock()->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  991. bool fp16_storage = false;
  992. bool fp16_compute = false;
  993. for (auto properties : ext_props) {
  994. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  995. fp16_storage = true;
  996. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  997. fp16_compute = true;
  998. }
  999. }
  1000. const char* GGML_VULKAN_DISABLE_F16 = getenv("GGML_VULKAN_DISABLE_F16");
  1001. bool force_disable_f16 = GGML_VULKAN_DISABLE_F16 != nullptr;
  1002. ctx->device.lock()->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1003. std::vector<vk::QueueFamilyProperties> queue_family_props = ctx->device.lock()->physical_device.getQueueFamilyProperties();
  1004. // Try to find a non-graphics compute queue and transfer-focused queues
  1005. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1006. 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);
  1007. const float priorities[] = { 1.0f, 1.0f };
  1008. ctx->device.lock()->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1009. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1010. if (compute_queue_family_index != transfer_queue_family_index) {
  1011. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1012. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1013. } else if(!ctx->device.lock()->single_queue) {
  1014. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1015. } else {
  1016. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1017. }
  1018. vk::DeviceCreateInfo device_create_info;
  1019. std::vector<const char *> device_extensions;
  1020. vk::PhysicalDeviceFeatures device_features = ctx->device.lock()->physical_device.getFeatures();
  1021. VkPhysicalDeviceFeatures2 device_features2;
  1022. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1023. device_features2.pNext = nullptr;
  1024. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1025. VkPhysicalDeviceVulkan11Features vk11_features;
  1026. vk11_features.pNext = nullptr;
  1027. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1028. device_features2.pNext = &vk11_features;
  1029. VkPhysicalDeviceVulkan12Features vk12_features;
  1030. vk12_features.pNext = nullptr;
  1031. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1032. vk11_features.pNext = &vk12_features;
  1033. vkGetPhysicalDeviceFeatures2(ctx->device.lock()->physical_device, &device_features2);
  1034. ctx->device.lock()->fp16 = ctx->device.lock()->fp16 && vk12_features.shaderFloat16;
  1035. if (!vk11_features.storageBuffer16BitAccess) {
  1036. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  1037. throw std::runtime_error("Unsupported device");
  1038. }
  1039. device_extensions.push_back("VK_KHR_16bit_storage");
  1040. #ifdef GGML_VULKAN_VALIDATE
  1041. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  1042. #endif
  1043. if (ctx->device.lock()->fp16) {
  1044. device_extensions.push_back("VK_KHR_shader_float16_int8");
  1045. }
  1046. ctx->device.lock()->name = ctx->device.lock()->properties.deviceName.data();
  1047. device_create_info = {
  1048. vk::DeviceCreateFlags(),
  1049. device_queue_create_infos,
  1050. {},
  1051. device_extensions
  1052. };
  1053. device_create_info.setPNext(&device_features2);
  1054. ctx->device.lock()->device = ctx->device.lock()->physical_device.createDevice(device_create_info);
  1055. ctx->device.lock()->descriptor_set_mode = VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN;
  1056. // Shaders
  1057. ggml_vk_load_shaders(ctx);
  1058. // Queues
  1059. ggml_vk_create_queue(ctx, ctx->device.lock()->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer });
  1060. if (!ctx->device.lock()->single_queue) {
  1061. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  1062. ggml_vk_create_queue(ctx, ctx->device.lock()->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer });
  1063. } else {
  1064. // TODO: Use pointer or reference to avoid copy
  1065. ctx->device.lock()->transfer_queue = ctx->device.lock()->compute_queue;
  1066. }
  1067. ctx->fence = ctx->device.lock()->device.createFence({});
  1068. ctx->compute_ctx = nullptr;
  1069. ctx->transfer_ctx = nullptr;
  1070. ctx->disable = false;
  1071. ctx->initialized = true;
  1072. ctx->idx = idx;
  1073. #ifdef GGML_VULKAN_CHECK_RESULTS
  1074. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  1075. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  1076. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  1077. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  1078. #endif
  1079. }
  1080. static vk_pipeline* ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  1081. #ifdef GGML_VULKAN_DEBUG
  1082. std::cerr << "ggml_vk_get_to_fp16()" << std::endl;
  1083. #endif
  1084. switch (type) {
  1085. case GGML_TYPE_F32:
  1086. case GGML_TYPE_Q4_0:
  1087. case GGML_TYPE_Q4_1:
  1088. case GGML_TYPE_Q5_0:
  1089. case GGML_TYPE_Q5_1:
  1090. case GGML_TYPE_Q8_0:
  1091. case GGML_TYPE_Q2_K:
  1092. case GGML_TYPE_Q3_K:
  1093. case GGML_TYPE_Q4_K:
  1094. case GGML_TYPE_Q5_K:
  1095. case GGML_TYPE_Q6_K:
  1096. break;
  1097. default:
  1098. return nullptr;
  1099. }
  1100. return &ctx->pipeline_dequant[type];
  1101. }
  1102. static vk_pipeline* ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type type) {
  1103. #ifdef GGML_VULKAN_DEBUG
  1104. std::cerr << "ggml_vk_get_dequantize_mul_mat_vec()" << std::endl;
  1105. #endif
  1106. switch (type) {
  1107. case GGML_TYPE_F16:
  1108. case GGML_TYPE_Q4_0:
  1109. case GGML_TYPE_Q4_1:
  1110. case GGML_TYPE_Q5_0:
  1111. case GGML_TYPE_Q5_1:
  1112. case GGML_TYPE_Q8_0:
  1113. case GGML_TYPE_Q2_K:
  1114. case GGML_TYPE_Q3_K:
  1115. case GGML_TYPE_Q4_K:
  1116. case GGML_TYPE_Q5_K:
  1117. case GGML_TYPE_Q6_K:
  1118. break;
  1119. default:
  1120. return nullptr;
  1121. }
  1122. return &ctx->pipeline_dequant_mul_mat_vec_f32[type];
  1123. }
  1124. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  1125. #ifdef GGML_VULKAN_DEBUG
  1126. std::cerr << "ggml_vk_pool_malloc(" << size << ")" << std::endl;
  1127. #endif
  1128. int best_i = -1;
  1129. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  1130. int worst_i = -1;
  1131. size_t worst_size = 0; //largest unused buffer seen so far
  1132. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  1133. vk_buffer &b = ctx->buffer_pool[i];
  1134. if (b != nullptr && b->size >= size && b->size < best_size) {
  1135. best_i = i;
  1136. best_size = b->size;
  1137. }
  1138. if (b != nullptr && b->size > worst_size) {
  1139. worst_i = i;
  1140. worst_size = b->size;
  1141. }
  1142. }
  1143. if(best_i != -1) {
  1144. //found the smallest buffer that fits our needs
  1145. vk_buffer b = ctx->buffer_pool[best_i];
  1146. ctx->buffer_pool[best_i].reset();
  1147. return b;
  1148. }
  1149. if(worst_i != -1) {
  1150. //no buffer that fits our needs, resize largest one to save memory
  1151. vk_buffer& b = ctx->buffer_pool[worst_i];
  1152. ggml_vk_destroy_buffer(b);
  1153. }
  1154. return ggml_vk_create_buffer_check(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1155. }
  1156. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  1157. #ifdef GGML_VULKAN_DEBUG
  1158. std::cerr << "ggml_vk_pool_free(" << buffer->size << ")" << std::endl;
  1159. #endif
  1160. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  1161. vk_buffer& b = ctx->buffer_pool[i];
  1162. if (b == nullptr) {
  1163. b = buffer;
  1164. return;
  1165. }
  1166. }
  1167. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  1168. ggml_vk_destroy_buffer(buffer);
  1169. }
  1170. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  1171. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  1172. // Try to find existing temp buffer with enough capacity
  1173. for (auto& buffer : ctx->gc.temp_buffers) {
  1174. if (buffer->size >= size) {
  1175. return buffer;
  1176. }
  1177. }
  1178. // Otherwise create new buffer
  1179. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  1180. ctx->gc.temp_buffers.push_back(buf);
  1181. return buf;
  1182. }
  1183. static void * ggml_vk_host_malloc(ggml_backend_vk_context * ctx, size_t size) {
  1184. #ifdef GGML_VULKAN_DEBUG
  1185. std::cerr << "ggml_vk_host_malloc(" << size << ")" << std::endl;
  1186. #endif
  1187. vk_buffer buf = ggml_vk_create_buffer(ctx, size,
  1188. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  1189. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1190. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  1191. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  1192. size/1024.0/1024.0);
  1193. ctx->device.lock()->device.freeMemory(buf->device_memory);
  1194. ctx->device.lock()->device.destroyBuffer(buf->buffer);
  1195. return nullptr;
  1196. }
  1197. ctx->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  1198. return buf->ptr;
  1199. }
  1200. static void ggml_vk_host_free(ggml_backend_vk_context * ctx, void* ptr) {
  1201. if (ptr == nullptr) {
  1202. return;
  1203. }
  1204. #ifdef GGML_VULKAN_DEBUG
  1205. std::cerr << "ggml_vk_host_free(" << ptr << ")" << std::endl;
  1206. #endif
  1207. vk_buffer buf;
  1208. size_t index;
  1209. for (size_t i = 0; i < ctx->pinned_memory.size(); i++) {
  1210. const uint8_t* addr = (const uint8_t*) std::get<0>(ctx->pinned_memory[i]);
  1211. const uint8_t* endr = addr + std::get<1>(ctx->pinned_memory[i]);
  1212. if (ptr >= addr && ptr < endr) {
  1213. buf = std::get<2>(ctx->pinned_memory[i]);
  1214. index = i;
  1215. break;
  1216. }
  1217. }
  1218. if (buf == nullptr) {
  1219. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  1220. return;
  1221. }
  1222. ggml_vk_destroy_buffer(buf);
  1223. ctx->pinned_memory.erase(ctx->pinned_memory.begin() + index);
  1224. }
  1225. static void ggml_vk_host_get(ggml_backend_vk_context * ctx, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  1226. buf = nullptr;
  1227. buf_offset = 0;
  1228. for (size_t i = 0; i < ctx->pinned_memory.size(); i++) {
  1229. const uint8_t* addr = (const uint8_t*) std::get<0>(ctx->pinned_memory[i]);
  1230. const uint8_t* endr = addr + std::get<1>(ctx->pinned_memory[i]);
  1231. if (ptr >= addr && ptr < endr) {
  1232. buf = std::get<2>(ctx->pinned_memory[i]);
  1233. buf_offset = ((const uint8_t *)ptr) - addr;
  1234. break;
  1235. }
  1236. }
  1237. }
  1238. static vk_submission ggml_vk_begin_submission(ggml_backend_vk_context * ctx, vk_queue& q, bool one_time = true) {
  1239. vk_submission s;
  1240. s.buffer = ggml_vk_create_cmd_buffer(ctx, q);
  1241. if (one_time) {
  1242. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  1243. } else {
  1244. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  1245. }
  1246. return s;
  1247. }
  1248. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context * ctx, vk_context * subctx, vk_pipeline& pipeline, std::vector<vk_subbuffer>&& buffers, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  1249. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline.wg_denoms[0]);
  1250. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline.wg_denoms[1]);
  1251. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline.wg_denoms[2]);
  1252. #ifdef GGML_VULKAN_DEBUG
  1253. std::cerr << "ggml_vk_dispatch_pipeline(" << pipeline.name << ", (" << wg0 << "," << wg1 << "," << wg2 << "))" << std::endl;
  1254. #endif
  1255. std::vector<vk::DescriptorBufferInfo> descriptor_buffer_infos;
  1256. std::vector<vk::WriteDescriptorSet> write_descriptor_sets;
  1257. GGML_ASSERT(pipeline.descriptor_set_idx < pipeline.descriptor_sets.size());
  1258. GGML_ASSERT(buffers.size() == pipeline.parameter_count);
  1259. vk::DescriptorSet& descriptor_set = pipeline.descriptor_sets[pipeline.descriptor_set_idx++];
  1260. for (uint32_t i = 0; i < pipeline.parameter_count; i++) {
  1261. descriptor_buffer_infos.push_back({buffers[i].buffer->buffer, buffers[i].offset, buffers[i].size});
  1262. }
  1263. for (uint32_t i = 0; i < pipeline.parameter_count; i++) {
  1264. write_descriptor_sets.push_back({descriptor_set, i, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &descriptor_buffer_infos[i]});
  1265. }
  1266. ctx->device.lock()->device.updateDescriptorSets(write_descriptor_sets, {});
  1267. subctx->s->buffer.pushConstants(pipeline.layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  1268. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline.pipeline);
  1269. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  1270. pipeline.layout,
  1271. 0,
  1272. { descriptor_set },
  1273. {});
  1274. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  1275. }
  1276. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  1277. s.buffer.end();
  1278. s.wait_semaphores = std::move(wait_semaphores);
  1279. s.signal_semaphores = std::move(signal_semaphores);
  1280. }
  1281. static void ggml_vk_ctx_end(vk_context * ctx) {
  1282. #ifdef GGML_VULKAN_DEBUG
  1283. std::cerr << "ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")" << std::endl;
  1284. #endif
  1285. if (ctx->s == nullptr) {
  1286. return;
  1287. }
  1288. ctx->s->buffer.end();
  1289. ctx->s = nullptr;
  1290. }
  1291. static void ggml_vk_ctx_begin(ggml_backend_vk_context * ctx, vk_context * subctx) {
  1292. #ifdef GGML_VULKAN_DEBUG
  1293. std::cerr << "ggml_vk_ctx_begin(" << ctx << ")" << std::endl;
  1294. #endif
  1295. if (subctx->s != nullptr) {
  1296. ggml_vk_ctx_end(subctx);
  1297. }
  1298. subctx->seqs.push_back({ ggml_vk_begin_submission(ctx, *subctx->q) });
  1299. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  1300. }
  1301. static size_t ggml_vk_align_size(size_t width, size_t align) {
  1302. return CEIL_DIV(width, align) * align;
  1303. }
  1304. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  1305. if (memcpys == nullptr) {
  1306. memcpy(dst, src, size);
  1307. } else {
  1308. memcpys->emplace_back(dst, src, size);
  1309. }
  1310. }
  1311. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  1312. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  1313. ggml_vk_destroy_buffer(ctx->sync_staging);
  1314. ctx->sync_staging = ggml_vk_create_buffer_check(ctx, size,
  1315. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  1316. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1317. }
  1318. }
  1319. 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) {
  1320. #ifdef GGML_VULKAN_DEBUG
  1321. std::cerr << "ggml_vk_buffer_write_nc_async(" << tensor << ")" << std::endl;
  1322. #endif
  1323. GGML_ASSERT(!ggml_is_contiguous(tensor));
  1324. // Buffer is already mapped
  1325. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1326. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  1327. GGML_ASSERT(false);
  1328. }
  1329. // Check if src is pinned memory
  1330. vk_buffer buf;
  1331. size_t buf_offset;
  1332. ggml_vk_host_get(ctx, tensor->data, buf, buf_offset);
  1333. const uint64_t ne0 = tensor->ne[0];
  1334. const uint64_t ne1 = tensor->ne[1];
  1335. const uint64_t ne2 = tensor->ne[2];
  1336. const uint64_t ne3 = tensor->ne[3];
  1337. const uint64_t nb0 = tensor->nb[0];
  1338. const uint64_t nb1 = tensor->nb[1];
  1339. const uint64_t nb2 = tensor->nb[2];
  1340. const uint64_t nb3 = tensor->nb[3];
  1341. const ggml_type type = tensor->type;
  1342. const uint64_t ts = ggml_type_size(type);
  1343. const uint64_t bs = ggml_blck_size(type);
  1344. const uint64_t dstnb0 = ts;
  1345. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  1346. const uint64_t dstnb2 = dstnb1*ne1;
  1347. const uint64_t dstnb3 = dstnb2*ne2;
  1348. const uint64_t ne = ggml_nelements(tensor);
  1349. if (buf != nullptr) {
  1350. // Memory is pinned, use as staging buffer
  1351. std::vector<vk::BufferCopy> slices;
  1352. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  1353. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  1354. // Find longest contiguous slice
  1355. if (ne1*nb1 == dstnb2) {
  1356. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  1357. } else {
  1358. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1359. if (ne0*nb0/bs == dstnb1) {
  1360. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  1361. } else {
  1362. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  1363. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  1364. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  1365. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. }
  1372. ggml_vk_sync_buffers(subctx);
  1373. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  1374. return;
  1375. }
  1376. // Staging buffer required
  1377. vk_buffer staging = ctx->staging;
  1378. size_t staging_offset = ctx->staging_offset;
  1379. const size_t copy_size = ts*ne/bs;
  1380. if (ctx->staging->size < ctx->staging_offset + copy_size) {
  1381. if (sync_staging) {
  1382. // Create temporary larger buffer
  1383. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1384. staging = ctx->sync_staging;
  1385. staging_offset = 0;
  1386. } else {
  1387. GGML_ASSERT(false);
  1388. }
  1389. }
  1390. VkBufferCopy buf_copy{ staging_offset, offset, copy_size };
  1391. ggml_vk_sync_buffers(subctx);
  1392. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  1393. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  1394. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  1395. // Find longest contiguous slice
  1396. if (ne1*nb1 == dstnb2) {
  1397. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i3*dstnb3 + i2*dstnb2, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2, dstnb2, &subctx->in_memcpys);
  1398. } else {
  1399. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1400. if (ne0*nb0/bs == dstnb1) {
  1401. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2 + i1*nb1, dstnb1, &subctx->in_memcpys);
  1402. } else {
  1403. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  1404. const uint64_t d_off = staging_offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  1405. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  1406. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  1407. }
  1408. }
  1409. }
  1410. }
  1411. }
  1412. }
  1413. }
  1414. static void ggml_vk_buffer_write_2d_async(ggml_backend_vk_context * ctx, 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) {
  1415. #ifdef GGML_VULKAN_DEBUG
  1416. std::cerr << "ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")" << std::endl;
  1417. #endif
  1418. // Make sure ctx owns the buffer
  1419. GGML_ASSERT(dst->ctx == ctx);
  1420. // Buffer is already mapped
  1421. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1422. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  1423. GGML_ASSERT(false);
  1424. }
  1425. // Check if src is pinned memory
  1426. vk_buffer buf = nullptr;
  1427. size_t buf_offset;
  1428. ggml_vk_host_get(ctx, src, buf, buf_offset);
  1429. if (buf != nullptr) {
  1430. // Memory is pinned, use as staging buffer
  1431. std::vector<vk::BufferCopy> slices(1);
  1432. if (width == spitch) {
  1433. // Only do single write if stride is equal
  1434. slices[0].srcOffset = buf_offset;
  1435. slices[0].dstOffset = offset;
  1436. slices[0].size = width * height;
  1437. } else {
  1438. slices.resize(height);
  1439. for (size_t i = 0; i < height; i++) {
  1440. slices[i].srcOffset = buf_offset + i * spitch;
  1441. slices[i].dstOffset = offset + i * width;
  1442. slices[i].size = width;
  1443. }
  1444. }
  1445. ggml_vk_sync_buffers(subctx);
  1446. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  1447. return;
  1448. }
  1449. #ifdef GGML_VULKAN_DEBUG
  1450. std::cerr << "STAGING" << std::endl;
  1451. #endif
  1452. // Staging buffer required
  1453. vk_buffer staging = ctx->staging;
  1454. size_t staging_offset = ctx->staging_offset;
  1455. const size_t copy_size = width*height;
  1456. if (ctx->staging == nullptr || ctx->staging->size < ctx->staging_offset + copy_size) {
  1457. if (sync_staging) {
  1458. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1459. staging = ctx->sync_staging;
  1460. staging_offset = 0;
  1461. } else {
  1462. GGML_ASSERT(false);
  1463. }
  1464. }
  1465. VkBufferCopy buf_copy = {
  1466. staging_offset,
  1467. offset,
  1468. copy_size};
  1469. ggml_vk_sync_buffers(subctx);
  1470. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  1471. if (width == spitch) {
  1472. deferred_memcpy((uint8_t *)staging->ptr + staging_offset, src, width * height, &subctx->in_memcpys);
  1473. } else {
  1474. for (size_t i = 0; i < height; i++) {
  1475. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  1476. }
  1477. }
  1478. }
  1479. static void ggml_vk_buffer_write_async(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  1480. #ifdef GGML_VULKAN_DEBUG
  1481. std::cerr << "ggml_vk_buffer_write_async(" << size << ")" << std::endl;
  1482. #endif
  1483. return ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, src, size, size, 1, sync_staging);
  1484. }
  1485. static void ggml_vk_buffer_write_2d(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height) {
  1486. #ifdef GGML_VULKAN_DEBUG
  1487. std::cerr << "ggml_vk_buffer_write_2d(" << width << ", " << height << ")" << std::endl;
  1488. #endif
  1489. // Buffer is already mapped
  1490. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1491. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  1492. for (size_t i = 0; i < height; i++) {
  1493. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  1494. }
  1495. } else {
  1496. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  1497. ggml_vk_ctx_begin(ctx, subctx);
  1498. ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, src, spitch, width, height, true);
  1499. ggml_vk_ctx_end(subctx);
  1500. for (auto& cpy : subctx->in_memcpys) {
  1501. memcpy(cpy.dst, cpy.src, cpy.n);
  1502. }
  1503. ggml_vk_submit(subctx, ctx->fence);
  1504. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  1505. ctx->device.lock()->device.resetFences({ ctx->fence });
  1506. }
  1507. }
  1508. static void ggml_vk_buffer_write(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, const void * src, size_t size) {
  1509. #ifdef GGML_VULKAN_DEBUG
  1510. std::cerr << "ggml_vk_buffer_write(" << size << ")" << std::endl;
  1511. #endif
  1512. ggml_vk_buffer_write_2d(ctx, dst, offset, src, 0, size, 1);
  1513. }
  1514. static void ggml_vk_buffer_read_2d_async(ggml_backend_vk_context * ctx, 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) {
  1515. #ifdef GGML_VULKAN_DEBUG
  1516. std::cerr << "ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")" << std::endl;
  1517. #endif
  1518. GGML_ASSERT(width > 0);
  1519. GGML_ASSERT(height > 0);
  1520. GGML_ASSERT(src != nullptr);
  1521. // Make sure ctx owns the buffer
  1522. GGML_ASSERT(src->ctx == ctx);
  1523. // Check if dst is pinned memory
  1524. vk_buffer buf = nullptr;
  1525. size_t buf_offset;
  1526. ggml_vk_host_get(ctx, dst, buf, buf_offset);
  1527. std::vector<vk::BufferCopy> slices(1);
  1528. if (width == spitch && width == dpitch) {
  1529. // Only do single write if stride is equal
  1530. slices[0].srcOffset = offset;
  1531. slices[0].dstOffset = buf_offset;
  1532. slices[0].size = width * height;
  1533. } else {
  1534. slices.resize(height);
  1535. for (size_t i = 0; i < height; i++) {
  1536. slices[i].srcOffset = offset + i * spitch;
  1537. slices[i].dstOffset = buf_offset + i * dpitch;
  1538. slices[i].size = width;
  1539. }
  1540. }
  1541. if (buf != nullptr) {
  1542. // Memory is pinned, use as staging buffer
  1543. ggml_vk_sync_buffers(subctx);
  1544. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  1545. return;
  1546. }
  1547. #ifdef GGML_VULKAN_DEBUG
  1548. std::cerr << "STAGING" << std::endl;
  1549. #endif
  1550. // Fall back to staging buffer
  1551. vk_buffer staging = ctx->staging;
  1552. const size_t copy_size = dpitch * height;
  1553. if (ctx->staging == nullptr || ctx->staging->size < ctx->staging_offset + copy_size) {
  1554. if (sync_staging) {
  1555. // Create temporary larger buffer
  1556. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1557. staging = ctx->sync_staging;
  1558. } else {
  1559. GGML_ASSERT(false);
  1560. }
  1561. }
  1562. ggml_vk_sync_buffers(subctx);
  1563. subctx->s->buffer.copyBuffer(src->buffer, staging->buffer, slices);
  1564. deferred_memcpy(dst, staging->ptr, copy_size, &subctx->out_memcpys);
  1565. }
  1566. static void ggml_vk_buffer_read_async(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  1567. return ggml_vk_buffer_read_2d_async(ctx, subctx, src, offset, dst, size, size, size, 1, sync_staging);
  1568. }
  1569. static void ggml_vk_buffer_read(ggml_backend_vk_context * ctx, vk_buffer& src, size_t offset, void * dst, size_t size) {
  1570. #ifdef GGML_VULKAN_DEBUG
  1571. std::cerr << "ggml_vk_buffer_read(" << offset << ", " << size << ")" << std::endl;
  1572. #endif
  1573. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1574. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  1575. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  1576. } else {
  1577. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  1578. ggml_vk_ctx_begin(ctx, subctx);
  1579. ggml_vk_buffer_read_async(ctx, subctx, src, offset, dst, size, true);
  1580. ggml_vk_ctx_end(subctx);
  1581. ggml_vk_submit(subctx, ctx->fence);
  1582. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  1583. ctx->device.lock()->device.resetFences({ ctx->fence });
  1584. for (auto& cpy : subctx->out_memcpys) {
  1585. memcpy(cpy.dst, cpy.src, cpy.n);
  1586. }
  1587. }
  1588. }
  1589. 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) {
  1590. #ifdef GGML_VULKAN_DEBUG
  1591. std::cerr << "ggml_vk_buffer_copy_async(" << size << ")" << std::endl;
  1592. #endif
  1593. // Make sure both buffers are on same ctx
  1594. GGML_ASSERT(src->ctx == dst->ctx);
  1595. VkBufferCopy bc{ src_offset, dst_offset, size };
  1596. vkCmdCopyBuffer(ctx->s->buffer, src->buffer, dst->buffer, 1, &bc);
  1597. }
  1598. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  1599. if (src->ctx == dst->ctx) {
  1600. #ifdef GGML_VULKAN_DEBUG
  1601. std::cerr << "ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")" << std::endl;
  1602. #endif
  1603. // Copy within the device
  1604. ggml_backend_vk_context * ctx = src->ctx;
  1605. VkBufferCopy bc{ src_offset, dst_offset, size };
  1606. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  1607. ggml_vk_ctx_begin(ctx, subctx);
  1608. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  1609. ggml_vk_ctx_end(subctx);
  1610. ggml_vk_submit(subctx, ctx->fence);
  1611. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  1612. ctx->device.lock()->device.resetFences({ ctx->fence });
  1613. } else {
  1614. #ifdef GGML_VULKAN_DEBUG
  1615. std::cerr << "ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")" << std::endl;
  1616. #endif
  1617. // Copy device to device
  1618. ggml_backend_vk_context * src_ctx = src->ctx;
  1619. ggml_backend_vk_context * dst_ctx = dst->ctx;
  1620. ggml_vk_ensure_sync_staging_buffer(src_ctx, size);
  1621. ggml_vk_ensure_sync_staging_buffer(dst_ctx, size);
  1622. // Copy to src staging buffer
  1623. ggml_vk_buffer_copy(src_ctx->sync_staging, 0, src, src_offset, size);
  1624. // memcpy to dst staging buffer
  1625. memcpy(dst_ctx->sync_staging->ptr, src_ctx->sync_staging->ptr, size);
  1626. // Copy to dst buffer
  1627. ggml_vk_buffer_copy(dst, dst_offset, dst_ctx->sync_staging, 0, size);
  1628. }
  1629. }
  1630. static void ggml_vk_buffer_memset(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  1631. #ifdef GGML_VULKAN_DEBUG
  1632. std::cerr << "ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")" << std::endl;
  1633. #endif
  1634. // Make sure ctx owns the buffer
  1635. GGML_ASSERT(dst->ctx == ctx);
  1636. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  1637. ggml_vk_ctx_begin(ctx, subctx);
  1638. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  1639. ggml_vk_ctx_end(subctx);
  1640. ggml_vk_submit(subctx, ctx->fence);
  1641. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  1642. ctx->device.lock()->device.resetFences({ ctx->fence });
  1643. }
  1644. static void ggml_vk_h2d_tensor_2d(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& dst, size_t offset, const ggml_tensor * src, uint64_t i3, uint64_t i2, uint64_t i1) {
  1645. #ifdef GGML_VULKAN_DEBUG
  1646. std::cerr << "ggml_vk_h2d_tensor_2d(dst=" << dst << ", offset=" << offset << ", src=" << src << ", i3=" << i3 << ", i2=" << i2 << ", i1=" << i1 << ")" << std::endl;
  1647. #endif
  1648. const uint64_t ne0 = src->ne[0];
  1649. const uint64_t ne1 = src->ne[1];
  1650. const uint64_t nb0 = src->nb[0];
  1651. const uint64_t nb1 = src->nb[1];
  1652. const uint64_t nb2 = src->nb[2];
  1653. const uint64_t nb3 = src->nb[3];
  1654. const enum ggml_type type = src->type;
  1655. const size_t ts = ggml_type_size(type);
  1656. const size_t bs = ggml_blck_size(type);
  1657. const size_t row_length = ts*ne0/bs;
  1658. const void * x = (const void *) ((const char *) src->data + i2*nb2 + i3*nb3);
  1659. if (nb0 == ts && nb1 == row_length) {
  1660. return ggml_vk_buffer_write_async(ctx, subctx, dst, offset, x, i1*nb1);
  1661. }
  1662. if (nb0 == ts && (i1 == ne1 || !ggml_is_permuted(src))) {
  1663. return ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, x, nb1, row_length, i1);
  1664. }
  1665. GGML_ASSERT(i3 == 0);
  1666. GGML_ASSERT(i2 == 0);
  1667. GGML_ASSERT(i1 == (uint64_t) ggml_nrows(src));
  1668. return ggml_vk_buffer_write_nc_async(ctx, subctx, dst, offset, src);
  1669. }
  1670. static void ggml_vk_d2h_tensor_2d(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& src, size_t offset, const ggml_tensor * dst) {
  1671. #ifdef GGML_VULKAN_DEBUG
  1672. std::cerr << "ggml_vk_d2h_tensor_2d()" << std::endl;
  1673. #endif
  1674. const uint64_t ne0 = dst->ne[0];
  1675. const uint64_t ne1 = dst->ne[1];
  1676. const uint64_t ne2 = dst->ne[2];
  1677. const uint64_t ne3 = dst->ne[3];
  1678. const uint64_t nb0 = dst->nb[0];
  1679. const uint64_t nb1 = dst->nb[1];
  1680. // const uint64_t nb2 = dst->nb[2];
  1681. // const uint64_t nb3 = dst->nb[3];
  1682. const enum ggml_type type = dst->type;
  1683. const size_t ts = ggml_type_size(type);
  1684. const size_t bs = ggml_blck_size(type);
  1685. const size_t row_length = ts*ne0/bs;
  1686. if (ggml_is_contiguous(dst)) {
  1687. return ggml_vk_buffer_read_async(ctx, subctx, src, offset, dst->data, ne1*nb1*ne2*ne3);
  1688. }
  1689. if (nb0 == ts) {
  1690. return ggml_vk_buffer_read_2d_async(ctx, subctx, src, offset, dst->data, nb1, nb1, row_length, ne1*ne2*ne3);
  1691. }
  1692. GGML_ASSERT(false);
  1693. }
  1694. static uint32_t ggml_vk_guess_split_k(int m, int n, int k) {
  1695. #ifdef GGML_VULKAN_DEBUG
  1696. std::cerr << "ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")";
  1697. #endif
  1698. if (k > 128 && (m < 128 || n < 128) && m > 2 && n > 2) {
  1699. #ifdef GGML_VULKAN_DEBUG
  1700. std::cerr << " = 4" << std::endl;
  1701. #endif
  1702. return 4;
  1703. }
  1704. #ifdef GGML_VULKAN_DEBUG
  1705. std::cerr << " = 1" << std::endl;
  1706. #endif
  1707. return 1;
  1708. }
  1709. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, int m, int n) {
  1710. #ifdef GGML_VULKAN_DEBUG
  1711. std::cerr << "ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")" << std::endl;
  1712. #endif
  1713. if (m <= 32 || n <= 32) {
  1714. return ctx->pipeline_matmul_f32_aligned_s.align;
  1715. }
  1716. if (ctx->device.lock()->subgroup_size == 64 || m <= 64 || n <= 64) {
  1717. return ctx->pipeline_matmul_f32_aligned_m.align;
  1718. }
  1719. return ctx->pipeline_matmul_f32_aligned_l.align;
  1720. }
  1721. static vk_pipeline* ggml_vk_guess_matmul_pipeline_amd(ggml_backend_vk_context * ctx, bool bit16_x, bool bit16_y, int m, int n, bool aligned) {
  1722. if (bit16_x && bit16_y) {
  1723. if (m <= 32 || n <= 32) {
  1724. #ifdef GGML_VULKAN_DEBUG
  1725. std::cerr << " S" << std::endl;
  1726. #endif
  1727. return aligned ? &ctx->pipeline_matmul_f16_aligned_s : &ctx->pipeline_matmul_f16_s;
  1728. }
  1729. #ifdef GGML_VULKAN_DEBUG
  1730. std::cerr << " M" << std::endl;
  1731. #endif
  1732. return aligned ? &ctx->pipeline_matmul_f16_aligned_m : &ctx->pipeline_matmul_f16_m;
  1733. }
  1734. if (bit16_x && !bit16_y) {
  1735. if (m <= 32 || n <= 32) {
  1736. #ifdef GGML_VULKAN_DEBUG
  1737. std::cerr << " S" << std::endl;
  1738. #endif
  1739. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_s : &ctx->pipeline_matmul_f16_f32_s;
  1740. }
  1741. #ifdef GGML_VULKAN_DEBUG
  1742. std::cerr << " M" << std::endl;
  1743. #endif
  1744. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_m : &ctx->pipeline_matmul_f16_f32_m;
  1745. }
  1746. if (!bit16_x && bit16_y) {
  1747. GGML_ASSERT(false);
  1748. }
  1749. if (m <= 32 || n <= 32) {
  1750. #ifdef GGML_VULKAN_DEBUG
  1751. std::cerr << " S" << std::endl;
  1752. #endif
  1753. return aligned ? &ctx->pipeline_matmul_f32_aligned_s : &ctx->pipeline_matmul_f32_s;
  1754. }
  1755. #ifdef GGML_VULKAN_DEBUG
  1756. std::cerr << " M" << std::endl;
  1757. #endif
  1758. return aligned ? &ctx->pipeline_matmul_f32_aligned_m : &ctx->pipeline_matmul_f32_m;
  1759. }
  1760. static vk_pipeline* ggml_vk_guess_matmul_pipeline_apple(ggml_backend_vk_context * ctx, bool bit16_x, bool bit16_y, bool aligned) {
  1761. #ifdef GGML_VULKAN_DEBUG
  1762. std::cerr << " M" << std::endl;
  1763. #endif
  1764. if (bit16_x && bit16_y) {
  1765. return aligned ? &ctx->pipeline_matmul_f16_aligned_m : &ctx->pipeline_matmul_f16_m;
  1766. }
  1767. if (bit16_x && !bit16_y) {
  1768. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_m : &ctx->pipeline_matmul_f16_f32_m;
  1769. }
  1770. if (!bit16_x && bit16_y) {
  1771. GGML_ASSERT(false);
  1772. }
  1773. return aligned ? &ctx->pipeline_matmul_f32_aligned_m : &ctx->pipeline_matmul_f32_m;
  1774. }
  1775. static vk_pipeline* ggml_vk_guess_matmul_pipeline_intel(ggml_backend_vk_context * ctx, bool bit16_x, bool bit16_y, bool aligned) {
  1776. #ifdef GGML_VULKAN_DEBUG
  1777. std::cerr << " S" << std::endl;
  1778. #endif
  1779. if (bit16_x && bit16_y) {
  1780. return aligned ? &ctx->pipeline_matmul_f16_aligned_s : &ctx->pipeline_matmul_f16_s;
  1781. }
  1782. if (bit16_x && !bit16_y) {
  1783. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_s : &ctx->pipeline_matmul_f16_f32_s;
  1784. }
  1785. if (!bit16_x && bit16_y) {
  1786. GGML_ASSERT(false);
  1787. }
  1788. return aligned ? &ctx->pipeline_matmul_f32_aligned_s : &ctx->pipeline_matmul_f32_s;
  1789. }
  1790. static vk_pipeline* ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, bool bit16_x, bool bit16_y, int m, int n, bool aligned) {
  1791. #ifdef GGML_VULKAN_DEBUG
  1792. std::cerr << "ggml_vk_guess_matmul_pipeline(" << bit16_x << ", " << bit16_y << ", " << m << ", " << n << ", " << aligned << ")";
  1793. #endif
  1794. switch (ctx->device.lock()->vendor_id) {
  1795. case VK_VENDOR_ID_AMD:
  1796. return ggml_vk_guess_matmul_pipeline_amd(ctx, bit16_x, bit16_y, m, n, aligned);
  1797. case VK_VENDOR_ID_APPLE:
  1798. return ggml_vk_guess_matmul_pipeline_apple(ctx, bit16_x, bit16_y, aligned);
  1799. case VK_VENDOR_ID_INTEL:
  1800. return ggml_vk_guess_matmul_pipeline_intel(ctx, bit16_x, bit16_y, aligned);
  1801. }
  1802. if (bit16_x && bit16_y) {
  1803. if (m <= 32 || n <= 32) {
  1804. #ifdef GGML_VULKAN_DEBUG
  1805. std::cerr << " S" << std::endl;
  1806. #endif
  1807. return aligned ? &ctx->pipeline_matmul_f16_aligned_s : &ctx->pipeline_matmul_f16_s;
  1808. }
  1809. if (m <= 64 || n <= 64) {
  1810. #ifdef GGML_VULKAN_DEBUG
  1811. std::cerr << " M" << std::endl;
  1812. #endif
  1813. return aligned ? &ctx->pipeline_matmul_f16_aligned_m : &ctx->pipeline_matmul_f16_m;
  1814. }
  1815. #ifdef GGML_VULKAN_DEBUG
  1816. std::cerr << " L" << std::endl;
  1817. #endif
  1818. return aligned ? &ctx->pipeline_matmul_f16_aligned_l : &ctx->pipeline_matmul_f16_l;
  1819. }
  1820. if (bit16_x && !bit16_y) {
  1821. if (m <= 32 || n <= 32) {
  1822. #ifdef GGML_VULKAN_DEBUG
  1823. std::cerr << " S" << std::endl;
  1824. #endif
  1825. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_s : &ctx->pipeline_matmul_f16_f32_s;
  1826. }
  1827. if (m <= 64 || n <= 64) {
  1828. #ifdef GGML_VULKAN_DEBUG
  1829. std::cerr << " M" << std::endl;
  1830. #endif
  1831. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_m : &ctx->pipeline_matmul_f16_f32_m;
  1832. }
  1833. #ifdef GGML_VULKAN_DEBUG
  1834. std::cerr << " L" << std::endl;
  1835. #endif
  1836. return aligned ? &ctx->pipeline_matmul_f16_f32_aligned_l : &ctx->pipeline_matmul_f16_f32_l;
  1837. }
  1838. if (!bit16_x && bit16_y) {
  1839. GGML_ASSERT(false);
  1840. }
  1841. if (m <= 32 || n <= 32) {
  1842. #ifdef GGML_VULKAN_DEBUG
  1843. std::cerr << " S" << std::endl;
  1844. #endif
  1845. return aligned ? &ctx->pipeline_matmul_f32_aligned_s : &ctx->pipeline_matmul_f32_s;
  1846. }
  1847. if (m <= 64 || n <= 64) {
  1848. #ifdef GGML_VULKAN_DEBUG
  1849. std::cerr << " M" << std::endl;
  1850. #endif
  1851. return aligned ? &ctx->pipeline_matmul_f32_aligned_m : &ctx->pipeline_matmul_f32_m;
  1852. }
  1853. #ifdef GGML_VULKAN_DEBUG
  1854. std::cerr << " L" << std::endl;
  1855. #endif
  1856. return aligned ? &ctx->pipeline_matmul_f32_aligned_l : &ctx->pipeline_matmul_f32_l;
  1857. }
  1858. static void ggml_vk_matmul(ggml_backend_vk_context * ctx, vk_context * subctx, vk_pipeline& pipeline, vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer, uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d) {
  1859. #ifdef GGML_VULKAN_DEBUG
  1860. std::cerr << "ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), c: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << split_k_buffer.buffer->buffer << ", " << 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 << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ")" << std::endl;
  1861. #endif
  1862. ggml_vk_sync_buffers(subctx);
  1863. if (split_k == 1) {
  1864. const std::array<uint32_t, 14> pc = { m, n, k, stride_a, stride_b, stride_d, k, ne02, ne12, broadcast2, broadcast3, batch_stride_a, batch_stride_b, batch_stride_d };
  1865. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc.size() * sizeof(uint32_t), pc.data(), { m, n, batch });
  1866. return;
  1867. }
  1868. GGML_ASSERT(batch_stride_d == m * n);
  1869. const std::array<uint32_t, 14> pc1 = { m, n, k, stride_a, stride_b, stride_d, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3, batch_stride_a, batch_stride_b, batch_stride_d };
  1870. // Make sure enough workgroups get assigned for split k to work
  1871. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1.size() * sizeof(uint32_t), pc1.data(), { (CEIL_DIV(m, pipeline.wg_denoms[0]) * pipeline.wg_denoms[0]) * split_k, n, batch });
  1872. ggml_vk_sync_buffers(subctx);
  1873. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  1874. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2.size() * sizeof(uint32_t), pc2.data(), { m * n * batch, 1, 1 });
  1875. }
  1876. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  1877. return
  1878. tensor->nb[0] == ggml_type_size(tensor->type) &&
  1879. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  1880. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1881. }
  1882. static vk_pipeline * ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, ggml_type from, ggml_type to) {
  1883. if (from == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  1884. return &ctx->pipeline_cpy_f32_f32;
  1885. }
  1886. if (from == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  1887. return &ctx->pipeline_cpy_f32_f16;
  1888. }
  1889. if (from == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  1890. return &ctx->pipeline_cpy_f16_f16;
  1891. }
  1892. std::cerr << "Missing CPY op for types: " << ggml_type_name(from) << " " << ggml_type_name(to) << std::endl;
  1893. GGML_ASSERT(false);
  1894. }
  1895. 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, ggml_type buffer_type, bool aligned=true) {
  1896. #ifdef GGML_VULKAN_DEBUG
  1897. std::cerr << "ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", backend=" << tensor->backend << ", 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] << "), ";
  1898. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")" << std::endl;
  1899. #endif
  1900. const int tensor_type_size = ggml_type_size(tensor->type);
  1901. const int dst_type_size = ggml_type_size(buffer_type);
  1902. const uint32_t ne = tensor->ne[0] * tensor->ne[1] * tensor->ne[2];
  1903. const uint32_t nb2 = aligned ? ggml_vk_align_size(dst_type_size * tensor->ne[0] * tensor->ne[1], ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size : tensor->ne[0] * tensor->ne[1];
  1904. const vk_op_cpy_push_constants pc = {
  1905. (uint32_t)ne,
  1906. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], (uint32_t)tensor->nb[0] / tensor_type_size, (uint32_t)tensor->nb[1] / tensor_type_size, (uint32_t)tensor->nb[2] / tensor_type_size,
  1907. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], 1 , (uint32_t)tensor->ne[0] , nb2,
  1908. 0,
  1909. };
  1910. ggml_vk_sync_buffers(subctx);
  1911. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { in, out }, sizeof(vk_op_cpy_push_constants), &pc, { ne, 1, 1 });
  1912. }
  1913. 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) {
  1914. #ifdef GGML_VULKAN_DEBUG
  1915. std::cerr << "ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  1916. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  1917. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  1918. #endif
  1919. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  1920. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  1921. const uint64_t ne00 = src0->ne[0];
  1922. const uint64_t ne01 = src0->ne[1];
  1923. const uint64_t ne02 = src0->ne[2];
  1924. const uint64_t ne03 = src0->ne[3];
  1925. const uint64_t ne10 = src1->ne[0];
  1926. const uint64_t ne11 = src1->ne[1];
  1927. const uint64_t ne12 = src1->ne[2];
  1928. const uint64_t ne13 = src1->ne[3];
  1929. const uint64_t ne20 = dst->ne[0];
  1930. const uint64_t ne21 = dst->ne[1];
  1931. const uint64_t r2 = ne12 / ne02;
  1932. const uint64_t r3 = ne13 / ne03;
  1933. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  1934. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  1935. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  1936. vk_buffer d_Qx;
  1937. size_t qx_buf_offset = 0;
  1938. vk_buffer d_Qy;
  1939. size_t qy_buf_offset = 0;
  1940. bool src0_uma = false;
  1941. bool src1_uma = false;
  1942. if (ctx->device.lock()->uma) {
  1943. ggml_vk_host_get(ctx, src0->data, d_Qx, qx_buf_offset);
  1944. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  1945. src0_uma = d_Qx != nullptr;
  1946. src1_uma = d_Qy != nullptr;
  1947. }
  1948. const bool load_x = src0->backend != GGML_BACKEND_GPU && !src0_uma;
  1949. const bool load_y = src1->backend != GGML_BACKEND_GPU && !src1_uma;
  1950. const bool x_non_contig = !load_x && !ggml_vk_dim01_contiguous(src0);
  1951. const bool y_non_contig = !load_y && !ggml_vk_dim01_contiguous(src1);
  1952. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  1953. const bool qx_needs_dequant = src0->type != GGML_TYPE_F16 || x_non_contig;
  1954. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  1955. // Not implemented
  1956. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  1957. const int x_ne = ne01 * ne00;
  1958. const int y_ne = ne11 * ne10;
  1959. const int d_ne = ne11 * ne01;
  1960. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, ne01, ne11));
  1961. const bool aligned = ne10 == kpad;
  1962. const uint32_t split_k = ggml_vk_guess_split_k(ne01, ne11, ne10);
  1963. vk_pipeline * pipeline = ggml_vk_guess_matmul_pipeline(ctx, true, !f16_f32_kernel, ne01, ne11, aligned);
  1964. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  1965. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  1966. const uint64_t x_sz = sizeof(ggml_fp16_t) * x_ne;
  1967. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  1968. const uint64_t d_sz = sizeof(float) * d_ne;
  1969. vk_buffer d_D = extra->buffer_gpu.lock();
  1970. const uint64_t d_buf_offset = extra->offset;
  1971. GGML_ASSERT(d_D != nullptr);
  1972. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  1973. vk_buffer d_X;
  1974. uint64_t x_buf_offset = 0;
  1975. vk_buffer d_Y;
  1976. uint64_t y_buf_offset = 0;
  1977. if (load_x) {
  1978. d_Qx = ctx->prealloc_qx;
  1979. } else if (!src0_uma) {
  1980. d_Qx = extra_src0->buffer_gpu.lock();
  1981. qx_buf_offset = extra_src0->offset;
  1982. GGML_ASSERT(d_Qx != nullptr);
  1983. }
  1984. if (load_y) {
  1985. d_Qy = ctx->prealloc_qy;
  1986. } else if (!src1_uma) {
  1987. d_Qy = extra_src1->buffer_gpu.lock();
  1988. qy_buf_offset = extra_src1->offset;
  1989. GGML_ASSERT(d_Qy != nullptr);
  1990. }
  1991. if (qx_needs_dequant) {
  1992. d_X = ctx->prealloc_x;
  1993. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  1994. } else {
  1995. d_X = d_Qx;
  1996. x_buf_offset = qx_buf_offset;
  1997. GGML_ASSERT(qx_sz == x_sz); // NOLINT
  1998. }
  1999. if (qy_needs_dequant) {
  2000. d_Y = ctx->prealloc_y;
  2001. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  2002. } else {
  2003. d_Y = d_Qy;
  2004. y_buf_offset = qy_buf_offset;
  2005. GGML_ASSERT(qy_sz == y_sz);
  2006. }
  2007. vk_pipeline * to_fp16_vk_0 = nullptr;
  2008. vk_pipeline * to_fp16_vk_1 = nullptr;
  2009. if (x_non_contig) {
  2010. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0->type, GGML_TYPE_F16);
  2011. } else {
  2012. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  2013. }
  2014. if (y_non_contig) {
  2015. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1->type, GGML_TYPE_F16);
  2016. } else {
  2017. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  2018. }
  2019. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  2020. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  2021. // Allocate descriptor sets
  2022. ggml_pipeline_allocate_descriptor_sets(ctx, *pipeline, ne12 * ne13);
  2023. if (qx_needs_dequant) {
  2024. ggml_pipeline_allocate_descriptor_sets(ctx, *to_fp16_vk_0, x_non_contig ? 1 : ne12 * ne13);
  2025. }
  2026. if (qy_needs_dequant) {
  2027. ggml_pipeline_allocate_descriptor_sets(ctx, *to_fp16_vk_1, y_non_contig ? 1 : ne12 * ne13);
  2028. }
  2029. if (split_k > 1) {
  2030. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->pipeline_matmul_split_k_reduce, ne12 * ne13);
  2031. }
  2032. if (x_non_contig) {
  2033. 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 }, dst->type, false);
  2034. } else if (load_x || qx_needs_dequant) {
  2035. if (load_x) {
  2036. // copy data to device
  2037. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qx, 0, src0, 0, 0, ggml_nrows(src0));
  2038. ctx->staging_offset = qx_sz * ne02 * ne03;
  2039. }
  2040. if (qx_needs_dequant) {
  2041. const std::vector<int> pc = { (int)ne01, (int)ne10, (int)ne10, (int)ne10 };
  2042. ggml_vk_sync_buffers(subctx);
  2043. ggml_vk_dispatch_pipeline(ctx, subctx, *to_fp16_vk_0, { { d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, { d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  2044. }
  2045. }
  2046. if (y_non_contig) {
  2047. 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 }, dst->type);
  2048. } else if (load_y) {
  2049. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, 0, src1, 0, 0, ggml_nrows(src1));
  2050. }
  2051. uint32_t stride_batch_x = ne00*ne01;
  2052. uint32_t stride_batch_y = ne10*ne11;
  2053. if (!ggml_vk_dim01_contiguous(src0) && !load_x && !qx_needs_dequant) {
  2054. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  2055. }
  2056. if (!ggml_vk_dim01_contiguous(src1) && !load_y && !qy_needs_dequant) {
  2057. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  2058. }
  2059. // compute
  2060. ggml_vk_matmul(ctx, subctx, *pipeline, { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 }, { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k }, ne01, ne11, ne10, ne10, ne10, ne01, split_k, ne12*ne13, ne02, ne12, r2, r3, stride_batch_x, stride_batch_y, ne20*ne21); // NOLINT
  2061. if (dst->backend == GGML_BACKEND_CPU) {
  2062. // copy dst to host
  2063. float * d = (float *) ((char *) dst->data);
  2064. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, d, sizeof(float) * d_ne * ne12 * ne13);
  2065. }
  2066. }
  2067. 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) {
  2068. #ifdef GGML_VULKAN_DEBUG
  2069. std::cerr << "ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2070. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2071. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2072. #endif
  2073. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  2074. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  2075. const uint64_t ne00 = src0->ne[0];
  2076. const uint64_t ne01 = src0->ne[1];
  2077. const uint64_t ne02 = src0->ne[2];
  2078. const uint64_t ne03 = src0->ne[3];
  2079. const uint64_t ne10 = src1->ne[0];
  2080. const uint64_t ne11 = src1->ne[1];
  2081. const uint64_t ne12 = src1->ne[2];
  2082. const uint64_t ne13 = src1->ne[3];
  2083. GGML_ASSERT(ne11 == 1);
  2084. const uint64_t nb2 = dst->nb[2];
  2085. const uint64_t nb3 = dst->nb[3];
  2086. const uint64_t r2 = ne12 / ne02;
  2087. const uint64_t r3 = ne13 / ne03;
  2088. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2089. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2090. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2091. vk_buffer d_Qx;
  2092. size_t qx_buf_offset = 0;
  2093. vk_buffer d_Qy;
  2094. size_t qy_buf_offset = 0;
  2095. bool src0_uma = false;
  2096. bool src1_uma = false;
  2097. if (ctx->device.lock()->uma) {
  2098. ggml_vk_host_get(ctx, src0->data, d_Qx, qx_buf_offset);
  2099. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2100. src0_uma = d_Qx != nullptr;
  2101. src1_uma = d_Qy != nullptr;
  2102. }
  2103. const bool load_x = src0->backend != GGML_BACKEND_GPU && !src0_uma;
  2104. const bool load_y = src1->backend != GGML_BACKEND_GPU && !src1_uma;
  2105. const bool x_non_contig = !load_x && !ggml_vk_dim01_contiguous(src0);
  2106. const bool y_non_contig = !load_y && !ggml_vk_dim01_contiguous(src1);
  2107. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  2108. const bool qx_needs_dequant = x_non_contig;
  2109. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  2110. const uint64_t x_ne = ne01 * ne00;
  2111. const uint64_t y_ne = ne11 * ne10;
  2112. const uint64_t d_ne = ne11 * ne01;
  2113. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment);
  2114. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  2115. const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) : qx_sz;
  2116. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  2117. const uint64_t d_sz = sizeof(float) * d_ne;
  2118. vk_buffer d_D = extra->buffer_gpu.lock();
  2119. const uint64_t d_buf_offset = extra->offset;
  2120. GGML_ASSERT(d_D != nullptr);
  2121. vk_buffer d_X;
  2122. uint64_t x_buf_offset = 0;
  2123. vk_buffer d_Y;
  2124. uint64_t y_buf_offset = 0;
  2125. if (load_x) {
  2126. d_Qx = ctx->prealloc_qx;
  2127. } else if(!src1_uma) {
  2128. d_Qx = extra_src0->buffer_gpu.lock();
  2129. qx_buf_offset = extra_src0->offset;
  2130. GGML_ASSERT(d_Qx != nullptr);
  2131. }
  2132. if (load_y) {
  2133. d_Qy = ctx->prealloc_qy;
  2134. } else if(!src1_uma) {
  2135. d_Qy = extra_src1->buffer_gpu.lock();
  2136. qy_buf_offset = extra_src1->offset;
  2137. GGML_ASSERT(d_Qy != nullptr);
  2138. }
  2139. if (qx_needs_dequant) {
  2140. d_X = ctx->prealloc_x;
  2141. } else {
  2142. d_X = d_Qx;
  2143. x_buf_offset = qx_buf_offset;
  2144. GGML_ASSERT(qx_sz == x_sz);
  2145. }
  2146. if (qy_needs_dequant) {
  2147. d_Y = ctx->prealloc_y;
  2148. } else {
  2149. d_Y = d_Qy;
  2150. y_buf_offset = qy_buf_offset;
  2151. GGML_ASSERT(qy_sz == y_sz);
  2152. }
  2153. vk_pipeline * to_fp16_vk_0 = nullptr;
  2154. vk_pipeline* to_fp16_vk_1 = nullptr;
  2155. if (x_non_contig) {
  2156. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0->type, src0->type);
  2157. }
  2158. if (y_non_contig) {
  2159. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1->type, src1->type);
  2160. } else {
  2161. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  2162. }
  2163. vk_pipeline* dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type);
  2164. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  2165. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  2166. GGML_ASSERT(dmmv != nullptr);
  2167. // Allocate descriptor sets
  2168. if (qx_needs_dequant) {
  2169. ggml_pipeline_allocate_descriptor_sets(ctx, *to_fp16_vk_0, 1);
  2170. }
  2171. if (qy_needs_dequant) {
  2172. ggml_pipeline_allocate_descriptor_sets(ctx, *to_fp16_vk_1, y_non_contig ? 1 : ne12 * ne13);
  2173. }
  2174. ggml_pipeline_allocate_descriptor_sets(ctx, *dmmv, ne12 * ne13);
  2175. if (x_non_contig) {
  2176. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment));
  2177. 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 }, src0->type);
  2178. } else if (load_x) {
  2179. // copy data to device
  2180. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qx, 0, src0, 0, 0, ggml_nrows(src0));
  2181. }
  2182. if (y_non_contig) {
  2183. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  2184. 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 }, src1->type);
  2185. } else if (load_y) {
  2186. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, 0, src1, 0, 0, ggml_nrows(src1));
  2187. }
  2188. for (uint64_t i13 = 0; i13 < ne13; i13++) {
  2189. const uint64_t i03 = i13 / r3;
  2190. for (uint64_t i12 = 0; i12 < ne12; i12++) {
  2191. const uint64_t i02 = i12 / r2;
  2192. const uint64_t it_idx0 = (i03 * ne02 + i02);
  2193. const uint64_t it_idx1 = (i13 * ne12 + i12);
  2194. const uint64_t x_offset = x_buf_offset + x_sz * it_idx0;
  2195. const uint64_t qy_offset = qy_buf_offset + qy_sz * it_idx1;
  2196. const uint64_t y_offset = y_buf_offset + y_sz * it_idx1;
  2197. const uint64_t d_offset = d_buf_offset + d_sz * it_idx1;
  2198. const uint64_t y_buffer_offset = (y_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2199. const uint64_t y_shader_offset = y_offset - y_buffer_offset;
  2200. const uint64_t d_buffer_offset = (d_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2201. const uint64_t d_shader_offset = d_offset - d_buffer_offset;
  2202. if (!y_non_contig && qy_needs_dequant) {
  2203. const std::vector<int> pc = { (int)ne11, (int)ne10, (int)ne10, (int)ne10 };
  2204. ggml_vk_sync_buffers(subctx);
  2205. ggml_vk_dispatch_pipeline(ctx, subctx, *to_fp16_vk_1, { { d_Qy, qy_offset, qy_sz }, { d_Y, y_offset, y_sz } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)y_ne, 1, 1});
  2206. }
  2207. // compute
  2208. const std::array<int, 3> pc = { (int)ne00, (int)(y_shader_offset / ggml_type_size(src1->type)), (int)(d_shader_offset / ggml_type_size(dst->type))};
  2209. ggml_vk_sync_buffers(subctx);
  2210. ggml_vk_dispatch_pipeline(ctx, subctx, *dmmv, { { d_X, x_offset, x_sz }, { d_Y, y_buffer_offset, y_sz + y_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 3 * sizeof(int), &pc, { (uint32_t)ne01, 1, 1});
  2211. if (dst->backend == GGML_BACKEND_CPU) {
  2212. // copy dst to host
  2213. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  2214. ggml_vk_sync_buffers(subctx);
  2215. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_offset, d, sizeof(float) * d_ne);
  2216. }
  2217. }
  2218. }
  2219. }
  2220. 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) {
  2221. #ifdef GGML_VULKAN_DEBUG
  2222. std::cerr << "ggml_vk_mul_mat_p021_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2223. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2224. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2225. #endif
  2226. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  2227. GGML_ASSERT(src0->backend == GGML_BACKEND_GPU);
  2228. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  2229. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  2230. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2231. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2232. const uint64_t ne00 = src0->ne[0];
  2233. const uint64_t ne01 = src0->ne[1];
  2234. const uint64_t ne02 = src0->ne[2];
  2235. // const uint64_t ne03 = src0->ne[3];
  2236. const uint64_t ne10 = src1->ne[0];
  2237. const uint64_t ne11 = src1->ne[1];
  2238. const uint64_t ne12 = src1->ne[2];
  2239. // const uint64_t ne13 = src1->ne[3];
  2240. GGML_ASSERT(ne11 == 1);
  2241. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2242. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2243. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2244. vk_buffer d_Qy;
  2245. size_t qy_buf_offset = 0;
  2246. bool src1_uma = false;
  2247. if (ctx->device.lock()->uma) {
  2248. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2249. src1_uma = d_Qy != nullptr;
  2250. }
  2251. const bool load_y = src1->backend != GGML_BACKEND_GPU && !src1_uma;
  2252. const uint64_t x_ne = ne00 * ne01 * ne02;
  2253. const uint64_t y_ne = ne10 * ne11 * ne12;
  2254. const uint64_t d_ne = ne01 * ne11 * ne12;
  2255. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment);
  2256. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  2257. const uint64_t d_sz = sizeof(float) * d_ne;
  2258. vk_buffer d_D = extra->buffer_gpu.lock();
  2259. const uint64_t d_buf_offset = extra->offset;
  2260. GGML_ASSERT(d_D != nullptr);
  2261. vk_buffer d_Qx = extra_src0->buffer_gpu.lock();
  2262. const uint64_t qx_buf_offset = extra_src0->offset;
  2263. GGML_ASSERT(d_Qx != nullptr);
  2264. if (load_y) {
  2265. d_Qy = ctx->prealloc_qy;
  2266. } else if (!src1_uma) {
  2267. d_Qy = extra_src1->buffer_gpu.lock();
  2268. qy_buf_offset = extra_src1->offset;
  2269. GGML_ASSERT(d_Qx != nullptr);
  2270. }
  2271. // Allocate descriptor sets
  2272. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->pipeline_mul_mat_vec_p021_f16_f32, 1);
  2273. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2274. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  2275. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2276. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  2277. if (load_y) {
  2278. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, qy_buf_offset, src1, 0, 0, ggml_nrows(src1));
  2279. }
  2280. // compute
  2281. 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)) };
  2282. ggml_vk_sync_buffers(subctx);
  2283. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->pipeline_mul_mat_vec_p021_f16_f32, { { d_Qx, qx_buf_offset, qx_sz }, { d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  2284. if (dst->backend == GGML_BACKEND_CPU) {
  2285. // copy dst to host
  2286. float * d = (float *) dst->data;
  2287. ggml_vk_sync_buffers(subctx);
  2288. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset, d, sizeof(float) * d_ne);
  2289. }
  2290. }
  2291. 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) {
  2292. #ifdef GGML_VULKAN_DEBUG
  2293. std::cerr << "ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2294. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2295. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2296. #endif
  2297. GGML_ASSERT(!ggml_is_transposed(src0));
  2298. GGML_ASSERT(!ggml_is_transposed(src1));
  2299. GGML_ASSERT(!ggml_is_permuted(src0));
  2300. GGML_ASSERT(src0->backend == GGML_BACKEND_GPU);
  2301. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2302. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2303. const uint64_t ne00 = src0->ne[0];
  2304. const uint64_t ne01 = src0->ne[1];
  2305. const uint64_t ne02 = src0->ne[2];
  2306. // const uint64_t ne03 = src0->ne[3];
  2307. const uint64_t nb01 = src0->nb[1];
  2308. const uint64_t nb02 = src0->nb[2];
  2309. // const uint64_t ne10 = src1->ne[0];
  2310. const uint64_t ne11 = src1->ne[1];
  2311. const uint64_t ne12 = src1->ne[2];
  2312. // const uint64_t ne13 = src1->ne[3];
  2313. GGML_ASSERT(ne11 == 1);
  2314. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2315. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2316. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2317. vk_buffer d_Qy = nullptr;
  2318. size_t qy_buf_offset = 0;
  2319. bool src1_uma = false;
  2320. if (ctx->device.lock()->uma) {
  2321. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2322. src1_uma = d_Qy != nullptr;
  2323. }
  2324. const bool load_y = src1->backend != GGML_BACKEND_GPU && !src1_uma;
  2325. const uint64_t d_ne = ne01 * ne11 * ne12;
  2326. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  2327. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  2328. const uint64_t qx_sz = ggml_nbytes(src0);
  2329. const uint64_t qy_sz = ggml_nbytes(src1);
  2330. const uint64_t d_sz = sizeof(float) * d_ne;
  2331. vk_buffer d_D = extra->buffer_gpu.lock();
  2332. const uint64_t d_buf_offset = extra->offset;
  2333. GGML_ASSERT(d_D != nullptr);
  2334. vk_buffer d_Qx = extra_src0->buffer_gpu.lock();
  2335. const uint64_t qx_buf_offset = extra_src0->offset;
  2336. GGML_ASSERT(d_Qx != nullptr);
  2337. if (load_y) {
  2338. d_Qy = ctx->prealloc_qy;
  2339. } else {
  2340. d_Qy = extra_src1->buffer_gpu.lock();
  2341. qy_buf_offset = extra_src1->offset;
  2342. GGML_ASSERT(d_Qx != nullptr);
  2343. }
  2344. // Allocate descriptor sets
  2345. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->pipeline_mul_mat_vec_nc_f16_f32, 1);
  2346. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2347. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  2348. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2349. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  2350. if (load_y) {
  2351. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, qy_buf_offset, src1, 0, 0, ggml_nrows(src1));
  2352. }
  2353. // compute
  2354. 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)) };
  2355. ggml_vk_sync_buffers(subctx);
  2356. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->pipeline_mul_mat_vec_nc_f16_f32, { { d_Qx, qx_buf_offset, qx_sz }, { d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  2357. if (dst->backend == GGML_BACKEND_CPU) {
  2358. // copy dst to host
  2359. float * d = (float *) dst->data;
  2360. ggml_vk_sync_buffers(subctx);
  2361. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset, d, sizeof(float) * d_ne);
  2362. }
  2363. }
  2364. static bool ggml_vk_can_mul_mat(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst) {
  2365. const uint64_t ne10 = src1->ne[0];
  2366. const uint64_t ne0 = dst->ne[0];
  2367. const uint64_t ne1 = dst->ne[1];
  2368. // TODO: find the optimal values for these
  2369. return (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) &&
  2370. (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || ggml_is_quantized(src1->type)) &&
  2371. dst->type == GGML_TYPE_F32 &&
  2372. ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32) || src0->backend == GGML_BACKEND_GPU);
  2373. }
  2374. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context * subctx, const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  2375. #ifdef GGML_VULKAN_DEBUG
  2376. std::cerr << "ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")" << std::endl;
  2377. #endif
  2378. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && src1->ne[1] == 1) {
  2379. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst);
  2380. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && src1->ne[1] == 1) {
  2381. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst);
  2382. } else if (src1->ne[1] == 1 && (src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  2383. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst);
  2384. } else {
  2385. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst);
  2386. }
  2387. }
  2388. static void ggml_vk_op_repeat(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2389. // guaranteed to be an integer due to the check in ggml_can_repeat
  2390. const uint64_t ne0 = dst->ne[0];
  2391. const uint64_t ne1 = dst->ne[1];
  2392. const uint64_t ne2 = dst->ne[2];
  2393. const uint64_t ne3 = dst->ne[3];
  2394. const uint64_t ne00 = src0->ne[0];
  2395. const uint64_t ne01 = src0->ne[1];
  2396. const uint64_t ne02 = src0->ne[2];
  2397. const uint64_t ne03 = src0->ne[3];
  2398. const uint64_t nb0 = dst->nb[0];
  2399. const uint64_t nb1 = dst->nb[1];
  2400. const uint64_t nb2 = dst->nb[2];
  2401. const uint64_t nb3 = dst->nb[3];
  2402. const uint64_t nb00 = src0->nb[0];
  2403. const uint64_t nb01 = src0->nb[1];
  2404. const uint64_t nb02 = src0->nb[2];
  2405. const uint64_t nb03 = src0->nb[3];
  2406. const uint64_t nr0 = ne0/ne00;
  2407. const uint64_t nr1 = ne1/ne01;
  2408. const uint64_t nr2 = ne2/ne02;
  2409. const uint64_t nr3 = ne3/ne03;
  2410. // TODO: support for transposed / permuted tensors
  2411. GGML_ASSERT(nb0 == sizeof(float));
  2412. GGML_ASSERT(nb00 == sizeof(float));
  2413. GGML_ASSERT(src0->backend == GGML_BACKEND_GPU);
  2414. GGML_ASSERT(dst->backend == GGML_BACKEND_GPU);
  2415. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2416. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2417. const vk_buffer src_buf = extra_src0->buffer_gpu.lock();
  2418. const uint64_t src_offset = extra_src0->offset;
  2419. vk_buffer dst_buf = extra->buffer_gpu.lock();
  2420. const uint64_t dst_offset = extra->offset;
  2421. std::vector<vk::BufferCopy> copies;
  2422. for (uint64_t i3 = 0; i3 < nr3; i3++) {
  2423. for (uint64_t k3 = 0; k3 < ne03; k3++) {
  2424. for (uint64_t i2 = 0; i2 < nr2; i2++) {
  2425. for (uint64_t k2 = 0; k2 < ne02; k2++) {
  2426. for (uint64_t i1 = 0; i1 < nr1; i1++) {
  2427. for (uint64_t k1 = 0; k1 < ne01; k1++) {
  2428. for (uint64_t i0 = 0; i0 < nr0; i0++) {
  2429. copies.push_back({
  2430. src_offset + (i3*ne03 + k3)*nb3 + (i2*ne02 + k2)*nb2 + (i1*ne01 + k1)*nb1 + (i0*ne00)*nb0,
  2431. dst_offset + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01,
  2432. ne00*nb0,
  2433. });
  2434. }
  2435. }
  2436. }
  2437. }
  2438. }
  2439. }
  2440. }
  2441. ggml_vk_sync_buffers(subctx);
  2442. subctx->s->buffer.copyBuffer(src_buf->buffer, dst_buf->buffer, copies);
  2443. GGML_UNUSED(ctx);
  2444. GGML_UNUSED(src1);
  2445. }
  2446. static vk_pipeline* ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, ggml_op op) {
  2447. switch (op) {
  2448. case GGML_OP_ADD:
  2449. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2450. return &ctx->pipeline_add_f32;
  2451. }
  2452. return nullptr;
  2453. case GGML_OP_GET_ROWS:
  2454. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  2455. if (dst->type == GGML_TYPE_F16) {
  2456. return &ctx->pipeline_get_rows[src0->type];
  2457. }
  2458. if (dst->type == GGML_TYPE_F32) {
  2459. return &ctx->pipeline_get_rows_f32[src0->type];
  2460. }
  2461. return nullptr;
  2462. case GGML_OP_MUL:
  2463. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2464. return &ctx->pipeline_mul_f32;
  2465. }
  2466. return nullptr;
  2467. case GGML_OP_SCALE:
  2468. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2469. return &ctx->pipeline_scale_f32;
  2470. }
  2471. return nullptr;
  2472. case GGML_OP_SQR:
  2473. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2474. return &ctx->pipeline_sqr_f32;
  2475. }
  2476. return nullptr;
  2477. case GGML_OP_CLAMP:
  2478. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2479. return &ctx->pipeline_clamp_f32;
  2480. }
  2481. return nullptr;
  2482. case GGML_OP_CPY:
  2483. case GGML_OP_CONT:
  2484. case GGML_OP_DUP:
  2485. return ggml_vk_get_cpy_pipeline(ctx, src0->type, dst->type);
  2486. case GGML_OP_NORM:
  2487. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2488. return &ctx->pipeline_norm_f32;
  2489. }
  2490. return nullptr;
  2491. case GGML_OP_RMS_NORM:
  2492. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2493. return &ctx->pipeline_rms_norm_f32;
  2494. }
  2495. return nullptr;
  2496. case GGML_OP_UNARY:
  2497. switch (ggml_get_unary_op(dst)) {
  2498. case GGML_UNARY_OP_SILU:
  2499. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2500. return &ctx->pipeline_silu_f32;
  2501. }
  2502. break;
  2503. case GGML_UNARY_OP_GELU:
  2504. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2505. return &ctx->pipeline_gelu_f32;
  2506. }
  2507. break;
  2508. case GGML_UNARY_OP_RELU:
  2509. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2510. return &ctx->pipeline_relu_f32;
  2511. }
  2512. break;
  2513. default:
  2514. break;
  2515. }
  2516. return nullptr;
  2517. case GGML_OP_DIAG_MASK_INF:
  2518. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2519. return &ctx->pipeline_diag_mask_inf_f32;
  2520. }
  2521. return nullptr;
  2522. case GGML_OP_SOFT_MAX:
  2523. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2524. return &ctx->pipeline_soft_max_f32;
  2525. }
  2526. return nullptr;
  2527. case GGML_OP_ROPE:
  2528. {
  2529. const int mode = ((const int32_t *) dst->op_params)[2];
  2530. const bool is_neox = mode & 2;
  2531. const bool is_glm = mode & 4;
  2532. if (is_glm) {
  2533. return nullptr;
  2534. }
  2535. if (is_neox) {
  2536. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2537. return &ctx->pipeline_rope_neox_f32;
  2538. }
  2539. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  2540. return &ctx->pipeline_rope_neox_f16;
  2541. }
  2542. } else {
  2543. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2544. return &ctx->pipeline_rope_f32;
  2545. }
  2546. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  2547. return &ctx->pipeline_rope_f16;
  2548. }
  2549. }
  2550. return nullptr;
  2551. }
  2552. default:
  2553. return nullptr;
  2554. }
  2555. }
  2556. static ggml_vk_func_t ggml_vk_op_get_func(ggml_op op) {
  2557. switch(op) {
  2558. case GGML_OP_REPEAT:
  2559. return ggml_vk_op_repeat;
  2560. default:
  2561. return nullptr;
  2562. }
  2563. }
  2564. template<typename PC>
  2565. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, ggml_op op, const PC&& pc) {
  2566. #ifdef GGML_VULKAN_DEBUG
  2567. std::cerr << "ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2568. if (src1 != nullptr) {
  2569. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2570. }
  2571. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "), " << ggml_op_name(op) << ")" << std::endl;
  2572. #endif
  2573. GGML_ASSERT(!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type))); // NOLINT
  2574. GGML_ASSERT(op == GGML_OP_CPY || ggml_vk_dim01_contiguous(src0)); // NOLINT
  2575. GGML_ASSERT(src1 == nullptr || ggml_vk_dim01_contiguous(src1)); // NOLINT
  2576. GGML_ASSERT(dst->extra != nullptr);
  2577. const uint64_t ne00 = src0->ne[0];
  2578. const uint64_t ne01 = src0->ne[1];
  2579. const uint64_t ne02 = src0->ne[2];
  2580. const uint64_t ne03 = src0->ne[3];
  2581. const uint64_t ne0 = ne00 * ne01;
  2582. const bool use_src1 = src1 != nullptr;
  2583. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  2584. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  2585. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  2586. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  2587. const uint64_t ne1 = ne10 * ne11;
  2588. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  2589. const uint64_t nb2 = dst->nb[2];
  2590. const uint64_t nb3 = dst->nb[3];
  2591. vk_pipeline * pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, dst, op);
  2592. ggml_vk_func_t op_func;
  2593. if (pipeline == nullptr) {
  2594. op_func = ggml_vk_op_get_func(op);
  2595. if (op_func == nullptr) {
  2596. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  2597. if (src1 != nullptr) {
  2598. std::cerr << " and " << ggml_type_name(src1->type);
  2599. }
  2600. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  2601. GGML_ASSERT(false);
  2602. }
  2603. op_func(ctx, subctx, src0, src1, dst);
  2604. return;
  2605. }
  2606. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2607. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2608. ggml_tensor_extra_gpu * extra_src1 = use_src1 ? (ggml_tensor_extra_gpu *) src1->extra : nullptr;
  2609. vk_buffer d_X = nullptr;
  2610. size_t x_buf_offset = 0;
  2611. vk_buffer d_Y = nullptr;
  2612. size_t y_buf_offset = 0;
  2613. bool src0_uma = false;
  2614. bool src1_uma = false;
  2615. if (ctx->device.lock()->uma) {
  2616. ggml_vk_host_get(ctx, src0->data, d_X, x_buf_offset);
  2617. src0_uma = d_X != nullptr;
  2618. if (use_src1) {
  2619. ggml_vk_host_get(ctx, src1->data, d_Y, y_buf_offset);
  2620. src1_uma = d_Y != nullptr;
  2621. }
  2622. }
  2623. const bool transfer_src0 = src0->backend != GGML_BACKEND_GPU && !src0_uma;
  2624. const bool transfer_src1 = use_src1 && src1->backend != GGML_BACKEND_GPU && !src1_uma;
  2625. uint64_t x_sz = ggml_vk_align_size(ggml_type_size(src0->type) * ne0, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment);
  2626. uint64_t y_sz = use_src1 ? ggml_vk_align_size(ggml_type_size(src1->type) * ne1, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) : 0;
  2627. uint64_t d_sz = ggml_type_size(dst->type) * ne0;
  2628. vk_buffer d_D = extra->buffer_gpu.lock();
  2629. // Workaround for tiny tensor inputs on ROPE
  2630. if (use_src1 && src1->backend == GGML_BACKEND_GPU && y_sz > d_D->size) {
  2631. y_sz = VK_WHOLE_SIZE;
  2632. }
  2633. GGML_ASSERT(d_D != nullptr);
  2634. uint64_t d_buf_offset = (extra->offset / ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  2635. GGML_ASSERT(d_buf_offset == extra->offset || op == GGML_OP_CPY); // NOLINT
  2636. if (transfer_src0) {
  2637. d_X = ctx->prealloc_qx;
  2638. } else if(!src0_uma) {
  2639. d_X = extra_src0->buffer_gpu.lock();
  2640. x_buf_offset = extra_src0->offset;
  2641. GGML_ASSERT(d_X != nullptr);
  2642. }
  2643. if (transfer_src1) {
  2644. d_Y = ctx->prealloc_qy;
  2645. } else if (use_src1 && !src1_uma) {
  2646. d_Y = extra_src1->buffer_gpu.lock();
  2647. y_buf_offset = extra_src1->offset;
  2648. GGML_ASSERT(d_Y != nullptr);
  2649. }
  2650. if (op == GGML_OP_CPY) {
  2651. GGML_ASSERT(!transfer_src0);
  2652. GGML_ASSERT(!transfer_src1);
  2653. x_sz = ggml_nbytes(src0);
  2654. d_sz = ggml_nbytes(dst);
  2655. if (extra_src0->offset + x_sz >= d_X->size) {
  2656. x_sz = VK_WHOLE_SIZE;
  2657. }
  2658. if (extra->offset + d_sz >= d_D->size) {
  2659. d_sz = VK_WHOLE_SIZE;
  2660. }
  2661. }
  2662. std::array<uint32_t, 3> elements;
  2663. // copy src0 to device
  2664. if (transfer_src0) {
  2665. ggml_vk_h2d_tensor_2d(ctx, subctx, d_X, 0, src0, 0, 0, ggml_nrows(src0));
  2666. ctx->staging_offset = x_sz * ne02 * ne03;
  2667. }
  2668. if (transfer_src1) {
  2669. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Y, 0, src1, 0, 0, ggml_nrows(src1));
  2670. }
  2671. // Single call if dimension 2 is contiguous
  2672. if (op == GGML_OP_CPY || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1)))) {
  2673. ggml_pipeline_allocate_descriptor_sets(ctx, *pipeline, 1);
  2674. switch (dst->op) {
  2675. case GGML_OP_NORM:
  2676. case GGML_OP_RMS_NORM:
  2677. case GGML_OP_SOFT_MAX:
  2678. elements = { (uint32_t)ggml_nrows(src0), 1, 1 };
  2679. break;
  2680. case GGML_OP_DIAG_MASK_INF:
  2681. case GGML_OP_ROPE:
  2682. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  2683. break;
  2684. default:
  2685. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  2686. break;
  2687. }
  2688. if (op != GGML_OP_CPY) {
  2689. if (x_sz != VK_WHOLE_SIZE) {
  2690. x_sz *= ne02 * ne03;
  2691. }
  2692. if (y_sz != VK_WHOLE_SIZE) {
  2693. y_sz *= ne12 * ne13;
  2694. }
  2695. if (d_sz != VK_WHOLE_SIZE) {
  2696. d_sz *= ne02 * ne03;
  2697. }
  2698. }
  2699. if (!use_src1 && op == GGML_OP_SOFT_MAX) {
  2700. // Empty src1 is possible on soft_max, but the shader needs a buffer
  2701. ggml_vk_sync_buffers(subctx);
  2702. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset, x_sz }, { ctx->prealloc_y, 0, ctx->prealloc_y->size }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2703. } else if (use_src1) {
  2704. ggml_vk_sync_buffers(subctx);
  2705. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2706. } else {
  2707. ggml_vk_sync_buffers(subctx);
  2708. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset, x_sz }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2709. }
  2710. if (dst->backend == GGML_BACKEND_CPU && op == GGML_OP_CPY) {
  2711. ggml_vk_d2h_tensor_2d(ctx, subctx, d_D, 0, dst);
  2712. } else if(dst->backend == GGML_BACKEND_CPU) {
  2713. // copy dst to host
  2714. float * d = (float *) dst->data;
  2715. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, d, d_sz);
  2716. }
  2717. } else {
  2718. ggml_pipeline_allocate_descriptor_sets(ctx, *pipeline, ne02 * ne03);
  2719. switch (dst->op) {
  2720. case GGML_OP_NORM:
  2721. case GGML_OP_RMS_NORM:
  2722. case GGML_OP_SOFT_MAX:
  2723. elements = { (uint32_t)ne01, 1, 1 };
  2724. break;
  2725. case GGML_OP_DIAG_MASK_INF:
  2726. case GGML_OP_ROPE:
  2727. elements = { (uint32_t)ne01, (uint32_t)ne00, 1 };
  2728. break;
  2729. default:
  2730. elements = { (uint32_t)ne0, 1, 1 };
  2731. break;
  2732. }
  2733. for (uint64_t i03 = 0; i03 < ne03; i03++) {
  2734. for (uint64_t i02 = 0; i02 < ne02; i02++) {
  2735. const uint32_t it_idx0 = (i03 * ne02 + i02);
  2736. const uint32_t it_idx1 = use_src1 ? ((i03 % ne13) * ne12 + (i02 % ne12)) : 0;
  2737. const uint32_t x_offset = x_sz * it_idx0;
  2738. const uint32_t y_offset = y_sz * it_idx1;
  2739. const uint32_t d_offset = d_sz * it_idx0;
  2740. if (!use_src1 && op == GGML_OP_SOFT_MAX) {
  2741. // Empty src1 is possible on soft_max, but the shader needs a buffer
  2742. ggml_vk_sync_buffers(subctx);
  2743. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset, x_sz }, { ctx->prealloc_y, 0, ctx->prealloc_y->size }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2744. } else if (use_src1) {
  2745. ggml_vk_sync_buffers(subctx);
  2746. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset + x_offset, x_sz }, { d_Y, y_buf_offset + y_offset, y_sz }, { d_D, d_buf_offset + d_offset, d_sz } }, sizeof(PC), &pc, elements);
  2747. } else {
  2748. ggml_vk_sync_buffers(subctx);
  2749. ggml_vk_dispatch_pipeline(ctx, subctx, *pipeline, { { d_X, x_buf_offset + x_offset, x_sz }, { d_D, d_buf_offset + d_offset, d_sz } }, sizeof(PC), &pc, elements);
  2750. }
  2751. if (dst->backend == GGML_BACKEND_CPU) {
  2752. // copy dst to host
  2753. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset + d_offset, (char *) dst->data + i02*nb2 + i03*nb3, d_sz);
  2754. }
  2755. }
  2756. }
  2757. }
  2758. }
  2759. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2760. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_REPEAT, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2761. }
  2762. 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) {
  2763. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_GET_ROWS, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2764. }
  2765. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2766. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_ADD, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2767. }
  2768. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2769. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_MUL, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2770. }
  2771. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2772. float * op_params = (float *)dst->op_params;
  2773. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_SCALE, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f });
  2774. }
  2775. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2776. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_SQR, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  2777. }
  2778. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2779. float * op_params = (float *)dst->op_params;
  2780. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_CLAMP, { (uint32_t)ggml_nelements(src0), 0, op_params[0], op_params[1] });
  2781. }
  2782. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2783. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2784. const int src0_type_size = ggml_type_size(src0->type);
  2785. const int dst_type_size = ggml_type_size(dst->type);
  2786. const uint32_t d_offset = (extra->offset % ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  2787. ggml_vk_op_f32<vk_op_cpy_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_CPY, {
  2788. (uint32_t)ggml_nelements(src0),
  2789. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size,
  2790. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size,
  2791. d_offset,
  2792. });
  2793. }
  2794. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2795. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f });
  2796. }
  2797. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2798. float * op_params = (float *)dst->op_params;
  2799. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_RMS_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  2800. }
  2801. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2802. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  2803. }
  2804. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2805. int32_t * op_params = (int32_t *)dst->op_params;
  2806. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  2807. }
  2808. 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) {
  2809. float * op_params = (float *)dst->op_params;
  2810. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_SOFT_MAX, { (uint32_t)src0->ne[0], (uint32_t)(src1 != nullptr ? ggml_nrows(src1) : 0), op_params[0], 0.0f });
  2811. }
  2812. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2813. const int n_dims = ((int32_t *) dst->op_params)[1];
  2814. const int mode = ((int32_t *) dst->op_params)[2];
  2815. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  2816. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  2817. const float freq_base = ((float *) dst->op_params)[5];
  2818. const float freq_scale = ((float *) dst->op_params)[6];
  2819. const float ext_factor = ((float *) dst->op_params)[7];
  2820. const float attn_factor = ((float *) dst->op_params)[8];
  2821. const float beta_fast = ((float *) dst->op_params)[9];
  2822. const float beta_slow = ((float *) dst->op_params)[10];
  2823. const bool is_neox = mode & 2;
  2824. const bool is_glm = mode & 4;
  2825. GGML_ASSERT(!is_glm);
  2826. float corr_dims[2];
  2827. ggml_rope_yarn_corr_dims(n_dims, n_orig_ctx, freq_base, beta_fast, beta_slow, corr_dims);
  2828. if (is_neox) {
  2829. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  2830. const float inv_ndims = -1.0f / n_dims;
  2831. ggml_vk_op_f32<vk_op_rope_neox_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_ROPE, { (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1], freq_base, ext_factor, attn_factor, corr_dims[0], corr_dims[1], 0.0f, 0.0f, theta_scale, inv_ndims });
  2832. } else {
  2833. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, dst, GGML_OP_ROPE, { (uint32_t)src0->ne[0], freq_scale, (uint32_t)src0->ne[1], freq_base, ext_factor, attn_factor, corr_dims[0], corr_dims[1], 0.0f, 0.0f });
  2834. }
  2835. }
  2836. static void ggml_vk_nop(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2837. // If backend is CPU, data from src0 has to be copied off the device
  2838. if (dst->backend == GGML_BACKEND_CPU) {
  2839. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2840. vk_buffer d_D = extra_src0->buffer_gpu.lock();
  2841. ggml_vk_sync_buffers(subctx);
  2842. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, dst->data, d_D->size);
  2843. }
  2844. }
  2845. #ifdef GGML_VULKAN_RUN_TESTS
  2846. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  2847. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  2848. return;
  2849. }
  2850. i0 = std::max(i0, 5);
  2851. i1 = std::max(i1, 5);
  2852. i2 = std::max(i2, 0);
  2853. fprintf(stderr, " ");
  2854. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  2855. fprintf(stderr, "%7d ", idx1);
  2856. }
  2857. fprintf(stderr, "\n");
  2858. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  2859. fprintf(stderr, "%7d: ", idx0);
  2860. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  2861. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  2862. float val;
  2863. if (type == GGML_TYPE_F32) {
  2864. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  2865. } else if (type == GGML_TYPE_F16) {
  2866. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  2867. }
  2868. fprintf(stderr, "% 7.2f ", val);
  2869. } else {
  2870. fprintf(stderr, " ");
  2871. }
  2872. }
  2873. fprintf(stderr, "\n");
  2874. }
  2875. }
  2876. template <typename X_TYPE, typename Y_TYPE>
  2877. 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) {
  2878. #ifdef GGML_VULKAN_DEBUG
  2879. std::cerr << "ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")" << std::endl;
  2880. #endif
  2881. const size_t x_ne = m * k * batch;
  2882. const size_t y_ne = k * n * batch;
  2883. const size_t d_ne = m * n * batch;
  2884. vk_pipeline * p;
  2885. std::string shname;
  2886. if (shader_size == 0) {
  2887. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2888. p = &ctx->pipeline_matmul_f32_aligned_s;
  2889. shname = "F32_ALIGNED_S";
  2890. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2891. p = &ctx->pipeline_matmul_f16_f32_aligned_s;
  2892. shname = "F16_F32_ALIGNED_S";
  2893. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2894. p = &ctx->pipeline_matmul_f16_aligned_s;
  2895. shname = "F16_ALIGNED_S";
  2896. } else {
  2897. GGML_ASSERT(false);
  2898. }
  2899. } else if (shader_size == 1) {
  2900. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2901. p = &ctx->pipeline_matmul_f32_aligned_m;
  2902. shname = "F32_ALIGNED_M";
  2903. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2904. p = &ctx->pipeline_matmul_f16_f32_aligned_m;
  2905. shname = "F16_F32_ALIGNED_M";
  2906. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2907. p = &ctx->pipeline_matmul_f16_aligned_m;
  2908. shname = "F16_ALIGNED_M";
  2909. } else {
  2910. GGML_ASSERT(false);
  2911. }
  2912. } else if (shader_size == 2) {
  2913. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2914. p = &ctx->pipeline_matmul_f32_aligned_l;
  2915. shname = "F32_ALIGNED_L";
  2916. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2917. p = &ctx->pipeline_matmul_f16_f32_aligned_l;
  2918. shname = "F16_F32_ALIGNED_L";
  2919. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2920. p = &ctx->pipeline_matmul_f16_aligned_l;
  2921. shname = "F16_ALIGNED_L";
  2922. } else {
  2923. GGML_ASSERT(false);
  2924. }
  2925. } else {
  2926. GGML_ASSERT(0);
  2927. }
  2928. const size_t kpad = ggml_vk_align_size(k, p->align);
  2929. if (k != kpad) {
  2930. if (shader_size == 0) {
  2931. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2932. p = &ctx->pipeline_matmul_f32_s;
  2933. shname = "F32_S";
  2934. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2935. p = &ctx->pipeline_matmul_f16_f32_s;
  2936. shname = "F16_F32_S";
  2937. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2938. p = &ctx->pipeline_matmul_f16_s;
  2939. shname = "F16_S";
  2940. }
  2941. } else if (shader_size == 1) {
  2942. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2943. p = &ctx->pipeline_matmul_f32_m;
  2944. shname = "F32_M";
  2945. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2946. p = &ctx->pipeline_matmul_f16_f32_m;
  2947. shname = "F16_F32_M";
  2948. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2949. p = &ctx->pipeline_matmul_f16_m;
  2950. shname = "F16_M";
  2951. }
  2952. } else if (shader_size == 2) {
  2953. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2954. p = &ctx->pipeline_matmul_f32_l;
  2955. shname = "F32_L";
  2956. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  2957. p = &ctx->pipeline_matmul_f16_f32_l;
  2958. shname = "F16_F32_L";
  2959. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2960. p = &ctx->pipeline_matmul_f16_l;
  2961. shname = "F16_L";
  2962. }
  2963. }
  2964. }
  2965. ggml_pipeline_allocate_descriptor_sets(ctx, *p, num_it);
  2966. if (split_k > 1) {
  2967. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->pipeline_matmul_split_k_reduce, num_it);
  2968. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  2969. // Resize buffer
  2970. if (ctx->prealloc_split_k != nullptr) {
  2971. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  2972. }
  2973. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  2974. }
  2975. }
  2976. vk_buffer d_X = ggml_vk_create_buffer_check(ctx, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  2977. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  2978. vk_buffer d_D = ggml_vk_create_buffer_check(ctx, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  2979. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  2980. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  2981. float* d = (float *) malloc(sizeof(float) * d_ne);
  2982. for (size_t i = 0; i < x_ne; i++) {
  2983. if (std::is_same<float, X_TYPE>()) {
  2984. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  2985. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  2986. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  2987. } else {
  2988. GGML_ASSERT(false);
  2989. }
  2990. }
  2991. for (size_t i = 0; i < y_ne; i++) {
  2992. if (std::is_same<float, Y_TYPE>()) {
  2993. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  2994. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  2995. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  2996. } else {
  2997. GGML_ASSERT(false);
  2998. }
  2999. }
  3000. ggml_vk_buffer_write(ctx, d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  3001. ggml_vk_buffer_write(ctx, d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  3002. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->compute_queue);
  3003. for (size_t i = 0; i < num_it; i++) {
  3004. ggml_vk_ctx_begin(ctx, subctx);
  3005. ggml_vk_matmul(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), m, n, k, k, k, m, split_k, batch, batch, batch, 1, 1, k*m, k*n, m*n);
  3006. ggml_vk_ctx_end(subctx);
  3007. }
  3008. auto begin = std::chrono::high_resolution_clock::now();
  3009. ggml_vk_submit(subctx, ctx->fence);
  3010. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  3011. ctx->device.lock()->device.resetFences({ ctx->fence });
  3012. auto end = std::chrono::high_resolution_clock::now();
  3013. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3014. // copy dst to host
  3015. ggml_vk_buffer_read(ctx, d_D, 0, d, sizeof(float) * d_ne);
  3016. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  3017. ggml_init_params iparams = {
  3018. /*.mem_size =*/ 1024*1024*1024,
  3019. /*.mem_buffer =*/ NULL,
  3020. /*.no_alloc =*/ true,
  3021. };
  3022. ggml_context * ggml_ctx = ggml_init(iparams);
  3023. ggml_type src0_type;
  3024. ggml_type src1_type;
  3025. if (std::is_same<float, X_TYPE>()) {
  3026. src0_type = GGML_TYPE_F32;
  3027. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  3028. src0_type = GGML_TYPE_F16;
  3029. } else {
  3030. GGML_ASSERT(false);
  3031. }
  3032. if (std::is_same<float, Y_TYPE>()) {
  3033. src1_type = GGML_TYPE_F32;
  3034. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3035. src1_type = GGML_TYPE_F16;
  3036. } else {
  3037. GGML_ASSERT(false);
  3038. }
  3039. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  3040. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  3041. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  3042. src0_ggml->data = x;
  3043. src1_ggml->data = y;
  3044. tensor_ggml->data = d_chk;
  3045. ctx->disable = true;
  3046. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  3047. ggml_build_forward_expand(cgraph, tensor_ggml);
  3048. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  3049. ctx->disable = false;
  3050. ggml_free(ggml_ctx);
  3051. double avg_err = 0.0;
  3052. int first_err_n = -1;
  3053. int first_err_m = -1;
  3054. int first_err_b = -1;
  3055. for (size_t i = 0; i < m*n*batch; i++) {
  3056. double err = std::fabs(d[i] - d_chk[i]);
  3057. avg_err += err;
  3058. if (err > 0.05f && first_err_n == -1) {
  3059. first_err_b = i / (m * n);
  3060. first_err_n = (i % (m * n)) / m;
  3061. first_err_m = (i % (m * n)) % m;
  3062. }
  3063. }
  3064. avg_err /= m * n;
  3065. std::cerr << "TEST " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time / num_it << "ms avg_err=" << avg_err << std::endl;
  3066. if (avg_err > 0.1) {
  3067. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  3068. std::cerr << "Actual result: " << std::endl << std::endl;
  3069. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3070. std::cerr << "Expected result: " << std::endl << std::endl;
  3071. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3072. if (split_k > 1) {
  3073. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  3074. ggml_vk_buffer_read(ctx, ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  3075. std::cerr << "d_buf0: " << std::endl << std::endl;
  3076. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3077. std::cerr << "d_buf1: " << std::endl << std::endl;
  3078. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3079. std::cerr << "d_buf2: " << std::endl << std::endl;
  3080. 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);
  3081. std::cerr << "d_buf3: " << std::endl << std::endl;
  3082. 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);
  3083. free(split_k_buf);
  3084. }
  3085. }
  3086. free(d_chk);
  3087. ggml_vk_queue_cleanup(ctx, ctx->device.lock()->transfer_queue);
  3088. ggml_vk_queue_cleanup(ctx, ctx->device.lock()->compute_queue);
  3089. ggml_vk_destroy_buffer(d_X);
  3090. ggml_vk_destroy_buffer(d_Y);
  3091. ggml_vk_destroy_buffer(d_D);
  3092. ggml_pipeline_cleanup(*p);
  3093. ggml_pipeline_cleanup(ctx->pipeline_matmul_split_k_reduce);
  3094. free(x);
  3095. free(y);
  3096. free(d);
  3097. }
  3098. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3099. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  3100. return;
  3101. }
  3102. i0 = std::max(i0, 5);
  3103. i1 = std::max(i1, 5);
  3104. i2 = std::max(i2, 0);
  3105. i3 = std::max(i3, 0);
  3106. fprintf(stderr, " ");
  3107. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3108. fprintf(stderr, "%7d ", idx1);
  3109. }
  3110. fprintf(stderr, "\n");
  3111. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  3112. fprintf(stderr, "%7d: ", idx0);
  3113. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3114. 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]) {
  3115. float val;
  3116. if (tensor->type == GGML_TYPE_F32) {
  3117. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  3118. } else if (tensor->type == GGML_TYPE_F16) {
  3119. 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]));
  3120. }
  3121. fprintf(stderr, "% 7.2f ", val);
  3122. } else {
  3123. fprintf(stderr, " ");
  3124. }
  3125. }
  3126. fprintf(stderr, "\n");
  3127. }
  3128. }
  3129. static void ggml_vk_test_h2d_nc(ggml_backend_vk_context * ctx, size_t ne0, size_t ne1, size_t ne2, size_t ne3) {
  3130. const size_t ne = ne0 * ne1 * ne2 * ne3;
  3131. ggml_init_params iparams = {
  3132. /*.mem_size =*/ 1024*1024*1024,
  3133. /*.mem_buffer =*/ NULL,
  3134. /*.no_alloc =*/ true,
  3135. };
  3136. ggml_context * ggml_ctx = ggml_init(iparams);
  3137. ggml_tensor * tensor = ggml_new_tensor_4d(ggml_ctx, GGML_TYPE_F32, ne0, ne2, ne1, ne3); // NOLINT
  3138. ggml_tensor * result_tensor = ggml_new_tensor_4d(ggml_ctx, GGML_TYPE_F32, ne0, ne1, ne2, ne3);
  3139. float * data = (float *) ggml_vk_host_malloc(ctx, ggml_nbytes(tensor));
  3140. tensor->data = data;
  3141. float * result_data = (float *) malloc(ggml_nbytes(tensor));
  3142. result_tensor->data = result_data;
  3143. // Permute
  3144. {
  3145. size_t tmp = tensor->nb[2];
  3146. tensor->nb[2] = tensor->nb[1];
  3147. tensor->nb[1] = tmp;
  3148. tensor->ne[2] = ne2;
  3149. tensor->ne[1] = ne1;
  3150. }
  3151. for (size_t i = 0; i < ne; i++) {
  3152. data[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  3153. }
  3154. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->compute_queue);
  3155. ggml_vk_ctx_begin(ctx, subctx);
  3156. vk_buffer buffer = ggml_vk_create_buffer_check(ctx, ggml_nbytes(tensor), vk::MemoryPropertyFlagBits::eDeviceLocal);
  3157. ggml_vk_h2d_tensor_2d(ctx, subctx, buffer, 0, tensor, 0, 0, ggml_nrows(tensor));
  3158. ggml_vk_ctx_end(subctx);
  3159. ggml_vk_submit(subctx, ctx->fence);
  3160. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_h2d_nc waitForFences");
  3161. ctx->device.lock()->device.resetFences({ ctx->fence });
  3162. ggml_vk_buffer_read(ctx, buffer, 0, result_data, ggml_nbytes(tensor));
  3163. double avg_err = 0.0;
  3164. int first_err_i0 = -1;
  3165. int first_err_i1 = -1;
  3166. int first_err_i2 = -1;
  3167. int first_err_i3 = -1;
  3168. for (size_t i3 = 0; i3 < ne3; i3++) {
  3169. for (size_t i2 = 0; i2 < ne2; i2++) {
  3170. for (size_t i1 = 0; i1 < ne1; i1++) {
  3171. for (size_t i0 = 0; i0 < ne0; i0++) {
  3172. float correct = *(float *) ((char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  3173. float result = *(float *) ((char *) result_data + i3*ne2*ne1*ne0*sizeof(float) + i2*ne1*ne0*sizeof(float) + i1*ne0*sizeof(float) + i0*sizeof(float));
  3174. double err = std::fabs(result - correct);
  3175. avg_err += err;
  3176. if (err > 0.05f && first_err_i0 == -1) {
  3177. first_err_i0 = i0;
  3178. first_err_i1 = i1;
  3179. first_err_i2 = i2;
  3180. first_err_i3 = i3;
  3181. }
  3182. }
  3183. }
  3184. }
  3185. }
  3186. avg_err /= ne;
  3187. std::cerr << "TEST nc copy ne0=" << ne0 << " ne1=" << ne1 << " ne2=" << ne2 << " ne3=" << ne3 << " avg_err=" << avg_err << std::endl;
  3188. if (avg_err > 0.1) {
  3189. std::cerr << "i0 = " << first_err_i0 << " i1 = " << first_err_i1 << " i2 = " << first_err_i2 << " i3 = " << first_err_i3 << std::endl;
  3190. std::cerr << "Actual result: " << std::endl << std::endl;
  3191. ggml_vk_print_tensor_area(result_tensor, first_err_i0, first_err_i1, first_err_i2, first_err_i3);
  3192. std::cerr << "Expected result: " << std::endl << std::endl;
  3193. ggml_vk_print_tensor_area(tensor, first_err_i0, first_err_i1, first_err_i2, first_err_i3);
  3194. }
  3195. ggml_free(ggml_ctx);
  3196. ggml_vk_destroy_buffer(buffer);
  3197. ggml_vk_host_free(ctx, data);
  3198. free(result_data);
  3199. }
  3200. static void ggml_vk_test_transfer(ggml_backend_vk_context * ctx, size_t ne, bool pinned) {
  3201. #ifdef GGML_VULKAN_DEBUG
  3202. std::cerr << "ggml_vk_test_transfer(" << ne << ")" << std::endl;
  3203. #endif
  3204. // Check transfers are correct
  3205. vk_buffer buffer = ggml_vk_create_buffer_check(ctx, sizeof(float) * ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3206. float * x;
  3207. float * y;
  3208. if (pinned) {
  3209. x = (float *) ggml_vk_host_malloc(ctx, sizeof(float) * ne);
  3210. y = (float *) ggml_vk_host_malloc(ctx, sizeof(float) * ne);
  3211. } else {
  3212. x = (float *) malloc(sizeof(float) * ne);
  3213. y = (float *) malloc(sizeof(float) * ne);
  3214. }
  3215. for (size_t i = 0; i < ne; i++) {
  3216. x[i] = rand() / (float)RAND_MAX;
  3217. }
  3218. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->compute_queue);
  3219. ggml_vk_ctx_begin(ctx, subctx);
  3220. auto begin = std::chrono::high_resolution_clock::now();
  3221. ggml_vk_buffer_write_async(ctx, subctx, buffer, 0, x, sizeof(float) * ne);
  3222. for (auto& cpy : subctx->in_memcpys) {
  3223. memcpy(cpy.dst, cpy.src, cpy.n);
  3224. }
  3225. subctx->in_memcpys.clear();
  3226. ggml_vk_ctx_end(subctx);
  3227. ggml_vk_submit(subctx, ctx->fence);
  3228. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_transfer waitForFences");
  3229. ctx->device.lock()->device.resetFences({ ctx->fence });
  3230. auto end = std::chrono::high_resolution_clock::now();
  3231. double ms_to_gpu = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3232. ggml_vk_ctx_begin(ctx, subctx);
  3233. begin = std::chrono::high_resolution_clock::now();
  3234. ggml_vk_buffer_read_async(ctx, subctx, buffer, 0, y, sizeof(float) * ne);
  3235. ggml_vk_ctx_end(subctx);
  3236. ggml_vk_submit(subctx, ctx->fence);
  3237. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_transfer waitForFences");
  3238. ctx->device.lock()->device.resetFences({ ctx->fence });
  3239. for (auto& cpy : subctx->out_memcpys) {
  3240. memcpy(cpy.dst, cpy.src, cpy.n);
  3241. }
  3242. subctx->out_memcpys.clear();
  3243. end = std::chrono::high_resolution_clock::now();
  3244. double ms_from_gpu = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3245. double avg_err = 0.0;
  3246. for (size_t i = 0; i < ne; i++) {
  3247. avg_err += std::fabs(x[i] - y[i]);
  3248. }
  3249. double kb = ne * sizeof(float) / 1024.0;
  3250. std::cerr << "TEST TRANSFER " << kb << " KB to_gpu " << ms_to_gpu << "ms (" << kb / ms_to_gpu * 1000.0 / 1024.0 << " MB/s) from_gpu " << ms_from_gpu << "ms (" << kb / ms_from_gpu * 1000.0 / 1024.0 << " MB/s) avg_err=" << avg_err / ne << std::endl;
  3251. ggml_vk_destroy_buffer(buffer);
  3252. if (pinned) {
  3253. ggml_vk_host_free(ctx, x);
  3254. ggml_vk_host_free(ctx, y);
  3255. } else {
  3256. free(x);
  3257. free(y);
  3258. }
  3259. }
  3260. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  3261. #ifdef GGML_VULKAN_DEBUG
  3262. std::cerr << "ggml_vk_test_dequant(" << ne << ")" << std::endl;
  3263. #endif
  3264. const size_t x_sz = sizeof(float) * ne;
  3265. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  3266. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  3267. float * x = (float *) malloc(x_sz);
  3268. void * qx = malloc(qx_sz);
  3269. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3270. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3271. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  3272. for (size_t i = 0; i < ne; i++) {
  3273. x[i] = rand() / (float)RAND_MAX;
  3274. }
  3275. std::vector<int64_t> hist_cur(1 << 4, 0);
  3276. vk_pipeline& p = ctx->pipeline_dequant[quant];
  3277. switch(quant) {
  3278. case GGML_TYPE_Q4_0:
  3279. ggml_quantize_q4_0(x, qx, ne, ne, hist_cur.data());
  3280. break;
  3281. case GGML_TYPE_Q4_1:
  3282. ggml_quantize_q4_1(x, qx, ne, ne, hist_cur.data());
  3283. break;
  3284. case GGML_TYPE_Q5_0:
  3285. ggml_quantize_q5_0(x, qx, ne, ne, hist_cur.data());
  3286. break;
  3287. case GGML_TYPE_Q5_1:
  3288. ggml_quantize_q4_1(x, qx, ne, ne, hist_cur.data());
  3289. break;
  3290. case GGML_TYPE_Q8_0:
  3291. ggml_quantize_q8_0(x, qx, ne, ne, hist_cur.data());
  3292. break;
  3293. case GGML_TYPE_Q2_K:
  3294. ggml_quantize_q2_K(x, qx, ne, ne, hist_cur.data());
  3295. break;
  3296. case GGML_TYPE_Q3_K:
  3297. ggml_quantize_q3_K(x, qx, ne, ne, hist_cur.data());
  3298. break;
  3299. case GGML_TYPE_Q4_K:
  3300. ggml_quantize_q4_K(x, qx, ne, ne, hist_cur.data());
  3301. break;
  3302. case GGML_TYPE_Q5_K:
  3303. ggml_quantize_q5_K(x, qx, ne, ne, hist_cur.data());
  3304. break;
  3305. case GGML_TYPE_Q6_K:
  3306. ggml_quantize_q6_K(x, qx, ne, ne, hist_cur.data());
  3307. break;
  3308. default:
  3309. GGML_ASSERT(false);
  3310. }
  3311. ggml_pipeline_allocate_descriptor_sets(ctx, p, 1);
  3312. ggml_vk_buffer_write(ctx, qx_buf, 0, qx, qx_sz);
  3313. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device.lock()->compute_queue);
  3314. ggml_vk_ctx_begin(ctx, subctx);
  3315. const std::vector<int> pc = { 1, (int)ne, (int)ne, (int)ne };
  3316. ggml_vk_dispatch_pipeline(ctx, subctx, p, { { qx_buf, 0, qx_sz }, { x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  3317. ggml_vk_ctx_end(subctx);
  3318. auto begin = std::chrono::high_resolution_clock::now();
  3319. ggml_vk_submit(subctx, ctx->fence);
  3320. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  3321. ctx->device.lock()->device.resetFences({ ctx->fence });
  3322. auto end = std::chrono::high_resolution_clock::now();
  3323. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3324. ggml_vk_buffer_read(ctx, x_buf, 0, x_chk, x_sz_f16);
  3325. double avg_err = 0.0;
  3326. for (size_t i = 0; i < ne; i++) {
  3327. avg_err += std::fabs(x[i] - ggml_fp16_to_fp32(x_chk[i]));
  3328. }
  3329. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err / ne << std::endl;
  3330. ggml_vk_destroy_buffer(x_buf);
  3331. ggml_vk_destroy_buffer(qx_buf);
  3332. free(x);
  3333. free(qx);
  3334. free(x_chk);
  3335. }
  3336. #endif
  3337. static ggml_tensor_extra_gpu * ggml_vk_tensor_create_extra(ggml_tensor * tensor) {
  3338. #ifdef GGML_VULKAN_DEBUG
  3339. std::cerr << "ggml_vk_create_extra(" << tensor << " (" << tensor->name << ", " << ggml_op_name(tensor->op) << "))" << std::endl;
  3340. #endif
  3341. ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu;
  3342. extra->reset();
  3343. tensor->extra = extra;
  3344. return extra;
  3345. }
  3346. static ggml_tensor * ggml_vk_find_last_use(const ggml_tensor * node, ggml_cgraph * graph) {
  3347. GGML_ASSERT(node != nullptr);
  3348. for (int i = graph->n_nodes - 1; i >= 0; i--) {
  3349. for (int j = 0; j < GGML_MAX_SRC; j++) {
  3350. if (graph->nodes[i]->src[j] == node) {
  3351. return graph->nodes[i];
  3352. }
  3353. }
  3354. }
  3355. return nullptr;
  3356. }
  3357. static void ggml_vk_preallocate_buffers_graph(ggml_backend_vk_context * ctx, ggml_tensor * node){
  3358. #ifdef GGML_VULKAN_DEBUG
  3359. std::cerr << "ggml_vk_preallocate_buffers_graph(" << node << ")" << std::endl;
  3360. #endif
  3361. const bool any_on_device = node->backend == GGML_BACKEND_GPU
  3362. || (node->src[0] != nullptr && (node->src[0]->backend == GGML_BACKEND_GPU || node->src[0]->backend == GGML_BACKEND_GPU_SPLIT))
  3363. || (node->src[1] != nullptr && (node->src[1]->backend == GGML_BACKEND_GPU));
  3364. if (ctx->disable || (!any_on_device && node->op != GGML_OP_MUL_MAT)) {
  3365. return;
  3366. }
  3367. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) node->extra;
  3368. if (extra == nullptr) {
  3369. // Workaround for CPU backend BLAS matmul calls
  3370. extra = ggml_vk_tensor_create_extra(node);
  3371. }
  3372. ggml_tensor * src0 = node->src[0];
  3373. ggml_tensor * src1 = node->src[1];
  3374. const bool use_src0 = src0 != nullptr;
  3375. const int64_t ne00 = use_src0 ? src0->ne[0] : 0;
  3376. const int64_t ne01 = use_src0 ? src0->ne[1] : 0;
  3377. const int64_t ne02 = use_src0 ? src0->ne[2] : 0;
  3378. const int64_t ne03 = use_src0 ? src0->ne[3] : 0;
  3379. const bool use_src1 = src1 != nullptr && node->op != GGML_OP_CPY && node->op != GGML_OP_CONT && node->op != GGML_OP_DUP;
  3380. const int64_t ne10 = use_src1 ? src1->ne[0] : 0;
  3381. const int64_t ne11 = use_src1 ? src1->ne[1] : 0;
  3382. const int64_t ne12 = use_src1 ? src1->ne[2] : 0;
  3383. const int64_t ne13 = use_src1 ? src1->ne[3] : 0;
  3384. const int64_t ne20 = node->ne[0];
  3385. const int64_t ne21 = node->ne[1];
  3386. const int64_t ne22 = node->ne[2];
  3387. const int64_t ne23 = node->ne[3];
  3388. const bool f16_f32_kernel = use_src1 && src1->type == GGML_TYPE_F32;
  3389. int split_k;
  3390. if (node->op == GGML_OP_MUL_MAT) {
  3391. split_k = ggml_vk_guess_split_k(ne01, ne11, ne10);
  3392. } else {
  3393. split_k = 1;
  3394. }
  3395. const uint32_t x_ne = ne00 * ne01;
  3396. const uint32_t y_ne = ne10 * ne11;
  3397. const uint32_t d_ne = ne20 * ne21;
  3398. const uint64_t qx_sz = use_src0 ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ne02 * ne03 : 0;
  3399. const uint64_t qy_sz = use_src1 ? ggml_vk_align_size(ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type), ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ne12 * ne13 : 0;
  3400. const uint64_t x_sz = use_src0 ? ggml_vk_align_size(sizeof(ggml_fp16_t) * x_ne, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ne02 * ne03 : 0;
  3401. const uint64_t y_sz = use_src1 ? ggml_vk_align_size(f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ne12 * ne13 : 0;
  3402. uint64_t d_sz = ggml_vk_align_size(ggml_type_size(node->type) * d_ne, ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment) * ne22 * ne23;
  3403. const uint64_t split_k_size = split_k > 1 ? d_sz * 4 : 0;
  3404. if (extra->buffer_gpu.expired()) {
  3405. // Workaround for CPU backend BLAS matmul calls
  3406. extra->buffer_gpu = ggml_vk_create_buffer_temp(ctx, d_sz);
  3407. }
  3408. switch (node->op) {
  3409. case GGML_OP_REPEAT:
  3410. case GGML_OP_GET_ROWS:
  3411. case GGML_OP_RESHAPE:
  3412. case GGML_OP_VIEW:
  3413. case GGML_OP_PERMUTE:
  3414. case GGML_OP_TRANSPOSE:
  3415. case GGML_OP_ADD:
  3416. case GGML_OP_SCALE:
  3417. case GGML_OP_SQR:
  3418. case GGML_OP_CLAMP:
  3419. case GGML_OP_CPY:
  3420. case GGML_OP_CONT:
  3421. case GGML_OP_DUP:
  3422. case GGML_OP_MUL:
  3423. case GGML_OP_NORM:
  3424. case GGML_OP_RMS_NORM:
  3425. case GGML_OP_DIAG_MASK_INF:
  3426. case GGML_OP_SOFT_MAX:
  3427. case GGML_OP_ROPE:
  3428. break;
  3429. case GGML_OP_UNARY:
  3430. switch (ggml_get_unary_op(node)) {
  3431. case GGML_UNARY_OP_SILU:
  3432. case GGML_UNARY_OP_GELU:
  3433. case GGML_UNARY_OP_RELU:
  3434. break;
  3435. default:
  3436. return;
  3437. }
  3438. break;
  3439. case GGML_OP_MUL_MAT:
  3440. if (ctx->prealloc_size_qx < qx_sz) {
  3441. ctx->prealloc_size_qx = qx_sz;
  3442. }
  3443. if (ctx->prealloc_size_qy < qy_sz) {
  3444. ctx->prealloc_size_qy = qy_sz;
  3445. }
  3446. if (ctx->prealloc_size_x < x_sz) {
  3447. ctx->prealloc_size_x = x_sz;
  3448. }
  3449. if (ctx->prealloc_size_y < y_sz) {
  3450. ctx->prealloc_size_y = y_sz;
  3451. }
  3452. if (ctx->prealloc_size_split_k < split_k_size) {
  3453. ctx->prealloc_size_split_k = split_k_size;
  3454. }
  3455. if (ctx->staging_size < x_sz + y_sz) {
  3456. ctx->staging_size = x_sz + y_sz;
  3457. }
  3458. break;
  3459. default:
  3460. return;
  3461. }
  3462. }
  3463. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  3464. if (ctx->disable) {
  3465. return;
  3466. }
  3467. #ifdef GGML_VULKAN_DEBUG
  3468. std::cerr << "ggml_vk_preallocate_buffers(qx_size: " << ctx->prealloc_size_qx << " qy_size: " << ctx->prealloc_size_qy << " x_size: " << ctx->prealloc_size_x << " y_size: " << ctx->prealloc_size_y << " split_k_size: " << ctx->prealloc_size_split_k << ")" << std::endl;
  3469. #endif
  3470. #if defined(GGML_VULKAN_RUN_TESTS)
  3471. ctx->staging = ggml_vk_create_buffer_check(ctx, 100ul * 1024ul * 1024ul,
  3472. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached
  3473. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  3474. ggml_vk_test_transfer(ctx, 8192 * 1000, false);
  3475. ggml_vk_test_transfer(ctx, 8192 * 1000, true);
  3476. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q4_0);
  3477. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q4_1);
  3478. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q5_0);
  3479. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q5_1);
  3480. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q8_0);
  3481. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q2_K);
  3482. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q3_K);
  3483. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q4_K);
  3484. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q5_K);
  3485. ggml_vk_test_dequant(ctx, 2560 * 7680, GGML_TYPE_Q6_K);
  3486. const std::vector<size_t> vals {
  3487. 8, 8, 8,
  3488. 100, 46, 576,
  3489. 623, 111, 128,
  3490. 100, 46, 558,
  3491. 512, 1, 256,
  3492. 128, 110, 622,
  3493. 511, 511, 127,
  3494. 511, 511, 7,
  3495. 511, 511, 17,
  3496. 49, 49, 128,
  3497. 128, 49, 49,
  3498. 4096, 49, 4096,
  3499. 11008, 49, 4096,
  3500. 4096, 49, 11008,
  3501. 32000, 49, 4096,
  3502. 512, 512, 128,
  3503. 128, 512, 512,
  3504. 4096, 512, 4096,
  3505. 11008, 512, 4096,
  3506. 4096, 512, 11008,
  3507. 32000, 512, 4096,
  3508. };
  3509. const size_t num_it = 1;
  3510. for (size_t i = 0; i < vals.size(); i += 3) {
  3511. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  3512. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  3513. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  3514. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  3515. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  3516. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  3517. std::cerr << std::endl;
  3518. }
  3519. GGML_ASSERT(false);
  3520. #endif
  3521. if (ctx->prealloc_qx == nullptr || (ctx->prealloc_size_qx > 0 && ctx->prealloc_qx->size < ctx->prealloc_size_qx)) {
  3522. // Resize buffer
  3523. if (ctx->prealloc_qx != nullptr) {
  3524. ggml_vk_destroy_buffer(ctx->prealloc_qx);
  3525. }
  3526. ctx->prealloc_qx = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_qx);
  3527. }
  3528. if (ctx->prealloc_qy == nullptr || (ctx->prealloc_size_qy > 0 && ctx->prealloc_qy->size < ctx->prealloc_size_qy)) {
  3529. // Resize buffer
  3530. if (ctx->prealloc_qy != nullptr) {
  3531. ggml_vk_destroy_buffer(ctx->prealloc_qy);
  3532. }
  3533. ctx->prealloc_qy = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_qy);
  3534. }
  3535. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  3536. // Resize buffer
  3537. if (ctx->prealloc_x != nullptr) {
  3538. ggml_vk_destroy_buffer(ctx->prealloc_x);
  3539. }
  3540. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_x);
  3541. }
  3542. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  3543. // Resize buffer
  3544. if (ctx->prealloc_y != nullptr) {
  3545. ggml_vk_destroy_buffer(ctx->prealloc_y);
  3546. }
  3547. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_y);
  3548. }
  3549. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  3550. // Resize buffer
  3551. if (ctx->prealloc_split_k != nullptr) {
  3552. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  3553. }
  3554. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_split_k);
  3555. }
  3556. if (ctx->staging == nullptr || (ctx->staging_size > 0 && ctx->staging->size < ctx->staging_size)) {
  3557. // Resize buffer
  3558. if (ctx->staging != nullptr) {
  3559. ggml_vk_destroy_buffer(ctx->staging);
  3560. }
  3561. ctx->staging = ggml_vk_create_buffer_check(ctx, ctx->staging_size,
  3562. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  3563. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  3564. }
  3565. }
  3566. static void ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, bool last_node){
  3567. const bool any_on_device = node->backend == GGML_BACKEND_GPU
  3568. || (node->src[0] != nullptr && (node->src[0]->backend == GGML_BACKEND_GPU || node->src[0]->backend == GGML_BACKEND_GPU_SPLIT))
  3569. || (node->src[1] != nullptr && node->src[1]->backend == GGML_BACKEND_GPU);
  3570. if (ctx->disable || (!any_on_device && node->op != GGML_OP_MUL_MAT) || (node->op == GGML_OP_MUL_MAT && !any_on_device && !ggml_vk_can_mul_mat(node->src[0], node->src[1], node))) {
  3571. return;
  3572. }
  3573. #ifdef GGML_VULKAN_DEBUG
  3574. std::cerr << "ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")" << std::endl;
  3575. #endif
  3576. ctx->semaphore_idx = 0;
  3577. ctx->staging_offset = 0;
  3578. const ggml_tensor * src0 = node->src[0];
  3579. const ggml_tensor * src1 = node->src[1];
  3580. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) node->extra;
  3581. switch (node->op) {
  3582. case GGML_OP_UNARY:
  3583. switch (ggml_get_unary_op(node)) {
  3584. case GGML_UNARY_OP_SILU:
  3585. case GGML_UNARY_OP_GELU:
  3586. case GGML_UNARY_OP_RELU:
  3587. break;
  3588. default:
  3589. return;
  3590. }
  3591. break;
  3592. case GGML_OP_REPEAT:
  3593. // case GGML_OP_GET_ROWS:
  3594. case GGML_OP_ADD:
  3595. case GGML_OP_MUL:
  3596. case GGML_OP_SCALE:
  3597. case GGML_OP_SQR:
  3598. case GGML_OP_CLAMP:
  3599. case GGML_OP_CPY:
  3600. case GGML_OP_CONT:
  3601. case GGML_OP_DUP:
  3602. case GGML_OP_RESHAPE:
  3603. case GGML_OP_VIEW:
  3604. case GGML_OP_PERMUTE:
  3605. case GGML_OP_TRANSPOSE:
  3606. case GGML_OP_NORM:
  3607. case GGML_OP_RMS_NORM:
  3608. case GGML_OP_DIAG_MASK_INF:
  3609. case GGML_OP_SOFT_MAX:
  3610. case GGML_OP_ROPE:
  3611. case GGML_OP_MUL_MAT:
  3612. case GGML_OP_NONE:
  3613. break;
  3614. default:
  3615. if (any_on_device) {
  3616. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  3617. GGML_ASSERT(false);
  3618. }
  3619. return;
  3620. }
  3621. if (ctx->compute_ctx == nullptr) {
  3622. ctx->compute_ctx = ggml_vk_create_context(ctx, ctx->device.lock()->compute_queue);
  3623. ggml_vk_ctx_begin(ctx, ctx->compute_ctx);
  3624. }
  3625. switch (node->op) {
  3626. case GGML_OP_REPEAT:
  3627. ggml_vk_repeat(ctx, ctx->compute_ctx, src0, src1, node);
  3628. break;
  3629. case GGML_OP_GET_ROWS:
  3630. ggml_vk_get_rows(ctx, ctx->compute_ctx, src0, src1, node);
  3631. break;
  3632. case GGML_OP_ADD:
  3633. ggml_vk_add(ctx, ctx->compute_ctx, src0, src1, node);
  3634. break;
  3635. case GGML_OP_MUL:
  3636. ggml_vk_mul(ctx, ctx->compute_ctx, src0, src1, node);
  3637. break;
  3638. case GGML_OP_SCALE:
  3639. ggml_vk_scale(ctx, ctx->compute_ctx, src0, node);
  3640. break;
  3641. case GGML_OP_SQR:
  3642. ggml_vk_sqr(ctx, ctx->compute_ctx, src0, node);
  3643. break;
  3644. case GGML_OP_CLAMP:
  3645. ggml_vk_clamp(ctx, ctx->compute_ctx, src0, node);
  3646. break;
  3647. case GGML_OP_CPY:
  3648. case GGML_OP_CONT:
  3649. case GGML_OP_DUP:
  3650. ggml_vk_cpy(ctx, ctx->compute_ctx, src0, node);
  3651. break;
  3652. case GGML_OP_RESHAPE:
  3653. case GGML_OP_VIEW:
  3654. case GGML_OP_PERMUTE:
  3655. case GGML_OP_TRANSPOSE:
  3656. case GGML_OP_NONE:
  3657. ggml_vk_nop(ctx, ctx->compute_ctx, src0, node);
  3658. break;
  3659. case GGML_OP_NORM:
  3660. ggml_vk_norm(ctx, ctx->compute_ctx, src0, node);
  3661. break;
  3662. case GGML_OP_RMS_NORM:
  3663. ggml_vk_rms_norm(ctx, ctx->compute_ctx, src0, node);
  3664. break;
  3665. case GGML_OP_UNARY:
  3666. switch (ggml_get_unary_op(node)) {
  3667. case GGML_UNARY_OP_SILU:
  3668. case GGML_UNARY_OP_GELU:
  3669. case GGML_UNARY_OP_RELU:
  3670. ggml_vk_unary(ctx, ctx->compute_ctx, src0, node);
  3671. break;
  3672. default:
  3673. return;
  3674. }
  3675. break;
  3676. case GGML_OP_DIAG_MASK_INF:
  3677. ggml_vk_diag_mask_inf(ctx, ctx->compute_ctx, src0, node);
  3678. break;
  3679. case GGML_OP_SOFT_MAX:
  3680. ggml_vk_soft_max(ctx, ctx->compute_ctx, src0, src1, node);
  3681. break;
  3682. case GGML_OP_ROPE:
  3683. ggml_vk_rope(ctx, ctx->compute_ctx, src0, src1, node);
  3684. break;
  3685. case GGML_OP_MUL_MAT:
  3686. ggml_vk_mul_mat(ctx, ctx->compute_ctx, src0, src1, node);
  3687. break;
  3688. default:
  3689. return;
  3690. }
  3691. extra->ready = true;
  3692. extra->ctx_idx = ctx->compute_ctx->idx;
  3693. #ifdef GGML_VULKAN_CHECK_RESULTS
  3694. // Force context reset on each node so that each tensor ends up in its own context
  3695. // and can be run and compared to its CPU equivalent separately
  3696. last_node = true;
  3697. #endif
  3698. if (node->backend == GGML_BACKEND_CPU || last_node) {
  3699. ggml_vk_ctx_end(ctx->compute_ctx);
  3700. ctx->compute_ctx->exit_tensor = node;
  3701. ctx->compute_ctx = nullptr;
  3702. }
  3703. }
  3704. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor){
  3705. const bool any_on_device = tensor->backend == GGML_BACKEND_GPU
  3706. || (tensor->src[0] != nullptr && (tensor->src[0]->backend == GGML_BACKEND_GPU || tensor->src[0]->backend == GGML_BACKEND_GPU_SPLIT))
  3707. || (tensor->src[1] != nullptr && tensor->src[1]->backend == GGML_BACKEND_GPU);
  3708. if (ctx->disable || (!any_on_device && tensor->op != GGML_OP_MUL_MAT)) {
  3709. return false;
  3710. }
  3711. ggml_tensor_extra_gpu * extra = nullptr;
  3712. switch (tensor->op) {
  3713. case GGML_OP_ADD:
  3714. case GGML_OP_GET_ROWS:
  3715. case GGML_OP_MUL:
  3716. case GGML_OP_SCALE:
  3717. case GGML_OP_SQR:
  3718. case GGML_OP_CLAMP:
  3719. case GGML_OP_CPY:
  3720. case GGML_OP_CONT:
  3721. case GGML_OP_DUP:
  3722. case GGML_OP_NORM:
  3723. case GGML_OP_RMS_NORM:
  3724. case GGML_OP_DIAG_MASK_INF:
  3725. case GGML_OP_SOFT_MAX:
  3726. case GGML_OP_ROPE:
  3727. case GGML_OP_RESHAPE:
  3728. case GGML_OP_VIEW:
  3729. case GGML_OP_PERMUTE:
  3730. case GGML_OP_TRANSPOSE:
  3731. case GGML_OP_NONE:
  3732. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  3733. break;
  3734. case GGML_OP_UNARY:
  3735. switch (ggml_get_unary_op(tensor)) {
  3736. case GGML_UNARY_OP_SILU:
  3737. case GGML_UNARY_OP_GELU:
  3738. case GGML_UNARY_OP_RELU:
  3739. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  3740. break;
  3741. default:
  3742. return false;
  3743. }
  3744. break;
  3745. case GGML_OP_MUL_MAT:
  3746. if (!any_on_device && !ggml_vk_can_mul_mat(tensor->src[0], tensor->src[1], tensor)) {
  3747. return false;
  3748. }
  3749. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  3750. break;
  3751. default:
  3752. return false;
  3753. }
  3754. if (extra == nullptr) {
  3755. return false;
  3756. }
  3757. if (params->ith != 0) {
  3758. return true;
  3759. }
  3760. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
  3761. return true;
  3762. }
  3763. #ifdef GGML_VULKAN_DEBUG
  3764. std::cerr << "ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", backend=" << tensor->backend << ", 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 << ")" << std::endl;
  3765. #endif
  3766. #ifdef GGML_VULKAN_CHECK_RESULTS
  3767. ggml_vk_check_results_0(ctx, params, tensor);
  3768. #endif
  3769. GGML_ASSERT(extra->ready);
  3770. vk_context& subctx = ctx->gc.contexts[extra->ctx_idx];
  3771. // Only run if ctx hasn't been submitted yet
  3772. if (!subctx.seqs.empty()) {
  3773. // Do staging buffer copies
  3774. for (auto& cpy : subctx.in_memcpys) {
  3775. memcpy(cpy.dst, cpy.src, cpy.n);
  3776. }
  3777. ggml_vk_submit(&subctx, ctx->fence);
  3778. }
  3779. if (tensor == subctx.exit_tensor) {
  3780. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  3781. ctx->device.lock()->device.resetFences({ ctx->fence });
  3782. // Do staging buffer copies
  3783. for (auto& cpy : subctx.out_memcpys) {
  3784. memcpy(cpy.dst, cpy.src, cpy.n);
  3785. }
  3786. subctx.in_memcpys.clear();
  3787. subctx.out_memcpys.clear();
  3788. }
  3789. extra->ready = false;
  3790. return true;
  3791. }
  3792. // Clean up after graph processing is done
  3793. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  3794. if (ctx->disable) {
  3795. return;
  3796. }
  3797. #ifdef GGML_VULKAN_DEBUG
  3798. std::cerr << "ggml_vk_graph_cleanup()" << std::endl;
  3799. #endif
  3800. for (auto& buffer : ctx->gc.temp_buffers) {
  3801. ggml_vk_pool_free(ctx, buffer);
  3802. }
  3803. ctx->gc.temp_buffers.clear();
  3804. for (auto * pipeline : ctx->gc.pipelines) {
  3805. ggml_pipeline_cleanup(*pipeline);
  3806. }
  3807. ggml_vk_queue_cleanup(ctx, ctx->device.lock()->compute_queue);
  3808. ggml_vk_queue_cleanup(ctx, ctx->device.lock()->transfer_queue);
  3809. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  3810. ctx->device.lock()->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  3811. }
  3812. ctx->gc.semaphores.clear();
  3813. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  3814. ctx->device.lock()->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  3815. }
  3816. ctx->gc.tl_semaphores.clear();
  3817. ctx->semaphore_idx = 0;
  3818. ctx->event_idx = 0;
  3819. for (auto& event : ctx->gc.events) {
  3820. ctx->device.lock()->device.resetEvent(event);
  3821. }
  3822. ctx->staging_offset = 0;
  3823. ctx->compute_ctx = nullptr;
  3824. ctx->transfer_ctx = nullptr;
  3825. ctx->gc.contexts.clear();
  3826. }
  3827. // Clean up on backend free
  3828. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  3829. #ifdef GGML_VULKAN_DEBUG
  3830. std::cerr << "ggml_vk_cleanup(" << ctx->idx << ")" << std::endl;
  3831. #endif
  3832. ggml_vk_graph_cleanup(ctx);
  3833. ggml_vk_destroy_buffer(ctx->prealloc_qx);
  3834. ggml_vk_destroy_buffer(ctx->prealloc_qy);
  3835. ggml_vk_destroy_buffer(ctx->prealloc_x);
  3836. ggml_vk_destroy_buffer(ctx->prealloc_y);
  3837. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  3838. ggml_vk_destroy_buffer(ctx->staging);
  3839. ggml_vk_destroy_buffer(ctx->sync_staging);
  3840. for (auto& buffer : ctx->buffer_pool) {
  3841. ggml_vk_destroy_buffer(buffer);
  3842. }
  3843. ctx->prealloc_size_qx = 0;
  3844. ctx->prealloc_size_qy = 0;
  3845. ctx->prealloc_size_x = 0;
  3846. ctx->prealloc_size_y = 0;
  3847. ctx->prealloc_size_split_k = 0;
  3848. ctx->staging_size = 0;
  3849. for (auto& event : ctx->gc.events) {
  3850. ctx->device.lock()->device.destroyEvent(event);
  3851. }
  3852. ctx->gc.events.clear();
  3853. for (auto* pipeline : ctx->gc.pipelines) {
  3854. ggml_vk_destroy_pipeline(ctx, pipeline);
  3855. }
  3856. ctx->gc.pipelines.clear();
  3857. ctx->device.lock()->device.destroyFence(ctx->fence);
  3858. ctx->device.lock()->device.destroyCommandPool(ctx->device.lock()->compute_queue.pool);
  3859. if (!ctx->device.lock()->single_queue) {
  3860. ctx->device.lock()->device.destroyCommandPool(ctx->device.lock()->transfer_queue.pool);
  3861. }
  3862. }
  3863. GGML_CALL static int ggml_vk_get_device_count() {
  3864. ggml_vk_instance_init();
  3865. return vk_instance.device_indices.size();
  3866. }
  3867. GGML_CALL static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  3868. ggml_vk_instance_init();
  3869. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3870. vk::PhysicalDeviceProperties props;
  3871. devices[device].getProperties(&props);
  3872. snprintf(description, description_size, "%s", props.deviceName.data());
  3873. }
  3874. // CPU assist interface
  3875. void ggml_vk_init_cpu_assist() {
  3876. ggml_vk_instance_init();
  3877. std::cerr << "ggml_vulkan: Found " << ggml_vk_get_device_count() << " Vulkan devices:" << std::endl;
  3878. for (int i = 0; i < ggml_vk_get_device_count(); i++) {
  3879. ggml_vk_print_gpu_info(i);
  3880. }
  3881. // Initialize the first backend to make sure CPU matrix multiplications can be offloaded.
  3882. ggml_backend_vk_init(0);
  3883. }
  3884. void ggml_vk_preallocate_buffers_graph_cpu_assist(ggml_tensor * node) {
  3885. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3886. if (!ctx->initialized) {
  3887. return;
  3888. }
  3889. ggml_vk_preallocate_buffers_graph(ctx, node);
  3890. }
  3891. void ggml_vk_preallocate_buffers_cpu_assist() {
  3892. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3893. if (!ctx->initialized) {
  3894. return;
  3895. }
  3896. ggml_vk_preallocate_buffers(ctx);
  3897. }
  3898. void ggml_vk_build_graph_cpu_assist(ggml_tensor * node, bool last_node) {
  3899. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3900. if (!ctx->initialized) {
  3901. return;
  3902. }
  3903. ggml_vk_build_graph(ctx, node, last_node);
  3904. }
  3905. bool ggml_vk_compute_forward_cpu_assist(ggml_compute_params * params, ggml_tensor * tensor){
  3906. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3907. if (!ctx->initialized) {
  3908. return false;
  3909. }
  3910. return ggml_vk_compute_forward(ctx, params, tensor);
  3911. }
  3912. void ggml_vk_graph_cleanup_cpu_assist() {
  3913. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3914. if (!ctx->initialized) {
  3915. return;
  3916. }
  3917. ggml_vk_graph_cleanup(ctx);
  3918. }
  3919. void ggml_vk_free_cpu_assist() {
  3920. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  3921. if (!ctx->initialized || vk_instance.backends[0] == nullptr) {
  3922. return;
  3923. }
  3924. ggml_backend_vk_free(vk_instance.backends[0]);
  3925. }
  3926. // backend interface
  3927. #define UNUSED GGML_UNUSED
  3928. // device backend
  3929. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  3930. struct ggml_backend_vk_buffer_context {
  3931. ggml_backend_vk_context * ctx;
  3932. vk_buffer dev_buffer;
  3933. ggml_tensor_extra_gpu * temp_tensor_extras = nullptr;
  3934. size_t temp_tensor_extra_index = 0;
  3935. std::string name;
  3936. ggml_backend_vk_buffer_context(ggml_backend_vk_context * ctx, vk_buffer&& dev_buffer, std::string& name) :
  3937. ctx(ctx),
  3938. dev_buffer(dev_buffer),
  3939. name(name) {
  3940. }
  3941. ~ggml_backend_vk_buffer_context() {
  3942. ggml_vk_destroy_buffer(dev_buffer);
  3943. delete[] temp_tensor_extras;
  3944. }
  3945. ggml_tensor_extra_gpu * ggml_vk_alloc_temp_tensor_extra() {
  3946. if (temp_tensor_extras == nullptr) {
  3947. temp_tensor_extras = new ggml_tensor_extra_gpu[GGML_VK_MAX_NODES];
  3948. }
  3949. size_t alloc_index = temp_tensor_extra_index;
  3950. temp_tensor_extra_index = (temp_tensor_extra_index + 1) % GGML_VK_MAX_NODES;
  3951. ggml_tensor_extra_gpu * extra = &temp_tensor_extras[alloc_index];
  3952. extra->reset();
  3953. return extra;
  3954. }
  3955. };
  3956. GGML_CALL static const char * ggml_backend_vk_buffer_get_name(ggml_backend_buffer_t buffer) {
  3957. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  3958. return ctx->name.c_str();
  3959. }
  3960. GGML_CALL static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  3961. return buffer->iface.get_name == ggml_backend_vk_buffer_get_name;
  3962. }
  3963. GGML_CALL static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  3964. #ifdef GGML_VULKAN_DEBUG
  3965. std::cerr << "ggml_backend_vk_buffer_free_buffer()" << std::endl;
  3966. #endif
  3967. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  3968. ggml_vk_destroy_buffer(ctx->dev_buffer);
  3969. delete ctx;
  3970. }
  3971. GGML_CALL static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  3972. return vk_ptr_base;
  3973. UNUSED(buffer);
  3974. }
  3975. GGML_CALL static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  3976. #ifdef GGML_VULKAN_DEBUG
  3977. std::cerr << "ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")" << std::endl;
  3978. #endif
  3979. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  3980. ggml_tensor_extra_gpu * extra = ctx->ggml_vk_alloc_temp_tensor_extra();
  3981. if (tensor->view_src != nullptr && tensor->view_src->extra != nullptr) {
  3982. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  3983. ggml_tensor_extra_gpu * extra_view = (ggml_tensor_extra_gpu *) tensor->view_src->extra;
  3984. extra->buffer_gpu = extra_view->buffer_gpu;
  3985. extra->offset = extra_view->offset + tensor->view_offs;
  3986. } else {
  3987. extra->buffer_gpu = ctx->dev_buffer;
  3988. extra->offset = (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  3989. }
  3990. tensor->backend = GGML_BACKEND_GPU;
  3991. tensor->extra = extra;
  3992. }
  3993. GGML_CALL 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) {
  3994. #ifdef GGML_VULKAN_DEBUG
  3995. std::cerr << "ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")" << std::endl;
  3996. #endif
  3997. GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
  3998. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  3999. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4000. vk_buffer buf = extra->buffer_gpu.lock();
  4001. ggml_vk_buffer_write(ctx->ctx, buf, extra->offset + offset, data, size);
  4002. }
  4003. GGML_CALL 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) {
  4004. #ifdef GGML_VULKAN_DEBUG
  4005. std::cerr << "ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")" << std::endl;
  4006. #endif
  4007. GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
  4008. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4009. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4010. vk_buffer buf = extra->buffer_gpu.lock();
  4011. ggml_vk_buffer_read(ctx->ctx, buf, extra->offset + offset, data, size);
  4012. }
  4013. GGML_CALL static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  4014. if (ggml_backend_buffer_is_vk(src->buffer)) {
  4015. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4016. ggml_tensor_extra_gpu * src_extra = (ggml_tensor_extra_gpu *) src->extra;
  4017. ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  4018. vk_buffer src_buf = src_extra->buffer_gpu.lock();
  4019. vk_buffer dst_buf = dst_extra->buffer_gpu.lock();
  4020. ggml_vk_buffer_copy(dst_buf, dst_extra->offset, src_buf, src_extra->offset, ggml_nbytes(src));
  4021. return true;
  4022. }
  4023. return false;
  4024. }
  4025. GGML_CALL static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  4026. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4027. ggml_vk_buffer_memset(ctx->ctx, ctx->dev_buffer, 0, value, buffer->size);
  4028. }
  4029. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  4030. /* .get_name = */ ggml_backend_vk_buffer_get_name,
  4031. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  4032. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  4033. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  4034. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  4035. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  4036. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  4037. /* .clear = */ ggml_backend_vk_buffer_clear,
  4038. /* .reset = */ NULL,
  4039. };
  4040. // vk buffer type
  4041. struct ggml_backend_vk_buffer_type_context {
  4042. std::string name;
  4043. ggml_backend_vk_context * ctx;
  4044. };
  4045. GGML_CALL static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  4046. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  4047. return ctx->name.c_str();
  4048. }
  4049. GGML_CALL static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  4050. #ifdef GGML_VULKAN_DEBUG
  4051. std::cerr << "ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")" << std::endl;
  4052. #endif
  4053. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4054. vk_buffer dev_buffer = ggml_vk_create_buffer_device(ctx->ctx, size);
  4055. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->ctx, std::move(dev_buffer), ctx->name);
  4056. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  4057. }
  4058. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  4059. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4060. return ctx->ctx->device.lock()->properties.limits.minStorageBufferOffsetAlignment;
  4061. }
  4062. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  4063. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4064. return ctx->ctx->device.lock()->max_memory_allocation_size;
  4065. }
  4066. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  4067. return ggml_nbytes(tensor);
  4068. UNUSED(buft);
  4069. }
  4070. GGML_CALL static bool ggml_backend_vk_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  4071. if (!ggml_backend_is_vk(backend)) {
  4072. return false;
  4073. }
  4074. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  4075. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4076. return buft_ctx->ctx->idx == ctx->idx;
  4077. }
  4078. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  4079. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  4080. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  4081. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  4082. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  4083. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  4084. /* .supports_backend = */ ggml_backend_vk_buffer_type_supports_backend,
  4085. /* .is_host = */ NULL,
  4086. };
  4087. GGML_CALL ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t idx) {
  4088. #ifdef GGML_VULKAN_DEBUG
  4089. std::cerr << "ggml_backend_vk_buffer_type(" << idx << ")" << std::endl;
  4090. #endif
  4091. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4092. ggml_backend_vk_init(idx);
  4093. return &vk_instance.buffer_types[idx];
  4094. }
  4095. // host buffer type
  4096. GGML_CALL static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  4097. return GGML_VK_NAME "_Host";
  4098. UNUSED(buft);
  4099. }
  4100. GGML_CALL static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  4101. return GGML_VK_NAME "_Host";
  4102. UNUSED(buffer);
  4103. }
  4104. GGML_CALL static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  4105. #ifdef GGML_VULKAN_DEBUG
  4106. std::cerr << "ggml_backend_vk_host_buffer_free_buffer()" << std::endl;
  4107. #endif
  4108. ggml_vk_host_free(&vk_instance.contexts[0], buffer->context);
  4109. }
  4110. GGML_CALL static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  4111. #ifdef GGML_VULKAN_DEBUG
  4112. std::cerr << "ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")" << std::endl;
  4113. #endif
  4114. void * ptr = nullptr;
  4115. try {
  4116. ptr = ggml_vk_host_malloc(&vk_instance.contexts[0], size);
  4117. } catch (vk::SystemError& e) {
  4118. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  4119. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  4120. // fallback to cpu buffer
  4121. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  4122. }
  4123. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  4124. buffer->buft = buft;
  4125. buffer->iface.get_name = ggml_backend_vk_host_buffer_name;
  4126. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  4127. return buffer;
  4128. }
  4129. GGML_CALL static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  4130. return vk_instance.contexts[0].device.lock()->properties.limits.minMemoryMapAlignment;
  4131. UNUSED(buft);
  4132. }
  4133. GGML_CALL ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  4134. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  4135. /* .iface = */ {
  4136. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  4137. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  4138. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  4139. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  4140. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  4141. /* .supports_backend = */ ggml_backend_cpu_buffer_type()->iface.supports_backend,
  4142. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  4143. },
  4144. /* .context = */ nullptr,
  4145. };
  4146. if (!vk_instance.contexts[0].initialized) {
  4147. // Fall back to CPU
  4148. return ggml_backend_cpu_buffer_type();
  4149. }
  4150. return &ggml_backend_vk_buffer_type_host;
  4151. }
  4152. // backend
  4153. GGML_CALL static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  4154. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4155. return ctx->name.c_str();
  4156. }
  4157. GGML_CALL static void ggml_backend_vk_free(ggml_backend_t backend) {
  4158. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4159. #ifdef GGML_VULKAN_DEBUG
  4160. std::cerr << "ggml_backend_vk_free(" << ctx->name << ")" << std::endl;
  4161. #endif
  4162. size_t idx = ctx->idx;
  4163. ggml_vk_cleanup(ctx);
  4164. // Release device
  4165. vk_instance.devices[ctx->idx].reset();
  4166. ctx->initialized = false;
  4167. vk_instance.initialized[idx] = false;
  4168. vk_instance.backends[idx] = nullptr;
  4169. memset(&vk_instance.buffer_types[idx], 0, sizeof(ggml_backend_buffer_type));
  4170. delete backend;
  4171. }
  4172. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  4173. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4174. GGML_ASSERT(ctx->initialized);
  4175. return ggml_backend_vk_buffer_type(ctx->idx);
  4176. }
  4177. GGML_CALL static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  4178. #ifdef GGML_VULKAN_DEBUG
  4179. std::cerr << "ggml_backend_vk_set_tensor_async(" << size << ")" << std::endl;
  4180. #endif
  4181. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4182. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  4183. GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
  4184. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4185. if (ctx->transfer_ctx == nullptr) {
  4186. // Initialize new transfer context
  4187. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  4188. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4189. }
  4190. vk_buffer buf = extra->buffer_gpu.lock();
  4191. ggml_vk_buffer_write_async(ctx, ctx->transfer_ctx, buf, extra->offset + offset, data, size);
  4192. }
  4193. GGML_CALL static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  4194. #ifdef GGML_VULKAN_DEBUG
  4195. std::cerr << "ggml_backend_vk_get_tensor_async(" << size << ")" << std::endl;
  4196. #endif
  4197. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4198. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  4199. GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
  4200. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4201. if (ctx->transfer_ctx == nullptr) {
  4202. // Initialize new transfer context
  4203. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  4204. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4205. }
  4206. vk_buffer buf = extra->buffer_gpu.lock();
  4207. ggml_vk_buffer_read_async(ctx, ctx->transfer_ctx, buf, extra->offset + offset, data, size);
  4208. }
  4209. GGML_CALL static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  4210. #ifdef GGML_VULKAN_DEBUG
  4211. std::cerr << "ggml_backend_vk_cpy_tensor_async()" << std::endl;
  4212. #endif
  4213. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4214. if ((dst->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || dst->buffer->buft == ggml_backend_vk_host_buffer_type()) && ggml_backend_buffer_is_vk(src->buffer)) {
  4215. ggml_tensor_extra_gpu * src_extra = (ggml_tensor_extra_gpu *) src->extra;
  4216. ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  4217. if (ctx->transfer_ctx == nullptr) {
  4218. // Initialize new transfer context
  4219. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device.lock()->transfer_queue);
  4220. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4221. }
  4222. vk_buffer src_buf = src_extra->buffer_gpu.lock();
  4223. vk_buffer dst_buf = dst_extra->buffer_gpu.lock();
  4224. ggml_vk_buffer_copy_async(ctx->transfer_ctx, src_buf, src_extra->offset, dst_buf, dst_extra->offset, ggml_nbytes(src));
  4225. return true;
  4226. }
  4227. return false;
  4228. }
  4229. GGML_CALL static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  4230. #ifdef GGML_VULKAN_DEBUG
  4231. std::cerr << "ggml_backend_vk_synchronize()" << std::endl;
  4232. #endif
  4233. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4234. if(ctx->transfer_ctx == nullptr) {
  4235. return;
  4236. }
  4237. ggml_vk_ctx_end(ctx->transfer_ctx);
  4238. for (auto& cpy : ctx->transfer_ctx->in_memcpys) {
  4239. memcpy(cpy.dst, cpy.src, cpy.n);
  4240. }
  4241. ggml_vk_submit(ctx->transfer_ctx, ctx->fence);
  4242. VK_CHECK(ctx->device.lock()->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  4243. ctx->device.lock()->device.resetFences({ ctx->fence });
  4244. for (auto& cpy : ctx->transfer_ctx->out_memcpys) {
  4245. memcpy(cpy.dst, cpy.src, cpy.n);
  4246. }
  4247. ctx->transfer_ctx = nullptr;
  4248. }
  4249. GGML_CALL static bool ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  4250. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4251. for (int i = 0; i < cgraph->n_nodes; i++) {
  4252. ggml_vk_preallocate_buffers_graph(ctx, cgraph->nodes[i]);
  4253. }
  4254. ggml_vk_preallocate_buffers(ctx);
  4255. int last_node = cgraph->n_nodes - 1;
  4256. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  4257. while (last_node > 0 && cgraph->nodes[last_node]->backend != GGML_BACKEND_GPU) {
  4258. last_node -= 1;
  4259. }
  4260. for (int i = 0; i < cgraph->n_nodes; i++) {
  4261. ggml_vk_build_graph(ctx,cgraph->nodes[i], i == last_node);
  4262. }
  4263. ggml_compute_params params = {};
  4264. params.type = GGML_TASK_COMPUTE;
  4265. params.ith = 0;
  4266. for (int i = 0; i < cgraph->n_nodes; i++) {
  4267. ggml_tensor * node = cgraph->nodes[i];
  4268. if (node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) {
  4269. continue;
  4270. }
  4271. bool ok = ggml_vk_compute_forward(ctx, &params, node);
  4272. if (!ok) {
  4273. fprintf(stderr, "%s: error: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op));
  4274. }
  4275. #ifdef GGML_VULKAN_CHECK_RESULTS
  4276. else {
  4277. ggml_vk_check_results_1(ctx, &params, node);
  4278. }
  4279. #endif
  4280. GGML_ASSERT(ok);
  4281. }
  4282. ggml_vk_graph_cleanup(ctx);
  4283. return true;
  4284. UNUSED(backend);
  4285. }
  4286. GGML_CALL static bool ggml_backend_vk_supports_op(ggml_backend_t backend, const ggml_tensor * op) {
  4287. switch (op->op) {
  4288. case GGML_OP_UNARY:
  4289. switch (ggml_get_unary_op(op)) {
  4290. case GGML_UNARY_OP_GELU:
  4291. case GGML_UNARY_OP_SILU:
  4292. case GGML_UNARY_OP_RELU:
  4293. return true;
  4294. default:
  4295. return false;
  4296. }
  4297. break;
  4298. case GGML_OP_MUL_MAT:
  4299. {
  4300. struct ggml_tensor * a;
  4301. struct ggml_tensor * b;
  4302. if (op->op == GGML_OP_MUL_MAT) {
  4303. a = op->src[0];
  4304. b = op->src[1];
  4305. } else {
  4306. a = op->src[2];
  4307. b = op->src[1];
  4308. }
  4309. if (a->ne[3] != b->ne[3]) {
  4310. return false;
  4311. }
  4312. return true;
  4313. } break;
  4314. // case GGML_OP_GET_ROWS:
  4315. // {
  4316. // switch (op->src[0]->type) {
  4317. // case GGML_TYPE_F16:
  4318. // case GGML_TYPE_F32:
  4319. // case GGML_TYPE_Q4_0:
  4320. // case GGML_TYPE_Q4_1:
  4321. // case GGML_TYPE_Q5_0:
  4322. // case GGML_TYPE_Q5_1:
  4323. // case GGML_TYPE_Q8_0:
  4324. // return true;
  4325. // default:
  4326. // return false;
  4327. // }
  4328. // } break;
  4329. case GGML_OP_CPY:
  4330. {
  4331. ggml_type src0_type = op->src[0]->type;
  4332. ggml_type src1_type = op->src[1]->type;
  4333. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4334. return true;
  4335. }
  4336. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4337. return true;
  4338. }
  4339. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4340. return true;
  4341. }
  4342. return false;
  4343. } break;
  4344. case GGML_OP_DUP:
  4345. // case GGML_OP_REPEAT:
  4346. // {
  4347. // ggml_type src0_type = op->src[0]->type;
  4348. // return src0_type != GGML_TYPE_I32 && src0_type != GGML_TYPE_I16;
  4349. // } break;
  4350. case GGML_OP_ROPE:
  4351. {
  4352. const int mode = ((const int32_t *) op->op_params)[2];
  4353. const bool is_glm = mode & 4;
  4354. return !is_glm;
  4355. } break;
  4356. case GGML_OP_NONE:
  4357. case GGML_OP_RESHAPE:
  4358. case GGML_OP_VIEW:
  4359. case GGML_OP_PERMUTE:
  4360. case GGML_OP_TRANSPOSE:
  4361. case GGML_OP_NORM:
  4362. case GGML_OP_ADD:
  4363. case GGML_OP_MUL:
  4364. case GGML_OP_RMS_NORM:
  4365. case GGML_OP_SCALE:
  4366. case GGML_OP_SQR:
  4367. case GGML_OP_CLAMP:
  4368. case GGML_OP_CONT:
  4369. case GGML_OP_DIAG_MASK_INF:
  4370. case GGML_OP_SOFT_MAX:
  4371. return true;
  4372. default:
  4373. return false;
  4374. }
  4375. UNUSED(backend);
  4376. }
  4377. // TODO: enable async and synchronize
  4378. static ggml_backend_i ggml_backend_vk_interface = {
  4379. /* .get_name = */ ggml_backend_vk_name,
  4380. /* .free = */ ggml_backend_vk_free,
  4381. /* .get_default_buffer_type = */ ggml_backend_vk_get_default_buffer_type,
  4382. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  4383. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  4384. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  4385. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  4386. /* .graph_plan_create = */ NULL,
  4387. /* .graph_plan_free = */ NULL,
  4388. /* .graph_plan_compute = */ NULL,
  4389. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  4390. /* .supports_op = */ ggml_backend_vk_supports_op,
  4391. };
  4392. GGML_CALL ggml_backend_t ggml_backend_vk_init(size_t idx) {
  4393. if (vk_instance.initialized[idx]) {
  4394. return vk_instance.backends[idx];
  4395. }
  4396. #ifdef GGML_VULKAN_DEBUG
  4397. std::cerr << "ggml_backend_vk_init(" << idx << ")" << std::endl;
  4398. #endif
  4399. ggml_backend_vk_context * ctx = &vk_instance.contexts[idx];
  4400. ggml_vk_init(ctx, idx);
  4401. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4402. vk_instance.buffer_types[idx] = {
  4403. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4404. /* .context = */ new ggml_backend_vk_buffer_type_context{ ctx->name, ctx },
  4405. };
  4406. vk_instance.initialized[idx] = true;
  4407. ggml_backend_t vk_backend = new ggml_backend {
  4408. /* .interface = */ ggml_backend_vk_interface,
  4409. /* .context = */ &vk_instance.contexts[ctx->idx],
  4410. };
  4411. vk_instance.backends[idx] = vk_backend;
  4412. return vk_backend;
  4413. }
  4414. GGML_CALL bool ggml_backend_is_vk(ggml_backend_t backend) {
  4415. return backend && backend->iface.get_name == ggml_backend_vk_name;
  4416. }
  4417. GGML_CALL int ggml_backend_vk_get_device_count() {
  4418. return ggml_vk_get_device_count();
  4419. }
  4420. GGML_CALL void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  4421. ggml_vk_get_device_description(device, description, description_size);
  4422. }
  4423. GGML_CALL void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  4424. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  4425. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  4426. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  4427. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  4428. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  4429. *total = heap.size;
  4430. *free = heap.size;
  4431. break;
  4432. }
  4433. }
  4434. }
  4435. // backend registry
  4436. GGML_CALL static ggml_backend_t ggml_backend_reg_vk_init(const char * params, void * user_data) {
  4437. ggml_backend_t vk_backend = ggml_backend_vk_init((int) (intptr_t) user_data);
  4438. return vk_backend;
  4439. UNUSED(params);
  4440. }
  4441. extern "C" GGML_CALL int ggml_backend_vk_reg_devices();
  4442. GGML_CALL int ggml_backend_vk_reg_devices() {
  4443. for (auto idx : vk_instance.device_indices) {
  4444. char name[128];
  4445. snprintf(name, sizeof(name), "%s%ld", GGML_VK_NAME, idx);
  4446. ggml_backend_register(name, ggml_backend_reg_vk_init, ggml_backend_vk_buffer_type(idx), (void *) (intptr_t) idx);
  4447. }
  4448. return vk_instance.device_indices.size();
  4449. }
  4450. // checks
  4451. #ifdef GGML_VULKAN_CHECK_RESULTS
  4452. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  4453. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  4454. return;
  4455. }
  4456. for (int j = 0; j < level; j++) {
  4457. std::cerr << " ";
  4458. }
  4459. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << " backend=" << tensor->backend << std::endl;
  4460. done.push_back(tensor);
  4461. for (int i = 0; i < GGML_MAX_SRC; i++) {
  4462. if (tensor->src[i] != nullptr) {
  4463. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  4464. }
  4465. }
  4466. }
  4467. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  4468. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  4469. return;
  4470. }
  4471. i0 = std::max(i0, 5);
  4472. i1 = std::max(i1, 5);
  4473. i2 = std::max(i2, 0);
  4474. i3 = std::max(i3, 0);
  4475. fprintf(stderr, " ");
  4476. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4477. fprintf(stderr, "%7d ", idx1);
  4478. }
  4479. fprintf(stderr, "\n");
  4480. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  4481. fprintf(stderr, "%7d: ", idx0);
  4482. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4483. 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]) {
  4484. float val;
  4485. if (tensor->type == GGML_TYPE_F32) {
  4486. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  4487. } else if (tensor->type == GGML_TYPE_F16) {
  4488. 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]));
  4489. }
  4490. fprintf(stderr, "% 7.2f ", val);
  4491. } else {
  4492. fprintf(stderr, " ");
  4493. }
  4494. }
  4495. fprintf(stderr, "\n");
  4496. }
  4497. }
  4498. static void ggml_vk_print_tensor(ggml_backend_vk_context * ctx, const ggml_tensor * tensor, const char * name) {
  4499. void * tensor_data = tensor->data;
  4500. if (tensor->backend == GGML_BACKEND_GPU) {
  4501. const size_t tensor_size = ggml_nbytes(tensor);
  4502. tensor_data = malloc(tensor_size);
  4503. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4504. ggml_vk_buffer_read(ctx, extra->buffer_gpu, extra->offset, tensor_data, tensor_size);
  4505. }
  4506. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  4507. std::cerr << "tensor=" << tensor << " tensor->backend: " << tensor->backend << " 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;
  4508. if (tensor->src[0] != nullptr) {
  4509. 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) << " backend=" << tensor->src[0]->backend << " 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;
  4510. }
  4511. if (tensor->src[1] != nullptr) {
  4512. 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) << " backend=" << tensor->src[1]->backend << " 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;
  4513. }
  4514. std::cerr << std::endl << "Result:" << std::endl;
  4515. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  4516. std::cerr << std::endl;
  4517. std::cerr << std::endl << "Result:" << std::endl;
  4518. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 1, 0);
  4519. std::cerr << std::endl;
  4520. std::vector<const ggml_tensor *> done;
  4521. ggml_vk_print_graph_origin(tensor, done);
  4522. if (tensor->backend == GGML_BACKEND_GPU) {
  4523. free(tensor_data);
  4524. }
  4525. }
  4526. static void ggml_vk_check_tensor(const std::string& name, const ggml_tensor * tensor) {
  4527. return;
  4528. GGML_ASSERT(tensor->backend == GGML_BACKEND_CPU);
  4529. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  4530. return;
  4531. }
  4532. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  4533. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  4534. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  4535. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  4536. float val = 0.0f;
  4537. if (tensor->type == GGML_TYPE_F32) {
  4538. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  4539. } else if (tensor->type == GGML_TYPE_F16) {
  4540. val = 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]));
  4541. }
  4542. if (std::isnan(val)) {
  4543. std::cerr << "ERROR: TENSOR CHECK " << name << ": Invalid value in " << ggml_op_name(tensor->op) << " i3=" << i3 << " i2=" << i2 << " i1=" << i1 << " i0=" << i0 << " val=" << val << std::endl;
  4544. std::cerr << "tensor=" << tensor << " tensor->type=" << ggml_type_name(tensor->type) << " tensor->backend: " << tensor->backend << " 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;
  4545. std::cerr << std::endl;
  4546. ggml_vk_print_tensor_area(tensor, tensor->data, i0, i1, i2, i3);
  4547. std::cerr << std::endl;
  4548. std::vector<const ggml_tensor *> done;
  4549. ggml_vk_print_graph_origin(tensor, done);
  4550. GGML_ASSERT(false);
  4551. }
  4552. }
  4553. }
  4554. }
  4555. }
  4556. }
  4557. void * comp_result;
  4558. size_t comp_size;
  4559. size_t comp_nb[GGML_MAX_DIMS];
  4560. size_t check_counter = 0;
  4561. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor) {
  4562. if (params->ith != 0) {
  4563. return;
  4564. }
  4565. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE || tensor->op == GGML_OP_TRANSPOSE) {
  4566. return;
  4567. }
  4568. check_counter++;
  4569. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  4570. return;
  4571. }
  4572. ggml_tensor * src0 = tensor->src[0];
  4573. ggml_tensor * src1 = tensor->src[1];
  4574. struct ggml_init_params iparams = {
  4575. /*.mem_size =*/ 1024*1024*1024,
  4576. /*.mem_buffer =*/ NULL,
  4577. /*.no_alloc =*/ false,
  4578. };
  4579. struct ggml_context * ggml_ctx = ggml_init(iparams);
  4580. struct ggml_tensor * src0_clone = nullptr;
  4581. struct ggml_tensor * src1_clone = nullptr;
  4582. struct ggml_tensor * tensor_clone = nullptr;
  4583. size_t src0_size;
  4584. size_t src1_size;
  4585. void * src0_buffer;
  4586. void * src1_buffer;
  4587. if (src0 != nullptr) {
  4588. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  4589. src0_size = ggml_nbytes(src0);
  4590. src0_buffer = malloc(src0_size);
  4591. src0_clone->data = src0_buffer;
  4592. if (src0->backend == GGML_BACKEND_CPU) {
  4593. memcpy(src0_clone->data, src0->data, src0_size);
  4594. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4595. } else if (src0->backend == GGML_BACKEND_GPU) {
  4596. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src0->extra;
  4597. uint64_t offset = extra->offset;
  4598. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  4599. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  4600. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  4601. const int idx = i3*src0->ne[2] + i2;
  4602. ggml_vk_buffer_read(ctx, extra->buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  4603. }
  4604. }
  4605. src0_clone->nb[0] = src0->nb[0];
  4606. src0_clone->nb[1] = src0->nb[1];
  4607. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  4608. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  4609. }
  4610. } else {
  4611. if (offset + src0_size >= extra->buffer_gpu->size) {
  4612. src0_size = extra->buffer_gpu->size - offset;
  4613. }
  4614. ggml_vk_buffer_read(ctx, extra->buffer_gpu, offset, src0_clone->data, src0_size);
  4615. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4616. }
  4617. } else {
  4618. GGML_ASSERT(false);
  4619. }
  4620. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  4621. ggml_vk_print_tensor(ctx, src0, "src0");
  4622. }
  4623. ggml_vk_check_tensor(std::string(ggml_op_name(tensor->op)) + "->src0", src0_clone);
  4624. }
  4625. if (src1 != nullptr) {
  4626. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  4627. src1_size = ggml_nbytes(src1);
  4628. src1_buffer = malloc(src1_size);
  4629. src1_clone->data = src1_buffer;
  4630. if (src1->backend == GGML_BACKEND_CPU) {
  4631. memcpy(src1_clone->data, src1->data, src1_size);
  4632. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4633. } else if (src1->backend == GGML_BACKEND_GPU) {
  4634. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src1->extra;
  4635. uint64_t offset = extra->offset;
  4636. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  4637. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  4638. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  4639. const int idx = i3*src1->ne[2] + i2;
  4640. ggml_vk_buffer_read(ctx, extra->buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  4641. }
  4642. }
  4643. src1_clone->nb[0] = src1->nb[0];
  4644. src1_clone->nb[1] = src1->nb[1];
  4645. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  4646. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  4647. }
  4648. } else {
  4649. if (offset + src1_size >= extra->buffer_gpu->size) {
  4650. src1_size = extra->buffer_gpu->size - offset;
  4651. }
  4652. ggml_vk_buffer_read(ctx, extra->buffer_gpu, offset, src1_clone->data, src1_size);
  4653. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4654. }
  4655. } else {
  4656. GGML_ASSERT(false);
  4657. }
  4658. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  4659. ggml_vk_print_tensor(ctx, src1, "src1");
  4660. std::cerr << "TENSOR CHECK: " << ggml_op_name(src1_clone->op) << " (check " << check_counter << ")" << std::endl;
  4661. std::cerr << "src1_clone=" << tensor << " src1_clone->backend: " << src1_clone->backend << " src1_clone->type: " << ggml_type_name(src1_clone->type) << " ne0=" << src1_clone->ne[0] << " nb0=" << src1_clone->nb[0] << " ne1=" << src1_clone->ne[1] << " nb1=" << src1_clone->nb[1] << " ne2=" << src1_clone->ne[2] << " nb2=" << src1_clone->nb[2] << " ne3=" << src1_clone->ne[3] << " nb3=" << src1_clone->nb[3] << std::endl;
  4662. if (src1->src[0] != nullptr) {
  4663. std::cerr << "src1->src[0]=" << src1->src[0] << " op=" << ggml_op_name(src1->src[0]->op) << " type=" << ggml_type_name(src1->src[0]->type) << " backend=" << src1->src[0]->backend << " ne0=" << src1->src[0]->ne[0] << " nb0=" << src1->src[0]->nb[0] << " ne1=" << src1->src[0]->ne[1] << " nb1=" << src1->src[0]->nb[1] << " ne2=" << src1->src[0]->ne[2] << " nb2=" << src1->src[0]->nb[2] << " ne3=" << src1->src[0]->ne[3] << " nb3=" << src1->src[0]->nb[3] << std::endl;
  4664. }
  4665. if (src1->src[1] != nullptr) {
  4666. std::cerr << "src1->src[1]=" << src1->src[1] << " op=" << ggml_op_name(src1->src[1]->op) << " type=" << ggml_type_name(src1->src[1]->type) << " backend=" << src1->src[1]->backend << " ne0=" << src1->src[1]->ne[0] << " nb0=" << src1->src[1]->nb[0] << " ne1=" << src1->src[1]->ne[1] << " nb1=" << src1->src[1]->nb[1] << " ne2=" << src1->src[1]->ne[2] << " nb2=" << src1->src[1]->nb[2] << " ne3=" << src1->src[1]->ne[3] << " nb3=" << src1->src[1]->nb[3] << std::endl;
  4667. }
  4668. std::cerr << std::endl << "Result:" << std::endl;
  4669. ggml_vk_print_tensor_area(src1_clone, src1_clone->data, 5, 5, 0, 0);
  4670. std::cerr << std::endl;
  4671. std::cerr << std::endl << "Result:" << std::endl;
  4672. ggml_vk_print_tensor_area(src1_clone, src1_clone->data, 5, 5, 1, 0);
  4673. std::cerr << std::endl;
  4674. std::vector<const ggml_tensor *> done;
  4675. ggml_vk_print_graph_origin(src1_clone, done);
  4676. }
  4677. ggml_vk_check_tensor(std::string(ggml_op_name(tensor->op)) + "->src1", src1_clone);
  4678. }
  4679. if (tensor->op == GGML_OP_MUL_MAT) {
  4680. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  4681. } else if (tensor->op == GGML_OP_MUL) {
  4682. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  4683. } else if (tensor->op == GGML_OP_SCALE) {
  4684. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  4685. } else if (tensor->op == GGML_OP_SQR) {
  4686. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  4687. } else if (tensor->op == GGML_OP_CLAMP) {
  4688. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  4689. } else if (tensor->op == GGML_OP_ADD) {
  4690. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  4691. } else if (tensor->op == GGML_OP_NORM) {
  4692. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  4693. } else if (tensor->op == GGML_OP_RMS_NORM) {
  4694. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  4695. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  4696. if (src1 != nullptr) {
  4697. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, *(float *)tensor->op_params);
  4698. } else {
  4699. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  4700. }
  4701. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  4702. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  4703. } else if (tensor->op == GGML_OP_ROPE) {
  4704. const int n_dims = ((int32_t *) tensor->op_params)[1];
  4705. const int mode = ((int32_t *) tensor->op_params)[2];
  4706. const int n_ggml_ctx = ((int32_t *) tensor->op_params)[3];
  4707. const int n_orig_ggml_ctx = ((int32_t *) tensor->op_params)[4];
  4708. float freq_base = ((float *) tensor->op_params)[5];
  4709. float freq_scale = ((float *) tensor->op_params)[6];
  4710. float ext_factor = ((float *) tensor->op_params)[7];
  4711. float attn_factor = ((float *) tensor->op_params)[8];
  4712. float beta_fast = ((float *) tensor->op_params)[9];
  4713. float beta_slow = ((float *) tensor->op_params)[10];
  4714. tensor_clone = ggml_rope_custom(ggml_ctx, src0_clone, src1_clone, n_dims, mode, n_ggml_ctx, n_orig_ggml_ctx, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  4715. } else if (tensor->op == GGML_OP_UNARY) {
  4716. switch (ggml_get_unary_op(tensor)) {
  4717. case GGML_UNARY_OP_SILU:
  4718. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  4719. break;
  4720. case GGML_UNARY_OP_GELU:
  4721. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  4722. break;
  4723. case GGML_UNARY_OP_RELU:
  4724. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  4725. break;
  4726. default:
  4727. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  4728. GGML_ASSERT(false);
  4729. }
  4730. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  4731. if (src1 == nullptr) {
  4732. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  4733. tensor_clone->type = tensor->type;
  4734. } else {
  4735. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  4736. }
  4737. } else if (tensor->op == GGML_OP_CONT) {
  4738. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  4739. } else if (tensor->op == GGML_OP_RESHAPE) {
  4740. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  4741. } else if (tensor->op == GGML_OP_VIEW) {
  4742. 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]);
  4743. } else if (tensor->op == GGML_OP_PERMUTE) {
  4744. int32_t * params = (int32_t *)tensor->op_params;
  4745. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  4746. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  4747. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  4748. } else {
  4749. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  4750. GGML_ASSERT(false);
  4751. }
  4752. // Disable vulkan here to avoid the hooks in ggml.c
  4753. ctx->disable = true;
  4754. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  4755. ggml_build_forward_expand(cgraph, tensor_clone);
  4756. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  4757. ctx->disable = false;
  4758. ggml_vk_check_tensor(ggml_op_name(tensor->op), tensor_clone);
  4759. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  4760. ggml_vk_print_tensor(ctx, tensor_clone, "tensor_clone");
  4761. }
  4762. comp_size = ggml_nbytes(tensor_clone);
  4763. comp_result = malloc(comp_size);
  4764. memcpy(comp_result, tensor_clone->data, comp_size);
  4765. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4766. if (src0 != nullptr) {
  4767. free(src0_buffer);
  4768. }
  4769. if (src1 != nullptr) {
  4770. free(src1_buffer);
  4771. }
  4772. ggml_free(ggml_ctx);
  4773. }
  4774. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor) {
  4775. if (params->ith != 0) {
  4776. return;
  4777. }
  4778. if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE || tensor->op == GGML_OP_TRANSPOSE) {
  4779. return;
  4780. }
  4781. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  4782. return;
  4783. }
  4784. ggml_tensor * src0 = tensor->src[0];
  4785. ggml_tensor * src1 = tensor->src[1];
  4786. void * tensor_data = tensor->data;
  4787. if (tensor->backend == GGML_BACKEND_GPU) {
  4788. size_t tensor_size = ggml_nbytes(tensor);
  4789. tensor_data = malloc(tensor_size);
  4790. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4791. if (extra->offset + tensor_size >= extra->buffer_gpu->size) {
  4792. tensor_size = extra->buffer_gpu->size - (extra->offset);
  4793. }
  4794. ggml_vk_buffer_read(ctx, extra->buffer_gpu, extra->offset, tensor_data, tensor_size);
  4795. }
  4796. float first_error_result = -1.0f;
  4797. float first_error_correct = -1.0f;
  4798. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  4799. double avg_err = 0.0;
  4800. size_t counter = 0;
  4801. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  4802. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  4803. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  4804. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  4805. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  4806. float correct = 0.0f;
  4807. float result = 0.0f;
  4808. if (buffer_size_fit) {
  4809. if (tensor->type == GGML_TYPE_F32) {
  4810. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  4811. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  4812. } else if (tensor->type == GGML_TYPE_F16) {
  4813. 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]));
  4814. 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]));
  4815. } else {
  4816. std::cerr << "comp_size=" << comp_size << " but required is " << (i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]) << std::endl;
  4817. }
  4818. } else {
  4819. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  4820. GGML_ASSERT(false);
  4821. }
  4822. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  4823. 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;
  4824. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  4825. if (src0 != nullptr) {
  4826. std::cerr << "src0=" << src0 << " src0->name=" << src0->name << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  4827. }
  4828. if (src1 != nullptr) {
  4829. std::cerr << "src1=" << src1 << " src1->name=" << src1->name << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  4830. }
  4831. 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;
  4832. std::cerr << std::endl << "Result:" << std::endl;
  4833. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  4834. std::cerr << std::endl << "Correct:" << std::endl;
  4835. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  4836. std::cerr << std::endl;
  4837. std::vector<const ggml_tensor *> done;
  4838. ggml_vk_print_graph_origin(tensor, done);
  4839. GGML_ASSERT(false);
  4840. }
  4841. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  4842. first_error[0] = i0;
  4843. first_error[1] = i1;
  4844. first_error[2] = i2;
  4845. first_error[3] = i3;
  4846. first_error_result = result;
  4847. first_error_correct = correct;
  4848. }
  4849. // Special case, value is infinite, avoid NaN result in avg_err
  4850. // NaN also appears in results, if both are nan error is 0
  4851. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  4852. avg_err += std::fabs(correct - result);
  4853. }
  4854. counter++;
  4855. }
  4856. }
  4857. }
  4858. }
  4859. avg_err /= counter;
  4860. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  4861. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  4862. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  4863. if (src0 != nullptr) {
  4864. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  4865. }
  4866. if (src1 != nullptr) {
  4867. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  4868. }
  4869. 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;
  4870. std::cerr << std::endl << "Result:" << std::endl;
  4871. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  4872. std::cerr << std::endl << "Correct:" << std::endl;
  4873. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  4874. std::cerr << std::endl;
  4875. std::cerr << std::endl << "Result:" << std::endl;
  4876. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 1, 0);
  4877. std::cerr << std::endl << "Correct:" << std::endl;
  4878. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 1, 0);
  4879. std::cerr << std::endl;
  4880. std::vector<const ggml_tensor *> done;
  4881. ggml_vk_print_graph_origin(tensor, done);
  4882. }
  4883. if (avg_err > 0.05 || std::isnan(avg_err)) {
  4884. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  4885. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  4886. if (src0 != nullptr) {
  4887. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  4888. }
  4889. if (src1 != nullptr) {
  4890. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  4891. }
  4892. 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;
  4893. std::cerr << std::endl << "Result:" << std::endl;
  4894. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  4895. std::cerr << std::endl << "Correct:" << std::endl;
  4896. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  4897. std::cerr << std::endl;
  4898. std::vector<const ggml_tensor *> done;
  4899. ggml_vk_print_graph_origin(tensor, done);
  4900. GGML_ASSERT(false);
  4901. } else {
  4902. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " backend=" << tensor->backend << " avg_err=" << avg_err << std::endl;
  4903. }
  4904. free(comp_result);
  4905. comp_result = nullptr;
  4906. comp_size = 0;
  4907. if (tensor->backend == GGML_BACKEND_GPU) {
  4908. free(tensor_data);
  4909. }
  4910. }
  4911. void ggml_vk_check_results_1_cpu_assist(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  4912. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4913. ggml_vk_check_results_0(ctx, params, tensor);
  4914. }
  4915. #endif