ggml.c 239 KB

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