ggml.c 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758
  1. /**
  2. * llama.cpp - commit 46e3556e01b824e52395fb050b29804b6cff2a7c - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #define _CRT_SECURE_NO_DEPRECATE // Disables "unsafe" warnings on Windows
  27. #define _USE_MATH_DEFINES // For M_PI on MSVC
  28. #include "ggml-backend.h"
  29. #include "ggml-impl.h"
  30. #include "ggml-threading.h"
  31. #include "ggml.h"
  32. // FIXME: required here for quantization functions
  33. #include "ggml-quants.h"
  34. #ifdef GGML_USE_CPU_HBM
  35. #include <hbwmalloc.h>
  36. #endif
  37. #if defined(_MSC_VER) || defined(__MINGW32__)
  38. #include <malloc.h> // using malloc.h with MSC/MINGW
  39. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  40. #include <alloca.h>
  41. #endif
  42. #include <assert.h>
  43. #include <errno.h>
  44. #include <time.h>
  45. #include <math.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <stdint.h>
  49. #include <inttypes.h>
  50. #include <stdio.h>
  51. #include <float.h>
  52. #include <limits.h>
  53. #include <stdarg.h>
  54. #include <signal.h>
  55. #if defined(__gnu_linux__)
  56. #include <syscall.h>
  57. #endif
  58. #if defined(__APPLE__)
  59. #include <unistd.h>
  60. #include <mach/mach.h>
  61. #include <TargetConditionals.h>
  62. #endif
  63. #if defined(_WIN32)
  64. #define WIN32_LEAN_AND_MEAN
  65. #ifndef NOMINMAX
  66. #define NOMINMAX
  67. #endif
  68. #include <windows.h>
  69. #endif
  70. #define UNUSED GGML_UNUSED
  71. #if defined(_MSC_VER)
  72. #define m512bh(p) p
  73. #define m512i(p) p
  74. #else
  75. #define m512bh(p) (__m512bh)(p)
  76. #define m512i(p) (__m512i)(p)
  77. #endif
  78. // precomputed f32 table for f16 (256 KB) (ggml-impl.h)
  79. float ggml_table_f32_f16[1 << 16];
  80. #if (defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && \
  81. (!defined(TARGET_OS_TV) && !defined(TARGET_OS_WATCH))
  82. #include <unistd.h>
  83. #include <sys/types.h>
  84. #include <sys/stat.h>
  85. #include <sys/wait.h>
  86. #if defined(__ANDROID__)
  87. #include <unwind.h>
  88. #include <dlfcn.h>
  89. #include <stdio.h>
  90. struct backtrace_state {
  91. void ** current;
  92. void ** end;
  93. };
  94. static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, void* arg) {
  95. struct backtrace_state * state = (struct backtrace_state *)arg;
  96. uintptr_t pc = _Unwind_GetIP(context);
  97. if (pc) {
  98. if (state->current == state->end) {
  99. return _URC_END_OF_STACK;
  100. } else {
  101. *state->current++ = (void*)pc;
  102. }
  103. }
  104. return _URC_NO_REASON;
  105. }
  106. static void ggml_print_backtrace_symbols(void) {
  107. const int max = 100;
  108. void* buffer[max];
  109. struct backtrace_state state = {buffer, buffer + max};
  110. _Unwind_Backtrace(unwind_callback, &state);
  111. int count = state.current - buffer;
  112. for (int idx = 0; idx < count; ++idx) {
  113. const void * addr = buffer[idx];
  114. const char * symbol = "";
  115. Dl_info info;
  116. if (dladdr(addr, &info) && info.dli_sname) {
  117. symbol = info.dli_sname;
  118. }
  119. fprintf(stderr, "%d: %p %s\n", idx, addr, symbol);
  120. }
  121. }
  122. #elif defined(__linux__) && defined(__GLIBC__)
  123. #include <execinfo.h>
  124. static void ggml_print_backtrace_symbols(void) {
  125. void * trace[100];
  126. int nptrs = backtrace(trace, sizeof(trace)/sizeof(trace[0]));
  127. backtrace_symbols_fd(trace, nptrs, STDERR_FILENO);
  128. }
  129. #else
  130. static void ggml_print_backtrace_symbols(void) {
  131. // platform not supported
  132. }
  133. #endif
  134. static void ggml_print_backtrace(void) {
  135. char attach[32];
  136. snprintf(attach, sizeof(attach), "attach %d", getpid());
  137. int pid = fork();
  138. if (pid == 0) {
  139. // try gdb
  140. execlp("gdb", "gdb", "--batch",
  141. "-ex", "set style enabled on",
  142. "-ex", attach,
  143. "-ex", "bt -frame-info source-and-location",
  144. "-ex", "detach",
  145. "-ex", "quit",
  146. (char *) NULL);
  147. // try lldb
  148. execlp("lldb", "lldb", "--batch",
  149. "-o", "bt",
  150. "-o", "quit",
  151. "-p", attach,
  152. (char *) NULL);
  153. exit(EXIT_FAILURE);
  154. } else {
  155. int wstatus;
  156. waitpid(pid, &wstatus, 0);
  157. if (WIFEXITED(wstatus)) {
  158. if (WEXITSTATUS(wstatus) == EXIT_FAILURE) {
  159. // gdb failed, fallback to backtrace_symbols
  160. ggml_print_backtrace_symbols();
  161. }
  162. }
  163. }
  164. }
  165. #else
  166. static void ggml_print_backtrace(void) {
  167. // platform not supported
  168. }
  169. #endif
  170. void ggml_abort(const char * file, int line, const char * fmt, ...) {
  171. fflush(stdout);
  172. fprintf(stderr, "%s:%d: ", file, line);
  173. va_list args;
  174. va_start(args, fmt);
  175. vfprintf(stderr, fmt, args);
  176. va_end(args);
  177. fprintf(stderr, "\n");
  178. ggml_print_backtrace();
  179. abort();
  180. }
  181. //
  182. // logging
  183. //
  184. struct ggml_logger_state {
  185. ggml_log_callback log_callback;
  186. void * log_callback_user_data;
  187. };
  188. static struct ggml_logger_state g_logger_state = {ggml_log_callback_default, NULL};
  189. static void ggml_log_internal_v(enum ggml_log_level level, const char * format, va_list args) {
  190. if (format == NULL) {
  191. return;
  192. }
  193. va_list args_copy;
  194. va_copy(args_copy, args);
  195. char buffer[128];
  196. int len = vsnprintf(buffer, 128, format, args);
  197. if (len < 128) {
  198. g_logger_state.log_callback(level, buffer, g_logger_state.log_callback_user_data);
  199. } else {
  200. char * buffer2 = (char *) calloc(len + 1, sizeof(char));
  201. vsnprintf(buffer2, len + 1, format, args_copy);
  202. buffer2[len] = 0;
  203. g_logger_state.log_callback(level, buffer2, g_logger_state.log_callback_user_data);
  204. free(buffer2);
  205. }
  206. va_end(args_copy);
  207. }
  208. void ggml_log_internal(enum ggml_log_level level, const char * format, ...) {
  209. va_list args;
  210. va_start(args, format);
  211. ggml_log_internal_v(level, format, args);
  212. va_end(args);
  213. }
  214. void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data) {
  215. (void) level;
  216. (void) user_data;
  217. fputs(text, stderr);
  218. fflush(stderr);
  219. }
  220. //
  221. // end of logging block
  222. //
  223. #ifdef GGML_USE_ACCELERATE
  224. // uncomment to use vDSP for soft max computation
  225. // note: not sure if it is actually faster
  226. //#define GGML_SOFT_MAX_ACCELERATE
  227. #endif
  228. void * ggml_aligned_malloc(size_t size) {
  229. const int alignment = 64;
  230. #if defined(_MSC_VER) || defined(__MINGW32__)
  231. return _aligned_malloc(size, alignment);
  232. #else
  233. if (size == 0) {
  234. GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_aligned_malloc!\n");
  235. return NULL;
  236. }
  237. void * aligned_memory = NULL;
  238. #ifdef GGML_USE_CPU_HBM
  239. int result = hbw_posix_memalign(&aligned_memory, alignment, size);
  240. #elif TARGET_OS_OSX
  241. GGML_UNUSED(alignment);
  242. kern_return_t alloc_status = vm_allocate((vm_map_t) mach_task_self(), (vm_address_t *) &aligned_memory, size, VM_FLAGS_ANYWHERE);
  243. int result = EFAULT;
  244. switch (alloc_status) {
  245. case KERN_SUCCESS:
  246. result = 0;
  247. break;
  248. case KERN_INVALID_ADDRESS:
  249. result = EINVAL;
  250. break;
  251. case KERN_NO_SPACE:
  252. result = ENOMEM;
  253. break;
  254. default:
  255. result = EFAULT;
  256. break;
  257. }
  258. #else
  259. int result = posix_memalign(&aligned_memory, alignment, size);
  260. #endif
  261. if (result != 0) {
  262. // Handle allocation failure
  263. const char *error_desc = "unknown allocation error";
  264. switch (result) {
  265. case EINVAL:
  266. error_desc = "invalid alignment value";
  267. break;
  268. case ENOMEM:
  269. error_desc = "insufficient memory";
  270. break;
  271. }
  272. GGML_LOG_ERROR("%s: %s (attempted to allocate %6.2f MB)\n", __func__, error_desc, size/(1024.0*1024.0));
  273. return NULL;
  274. }
  275. return aligned_memory;
  276. #endif
  277. }
  278. void ggml_aligned_free(void * ptr, size_t size) {
  279. GGML_UNUSED(size);
  280. #if defined(_MSC_VER) || defined(__MINGW32__)
  281. _aligned_free(ptr);
  282. #elif GGML_USE_CPU_HBM
  283. if (ptr != NULL) {
  284. hbw_free(ptr);
  285. }
  286. #elif TARGET_OS_OSX
  287. if (ptr != NULL) {
  288. vm_deallocate((vm_map_t)mach_task_self(), (vm_address_t)ptr, size);
  289. }
  290. #else
  291. free(ptr);
  292. #endif
  293. }
  294. inline static void * ggml_malloc(size_t size) {
  295. if (size == 0) {
  296. GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_malloc!\n");
  297. return NULL;
  298. }
  299. void * result = malloc(size);
  300. if (result == NULL) {
  301. GGML_LOG_ERROR("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  302. GGML_ABORT("fatal error");
  303. }
  304. return result;
  305. }
  306. // calloc
  307. inline static void * ggml_calloc(size_t num, size_t size) {
  308. if (num == 0 || size == 0) {
  309. GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_calloc!\n");
  310. return NULL;
  311. }
  312. void * result = calloc(num, size);
  313. if (result == NULL) {
  314. GGML_LOG_ERROR("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
  315. GGML_ABORT("fatal error");
  316. }
  317. return result;
  318. }
  319. #define GGML_MALLOC(size) ggml_malloc(size)
  320. #define GGML_CALLOC(num, size) ggml_calloc(num, size)
  321. #define GGML_FREE(ptr) free(ptr)
  322. const char * ggml_status_to_string(enum ggml_status status) {
  323. switch (status) {
  324. case GGML_STATUS_ALLOC_FAILED: return "GGML status: error (failed to allocate memory)";
  325. case GGML_STATUS_FAILED: return "GGML status: error (operation failed)";
  326. case GGML_STATUS_SUCCESS: return "GGML status: success";
  327. case GGML_STATUS_ABORTED: return "GGML status: warning (operation aborted)";
  328. }
  329. return "GGML status: unknown";
  330. }
  331. float ggml_fp16_to_fp32(ggml_fp16_t x) {
  332. #define ggml_fp16_to_fp32 do_not_use__ggml_fp16_to_fp32__in_ggml
  333. return GGML_FP16_TO_FP32(x);
  334. }
  335. ggml_fp16_t ggml_fp32_to_fp16(float x) {
  336. #define ggml_fp32_to_fp16 do_not_use__ggml_fp32_to_fp16__in_ggml
  337. return GGML_FP32_TO_FP16(x);
  338. }
  339. float ggml_bf16_to_fp32(ggml_bf16_t x) {
  340. #define ggml_bf16_to_fp32 do_not_use__ggml_bf16_to_fp32__in_ggml
  341. return GGML_BF16_TO_FP32(x); // it just left shifts
  342. }
  343. ggml_bf16_t ggml_fp32_to_bf16(float x) {
  344. #define ggml_fp32_to_bf16 do_not_use__ggml_fp32_to_bf16__in_ggml
  345. return GGML_FP32_TO_BF16(x);
  346. }
  347. void ggml_fp16_to_fp32_row(const ggml_fp16_t * x, float * y, int64_t n) {
  348. for (int64_t i = 0; i < n; i++) {
  349. y[i] = GGML_FP16_TO_FP32(x[i]);
  350. }
  351. }
  352. // FIXME: these functions must detect the instruction set at runtime, since they are part of the core ggml library
  353. // currently, the ggml_cpu_has_* functions are entirely compile-time
  354. void ggml_fp32_to_fp16_row(const float * x, ggml_fp16_t * y, int64_t n) {
  355. int64_t i = 0;
  356. #if defined(__F16C__)
  357. //if (ggml_cpu_has_f16c()) {
  358. for (; i + 7 < n; i += 8) {
  359. __m256 x_vec = _mm256_loadu_ps(x + i);
  360. __m128i y_vec = _mm256_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  361. _mm_storeu_si128((__m128i *)(y + i), y_vec);
  362. }
  363. for(; i + 3 < n; i += 4) {
  364. __m128 x_vec = _mm_loadu_ps(x + i);
  365. __m128i y_vec = _mm_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT);
  366. _mm_storel_epi64((__m128i *)(y + i), y_vec);
  367. }
  368. //}
  369. #endif
  370. for (; i < n; i++) {
  371. y[i] = GGML_FP32_TO_FP16(x[i]);
  372. }
  373. }
  374. void ggml_bf16_to_fp32_row(const ggml_bf16_t * x, float * y, int64_t n) {
  375. int64_t i = 0;
  376. #if defined(__AVX512F__)
  377. //if (ggml_cpu_has_avx512()) {
  378. for (; i + 16 <= n; i += 16) {
  379. _mm512_storeu_ps(y + i,
  380. _mm512_castsi512_ps(
  381. _mm512_slli_epi32(
  382. _mm512_cvtepu16_epi32(
  383. _mm256_loadu_si256(
  384. (const __m256i *)(x + i))),
  385. 16)));
  386. }
  387. //}
  388. #endif
  389. #if defined(__AVX2__)
  390. //if (ggml_cpu_has_avx2()) {
  391. for (; i + 8 <= n; i += 8) {
  392. _mm256_storeu_ps(y + i,
  393. _mm256_castsi256_ps(
  394. _mm256_slli_epi32(
  395. _mm256_cvtepu16_epi32(
  396. _mm_loadu_si128(
  397. (const __m128i *)(x + i))),
  398. 16)));
  399. }
  400. //}
  401. #endif
  402. for (; i < n; i++) {
  403. y[i] = GGML_BF16_TO_FP32(x[i]);
  404. }
  405. }
  406. void ggml_fp32_to_bf16_row_ref(const float * x, ggml_bf16_t * y, int64_t n) {
  407. for (int i = 0; i < n; i++) {
  408. y[i] = ggml_compute_fp32_to_bf16(x[i]);
  409. }
  410. }
  411. void ggml_fp32_to_bf16_row(const float * x, ggml_bf16_t * y, int64_t n) {
  412. int i = 0;
  413. #if defined(__AVX512BF16__)
  414. // subnormals are flushed to zero on this platform
  415. for (; i + 32 <= n; i += 32) {
  416. _mm512_storeu_si512(
  417. (__m512i *)(y + i),
  418. m512i(_mm512_cvtne2ps_pbh(_mm512_loadu_ps(x + i + 16),
  419. _mm512_loadu_ps(x + i))));
  420. }
  421. #endif
  422. for (; i < n; i++) {
  423. y[i] = GGML_FP32_TO_BF16(x[i]);
  424. }
  425. }
  426. bool ggml_guid_matches(ggml_guid_t guid_a, ggml_guid_t guid_b) {
  427. return memcmp(guid_a, guid_b, sizeof(ggml_guid)) == 0;
  428. }
  429. //
  430. // timing
  431. //
  432. #if defined(_MSC_VER) || defined(__MINGW32__)
  433. static int64_t timer_freq, timer_start;
  434. void ggml_time_init(void) {
  435. LARGE_INTEGER t;
  436. QueryPerformanceFrequency(&t);
  437. timer_freq = t.QuadPart;
  438. // The multiplication by 1000 or 1000000 below can cause an overflow if timer_freq
  439. // and the uptime is high enough.
  440. // We subtract the program start time to reduce the likelihood of that happening.
  441. QueryPerformanceCounter(&t);
  442. timer_start = t.QuadPart;
  443. }
  444. int64_t ggml_time_ms(void) {
  445. LARGE_INTEGER t;
  446. QueryPerformanceCounter(&t);
  447. return ((t.QuadPart-timer_start) * 1000) / timer_freq;
  448. }
  449. int64_t ggml_time_us(void) {
  450. LARGE_INTEGER t;
  451. QueryPerformanceCounter(&t);
  452. return ((t.QuadPart-timer_start) * 1000000) / timer_freq;
  453. }
  454. #else
  455. void ggml_time_init(void) {}
  456. int64_t ggml_time_ms(void) {
  457. struct timespec ts;
  458. clock_gettime(CLOCK_MONOTONIC, &ts);
  459. return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
  460. }
  461. int64_t ggml_time_us(void) {
  462. struct timespec ts;
  463. clock_gettime(CLOCK_MONOTONIC, &ts);
  464. return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
  465. }
  466. #endif
  467. int64_t ggml_cycles(void) {
  468. return clock();
  469. }
  470. int64_t ggml_cycles_per_ms(void) {
  471. return CLOCKS_PER_SEC/1000;
  472. }
  473. //
  474. // cross-platform UTF-8 file paths
  475. //
  476. #ifdef _WIN32
  477. static wchar_t * ggml_mbstowcs(const char * mbs) {
  478. int wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, NULL, 0);
  479. if (!wlen) {
  480. errno = EINVAL;
  481. return NULL;
  482. }
  483. wchar_t * wbuf = GGML_MALLOC(wlen * sizeof(wchar_t));
  484. wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, wbuf, wlen);
  485. if (!wlen) {
  486. GGML_FREE(wbuf);
  487. errno = EINVAL;
  488. return NULL;
  489. }
  490. return wbuf;
  491. }
  492. #endif
  493. FILE * ggml_fopen(const char * fname, const char * mode) {
  494. #ifdef _WIN32
  495. FILE * file = NULL;
  496. // convert fname (UTF-8)
  497. wchar_t * wfname = ggml_mbstowcs(fname);
  498. if (wfname) {
  499. // convert mode (ANSI)
  500. wchar_t * wmode = GGML_MALLOC((strlen(mode) + 1) * sizeof(wchar_t));
  501. wchar_t * wmode_p = wmode;
  502. do {
  503. *wmode_p++ = (wchar_t)*mode;
  504. } while (*mode++);
  505. // open file
  506. file = _wfopen(wfname, wmode);
  507. GGML_FREE(wfname);
  508. GGML_FREE(wmode);
  509. }
  510. return file;
  511. #else
  512. return fopen(fname, mode);
  513. #endif
  514. }
  515. static void ggml_vec_dot_f32(int n, float * restrict s, size_t bs, const float * restrict x, size_t bx, const float * restrict y, size_t by, int nrc);
  516. static void ggml_vec_dot_f16(int n, float * restrict s, size_t bs, ggml_fp16_t * restrict x, size_t bx, ggml_fp16_t * restrict y, size_t by, int nrc);
  517. static void ggml_vec_dot_bf16(int n, float * restrict s, size_t bs, ggml_bf16_t * restrict x, size_t bx, ggml_bf16_t * restrict y, size_t by, int nrc);
  518. static const struct ggml_type_traits type_traits[GGML_TYPE_COUNT] = {
  519. [GGML_TYPE_I8] = {
  520. .type_name = "i8",
  521. .blck_size = 1,
  522. .type_size = sizeof(int8_t),
  523. .is_quantized = false,
  524. },
  525. [GGML_TYPE_I16] = {
  526. .type_name = "i16",
  527. .blck_size = 1,
  528. .type_size = sizeof(int16_t),
  529. .is_quantized = false,
  530. },
  531. [GGML_TYPE_I32] = {
  532. .type_name = "i32",
  533. .blck_size = 1,
  534. .type_size = sizeof(int32_t),
  535. .is_quantized = false,
  536. },
  537. [GGML_TYPE_I64] = {
  538. .type_name = "i64",
  539. .blck_size = 1,
  540. .type_size = sizeof(int64_t),
  541. .is_quantized = false,
  542. },
  543. [GGML_TYPE_F64] = {
  544. .type_name = "f64",
  545. .blck_size = 1,
  546. .type_size = sizeof(double),
  547. .is_quantized = false,
  548. },
  549. [GGML_TYPE_F32] = {
  550. .type_name = "f32",
  551. .blck_size = 1,
  552. .type_size = sizeof(float),
  553. .is_quantized = false,
  554. },
  555. [GGML_TYPE_F16] = {
  556. .type_name = "f16",
  557. .blck_size = 1,
  558. .type_size = sizeof(ggml_fp16_t),
  559. .is_quantized = false,
  560. .to_float = (ggml_to_float_t) ggml_fp16_to_fp32_row,
  561. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  562. },
  563. [GGML_TYPE_Q4_0] = {
  564. .type_name = "q4_0",
  565. .blck_size = QK4_0,
  566. .type_size = sizeof(block_q4_0),
  567. .is_quantized = true,
  568. .to_float = (ggml_to_float_t) dequantize_row_q4_0,
  569. .from_float_ref = (ggml_from_float_t) quantize_row_q4_0_ref,
  570. },
  571. [GGML_TYPE_Q4_1] = {
  572. .type_name = "q4_1",
  573. .blck_size = QK4_1,
  574. .type_size = sizeof(block_q4_1),
  575. .is_quantized = true,
  576. .to_float = (ggml_to_float_t) dequantize_row_q4_1,
  577. .from_float_ref = (ggml_from_float_t) quantize_row_q4_1_ref,
  578. },
  579. [4] = { // GGML_TYPE_Q4_2
  580. .type_name = "DEPRECATED",
  581. .blck_size = 0,
  582. .type_size = 0,
  583. .is_quantized = false,
  584. },
  585. [5] = { // GGML_TYPE_Q4_3
  586. .type_name = "DEPRECATED",
  587. .blck_size = 0,
  588. .type_size = 0,
  589. .is_quantized = false,
  590. },
  591. [GGML_TYPE_Q5_0] = {
  592. .type_name = "q5_0",
  593. .blck_size = QK5_0,
  594. .type_size = sizeof(block_q5_0),
  595. .is_quantized = true,
  596. .to_float = (ggml_to_float_t) dequantize_row_q5_0,
  597. .from_float_ref = (ggml_from_float_t) quantize_row_q5_0_ref,
  598. },
  599. [GGML_TYPE_Q5_1] = {
  600. .type_name = "q5_1",
  601. .blck_size = QK5_1,
  602. .type_size = sizeof(block_q5_1),
  603. .is_quantized = true,
  604. .to_float = (ggml_to_float_t) dequantize_row_q5_1,
  605. .from_float_ref = (ggml_from_float_t) quantize_row_q5_1_ref,
  606. },
  607. [GGML_TYPE_Q8_0] = {
  608. .type_name = "q8_0",
  609. .blck_size = QK8_0,
  610. .type_size = sizeof(block_q8_0),
  611. .is_quantized = true,
  612. .to_float = (ggml_to_float_t) dequantize_row_q8_0,
  613. .from_float_ref = (ggml_from_float_t) quantize_row_q8_0_ref,
  614. },
  615. [GGML_TYPE_Q8_1] = {
  616. .type_name = "q8_1",
  617. .blck_size = QK8_1,
  618. .type_size = sizeof(block_q8_1),
  619. .is_quantized = true,
  620. .from_float_ref = (ggml_from_float_t) quantize_row_q8_1_ref,
  621. },
  622. [GGML_TYPE_Q2_K] = {
  623. .type_name = "q2_K",
  624. .blck_size = QK_K,
  625. .type_size = sizeof(block_q2_K),
  626. .is_quantized = true,
  627. .to_float = (ggml_to_float_t) dequantize_row_q2_K,
  628. .from_float_ref = (ggml_from_float_t) quantize_row_q2_K_ref,
  629. },
  630. [GGML_TYPE_Q3_K] = {
  631. .type_name = "q3_K",
  632. .blck_size = QK_K,
  633. .type_size = sizeof(block_q3_K),
  634. .is_quantized = true,
  635. .to_float = (ggml_to_float_t) dequantize_row_q3_K,
  636. .from_float_ref = (ggml_from_float_t) quantize_row_q3_K_ref,
  637. },
  638. [GGML_TYPE_Q4_K] = {
  639. .type_name = "q4_K",
  640. .blck_size = QK_K,
  641. .type_size = sizeof(block_q4_K),
  642. .is_quantized = true,
  643. .to_float = (ggml_to_float_t) dequantize_row_q4_K,
  644. .from_float_ref = (ggml_from_float_t) quantize_row_q4_K_ref,
  645. },
  646. [GGML_TYPE_Q5_K] = {
  647. .type_name = "q5_K",
  648. .blck_size = QK_K,
  649. .type_size = sizeof(block_q5_K),
  650. .is_quantized = true,
  651. .to_float = (ggml_to_float_t) dequantize_row_q5_K,
  652. .from_float_ref = (ggml_from_float_t) quantize_row_q5_K_ref,
  653. },
  654. [GGML_TYPE_Q6_K] = {
  655. .type_name = "q6_K",
  656. .blck_size = QK_K,
  657. .type_size = sizeof(block_q6_K),
  658. .is_quantized = true,
  659. .to_float = (ggml_to_float_t) dequantize_row_q6_K,
  660. .from_float_ref = (ggml_from_float_t) quantize_row_q6_K_ref,
  661. },
  662. [GGML_TYPE_IQ2_XXS] = {
  663. .type_name = "iq2_xxs",
  664. .blck_size = QK_K,
  665. .type_size = sizeof(block_iq2_xxs),
  666. .is_quantized = true,
  667. .to_float = (ggml_to_float_t) dequantize_row_iq2_xxs,
  668. .from_float_ref = NULL,
  669. },
  670. [GGML_TYPE_IQ2_XS] = {
  671. .type_name = "iq2_xs",
  672. .blck_size = QK_K,
  673. .type_size = sizeof(block_iq2_xs),
  674. .is_quantized = true,
  675. .to_float = (ggml_to_float_t) dequantize_row_iq2_xs,
  676. .from_float_ref = NULL,
  677. },
  678. [GGML_TYPE_IQ3_XXS] = {
  679. .type_name = "iq3_xxs",
  680. .blck_size = QK_K,
  681. .type_size = sizeof(block_iq3_xxs),
  682. .is_quantized = true,
  683. .to_float = (ggml_to_float_t) dequantize_row_iq3_xxs,
  684. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_xxs_ref,
  685. },
  686. [GGML_TYPE_IQ3_S] = {
  687. .type_name = "iq3_s",
  688. .blck_size = QK_K,
  689. .type_size = sizeof(block_iq3_s),
  690. .is_quantized = true,
  691. .to_float = (ggml_to_float_t) dequantize_row_iq3_s,
  692. .from_float_ref = (ggml_from_float_t)quantize_row_iq3_s_ref,
  693. },
  694. [GGML_TYPE_IQ2_S] = {
  695. .type_name = "iq2_s",
  696. .blck_size = QK_K,
  697. .type_size = sizeof(block_iq2_s),
  698. .is_quantized = true,
  699. .to_float = (ggml_to_float_t) dequantize_row_iq2_s,
  700. .from_float_ref = (ggml_from_float_t)quantize_row_iq2_s_ref,
  701. },
  702. [GGML_TYPE_IQ1_S] = {
  703. .type_name = "iq1_s",
  704. .blck_size = QK_K,
  705. .type_size = sizeof(block_iq1_s),
  706. .is_quantized = true,
  707. .to_float = (ggml_to_float_t) dequantize_row_iq1_s,
  708. .from_float_ref = NULL,
  709. },
  710. [GGML_TYPE_IQ1_M] = {
  711. .type_name = "iq1_m",
  712. .blck_size = QK_K,
  713. .type_size = sizeof(block_iq1_m),
  714. .is_quantized = true,
  715. .to_float = (ggml_to_float_t) dequantize_row_iq1_m,
  716. .from_float_ref = NULL,
  717. },
  718. [GGML_TYPE_IQ4_NL] = {
  719. .type_name = "iq4_nl",
  720. .blck_size = QK4_NL,
  721. .type_size = sizeof(block_iq4_nl),
  722. .is_quantized = true,
  723. .to_float = (ggml_to_float_t) dequantize_row_iq4_nl,
  724. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_nl_ref,
  725. },
  726. [GGML_TYPE_IQ4_XS] = {
  727. .type_name = "iq4_xs",
  728. .blck_size = QK_K,
  729. .type_size = sizeof(block_iq4_xs),
  730. .is_quantized = true,
  731. .to_float = (ggml_to_float_t) dequantize_row_iq4_xs,
  732. .from_float_ref = (ggml_from_float_t)quantize_row_iq4_xs_ref,
  733. },
  734. [GGML_TYPE_Q8_K] = {
  735. .type_name = "q8_K",
  736. .blck_size = QK_K,
  737. .type_size = sizeof(block_q8_K),
  738. .is_quantized = true,
  739. },
  740. [GGML_TYPE_BF16] = {
  741. .type_name = "bf16",
  742. .blck_size = 1,
  743. .type_size = sizeof(ggml_bf16_t),
  744. .is_quantized = false,
  745. .to_float = (ggml_to_float_t) ggml_bf16_to_fp32_row,
  746. .from_float_ref = (ggml_from_float_t) ggml_fp32_to_bf16_row_ref,
  747. },
  748. [31] = { // GGML_TYPE_Q4_0_4_4
  749. .type_name = "TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking",
  750. .blck_size = 0,
  751. .type_size = 0,
  752. .is_quantized = false,
  753. },
  754. [32] = { // GGML_TYPE_Q4_0_4_8
  755. .type_name = "TYPE_Q4_0_4_8 REMOVED, use Q4_0 with runtime repacking",
  756. .blck_size = 0,
  757. .type_size = 0,
  758. .is_quantized = false,
  759. },
  760. [33] = { // GGML_TYPE_Q4_0_8_8
  761. .type_name = "TYPE_Q4_0_8_8 REMOVED, use Q4_0 with runtime repacking",
  762. .blck_size = 0,
  763. .type_size = 0,
  764. .is_quantized = false,
  765. },
  766. [GGML_TYPE_TQ1_0] = {
  767. .type_name = "tq1_0",
  768. .blck_size = QK_K,
  769. .type_size = sizeof(block_tq1_0),
  770. .is_quantized = true,
  771. .to_float = (ggml_to_float_t) dequantize_row_tq1_0,
  772. .from_float_ref = (ggml_from_float_t) quantize_row_tq1_0_ref,
  773. },
  774. [GGML_TYPE_TQ2_0] = {
  775. .type_name = "tq2_0",
  776. .blck_size = QK_K,
  777. .type_size = sizeof(block_tq2_0),
  778. .is_quantized = true,
  779. .to_float = (ggml_to_float_t) dequantize_row_tq2_0,
  780. .from_float_ref = (ggml_from_float_t) quantize_row_tq2_0_ref,
  781. },
  782. [36] = { // GGML_TYPE_IQ4_NL_4_4
  783. .type_name = "TYPE_IQ4_NL_4_4 REMOVED, use IQ4_NL with runtime repacking",
  784. .blck_size = 0,
  785. .type_size = 0,
  786. .is_quantized = false,
  787. },
  788. [37] = { // GGML_TYPE_IQ4_NL_4_8
  789. .type_name = "TYPE_IQ4_NL_4_8 REMOVED, use IQ4_NL with runtime repacking",
  790. .blck_size = 0,
  791. .type_size = 0,
  792. .is_quantized = false,
  793. },
  794. [38] = { // GGML_TYPE_IQ4_NL_8_8
  795. .type_name = "TYPE_IQ4_NL_8_8 REMOVED, use IQ4_NL with runtime repacking",
  796. .blck_size = 0,
  797. .type_size = 0,
  798. .is_quantized = false,
  799. },
  800. };
  801. const struct ggml_type_traits * ggml_get_type_traits(enum ggml_type type) {
  802. GGML_ASSERT(type < GGML_TYPE_COUNT);
  803. return &type_traits[type];
  804. }
  805. //
  806. // ggml object
  807. //
  808. struct ggml_object {
  809. size_t offs;
  810. size_t size;
  811. struct ggml_object * next;
  812. enum ggml_object_type type;
  813. char padding[4];
  814. };
  815. static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
  816. //
  817. // ggml context
  818. //
  819. struct ggml_context {
  820. size_t mem_size;
  821. void * mem_buffer;
  822. bool mem_buffer_owned;
  823. bool no_alloc;
  824. int n_objects;
  825. struct ggml_object * objects_begin;
  826. struct ggml_object * objects_end;
  827. };
  828. struct ggml_context_container {
  829. bool used;
  830. struct ggml_context context;
  831. };
  832. //
  833. // data types
  834. //
  835. static const char * GGML_OP_NAME[GGML_OP_COUNT] = {
  836. "NONE",
  837. "DUP",
  838. "ADD",
  839. "ADD1",
  840. "ACC",
  841. "SUB",
  842. "MUL",
  843. "DIV",
  844. "SQR",
  845. "SQRT",
  846. "LOG",
  847. "SIN",
  848. "COS",
  849. "SUM",
  850. "SUM_ROWS",
  851. "MEAN",
  852. "ARGMAX",
  853. "COUNT_EQUAL",
  854. "REPEAT",
  855. "REPEAT_BACK",
  856. "CONCAT",
  857. "SILU_BACK",
  858. "NORM",
  859. "RMS_NORM",
  860. "RMS_NORM_BACK",
  861. "GROUP_NORM",
  862. "MUL_MAT",
  863. "MUL_MAT_ID",
  864. "OUT_PROD",
  865. "SCALE",
  866. "SET",
  867. "CPY",
  868. "CONT",
  869. "RESHAPE",
  870. "VIEW",
  871. "PERMUTE",
  872. "TRANSPOSE",
  873. "GET_ROWS",
  874. "GET_ROWS_BACK",
  875. "DIAG",
  876. "DIAG_MASK_INF",
  877. "DIAG_MASK_ZERO",
  878. "SOFT_MAX",
  879. "SOFT_MAX_BACK",
  880. "ROPE",
  881. "ROPE_BACK",
  882. "CLAMP",
  883. "CONV_TRANSPOSE_1D",
  884. "IM2COL",
  885. "IM2COL_BACK",
  886. "CONV_TRANSPOSE_2D",
  887. "POOL_1D",
  888. "POOL_2D",
  889. "POOL_2D_BACK",
  890. "UPSCALE",
  891. "PAD",
  892. "PAD_REFLECT_1D",
  893. "UNPAD",
  894. "ARANGE",
  895. "TIMESTEP_EMBEDDING",
  896. "ARGSORT",
  897. "LEAKY_RELU",
  898. "FLASH_ATTN_EXT",
  899. "FLASH_ATTN_BACK",
  900. "SSM_CONV",
  901. "SSM_SCAN",
  902. "WIN_PART",
  903. "WIN_UNPART",
  904. "GET_REL_POS",
  905. "ADD_REL_POS",
  906. "RWKV_WKV6",
  907. "UNARY",
  908. "MAP_UNARY",
  909. "MAP_BINARY",
  910. "MAP_CUSTOM1_F32",
  911. "MAP_CUSTOM2_F32",
  912. "MAP_CUSTOM3_F32",
  913. "MAP_CUSTOM1",
  914. "MAP_CUSTOM2",
  915. "MAP_CUSTOM3",
  916. "CROSS_ENTROPY_LOSS",
  917. "CROSS_ENTROPY_LOSS_BACK",
  918. "OPT_STEP_ADAMW",
  919. };
  920. static_assert(GGML_OP_COUNT == 83, "GGML_OP_COUNT != 83");
  921. static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
  922. "none",
  923. "x",
  924. "x+y",
  925. "x+y",
  926. "view(x,nb,offset)+=y->x",
  927. "x-y",
  928. "x*y",
  929. "x/y",
  930. "x^2",
  931. "√x",
  932. "log(x)",
  933. "sin(x)",
  934. "cos(x)",
  935. "Σx",
  936. "Σx_k",
  937. "Σx/n",
  938. "argmax(x)",
  939. "count_equal(x)",
  940. "repeat(x)",
  941. "repeat_back(x)",
  942. "concat(x, y)",
  943. "silu_back(x)",
  944. "norm(x)",
  945. "rms_norm(x)",
  946. "rms_norm_back(x)",
  947. "group_norm(x)",
  948. "X*Y",
  949. "X[i]*Y",
  950. "X*Y",
  951. "x*v",
  952. "y-\\>view(x)",
  953. "x-\\>y",
  954. "cont(x)",
  955. "reshape(x)",
  956. "view(x)",
  957. "permute(x)",
  958. "transpose(x)",
  959. "get_rows(x)",
  960. "get_rows_back(x)",
  961. "diag(x)",
  962. "diag_mask_inf(x)",
  963. "diag_mask_zero(x)",
  964. "soft_max(x)",
  965. "soft_max_back(x)",
  966. "rope(x)",
  967. "rope_back(x)",
  968. "clamp(x)",
  969. "conv_transpose_1d(x)",
  970. "im2col(x)",
  971. "im2col_back(x)",
  972. "conv_transpose_2d(x)",
  973. "pool_1d(x)",
  974. "pool_2d(x)",
  975. "pool_2d_back(x)",
  976. "upscale(x)",
  977. "pad(x)",
  978. "pad_reflect_1d(x)",
  979. "unpad(x)",
  980. "arange(start, stop, step)",
  981. "timestep_embedding(timesteps, dim, max_period)",
  982. "argsort(x)",
  983. "leaky_relu(x)",
  984. "flash_attn_ext(x)",
  985. "flash_attn_back(x)",
  986. "ssm_conv(x)",
  987. "ssm_scan(x)",
  988. "win_part(x)",
  989. "win_unpart(x)",
  990. "get_rel_pos(x)",
  991. "add_rel_pos(x)",
  992. "rwkv_wkv6(k, v, r, tf, td, s)",
  993. "unary(x)",
  994. "f(x)",
  995. "f(x,y)",
  996. "custom_f32(x)",
  997. "custom_f32(x,y)",
  998. "custom_f32(x,y,z)",
  999. "custom(x)",
  1000. "custom(x,y)",
  1001. "custom(x,y,z)",
  1002. "cross_entropy_loss(x,y)",
  1003. "cross_entropy_loss_back(x,y)",
  1004. "adamw(x)",
  1005. };
  1006. static_assert(GGML_OP_COUNT == 83, "GGML_OP_COUNT != 83");
  1007. static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2");
  1008. static const char * GGML_UNARY_OP_NAME[GGML_UNARY_OP_COUNT] = {
  1009. "ABS",
  1010. "SGN",
  1011. "NEG",
  1012. "STEP",
  1013. "TANH",
  1014. "ELU",
  1015. "RELU",
  1016. "SIGMOID",
  1017. "GELU",
  1018. "GELU_QUICK",
  1019. "SILU",
  1020. "HARDSWISH",
  1021. "HARDSIGMOID",
  1022. "EXP",
  1023. };
  1024. static_assert(GGML_UNARY_OP_COUNT == 14, "GGML_UNARY_OP_COUNT != 14");
  1025. static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
  1026. static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
  1027. ////////////////////////////////////////////////////////////////////////////////
  1028. void ggml_print_object(const struct ggml_object * obj) {
  1029. GGML_LOG_INFO(" - ggml_object: type = %d, offset = %zu, size = %zu, next = %p\n",
  1030. obj->type, obj->offs, obj->size, (const void *) obj->next);
  1031. }
  1032. void ggml_print_objects(const struct ggml_context * ctx) {
  1033. struct ggml_object * obj = ctx->objects_begin;
  1034. GGML_LOG_INFO("%s: objects in context %p:\n", __func__, (const void *) ctx);
  1035. while (obj != NULL) {
  1036. ggml_print_object(obj);
  1037. obj = obj->next;
  1038. }
  1039. GGML_LOG_INFO("%s: --- end ---\n", __func__);
  1040. }
  1041. int64_t ggml_nelements(const struct ggml_tensor * tensor) {
  1042. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1043. return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  1044. }
  1045. int64_t ggml_nrows(const struct ggml_tensor * tensor) {
  1046. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1047. return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
  1048. }
  1049. size_t ggml_nbytes(const struct ggml_tensor * tensor) {
  1050. size_t nbytes;
  1051. const size_t blck_size = ggml_blck_size(tensor->type);
  1052. if (blck_size == 1) {
  1053. nbytes = ggml_type_size(tensor->type);
  1054. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1055. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  1056. }
  1057. }
  1058. else {
  1059. nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
  1060. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  1061. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  1062. }
  1063. }
  1064. return nbytes;
  1065. }
  1066. size_t ggml_nbytes_pad(const struct ggml_tensor * tensor) {
  1067. return GGML_PAD(ggml_nbytes(tensor), GGML_MEM_ALIGN);
  1068. }
  1069. int64_t ggml_blck_size(enum ggml_type type) {
  1070. return type_traits[type].blck_size;
  1071. }
  1072. size_t ggml_type_size(enum ggml_type type) {
  1073. return type_traits[type].type_size;
  1074. }
  1075. size_t ggml_row_size(enum ggml_type type, int64_t ne) {
  1076. assert(ne % ggml_blck_size(type) == 0);
  1077. return ggml_type_size(type)*ne/ggml_blck_size(type);
  1078. }
  1079. double ggml_type_sizef(enum ggml_type type) {
  1080. return ((double)(type_traits[type].type_size))/type_traits[type].blck_size;
  1081. }
  1082. const char * ggml_type_name(enum ggml_type type) {
  1083. return type < GGML_TYPE_COUNT ? type_traits[type].type_name : "NONE";
  1084. }
  1085. bool ggml_is_quantized(enum ggml_type type) {
  1086. return type_traits[type].is_quantized;
  1087. }
  1088. const char * ggml_op_name(enum ggml_op op) {
  1089. return GGML_OP_NAME[op];
  1090. }
  1091. const char * ggml_op_symbol(enum ggml_op op) {
  1092. return GGML_OP_SYMBOL[op];
  1093. }
  1094. const char * ggml_unary_op_name(enum ggml_unary_op op) {
  1095. return GGML_UNARY_OP_NAME[op];
  1096. }
  1097. const char * ggml_op_desc(const struct ggml_tensor * t) {
  1098. if (t->op == GGML_OP_UNARY) {
  1099. enum ggml_unary_op uop = ggml_get_unary_op(t);
  1100. return ggml_unary_op_name(uop);
  1101. }
  1102. return ggml_op_name(t->op);
  1103. }
  1104. size_t ggml_element_size(const struct ggml_tensor * tensor) {
  1105. return ggml_type_size(tensor->type);
  1106. }
  1107. bool ggml_is_scalar(const struct ggml_tensor * tensor) {
  1108. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1109. return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1110. }
  1111. bool ggml_is_vector(const struct ggml_tensor * tensor) {
  1112. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1113. return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1114. }
  1115. bool ggml_is_matrix(const struct ggml_tensor * tensor) {
  1116. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1117. return tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1118. }
  1119. bool ggml_is_3d(const struct ggml_tensor * tensor) {
  1120. return tensor->ne[3] == 1;
  1121. }
  1122. int ggml_n_dims(const struct ggml_tensor * tensor) {
  1123. for (int i = GGML_MAX_DIMS - 1; i >= 1; --i) {
  1124. if (tensor->ne[i] > 1) {
  1125. return i + 1;
  1126. }
  1127. }
  1128. return 1;
  1129. }
  1130. enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype) {
  1131. enum ggml_type wtype = GGML_TYPE_COUNT;
  1132. switch (ftype) {
  1133. case GGML_FTYPE_ALL_F32: wtype = GGML_TYPE_F32; break;
  1134. case GGML_FTYPE_MOSTLY_F16: wtype = GGML_TYPE_F16; break;
  1135. case GGML_FTYPE_MOSTLY_BF16: wtype = GGML_TYPE_BF16; break;
  1136. case GGML_FTYPE_MOSTLY_Q4_0: wtype = GGML_TYPE_Q4_0; break;
  1137. case GGML_FTYPE_MOSTLY_Q4_1: wtype = GGML_TYPE_Q4_1; break;
  1138. case GGML_FTYPE_MOSTLY_Q5_0: wtype = GGML_TYPE_Q5_0; break;
  1139. case GGML_FTYPE_MOSTLY_Q5_1: wtype = GGML_TYPE_Q5_1; break;
  1140. case GGML_FTYPE_MOSTLY_Q8_0: wtype = GGML_TYPE_Q8_0; break;
  1141. case GGML_FTYPE_MOSTLY_Q2_K: wtype = GGML_TYPE_Q2_K; break;
  1142. case GGML_FTYPE_MOSTLY_Q3_K: wtype = GGML_TYPE_Q3_K; break;
  1143. case GGML_FTYPE_MOSTLY_Q4_K: wtype = GGML_TYPE_Q4_K; break;
  1144. case GGML_FTYPE_MOSTLY_Q5_K: wtype = GGML_TYPE_Q5_K; break;
  1145. case GGML_FTYPE_MOSTLY_Q6_K: wtype = GGML_TYPE_Q6_K; break;
  1146. case GGML_FTYPE_MOSTLY_IQ2_XXS: wtype = GGML_TYPE_IQ2_XXS; break;
  1147. case GGML_FTYPE_MOSTLY_IQ2_XS: wtype = GGML_TYPE_IQ2_XS; break;
  1148. case GGML_FTYPE_MOSTLY_IQ3_XXS: wtype = GGML_TYPE_IQ3_XXS; break;
  1149. case GGML_FTYPE_MOSTLY_IQ1_S: wtype = GGML_TYPE_IQ1_S; break;
  1150. case GGML_FTYPE_MOSTLY_IQ1_M: wtype = GGML_TYPE_IQ1_M; break;
  1151. case GGML_FTYPE_MOSTLY_IQ4_NL: wtype = GGML_TYPE_IQ4_NL; break;
  1152. case GGML_FTYPE_MOSTLY_IQ4_XS: wtype = GGML_TYPE_IQ4_XS; break;
  1153. case GGML_FTYPE_MOSTLY_IQ3_S: wtype = GGML_TYPE_IQ3_S; break;
  1154. case GGML_FTYPE_MOSTLY_IQ2_S: wtype = GGML_TYPE_IQ2_S; break;
  1155. case GGML_FTYPE_UNKNOWN: wtype = GGML_TYPE_COUNT; break;
  1156. case GGML_FTYPE_MOSTLY_Q4_1_SOME_F16: wtype = GGML_TYPE_COUNT; break;
  1157. }
  1158. GGML_ASSERT(wtype != GGML_TYPE_COUNT);
  1159. return wtype;
  1160. }
  1161. size_t ggml_tensor_overhead(void) {
  1162. return GGML_OBJECT_SIZE + GGML_TENSOR_SIZE;
  1163. }
  1164. bool ggml_is_transposed(const struct ggml_tensor * tensor) {
  1165. return tensor->nb[0] > tensor->nb[1];
  1166. }
  1167. static bool ggml_is_contiguous_n(const struct ggml_tensor * tensor, int n) {
  1168. size_t next_nb = ggml_type_size(tensor->type);
  1169. if (tensor->ne[0] != ggml_blck_size(tensor->type) && tensor->nb[0] != next_nb) {
  1170. return false;
  1171. }
  1172. next_nb *= tensor->ne[0]/ggml_blck_size(tensor->type);
  1173. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1174. if (tensor->ne[i] != 1) {
  1175. if (i > n) {
  1176. if (tensor->nb[i] != next_nb) {
  1177. return false;
  1178. }
  1179. next_nb *= tensor->ne[i];
  1180. } else {
  1181. // this dimension does not need to be contiguous
  1182. next_nb = tensor->ne[i]*tensor->nb[i];
  1183. }
  1184. }
  1185. }
  1186. return true;
  1187. }
  1188. bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
  1189. return ggml_is_contiguous_0(tensor);
  1190. }
  1191. bool ggml_is_contiguous_0(const struct ggml_tensor * tensor) {
  1192. return ggml_is_contiguous_n(tensor, 0);
  1193. }
  1194. bool ggml_is_contiguous_1(const struct ggml_tensor * tensor) {
  1195. return ggml_is_contiguous_n(tensor, 1);
  1196. }
  1197. bool ggml_is_contiguous_2(const struct ggml_tensor * tensor) {
  1198. return ggml_is_contiguous_n(tensor, 2);
  1199. }
  1200. bool ggml_is_permuted(const struct ggml_tensor * tensor) {
  1201. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1202. return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
  1203. }
  1204. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  1205. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1206. return
  1207. tensor->nb[0] == ggml_type_size(tensor->type) &&
  1208. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  1209. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1210. }
  1211. bool ggml_is_empty(const struct ggml_tensor * tensor) {
  1212. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1213. if (tensor->ne[i] == 0) {
  1214. // empty if any dimension has no elements
  1215. return true;
  1216. }
  1217. }
  1218. return false;
  1219. }
  1220. bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1221. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1222. return
  1223. (t0->ne[0] == t1->ne[0]) &&
  1224. (t0->ne[1] == t1->ne[1]) &&
  1225. (t0->ne[2] == t1->ne[2]) &&
  1226. (t0->ne[3] == t1->ne[3]);
  1227. }
  1228. bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1229. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1230. return
  1231. (t0->nb[0] == t1->nb[0]) &&
  1232. (t0->nb[1] == t1->nb[1]) &&
  1233. (t0->nb[2] == t1->nb[2]) &&
  1234. (t0->nb[3] == t1->nb[3]);
  1235. }
  1236. // check if t1 can be represented as a repeatition of t0
  1237. bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1238. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1239. return ggml_is_empty(t0) ? ggml_is_empty(t1) :
  1240. (t1->ne[0]%t0->ne[0] == 0) &&
  1241. (t1->ne[1]%t0->ne[1] == 0) &&
  1242. (t1->ne[2]%t0->ne[2] == 0) &&
  1243. (t1->ne[3]%t0->ne[3] == 0);
  1244. }
  1245. static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1246. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1247. return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
  1248. }
  1249. // assert that pointer is aligned to GGML_MEM_ALIGN
  1250. #define GGML_ASSERT_ALIGNED(ptr) \
  1251. GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  1252. ////////////////////////////////////////////////////////////////////////////////
  1253. struct ggml_context * ggml_init(struct ggml_init_params params) {
  1254. static bool is_first_call = true;
  1255. ggml_critical_section_start();
  1256. if (is_first_call) {
  1257. // initialize time system (required on Windows)
  1258. ggml_time_init();
  1259. for (int i = 0; i < (1 << 16); ++i) {
  1260. union {
  1261. uint16_t u16;
  1262. ggml_fp16_t fp16;
  1263. } u = {i};
  1264. ggml_table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(u.fp16);
  1265. }
  1266. is_first_call = false;
  1267. }
  1268. ggml_critical_section_end();
  1269. struct ggml_context * ctx = GGML_MALLOC(sizeof(struct ggml_context));
  1270. // allow to call ggml_init with 0 size
  1271. if (params.mem_size == 0) {
  1272. params.mem_size = GGML_MEM_ALIGN;
  1273. }
  1274. const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
  1275. *ctx = (struct ggml_context) {
  1276. /*.mem_size =*/ mem_size,
  1277. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : ggml_aligned_malloc(mem_size),
  1278. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  1279. /*.no_alloc =*/ params.no_alloc,
  1280. /*.n_objects =*/ 0,
  1281. /*.objects_begin =*/ NULL,
  1282. /*.objects_end =*/ NULL,
  1283. };
  1284. GGML_ASSERT(ctx->mem_buffer != NULL);
  1285. GGML_ASSERT_ALIGNED(ctx->mem_buffer);
  1286. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  1287. return ctx;
  1288. }
  1289. void ggml_reset(struct ggml_context * ctx) {
  1290. if (ctx == NULL) {
  1291. return;
  1292. }
  1293. ctx->n_objects = 0;
  1294. ctx->objects_begin = NULL;
  1295. ctx->objects_end = NULL;
  1296. }
  1297. void ggml_free(struct ggml_context * ctx) {
  1298. if (ctx == NULL) {
  1299. return;
  1300. }
  1301. if (ctx->mem_buffer_owned) {
  1302. ggml_aligned_free(ctx->mem_buffer, ctx->mem_size);
  1303. }
  1304. GGML_FREE(ctx);
  1305. }
  1306. size_t ggml_used_mem(const struct ggml_context * ctx) {
  1307. return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
  1308. }
  1309. bool ggml_get_no_alloc(struct ggml_context * ctx) {
  1310. return ctx->no_alloc;
  1311. }
  1312. void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
  1313. ctx->no_alloc = no_alloc;
  1314. }
  1315. void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
  1316. return ctx->mem_buffer;
  1317. }
  1318. size_t ggml_get_mem_size(const struct ggml_context * ctx) {
  1319. return ctx->mem_size;
  1320. }
  1321. size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
  1322. size_t max_size = 0;
  1323. for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
  1324. size_t bytes = ggml_nbytes(tensor);
  1325. max_size = MAX(max_size, bytes);
  1326. }
  1327. return max_size;
  1328. }
  1329. ////////////////////////////////////////////////////////////////////////////////
  1330. static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
  1331. // always insert objects at the end of the context's memory pool
  1332. struct ggml_object * obj_cur = ctx->objects_end;
  1333. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  1334. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  1335. const size_t cur_end = cur_offs + cur_size;
  1336. // align to GGML_MEM_ALIGN
  1337. size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
  1338. char * const mem_buffer = ctx->mem_buffer;
  1339. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  1340. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  1341. GGML_LOG_WARN("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  1342. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  1343. #ifndef NDEBUG
  1344. GGML_ABORT("not enough space in the context's memory pool");
  1345. #endif
  1346. return NULL;
  1347. }
  1348. *obj_new = (struct ggml_object) {
  1349. .offs = cur_end + GGML_OBJECT_SIZE,
  1350. .size = size_needed,
  1351. .next = NULL,
  1352. .type = type,
  1353. };
  1354. GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
  1355. if (obj_cur != NULL) {
  1356. obj_cur->next = obj_new;
  1357. } else {
  1358. // this is the first object in this context
  1359. ctx->objects_begin = obj_new;
  1360. }
  1361. ctx->objects_end = obj_new;
  1362. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  1363. return obj_new;
  1364. }
  1365. static struct ggml_tensor * ggml_new_tensor_impl(
  1366. struct ggml_context * ctx,
  1367. enum ggml_type type,
  1368. int n_dims,
  1369. const int64_t * ne,
  1370. struct ggml_tensor * view_src,
  1371. size_t view_offs) {
  1372. GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
  1373. GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
  1374. // find the base tensor and absolute offset
  1375. if (view_src != NULL && view_src->view_src != NULL) {
  1376. view_offs += view_src->view_offs;
  1377. view_src = view_src->view_src;
  1378. }
  1379. size_t data_size = ggml_row_size(type, ne[0]);
  1380. for (int i = 1; i < n_dims; i++) {
  1381. data_size *= ne[i];
  1382. }
  1383. GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
  1384. void * data = view_src != NULL ? view_src->data : NULL;
  1385. if (data != NULL) {
  1386. data = (char *) data + view_offs;
  1387. }
  1388. size_t obj_alloc_size = 0;
  1389. if (view_src == NULL && !ctx->no_alloc) {
  1390. // allocate tensor data in the context's memory pool
  1391. obj_alloc_size = data_size;
  1392. }
  1393. struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
  1394. GGML_ASSERT(obj_new);
  1395. struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
  1396. #ifdef __clang__
  1397. // temporary until ggml_tensor::backend is removed
  1398. #pragma clang diagnostic push
  1399. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  1400. #endif
  1401. *result = (struct ggml_tensor) {
  1402. /*.type =*/ type,
  1403. /*.backend =*/ GGML_BACKEND_TYPE_CPU,
  1404. /*.buffer =*/ NULL,
  1405. /*.ne =*/ { 1, 1, 1, 1 },
  1406. /*.nb =*/ { 0, 0, 0, 0 },
  1407. /*.op =*/ GGML_OP_NONE,
  1408. /*.op_params =*/ { 0 },
  1409. /*.flags =*/ 0,
  1410. /*.src =*/ { NULL },
  1411. /*.view_src =*/ view_src,
  1412. /*.view_offs =*/ view_offs,
  1413. /*.data =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
  1414. /*.name =*/ { 0 },
  1415. /*.extra =*/ NULL,
  1416. /*.padding =*/ { 0 },
  1417. };
  1418. #ifdef __clang__
  1419. #pragma clang diagnostic pop
  1420. #endif
  1421. // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
  1422. //GGML_ASSERT_ALIGNED(result->data);
  1423. for (int i = 0; i < n_dims; i++) {
  1424. result->ne[i] = ne[i];
  1425. }
  1426. result->nb[0] = ggml_type_size(type);
  1427. result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
  1428. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  1429. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  1430. }
  1431. ctx->n_objects++;
  1432. return result;
  1433. }
  1434. struct ggml_tensor * ggml_new_tensor(
  1435. struct ggml_context * ctx,
  1436. enum ggml_type type,
  1437. int n_dims,
  1438. const int64_t * ne) {
  1439. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
  1440. }
  1441. struct ggml_tensor * ggml_new_tensor_1d(
  1442. struct ggml_context * ctx,
  1443. enum ggml_type type,
  1444. int64_t ne0) {
  1445. return ggml_new_tensor(ctx, type, 1, &ne0);
  1446. }
  1447. struct ggml_tensor * ggml_new_tensor_2d(
  1448. struct ggml_context * ctx,
  1449. enum ggml_type type,
  1450. int64_t ne0,
  1451. int64_t ne1) {
  1452. const int64_t ne[2] = { ne0, ne1 };
  1453. return ggml_new_tensor(ctx, type, 2, ne);
  1454. }
  1455. struct ggml_tensor * ggml_new_tensor_3d(
  1456. struct ggml_context * ctx,
  1457. enum ggml_type type,
  1458. int64_t ne0,
  1459. int64_t ne1,
  1460. int64_t ne2) {
  1461. const int64_t ne[3] = { ne0, ne1, ne2 };
  1462. return ggml_new_tensor(ctx, type, 3, ne);
  1463. }
  1464. struct ggml_tensor * ggml_new_tensor_4d(
  1465. struct ggml_context * ctx,
  1466. enum ggml_type type,
  1467. int64_t ne0,
  1468. int64_t ne1,
  1469. int64_t ne2,
  1470. int64_t ne3) {
  1471. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  1472. return ggml_new_tensor(ctx, type, 4, ne);
  1473. }
  1474. void * ggml_new_buffer(struct ggml_context * ctx, size_t nbytes) {
  1475. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, nbytes);
  1476. return (uint8_t *)ctx->mem_buffer + obj->offs;
  1477. }
  1478. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  1479. return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
  1480. }
  1481. void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
  1482. const int64_t ne2 = tensor->ne[2];
  1483. const int64_t ne1 = tensor->ne[1];
  1484. const int64_t ne0 = tensor->ne[0];
  1485. const int64_t i3_ = (i/(ne2*ne1*ne0));
  1486. const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
  1487. const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
  1488. const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
  1489. if (i0) {
  1490. * i0 = i0_;
  1491. }
  1492. if (i1) {
  1493. * i1 = i1_;
  1494. }
  1495. if (i2) {
  1496. * i2 = i2_;
  1497. }
  1498. if (i3) {
  1499. * i3 = i3_;
  1500. }
  1501. }
  1502. void * ggml_get_data(const struct ggml_tensor * tensor) {
  1503. return tensor->data;
  1504. }
  1505. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  1506. assert(tensor->type == GGML_TYPE_F32);
  1507. return (float *)(tensor->data);
  1508. }
  1509. enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
  1510. GGML_ASSERT(tensor->op == GGML_OP_UNARY);
  1511. return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
  1512. }
  1513. const char * ggml_get_name(const struct ggml_tensor * tensor) {
  1514. return tensor->name;
  1515. }
  1516. struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
  1517. size_t i;
  1518. for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
  1519. tensor->name[i] = name[i];
  1520. }
  1521. tensor->name[i] = '\0';
  1522. return tensor;
  1523. }
  1524. struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
  1525. va_list args;
  1526. va_start(args, fmt);
  1527. vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
  1528. va_end(args);
  1529. return tensor;
  1530. }
  1531. struct ggml_tensor * ggml_view_tensor(
  1532. struct ggml_context * ctx,
  1533. struct ggml_tensor * src) {
  1534. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
  1535. ggml_format_name(result, "%s (view)", src->name);
  1536. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  1537. result->nb[i] = src->nb[i];
  1538. }
  1539. return result;
  1540. }
  1541. struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
  1542. struct ggml_object * obj = ctx->objects_begin;
  1543. char * const mem_buffer = ctx->mem_buffer;
  1544. while (obj != NULL) {
  1545. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1546. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1547. }
  1548. obj = obj->next;
  1549. }
  1550. return NULL;
  1551. }
  1552. struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
  1553. struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
  1554. obj = obj->next;
  1555. char * const mem_buffer = ctx->mem_buffer;
  1556. while (obj != NULL) {
  1557. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1558. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1559. }
  1560. obj = obj->next;
  1561. }
  1562. return NULL;
  1563. }
  1564. struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
  1565. struct ggml_object * obj = ctx->objects_begin;
  1566. char * const mem_buffer = ctx->mem_buffer;
  1567. while (obj != NULL) {
  1568. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1569. struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
  1570. if (strcmp(cur->name, name) == 0) {
  1571. return cur;
  1572. }
  1573. }
  1574. obj = obj->next;
  1575. }
  1576. return NULL;
  1577. }
  1578. ////////////////////////////////////////////////////////////////////////////////
  1579. // ggml_dup
  1580. static struct ggml_tensor * ggml_dup_impl(
  1581. struct ggml_context * ctx,
  1582. struct ggml_tensor * a,
  1583. bool inplace) {
  1584. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1585. result->op = GGML_OP_DUP;
  1586. result->src[0] = a;
  1587. return result;
  1588. }
  1589. struct ggml_tensor * ggml_dup(
  1590. struct ggml_context * ctx,
  1591. struct ggml_tensor * a) {
  1592. return ggml_dup_impl(ctx, a, false);
  1593. }
  1594. struct ggml_tensor * ggml_dup_inplace(
  1595. struct ggml_context * ctx,
  1596. struct ggml_tensor * a) {
  1597. return ggml_dup_impl(ctx, a, true);
  1598. }
  1599. // ggml_add
  1600. static struct ggml_tensor * ggml_add_impl(
  1601. struct ggml_context * ctx,
  1602. struct ggml_tensor * a,
  1603. struct ggml_tensor * b,
  1604. bool inplace) {
  1605. GGML_ASSERT(ggml_can_repeat(b, a));
  1606. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1607. result->op = GGML_OP_ADD;
  1608. result->src[0] = a;
  1609. result->src[1] = b;
  1610. return result;
  1611. }
  1612. struct ggml_tensor * ggml_add(
  1613. struct ggml_context * ctx,
  1614. struct ggml_tensor * a,
  1615. struct ggml_tensor * b) {
  1616. return ggml_add_impl(ctx, a, b, false);
  1617. }
  1618. struct ggml_tensor * ggml_add_inplace(
  1619. struct ggml_context * ctx,
  1620. struct ggml_tensor * a,
  1621. struct ggml_tensor * b) {
  1622. return ggml_add_impl(ctx, a, b, true);
  1623. }
  1624. // ggml_add_cast
  1625. static struct ggml_tensor * ggml_add_cast_impl(
  1626. struct ggml_context * ctx,
  1627. struct ggml_tensor * a,
  1628. struct ggml_tensor * b,
  1629. enum ggml_type type) {
  1630. // TODO: support less-strict constraint
  1631. // GGML_ASSERT(ggml_can_repeat(b, a));
  1632. GGML_ASSERT(ggml_can_repeat_rows(b, a));
  1633. // currently only supported for quantized input and f16
  1634. GGML_ASSERT(ggml_is_quantized(a->type) ||
  1635. a->type == GGML_TYPE_F16 ||
  1636. a->type == GGML_TYPE_BF16);
  1637. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  1638. result->op = GGML_OP_ADD;
  1639. result->src[0] = a;
  1640. result->src[1] = b;
  1641. return result;
  1642. }
  1643. struct ggml_tensor * ggml_add_cast(
  1644. struct ggml_context * ctx,
  1645. struct ggml_tensor * a,
  1646. struct ggml_tensor * b,
  1647. enum ggml_type type) {
  1648. return ggml_add_cast_impl(ctx, a, b, type);
  1649. }
  1650. // ggml_add1
  1651. static struct ggml_tensor * ggml_add1_impl(
  1652. struct ggml_context * ctx,
  1653. struct ggml_tensor * a,
  1654. struct ggml_tensor * b,
  1655. bool inplace) {
  1656. GGML_ASSERT(ggml_is_scalar(b));
  1657. GGML_ASSERT(ggml_is_padded_1d(a));
  1658. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1659. result->op = GGML_OP_ADD1;
  1660. result->src[0] = a;
  1661. result->src[1] = b;
  1662. return result;
  1663. }
  1664. struct ggml_tensor * ggml_add1(
  1665. struct ggml_context * ctx,
  1666. struct ggml_tensor * a,
  1667. struct ggml_tensor * b) {
  1668. return ggml_add1_impl(ctx, a, b, false);
  1669. }
  1670. struct ggml_tensor * ggml_add1_inplace(
  1671. struct ggml_context * ctx,
  1672. struct ggml_tensor * a,
  1673. struct ggml_tensor * b) {
  1674. return ggml_add1_impl(ctx, a, b, true);
  1675. }
  1676. // ggml_acc
  1677. static struct ggml_tensor * ggml_acc_impl(
  1678. struct ggml_context * ctx,
  1679. struct ggml_tensor * a,
  1680. struct ggml_tensor * b,
  1681. size_t nb1,
  1682. size_t nb2,
  1683. size_t nb3,
  1684. size_t offset,
  1685. bool inplace) {
  1686. GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
  1687. GGML_ASSERT(ggml_is_contiguous(a));
  1688. GGML_ASSERT(a->type == GGML_TYPE_F32);
  1689. GGML_ASSERT(b->type == GGML_TYPE_F32);
  1690. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1691. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  1692. ggml_set_op_params(result, params, sizeof(params));
  1693. result->op = GGML_OP_ACC;
  1694. result->src[0] = a;
  1695. result->src[1] = b;
  1696. return result;
  1697. }
  1698. struct ggml_tensor * ggml_acc(
  1699. struct ggml_context * ctx,
  1700. struct ggml_tensor * a,
  1701. struct ggml_tensor * b,
  1702. size_t nb1,
  1703. size_t nb2,
  1704. size_t nb3,
  1705. size_t offset) {
  1706. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  1707. }
  1708. struct ggml_tensor * ggml_acc_inplace(
  1709. struct ggml_context * ctx,
  1710. struct ggml_tensor * a,
  1711. struct ggml_tensor * b,
  1712. size_t nb1,
  1713. size_t nb2,
  1714. size_t nb3,
  1715. size_t offset) {
  1716. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  1717. }
  1718. // ggml_sub
  1719. static struct ggml_tensor * ggml_sub_impl(
  1720. struct ggml_context * ctx,
  1721. struct ggml_tensor * a,
  1722. struct ggml_tensor * b,
  1723. bool inplace) {
  1724. GGML_ASSERT(ggml_can_repeat(b, a));
  1725. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1726. result->op = GGML_OP_SUB;
  1727. result->src[0] = a;
  1728. result->src[1] = b;
  1729. return result;
  1730. }
  1731. struct ggml_tensor * ggml_sub(
  1732. struct ggml_context * ctx,
  1733. struct ggml_tensor * a,
  1734. struct ggml_tensor * b) {
  1735. return ggml_sub_impl(ctx, a, b, false);
  1736. }
  1737. struct ggml_tensor * ggml_sub_inplace(
  1738. struct ggml_context * ctx,
  1739. struct ggml_tensor * a,
  1740. struct ggml_tensor * b) {
  1741. return ggml_sub_impl(ctx, a, b, true);
  1742. }
  1743. // ggml_mul
  1744. static struct ggml_tensor * ggml_mul_impl(
  1745. struct ggml_context * ctx,
  1746. struct ggml_tensor * a,
  1747. struct ggml_tensor * b,
  1748. bool inplace) {
  1749. GGML_ASSERT(ggml_can_repeat(b, a));
  1750. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1751. result->op = GGML_OP_MUL;
  1752. result->src[0] = a;
  1753. result->src[1] = b;
  1754. return result;
  1755. }
  1756. struct ggml_tensor * ggml_mul(
  1757. struct ggml_context * ctx,
  1758. struct ggml_tensor * a,
  1759. struct ggml_tensor * b) {
  1760. return ggml_mul_impl(ctx, a, b, false);
  1761. }
  1762. struct ggml_tensor * ggml_mul_inplace(
  1763. struct ggml_context * ctx,
  1764. struct ggml_tensor * a,
  1765. struct ggml_tensor * b) {
  1766. return ggml_mul_impl(ctx, a, b, true);
  1767. }
  1768. // ggml_div
  1769. static struct ggml_tensor * ggml_div_impl(
  1770. struct ggml_context * ctx,
  1771. struct ggml_tensor * a,
  1772. struct ggml_tensor * b,
  1773. bool inplace) {
  1774. GGML_ASSERT(ggml_can_repeat(b, a));
  1775. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1776. result->op = GGML_OP_DIV;
  1777. result->src[0] = a;
  1778. result->src[1] = b;
  1779. return result;
  1780. }
  1781. struct ggml_tensor * ggml_div(
  1782. struct ggml_context * ctx,
  1783. struct ggml_tensor * a,
  1784. struct ggml_tensor * b) {
  1785. return ggml_div_impl(ctx, a, b, false);
  1786. }
  1787. struct ggml_tensor * ggml_div_inplace(
  1788. struct ggml_context * ctx,
  1789. struct ggml_tensor * a,
  1790. struct ggml_tensor * b) {
  1791. return ggml_div_impl(ctx, a, b, true);
  1792. }
  1793. // ggml_sqr
  1794. static struct ggml_tensor * ggml_sqr_impl(
  1795. struct ggml_context * ctx,
  1796. struct ggml_tensor * a,
  1797. bool inplace) {
  1798. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1799. result->op = GGML_OP_SQR;
  1800. result->src[0] = a;
  1801. return result;
  1802. }
  1803. struct ggml_tensor * ggml_sqr(
  1804. struct ggml_context * ctx,
  1805. struct ggml_tensor * a) {
  1806. return ggml_sqr_impl(ctx, a, false);
  1807. }
  1808. struct ggml_tensor * ggml_sqr_inplace(
  1809. struct ggml_context * ctx,
  1810. struct ggml_tensor * a) {
  1811. return ggml_sqr_impl(ctx, a, true);
  1812. }
  1813. // ggml_sqrt
  1814. static struct ggml_tensor * ggml_sqrt_impl(
  1815. struct ggml_context * ctx,
  1816. struct ggml_tensor * a,
  1817. bool inplace) {
  1818. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1819. result->op = GGML_OP_SQRT;
  1820. result->src[0] = a;
  1821. return result;
  1822. }
  1823. struct ggml_tensor * ggml_sqrt(
  1824. struct ggml_context * ctx,
  1825. struct ggml_tensor * a) {
  1826. return ggml_sqrt_impl(ctx, a, false);
  1827. }
  1828. struct ggml_tensor * ggml_sqrt_inplace(
  1829. struct ggml_context * ctx,
  1830. struct ggml_tensor * a) {
  1831. return ggml_sqrt_impl(ctx, a, true);
  1832. }
  1833. // ggml_log
  1834. static struct ggml_tensor * ggml_log_impl(
  1835. struct ggml_context * ctx,
  1836. struct ggml_tensor * a,
  1837. bool inplace) {
  1838. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1839. result->op = GGML_OP_LOG;
  1840. result->src[0] = a;
  1841. return result;
  1842. }
  1843. struct ggml_tensor * ggml_log(
  1844. struct ggml_context * ctx,
  1845. struct ggml_tensor * a) {
  1846. return ggml_log_impl(ctx, a, false);
  1847. }
  1848. struct ggml_tensor * ggml_log_inplace(
  1849. struct ggml_context * ctx,
  1850. struct ggml_tensor * a) {
  1851. return ggml_log_impl(ctx, a, true);
  1852. }
  1853. // ggml_sin
  1854. static struct ggml_tensor * ggml_sin_impl(
  1855. struct ggml_context * ctx,
  1856. struct ggml_tensor * a,
  1857. bool inplace) {
  1858. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1859. result->op = GGML_OP_SIN;
  1860. result->src[0] = a;
  1861. return result;
  1862. }
  1863. struct ggml_tensor * ggml_sin(
  1864. struct ggml_context * ctx,
  1865. struct ggml_tensor * a) {
  1866. return ggml_sin_impl(ctx, a, false);
  1867. }
  1868. struct ggml_tensor * ggml_sin_inplace(
  1869. struct ggml_context * ctx,
  1870. struct ggml_tensor * a) {
  1871. return ggml_sin_impl(ctx, a, true);
  1872. }
  1873. // ggml_cos
  1874. static struct ggml_tensor * ggml_cos_impl(
  1875. struct ggml_context * ctx,
  1876. struct ggml_tensor * a,
  1877. bool inplace) {
  1878. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1879. result->op = GGML_OP_COS;
  1880. result->src[0] = a;
  1881. return result;
  1882. }
  1883. struct ggml_tensor * ggml_cos(
  1884. struct ggml_context * ctx,
  1885. struct ggml_tensor * a) {
  1886. return ggml_cos_impl(ctx, a, false);
  1887. }
  1888. struct ggml_tensor * ggml_cos_inplace(
  1889. struct ggml_context * ctx,
  1890. struct ggml_tensor * a) {
  1891. return ggml_cos_impl(ctx, a, true);
  1892. }
  1893. // ggml_sum
  1894. struct ggml_tensor * ggml_sum(
  1895. struct ggml_context * ctx,
  1896. struct ggml_tensor * a) {
  1897. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  1898. result->op = GGML_OP_SUM;
  1899. result->src[0] = a;
  1900. return result;
  1901. }
  1902. // ggml_sum_rows
  1903. struct ggml_tensor * ggml_sum_rows(
  1904. struct ggml_context * ctx,
  1905. struct ggml_tensor * a) {
  1906. int64_t ne[GGML_MAX_DIMS] = { 1 };
  1907. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  1908. ne[i] = a->ne[i];
  1909. }
  1910. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1911. result->op = GGML_OP_SUM_ROWS;
  1912. result->src[0] = a;
  1913. return result;
  1914. }
  1915. // ggml_mean
  1916. struct ggml_tensor * ggml_mean(
  1917. struct ggml_context * ctx,
  1918. struct ggml_tensor * a) {
  1919. int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  1920. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  1921. result->op = GGML_OP_MEAN;
  1922. result->src[0] = a;
  1923. return result;
  1924. }
  1925. // ggml_argmax
  1926. struct ggml_tensor * ggml_argmax(
  1927. struct ggml_context * ctx,
  1928. struct ggml_tensor * a) {
  1929. GGML_ASSERT(ggml_is_matrix(a));
  1930. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  1931. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
  1932. result->op = GGML_OP_ARGMAX;
  1933. result->src[0] = a;
  1934. return result;
  1935. }
  1936. // ggml_count_equal
  1937. struct ggml_tensor * ggml_count_equal(
  1938. struct ggml_context * ctx,
  1939. struct ggml_tensor * a,
  1940. struct ggml_tensor * b) {
  1941. GGML_ASSERT(ggml_are_same_shape(a, b));
  1942. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, 1);
  1943. result->op = GGML_OP_COUNT_EQUAL;
  1944. result->src[0] = a;
  1945. result->src[1] = b;
  1946. return result;
  1947. }
  1948. // ggml_repeat
  1949. struct ggml_tensor * ggml_repeat(
  1950. struct ggml_context * ctx,
  1951. struct ggml_tensor * a,
  1952. struct ggml_tensor * b) {
  1953. GGML_ASSERT(ggml_can_repeat(a, b));
  1954. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1955. result->op = GGML_OP_REPEAT;
  1956. result->src[0] = a;
  1957. return result;
  1958. }
  1959. // ggml_repeat_back
  1960. struct ggml_tensor * ggml_repeat_back(
  1961. struct ggml_context * ctx,
  1962. struct ggml_tensor * a,
  1963. struct ggml_tensor * b) {
  1964. GGML_ASSERT(ggml_can_repeat(b, a));
  1965. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1966. result->op = GGML_OP_REPEAT_BACK;
  1967. result->src[0] = a;
  1968. return result;
  1969. }
  1970. // ggml_concat
  1971. struct ggml_tensor * ggml_concat(
  1972. struct ggml_context * ctx,
  1973. struct ggml_tensor * a,
  1974. struct ggml_tensor * b,
  1975. int dim) {
  1976. GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
  1977. int64_t ne[GGML_MAX_DIMS];
  1978. for (int d = 0; d < GGML_MAX_DIMS; ++d) {
  1979. if (d == dim) {
  1980. ne[d] = a->ne[d] + b->ne[d];
  1981. continue;
  1982. }
  1983. GGML_ASSERT(a->ne[d] == b->ne[d]);
  1984. ne[d] = a->ne[d];
  1985. }
  1986. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1987. ggml_set_op_params_i32(result, 0, dim);
  1988. result->op = GGML_OP_CONCAT;
  1989. result->src[0] = a;
  1990. result->src[1] = b;
  1991. return result;
  1992. }
  1993. // ggml_abs
  1994. struct ggml_tensor * ggml_abs(
  1995. struct ggml_context * ctx,
  1996. struct ggml_tensor * a) {
  1997. return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
  1998. }
  1999. struct ggml_tensor * ggml_abs_inplace(
  2000. struct ggml_context * ctx,
  2001. struct ggml_tensor * a) {
  2002. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
  2003. }
  2004. // ggml_sgn
  2005. struct ggml_tensor * ggml_sgn(
  2006. struct ggml_context * ctx,
  2007. struct ggml_tensor * a) {
  2008. return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
  2009. }
  2010. struct ggml_tensor * ggml_sgn_inplace(
  2011. struct ggml_context * ctx,
  2012. struct ggml_tensor * a) {
  2013. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
  2014. }
  2015. // ggml_neg
  2016. struct ggml_tensor * ggml_neg(
  2017. struct ggml_context * ctx,
  2018. struct ggml_tensor * a) {
  2019. return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
  2020. }
  2021. struct ggml_tensor * ggml_neg_inplace(
  2022. struct ggml_context * ctx,
  2023. struct ggml_tensor * a) {
  2024. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
  2025. }
  2026. // ggml_step
  2027. struct ggml_tensor * ggml_step(
  2028. struct ggml_context * ctx,
  2029. struct ggml_tensor * a) {
  2030. return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
  2031. }
  2032. struct ggml_tensor * ggml_step_inplace(
  2033. struct ggml_context * ctx,
  2034. struct ggml_tensor * a) {
  2035. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
  2036. }
  2037. // ggml_tanh
  2038. struct ggml_tensor * ggml_tanh(
  2039. struct ggml_context * ctx,
  2040. struct ggml_tensor * a) {
  2041. return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
  2042. }
  2043. struct ggml_tensor * ggml_tanh_inplace(
  2044. struct ggml_context * ctx,
  2045. struct ggml_tensor * a) {
  2046. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
  2047. }
  2048. // ggml_elu
  2049. struct ggml_tensor * ggml_elu(
  2050. struct ggml_context * ctx,
  2051. struct ggml_tensor * a) {
  2052. return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
  2053. }
  2054. struct ggml_tensor * ggml_elu_inplace(
  2055. struct ggml_context * ctx,
  2056. struct ggml_tensor * a) {
  2057. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
  2058. }
  2059. // ggml_relu
  2060. struct ggml_tensor * ggml_relu(
  2061. struct ggml_context * ctx,
  2062. struct ggml_tensor * a) {
  2063. return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
  2064. }
  2065. struct ggml_tensor * ggml_relu_inplace(
  2066. struct ggml_context * ctx,
  2067. struct ggml_tensor * a) {
  2068. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
  2069. }
  2070. // ggml_leaky_relu
  2071. struct ggml_tensor * ggml_leaky_relu(
  2072. struct ggml_context * ctx,
  2073. struct ggml_tensor * a,
  2074. float negative_slope,
  2075. bool inplace) {
  2076. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2077. ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
  2078. result->op = GGML_OP_LEAKY_RELU;
  2079. result->src[0] = a;
  2080. return result;
  2081. }
  2082. // ggml_sigmoid
  2083. struct ggml_tensor * ggml_sigmoid(
  2084. struct ggml_context * ctx,
  2085. struct ggml_tensor * a) {
  2086. return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
  2087. }
  2088. struct ggml_tensor * ggml_sigmoid_inplace(
  2089. struct ggml_context * ctx,
  2090. struct ggml_tensor * a) {
  2091. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
  2092. }
  2093. // ggml_gelu
  2094. struct ggml_tensor * ggml_gelu(
  2095. struct ggml_context * ctx,
  2096. struct ggml_tensor * a) {
  2097. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
  2098. }
  2099. struct ggml_tensor * ggml_gelu_inplace(
  2100. struct ggml_context * ctx,
  2101. struct ggml_tensor * a) {
  2102. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
  2103. }
  2104. // ggml_gelu_quick
  2105. struct ggml_tensor * ggml_gelu_quick(
  2106. struct ggml_context * ctx,
  2107. struct ggml_tensor * a) {
  2108. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2109. }
  2110. struct ggml_tensor * ggml_gelu_quick_inplace(
  2111. struct ggml_context * ctx,
  2112. struct ggml_tensor * a) {
  2113. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2114. }
  2115. // ggml_silu
  2116. struct ggml_tensor * ggml_silu(
  2117. struct ggml_context * ctx,
  2118. struct ggml_tensor * a) {
  2119. return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
  2120. }
  2121. struct ggml_tensor * ggml_silu_inplace(
  2122. struct ggml_context * ctx,
  2123. struct ggml_tensor * a) {
  2124. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
  2125. }
  2126. // ggml_silu_back
  2127. struct ggml_tensor * ggml_silu_back(
  2128. struct ggml_context * ctx,
  2129. struct ggml_tensor * a,
  2130. struct ggml_tensor * b) {
  2131. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2132. result->op = GGML_OP_SILU_BACK;
  2133. result->src[0] = a;
  2134. result->src[1] = b;
  2135. return result;
  2136. }
  2137. // ggml hardswish
  2138. struct ggml_tensor * ggml_hardswish(
  2139. struct ggml_context * ctx,
  2140. struct ggml_tensor * a) {
  2141. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
  2142. }
  2143. // ggml hardsigmoid
  2144. struct ggml_tensor * ggml_hardsigmoid(
  2145. struct ggml_context * ctx,
  2146. struct ggml_tensor * a) {
  2147. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
  2148. }
  2149. // ggml exp
  2150. struct ggml_tensor * ggml_exp(
  2151. struct ggml_context * ctx,
  2152. struct ggml_tensor * a) {
  2153. return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
  2154. }
  2155. struct ggml_tensor * ggml_exp_inplace(
  2156. struct ggml_context * ctx,
  2157. struct ggml_tensor * a) {
  2158. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
  2159. }
  2160. // ggml_norm
  2161. static struct ggml_tensor * ggml_norm_impl(
  2162. struct ggml_context * ctx,
  2163. struct ggml_tensor * a,
  2164. float eps,
  2165. bool inplace) {
  2166. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2167. ggml_set_op_params(result, &eps, sizeof(eps));
  2168. result->op = GGML_OP_NORM;
  2169. result->src[0] = a;
  2170. return result;
  2171. }
  2172. struct ggml_tensor * ggml_norm(
  2173. struct ggml_context * ctx,
  2174. struct ggml_tensor * a,
  2175. float eps) {
  2176. return ggml_norm_impl(ctx, a, eps, false);
  2177. }
  2178. struct ggml_tensor * ggml_norm_inplace(
  2179. struct ggml_context * ctx,
  2180. struct ggml_tensor * a,
  2181. float eps) {
  2182. return ggml_norm_impl(ctx, a, eps, true);
  2183. }
  2184. // ggml_rms_norm
  2185. static struct ggml_tensor * ggml_rms_norm_impl(
  2186. struct ggml_context * ctx,
  2187. struct ggml_tensor * a,
  2188. float eps,
  2189. bool inplace) {
  2190. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2191. ggml_set_op_params(result, &eps, sizeof(eps));
  2192. result->op = GGML_OP_RMS_NORM;
  2193. result->src[0] = a;
  2194. return result;
  2195. }
  2196. struct ggml_tensor * ggml_rms_norm(
  2197. struct ggml_context * ctx,
  2198. struct ggml_tensor * a,
  2199. float eps) {
  2200. return ggml_rms_norm_impl(ctx, a, eps, false);
  2201. }
  2202. struct ggml_tensor * ggml_rms_norm_inplace(
  2203. struct ggml_context * ctx,
  2204. struct ggml_tensor * a,
  2205. float eps) {
  2206. return ggml_rms_norm_impl(ctx, a, eps, true);
  2207. }
  2208. // ggml_rms_norm_back
  2209. struct ggml_tensor * ggml_rms_norm_back(
  2210. struct ggml_context * ctx,
  2211. struct ggml_tensor * a,
  2212. struct ggml_tensor * b,
  2213. float eps) {
  2214. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2215. ggml_set_op_params(result, &eps, sizeof(eps));
  2216. result->op = GGML_OP_RMS_NORM_BACK;
  2217. result->src[0] = a;
  2218. result->src[1] = b;
  2219. return result;
  2220. }
  2221. // ggml_group_norm
  2222. static struct ggml_tensor * ggml_group_norm_impl(
  2223. struct ggml_context * ctx,
  2224. struct ggml_tensor * a,
  2225. int n_groups,
  2226. float eps,
  2227. bool inplace) {
  2228. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2229. ggml_set_op_params_i32(result, 0, n_groups);
  2230. ggml_set_op_params_f32(result, 1, eps);
  2231. result->op = GGML_OP_GROUP_NORM;
  2232. result->src[0] = a;
  2233. return result;
  2234. }
  2235. struct ggml_tensor * ggml_group_norm(
  2236. struct ggml_context * ctx,
  2237. struct ggml_tensor * a,
  2238. int n_groups,
  2239. float eps) {
  2240. return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
  2241. }
  2242. struct ggml_tensor * ggml_group_norm_inplace(
  2243. struct ggml_context * ctx,
  2244. struct ggml_tensor * a,
  2245. int n_groups,
  2246. float eps) {
  2247. return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
  2248. }
  2249. // ggml_mul_mat
  2250. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2251. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2252. return (t0->ne[0] == t1->ne[0]) &&
  2253. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2254. (t1->ne[3]%t0->ne[3] == 0);
  2255. }
  2256. struct ggml_tensor * ggml_mul_mat(
  2257. struct ggml_context * ctx,
  2258. struct ggml_tensor * a,
  2259. struct ggml_tensor * b) {
  2260. GGML_ASSERT(ggml_can_mul_mat(a, b));
  2261. GGML_ASSERT(!ggml_is_transposed(a));
  2262. const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
  2263. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2264. result->op = GGML_OP_MUL_MAT;
  2265. result->src[0] = a;
  2266. result->src[1] = b;
  2267. return result;
  2268. }
  2269. void ggml_mul_mat_set_prec(
  2270. struct ggml_tensor * a,
  2271. enum ggml_prec prec) {
  2272. GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
  2273. const int32_t prec_i32 = (int32_t) prec;
  2274. ggml_set_op_params_i32(a, 0, prec_i32);
  2275. }
  2276. // ggml_mul_mat_id
  2277. /*
  2278. c = ggml_mul_mat_id(ctx, as, b, ids);
  2279. as -> [cols, rows, n_expert]
  2280. ids -> [n_experts_used, n_tokens] (i32)
  2281. b -> [cols, n_expert_used, n_tokens]
  2282. c -> [rows, n_expert_used, n_tokens]
  2283. in b, n_experts_used can be broadcasted to match the n_expert_used of ids
  2284. c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
  2285. */
  2286. struct ggml_tensor * ggml_mul_mat_id(
  2287. struct ggml_context * ctx,
  2288. struct ggml_tensor * as,
  2289. struct ggml_tensor * b,
  2290. struct ggml_tensor * ids) {
  2291. GGML_ASSERT(!ggml_is_transposed(as));
  2292. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  2293. GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
  2294. GGML_ASSERT(b->ne[3] == 1); // b is 3d
  2295. GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
  2296. GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
  2297. GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
  2298. GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
  2299. const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
  2300. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2301. result->op = GGML_OP_MUL_MAT_ID;
  2302. result->src[0] = as;
  2303. result->src[1] = b;
  2304. result->src[2] = ids;
  2305. return result;
  2306. }
  2307. // ggml_out_prod
  2308. static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2309. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2310. return (t0->ne[1] == t1->ne[1]) &&
  2311. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2312. (t1->ne[3]%t0->ne[3] == 0);
  2313. }
  2314. struct ggml_tensor * ggml_out_prod(
  2315. struct ggml_context * ctx,
  2316. struct ggml_tensor * a,
  2317. struct ggml_tensor * b) {
  2318. GGML_ASSERT(ggml_can_out_prod(a, b));
  2319. GGML_ASSERT(!ggml_is_transposed(a));
  2320. // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
  2321. const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
  2322. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2323. result->op = GGML_OP_OUT_PROD;
  2324. result->src[0] = a;
  2325. result->src[1] = b;
  2326. return result;
  2327. }
  2328. // ggml_scale
  2329. static struct ggml_tensor * ggml_scale_impl(
  2330. struct ggml_context * ctx,
  2331. struct ggml_tensor * a,
  2332. float s,
  2333. bool inplace) {
  2334. GGML_ASSERT(ggml_is_padded_1d(a));
  2335. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2336. ggml_set_op_params(result, &s, sizeof(s));
  2337. result->op = GGML_OP_SCALE;
  2338. result->src[0] = a;
  2339. return result;
  2340. }
  2341. struct ggml_tensor * ggml_scale(
  2342. struct ggml_context * ctx,
  2343. struct ggml_tensor * a,
  2344. float s) {
  2345. return ggml_scale_impl(ctx, a, s, false);
  2346. }
  2347. struct ggml_tensor * ggml_scale_inplace(
  2348. struct ggml_context * ctx,
  2349. struct ggml_tensor * a,
  2350. float s) {
  2351. return ggml_scale_impl(ctx, a, s, true);
  2352. }
  2353. // ggml_set
  2354. static struct ggml_tensor * ggml_set_impl(
  2355. struct ggml_context * ctx,
  2356. struct ggml_tensor * a,
  2357. struct ggml_tensor * b,
  2358. size_t nb1,
  2359. size_t nb2,
  2360. size_t nb3,
  2361. size_t offset,
  2362. bool inplace) {
  2363. GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
  2364. // make a view of the destination
  2365. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2366. GGML_ASSERT(offset < (size_t)(1 << 30));
  2367. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  2368. ggml_set_op_params(result, params, sizeof(params));
  2369. result->op = GGML_OP_SET;
  2370. result->src[0] = a;
  2371. result->src[1] = b;
  2372. return result;
  2373. }
  2374. struct ggml_tensor * ggml_set(
  2375. struct ggml_context * ctx,
  2376. struct ggml_tensor * a,
  2377. struct ggml_tensor * b,
  2378. size_t nb1,
  2379. size_t nb2,
  2380. size_t nb3,
  2381. size_t offset) {
  2382. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  2383. }
  2384. struct ggml_tensor * ggml_set_inplace(
  2385. struct ggml_context * ctx,
  2386. struct ggml_tensor * a,
  2387. struct ggml_tensor * b,
  2388. size_t nb1,
  2389. size_t nb2,
  2390. size_t nb3,
  2391. size_t offset) {
  2392. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  2393. }
  2394. struct ggml_tensor * ggml_set_1d(
  2395. struct ggml_context * ctx,
  2396. struct ggml_tensor * a,
  2397. struct ggml_tensor * b,
  2398. size_t offset) {
  2399. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
  2400. }
  2401. struct ggml_tensor * ggml_set_1d_inplace(
  2402. struct ggml_context * ctx,
  2403. struct ggml_tensor * a,
  2404. struct ggml_tensor * b,
  2405. size_t offset) {
  2406. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
  2407. }
  2408. struct ggml_tensor * ggml_set_2d(
  2409. struct ggml_context * ctx,
  2410. struct ggml_tensor * a,
  2411. struct ggml_tensor * b,
  2412. size_t nb1,
  2413. size_t offset) {
  2414. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
  2415. }
  2416. struct ggml_tensor * ggml_set_2d_inplace(
  2417. struct ggml_context * ctx,
  2418. struct ggml_tensor * a,
  2419. struct ggml_tensor * b,
  2420. size_t nb1,
  2421. size_t offset) {
  2422. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
  2423. }
  2424. // ggml_cpy
  2425. static struct ggml_tensor * ggml_cpy_impl(
  2426. struct ggml_context * ctx,
  2427. struct ggml_tensor * a,
  2428. struct ggml_tensor * b) {
  2429. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2430. // make a view of the destination
  2431. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  2432. if (strlen(b->name) > 0) {
  2433. ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
  2434. } else {
  2435. ggml_format_name(result, "%s (copy)", a->name);
  2436. }
  2437. result->op = GGML_OP_CPY;
  2438. result->src[0] = a;
  2439. result->src[1] = b;
  2440. return result;
  2441. }
  2442. struct ggml_tensor * ggml_cpy(
  2443. struct ggml_context * ctx,
  2444. struct ggml_tensor * a,
  2445. struct ggml_tensor * b) {
  2446. return ggml_cpy_impl(ctx, a, b);
  2447. }
  2448. struct ggml_tensor * ggml_cast(
  2449. struct ggml_context * ctx,
  2450. struct ggml_tensor * a,
  2451. enum ggml_type type) {
  2452. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  2453. ggml_format_name(result, "%s (copy)", a->name);
  2454. result->op = GGML_OP_CPY;
  2455. result->src[0] = a;
  2456. result->src[1] = result;
  2457. return result;
  2458. }
  2459. // ggml_cont
  2460. static struct ggml_tensor * ggml_cont_impl(
  2461. struct ggml_context * ctx,
  2462. struct ggml_tensor * a) {
  2463. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2464. ggml_format_name(result, "%s (cont)", a->name);
  2465. result->op = GGML_OP_CONT;
  2466. result->src[0] = a;
  2467. return result;
  2468. }
  2469. struct ggml_tensor * ggml_cont(
  2470. struct ggml_context * ctx,
  2471. struct ggml_tensor * a) {
  2472. return ggml_cont_impl(ctx, a);
  2473. }
  2474. // make contiguous, with new shape
  2475. GGML_API struct ggml_tensor * ggml_cont_1d(
  2476. struct ggml_context * ctx,
  2477. struct ggml_tensor * a,
  2478. int64_t ne0) {
  2479. return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
  2480. }
  2481. GGML_API struct ggml_tensor * ggml_cont_2d(
  2482. struct ggml_context * ctx,
  2483. struct ggml_tensor * a,
  2484. int64_t ne0,
  2485. int64_t ne1) {
  2486. return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
  2487. }
  2488. GGML_API struct ggml_tensor * ggml_cont_3d(
  2489. struct ggml_context * ctx,
  2490. struct ggml_tensor * a,
  2491. int64_t ne0,
  2492. int64_t ne1,
  2493. int64_t ne2) {
  2494. return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
  2495. }
  2496. struct ggml_tensor * ggml_cont_4d(
  2497. struct ggml_context * ctx,
  2498. struct ggml_tensor * a,
  2499. int64_t ne0,
  2500. int64_t ne1,
  2501. int64_t ne2,
  2502. int64_t ne3) {
  2503. GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
  2504. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  2505. ggml_format_name(result, "%s (cont)", a->name);
  2506. result->op = GGML_OP_CONT;
  2507. result->src[0] = a;
  2508. return result;
  2509. }
  2510. // ggml_reshape
  2511. struct ggml_tensor * ggml_reshape(
  2512. struct ggml_context * ctx,
  2513. struct ggml_tensor * a,
  2514. struct ggml_tensor * b) {
  2515. GGML_ASSERT(ggml_is_contiguous(a));
  2516. // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
  2517. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2518. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->ne, a, 0);
  2519. ggml_format_name(result, "%s (reshaped)", a->name);
  2520. result->op = GGML_OP_RESHAPE;
  2521. result->src[0] = a;
  2522. return result;
  2523. }
  2524. struct ggml_tensor * ggml_reshape_1d(
  2525. struct ggml_context * ctx,
  2526. struct ggml_tensor * a,
  2527. int64_t ne0) {
  2528. GGML_ASSERT(ggml_is_contiguous(a));
  2529. GGML_ASSERT(ggml_nelements(a) == ne0);
  2530. const int64_t ne[1] = { ne0 };
  2531. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
  2532. ggml_format_name(result, "%s (reshaped)", a->name);
  2533. result->op = GGML_OP_RESHAPE;
  2534. result->src[0] = a;
  2535. return result;
  2536. }
  2537. struct ggml_tensor * ggml_reshape_2d(
  2538. struct ggml_context * ctx,
  2539. struct ggml_tensor * a,
  2540. int64_t ne0,
  2541. int64_t ne1) {
  2542. GGML_ASSERT(ggml_is_contiguous(a));
  2543. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  2544. const int64_t ne[2] = { ne0, ne1 };
  2545. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
  2546. ggml_format_name(result, "%s (reshaped)", a->name);
  2547. result->op = GGML_OP_RESHAPE;
  2548. result->src[0] = a;
  2549. return result;
  2550. }
  2551. struct ggml_tensor * ggml_reshape_3d(
  2552. struct ggml_context * ctx,
  2553. struct ggml_tensor * a,
  2554. int64_t ne0,
  2555. int64_t ne1,
  2556. int64_t ne2) {
  2557. GGML_ASSERT(ggml_is_contiguous(a));
  2558. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  2559. const int64_t ne[3] = { ne0, ne1, ne2 };
  2560. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
  2561. ggml_format_name(result, "%s (reshaped)", a->name);
  2562. result->op = GGML_OP_RESHAPE;
  2563. result->src[0] = a;
  2564. return result;
  2565. }
  2566. struct ggml_tensor * ggml_reshape_4d(
  2567. struct ggml_context * ctx,
  2568. struct ggml_tensor * a,
  2569. int64_t ne0,
  2570. int64_t ne1,
  2571. int64_t ne2,
  2572. int64_t ne3) {
  2573. GGML_ASSERT(ggml_is_contiguous(a));
  2574. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
  2575. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2576. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
  2577. ggml_format_name(result, "%s (reshaped)", a->name);
  2578. result->op = GGML_OP_RESHAPE;
  2579. result->src[0] = a;
  2580. return result;
  2581. }
  2582. static struct ggml_tensor * ggml_view_impl(
  2583. struct ggml_context * ctx,
  2584. struct ggml_tensor * a,
  2585. int n_dims,
  2586. const int64_t * ne,
  2587. size_t offset) {
  2588. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
  2589. ggml_format_name(result, "%s (view)", a->name);
  2590. ggml_set_op_params(result, &offset, sizeof(offset));
  2591. result->op = GGML_OP_VIEW;
  2592. result->src[0] = a;
  2593. return result;
  2594. }
  2595. // ggml_view_1d
  2596. struct ggml_tensor * ggml_view_1d(
  2597. struct ggml_context * ctx,
  2598. struct ggml_tensor * a,
  2599. int64_t ne0,
  2600. size_t offset) {
  2601. struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
  2602. return result;
  2603. }
  2604. // ggml_view_2d
  2605. struct ggml_tensor * ggml_view_2d(
  2606. struct ggml_context * ctx,
  2607. struct ggml_tensor * a,
  2608. int64_t ne0,
  2609. int64_t ne1,
  2610. size_t nb1,
  2611. size_t offset) {
  2612. const int64_t ne[2] = { ne0, ne1 };
  2613. struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
  2614. result->nb[1] = nb1;
  2615. result->nb[2] = result->nb[1]*ne1;
  2616. result->nb[3] = result->nb[2];
  2617. return result;
  2618. }
  2619. // ggml_view_3d
  2620. struct ggml_tensor * ggml_view_3d(
  2621. struct ggml_context * ctx,
  2622. struct ggml_tensor * a,
  2623. int64_t ne0,
  2624. int64_t ne1,
  2625. int64_t ne2,
  2626. size_t nb1,
  2627. size_t nb2,
  2628. size_t offset) {
  2629. const int64_t ne[3] = { ne0, ne1, ne2 };
  2630. struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
  2631. result->nb[1] = nb1;
  2632. result->nb[2] = nb2;
  2633. result->nb[3] = result->nb[2]*ne2;
  2634. return result;
  2635. }
  2636. // ggml_view_4d
  2637. struct ggml_tensor * ggml_view_4d(
  2638. struct ggml_context * ctx,
  2639. struct ggml_tensor * a,
  2640. int64_t ne0,
  2641. int64_t ne1,
  2642. int64_t ne2,
  2643. int64_t ne3,
  2644. size_t nb1,
  2645. size_t nb2,
  2646. size_t nb3,
  2647. size_t offset) {
  2648. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2649. struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
  2650. result->nb[1] = nb1;
  2651. result->nb[2] = nb2;
  2652. result->nb[3] = nb3;
  2653. return result;
  2654. }
  2655. // ggml_permute
  2656. struct ggml_tensor * ggml_permute(
  2657. struct ggml_context * ctx,
  2658. struct ggml_tensor * a,
  2659. int axis0,
  2660. int axis1,
  2661. int axis2,
  2662. int axis3) {
  2663. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  2664. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  2665. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  2666. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  2667. GGML_ASSERT(axis0 != axis1);
  2668. GGML_ASSERT(axis0 != axis2);
  2669. GGML_ASSERT(axis0 != axis3);
  2670. GGML_ASSERT(axis1 != axis2);
  2671. GGML_ASSERT(axis1 != axis3);
  2672. GGML_ASSERT(axis2 != axis3);
  2673. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2674. ggml_format_name(result, "%s (permuted)", a->name);
  2675. int ne[GGML_MAX_DIMS];
  2676. int nb[GGML_MAX_DIMS];
  2677. ne[axis0] = a->ne[0];
  2678. ne[axis1] = a->ne[1];
  2679. ne[axis2] = a->ne[2];
  2680. ne[axis3] = a->ne[3];
  2681. nb[axis0] = a->nb[0];
  2682. nb[axis1] = a->nb[1];
  2683. nb[axis2] = a->nb[2];
  2684. nb[axis3] = a->nb[3];
  2685. result->ne[0] = ne[0];
  2686. result->ne[1] = ne[1];
  2687. result->ne[2] = ne[2];
  2688. result->ne[3] = ne[3];
  2689. result->nb[0] = nb[0];
  2690. result->nb[1] = nb[1];
  2691. result->nb[2] = nb[2];
  2692. result->nb[3] = nb[3];
  2693. result->op = GGML_OP_PERMUTE;
  2694. result->src[0] = a;
  2695. int32_t params[] = { axis0, axis1, axis2, axis3 };
  2696. ggml_set_op_params(result, params, sizeof(params));
  2697. return result;
  2698. }
  2699. // ggml_transpose
  2700. struct ggml_tensor * ggml_transpose(
  2701. struct ggml_context * ctx,
  2702. struct ggml_tensor * a) {
  2703. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2704. ggml_format_name(result, "%s (transposed)", a->name);
  2705. result->ne[0] = a->ne[1];
  2706. result->ne[1] = a->ne[0];
  2707. result->nb[0] = a->nb[1];
  2708. result->nb[1] = a->nb[0];
  2709. result->op = GGML_OP_TRANSPOSE;
  2710. result->src[0] = a;
  2711. return result;
  2712. }
  2713. // ggml_get_rows
  2714. struct ggml_tensor * ggml_get_rows(
  2715. struct ggml_context * ctx,
  2716. struct ggml_tensor * a,
  2717. struct ggml_tensor * b) {
  2718. GGML_ASSERT(a->ne[2] == b->ne[1]);
  2719. GGML_ASSERT(b->ne[3] == 1);
  2720. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2721. // TODO: implement non F32 return
  2722. enum ggml_type type = GGML_TYPE_F32;
  2723. if (a->type == GGML_TYPE_I32) {
  2724. type = a->type;
  2725. }
  2726. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
  2727. result->op = GGML_OP_GET_ROWS;
  2728. result->src[0] = a;
  2729. result->src[1] = b;
  2730. return result;
  2731. }
  2732. // ggml_get_rows_back
  2733. struct ggml_tensor * ggml_get_rows_back(
  2734. struct ggml_context * ctx,
  2735. struct ggml_tensor * a,
  2736. struct ggml_tensor * b,
  2737. struct ggml_tensor * c) {
  2738. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  2739. GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
  2740. // TODO: implement non F32 return
  2741. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  2742. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
  2743. result->op = GGML_OP_GET_ROWS_BACK;
  2744. result->src[0] = a;
  2745. result->src[1] = b;
  2746. return result;
  2747. }
  2748. // ggml_diag
  2749. struct ggml_tensor * ggml_diag(
  2750. struct ggml_context * ctx,
  2751. struct ggml_tensor * a) {
  2752. GGML_ASSERT(a->ne[1] == 1);
  2753. const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
  2754. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
  2755. result->op = GGML_OP_DIAG;
  2756. result->src[0] = a;
  2757. return result;
  2758. }
  2759. // ggml_diag_mask_inf
  2760. static struct ggml_tensor * ggml_diag_mask_inf_impl(
  2761. struct ggml_context * ctx,
  2762. struct ggml_tensor * a,
  2763. int n_past,
  2764. bool inplace) {
  2765. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2766. int32_t params[] = { n_past };
  2767. ggml_set_op_params(result, params, sizeof(params));
  2768. result->op = GGML_OP_DIAG_MASK_INF;
  2769. result->src[0] = a;
  2770. return result;
  2771. }
  2772. struct ggml_tensor * ggml_diag_mask_inf(
  2773. struct ggml_context * ctx,
  2774. struct ggml_tensor * a,
  2775. int n_past) {
  2776. return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
  2777. }
  2778. struct ggml_tensor * ggml_diag_mask_inf_inplace(
  2779. struct ggml_context * ctx,
  2780. struct ggml_tensor * a,
  2781. int n_past) {
  2782. return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
  2783. }
  2784. // ggml_diag_mask_zero
  2785. static struct ggml_tensor * ggml_diag_mask_zero_impl(
  2786. struct ggml_context * ctx,
  2787. struct ggml_tensor * a,
  2788. int n_past,
  2789. bool inplace) {
  2790. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2791. int32_t params[] = { n_past };
  2792. ggml_set_op_params(result, params, sizeof(params));
  2793. result->op = GGML_OP_DIAG_MASK_ZERO;
  2794. result->src[0] = a;
  2795. return result;
  2796. }
  2797. struct ggml_tensor * ggml_diag_mask_zero(
  2798. struct ggml_context * ctx,
  2799. struct ggml_tensor * a,
  2800. int n_past) {
  2801. return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
  2802. }
  2803. struct ggml_tensor * ggml_diag_mask_zero_inplace(
  2804. struct ggml_context * ctx,
  2805. struct ggml_tensor * a,
  2806. int n_past) {
  2807. return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
  2808. }
  2809. // ggml_soft_max
  2810. static struct ggml_tensor * ggml_soft_max_impl(
  2811. struct ggml_context * ctx,
  2812. struct ggml_tensor * a,
  2813. struct ggml_tensor * mask,
  2814. float scale,
  2815. float max_bias,
  2816. bool inplace) {
  2817. GGML_ASSERT(ggml_is_contiguous(a));
  2818. if (mask) {
  2819. GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
  2820. GGML_ASSERT(ggml_is_contiguous(mask));
  2821. GGML_ASSERT(ggml_is_matrix(mask));
  2822. GGML_ASSERT(mask->ne[0] == a->ne[0]);
  2823. GGML_ASSERT(mask->ne[1] >= a->ne[1]);
  2824. }
  2825. if (max_bias > 0.0f) {
  2826. GGML_ASSERT(mask);
  2827. }
  2828. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2829. float params[] = { scale, max_bias };
  2830. ggml_set_op_params(result, params, sizeof(params));
  2831. result->op = GGML_OP_SOFT_MAX;
  2832. result->src[0] = a;
  2833. result->src[1] = mask;
  2834. return result;
  2835. }
  2836. struct ggml_tensor * ggml_soft_max(
  2837. struct ggml_context * ctx,
  2838. struct ggml_tensor * a) {
  2839. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
  2840. }
  2841. struct ggml_tensor * ggml_soft_max_inplace(
  2842. struct ggml_context * ctx,
  2843. struct ggml_tensor * a) {
  2844. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
  2845. }
  2846. struct ggml_tensor * ggml_soft_max_ext(
  2847. struct ggml_context * ctx,
  2848. struct ggml_tensor * a,
  2849. struct ggml_tensor * mask,
  2850. float scale,
  2851. float max_bias) {
  2852. return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
  2853. }
  2854. // ggml_soft_max_back
  2855. static struct ggml_tensor * ggml_soft_max_back_impl(
  2856. struct ggml_context * ctx,
  2857. struct ggml_tensor * a,
  2858. struct ggml_tensor * b,
  2859. bool inplace) {
  2860. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2861. result->op = GGML_OP_SOFT_MAX_BACK;
  2862. result->src[0] = a;
  2863. result->src[1] = b;
  2864. return result;
  2865. }
  2866. struct ggml_tensor * ggml_soft_max_back(
  2867. struct ggml_context * ctx,
  2868. struct ggml_tensor * a,
  2869. struct ggml_tensor * b) {
  2870. return ggml_soft_max_back_impl(ctx, a, b, false);
  2871. }
  2872. struct ggml_tensor * ggml_soft_max_back_inplace(
  2873. struct ggml_context * ctx,
  2874. struct ggml_tensor * a,
  2875. struct ggml_tensor * b) {
  2876. return ggml_soft_max_back_impl(ctx, a, b, true);
  2877. }
  2878. // ggml_rope
  2879. static struct ggml_tensor * ggml_rope_impl(
  2880. struct ggml_context * ctx,
  2881. struct ggml_tensor * a,
  2882. struct ggml_tensor * b,
  2883. struct ggml_tensor * c,
  2884. int n_dims,
  2885. int mode,
  2886. int n_ctx_orig,
  2887. float freq_base,
  2888. float freq_scale,
  2889. float ext_factor,
  2890. float attn_factor,
  2891. float beta_fast,
  2892. float beta_slow,
  2893. bool inplace) {
  2894. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2895. GGML_ASSERT(ggml_is_vector(b));
  2896. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2897. GGML_ASSERT(a->ne[2] == b->ne[0]);
  2898. if (c) {
  2899. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2900. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2901. }
  2902. int sections[4] = {0, 0, 0, 0};
  2903. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2904. int32_t params[15] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2905. memcpy(params + 5, &freq_base, sizeof(float));
  2906. memcpy(params + 6, &freq_scale, sizeof(float));
  2907. memcpy(params + 7, &ext_factor, sizeof(float));
  2908. memcpy(params + 8, &attn_factor, sizeof(float));
  2909. memcpy(params + 9, &beta_fast, sizeof(float));
  2910. memcpy(params + 10, &beta_slow, sizeof(float));
  2911. memcpy(params + 11, &sections, sizeof(int)*4);
  2912. ggml_set_op_params(result, params, sizeof(params));
  2913. result->op = GGML_OP_ROPE;
  2914. result->src[0] = a;
  2915. result->src[1] = b;
  2916. result->src[2] = c;
  2917. return result;
  2918. }
  2919. struct ggml_tensor * ggml_rope(
  2920. struct ggml_context * ctx,
  2921. struct ggml_tensor * a,
  2922. struct ggml_tensor * b,
  2923. int n_dims,
  2924. int mode) {
  2925. return ggml_rope_impl(
  2926. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
  2927. );
  2928. }
  2929. struct ggml_tensor * ggml_rope_multi(
  2930. struct ggml_context * ctx,
  2931. struct ggml_tensor * a,
  2932. struct ggml_tensor * b,
  2933. struct ggml_tensor * c,
  2934. int n_dims,
  2935. int sections[4],
  2936. int mode,
  2937. int n_ctx_orig,
  2938. float freq_base,
  2939. float freq_scale,
  2940. float ext_factor,
  2941. float attn_factor,
  2942. float beta_fast,
  2943. float beta_slow) {
  2944. // Multimodal Rotary Position Embedding
  2945. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2946. GGML_ASSERT(ggml_is_vector(b));
  2947. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2948. GGML_ASSERT(a->ne[2] * 4 == b->ne[0]); // mrope expecting 4 position ids per token
  2949. if (c) {
  2950. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2951. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2952. }
  2953. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2954. int32_t params[11 + 4] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2955. memcpy(params + 5, &freq_base, sizeof(float));
  2956. memcpy(params + 6, &freq_scale, sizeof(float));
  2957. memcpy(params + 7, &ext_factor, sizeof(float));
  2958. memcpy(params + 8, &attn_factor, sizeof(float));
  2959. memcpy(params + 9, &beta_fast, sizeof(float));
  2960. memcpy(params + 10, &beta_slow, sizeof(float));
  2961. memcpy(&params[11], sections, sizeof(int)*4);
  2962. ggml_set_op_params(result, params, sizeof(params));
  2963. result->op = GGML_OP_ROPE;
  2964. result->src[0] = a;
  2965. result->src[1] = b;
  2966. result->src[2] = c;
  2967. return result;
  2968. }
  2969. struct ggml_tensor * ggml_rope_inplace(
  2970. struct ggml_context * ctx,
  2971. struct ggml_tensor * a,
  2972. struct ggml_tensor * b,
  2973. int n_dims,
  2974. int mode) {
  2975. return ggml_rope_impl(
  2976. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
  2977. );
  2978. }
  2979. struct ggml_tensor * ggml_rope_ext(
  2980. struct ggml_context * ctx,
  2981. struct ggml_tensor * a,
  2982. struct ggml_tensor * b,
  2983. struct ggml_tensor * c,
  2984. int n_dims,
  2985. int mode,
  2986. int n_ctx_orig,
  2987. float freq_base,
  2988. float freq_scale,
  2989. float ext_factor,
  2990. float attn_factor,
  2991. float beta_fast,
  2992. float beta_slow) {
  2993. return ggml_rope_impl(
  2994. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  2995. ext_factor, attn_factor, beta_fast, beta_slow, false
  2996. );
  2997. }
  2998. struct ggml_tensor * ggml_rope_ext_inplace(
  2999. struct ggml_context * ctx,
  3000. struct ggml_tensor * a,
  3001. struct ggml_tensor * b,
  3002. struct ggml_tensor * c,
  3003. int n_dims,
  3004. int mode,
  3005. int n_ctx_orig,
  3006. float freq_base,
  3007. float freq_scale,
  3008. float ext_factor,
  3009. float attn_factor,
  3010. float beta_fast,
  3011. float beta_slow) {
  3012. return ggml_rope_impl(
  3013. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3014. ext_factor, attn_factor, beta_fast, beta_slow, true
  3015. );
  3016. }
  3017. struct ggml_tensor * ggml_rope_custom(
  3018. struct ggml_context * ctx,
  3019. struct ggml_tensor * a,
  3020. struct ggml_tensor * b,
  3021. int n_dims,
  3022. int mode,
  3023. int n_ctx_orig,
  3024. float freq_base,
  3025. float freq_scale,
  3026. float ext_factor,
  3027. float attn_factor,
  3028. float beta_fast,
  3029. float beta_slow) {
  3030. return ggml_rope_impl(
  3031. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3032. ext_factor, attn_factor, beta_fast, beta_slow, false
  3033. );
  3034. }
  3035. struct ggml_tensor * ggml_rope_custom_inplace(
  3036. struct ggml_context * ctx,
  3037. struct ggml_tensor * a,
  3038. struct ggml_tensor * b,
  3039. int n_dims,
  3040. int mode,
  3041. int n_ctx_orig,
  3042. float freq_base,
  3043. float freq_scale,
  3044. float ext_factor,
  3045. float attn_factor,
  3046. float beta_fast,
  3047. float beta_slow) {
  3048. return ggml_rope_impl(
  3049. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3050. ext_factor, attn_factor, beta_fast, beta_slow, true
  3051. );
  3052. }
  3053. // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
  3054. // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
  3055. static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
  3056. return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
  3057. }
  3058. void ggml_rope_yarn_corr_dims(
  3059. int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
  3060. ) {
  3061. // start and end correction dims
  3062. float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
  3063. float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
  3064. dims[0] = MAX(0, start);
  3065. dims[1] = MIN(n_dims - 1, end);
  3066. }
  3067. // ggml_rope_back
  3068. struct ggml_tensor * ggml_rope_back(
  3069. struct ggml_context * ctx,
  3070. struct ggml_tensor * a,
  3071. struct ggml_tensor * b,
  3072. struct ggml_tensor * c,
  3073. int n_dims,
  3074. int mode,
  3075. int n_ctx_orig,
  3076. float freq_base,
  3077. float freq_scale,
  3078. float ext_factor,
  3079. float attn_factor,
  3080. float beta_fast,
  3081. float beta_slow) {
  3082. GGML_ASSERT(ggml_is_vector(b));
  3083. GGML_ASSERT(b->type == GGML_TYPE_I32);
  3084. GGML_ASSERT(a->ne[2] == b->ne[0]);
  3085. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  3086. int32_t params[11] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  3087. memcpy(params + 5, &freq_base, sizeof(float));
  3088. memcpy(params + 6, &freq_scale, sizeof(float));
  3089. memcpy(params + 7, &ext_factor, sizeof(float));
  3090. memcpy(params + 8, &attn_factor, sizeof(float));
  3091. memcpy(params + 9, &beta_fast, sizeof(float));
  3092. memcpy(params + 10, &beta_slow, sizeof(float));
  3093. ggml_set_op_params(result, params, sizeof(params));
  3094. result->op = GGML_OP_ROPE_BACK;
  3095. result->src[0] = a;
  3096. result->src[1] = b;
  3097. result->src[2] = c;
  3098. return result;
  3099. }
  3100. // ggml_clamp
  3101. struct ggml_tensor * ggml_clamp(
  3102. struct ggml_context * ctx,
  3103. struct ggml_tensor * a,
  3104. float min,
  3105. float max) {
  3106. // TODO: when implement backward, fix this:
  3107. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3108. float params[] = { min, max };
  3109. ggml_set_op_params(result, params, sizeof(params));
  3110. result->op = GGML_OP_CLAMP;
  3111. result->src[0] = a;
  3112. return result;
  3113. }
  3114. static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3115. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  3116. }
  3117. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  3118. // a: [OC,IC, KH, KW]
  3119. // b: [N, IC, IH, IW]
  3120. // result: [N, OH, OW, IC*KH*KW]
  3121. struct ggml_tensor * ggml_im2col(
  3122. struct ggml_context * ctx,
  3123. struct ggml_tensor * a,
  3124. struct ggml_tensor * b,
  3125. int s0,
  3126. int s1,
  3127. int p0,
  3128. int p1,
  3129. int d0,
  3130. int d1,
  3131. bool is_2D,
  3132. enum ggml_type dst_type) {
  3133. if (is_2D) {
  3134. GGML_ASSERT(a->ne[2] == b->ne[2]);
  3135. } else {
  3136. //GGML_ASSERT(b->ne[1] % a->ne[1] == 0);
  3137. GGML_ASSERT(b->ne[1] == a->ne[1]);
  3138. GGML_ASSERT(b->ne[3] == 1);
  3139. }
  3140. const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
  3141. const int64_t OW = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
  3142. GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
  3143. GGML_ASSERT((OW > 0) && "b too small compared to a");
  3144. const int64_t ne[4] = {
  3145. is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
  3146. OW,
  3147. is_2D ? OH : b->ne[2],
  3148. is_2D ? b->ne[3] : 1,
  3149. };
  3150. struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
  3151. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3152. ggml_set_op_params(result, params, sizeof(params));
  3153. result->op = GGML_OP_IM2COL;
  3154. result->src[0] = a;
  3155. result->src[1] = b;
  3156. return result;
  3157. }
  3158. struct ggml_tensor * ggml_im2col_back(
  3159. struct ggml_context * ctx,
  3160. struct ggml_tensor * a,
  3161. struct ggml_tensor * b,
  3162. int64_t * ne,
  3163. int s0,
  3164. int s1,
  3165. int p0,
  3166. int p1,
  3167. int d0,
  3168. int d1,
  3169. bool is_2D) {
  3170. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3171. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3172. ggml_set_op_params(result, params, sizeof(params));
  3173. result->op = GGML_OP_IM2COL_BACK;
  3174. result->src[0] = a;
  3175. result->src[1] = b;
  3176. return result;
  3177. }
  3178. // ggml_conv_1d
  3179. struct ggml_tensor * ggml_conv_1d(
  3180. struct ggml_context * ctx,
  3181. struct ggml_tensor * a,
  3182. struct ggml_tensor * b,
  3183. int s0,
  3184. int p0,
  3185. int d0) {
  3186. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16); // [N, OL, IC * K]
  3187. struct ggml_tensor * result =
  3188. ggml_mul_mat(ctx,
  3189. ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
  3190. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2])); // [OC,IC, K] => [OC, IC * K]
  3191. result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
  3192. return result;
  3193. }
  3194. // ggml_conv_1d_ph
  3195. struct ggml_tensor* ggml_conv_1d_ph(
  3196. struct ggml_context * ctx,
  3197. struct ggml_tensor * a,
  3198. struct ggml_tensor * b,
  3199. int s,
  3200. int d) {
  3201. return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
  3202. }
  3203. // ggml_conv_1d_dw
  3204. struct ggml_tensor * ggml_conv_1d_dw(
  3205. struct ggml_context * ctx,
  3206. struct ggml_tensor * a,
  3207. struct ggml_tensor * b,
  3208. int s0,
  3209. int p0,
  3210. int d0) {
  3211. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], 1, a->ne[1], a->ne[2]);
  3212. struct ggml_tensor * new_b = ggml_reshape_4d(ctx, b, b->ne[0], 1, b->ne[1], b->ne[2]);
  3213. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a, new_b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16);
  3214. struct ggml_tensor * result = ggml_mul_mat(ctx, im2col, a);
  3215. result = ggml_reshape_3d(ctx, result, b->ne[0], b->ne[1], 1);
  3216. return result;
  3217. }
  3218. // ggml_conv_1d_dw_ph
  3219. struct ggml_tensor * ggml_conv_1d_dw_ph(
  3220. struct ggml_context * ctx,
  3221. struct ggml_tensor * a,
  3222. struct ggml_tensor * b,
  3223. int s0,
  3224. int d0) {
  3225. return ggml_conv_1d_dw(ctx, a, b, s0, a->ne[0] / 2, d0);
  3226. }
  3227. // ggml_conv_transpose_1d
  3228. static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3229. return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
  3230. }
  3231. GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
  3232. struct ggml_context * ctx,
  3233. struct ggml_tensor * a,
  3234. struct ggml_tensor * b,
  3235. int s0,
  3236. int p0,
  3237. int d0) {
  3238. GGML_ASSERT(ggml_is_matrix(b));
  3239. GGML_ASSERT(a->ne[2] == b->ne[1]);
  3240. GGML_ASSERT(a->ne[3] == 1);
  3241. GGML_ASSERT(p0 == 0);
  3242. GGML_ASSERT(d0 == 1);
  3243. const int64_t ne[4] = {
  3244. ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
  3245. a->ne[1], b->ne[2], 1,
  3246. };
  3247. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3248. int32_t params[] = { s0, p0, d0 };
  3249. ggml_set_op_params(result, params, sizeof(params));
  3250. result->op = GGML_OP_CONV_TRANSPOSE_1D;
  3251. result->src[0] = a;
  3252. result->src[1] = b;
  3253. return result;
  3254. }
  3255. // ggml_conv_2d
  3256. // a: [OC,IC, KH, KW]
  3257. // b: [N, IC, IH, IW]
  3258. // result: [N, OC, OH, OW]
  3259. struct ggml_tensor * ggml_conv_2d(
  3260. struct ggml_context * ctx,
  3261. struct ggml_tensor * a,
  3262. struct ggml_tensor * b,
  3263. int s0,
  3264. int s1,
  3265. int p0,
  3266. int p1,
  3267. int d0,
  3268. int d1) {
  3269. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type); // [N, OH, OW, IC * KH * KW]
  3270. struct ggml_tensor * result =
  3271. ggml_mul_mat(ctx,
  3272. ggml_reshape_2d(ctx, im2col, im2col->ne[0], im2col->ne[3] * im2col->ne[2] * im2col->ne[1]), // [N, OH, OW, IC * KH * KW] => [N*OH*OW, IC * KH * KW]
  3273. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1] * a->ne[2]), a->ne[3])); // [OC,IC, KH, KW] => [OC, IC * KH * KW]
  3274. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
  3275. result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
  3276. return result;
  3277. }
  3278. // ggml_conv_2d_sk_p0
  3279. struct ggml_tensor * ggml_conv_2d_sk_p0(
  3280. struct ggml_context * ctx,
  3281. struct ggml_tensor * a,
  3282. struct ggml_tensor * b) {
  3283. return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
  3284. }
  3285. // ggml_conv_2d_s1_ph
  3286. struct ggml_tensor * ggml_conv_2d_s1_ph(
  3287. struct ggml_context * ctx,
  3288. struct ggml_tensor * a,
  3289. struct ggml_tensor * b) {
  3290. return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
  3291. }
  3292. // ggml_conv_2d_dw
  3293. struct ggml_tensor * ggml_conv_2d_dw(
  3294. struct ggml_context * ctx,
  3295. struct ggml_tensor * a,
  3296. struct ggml_tensor * b,
  3297. int s0,
  3298. int s1,
  3299. int p0,
  3300. int p1,
  3301. int d0,
  3302. int d1) {
  3303. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
  3304. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
  3305. ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
  3306. s0, s1, p0, p1, d0, d1, true, GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
  3307. struct ggml_tensor * new_b = ggml_reshape_4d(ctx, im2col, im2col->ne[0], im2col->ne[2] * im2col->ne[1], b->ne[2], b->ne[3]); // [N * IC, OH, OW, KH * KW] => [N, IC, OH * OW, KH * KW]
  3308. new_a = ggml_reshape_4d(ctx, new_a, (new_a->ne[0] * new_a->ne[1]), new_a->ne[2], new_a->ne[3], 1); // [OC,1, KH, KW] => [1, OC, 1, KH * KW]
  3309. struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
  3310. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
  3311. return result;
  3312. }
  3313. // ggml_conv_transpose_2d_p0
  3314. static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
  3315. return (ins - 1) * s - 2 * p + ks;
  3316. }
  3317. struct ggml_tensor * ggml_conv_transpose_2d_p0(
  3318. struct ggml_context * ctx,
  3319. struct ggml_tensor * a,
  3320. struct ggml_tensor * b,
  3321. int stride) {
  3322. GGML_ASSERT(a->ne[3] == b->ne[2]);
  3323. const int64_t ne[4] = {
  3324. ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
  3325. ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
  3326. a->ne[2], b->ne[3],
  3327. };
  3328. struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3329. ggml_set_op_params_i32(result, 0, stride);
  3330. result->op = GGML_OP_CONV_TRANSPOSE_2D;
  3331. result->src[0] = a;
  3332. result->src[1] = b;
  3333. return result;
  3334. }
  3335. // ggml_pool_*
  3336. static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
  3337. return (ins + 2 * p - ks) / s + 1;
  3338. }
  3339. // ggml_pool_1d
  3340. struct ggml_tensor * ggml_pool_1d(
  3341. struct ggml_context * ctx,
  3342. struct ggml_tensor * a,
  3343. enum ggml_op_pool op,
  3344. int k0,
  3345. int s0,
  3346. int p0) {
  3347. const int64_t ne[4] = {
  3348. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3349. a->ne[1],
  3350. a->ne[2],
  3351. a->ne[3],
  3352. };
  3353. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3354. int32_t params[] = { op, k0, s0, p0 };
  3355. ggml_set_op_params(result, params, sizeof(params));
  3356. result->op = GGML_OP_POOL_1D;
  3357. result->src[0] = a;
  3358. return result;
  3359. }
  3360. // ggml_pool_2d
  3361. struct ggml_tensor * ggml_pool_2d(
  3362. struct ggml_context * ctx,
  3363. struct ggml_tensor * a,
  3364. enum ggml_op_pool op,
  3365. int k0,
  3366. int k1,
  3367. int s0,
  3368. int s1,
  3369. float p0,
  3370. float p1) {
  3371. struct ggml_tensor * result;
  3372. const int64_t ne[4] = {
  3373. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3374. ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
  3375. a->ne[2],
  3376. a->ne[3],
  3377. };
  3378. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3379. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3380. ggml_set_op_params(result, params, sizeof(params));
  3381. result->op = GGML_OP_POOL_2D;
  3382. result->src[0] = a;
  3383. return result;
  3384. }
  3385. struct ggml_tensor * ggml_pool_2d_back(
  3386. struct ggml_context * ctx,
  3387. struct ggml_tensor * a,
  3388. struct ggml_tensor * af,
  3389. enum ggml_op_pool op,
  3390. int k0,
  3391. int k1,
  3392. int s0,
  3393. int s1,
  3394. float p0,
  3395. float p1) {
  3396. struct ggml_tensor * result;
  3397. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
  3398. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3399. ggml_set_op_params(result, params, sizeof(params));
  3400. result->op = GGML_OP_POOL_2D_BACK;
  3401. result->src[0] = a;
  3402. result->src[1] = af;
  3403. return result;
  3404. }
  3405. // ggml_upscale
  3406. static struct ggml_tensor * ggml_upscale_impl(
  3407. struct ggml_context * ctx,
  3408. struct ggml_tensor * a,
  3409. int ne0,
  3410. int ne1,
  3411. int ne2,
  3412. int ne3) {
  3413. GGML_ASSERT(a->ne[0] <= ne0);
  3414. GGML_ASSERT(a->ne[1] <= ne1);
  3415. GGML_ASSERT(a->ne[2] <= ne2);
  3416. GGML_ASSERT(a->ne[3] <= ne3);
  3417. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  3418. result->op = GGML_OP_UPSCALE;
  3419. result->src[0] = a;
  3420. return result;
  3421. }
  3422. struct ggml_tensor * ggml_upscale(
  3423. struct ggml_context * ctx,
  3424. struct ggml_tensor * a,
  3425. int scale_factor) {
  3426. return ggml_upscale_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3]);
  3427. }
  3428. struct ggml_tensor * ggml_upscale_ext(
  3429. struct ggml_context * ctx,
  3430. struct ggml_tensor * a,
  3431. int ne0,
  3432. int ne1,
  3433. int ne2,
  3434. int ne3) {
  3435. return ggml_upscale_impl(ctx, a, ne0, ne1, ne2, ne3);
  3436. }
  3437. // ggml_pad
  3438. struct ggml_tensor * ggml_pad(
  3439. struct ggml_context * ctx,
  3440. struct ggml_tensor * a,
  3441. int p0,
  3442. int p1,
  3443. int p2,
  3444. int p3) {
  3445. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3446. a->ne[0] + p0,
  3447. a->ne[1] + p1,
  3448. a->ne[2] + p2,
  3449. a->ne[3] + p3);
  3450. result->op = GGML_OP_PAD;
  3451. result->src[0] = a;
  3452. return result;
  3453. }
  3454. // ggml_pad_reflect_1d
  3455. struct ggml_tensor * ggml_pad_reflect_1d(
  3456. struct ggml_context * ctx,
  3457. struct ggml_tensor * a,
  3458. int p0,
  3459. int p1) {
  3460. GGML_ASSERT(p0 >= 0);
  3461. GGML_ASSERT(p1 >= 0);
  3462. GGML_ASSERT(p0 < a->ne[0]); // padding length on each size must be less than the
  3463. GGML_ASSERT(p1 < a->ne[0]); // existing length of the dimension being padded
  3464. GGML_ASSERT(ggml_is_contiguous(a));
  3465. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3466. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3467. a->ne[0] + p0 + p1,
  3468. a->ne[1],
  3469. a->ne[2],
  3470. a->ne[3]);
  3471. int32_t params[] = { p0, p1 };
  3472. ggml_set_op_params(result, params, sizeof(params));
  3473. result->op = GGML_OP_PAD_REFLECT_1D;
  3474. result->src[0] = a;
  3475. return result;
  3476. }
  3477. // ggml_unpad
  3478. struct ggml_tensor * ggml_unpad(
  3479. struct ggml_context * ctx,
  3480. struct ggml_tensor * a,
  3481. int p0, int p1, int p2, int p3) {
  3482. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3483. a->ne[0] - p0,
  3484. a->ne[1] - p1,
  3485. a->ne[2] - p2,
  3486. a->ne[3] - p3);
  3487. result->op = GGML_OP_UNPAD;
  3488. result->src[0] = a;
  3489. return result;
  3490. }
  3491. // ggml_arange
  3492. struct ggml_tensor * ggml_arange(
  3493. struct ggml_context * ctx,
  3494. float start,
  3495. float stop,
  3496. float step) {
  3497. GGML_ASSERT(stop > start);
  3498. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  3499. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
  3500. ggml_set_op_params_f32(result, 0, start);
  3501. ggml_set_op_params_f32(result, 1, stop);
  3502. ggml_set_op_params_f32(result, 2, step);
  3503. result->op = GGML_OP_ARANGE;
  3504. return result;
  3505. }
  3506. // ggml_timestep_embedding
  3507. struct ggml_tensor * ggml_timestep_embedding(
  3508. struct ggml_context * ctx,
  3509. struct ggml_tensor * timesteps,
  3510. int dim,
  3511. int max_period) {
  3512. int actual_dim = dim;
  3513. if (dim % 2 != 0) {
  3514. actual_dim = dim + 1;
  3515. }
  3516. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, actual_dim, timesteps->ne[0]);
  3517. ggml_set_op_params_i32(result, 0, dim);
  3518. ggml_set_op_params_i32(result, 1, max_period);
  3519. result->op = GGML_OP_TIMESTEP_EMBEDDING;
  3520. result->src[0] = timesteps;
  3521. return result;
  3522. }
  3523. // ggml_argsort
  3524. struct ggml_tensor * ggml_argsort(
  3525. struct ggml_context * ctx,
  3526. struct ggml_tensor * a,
  3527. enum ggml_sort_order order) {
  3528. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  3529. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
  3530. ggml_set_op_params_i32(result, 0, (int32_t) order);
  3531. result->op = GGML_OP_ARGSORT;
  3532. result->src[0] = a;
  3533. return result;
  3534. }
  3535. // ggml_top_k
  3536. struct ggml_tensor * ggml_top_k(
  3537. struct ggml_context * ctx,
  3538. struct ggml_tensor * a,
  3539. int k) {
  3540. GGML_ASSERT(a->ne[0] >= k);
  3541. struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
  3542. result = ggml_view_4d(ctx, result,
  3543. k, result->ne[1], result->ne[2], result->ne[3],
  3544. result->nb[1], result->nb[2], result->nb[3],
  3545. 0);
  3546. return result;
  3547. }
  3548. // ggml_flash_attn_ext
  3549. struct ggml_tensor * ggml_flash_attn_ext(
  3550. struct ggml_context * ctx,
  3551. struct ggml_tensor * q,
  3552. struct ggml_tensor * k,
  3553. struct ggml_tensor * v,
  3554. struct ggml_tensor * mask,
  3555. float scale,
  3556. float max_bias,
  3557. float logit_softcap) {
  3558. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3559. // TODO: check if vT can be multiplied by (k*qT)
  3560. if (mask) {
  3561. GGML_ASSERT(ggml_is_contiguous(mask));
  3562. GGML_ASSERT(mask->ne[2] == 1);
  3563. GGML_ASSERT(mask->ne[3] == 1);
  3564. GGML_ASSERT(mask->ne[1] >= GGML_PAD(q->ne[1], GGML_KQ_MASK_PAD) &&
  3565. "the Flash-Attention kernel requires the mask to be padded to GGML_KQ_MASK_PAD and at least n_queries big");
  3566. //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
  3567. }
  3568. if (max_bias > 0.0f) {
  3569. GGML_ASSERT(mask);
  3570. }
  3571. // permute(0, 2, 1, 3)
  3572. int64_t ne[4] = { q->ne[0], q->ne[2], q->ne[1], q->ne[3] };
  3573. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3574. float params[] = { scale, max_bias, logit_softcap };
  3575. ggml_set_op_params(result, params, sizeof(params));
  3576. result->op = GGML_OP_FLASH_ATTN_EXT;
  3577. result->src[0] = q;
  3578. result->src[1] = k;
  3579. result->src[2] = v;
  3580. result->src[3] = mask;
  3581. return result;
  3582. }
  3583. void ggml_flash_attn_ext_set_prec(
  3584. struct ggml_tensor * a,
  3585. enum ggml_prec prec) {
  3586. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3587. const int32_t prec_i32 = (int32_t) prec;
  3588. ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
  3589. }
  3590. enum ggml_prec ggml_flash_attn_ext_get_prec(
  3591. const struct ggml_tensor * a) {
  3592. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3593. const int32_t prec_i32 = ggml_get_op_params_i32(a, 3);
  3594. return (enum ggml_prec) prec_i32;
  3595. }
  3596. // ggml_flash_attn_back
  3597. struct ggml_tensor * ggml_flash_attn_back(
  3598. struct ggml_context * ctx,
  3599. struct ggml_tensor * q,
  3600. struct ggml_tensor * k,
  3601. struct ggml_tensor * v,
  3602. struct ggml_tensor * d,
  3603. bool masked) {
  3604. GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
  3605. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3606. // TODO: check if vT can be multiplied by (k*qT)
  3607. // d shape [D,N,ne2,ne3]
  3608. // q shape [D,N,ne2,ne3]
  3609. // k shape [D,M,kvne2,ne3]
  3610. // v shape [M,D,kvne2,ne3]
  3611. const int64_t D = q->ne[0];
  3612. const int64_t N = q->ne[1];
  3613. const int64_t M = k->ne[1];
  3614. const int64_t ne2 = q->ne[2];
  3615. const int64_t ne3 = q->ne[3];
  3616. const int64_t kvne2 = k->ne[2];
  3617. GGML_ASSERT(k->ne[0] == D);
  3618. GGML_ASSERT(v->ne[0] == M);
  3619. GGML_ASSERT(v->ne[1] == D);
  3620. GGML_ASSERT(d->ne[0] == D);
  3621. GGML_ASSERT(d->ne[1] == N);
  3622. GGML_ASSERT(k->ne[2] == kvne2);
  3623. GGML_ASSERT(k->ne[3] == ne3);
  3624. GGML_ASSERT(v->ne[2] == kvne2);
  3625. GGML_ASSERT(v->ne[3] == ne3);
  3626. GGML_ASSERT(d->ne[2] == ne2);
  3627. GGML_ASSERT(d->ne[3] == ne3);
  3628. GGML_ASSERT(ne2 % kvne2 == 0);
  3629. // store gradients of q, k and v as continuous tensors concatenated in result.
  3630. // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
  3631. const int64_t elem_q = ggml_nelements(q);
  3632. const int64_t elem_k = ggml_nelements(k);
  3633. const int64_t elem_v = ggml_nelements(v);
  3634. enum ggml_type result_type = GGML_TYPE_F32;
  3635. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  3636. const size_t tsize = ggml_type_size(result_type);
  3637. const size_t offs_q = 0;
  3638. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  3639. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  3640. const size_t end = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
  3641. const size_t nelements = (end + tsize - 1)/tsize;
  3642. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
  3643. int32_t masked_i = masked ? 1 : 0;
  3644. ggml_set_op_params(result, &masked_i, sizeof(masked_i));
  3645. result->op = GGML_OP_FLASH_ATTN_BACK;
  3646. result->src[0] = q;
  3647. result->src[1] = k;
  3648. result->src[2] = v;
  3649. result->src[3] = d;
  3650. return result;
  3651. }
  3652. // ggml_ssm_conv
  3653. struct ggml_tensor * ggml_ssm_conv(
  3654. struct ggml_context * ctx,
  3655. struct ggml_tensor * sx,
  3656. struct ggml_tensor * c) {
  3657. GGML_ASSERT(ggml_is_3d(sx));
  3658. GGML_ASSERT(ggml_is_matrix(c));
  3659. const int64_t d_conv = c->ne[0];
  3660. const int64_t d_inner = c->ne[1];
  3661. const int64_t n_t = sx->ne[0] - d_conv + 1; // tokens per sequence
  3662. const int64_t n_s = sx->ne[2];
  3663. // TODO: maybe support other strides than 1?
  3664. // FIXME: this is always true?
  3665. GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
  3666. GGML_ASSERT(sx->ne[1] == d_inner);
  3667. GGML_ASSERT(n_t >= 0);
  3668. struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
  3669. result->op = GGML_OP_SSM_CONV;
  3670. result->src[0] = sx;
  3671. result->src[1] = c;
  3672. return result;
  3673. }
  3674. // ggml_ssm_scan
  3675. struct ggml_tensor * ggml_ssm_scan(
  3676. struct ggml_context * ctx,
  3677. struct ggml_tensor * s,
  3678. struct ggml_tensor * x,
  3679. struct ggml_tensor * dt,
  3680. struct ggml_tensor * A,
  3681. struct ggml_tensor * B,
  3682. struct ggml_tensor * C) {
  3683. GGML_ASSERT(ggml_is_contiguous(s));
  3684. GGML_ASSERT(ggml_is_contiguous(x));
  3685. GGML_ASSERT(ggml_is_contiguous(dt));
  3686. GGML_ASSERT(ggml_is_contiguous(A));
  3687. GGML_ASSERT(ggml_is_matrix(A));
  3688. GGML_ASSERT(ggml_is_3d(B));
  3689. GGML_ASSERT(ggml_is_3d(s));
  3690. GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
  3691. GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
  3692. GGML_ASSERT(ggml_are_same_shape(x, dt));
  3693. GGML_ASSERT(ggml_are_same_shape(B, C));
  3694. {
  3695. const int64_t d_state = s->ne[0];
  3696. const int64_t d_inner = s->ne[1];
  3697. const int64_t n_seq_tokens = x->ne[1];
  3698. const int64_t n_seqs = x->ne[2];
  3699. GGML_ASSERT(s->ne[2] == n_seqs);
  3700. GGML_ASSERT(x->ne[0] == d_inner);
  3701. GGML_ASSERT(A->ne[0] == d_state);
  3702. GGML_ASSERT(A->ne[1] == d_inner);
  3703. GGML_ASSERT(B->ne[0] == d_state);
  3704. GGML_ASSERT(B->ne[1] == n_seq_tokens);
  3705. GGML_ASSERT(B->ne[2] == n_seqs);
  3706. }
  3707. // concatenated y + ssm_states
  3708. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + ggml_nelements(s));
  3709. result->op = GGML_OP_SSM_SCAN;
  3710. result->src[0] = s;
  3711. result->src[1] = x;
  3712. result->src[2] = dt;
  3713. result->src[3] = A;
  3714. result->src[4] = B;
  3715. result->src[5] = C;
  3716. return result;
  3717. }
  3718. // ggml_win_part
  3719. struct ggml_tensor * ggml_win_part(
  3720. struct ggml_context * ctx,
  3721. struct ggml_tensor * a,
  3722. int w) {
  3723. GGML_ASSERT(a->ne[3] == 1);
  3724. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3725. // padding
  3726. const int px = (w - a->ne[1]%w)%w;
  3727. const int py = (w - a->ne[2]%w)%w;
  3728. const int npx = (px + a->ne[1])/w;
  3729. const int npy = (py + a->ne[2])/w;
  3730. const int np = npx*npy;
  3731. const int64_t ne[4] = { a->ne[0], w, w, np, };
  3732. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3733. int32_t params[] = { npx, npy, w };
  3734. ggml_set_op_params(result, params, sizeof(params));
  3735. result->op = GGML_OP_WIN_PART;
  3736. result->src[0] = a;
  3737. return result;
  3738. }
  3739. // ggml_win_unpart
  3740. struct ggml_tensor * ggml_win_unpart(
  3741. struct ggml_context * ctx,
  3742. struct ggml_tensor * a,
  3743. int w0,
  3744. int h0,
  3745. int w) {
  3746. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3747. const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
  3748. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
  3749. int32_t params[] = { w };
  3750. ggml_set_op_params(result, params, sizeof(params));
  3751. result->op = GGML_OP_WIN_UNPART;
  3752. result->src[0] = a;
  3753. return result;
  3754. }
  3755. // ggml_get_rel_pos
  3756. struct ggml_tensor * ggml_get_rel_pos(
  3757. struct ggml_context * ctx,
  3758. struct ggml_tensor * a,
  3759. int qh,
  3760. int kh) {
  3761. GGML_ASSERT(qh == kh);
  3762. GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
  3763. const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
  3764. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
  3765. result->op = GGML_OP_GET_REL_POS;
  3766. result->src[0] = a;
  3767. return result;
  3768. }
  3769. // ggml_add_rel_pos
  3770. static struct ggml_tensor * ggml_add_rel_pos_impl(
  3771. struct ggml_context * ctx,
  3772. struct ggml_tensor * a,
  3773. struct ggml_tensor * pw,
  3774. struct ggml_tensor * ph,
  3775. bool inplace) {
  3776. GGML_ASSERT(ggml_are_same_shape(pw, ph));
  3777. GGML_ASSERT(ggml_is_contiguous(a));
  3778. GGML_ASSERT(ggml_is_contiguous(pw));
  3779. GGML_ASSERT(ggml_is_contiguous(ph));
  3780. GGML_ASSERT(ph->type == GGML_TYPE_F32);
  3781. GGML_ASSERT(pw->type == GGML_TYPE_F32);
  3782. GGML_ASSERT(pw->ne[3] == a->ne[2]);
  3783. GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
  3784. GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
  3785. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3786. ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
  3787. result->op = GGML_OP_ADD_REL_POS;
  3788. result->src[0] = a;
  3789. result->src[1] = pw;
  3790. result->src[2] = ph;
  3791. return result;
  3792. }
  3793. struct ggml_tensor * ggml_add_rel_pos(
  3794. struct ggml_context * ctx,
  3795. struct ggml_tensor * a,
  3796. struct ggml_tensor * pw,
  3797. struct ggml_tensor * ph) {
  3798. return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
  3799. }
  3800. struct ggml_tensor * ggml_add_rel_pos_inplace(
  3801. struct ggml_context * ctx,
  3802. struct ggml_tensor * a,
  3803. struct ggml_tensor * pw,
  3804. struct ggml_tensor * ph) {
  3805. return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
  3806. }
  3807. // ggml_rwkv_wkv6
  3808. struct ggml_tensor * ggml_rwkv_wkv6(
  3809. struct ggml_context * ctx,
  3810. struct ggml_tensor * k,
  3811. struct ggml_tensor * v,
  3812. struct ggml_tensor * r,
  3813. struct ggml_tensor * tf,
  3814. struct ggml_tensor * td,
  3815. struct ggml_tensor * state) {
  3816. GGML_ASSERT(ggml_is_contiguous(k));
  3817. GGML_ASSERT(ggml_is_contiguous(v));
  3818. GGML_ASSERT(ggml_is_contiguous(r));
  3819. GGML_ASSERT(ggml_is_contiguous(tf));
  3820. GGML_ASSERT(ggml_is_contiguous(td));
  3821. GGML_ASSERT(ggml_is_contiguous(state));
  3822. const int64_t S = k->ne[0];
  3823. const int64_t H = k->ne[2];
  3824. const int64_t n_tokens = k->ne[3];
  3825. const int64_t n_seqs = state->ne[1];
  3826. {
  3827. GGML_ASSERT(k->ne[1] == 1);
  3828. GGML_ASSERT(v->ne[0] == 1 && v->ne[1] == S && v->ne[2] == H && v->ne[3] == n_tokens);
  3829. GGML_ASSERT(r->ne[0] == 1 && r->ne[1] == S && r->ne[2] == H && r->ne[3] == n_tokens);
  3830. // TODO: RWKV v4 and v5
  3831. GGML_ASSERT(td->ne[0] == 1 && td->ne[1] == S && td->ne[2] == H && td->ne[3] == n_tokens);
  3832. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3833. }
  3834. // concat output and new_state
  3835. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3836. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3837. result->op = GGML_OP_RWKV_WKV6;
  3838. result->src[0] = k;
  3839. result->src[1] = v;
  3840. result->src[2] = r;
  3841. result->src[3] = tf;
  3842. result->src[4] = td;
  3843. result->src[5] = state;
  3844. return result;
  3845. }
  3846. // ggml_unary
  3847. static struct ggml_tensor * ggml_unary_impl(
  3848. struct ggml_context * ctx,
  3849. struct ggml_tensor * a,
  3850. enum ggml_unary_op op,
  3851. bool inplace) {
  3852. GGML_ASSERT(ggml_is_contiguous_1(a));
  3853. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3854. ggml_set_op_params_i32(result, 0, (int32_t) op);
  3855. result->op = GGML_OP_UNARY;
  3856. result->src[0] = a;
  3857. return result;
  3858. }
  3859. struct ggml_tensor * ggml_unary(
  3860. struct ggml_context * ctx,
  3861. struct ggml_tensor * a,
  3862. enum ggml_unary_op op) {
  3863. return ggml_unary_impl(ctx, a, op, false);
  3864. }
  3865. struct ggml_tensor * ggml_unary_inplace(
  3866. struct ggml_context * ctx,
  3867. struct ggml_tensor * a,
  3868. enum ggml_unary_op op) {
  3869. return ggml_unary_impl(ctx, a, op, true);
  3870. }
  3871. // ggml_map_unary
  3872. static struct ggml_tensor * ggml_map_unary_impl_f32(
  3873. struct ggml_context * ctx,
  3874. struct ggml_tensor * a,
  3875. const ggml_unary_op_f32_t fun,
  3876. bool inplace) {
  3877. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3878. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3879. result->op = GGML_OP_MAP_UNARY;
  3880. result->src[0] = a;
  3881. return result;
  3882. }
  3883. struct ggml_tensor * ggml_map_unary_f32(
  3884. struct ggml_context * ctx,
  3885. struct ggml_tensor * a,
  3886. const ggml_unary_op_f32_t fun) {
  3887. return ggml_map_unary_impl_f32(ctx, a, fun, false);
  3888. }
  3889. struct ggml_tensor * ggml_map_unary_inplace_f32(
  3890. struct ggml_context * ctx,
  3891. struct ggml_tensor * a,
  3892. const ggml_unary_op_f32_t fun) {
  3893. return ggml_map_unary_impl_f32(ctx, a, fun, true);
  3894. }
  3895. // ggml_map_binary
  3896. static struct ggml_tensor * ggml_map_binary_impl_f32(
  3897. struct ggml_context * ctx,
  3898. struct ggml_tensor * a,
  3899. struct ggml_tensor * b,
  3900. const ggml_binary_op_f32_t fun,
  3901. bool inplace) {
  3902. GGML_ASSERT(ggml_are_same_shape(a, b));
  3903. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3904. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3905. result->op = GGML_OP_MAP_BINARY;
  3906. result->src[0] = a;
  3907. result->src[1] = b;
  3908. return result;
  3909. }
  3910. struct ggml_tensor * ggml_map_binary_f32(
  3911. struct ggml_context * ctx,
  3912. struct ggml_tensor * a,
  3913. struct ggml_tensor * b,
  3914. const ggml_binary_op_f32_t fun) {
  3915. return ggml_map_binary_impl_f32(ctx, a, b, fun, false);
  3916. }
  3917. struct ggml_tensor * ggml_map_binary_inplace_f32(
  3918. struct ggml_context * ctx,
  3919. struct ggml_tensor * a,
  3920. struct ggml_tensor * b,
  3921. const ggml_binary_op_f32_t fun) {
  3922. return ggml_map_binary_impl_f32(ctx, a, b, fun, true);
  3923. }
  3924. // ggml_map_custom1_f32
  3925. static struct ggml_tensor * ggml_map_custom1_impl_f32(
  3926. struct ggml_context * ctx,
  3927. struct ggml_tensor * a,
  3928. const ggml_custom1_op_f32_t fun,
  3929. bool inplace) {
  3930. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3931. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3932. result->op = GGML_OP_MAP_CUSTOM1_F32;
  3933. result->src[0] = a;
  3934. return result;
  3935. }
  3936. struct ggml_tensor * ggml_map_custom1_f32(
  3937. struct ggml_context * ctx,
  3938. struct ggml_tensor * a,
  3939. const ggml_custom1_op_f32_t fun) {
  3940. return ggml_map_custom1_impl_f32(ctx, a, fun, false);
  3941. }
  3942. struct ggml_tensor * ggml_map_custom1_inplace_f32(
  3943. struct ggml_context * ctx,
  3944. struct ggml_tensor * a,
  3945. const ggml_custom1_op_f32_t fun) {
  3946. return ggml_map_custom1_impl_f32(ctx, a, fun, true);
  3947. }
  3948. // ggml_map_custom2_f32
  3949. static struct ggml_tensor * ggml_map_custom2_impl_f32(
  3950. struct ggml_context * ctx,
  3951. struct ggml_tensor * a,
  3952. struct ggml_tensor * b,
  3953. const ggml_custom2_op_f32_t fun,
  3954. bool inplace) {
  3955. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3956. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3957. result->op = GGML_OP_MAP_CUSTOM2_F32;
  3958. result->src[0] = a;
  3959. result->src[1] = b;
  3960. return result;
  3961. }
  3962. struct ggml_tensor * ggml_map_custom2_f32(
  3963. struct ggml_context * ctx,
  3964. struct ggml_tensor * a,
  3965. struct ggml_tensor * b,
  3966. const ggml_custom2_op_f32_t fun) {
  3967. return ggml_map_custom2_impl_f32(ctx, a, b, fun, false);
  3968. }
  3969. struct ggml_tensor * ggml_map_custom2_inplace_f32(
  3970. struct ggml_context * ctx,
  3971. struct ggml_tensor * a,
  3972. struct ggml_tensor * b,
  3973. const ggml_custom2_op_f32_t fun) {
  3974. return ggml_map_custom2_impl_f32(ctx, a, b, fun, true);
  3975. }
  3976. // ggml_map_custom3_f32
  3977. static struct ggml_tensor * ggml_map_custom3_impl_f32(
  3978. struct ggml_context * ctx,
  3979. struct ggml_tensor * a,
  3980. struct ggml_tensor * b,
  3981. struct ggml_tensor * c,
  3982. const ggml_custom3_op_f32_t fun,
  3983. bool inplace) {
  3984. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3985. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3986. result->op = GGML_OP_MAP_CUSTOM3_F32;
  3987. result->src[0] = a;
  3988. result->src[1] = b;
  3989. result->src[2] = c;
  3990. return result;
  3991. }
  3992. struct ggml_tensor * ggml_map_custom3_f32(
  3993. struct ggml_context * ctx,
  3994. struct ggml_tensor * a,
  3995. struct ggml_tensor * b,
  3996. struct ggml_tensor * c,
  3997. const ggml_custom3_op_f32_t fun) {
  3998. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, false);
  3999. }
  4000. struct ggml_tensor * ggml_map_custom3_inplace_f32(
  4001. struct ggml_context * ctx,
  4002. struct ggml_tensor * a,
  4003. struct ggml_tensor * b,
  4004. struct ggml_tensor * c,
  4005. const ggml_custom3_op_f32_t fun) {
  4006. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, true);
  4007. }
  4008. // ggml_map_custom1
  4009. static struct ggml_tensor * ggml_map_custom1_impl(
  4010. struct ggml_context * ctx,
  4011. struct ggml_tensor * a,
  4012. const ggml_custom1_op_t fun,
  4013. int n_tasks,
  4014. void * userdata,
  4015. bool inplace) {
  4016. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4017. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4018. struct ggml_map_custom1_op_params params = {
  4019. /*.fun =*/ fun,
  4020. /*.n_tasks =*/ n_tasks,
  4021. /*.userdata =*/ userdata
  4022. };
  4023. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4024. result->op = GGML_OP_MAP_CUSTOM1;
  4025. result->src[0] = a;
  4026. return result;
  4027. }
  4028. struct ggml_tensor * ggml_map_custom1(
  4029. struct ggml_context * ctx,
  4030. struct ggml_tensor * a,
  4031. const ggml_custom1_op_t fun,
  4032. int n_tasks,
  4033. void * userdata) {
  4034. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
  4035. }
  4036. struct ggml_tensor * ggml_map_custom1_inplace(
  4037. struct ggml_context * ctx,
  4038. struct ggml_tensor * a,
  4039. const ggml_custom1_op_t fun,
  4040. int n_tasks,
  4041. void * userdata) {
  4042. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
  4043. }
  4044. // ggml_map_custom2
  4045. static struct ggml_tensor * ggml_map_custom2_impl(
  4046. struct ggml_context * ctx,
  4047. struct ggml_tensor * a,
  4048. struct ggml_tensor * b,
  4049. const ggml_custom2_op_t fun,
  4050. int n_tasks,
  4051. void * userdata,
  4052. bool inplace) {
  4053. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4054. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4055. struct ggml_map_custom2_op_params params = {
  4056. /*.fun =*/ fun,
  4057. /*.n_tasks =*/ n_tasks,
  4058. /*.userdata =*/ userdata
  4059. };
  4060. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4061. result->op = GGML_OP_MAP_CUSTOM2;
  4062. result->src[0] = a;
  4063. result->src[1] = b;
  4064. return result;
  4065. }
  4066. struct ggml_tensor * ggml_map_custom2(
  4067. struct ggml_context * ctx,
  4068. struct ggml_tensor * a,
  4069. struct ggml_tensor * b,
  4070. const ggml_custom2_op_t fun,
  4071. int n_tasks,
  4072. void * userdata) {
  4073. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
  4074. }
  4075. struct ggml_tensor * ggml_map_custom2_inplace(
  4076. struct ggml_context * ctx,
  4077. struct ggml_tensor * a,
  4078. struct ggml_tensor * b,
  4079. const ggml_custom2_op_t fun,
  4080. int n_tasks,
  4081. void * userdata) {
  4082. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
  4083. }
  4084. // ggml_map_custom3
  4085. static struct ggml_tensor * ggml_map_custom3_impl(
  4086. struct ggml_context * ctx,
  4087. struct ggml_tensor * a,
  4088. struct ggml_tensor * b,
  4089. struct ggml_tensor * c,
  4090. const ggml_custom3_op_t fun,
  4091. int n_tasks,
  4092. void * userdata,
  4093. bool inplace) {
  4094. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4095. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4096. struct ggml_map_custom3_op_params params = {
  4097. /*.fun =*/ fun,
  4098. /*.n_tasks =*/ n_tasks,
  4099. /*.userdata =*/ userdata
  4100. };
  4101. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4102. result->op = GGML_OP_MAP_CUSTOM3;
  4103. result->src[0] = a;
  4104. result->src[1] = b;
  4105. result->src[2] = c;
  4106. return result;
  4107. }
  4108. struct ggml_tensor * ggml_map_custom3(
  4109. struct ggml_context * ctx,
  4110. struct ggml_tensor * a,
  4111. struct ggml_tensor * b,
  4112. struct ggml_tensor * c,
  4113. const ggml_custom3_op_t fun,
  4114. int n_tasks,
  4115. void * userdata) {
  4116. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
  4117. }
  4118. struct ggml_tensor * ggml_map_custom3_inplace(
  4119. struct ggml_context * ctx,
  4120. struct ggml_tensor * a,
  4121. struct ggml_tensor * b,
  4122. struct ggml_tensor * c,
  4123. const ggml_custom3_op_t fun,
  4124. int n_tasks,
  4125. void * userdata) {
  4126. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
  4127. }
  4128. // ggml_cross_entropy_loss
  4129. struct ggml_tensor * ggml_cross_entropy_loss(
  4130. struct ggml_context * ctx,
  4131. struct ggml_tensor * a,
  4132. struct ggml_tensor * b) {
  4133. GGML_ASSERT(ggml_are_same_shape(a, b));
  4134. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  4135. result->op = GGML_OP_CROSS_ENTROPY_LOSS;
  4136. result->src[0] = a;
  4137. result->src[1] = b;
  4138. return result;
  4139. }
  4140. // ggml_cross_entropy_loss_back
  4141. struct ggml_tensor * ggml_cross_entropy_loss_back(
  4142. struct ggml_context * ctx,
  4143. struct ggml_tensor * a,
  4144. struct ggml_tensor * b,
  4145. struct ggml_tensor * c) {
  4146. GGML_ASSERT(ggml_are_same_shape(a, b));
  4147. GGML_ASSERT(ggml_is_scalar(c));
  4148. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  4149. result->op = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
  4150. result->src[0] = a;
  4151. result->src[1] = b;
  4152. result->src[2] = c;
  4153. return result;
  4154. }
  4155. // opt_step_adamw
  4156. struct ggml_tensor * ggml_opt_step_adamw(
  4157. struct ggml_context * ctx,
  4158. struct ggml_tensor * a,
  4159. struct ggml_tensor * grad,
  4160. struct ggml_tensor * m,
  4161. struct ggml_tensor * v,
  4162. struct ggml_tensor * adamw_params) {
  4163. GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
  4164. GGML_ASSERT(ggml_are_same_shape(a, grad));
  4165. GGML_ASSERT(ggml_are_same_shape(a, m));
  4166. GGML_ASSERT(ggml_are_same_shape(a, v));
  4167. GGML_ASSERT(adamw_params->type == GGML_TYPE_F32);
  4168. GGML_ASSERT(ggml_nelements(adamw_params) == 7);
  4169. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  4170. result->op = GGML_OP_OPT_STEP_ADAMW;
  4171. result->src[0] = a;
  4172. result->src[1] = grad;
  4173. result->src[2] = m;
  4174. result->src[3] = v;
  4175. result->src[4] = adamw_params;
  4176. return result;
  4177. }
  4178. ////////////////////////////////////////////////////////////////////////////////
  4179. struct ggml_hash_set ggml_hash_set_new(size_t size) {
  4180. size = ggml_hash_size(size);
  4181. struct ggml_hash_set result;
  4182. result.size = size;
  4183. result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
  4184. result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
  4185. return result;
  4186. }
  4187. void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
  4188. memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
  4189. }
  4190. void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
  4191. GGML_FREE(hash_set->used);
  4192. GGML_FREE(hash_set->keys);
  4193. }
  4194. size_t ggml_hash_size(size_t min_sz) {
  4195. // next primes after powers of two
  4196. static const size_t primes[] = {
  4197. 2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
  4198. 2053, 4099, 8209, 16411, 32771, 65537, 131101,
  4199. 262147, 524309, 1048583, 2097169, 4194319, 8388617,
  4200. 16777259, 33554467, 67108879, 134217757, 268435459,
  4201. 536870923, 1073741827, 2147483659
  4202. };
  4203. static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
  4204. // find the smallest prime that is larger or equal than min_sz
  4205. size_t l = 0;
  4206. size_t r = n_primes;
  4207. while (l < r) {
  4208. size_t m = (l + r)/2;
  4209. if (primes[m] < min_sz) {
  4210. l = m + 1;
  4211. } else {
  4212. r = m;
  4213. }
  4214. }
  4215. size_t sz = l < n_primes ? primes[l] : min_sz | 1;
  4216. return sz;
  4217. }
  4218. struct hash_map {
  4219. struct ggml_hash_set set;
  4220. struct ggml_tensor ** vals;
  4221. };
  4222. static struct hash_map * ggml_new_hash_map(size_t size) {
  4223. struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
  4224. result->set = ggml_hash_set_new(size);
  4225. result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
  4226. return result;
  4227. }
  4228. static void ggml_hash_map_free(struct hash_map * map) {
  4229. ggml_hash_set_free(&map->set);
  4230. GGML_FREE(map->vals);
  4231. GGML_FREE(map);
  4232. }
  4233. // utility functions to change gradients
  4234. // isrc is the index of tensor in cgraph->visited_has_set.keys
  4235. // the corresponding gradient (accumulators) are also at position isrc
  4236. // if tensor has a gradient accumulator, modify that accumulator in-place
  4237. // else if there is no gradient for tensor, set the corresponding value
  4238. // else, just add/subtract/etc. the gradients
  4239. static void ggml_add_or_set(
  4240. struct ggml_context * ctx,
  4241. struct ggml_cgraph * cgraph,
  4242. size_t isrc,
  4243. struct ggml_tensor * tensor) {
  4244. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4245. GGML_ASSERT(src);
  4246. if (cgraph->grads[isrc]) {
  4247. cgraph->grads[isrc] = ggml_add_impl(ctx, cgraph->grads[isrc], tensor, /*inplace =*/ cgraph->grad_accs[isrc]);
  4248. } else {
  4249. cgraph->grads[isrc] = tensor;
  4250. }
  4251. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4252. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4253. }
  4254. static void ggml_acc_or_set(
  4255. struct ggml_context * ctx,
  4256. struct ggml_cgraph * cgraph,
  4257. size_t isrc,
  4258. struct ggml_tensor * tensor,
  4259. const size_t nb1,
  4260. const size_t nb2,
  4261. const size_t nb3,
  4262. const size_t offset) {
  4263. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4264. GGML_ASSERT(src);
  4265. if (cgraph->grads[isrc]) {
  4266. cgraph->grads[isrc] = ggml_acc_impl(ctx, cgraph->grads[isrc], tensor, nb1, nb2, nb3, offset, cgraph->grad_accs[isrc]);
  4267. } else {
  4268. struct ggml_tensor * a_zero = ggml_scale(ctx, src, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
  4269. cgraph->grads[isrc] = ggml_acc_impl(ctx, a_zero, tensor, nb1, nb2, nb3, offset, false);
  4270. }
  4271. ggml_format_name(cgraph->grads[isrc], "grad for %s", cgraph->visited_hash_set.keys[isrc]->name);
  4272. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4273. }
  4274. static void ggml_add1_or_set(
  4275. struct ggml_context * ctx,
  4276. struct ggml_cgraph * cgraph,
  4277. size_t isrc,
  4278. struct ggml_tensor * tensor) {
  4279. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4280. GGML_ASSERT(src);
  4281. if (cgraph->grads[isrc]) {
  4282. cgraph->grads[isrc] = ggml_add1_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4283. } else {
  4284. cgraph->grads[isrc] = ggml_repeat(ctx, tensor, src);
  4285. }
  4286. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4287. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4288. }
  4289. static void ggml_sub_or_set(
  4290. struct ggml_context * ctx,
  4291. struct ggml_cgraph * cgraph,
  4292. size_t isrc,
  4293. struct ggml_tensor * tensor) {
  4294. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4295. GGML_ASSERT(src);
  4296. if (cgraph->grads[isrc]) {
  4297. cgraph->grads[isrc] = ggml_sub_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4298. } else {
  4299. cgraph->grads[isrc] = ggml_neg(ctx, tensor);
  4300. }
  4301. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4302. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4303. }
  4304. static void ggml_compute_backward(
  4305. struct ggml_context * ctx, struct ggml_cgraph * cgraph, int i, bool * grads_needed) {
  4306. struct ggml_tensor * tensor = cgraph->nodes[i];
  4307. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, tensor);
  4308. if (!grad) {
  4309. return;
  4310. }
  4311. struct ggml_tensor * src0 = tensor->src[0];
  4312. struct ggml_tensor * src1 = tensor->src[1];
  4313. struct ggml_tensor * src2 = tensor->src[2];
  4314. struct ggml_hash_set * hash_set = &cgraph->visited_hash_set;
  4315. const size_t isrc0 = src0 ? ggml_hash_find(hash_set, src0) : (size_t) -1;
  4316. const size_t isrc1 = src1 ? ggml_hash_find(hash_set, src1) : (size_t) -1;
  4317. const size_t isrc2 = src2 ? ggml_hash_find(hash_set, src2) : (size_t) -1;
  4318. const bool src0_needs_grads = src0 && isrc0 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc0) && grads_needed[isrc0];
  4319. const bool src1_needs_grads = src1 && isrc1 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc1) && grads_needed[isrc1];
  4320. const bool src2_needs_grads = src2 && isrc2 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc2) && grads_needed[isrc2];
  4321. switch (tensor->op) {
  4322. case GGML_OP_DUP: {
  4323. if (src0_needs_grads) {
  4324. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4325. }
  4326. } break;
  4327. case GGML_OP_ADD: {
  4328. if (src0_needs_grads) {
  4329. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4330. }
  4331. if (src1_needs_grads) {
  4332. struct ggml_tensor * tmp = grad;
  4333. if (!ggml_are_same_shape(src0, src1)) {
  4334. tmp = ggml_repeat_back(ctx, tmp, src1);
  4335. }
  4336. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4337. }
  4338. } break;
  4339. case GGML_OP_ADD1: {
  4340. if (src0_needs_grads) {
  4341. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4342. }
  4343. if (src1_needs_grads) {
  4344. ggml_add_or_set(ctx, cgraph, isrc1, ggml_mean(ctx, grad)); // TODO: should probably be sum instead of mean
  4345. }
  4346. } break;
  4347. case GGML_OP_ACC: {
  4348. if (src0_needs_grads) {
  4349. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4350. }
  4351. if (src1_needs_grads) {
  4352. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  4353. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  4354. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  4355. const size_t offset = ((int32_t *) tensor->op_params)[3];
  4356. struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
  4357. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4358. nb1, nb2, nb3, offset);
  4359. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4360. }
  4361. } break;
  4362. case GGML_OP_SUB: {
  4363. if (src0_needs_grads) {
  4364. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4365. }
  4366. if (src1_needs_grads) {
  4367. ggml_sub_or_set(ctx, cgraph, isrc1, grad);
  4368. }
  4369. } break;
  4370. case GGML_OP_MUL: {
  4371. if (src0_needs_grads) {
  4372. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, src1, grad));
  4373. }
  4374. if (src1_needs_grads) {
  4375. struct ggml_tensor * tmp = ggml_mul(ctx, src0, grad);
  4376. if (!ggml_are_same_shape(src0, src1)) {
  4377. tmp = ggml_repeat_back(ctx, tmp, src1);
  4378. }
  4379. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4380. }
  4381. } break;
  4382. case GGML_OP_DIV: {
  4383. if (src0_needs_grads) {
  4384. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src1));
  4385. }
  4386. if (src1_needs_grads) {
  4387. ggml_sub_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1)));
  4388. }
  4389. } break;
  4390. case GGML_OP_SQR: {
  4391. if (src0_needs_grads) {
  4392. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_mul(ctx, src0, grad), 2.0f));
  4393. }
  4394. } break;
  4395. case GGML_OP_SQRT: {
  4396. if (src0_needs_grads) {
  4397. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_div(ctx, grad, tensor), 0.5f));
  4398. }
  4399. } break;
  4400. case GGML_OP_LOG: {
  4401. if (src0_needs_grads) {
  4402. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src0));
  4403. }
  4404. } break;
  4405. case GGML_OP_SIN: {
  4406. if (src0_needs_grads) {
  4407. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_cos(ctx, src0)));
  4408. }
  4409. } break;
  4410. case GGML_OP_COS: {
  4411. if (src0_needs_grads) {
  4412. ggml_sub_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sin(ctx, src0)));
  4413. }
  4414. } break;
  4415. case GGML_OP_SUM: {
  4416. if (src0_needs_grads) {
  4417. ggml_add1_or_set(ctx, cgraph, isrc0, grad);
  4418. }
  4419. } break;
  4420. case GGML_OP_SUM_ROWS: {
  4421. if (src0_needs_grads) {
  4422. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4423. }
  4424. } break;
  4425. case GGML_OP_MEAN: {
  4426. if (src0_needs_grads) {
  4427. ggml_add1_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], false));
  4428. }
  4429. } break;
  4430. case GGML_OP_REPEAT: {
  4431. if (src0_needs_grads) {
  4432. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat_back(ctx, grad, src0));
  4433. }
  4434. } break;
  4435. case GGML_OP_REPEAT_BACK: {
  4436. if (src0_needs_grads) {
  4437. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4438. }
  4439. } break;
  4440. case GGML_OP_RMS_NORM: {
  4441. if (src0_needs_grads) {
  4442. float eps;
  4443. memcpy(&eps, tensor->op_params, sizeof(float));
  4444. ggml_add_or_set(ctx, cgraph, isrc0, ggml_rms_norm_back(ctx, src0, grad, eps));
  4445. }
  4446. } break;
  4447. case GGML_OP_MUL_MAT: {
  4448. // https://cs231n.github.io/optimization-2/#staged
  4449. // # forward pass
  4450. // s0 = np.random.randn(5, 10)
  4451. // s1 = np.random.randn(10, 3)
  4452. // t = s0.dot(s1)
  4453. // # now suppose we had the gradient on t from above in the circuit
  4454. // dt = np.random.randn(*t.shape) # same shape as t
  4455. // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
  4456. // ds1 = t.T.dot(dt)
  4457. // tensor.shape [m,p,qq,rr]
  4458. // src0.shape [n,m,q1,r1]
  4459. // src1.shape [n,p,qq,rr]
  4460. if (src0_needs_grads) {
  4461. struct ggml_tensor * s1_tg =
  4462. ggml_out_prod(ctx, // [n,m,qq,rr]
  4463. src1, // [n,p,qq,rr]
  4464. grad); // [m,p,qq,rr]
  4465. const int64_t qq = s1_tg->ne[2];
  4466. const int64_t rr = s1_tg->ne[3];
  4467. const int64_t q1 = src0->ne[2];
  4468. const int64_t r1 = src0->ne[3];
  4469. const bool ne2_broadcasted = qq > q1;
  4470. const bool ne3_broadcasted = rr > r1;
  4471. if (ne2_broadcasted || ne3_broadcasted) {
  4472. // sum broadcast repetitions of s1_tg into shape of src0
  4473. s1_tg = ggml_repeat_back(ctx, s1_tg, src0);
  4474. }
  4475. ggml_add_or_set(ctx, cgraph, isrc0, s1_tg /*= [n,m,q1,r1]*/);
  4476. }
  4477. if (src1_needs_grads) {
  4478. ggml_add_or_set(ctx, cgraph, isrc1,
  4479. // ggml_mul_mat(ctx, // [n,p,qq,rr]
  4480. // ggml_cont(ctx, // [m,n,q1,r1]
  4481. // ggml_transpose(ctx, src0)), // [m,n,q1,r1]
  4482. // grad), // [m,p,qq,rr]
  4483. // when src0 is bigger than tensor->grad (this is mostly the case in llama),
  4484. // avoid transpose of src0, rather transpose smaller tensor->grad
  4485. // and then use ggml_out_prod
  4486. ggml_out_prod(ctx, // [n,p,qq,rr]
  4487. src0, // [n,m,q1,r1]
  4488. ggml_transpose(ctx, // [p,m,qq,rr]
  4489. grad))); // [m,p,qq,rr]
  4490. }
  4491. } break;
  4492. case GGML_OP_SCALE: {
  4493. if (src0_needs_grads) {
  4494. float s;
  4495. memcpy(&s, tensor->op_params, sizeof(float));
  4496. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, s, false));
  4497. }
  4498. } break;
  4499. case GGML_OP_SET: {
  4500. const size_t nb1 = ((const int32_t *) tensor->op_params)[0];
  4501. const size_t nb2 = ((const int32_t *) tensor->op_params)[1];
  4502. const size_t nb3 = ((const int32_t *) tensor->op_params)[2];
  4503. const size_t offset = ((const int32_t *) tensor->op_params)[3];
  4504. struct ggml_tensor * tensor_grad_view = NULL;
  4505. if (src0_needs_grads || src1_needs_grads) {
  4506. GGML_ASSERT(src0->type == tensor->type);
  4507. GGML_ASSERT(!cgraph->grads[isrc0] || cgraph->grads[isrc0]->type == grad->type);
  4508. GGML_ASSERT(!cgraph->grads[isrc1] || !src1_needs_grads || cgraph->grads[isrc1]->type == grad->type);
  4509. tensor_grad_view = ggml_view_4d(ctx,
  4510. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4511. nb1, nb2, nb3, offset);
  4512. }
  4513. if (src0_needs_grads) {
  4514. struct ggml_tensor * tmp = ggml_neg(ctx, tensor_grad_view);
  4515. ggml_add_or_set(ctx, cgraph, isrc0, ggml_acc_impl(ctx, grad, tmp, nb1, nb2, nb3, offset, false));
  4516. }
  4517. if (src1_needs_grads) {
  4518. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4519. }
  4520. } break;
  4521. case GGML_OP_CPY: {
  4522. // cpy overwrites value of src1 by src0 and returns view(src1)
  4523. // the overwriting is mathematically equivalent to:
  4524. // tensor = src0 * 1 + src1 * 0
  4525. if (src0_needs_grads) {
  4526. // dsrc0 = dtensor * 1
  4527. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4528. }
  4529. if (src1_needs_grads) {
  4530. // dsrc1 = dtensor * 0 -> noop
  4531. }
  4532. } break;
  4533. case GGML_OP_CONT: {
  4534. // same as cpy
  4535. if (src0_needs_grads) {
  4536. GGML_ASSERT(!cgraph->grads[isrc0] || ggml_is_contiguous(cgraph->grads[isrc0]));
  4537. GGML_ASSERT(ggml_is_contiguous(grad));
  4538. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4539. }
  4540. } break;
  4541. case GGML_OP_RESHAPE: {
  4542. if (src0_needs_grads) {
  4543. struct ggml_tensor * grad_cont = ggml_is_contiguous(grad) ? grad : ggml_cont(ctx, grad);
  4544. ggml_add_or_set(ctx, cgraph, isrc0, ggml_reshape(ctx, grad_cont, src0));
  4545. }
  4546. } break;
  4547. case GGML_OP_VIEW: {
  4548. if (src0_needs_grads) {
  4549. size_t offset;
  4550. memcpy(&offset, tensor->op_params, sizeof(offset));
  4551. size_t nb1 = tensor->nb[1];
  4552. size_t nb2 = tensor->nb[2];
  4553. size_t nb3 = tensor->nb[3];
  4554. if (cgraph->grads[isrc0] && src0->type != cgraph->grads[isrc0]->type) {
  4555. // gradient is typically F32, but src0 could be other type
  4556. size_t ng = ggml_element_size(cgraph->grads[isrc0]);
  4557. size_t n0 = ggml_element_size(src0);
  4558. GGML_ASSERT(offset % n0 == 0);
  4559. GGML_ASSERT(nb1 % n0 == 0);
  4560. GGML_ASSERT(nb2 % n0 == 0);
  4561. GGML_ASSERT(nb3 % n0 == 0);
  4562. offset = (offset / n0) * ng;
  4563. nb1 = (nb1 / n0) * ng;
  4564. nb2 = (nb2 / n0) * ng;
  4565. nb3 = (nb3 / n0) * ng;
  4566. }
  4567. ggml_acc_or_set(ctx, cgraph, isrc0, grad, nb1, nb2, nb3, offset);
  4568. }
  4569. } break;
  4570. case GGML_OP_PERMUTE: {
  4571. if (src0_needs_grads) {
  4572. const int32_t * axes = (const int32_t *) tensor->op_params;
  4573. const int axis0 = axes[0] & 0x3;
  4574. const int axis1 = axes[1] & 0x3;
  4575. const int axis2 = axes[2] & 0x3;
  4576. const int axis3 = axes[3] & 0x3;
  4577. int axb[4] = {0,0,0,0}; // axes backward
  4578. axb[axis0] = 0;
  4579. axb[axis1] = 1;
  4580. axb[axis2] = 2;
  4581. axb[axis3] = 3;
  4582. ggml_add_or_set(ctx, cgraph, isrc0, ggml_permute(ctx, grad, axb[0], axb[1], axb[2], axb[3]));
  4583. }
  4584. } break;
  4585. case GGML_OP_TRANSPOSE: {
  4586. if (src0_needs_grads) {
  4587. ggml_add_or_set(ctx, cgraph, isrc0, ggml_transpose(ctx, grad));
  4588. }
  4589. } break;
  4590. case GGML_OP_GET_ROWS: {
  4591. if (src0_needs_grads) {
  4592. ggml_add_or_set(ctx, cgraph, isrc0, ggml_get_rows_back(ctx, grad, src1, src0));
  4593. }
  4594. if (src1_needs_grads) {
  4595. // noop
  4596. }
  4597. } break;
  4598. case GGML_OP_DIAG_MASK_INF: {
  4599. if (src0_needs_grads) {
  4600. /* ggml_diag_mask_inf_impl() shouldn't be here */
  4601. /* ref: https://github.com/ggerganov/llama.cpp/pull/4203#discussion_r1412377992 */
  4602. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4603. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4604. }
  4605. } break;
  4606. case GGML_OP_DIAG_MASK_ZERO: {
  4607. if (src0_needs_grads) {
  4608. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4609. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4610. }
  4611. } break;
  4612. case GGML_OP_SOFT_MAX: {
  4613. if (src0_needs_grads) {
  4614. ggml_add_or_set(ctx, cgraph, isrc0, ggml_soft_max_back(ctx, grad, tensor));
  4615. }
  4616. GGML_ASSERT((!src1 || !src1_needs_grads) && "backward pass for softmax mask not implemented");
  4617. } break;
  4618. case GGML_OP_ROPE: {
  4619. if (src0_needs_grads) {
  4620. //const int n_past = ((int32_t *) tensor->op_params)[0];
  4621. const int n_dims = ((const int32_t *) tensor->op_params)[1];
  4622. const int mode = ((const int32_t *) tensor->op_params)[2];
  4623. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  4624. const int n_ctx_orig = ((const int32_t *) tensor->op_params)[4];
  4625. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  4626. memcpy(&freq_base, (const float *) tensor->op_params + 5, sizeof(float));
  4627. memcpy(&freq_scale, (const float *) tensor->op_params + 6, sizeof(float));
  4628. memcpy(&ext_factor, (const float *) tensor->op_params + 7, sizeof(float));
  4629. memcpy(&attn_factor, (const float *) tensor->op_params + 8, sizeof(float));
  4630. memcpy(&beta_fast, (const float *) tensor->op_params + 9, sizeof(float));
  4631. memcpy(&beta_slow, (const float *) tensor->op_params + 10, sizeof(float));
  4632. ggml_add_or_set(ctx, cgraph, isrc0,
  4633. ggml_rope_back(ctx, grad, src1, src2, n_dims, mode, n_ctx_orig, freq_base,
  4634. freq_scale, ext_factor, attn_factor, beta_fast, beta_slow));
  4635. }
  4636. GGML_ASSERT((!src2 || !src2_needs_grads) && "gradients for freq factors not implemented");
  4637. } break;
  4638. case GGML_OP_IM2COL: {
  4639. if (src1_needs_grads) {
  4640. const int32_t s0 = ggml_get_op_params_i32(tensor, 0);
  4641. const int32_t s1 = ggml_get_op_params_i32(tensor, 1);
  4642. const int32_t p0 = ggml_get_op_params_i32(tensor, 2);
  4643. const int32_t p1 = ggml_get_op_params_i32(tensor, 3);
  4644. const int32_t d0 = ggml_get_op_params_i32(tensor, 4);
  4645. const int32_t d1 = ggml_get_op_params_i32(tensor, 5);
  4646. const bool is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
  4647. ggml_add_or_set(ctx, cgraph, isrc1, ggml_im2col_back(ctx, src0, grad, src1->ne, s0, s1, p0, p1, d0, d1, is_2D));
  4648. }
  4649. } break;
  4650. case GGML_OP_POOL_2D: {
  4651. if (src0_needs_grads) {
  4652. const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
  4653. const int32_t k0 = ggml_get_op_params_i32(tensor, 1);
  4654. const int32_t k1 = ggml_get_op_params_i32(tensor, 2);
  4655. const int32_t s0 = ggml_get_op_params_i32(tensor, 3);
  4656. const int32_t s1 = ggml_get_op_params_i32(tensor, 4);
  4657. const int32_t p0 = ggml_get_op_params_i32(tensor, 5);
  4658. const int32_t p1 = ggml_get_op_params_i32(tensor, 6);
  4659. ggml_add_or_set(ctx, cgraph, isrc0, ggml_pool_2d_back(ctx, grad, src0, op, k0, k1, s0, s1, p0, p1));
  4660. }
  4661. } break;
  4662. case GGML_OP_WIN_PART:
  4663. case GGML_OP_WIN_UNPART:
  4664. case GGML_OP_UNARY: {
  4665. switch (ggml_get_unary_op(tensor)) {
  4666. case GGML_UNARY_OP_ABS: {
  4667. if (src0_needs_grads) {
  4668. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_sgn(ctx, src0), grad));
  4669. }
  4670. } break;
  4671. case GGML_UNARY_OP_SGN: {
  4672. // noop
  4673. } break;
  4674. case GGML_UNARY_OP_NEG: {
  4675. if (src0_needs_grads) {
  4676. ggml_sub_or_set(ctx, cgraph, isrc0, grad);
  4677. }
  4678. } break;
  4679. case GGML_UNARY_OP_STEP: {
  4680. // noop
  4681. } break;
  4682. case GGML_UNARY_OP_RELU: {
  4683. if (src0_needs_grads) {
  4684. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_step(ctx, src0), grad));
  4685. }
  4686. } break;
  4687. case GGML_UNARY_OP_SILU: {
  4688. if (src0_needs_grads) {
  4689. ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, src0, grad));
  4690. }
  4691. } break;
  4692. case GGML_UNARY_OP_EXP: {
  4693. if (src0_needs_grads) {
  4694. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad));
  4695. }
  4696. } break;
  4697. default: {
  4698. fprintf(stderr, "%s: unsupported unary op for backward pass: %s\n",
  4699. __func__, ggml_unary_op_name(ggml_get_unary_op(tensor)));
  4700. GGML_ABORT("fatal error");
  4701. } //break;
  4702. }
  4703. } break;
  4704. case GGML_OP_CROSS_ENTROPY_LOSS: {
  4705. if (src0_needs_grads) {
  4706. ggml_add_or_set(ctx, cgraph, isrc0, ggml_cross_entropy_loss_back(ctx, src0, src1, grad));
  4707. }
  4708. GGML_ASSERT(!src1_needs_grads && "backward pass for labels not implemented");
  4709. } break;
  4710. case GGML_OP_NONE: {
  4711. // noop
  4712. } break;
  4713. case GGML_OP_COUNT:
  4714. default: {
  4715. fprintf(stderr, "%s: unsupported ggml op for backward pass: %s\n", __func__, ggml_op_name(tensor->op));
  4716. GGML_ABORT("fatal error");
  4717. } //break;
  4718. }
  4719. GGML_ASSERT(!src0_needs_grads || ggml_are_same_shape(src0, cgraph->grads[isrc0]));
  4720. GGML_ASSERT(!src1_needs_grads || ggml_are_same_shape(src1, cgraph->grads[isrc1]));
  4721. GGML_ASSERT(!src2_needs_grads || ggml_are_same_shape(src2, cgraph->grads[isrc2]));
  4722. }
  4723. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  4724. // check if already visited
  4725. if (ggml_hash_insert(&cgraph->visited_hash_set, node) == GGML_HASHSET_ALREADY_EXISTS) {
  4726. return;
  4727. }
  4728. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  4729. const int k =
  4730. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
  4731. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
  4732. /* unknown order, just fall back to using i*/ i;
  4733. if (node->src[k]) {
  4734. ggml_visit_parents(cgraph, node->src[k]);
  4735. }
  4736. }
  4737. if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
  4738. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  4739. GGML_ASSERT(cgraph->n_leafs < cgraph->size);
  4740. if (strlen(node->name) == 0) {
  4741. ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
  4742. }
  4743. cgraph->leafs[cgraph->n_leafs] = node;
  4744. cgraph->n_leafs++;
  4745. } else {
  4746. GGML_ASSERT(cgraph->n_nodes < cgraph->size);
  4747. if (strlen(node->name) == 0) {
  4748. ggml_format_name(node, "node_%d", cgraph->n_nodes);
  4749. }
  4750. cgraph->nodes[cgraph->n_nodes] = node;
  4751. cgraph->n_nodes++;
  4752. }
  4753. }
  4754. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  4755. if (!expand) {
  4756. // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
  4757. ggml_graph_clear(cgraph);
  4758. }
  4759. const int n0 = cgraph->n_nodes;
  4760. ggml_visit_parents(cgraph, tensor);
  4761. const int n_new = cgraph->n_nodes - n0;
  4762. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  4763. if (n_new > 0) {
  4764. // the last added node should always be starting point
  4765. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  4766. }
  4767. }
  4768. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  4769. ggml_build_forward_impl(cgraph, tensor, true);
  4770. }
  4771. void ggml_build_backward_expand(
  4772. struct ggml_context * ctx_static,
  4773. struct ggml_context * ctx_compute,
  4774. struct ggml_cgraph * cgraph,
  4775. bool accumulate) {
  4776. GGML_ASSERT(cgraph->n_nodes > 0);
  4777. GGML_ASSERT(cgraph->grads);
  4778. GGML_ASSERT(cgraph->grad_accs);
  4779. const int n_nodes_f = cgraph->n_nodes;
  4780. memset(cgraph->grads, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4781. memset(cgraph->grad_accs, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4782. bool * grads_needed = calloc(cgraph->visited_hash_set.size, sizeof(bool));
  4783. {
  4784. bool any_params = false;
  4785. bool any_loss = false;
  4786. for (int i = 0; i < n_nodes_f; ++i) {
  4787. struct ggml_tensor * node = cgraph->nodes[i];
  4788. any_params = any_params || (node->flags & GGML_TENSOR_FLAG_PARAM);
  4789. any_loss = any_loss || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4790. }
  4791. GGML_ASSERT(any_params && "no trainable parameters found, did you forget to call ggml_set_param?");
  4792. GGML_ASSERT(any_loss && "no training loss found, did you forget to call ggml_set_loss?");
  4793. }
  4794. for (int i = 0; i < n_nodes_f; ++i) {
  4795. struct ggml_tensor * node = cgraph->nodes[i];
  4796. if (node->type == GGML_TYPE_I32) {
  4797. continue;
  4798. }
  4799. bool node_needs_grad = (node->flags & GGML_TENSOR_FLAG_PARAM) || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4800. bool ignore_src[GGML_MAX_SRC] = {false};
  4801. switch (node->op) {
  4802. // gradients in node->src[0] for one reason or another have no effect on output gradients
  4803. case GGML_OP_IM2COL: // only used for its shape
  4804. case GGML_OP_IM2COL_BACK: // same as IM2COL
  4805. ignore_src[0] = true;
  4806. break;
  4807. case GGML_OP_UNARY: {
  4808. const enum ggml_unary_op uop = ggml_get_unary_op(node);
  4809. // SGN and STEP unary ops are piecewise constant
  4810. if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
  4811. ignore_src[0] = true;
  4812. }
  4813. } break;
  4814. // gradients in node->src[1] for one reason or another have no effect on output gradients
  4815. case GGML_OP_CPY: // gradients in CPY target are irrelevant
  4816. case GGML_OP_GET_ROWS: // row indices not differentiable
  4817. case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
  4818. case GGML_OP_ROPE: // positions not differentiable
  4819. ignore_src[1] = true;
  4820. break;
  4821. default:
  4822. break;
  4823. }
  4824. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  4825. if (!node->src[j] || ignore_src[j] || !grads_needed[ggml_hash_find(&cgraph->visited_hash_set, node->src[j])]) {
  4826. continue;
  4827. }
  4828. GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
  4829. node_needs_grad = true;
  4830. break;
  4831. }
  4832. if (!node_needs_grad) {
  4833. continue;
  4834. }
  4835. // inplace operations are currently not supported
  4836. GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
  4837. node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
  4838. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  4839. GGML_ASSERT(igrad != GGML_HASHSET_FULL);
  4840. GGML_ASSERT(ggml_bitset_get(cgraph->visited_hash_set.used, igrad));
  4841. if ((accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) || (node->flags & GGML_TENSOR_FLAG_LOSS)) {
  4842. cgraph->grad_accs[igrad] = ggml_dup_tensor(ctx_static, node);
  4843. cgraph->grads[igrad] = cgraph->grad_accs[igrad];
  4844. ggml_format_name(cgraph->grad_accs[igrad], "grad acc for %s", node->name);
  4845. }
  4846. grads_needed[igrad] = true;
  4847. }
  4848. for (int i = n_nodes_f - 1; i >= 0; --i) {
  4849. // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
  4850. // use allocator to automatically make inplace operations
  4851. ggml_compute_backward(ctx_compute, cgraph, i, grads_needed);
  4852. }
  4853. free(grads_needed);
  4854. }
  4855. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  4856. void * ptr = *p;
  4857. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  4858. *p = (void *) ((char *) ptr + size);
  4859. return ptr;
  4860. }
  4861. static size_t ggml_graph_nbytes(size_t size, bool grads) {
  4862. size_t hash_size = ggml_hash_size(size * 2);
  4863. void * p = 0;
  4864. incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
  4865. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
  4866. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
  4867. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
  4868. if (grads) {
  4869. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
  4870. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grad_accs
  4871. }
  4872. incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4873. size_t nbytes = (size_t) p;
  4874. return nbytes;
  4875. }
  4876. size_t ggml_graph_overhead_custom(size_t size, bool grads) {
  4877. return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
  4878. }
  4879. size_t ggml_graph_overhead(void) {
  4880. return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
  4881. }
  4882. struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
  4883. const size_t obj_size = ggml_graph_nbytes(size, grads);
  4884. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
  4885. struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
  4886. // the size of the hash table is doubled since it needs to hold both nodes and leafs
  4887. size_t hash_size = ggml_hash_size(size * 2);
  4888. void * p = cgraph + 1;
  4889. struct ggml_tensor ** nodes_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4890. struct ggml_tensor ** leafs_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4891. struct ggml_tensor ** hash_keys_ptr = incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4892. struct ggml_tensor ** grads_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4893. struct ggml_tensor ** grad_accs_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4894. ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4895. // check that we allocated the correct amount of memory
  4896. assert(obj_size == (size_t)((char *)p - (char *)cgraph));
  4897. *cgraph = (struct ggml_cgraph) {
  4898. /*.size =*/ size,
  4899. /*.n_nodes =*/ 0,
  4900. /*.n_leafs =*/ 0,
  4901. /*.nodes =*/ nodes_ptr,
  4902. /*.grads =*/ grads_ptr,
  4903. /*.grad_accs =*/ grad_accs_ptr,
  4904. /*.leafs =*/ leafs_ptr,
  4905. /*.hash_table =*/ { hash_size, hash_used, hash_keys_ptr },
  4906. /*.order =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
  4907. };
  4908. ggml_hash_set_reset(&cgraph->visited_hash_set);
  4909. if (grads) {
  4910. memset(cgraph->grads, 0, hash_size*sizeof(struct ggml_tensor *));
  4911. memset(cgraph->grad_accs, 0, hash_size*sizeof(struct ggml_tensor *));
  4912. }
  4913. return cgraph;
  4914. }
  4915. struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
  4916. return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
  4917. }
  4918. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
  4919. struct ggml_cgraph cgraph = {
  4920. /*.size =*/ 0,
  4921. /*.n_nodes =*/ i1 - i0,
  4922. /*.n_leafs =*/ 0,
  4923. /*.nodes =*/ cgraph0->nodes + i0,
  4924. /*.grads =*/ NULL, // gradients would need visited_hash_set
  4925. /*.grad_accs =*/ NULL,
  4926. /*.leafs =*/ NULL,
  4927. /*.visited_hash_set =*/ { 0, NULL, NULL },
  4928. /*.order =*/ cgraph0->order,
  4929. };
  4930. return cgraph;
  4931. }
  4932. void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
  4933. GGML_ASSERT(dst->size >= src->n_leafs);
  4934. GGML_ASSERT(dst->size >= src->n_nodes);
  4935. GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
  4936. dst->n_leafs = src->n_leafs;
  4937. dst->n_nodes = src->n_nodes;
  4938. dst->order = src->order;
  4939. for (int i = 0; i < src->n_leafs; ++i) {
  4940. dst->leafs[i] = src->leafs[i];
  4941. }
  4942. for (int i = 0; i < src->n_nodes; ++i) {
  4943. dst->nodes[i] = src->nodes[i];
  4944. }
  4945. for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
  4946. // copy all hashset keys (tensors) that are in use
  4947. if (ggml_bitset_get(src->visited_hash_set.used, i)) {
  4948. ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
  4949. }
  4950. }
  4951. if (dst->grads) {
  4952. memset(dst->grads, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4953. memset(dst->grad_accs, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4954. }
  4955. if (src->grads) {
  4956. GGML_ASSERT(dst->grads != NULL);
  4957. GGML_ASSERT(dst->grad_accs != NULL);
  4958. for (int i = 0; i < src->n_nodes; ++i) {
  4959. const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
  4960. const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
  4961. GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
  4962. GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
  4963. GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
  4964. GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
  4965. dst->grads[igrad_dst] = src->grads[igrad_src];
  4966. dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
  4967. }
  4968. }
  4969. }
  4970. struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  4971. struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads != NULL);
  4972. ggml_graph_cpy(cgraph, result);
  4973. return result;
  4974. }
  4975. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  4976. if (ggml_is_empty(tensor)) {
  4977. return tensor;
  4978. }
  4979. if (tensor->buffer) {
  4980. ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
  4981. } else {
  4982. GGML_ASSERT(tensor->data);
  4983. memset(tensor->data, 0, ggml_nbytes(tensor));
  4984. }
  4985. return tensor;
  4986. }
  4987. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  4988. GGML_ASSERT(cgraph->grads != NULL);
  4989. for (int i = 0; i < cgraph->n_nodes; i++) {
  4990. struct ggml_tensor * node = cgraph->nodes[i];
  4991. struct ggml_tensor * grad_acc = ggml_graph_get_grad_acc(cgraph, node);
  4992. if (node->op == GGML_OP_OPT_STEP_ADAMW) {
  4993. // clear momenta
  4994. ggml_set_zero(node->src[2]);
  4995. ggml_set_zero(node->src[3]);
  4996. }
  4997. // initial gradients of loss should be 1, 0 otherwise
  4998. if (grad_acc) {
  4999. if (node->flags & GGML_TENSOR_FLAG_LOSS) {
  5000. GGML_ASSERT(grad_acc->type == GGML_TYPE_F32);
  5001. GGML_ASSERT(ggml_is_scalar(grad_acc));
  5002. const float onef = 1.0f;
  5003. if (grad_acc->buffer) {
  5004. ggml_backend_tensor_set(grad_acc, &onef, 0, sizeof(float));
  5005. } else {
  5006. GGML_ASSERT(grad_acc->data);
  5007. *((float *) grad_acc->data) = onef;
  5008. }
  5009. } else {
  5010. ggml_set_zero(grad_acc);
  5011. }
  5012. }
  5013. }
  5014. }
  5015. void ggml_graph_clear(struct ggml_cgraph * cgraph) {
  5016. cgraph->n_leafs = 0;
  5017. cgraph->n_nodes = 0;
  5018. ggml_hash_set_reset(&cgraph->visited_hash_set);
  5019. }
  5020. int ggml_graph_size(struct ggml_cgraph * cgraph) {
  5021. return cgraph->size;
  5022. }
  5023. struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
  5024. if (i < 0) {
  5025. GGML_ASSERT(cgraph->n_nodes + i >= 0);
  5026. return cgraph->nodes[cgraph->n_nodes + i];
  5027. }
  5028. GGML_ASSERT(i < cgraph->n_nodes);
  5029. return cgraph->nodes[i];
  5030. }
  5031. struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
  5032. return cgraph->nodes;
  5033. }
  5034. int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
  5035. return cgraph->n_nodes;
  5036. }
  5037. void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  5038. GGML_ASSERT(cgraph->size > cgraph->n_nodes);
  5039. cgraph->nodes[cgraph->n_nodes] = tensor;
  5040. cgraph->n_nodes++;
  5041. }
  5042. struct ggml_tensor * ggml_graph_get_tensor(const struct ggml_cgraph * cgraph, const char * name) {
  5043. for (int i = 0; i < cgraph->n_leafs; i++) {
  5044. struct ggml_tensor * leaf = cgraph->leafs[i];
  5045. if (strcmp(leaf->name, name) == 0) {
  5046. return leaf;
  5047. }
  5048. }
  5049. for (int i = 0; i < cgraph->n_nodes; i++) {
  5050. struct ggml_tensor * node = cgraph->nodes[i];
  5051. if (strcmp(node->name, name) == 0) {
  5052. return node;
  5053. }
  5054. }
  5055. return NULL;
  5056. }
  5057. struct ggml_tensor * ggml_graph_get_grad(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5058. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5059. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grads ? cgraph->grads[igrad] : NULL;
  5060. }
  5061. struct ggml_tensor * ggml_graph_get_grad_acc(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5062. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5063. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grad_accs ? cgraph->grad_accs[igrad] : NULL;
  5064. }
  5065. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  5066. GGML_LOG_INFO("=== GRAPH ===\n");
  5067. GGML_LOG_INFO("n_nodes = %d\n", cgraph->n_nodes);
  5068. for (int i = 0; i < cgraph->n_nodes; i++) {
  5069. struct ggml_tensor * node = cgraph->nodes[i];
  5070. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
  5071. i,
  5072. node->ne[0], node->ne[1], node->ne[2],
  5073. ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" :
  5074. ggml_graph_get_grad(cgraph, node) ? "g" : " ");
  5075. }
  5076. GGML_LOG_INFO("n_leafs = %d\n", cgraph->n_leafs);
  5077. for (int i = 0; i < cgraph->n_leafs; i++) {
  5078. struct ggml_tensor * node = cgraph->leafs[i];
  5079. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
  5080. i,
  5081. node->ne[0], node->ne[1],
  5082. ggml_op_name(node->op),
  5083. ggml_get_name(node));
  5084. }
  5085. GGML_LOG_INFO("========================================\n");
  5086. }
  5087. // check if node is part of the graph
  5088. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5089. if (cgraph == NULL) {
  5090. return true;
  5091. }
  5092. for (int i = 0; i < cgraph->n_nodes; i++) {
  5093. if (cgraph->nodes[i] == node) {
  5094. return true;
  5095. }
  5096. }
  5097. return false;
  5098. }
  5099. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5100. for (int i = 0; i < cgraph->n_nodes; i++) {
  5101. struct ggml_tensor * parent = cgraph->nodes[i];
  5102. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, parent);
  5103. if (grad == node) {
  5104. return parent;
  5105. }
  5106. }
  5107. return NULL;
  5108. }
  5109. static void ggml_graph_dump_dot_node_edge(FILE * fp, const struct ggml_cgraph * gb, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  5110. struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
  5111. struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
  5112. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
  5113. gparent0 ? (void *) gparent0 : (void *) parent,
  5114. gparent0 ? "g" : "x",
  5115. gparent ? (void *) gparent : (void *) node,
  5116. gparent ? "g" : "x",
  5117. gparent ? "empty" : "vee",
  5118. gparent ? "dashed" : "solid",
  5119. label);
  5120. }
  5121. static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  5122. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"%s\"; ]\n",
  5123. (void *) parent, "x",
  5124. (void *) node, "x",
  5125. label);
  5126. }
  5127. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  5128. char color[16];
  5129. FILE * fp = ggml_fopen(filename, "w");
  5130. GGML_ASSERT(fp);
  5131. fprintf(fp, "digraph G {\n");
  5132. fprintf(fp, " newrank = true;\n");
  5133. fprintf(fp, " rankdir = TB;\n");
  5134. for (int i = 0; i < gb->n_nodes; i++) {
  5135. struct ggml_tensor * node = gb->nodes[i];
  5136. struct ggml_tensor * grad = ggml_graph_get_grad(gb, node);
  5137. if (ggml_graph_get_parent(gb, node) != NULL) {
  5138. continue;
  5139. }
  5140. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  5141. snprintf(color, sizeof(color), "yellow");
  5142. } else if (grad) {
  5143. if (ggml_graph_find(gf, node)) {
  5144. snprintf(color, sizeof(color), "green");
  5145. } else {
  5146. snprintf(color, sizeof(color), "lightblue");
  5147. }
  5148. } else {
  5149. snprintf(color, sizeof(color), "white");
  5150. }
  5151. fprintf(fp, " \"%p\" [ "
  5152. "style = filled; fillcolor = %s; shape = record; "
  5153. "label=\"",
  5154. (void *) node, color);
  5155. if (strlen(node->name) > 0) {
  5156. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5157. } else {
  5158. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5159. }
  5160. if (ggml_is_matrix(node)) {
  5161. fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
  5162. } else {
  5163. fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
  5164. }
  5165. if (grad) {
  5166. fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(grad->op));
  5167. } else {
  5168. fprintf(fp, "\"; ]\n");
  5169. }
  5170. }
  5171. for (int i = 0; i < gb->n_leafs; i++) {
  5172. struct ggml_tensor * node = gb->leafs[i];
  5173. snprintf(color, sizeof(color), "pink");
  5174. fprintf(fp, " \"%p\" [ "
  5175. "style = filled; fillcolor = %s; shape = record; "
  5176. "label=\"<x>",
  5177. (void *) node, color);
  5178. if (strlen(node->name) > 0) {
  5179. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5180. } else {
  5181. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5182. }
  5183. fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
  5184. if (ggml_nelements(node) < 5 && node->data != NULL) {
  5185. fprintf(fp, " | (");
  5186. for (int j = 0; j < ggml_nelements(node); j++) {
  5187. // FIXME: use ggml-backend to obtain the tensor data
  5188. //if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
  5189. // fprintf(fp, "%d", ggml_get_i32_1d(node, j));
  5190. //}
  5191. //else if (node->type == GGML_TYPE_F32 ||
  5192. // node->type == GGML_TYPE_F16 ||
  5193. // node->type == GGML_TYPE_BF16) {
  5194. // fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
  5195. //}
  5196. //else
  5197. {
  5198. fprintf(fp, "#");
  5199. }
  5200. if (j < ggml_nelements(node) - 1) {
  5201. fprintf(fp, ", ");
  5202. }
  5203. }
  5204. fprintf(fp, ")");
  5205. }
  5206. fprintf(fp, "\"; ]\n");
  5207. }
  5208. for (int i = 0; i < gb->n_nodes; i++) {
  5209. struct ggml_tensor * node = gb->nodes[i];
  5210. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5211. if (node->src[j]) {
  5212. char label[16];
  5213. snprintf(label, sizeof(label), "src %d", j);
  5214. ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
  5215. }
  5216. }
  5217. }
  5218. for (int i = 0; i < gb->n_leafs; i++) {
  5219. struct ggml_tensor * node = gb->leafs[i];
  5220. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5221. if (node->src[j]) {
  5222. char label[16];
  5223. snprintf(label, sizeof(label), "src %d", j);
  5224. ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
  5225. }
  5226. }
  5227. }
  5228. fprintf(fp, "}\n");
  5229. fclose(fp);
  5230. GGML_LOG_INFO("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  5231. }
  5232. ////////////////////////////////////////////////////////////////////////////////
  5233. void ggml_set_input(struct ggml_tensor * tensor) {
  5234. tensor->flags |= GGML_TENSOR_FLAG_INPUT;
  5235. }
  5236. void ggml_set_output(struct ggml_tensor * tensor) {
  5237. tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
  5238. }
  5239. void ggml_set_param(struct ggml_context * ctx, struct ggml_tensor * tensor) {
  5240. GGML_UNUSED(ctx); // TODO: remove this parameter
  5241. tensor->flags |= GGML_TENSOR_FLAG_PARAM;
  5242. }
  5243. void ggml_set_loss(struct ggml_tensor * tensor) {
  5244. GGML_ASSERT(ggml_is_scalar(tensor));
  5245. GGML_ASSERT(tensor->type == GGML_TYPE_F32);
  5246. tensor->flags |= GGML_TENSOR_FLAG_LOSS;
  5247. }
  5248. ////////////////////////////////////////////////////////////////////////////////
  5249. void ggml_quantize_init(enum ggml_type type) {
  5250. ggml_critical_section_start();
  5251. switch (type) {
  5252. case GGML_TYPE_IQ2_XXS:
  5253. case GGML_TYPE_IQ2_XS:
  5254. case GGML_TYPE_IQ2_S:
  5255. case GGML_TYPE_IQ1_S:
  5256. case GGML_TYPE_IQ1_M: iq2xs_init_impl(type); break;
  5257. case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
  5258. case GGML_TYPE_IQ3_S: iq3xs_init_impl(512); break;
  5259. default: // nothing
  5260. break;
  5261. }
  5262. ggml_critical_section_end();
  5263. }
  5264. void ggml_quantize_free(void) {
  5265. ggml_critical_section_start();
  5266. iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
  5267. iq2xs_free_impl(GGML_TYPE_IQ2_XS);
  5268. iq2xs_free_impl(GGML_TYPE_IQ1_S);
  5269. iq3xs_free_impl(256);
  5270. ggml_critical_section_end();
  5271. }
  5272. bool ggml_quantize_requires_imatrix(enum ggml_type type) {
  5273. return
  5274. type == GGML_TYPE_IQ2_XXS ||
  5275. type == GGML_TYPE_IQ2_XS ||
  5276. type == GGML_TYPE_IQ1_S;// ||
  5277. //type == GGML_TYPE_IQ1_M;
  5278. }
  5279. size_t ggml_quantize_chunk(
  5280. enum ggml_type type,
  5281. const float * src,
  5282. void * dst,
  5283. int64_t start,
  5284. int64_t nrows,
  5285. int64_t n_per_row,
  5286. const float * imatrix) {
  5287. const int64_t n = (int64_t) nrows * n_per_row;
  5288. if (ggml_quantize_requires_imatrix(type)) {
  5289. GGML_ASSERT(imatrix != NULL);
  5290. }
  5291. GGML_ASSERT(start % type_traits[type].blck_size == 0);
  5292. GGML_ASSERT(start % n_per_row == 0);
  5293. ggml_quantize_init(type); // this is noop if already initialized
  5294. const size_t start_row = start / n_per_row;
  5295. const size_t row_size = ggml_row_size(type, n_per_row);
  5296. size_t result = 0;
  5297. switch (type) {
  5298. case GGML_TYPE_Q4_0: result = quantize_q4_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5299. case GGML_TYPE_Q4_1: result = quantize_q4_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5300. case GGML_TYPE_Q5_0: result = quantize_q5_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5301. case GGML_TYPE_Q5_1: result = quantize_q5_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5302. case GGML_TYPE_Q8_0: result = quantize_q8_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5303. case GGML_TYPE_Q2_K: result = quantize_q2_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5304. case GGML_TYPE_Q3_K: result = quantize_q3_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5305. case GGML_TYPE_Q4_K: result = quantize_q4_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5306. case GGML_TYPE_Q5_K: result = quantize_q5_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5307. case GGML_TYPE_Q6_K: result = quantize_q6_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5308. case GGML_TYPE_TQ1_0: result = quantize_tq1_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5309. case GGML_TYPE_TQ2_0: result = quantize_tq2_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5310. case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5311. case GGML_TYPE_IQ2_XS: result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5312. case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5313. case GGML_TYPE_IQ3_S: result = quantize_iq3_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5314. case GGML_TYPE_IQ2_S: result = quantize_iq2_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5315. case GGML_TYPE_IQ1_S: result = quantize_iq1_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5316. case GGML_TYPE_IQ1_M: result = quantize_iq1_m (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5317. case GGML_TYPE_IQ4_NL: result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5318. case GGML_TYPE_IQ4_XS: result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5319. case GGML_TYPE_F16:
  5320. {
  5321. size_t elemsize = sizeof(ggml_fp16_t);
  5322. ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
  5323. result = n * elemsize;
  5324. } break;
  5325. case GGML_TYPE_BF16:
  5326. {
  5327. size_t elemsize = sizeof(ggml_bf16_t);
  5328. ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
  5329. result = n * elemsize;
  5330. } break;
  5331. case GGML_TYPE_F32:
  5332. {
  5333. size_t elemsize = sizeof(float);
  5334. result = n * elemsize;
  5335. memcpy((uint8_t *)dst + start * elemsize, src + start, result);
  5336. } break;
  5337. default:
  5338. assert(false);
  5339. }
  5340. GGML_ASSERT(result == nrows * row_size);
  5341. return result;
  5342. }
  5343. ////////////////////////////////////////////////////////////////////////////////
  5344. struct gguf_str {
  5345. uint64_t n; // GGUFv2
  5346. char * data;
  5347. };
  5348. static const size_t GGUF_TYPE_SIZE[GGUF_TYPE_COUNT] = {
  5349. [GGUF_TYPE_UINT8] = sizeof(uint8_t),
  5350. [GGUF_TYPE_INT8] = sizeof(int8_t),
  5351. [GGUF_TYPE_UINT16] = sizeof(uint16_t),
  5352. [GGUF_TYPE_INT16] = sizeof(int16_t),
  5353. [GGUF_TYPE_UINT32] = sizeof(uint32_t),
  5354. [GGUF_TYPE_INT32] = sizeof(int32_t),
  5355. [GGUF_TYPE_FLOAT32] = sizeof(float),
  5356. [GGUF_TYPE_BOOL] = sizeof(bool),
  5357. [GGUF_TYPE_STRING] = sizeof(struct gguf_str),
  5358. [GGUF_TYPE_UINT64] = sizeof(uint64_t),
  5359. [GGUF_TYPE_INT64] = sizeof(int64_t),
  5360. [GGUF_TYPE_FLOAT64] = sizeof(double),
  5361. [GGUF_TYPE_ARRAY] = 0, // undefined
  5362. };
  5363. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  5364. static const char * GGUF_TYPE_NAME[GGUF_TYPE_COUNT] = {
  5365. [GGUF_TYPE_UINT8] = "u8",
  5366. [GGUF_TYPE_INT8] = "i8",
  5367. [GGUF_TYPE_UINT16] = "u16",
  5368. [GGUF_TYPE_INT16] = "i16",
  5369. [GGUF_TYPE_UINT32] = "u32",
  5370. [GGUF_TYPE_INT32] = "i32",
  5371. [GGUF_TYPE_FLOAT32] = "f32",
  5372. [GGUF_TYPE_BOOL] = "bool",
  5373. [GGUF_TYPE_STRING] = "str",
  5374. [GGUF_TYPE_ARRAY] = "arr",
  5375. [GGUF_TYPE_UINT64] = "u64",
  5376. [GGUF_TYPE_INT64] = "i64",
  5377. [GGUF_TYPE_FLOAT64] = "f64",
  5378. };
  5379. static_assert(GGUF_TYPE_COUNT == 13, "GGUF_TYPE_COUNT != 13");
  5380. union gguf_value {
  5381. uint8_t uint8;
  5382. int8_t int8;
  5383. uint16_t uint16;
  5384. int16_t int16;
  5385. uint32_t uint32;
  5386. int32_t int32;
  5387. float float32;
  5388. uint64_t uint64;
  5389. int64_t int64;
  5390. double float64;
  5391. bool bool_;
  5392. struct gguf_str str;
  5393. struct {
  5394. enum gguf_type type;
  5395. uint64_t n; // GGUFv2
  5396. void * data;
  5397. } arr;
  5398. };
  5399. struct gguf_kv {
  5400. struct gguf_str key;
  5401. enum gguf_type type;
  5402. union gguf_value value;
  5403. };
  5404. struct gguf_header {
  5405. char magic[4];
  5406. uint32_t version;
  5407. uint64_t n_tensors; // GGUFv2
  5408. uint64_t n_kv; // GGUFv2
  5409. };
  5410. struct gguf_tensor_info {
  5411. struct gguf_str name;
  5412. uint32_t n_dims;
  5413. uint64_t ne[GGML_MAX_DIMS];
  5414. enum ggml_type type;
  5415. uint64_t offset; // offset from start of `data`, must be a multiple of `ALIGNMENT`
  5416. // for writing API
  5417. const void * data;
  5418. size_t size;
  5419. };
  5420. struct gguf_context {
  5421. struct gguf_header header;
  5422. struct gguf_kv * kv;
  5423. struct gguf_tensor_info * infos;
  5424. size_t alignment;
  5425. size_t offset; // offset of `data` from beginning of file
  5426. size_t size; // size of `data` in bytes
  5427. //uint8_t * padding;
  5428. void * data;
  5429. };
  5430. size_t gguf_type_size(enum gguf_type type) {
  5431. GGML_ASSERT(0 <= type && type < GGUF_TYPE_COUNT);
  5432. return GGUF_TYPE_SIZE[type];
  5433. }
  5434. static bool gguf_tensor_info_sanitize(struct gguf_tensor_info * info) {
  5435. if (info->n_dims > GGML_MAX_DIMS) {
  5436. fprintf(stderr, "%s: invalid number of dimensions (%" PRIu32 ")\n", __func__, info->n_dims);
  5437. return false;
  5438. }
  5439. if (info->type < 0 || info->type >= GGML_TYPE_COUNT) {
  5440. fprintf(stderr, "%s: invalid type (%d)\n", __func__, info->type);
  5441. return false;
  5442. }
  5443. if (strlen(info->name.data) >= GGML_MAX_NAME) {
  5444. fprintf(stderr, "%s: tensor '%s' name is too long\n", __func__, info->name.data);
  5445. return false;
  5446. }
  5447. for (uint32_t i = 0; i < info->n_dims; ++i) {
  5448. if (info->ne[i] <= 0) {
  5449. fprintf(stderr, "%s: invalid number of elements (%" PRIu64 ")\n", __func__, info->ne[i]);
  5450. return false;
  5451. }
  5452. }
  5453. // prevent overflow for total number of elements
  5454. if (INT64_MAX/info->ne[1] <= info->ne[0]) {
  5455. fprintf(stderr, "%s: invalid number of elements (%" PRIu64 ")\n", __func__, info->ne[1]);
  5456. return false;
  5457. }
  5458. if (INT64_MAX/info->ne[2] <= info->ne[0]*info->ne[1]) {
  5459. fprintf(stderr, "%s: invalid number of elements (%" PRIu64 ")\n", __func__, info->ne[2]);
  5460. return false;
  5461. }
  5462. if (INT64_MAX/info->ne[3] <= info->ne[0]*info->ne[1]*info->ne[2]) {
  5463. fprintf(stderr, "%s: invalid number of elements (%" PRIu64 ")\n", __func__, info->ne[3]);
  5464. return false;
  5465. }
  5466. return true;
  5467. }
  5468. static bool gguf_fread_el(FILE * file, void * dst, size_t size, size_t * offset) {
  5469. const size_t n = fread(dst, 1, size, file);
  5470. *offset += n;
  5471. return n == size;
  5472. }
  5473. static bool gguf_fread_str(FILE * file, struct gguf_str * p, size_t * offset) {
  5474. p->n = 0;
  5475. p->data = NULL;
  5476. bool ok = true;
  5477. ok = ok && gguf_fread_el(file, &p->n, sizeof(p->n), offset);
  5478. // early exit if string length is invalid, prevents from integer overflow
  5479. if (p->n == SIZE_MAX) {
  5480. fprintf(stderr, "%s: invalid string length (%" PRIu64 ")\n", __func__, p->n);
  5481. return false;
  5482. }
  5483. p->data = calloc(p->n + 1, 1);
  5484. if (!p->data) {
  5485. fprintf(stderr, "%s: failed to allocate memory for string of length %" PRIu64 "\n", __func__, p->n);
  5486. return false;
  5487. }
  5488. ok = ok && gguf_fread_el(file, p->data, p->n, offset);
  5489. return ok;
  5490. }
  5491. static void gguf_free_kv(struct gguf_kv * kv) {
  5492. if (kv->key.data) {
  5493. GGML_FREE(kv->key.data);
  5494. }
  5495. if (kv->type == GGUF_TYPE_STRING) {
  5496. if (kv->value.str.data) {
  5497. GGML_FREE(kv->value.str.data);
  5498. }
  5499. }
  5500. if (kv->type == GGUF_TYPE_ARRAY) {
  5501. if (kv->value.arr.data) {
  5502. if (kv->value.arr.type == GGUF_TYPE_STRING) {
  5503. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  5504. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[j];
  5505. if (str->data) {
  5506. GGML_FREE(str->data);
  5507. }
  5508. }
  5509. }
  5510. GGML_FREE(kv->value.arr.data);
  5511. }
  5512. }
  5513. }
  5514. struct gguf_context * gguf_init_empty(void) {
  5515. struct gguf_context * ctx = calloc(1, sizeof(struct gguf_context));
  5516. if (!ctx) {
  5517. fprintf(stderr, "%s: failed to allocate memory for context\n", __func__);
  5518. return NULL;
  5519. }
  5520. memcpy(ctx->header.magic, GGUF_MAGIC, sizeof(ctx->header.magic));
  5521. ctx->header.version = GGUF_VERSION;
  5522. ctx->header.n_tensors = 0;
  5523. ctx->header.n_kv = 0;
  5524. ctx->kv = NULL;
  5525. ctx->infos = NULL;
  5526. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  5527. ctx->offset = 0;
  5528. ctx->size = 0;
  5529. ctx->data = NULL;
  5530. return ctx;
  5531. }
  5532. struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params) {
  5533. // offset from start of file
  5534. size_t offset = 0;
  5535. char magic[4];
  5536. // check the magic before making allocations
  5537. {
  5538. gguf_fread_el(file, &magic, sizeof(magic), &offset);
  5539. for (uint32_t i = 0; i < sizeof(magic); i++) {
  5540. if (magic[i] != GGUF_MAGIC[i]) {
  5541. fprintf(stderr, "%s: invalid magic characters '%c%c%c%c'\n", __func__, magic[0], magic[1], magic[2], magic[3]);
  5542. return NULL;
  5543. }
  5544. }
  5545. }
  5546. bool ok = true;
  5547. struct gguf_context * ctx = calloc(1, sizeof(struct gguf_context));
  5548. if (!ctx) {
  5549. fprintf(stderr, "%s: failed to allocate memory for context\n", __func__);
  5550. return NULL;
  5551. }
  5552. // read the header
  5553. {
  5554. strncpy(ctx->header.magic, magic, 4);
  5555. ctx->kv = NULL;
  5556. ctx->infos = NULL;
  5557. ctx->data = NULL;
  5558. ok = ok && gguf_fread_el(file, &ctx->header.version, sizeof(ctx->header.version), &offset);
  5559. ok = ok && gguf_fread_el(file, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors), &offset);
  5560. ok = ok && gguf_fread_el(file, &ctx->header.n_kv, sizeof(ctx->header.n_kv), &offset);
  5561. if (ctx->header.version == 1) {
  5562. fprintf(stderr, "%s: GGUFv1 is no longer supported. please use a more up-to-date version\n", __func__);
  5563. gguf_free(ctx);
  5564. return NULL;
  5565. }
  5566. // sanity-checks to prevent from integer/buffer overflows
  5567. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/sizeof(struct gguf_tensor_info));
  5568. ok = ok && (ctx->header.n_tensors < (SIZE_MAX/2)/ggml_tensor_overhead());
  5569. ok = ok && (ctx->header.n_kv < (SIZE_MAX/2)/sizeof(struct gguf_kv));
  5570. if (!ok) {
  5571. fprintf(stderr, "%s: failed to read header\n", __func__);
  5572. gguf_free(ctx);
  5573. return NULL;
  5574. }
  5575. }
  5576. // read the kv pairs
  5577. {
  5578. const uint64_t n_kv = ctx->header.n_kv;
  5579. if (n_kv > 0) {
  5580. ctx->kv = calloc(n_kv, sizeof(struct gguf_kv));
  5581. if (!ctx->kv) {
  5582. fprintf(stderr, "%s: failed to allocate memory for kv pairs\n", __func__);
  5583. gguf_free(ctx);
  5584. return NULL;
  5585. }
  5586. }
  5587. for (uint64_t i = 0; i < n_kv; ++i) {
  5588. struct gguf_kv * kv = &ctx->kv[i];
  5589. //fprintf(stderr, "%s: reading kv %d\n", __func__, i);
  5590. ok = ok && gguf_fread_str(file, &kv->key, &offset);
  5591. ok = ok && gguf_fread_el (file, &kv->type, sizeof(kv->type), &offset);
  5592. //fprintf(stderr, "%s: reading kv with key %s\n", __func__, kv->key.data);
  5593. switch (kv->type) {
  5594. case GGUF_TYPE_UINT8: ok = ok && gguf_fread_el (file, &kv->value.uint8, sizeof(kv->value.uint8), &offset); break;
  5595. case GGUF_TYPE_INT8: ok = ok && gguf_fread_el (file, &kv->value.int8, sizeof(kv->value.int8), &offset); break;
  5596. case GGUF_TYPE_UINT16: ok = ok && gguf_fread_el (file, &kv->value.uint16, sizeof(kv->value.uint16), &offset); break;
  5597. case GGUF_TYPE_INT16: ok = ok && gguf_fread_el (file, &kv->value.int16, sizeof(kv->value.int16), &offset); break;
  5598. case GGUF_TYPE_UINT32: ok = ok && gguf_fread_el (file, &kv->value.uint32, sizeof(kv->value.uint32), &offset); break;
  5599. case GGUF_TYPE_INT32: ok = ok && gguf_fread_el (file, &kv->value.int32, sizeof(kv->value.int32), &offset); break;
  5600. case GGUF_TYPE_FLOAT32: ok = ok && gguf_fread_el (file, &kv->value.float32, sizeof(kv->value.float32), &offset); break;
  5601. case GGUF_TYPE_UINT64: ok = ok && gguf_fread_el (file, &kv->value.uint64, sizeof(kv->value.uint64), &offset); break;
  5602. case GGUF_TYPE_INT64: ok = ok && gguf_fread_el (file, &kv->value.int64, sizeof(kv->value.int64), &offset); break;
  5603. case GGUF_TYPE_FLOAT64: ok = ok && gguf_fread_el (file, &kv->value.float64, sizeof(kv->value.float64), &offset); break;
  5604. case GGUF_TYPE_BOOL: ok = ok && gguf_fread_el (file, &kv->value.bool_, sizeof(kv->value.bool_), &offset); break;
  5605. case GGUF_TYPE_STRING: ok = ok && gguf_fread_str(file, &kv->value.str, &offset); break;
  5606. case GGUF_TYPE_ARRAY:
  5607. {
  5608. ok = ok && gguf_fread_el(file, &kv->value.arr.type, sizeof(kv->value.arr.type), &offset);
  5609. ok = ok && gguf_fread_el(file, &kv->value.arr.n, sizeof(kv->value.arr.n), &offset);
  5610. switch (kv->value.arr.type) {
  5611. case GGUF_TYPE_UINT8:
  5612. case GGUF_TYPE_INT8:
  5613. case GGUF_TYPE_UINT16:
  5614. case GGUF_TYPE_INT16:
  5615. case GGUF_TYPE_UINT32:
  5616. case GGUF_TYPE_INT32:
  5617. case GGUF_TYPE_FLOAT32:
  5618. case GGUF_TYPE_UINT64:
  5619. case GGUF_TYPE_INT64:
  5620. case GGUF_TYPE_FLOAT64:
  5621. case GGUF_TYPE_BOOL:
  5622. {
  5623. // prevent from integer overflow in the malloc below
  5624. if (kv->value.arr.n >= SIZE_MAX/gguf_type_size(kv->value.arr.type)) {
  5625. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  5626. gguf_free(ctx);
  5627. return NULL;
  5628. }
  5629. kv->value.arr.data = calloc(kv->value.arr.n, gguf_type_size(kv->value.arr.type));
  5630. if (!kv->value.arr.data) {
  5631. fprintf(stderr, "%s: failed to allocate memory for array\n", __func__);
  5632. gguf_free(ctx);
  5633. return NULL;
  5634. }
  5635. ok = ok && gguf_fread_el(file, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type), &offset);
  5636. } break;
  5637. case GGUF_TYPE_STRING:
  5638. {
  5639. // prevent from integer overflow in the malloc below
  5640. if (kv->value.arr.n >= SIZE_MAX/sizeof(struct gguf_str)) {
  5641. fprintf(stderr, "%s: array size is too large (%" PRIu64 ")\n", __func__, kv->value.arr.n);
  5642. gguf_free(ctx);
  5643. return NULL;
  5644. }
  5645. kv->value.arr.data = calloc(kv->value.arr.n, sizeof(struct gguf_str));
  5646. if (!kv->value.arr.data) {
  5647. fprintf(stderr, "%s: failed to allocate memory for array\n", __func__);
  5648. gguf_free(ctx);
  5649. return NULL;
  5650. }
  5651. for (uint64_t j = 0; j < kv->value.arr.n; ++j) {
  5652. ok = ok && gguf_fread_str(file, &((struct gguf_str *) kv->value.arr.data)[j], &offset);
  5653. }
  5654. } break;
  5655. case GGUF_TYPE_ARRAY:
  5656. default:
  5657. {
  5658. fprintf(stderr, "%s: invalid array type %d\n", __func__, kv->value.arr.type);
  5659. ok = false;
  5660. } break;
  5661. }
  5662. } break;
  5663. default:
  5664. {
  5665. fprintf(stderr, "%s: invalid type %d\n", __func__, kv->type);
  5666. ok = false;
  5667. } break;
  5668. }
  5669. if (!ok) {
  5670. break;
  5671. }
  5672. }
  5673. if (!ok) {
  5674. fprintf(stderr, "%s: failed to read key-value pairs\n", __func__);
  5675. gguf_free(ctx);
  5676. return NULL;
  5677. }
  5678. }
  5679. // read the tensor infos
  5680. if (ctx->header.n_tensors > 0) {
  5681. ctx->infos = calloc(ctx->header.n_tensors, sizeof(struct gguf_tensor_info));
  5682. if (!ctx->infos) {
  5683. fprintf(stderr, "%s: failed to allocate memory for tensor infos\n", __func__);
  5684. gguf_free(ctx);
  5685. return NULL;
  5686. }
  5687. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  5688. struct gguf_tensor_info * info = &ctx->infos[i];
  5689. for (int j = 0; j < GGML_MAX_DIMS; ++j) {
  5690. info->ne[j] = 1;
  5691. }
  5692. ok = ok && gguf_fread_str(file, &info->name, &offset);
  5693. ok = ok && gguf_fread_el (file, &info->n_dims, sizeof(info->n_dims), &offset);
  5694. ok = ok && (info->n_dims <= GGML_MAX_DIMS);
  5695. for (uint32_t j = 0; j < info->n_dims; ++j) {
  5696. ok = ok && gguf_fread_el(file, &info->ne[j], sizeof(info->ne[j]), &offset);
  5697. }
  5698. ok = ok && gguf_fread_el (file, &info->type, sizeof(info->type), &offset);
  5699. ok = ok && gguf_fread_el (file, &info->offset, sizeof(info->offset), &offset);
  5700. ok = ok && gguf_tensor_info_sanitize(info);
  5701. // make sure there is no duplicated tensor names
  5702. for (uint64_t j = 0; j < i && ok; ++j) {
  5703. if (strcmp(info->name.data, ctx->infos[j].name.data) == 0) {
  5704. fprintf(stderr, "%s: duplicated tensor name %s\n", __func__, info->name.data);
  5705. ok = false;
  5706. }
  5707. }
  5708. if (!ok) {
  5709. fprintf(stderr, "%s: failed to read tensor info\n", __func__);
  5710. gguf_free(ctx);
  5711. return NULL;
  5712. }
  5713. }
  5714. }
  5715. ctx->alignment = GGUF_DEFAULT_ALIGNMENT;
  5716. int alignment_idx = gguf_find_key(ctx, "general.alignment");
  5717. if (alignment_idx != -1) {
  5718. ctx->alignment = gguf_get_val_u32(ctx, alignment_idx);
  5719. }
  5720. // we require the data section to be aligned, so take into account any padding
  5721. {
  5722. const size_t offset_pad = offset % ctx->alignment;
  5723. if (offset_pad != 0) {
  5724. offset += ctx->alignment - offset_pad;
  5725. fseek(file, offset, SEEK_SET);
  5726. }
  5727. }
  5728. // store the current file offset - this is where the data section starts
  5729. ctx->offset = offset;
  5730. // compute the total size of the data section, taking into account the alignment
  5731. {
  5732. ctx->size = 0;
  5733. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  5734. struct gguf_tensor_info * info = &ctx->infos[i];
  5735. const int64_t ne =
  5736. (int64_t) info->ne[0] *
  5737. (int64_t) info->ne[1] *
  5738. (int64_t) info->ne[2] *
  5739. (int64_t) info->ne[3];
  5740. if (ggml_blck_size(info->type) == 0 ) {
  5741. // this tensor type support have been removed:
  5742. fprintf(stderr, "%s: tensor '%s' of type %d: %s\n",
  5743. __func__, info->name.data, (int) info->type, ggml_type_name(info->type));
  5744. gguf_free(ctx);
  5745. return NULL;
  5746. }
  5747. if (ne % ggml_blck_size(info->type) != 0) {
  5748. fprintf(stderr, "%s: tensor '%s' of type %d (%s) number of elements (%" PRId64 ") is not a multiple of block size (%" PRId64 ")\n",
  5749. __func__, info->name.data, (int) info->type, ggml_type_name(info->type), ne, ggml_blck_size(info->type));
  5750. gguf_free(ctx);
  5751. return NULL;
  5752. }
  5753. const size_t size_cur = ggml_row_size(info->type, ne);
  5754. ctx->size += GGML_PAD(size_cur, ctx->alignment);
  5755. }
  5756. }
  5757. // load the tensor data only if requested
  5758. if (params.ctx != NULL) {
  5759. // if the provided gguf_context is no_alloc, then we create "empty" tensors and do not read the binary blob
  5760. // otherwise, we load the binary blob into the created ggml_context as well, and point the "data" members of
  5761. // the ggml_tensor structs to the appropriate locations in the binary blob
  5762. // compute the exact size needed for the new ggml_context
  5763. const size_t mem_size =
  5764. params.no_alloc ?
  5765. (ctx->header.n_tensors )*ggml_tensor_overhead() :
  5766. (ctx->header.n_tensors + 1)*ggml_tensor_overhead() + ctx->size;
  5767. struct ggml_init_params pdata = {
  5768. .mem_size = mem_size,
  5769. .mem_buffer = NULL,
  5770. .no_alloc = params.no_alloc,
  5771. };
  5772. *params.ctx = ggml_init(pdata);
  5773. if (*params.ctx == NULL) {
  5774. fprintf(stderr, "%s: failed to initialize context\n", __func__);
  5775. gguf_free(ctx);
  5776. return NULL;
  5777. }
  5778. struct ggml_context * ctx_data = *params.ctx;
  5779. struct ggml_tensor * data = NULL;
  5780. if (!params.no_alloc) {
  5781. data = ggml_new_tensor_1d(ctx_data, GGML_TYPE_I8, ctx->size);
  5782. ok = ok && data != NULL;
  5783. // read the binary blob with the tensor data
  5784. ok = ok && gguf_fread_el(file, data->data, ctx->size, &offset);
  5785. if (!ok) {
  5786. fprintf(stderr, "%s: failed to read tensor data\n", __func__);
  5787. ggml_free(ctx_data);
  5788. gguf_free(ctx);
  5789. return NULL;
  5790. }
  5791. ctx->data = data->data;
  5792. }
  5793. ggml_set_no_alloc(ctx_data, true);
  5794. // create the tensors
  5795. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  5796. const int64_t ne[GGML_MAX_DIMS] = {
  5797. ctx->infos[i].ne[0],
  5798. ctx->infos[i].ne[1],
  5799. ctx->infos[i].ne[2],
  5800. ctx->infos[i].ne[3],
  5801. };
  5802. struct ggml_tensor * cur = ggml_new_tensor(ctx_data, ctx->infos[i].type, ctx->infos[i].n_dims, ne);
  5803. ok = ok && cur != NULL;
  5804. if (!ok) {
  5805. break;
  5806. }
  5807. ggml_set_name(cur, ctx->infos[i].name.data);
  5808. // point the data member to the appropriate location in the binary blob using the tensor infos
  5809. if (!params.no_alloc) {
  5810. //cur->data = (char *) data->data + ctx->infos[i].offset - ctx->offset; // offset from start of file
  5811. cur->data = (char *) data->data + ctx->infos[i].offset; // offset from data
  5812. }
  5813. }
  5814. if (!ok) {
  5815. fprintf(stderr, "%s: failed to read the tensor data\n", __func__);
  5816. ggml_free(ctx_data);
  5817. gguf_free(ctx);
  5818. return NULL;
  5819. }
  5820. ggml_set_no_alloc(ctx_data, params.no_alloc);
  5821. }
  5822. return ctx;
  5823. }
  5824. struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params) {
  5825. FILE * file = ggml_fopen(fname, "rb");
  5826. if (!file) {
  5827. fprintf(stderr, "%s: failed to open '%s': '%s'\n", __func__, fname, strerror(errno));
  5828. return NULL;
  5829. }
  5830. struct gguf_context * result = gguf_init_from_file_impl(file, params);
  5831. fclose(file);
  5832. return result;
  5833. }
  5834. void gguf_free(struct gguf_context * ctx) {
  5835. if (ctx == NULL) {
  5836. return;
  5837. }
  5838. if (ctx->kv) {
  5839. // free string memory - not great..
  5840. for (uint64_t i = 0; i < ctx->header.n_kv; ++i) {
  5841. gguf_free_kv(&ctx->kv[i]);
  5842. }
  5843. GGML_FREE(ctx->kv);
  5844. }
  5845. if (ctx->infos) {
  5846. for (uint64_t i = 0; i < ctx->header.n_tensors; ++i) {
  5847. struct gguf_tensor_info * info = &ctx->infos[i];
  5848. if (info->name.data) {
  5849. GGML_FREE(info->name.data);
  5850. }
  5851. }
  5852. GGML_FREE(ctx->infos);
  5853. }
  5854. GGML_FREE(ctx);
  5855. }
  5856. const char * gguf_type_name(enum gguf_type type) {
  5857. return GGUF_TYPE_NAME[type];
  5858. }
  5859. int gguf_get_version(const struct gguf_context * ctx) {
  5860. return ctx->header.version;
  5861. }
  5862. size_t gguf_get_alignment(const struct gguf_context * ctx) {
  5863. return ctx->alignment;
  5864. }
  5865. size_t gguf_get_data_offset(const struct gguf_context * ctx) {
  5866. return ctx->offset;
  5867. }
  5868. void * gguf_get_data(const struct gguf_context * ctx) {
  5869. return ctx->data;
  5870. }
  5871. int gguf_get_n_kv(const struct gguf_context * ctx) {
  5872. return ctx->header.n_kv;
  5873. }
  5874. int gguf_find_key(const struct gguf_context * ctx, const char * key) {
  5875. // return -1 if key not found
  5876. int keyfound = -1;
  5877. const int n_kv = gguf_get_n_kv(ctx);
  5878. for (int i = 0; i < n_kv; ++i) {
  5879. if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
  5880. keyfound = i;
  5881. break;
  5882. }
  5883. }
  5884. return keyfound;
  5885. }
  5886. const char * gguf_get_key(const struct gguf_context * ctx, int key_id) {
  5887. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5888. return ctx->kv[key_id].key.data;
  5889. }
  5890. enum gguf_type gguf_get_kv_type(const struct gguf_context * ctx, int key_id) {
  5891. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5892. return ctx->kv[key_id].type;
  5893. }
  5894. enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int key_id) {
  5895. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5896. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  5897. return ctx->kv[key_id].value.arr.type;
  5898. }
  5899. const void * gguf_get_arr_data(const struct gguf_context * ctx, int key_id) {
  5900. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5901. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  5902. return ctx->kv[key_id].value.arr.data;
  5903. }
  5904. const char * gguf_get_arr_str(const struct gguf_context * ctx, int key_id, int i) {
  5905. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5906. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  5907. struct gguf_kv * kv = &ctx->kv[key_id];
  5908. struct gguf_str * str = &((struct gguf_str *) kv->value.arr.data)[i];
  5909. return str->data;
  5910. }
  5911. int gguf_get_arr_n(const struct gguf_context * ctx, int key_id) {
  5912. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5913. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_ARRAY);
  5914. return ctx->kv[key_id].value.arr.n;
  5915. }
  5916. uint8_t gguf_get_val_u8(const struct gguf_context * ctx, int key_id) {
  5917. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5918. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT8);
  5919. return ctx->kv[key_id].value.uint8;
  5920. }
  5921. int8_t gguf_get_val_i8(const struct gguf_context * ctx, int key_id) {
  5922. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5923. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT8);
  5924. return ctx->kv[key_id].value.int8;
  5925. }
  5926. uint16_t gguf_get_val_u16(const struct gguf_context * ctx, int key_id) {
  5927. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5928. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT16);
  5929. return ctx->kv[key_id].value.uint16;
  5930. }
  5931. int16_t gguf_get_val_i16(const struct gguf_context * ctx, int key_id) {
  5932. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5933. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT16);
  5934. return ctx->kv[key_id].value.int16;
  5935. }
  5936. uint32_t gguf_get_val_u32(const struct gguf_context * ctx, int key_id) {
  5937. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5938. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT32);
  5939. return ctx->kv[key_id].value.uint32;
  5940. }
  5941. int32_t gguf_get_val_i32(const struct gguf_context * ctx, int key_id) {
  5942. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5943. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT32);
  5944. return ctx->kv[key_id].value.int32;
  5945. }
  5946. float gguf_get_val_f32(const struct gguf_context * ctx, int key_id) {
  5947. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5948. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT32);
  5949. return ctx->kv[key_id].value.float32;
  5950. }
  5951. uint64_t gguf_get_val_u64(const struct gguf_context * ctx, int key_id) {
  5952. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5953. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_UINT64);
  5954. return ctx->kv[key_id].value.uint64;
  5955. }
  5956. int64_t gguf_get_val_i64(const struct gguf_context * ctx, int key_id) {
  5957. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5958. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_INT64);
  5959. return ctx->kv[key_id].value.int64;
  5960. }
  5961. double gguf_get_val_f64(const struct gguf_context * ctx, int key_id) {
  5962. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5963. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_FLOAT64);
  5964. return ctx->kv[key_id].value.float64;
  5965. }
  5966. bool gguf_get_val_bool(const struct gguf_context * ctx, int key_id) {
  5967. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5968. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_BOOL);
  5969. return ctx->kv[key_id].value.bool_;
  5970. }
  5971. const char * gguf_get_val_str(const struct gguf_context * ctx, int key_id) {
  5972. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5973. GGML_ASSERT(ctx->kv[key_id].type == GGUF_TYPE_STRING);
  5974. return ctx->kv[key_id].value.str.data;
  5975. }
  5976. const void * gguf_get_val_data(const struct gguf_context * ctx, int key_id) {
  5977. GGML_ASSERT(key_id >= 0 && key_id < gguf_get_n_kv(ctx));
  5978. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_ARRAY);
  5979. GGML_ASSERT(ctx->kv[key_id].type != GGUF_TYPE_STRING);
  5980. return &ctx->kv[key_id].value;
  5981. }
  5982. int gguf_get_n_tensors(const struct gguf_context * ctx) {
  5983. return ctx->header.n_tensors;
  5984. }
  5985. int gguf_find_tensor(const struct gguf_context * ctx, const char * name) {
  5986. // return -1 if tensor not found
  5987. int tensorfound = -1;
  5988. const int n_tensors = gguf_get_n_tensors(ctx);
  5989. for (int i = 0; i < n_tensors; ++i) {
  5990. if (strcmp(name, gguf_get_tensor_name(ctx, i)) == 0) {
  5991. tensorfound = i;
  5992. break;
  5993. }
  5994. }
  5995. return tensorfound;
  5996. }
  5997. size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int i) {
  5998. return ctx->infos[i].offset;
  5999. }
  6000. char * gguf_get_tensor_name(const struct gguf_context * ctx, int i) {
  6001. return ctx->infos[i].name.data;
  6002. }
  6003. enum ggml_type gguf_get_tensor_type(const struct gguf_context * ctx, int i) {
  6004. return ctx->infos[i].type;
  6005. }
  6006. // returns the index
  6007. static int gguf_get_or_add_key(struct gguf_context * ctx, const char * key) {
  6008. const int idx = gguf_find_key(ctx, key);
  6009. if (idx >= 0) {
  6010. return idx;
  6011. }
  6012. const int n_kv = gguf_get_n_kv(ctx);
  6013. ctx->kv = realloc(ctx->kv, (n_kv + 1) * sizeof(struct gguf_kv));
  6014. ctx->kv[n_kv].key.n = strlen(key);
  6015. ctx->kv[n_kv].key.data = strdup(key);
  6016. ctx->header.n_kv++;
  6017. return n_kv;
  6018. }
  6019. void gguf_remove_key(struct gguf_context * ctx, const char * key) {
  6020. const int idx = gguf_find_key(ctx, key);
  6021. if (idx >= 0) {
  6022. const int n_kv = gguf_get_n_kv(ctx);
  6023. gguf_free_kv(&ctx->kv[idx]);
  6024. for (int i = idx; i < n_kv-1; ++i) {
  6025. ctx->kv[i] = ctx->kv[i+1];
  6026. }
  6027. ctx->kv = realloc(ctx->kv, (n_kv - 1) * sizeof(struct gguf_kv));
  6028. ctx->header.n_kv--;
  6029. }
  6030. }
  6031. void gguf_set_val_u8(struct gguf_context * ctx, const char * key, uint8_t val) {
  6032. const int idx = gguf_get_or_add_key(ctx, key);
  6033. ctx->kv[idx].type = GGUF_TYPE_UINT8;
  6034. ctx->kv[idx].value.uint8 = val;
  6035. }
  6036. void gguf_set_val_i8(struct gguf_context * ctx, const char * key, int8_t val) {
  6037. const int idx = gguf_get_or_add_key(ctx, key);
  6038. ctx->kv[idx].type = GGUF_TYPE_INT8;
  6039. ctx->kv[idx].value.int8 = val;
  6040. }
  6041. void gguf_set_val_u16(struct gguf_context * ctx, const char * key, uint16_t val) {
  6042. const int idx = gguf_get_or_add_key(ctx, key);
  6043. ctx->kv[idx].type = GGUF_TYPE_UINT16;
  6044. ctx->kv[idx].value.uint16 = val;
  6045. }
  6046. void gguf_set_val_i16(struct gguf_context * ctx, const char * key, int16_t val) {
  6047. const int idx = gguf_get_or_add_key(ctx, key);
  6048. ctx->kv[idx].type = GGUF_TYPE_INT16;
  6049. ctx->kv[idx].value.int16 = val;
  6050. }
  6051. void gguf_set_val_u32(struct gguf_context * ctx, const char * key, uint32_t val) {
  6052. const int idx = gguf_get_or_add_key(ctx, key);
  6053. ctx->kv[idx].type = GGUF_TYPE_UINT32;
  6054. ctx->kv[idx].value.uint32 = val;
  6055. }
  6056. void gguf_set_val_i32(struct gguf_context * ctx, const char * key, int32_t val) {
  6057. const int idx = gguf_get_or_add_key(ctx, key);
  6058. ctx->kv[idx].type = GGUF_TYPE_INT32;
  6059. ctx->kv[idx].value.int32 = val;
  6060. }
  6061. void gguf_set_val_f32(struct gguf_context * ctx, const char * key, float val) {
  6062. const int idx = gguf_get_or_add_key(ctx, key);
  6063. ctx->kv[idx].type = GGUF_TYPE_FLOAT32;
  6064. ctx->kv[idx].value.float32 = val;
  6065. }
  6066. void gguf_set_val_u64(struct gguf_context * ctx, const char * key, uint64_t val) {
  6067. const int idx = gguf_get_or_add_key(ctx, key);
  6068. ctx->kv[idx].type = GGUF_TYPE_UINT64;
  6069. ctx->kv[idx].value.uint64 = val;
  6070. }
  6071. void gguf_set_val_i64(struct gguf_context * ctx, const char * key, int64_t val) {
  6072. const int idx = gguf_get_or_add_key(ctx, key);
  6073. ctx->kv[idx].type = GGUF_TYPE_INT64;
  6074. ctx->kv[idx].value.int64 = val;
  6075. }
  6076. void gguf_set_val_f64(struct gguf_context * ctx, const char * key, double val) {
  6077. const int idx = gguf_get_or_add_key(ctx, key);
  6078. ctx->kv[idx].type = GGUF_TYPE_FLOAT64;
  6079. ctx->kv[idx].value.float64 = val;
  6080. }
  6081. void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val) {
  6082. const int idx = gguf_get_or_add_key(ctx, key);
  6083. ctx->kv[idx].type = GGUF_TYPE_BOOL;
  6084. ctx->kv[idx].value.bool_ = val;
  6085. }
  6086. void gguf_set_val_str(struct gguf_context * ctx, const char * key, const char * val) {
  6087. const int idx = gguf_get_or_add_key(ctx, key);
  6088. ctx->kv[idx].type = GGUF_TYPE_STRING;
  6089. ctx->kv[idx].value.str.n = strlen(val);
  6090. ctx->kv[idx].value.str.data = strdup(val);
  6091. }
  6092. void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, int n) {
  6093. const int idx = gguf_get_or_add_key(ctx, key);
  6094. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  6095. ctx->kv[idx].value.arr.type = type;
  6096. ctx->kv[idx].value.arr.n = n;
  6097. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, gguf_type_size(type));
  6098. memcpy(ctx->kv[idx].value.arr.data, data, n*gguf_type_size(type));
  6099. }
  6100. void gguf_set_arr_str(struct gguf_context * ctx, const char * key, const char ** data, int n) {
  6101. const int idx = gguf_get_or_add_key(ctx, key);
  6102. ctx->kv[idx].type = GGUF_TYPE_ARRAY;
  6103. ctx->kv[idx].value.arr.type = GGUF_TYPE_STRING;
  6104. ctx->kv[idx].value.arr.n = n;
  6105. ctx->kv[idx].value.arr.data = GGML_CALLOC(n, sizeof(struct gguf_str));
  6106. for (int i = 0; i < n; i++) {
  6107. struct gguf_str * str = &((struct gguf_str *)ctx->kv[idx].value.arr.data)[i];
  6108. str->n = strlen(data[i]);
  6109. str->data = strdup(data[i]);
  6110. }
  6111. }
  6112. // set or add KV pairs from another context
  6113. void gguf_set_kv(struct gguf_context * ctx, struct gguf_context * src) {
  6114. for (uint32_t i = 0; i < src->header.n_kv; i++) {
  6115. switch (src->kv[i].type) {
  6116. case GGUF_TYPE_UINT8: gguf_set_val_u8 (ctx, src->kv[i].key.data, src->kv[i].value.uint8); break;
  6117. case GGUF_TYPE_INT8: gguf_set_val_i8 (ctx, src->kv[i].key.data, src->kv[i].value.int8); break;
  6118. case GGUF_TYPE_UINT16: gguf_set_val_u16 (ctx, src->kv[i].key.data, src->kv[i].value.uint16); break;
  6119. case GGUF_TYPE_INT16: gguf_set_val_i16 (ctx, src->kv[i].key.data, src->kv[i].value.int16); break;
  6120. case GGUF_TYPE_UINT32: gguf_set_val_u32 (ctx, src->kv[i].key.data, src->kv[i].value.uint32); break;
  6121. case GGUF_TYPE_INT32: gguf_set_val_i32 (ctx, src->kv[i].key.data, src->kv[i].value.int32); break;
  6122. case GGUF_TYPE_FLOAT32: gguf_set_val_f32 (ctx, src->kv[i].key.data, src->kv[i].value.float32); break;
  6123. case GGUF_TYPE_UINT64: gguf_set_val_u64 (ctx, src->kv[i].key.data, src->kv[i].value.uint64); break;
  6124. case GGUF_TYPE_INT64: gguf_set_val_i64 (ctx, src->kv[i].key.data, src->kv[i].value.int64); break;
  6125. case GGUF_TYPE_FLOAT64: gguf_set_val_f64 (ctx, src->kv[i].key.data, src->kv[i].value.float64); break;
  6126. case GGUF_TYPE_BOOL: gguf_set_val_bool(ctx, src->kv[i].key.data, src->kv[i].value.bool_); break;
  6127. case GGUF_TYPE_STRING: gguf_set_val_str (ctx, src->kv[i].key.data, src->kv[i].value.str.data); break;
  6128. case GGUF_TYPE_ARRAY:
  6129. {
  6130. if (src->kv[i].value.arr.type == GGUF_TYPE_STRING) {
  6131. const char ** data = GGML_CALLOC(src->kv[i].value.arr.n, sizeof(char *));
  6132. for (uint32_t j = 0; j < src->kv[i].value.arr.n; j++) {
  6133. data[j] = ((struct gguf_str *)src->kv[i].value.arr.data)[j].data;
  6134. }
  6135. gguf_set_arr_str(ctx, src->kv[i].key.data, data, src->kv[i].value.arr.n);
  6136. GGML_FREE((void *)data);
  6137. } else if (src->kv[i].value.arr.type == GGUF_TYPE_ARRAY) {
  6138. GGML_ABORT("nested arrays not supported");
  6139. } else {
  6140. gguf_set_arr_data(ctx, src->kv[i].key.data, src->kv[i].value.arr.type, src->kv[i].value.arr.data, src->kv[i].value.arr.n);
  6141. }
  6142. } break;
  6143. default: GGML_ABORT("invalid type");
  6144. }
  6145. }
  6146. }
  6147. void gguf_add_tensor(
  6148. struct gguf_context * ctx,
  6149. const struct ggml_tensor * tensor) {
  6150. GGML_ASSERT(tensor);
  6151. if (gguf_find_tensor(ctx, tensor->name) != -1) {
  6152. GGML_ABORT("duplicated tensor name");
  6153. }
  6154. const int idx = ctx->header.n_tensors;
  6155. ctx->infos = realloc(ctx->infos, (idx + 1)*sizeof(struct gguf_tensor_info));
  6156. ctx->infos[idx].name.n = strlen(tensor->name);
  6157. ctx->infos[idx].name.data = strdup(tensor->name);
  6158. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  6159. ctx->infos[idx].ne[i] = 1;
  6160. }
  6161. ctx->infos[idx].n_dims = ggml_n_dims(tensor);
  6162. for (uint32_t i = 0; i < ctx->infos[idx].n_dims; i++) {
  6163. ctx->infos[idx].ne[i] = tensor->ne[i];
  6164. }
  6165. ctx->infos[idx].type = tensor->type;
  6166. ctx->infos[idx].offset = 0;
  6167. ctx->infos[idx].data = tensor->data;
  6168. ctx->infos[idx].size = ggml_nbytes(tensor);
  6169. if (ctx->header.n_tensors > 0) {
  6170. ctx->infos[idx].offset = ctx->infos[idx - 1].offset + GGML_PAD(ctx->infos[idx - 1].size, ctx->alignment);
  6171. }
  6172. ctx->header.n_tensors++;
  6173. }
  6174. void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
  6175. const int idx = gguf_find_tensor(ctx, name);
  6176. if (idx < 0) {
  6177. GGML_ABORT("tensor not found");
  6178. }
  6179. ctx->infos[idx].type = type;
  6180. }
  6181. void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data, size_t size) {
  6182. const int idx = gguf_find_tensor(ctx, name);
  6183. if (idx < 0) {
  6184. GGML_ABORT("tensor not found");
  6185. }
  6186. ctx->infos[idx].data = data;
  6187. ctx->infos[idx].size = size;
  6188. // update offsets
  6189. for (uint32_t i = idx + 1; i < ctx->header.n_tensors; ++i) {
  6190. ctx->infos[i].offset = ctx->infos[i - 1].offset + GGML_PAD(ctx->infos[i - 1].size, ctx->alignment);
  6191. }
  6192. }
  6193. //static void gguf_fwrite_str(FILE * file, const struct gguf_str * val) {
  6194. // fwrite(&val->n, sizeof(val->n), 1, file);
  6195. // fwrite(val->data, sizeof(char), val->n, file);
  6196. //}
  6197. //
  6198. //static void gguf_fwrite_el(FILE * file, const void * val, size_t size) {
  6199. // fwrite(val, sizeof(char), size, file);
  6200. //}
  6201. struct gguf_buf gguf_buf_init(size_t size) {
  6202. struct gguf_buf buf = {
  6203. /*buf.data =*/ size == 0 ? NULL : GGML_CALLOC(1, size),
  6204. /*buf.size =*/ size,
  6205. /*buf.offset =*/ 0,
  6206. };
  6207. return buf;
  6208. }
  6209. void gguf_buf_free(struct gguf_buf buf) {
  6210. if (buf.data) {
  6211. GGML_FREE(buf.data);
  6212. }
  6213. }
  6214. static void gguf_buf_grow(struct gguf_buf * buf, size_t size) {
  6215. if (buf->offset + size > buf->size) {
  6216. buf->size = 1.5*(buf->offset + size);
  6217. if (buf->data) {
  6218. buf->data = realloc(buf->data, buf->size);
  6219. }
  6220. }
  6221. }
  6222. static void gguf_bwrite_str(struct gguf_buf * buf, const struct gguf_str * val) {
  6223. gguf_buf_grow(buf, sizeof(val->n) + val->n);
  6224. if (buf->data) {
  6225. memcpy((char *) buf->data + buf->offset, &val->n, sizeof(val->n));
  6226. }
  6227. buf->offset += sizeof(val->n);
  6228. if (buf->data) {
  6229. memcpy((char *) buf->data + buf->offset, val->data, val->n);
  6230. }
  6231. buf->offset += val->n;
  6232. }
  6233. static void gguf_bwrite_el(struct gguf_buf * buf, const void * val, size_t el_size) {
  6234. gguf_buf_grow(buf, el_size);
  6235. if (buf->data) {
  6236. memcpy((char *) buf->data + buf->offset, val, el_size);
  6237. }
  6238. buf->offset += el_size;
  6239. }
  6240. void gguf_write_to_buf(const struct gguf_context * ctx, struct gguf_buf * buf, bool only_meta) {
  6241. // write header
  6242. gguf_bwrite_el(buf, &ctx->header.magic, sizeof(ctx->header.magic));
  6243. gguf_bwrite_el(buf, &ctx->header.version, sizeof(ctx->header.version));
  6244. gguf_bwrite_el(buf, &ctx->header.n_tensors, sizeof(ctx->header.n_tensors));
  6245. gguf_bwrite_el(buf, &ctx->header.n_kv, sizeof(ctx->header.n_kv));
  6246. // write key-value pairs
  6247. for (uint32_t i = 0; i < ctx->header.n_kv; ++i) {
  6248. struct gguf_kv * kv = &ctx->kv[i];
  6249. gguf_bwrite_str(buf, &kv->key);
  6250. gguf_bwrite_el (buf, &kv->type, sizeof(kv->type));
  6251. switch (kv->type) {
  6252. case GGUF_TYPE_UINT8: gguf_bwrite_el( buf, &kv->value.uint8, sizeof(kv->value.uint8) ); break;
  6253. case GGUF_TYPE_INT8: gguf_bwrite_el (buf, &kv->value.int8, sizeof(kv->value.int8) ); break;
  6254. case GGUF_TYPE_UINT16: gguf_bwrite_el (buf, &kv->value.uint16, sizeof(kv->value.uint16) ); break;
  6255. case GGUF_TYPE_INT16: gguf_bwrite_el (buf, &kv->value.int16, sizeof(kv->value.int16) ); break;
  6256. case GGUF_TYPE_UINT32: gguf_bwrite_el (buf, &kv->value.uint32, sizeof(kv->value.uint32) ); break;
  6257. case GGUF_TYPE_INT32: gguf_bwrite_el (buf, &kv->value.int32, sizeof(kv->value.int32) ); break;
  6258. case GGUF_TYPE_FLOAT32: gguf_bwrite_el (buf, &kv->value.float32, sizeof(kv->value.float32)); break;
  6259. case GGUF_TYPE_UINT64: gguf_bwrite_el (buf, &kv->value.uint64, sizeof(kv->value.uint64) ); break;
  6260. case GGUF_TYPE_INT64: gguf_bwrite_el (buf, &kv->value.int64, sizeof(kv->value.int64) ); break;
  6261. case GGUF_TYPE_FLOAT64: gguf_bwrite_el (buf, &kv->value.float64, sizeof(kv->value.float64)); break;
  6262. case GGUF_TYPE_BOOL: gguf_bwrite_el (buf, &kv->value.bool_, sizeof(kv->value.bool_) ); break;
  6263. case GGUF_TYPE_STRING: gguf_bwrite_str(buf, &kv->value.str ); break;
  6264. case GGUF_TYPE_ARRAY:
  6265. {
  6266. gguf_bwrite_el(buf, &kv->value.arr.type, sizeof(kv->value.arr.type));
  6267. gguf_bwrite_el(buf, &kv->value.arr.n, sizeof(kv->value.arr.n) );
  6268. switch (kv->value.arr.type) {
  6269. case GGUF_TYPE_UINT8:
  6270. case GGUF_TYPE_INT8:
  6271. case GGUF_TYPE_UINT16:
  6272. case GGUF_TYPE_INT16:
  6273. case GGUF_TYPE_UINT32:
  6274. case GGUF_TYPE_INT32:
  6275. case GGUF_TYPE_FLOAT32:
  6276. case GGUF_TYPE_UINT64:
  6277. case GGUF_TYPE_INT64:
  6278. case GGUF_TYPE_FLOAT64:
  6279. case GGUF_TYPE_BOOL:
  6280. {
  6281. gguf_bwrite_el(buf, kv->value.arr.data, kv->value.arr.n * gguf_type_size(kv->value.arr.type));
  6282. } break;
  6283. case GGUF_TYPE_STRING:
  6284. {
  6285. for (uint32_t j = 0; j < kv->value.arr.n; ++j) {
  6286. gguf_bwrite_str(buf, &((struct gguf_str *) kv->value.arr.data)[j]);
  6287. }
  6288. } break;
  6289. case GGUF_TYPE_ARRAY:
  6290. default: GGML_ABORT("invalid type");
  6291. }
  6292. } break;
  6293. default: GGML_ABORT("invalid type");
  6294. }
  6295. }
  6296. // write tensor infos
  6297. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  6298. struct gguf_tensor_info * info = &ctx->infos[i];
  6299. gguf_bwrite_str(buf, &info->name);
  6300. gguf_bwrite_el (buf, &info->n_dims, sizeof(info->n_dims));
  6301. for (uint32_t j = 0; j < info->n_dims; ++j) {
  6302. gguf_bwrite_el(buf, &info->ne[j], sizeof(info->ne[j]));
  6303. }
  6304. gguf_bwrite_el(buf, &info->type, sizeof(info->type));
  6305. gguf_bwrite_el(buf, &info->offset, sizeof(info->offset));
  6306. }
  6307. // we require the data section to be aligned, so take into account any padding
  6308. {
  6309. const size_t offset = buf->offset;
  6310. const size_t offset_pad = GGML_PAD(offset, ctx->alignment);
  6311. if (offset_pad != offset) {
  6312. uint8_t pad = 0;
  6313. for (size_t i = 0; i < offset_pad - offset; ++i) {
  6314. gguf_bwrite_el(buf, &pad, sizeof(pad));
  6315. }
  6316. }
  6317. }
  6318. if (only_meta) {
  6319. return;
  6320. }
  6321. size_t offset = 0;
  6322. // write tensor data
  6323. for (uint32_t i = 0; i < ctx->header.n_tensors; ++i) {
  6324. struct gguf_tensor_info * info = &ctx->infos[i];
  6325. const size_t size = info->size;
  6326. const size_t size_pad = GGML_PAD(size, ctx->alignment);
  6327. gguf_bwrite_el(buf, info->data, size);
  6328. if (size_pad != size) {
  6329. uint8_t pad = 0;
  6330. for (size_t j = 0; j < size_pad - size; ++j) {
  6331. gguf_bwrite_el(buf, &pad, sizeof(pad));
  6332. }
  6333. }
  6334. GGML_ASSERT(offset == info->offset);
  6335. offset += size_pad;
  6336. }
  6337. }
  6338. void gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta) {
  6339. FILE * file = ggml_fopen(fname, "wb");
  6340. if (!file) {
  6341. GGML_ABORT("failed to open file for writing");
  6342. }
  6343. struct gguf_buf buf = gguf_buf_init(16*1024);
  6344. gguf_write_to_buf(ctx, &buf, only_meta);
  6345. fwrite(buf.data, 1, buf.offset, file);
  6346. gguf_buf_free(buf);
  6347. fclose(file);
  6348. }
  6349. size_t gguf_get_meta_size(const struct gguf_context * ctx) {
  6350. // no allocs - only compute size
  6351. struct gguf_buf buf = gguf_buf_init(0);
  6352. gguf_write_to_buf(ctx, &buf, true);
  6353. return buf.offset;
  6354. }
  6355. void gguf_get_meta_data(const struct gguf_context * ctx, void * data) {
  6356. struct gguf_buf buf = gguf_buf_init(16*1024);
  6357. gguf_write_to_buf(ctx, &buf, true);
  6358. memcpy(data, buf.data, buf.offset);
  6359. gguf_buf_free(buf);
  6360. }
  6361. void ggml_log_set(ggml_log_callback log_callback, void * user_data) {
  6362. g_logger_state.log_callback = log_callback ? log_callback : ggml_log_callback_default;
  6363. g_logger_state.log_callback_user_data = user_data;
  6364. }
  6365. void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
  6366. p->n_threads = n_threads;
  6367. p->prio = 0; // default priority (usually means normal or inherited)
  6368. p->poll = 50; // hybrid-polling enabled
  6369. p->strict_cpu = false; // no strict placement (all threads share same cpumask)
  6370. p->paused = false; // threads are ready to go
  6371. memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
  6372. }
  6373. struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
  6374. struct ggml_threadpool_params p;
  6375. ggml_threadpool_params_init(&p, n_threads);
  6376. return p;
  6377. }
  6378. bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
  6379. if (p0->n_threads != p1->n_threads ) return false;
  6380. if (p0->prio != p1->prio ) return false;
  6381. if (p0->poll != p1->poll ) return false;
  6382. if (p0->strict_cpu != p1->strict_cpu ) return false;
  6383. return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
  6384. }