ggml-vulkan.cpp 249 KB

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