ggml.c 205 KB

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