ggml-vulkan.cpp 255 KB

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