ggml.c 204 KB

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