ggml.c 203 KB

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