ggml.c 217 KB

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