ggml.c 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495
  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_permuted(const struct ggml_tensor * tensor) {
  1146. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1147. return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
  1148. }
  1149. bool ggml_is_contiguous_channels(const struct ggml_tensor * tensor) {
  1150. return
  1151. tensor->nb[0] > tensor->nb[2] &&
  1152. tensor->nb[1] > tensor->nb[0] &&
  1153. tensor->nb[2] == ggml_type_size(tensor->type);
  1154. }
  1155. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  1156. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1157. return
  1158. tensor->nb[0] == ggml_type_size(tensor->type) &&
  1159. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  1160. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1161. }
  1162. bool ggml_is_empty(const struct ggml_tensor * tensor) {
  1163. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1164. if (tensor->ne[i] == 0) {
  1165. // empty if any dimension has no elements
  1166. return true;
  1167. }
  1168. }
  1169. return false;
  1170. }
  1171. bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1172. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1173. return
  1174. (t0->ne[0] == t1->ne[0]) &&
  1175. (t0->ne[1] == t1->ne[1]) &&
  1176. (t0->ne[2] == t1->ne[2]) &&
  1177. (t0->ne[3] == t1->ne[3]);
  1178. }
  1179. bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1180. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1181. return
  1182. (t0->nb[0] == t1->nb[0]) &&
  1183. (t0->nb[1] == t1->nb[1]) &&
  1184. (t0->nb[2] == t1->nb[2]) &&
  1185. (t0->nb[3] == t1->nb[3]);
  1186. }
  1187. // check if t1 can be represented as a repetition of t0
  1188. bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1189. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1190. return ggml_is_empty(t0) ? ggml_is_empty(t1) :
  1191. (t1->ne[0]%t0->ne[0] == 0) &&
  1192. (t1->ne[1]%t0->ne[1] == 0) &&
  1193. (t1->ne[2]%t0->ne[2] == 0) &&
  1194. (t1->ne[3]%t0->ne[3] == 0);
  1195. }
  1196. static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1197. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1198. return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
  1199. }
  1200. // assert that pointer is aligned to GGML_MEM_ALIGN
  1201. #define GGML_ASSERT_ALIGNED(ptr) \
  1202. GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  1203. ////////////////////////////////////////////////////////////////////////////////
  1204. struct ggml_context * ggml_init(struct ggml_init_params params) {
  1205. static bool is_first_call = true;
  1206. ggml_critical_section_start();
  1207. if (is_first_call) {
  1208. // initialize time system (required on Windows)
  1209. ggml_time_init();
  1210. for (int i = 0; i < (1 << 16); ++i) {
  1211. union {
  1212. uint16_t u16;
  1213. ggml_fp16_t fp16;
  1214. } u = {i};
  1215. ggml_table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(u.fp16);
  1216. }
  1217. is_first_call = false;
  1218. }
  1219. ggml_critical_section_end();
  1220. struct ggml_context * ctx = GGML_MALLOC(sizeof(struct ggml_context));
  1221. // allow to call ggml_init with 0 size
  1222. if (params.mem_size == 0) {
  1223. params.mem_size = GGML_MEM_ALIGN;
  1224. }
  1225. const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
  1226. *ctx = (struct ggml_context) {
  1227. /*.mem_size =*/ mem_size,
  1228. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : ggml_aligned_malloc(mem_size),
  1229. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  1230. /*.no_alloc =*/ params.no_alloc,
  1231. /*.n_objects =*/ 0,
  1232. /*.objects_begin =*/ NULL,
  1233. /*.objects_end =*/ NULL,
  1234. };
  1235. GGML_ASSERT(ctx->mem_buffer != NULL);
  1236. GGML_ASSERT_ALIGNED(ctx->mem_buffer);
  1237. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  1238. return ctx;
  1239. }
  1240. void ggml_reset(struct ggml_context * ctx) {
  1241. if (ctx == NULL) {
  1242. return;
  1243. }
  1244. ctx->n_objects = 0;
  1245. ctx->objects_begin = NULL;
  1246. ctx->objects_end = NULL;
  1247. }
  1248. void ggml_free(struct ggml_context * ctx) {
  1249. if (ctx == NULL) {
  1250. return;
  1251. }
  1252. if (ctx->mem_buffer_owned) {
  1253. ggml_aligned_free(ctx->mem_buffer, ctx->mem_size);
  1254. }
  1255. GGML_FREE(ctx);
  1256. }
  1257. size_t ggml_used_mem(const struct ggml_context * ctx) {
  1258. return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
  1259. }
  1260. bool ggml_get_no_alloc(struct ggml_context * ctx) {
  1261. return ctx->no_alloc;
  1262. }
  1263. void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
  1264. ctx->no_alloc = no_alloc;
  1265. }
  1266. void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
  1267. return ctx->mem_buffer;
  1268. }
  1269. size_t ggml_get_mem_size(const struct ggml_context * ctx) {
  1270. return ctx->mem_size;
  1271. }
  1272. size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
  1273. size_t max_size = 0;
  1274. for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
  1275. size_t bytes = ggml_nbytes(tensor);
  1276. max_size = MAX(max_size, bytes);
  1277. }
  1278. return max_size;
  1279. }
  1280. ////////////////////////////////////////////////////////////////////////////////
  1281. static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
  1282. // always insert objects at the end of the context's memory pool
  1283. struct ggml_object * obj_cur = ctx->objects_end;
  1284. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  1285. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  1286. const size_t cur_end = cur_offs + cur_size;
  1287. // align to GGML_MEM_ALIGN
  1288. size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
  1289. char * const mem_buffer = ctx->mem_buffer;
  1290. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  1291. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  1292. GGML_LOG_WARN("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  1293. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  1294. #ifndef NDEBUG
  1295. GGML_ABORT("not enough space in the context's memory pool");
  1296. #endif
  1297. return NULL;
  1298. }
  1299. *obj_new = (struct ggml_object) {
  1300. .offs = cur_end + GGML_OBJECT_SIZE,
  1301. .size = size_needed,
  1302. .next = NULL,
  1303. .type = type,
  1304. };
  1305. GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
  1306. if (obj_cur != NULL) {
  1307. obj_cur->next = obj_new;
  1308. } else {
  1309. // this is the first object in this context
  1310. ctx->objects_begin = obj_new;
  1311. }
  1312. ctx->objects_end = obj_new;
  1313. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  1314. return obj_new;
  1315. }
  1316. static struct ggml_tensor * ggml_new_tensor_impl(
  1317. struct ggml_context * ctx,
  1318. enum ggml_type type,
  1319. int n_dims,
  1320. const int64_t * ne,
  1321. struct ggml_tensor * view_src,
  1322. size_t view_offs) {
  1323. GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
  1324. GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
  1325. // find the base tensor and absolute offset
  1326. if (view_src != NULL && view_src->view_src != NULL) {
  1327. view_offs += view_src->view_offs;
  1328. view_src = view_src->view_src;
  1329. }
  1330. size_t data_size = ggml_row_size(type, ne[0]);
  1331. for (int i = 1; i < n_dims; i++) {
  1332. data_size *= ne[i];
  1333. }
  1334. GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
  1335. void * data = view_src != NULL ? view_src->data : NULL;
  1336. if (data != NULL) {
  1337. data = (char *) data + view_offs;
  1338. }
  1339. size_t obj_alloc_size = 0;
  1340. if (view_src == NULL && !ctx->no_alloc) {
  1341. // allocate tensor data in the context's memory pool
  1342. obj_alloc_size = data_size;
  1343. }
  1344. struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
  1345. GGML_ASSERT(obj_new);
  1346. struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
  1347. *result = (struct ggml_tensor) {
  1348. /*.type =*/ type,
  1349. /*.buffer =*/ NULL,
  1350. /*.ne =*/ { 1, 1, 1, 1 },
  1351. /*.nb =*/ { 0, 0, 0, 0 },
  1352. /*.op =*/ GGML_OP_NONE,
  1353. /*.op_params =*/ { 0 },
  1354. /*.flags =*/ 0,
  1355. /*.src =*/ { NULL },
  1356. /*.view_src =*/ view_src,
  1357. /*.view_offs =*/ view_offs,
  1358. /*.data =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
  1359. /*.name =*/ { 0 },
  1360. /*.extra =*/ NULL,
  1361. /*.padding =*/ { 0 },
  1362. };
  1363. // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
  1364. //GGML_ASSERT_ALIGNED(result->data);
  1365. for (int i = 0; i < n_dims; i++) {
  1366. result->ne[i] = ne[i];
  1367. }
  1368. result->nb[0] = ggml_type_size(type);
  1369. result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
  1370. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  1371. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  1372. }
  1373. ctx->n_objects++;
  1374. return result;
  1375. }
  1376. struct ggml_tensor * ggml_new_tensor(
  1377. struct ggml_context * ctx,
  1378. enum ggml_type type,
  1379. int n_dims,
  1380. const int64_t * ne) {
  1381. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
  1382. }
  1383. struct ggml_tensor * ggml_new_tensor_1d(
  1384. struct ggml_context * ctx,
  1385. enum ggml_type type,
  1386. int64_t ne0) {
  1387. return ggml_new_tensor(ctx, type, 1, &ne0);
  1388. }
  1389. struct ggml_tensor * ggml_new_tensor_2d(
  1390. struct ggml_context * ctx,
  1391. enum ggml_type type,
  1392. int64_t ne0,
  1393. int64_t ne1) {
  1394. const int64_t ne[2] = { ne0, ne1 };
  1395. return ggml_new_tensor(ctx, type, 2, ne);
  1396. }
  1397. struct ggml_tensor * ggml_new_tensor_3d(
  1398. struct ggml_context * ctx,
  1399. enum ggml_type type,
  1400. int64_t ne0,
  1401. int64_t ne1,
  1402. int64_t ne2) {
  1403. const int64_t ne[3] = { ne0, ne1, ne2 };
  1404. return ggml_new_tensor(ctx, type, 3, ne);
  1405. }
  1406. struct ggml_tensor * ggml_new_tensor_4d(
  1407. struct ggml_context * ctx,
  1408. enum ggml_type type,
  1409. int64_t ne0,
  1410. int64_t ne1,
  1411. int64_t ne2,
  1412. int64_t ne3) {
  1413. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  1414. return ggml_new_tensor(ctx, type, 4, ne);
  1415. }
  1416. void * ggml_new_buffer(struct ggml_context * ctx, size_t nbytes) {
  1417. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, nbytes);
  1418. return (uint8_t *)ctx->mem_buffer + obj->offs;
  1419. }
  1420. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  1421. return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
  1422. }
  1423. void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
  1424. const int64_t ne2 = tensor->ne[2];
  1425. const int64_t ne1 = tensor->ne[1];
  1426. const int64_t ne0 = tensor->ne[0];
  1427. const int64_t i3_ = (i/(ne2*ne1*ne0));
  1428. const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
  1429. const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
  1430. const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
  1431. if (i0) {
  1432. * i0 = i0_;
  1433. }
  1434. if (i1) {
  1435. * i1 = i1_;
  1436. }
  1437. if (i2) {
  1438. * i2 = i2_;
  1439. }
  1440. if (i3) {
  1441. * i3 = i3_;
  1442. }
  1443. }
  1444. void * ggml_get_data(const struct ggml_tensor * tensor) {
  1445. return tensor->data;
  1446. }
  1447. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  1448. assert(tensor->type == GGML_TYPE_F32);
  1449. return (float *)(tensor->data);
  1450. }
  1451. enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
  1452. GGML_ASSERT(tensor->op == GGML_OP_UNARY);
  1453. return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
  1454. }
  1455. const char * ggml_get_name(const struct ggml_tensor * tensor) {
  1456. return tensor->name;
  1457. }
  1458. struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
  1459. size_t i;
  1460. for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
  1461. tensor->name[i] = name[i];
  1462. }
  1463. tensor->name[i] = '\0';
  1464. return tensor;
  1465. }
  1466. struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
  1467. va_list args;
  1468. va_start(args, fmt);
  1469. vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
  1470. va_end(args);
  1471. return tensor;
  1472. }
  1473. struct ggml_tensor * ggml_view_tensor(
  1474. struct ggml_context * ctx,
  1475. struct ggml_tensor * src) {
  1476. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
  1477. ggml_format_name(result, "%s (view)", src->name);
  1478. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  1479. result->nb[i] = src->nb[i];
  1480. }
  1481. return result;
  1482. }
  1483. struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
  1484. struct ggml_object * obj = ctx->objects_begin;
  1485. char * const mem_buffer = ctx->mem_buffer;
  1486. while (obj != NULL) {
  1487. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1488. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1489. }
  1490. obj = obj->next;
  1491. }
  1492. return NULL;
  1493. }
  1494. struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
  1495. struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
  1496. obj = obj->next;
  1497. char * const mem_buffer = ctx->mem_buffer;
  1498. while (obj != NULL) {
  1499. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1500. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1501. }
  1502. obj = obj->next;
  1503. }
  1504. return NULL;
  1505. }
  1506. struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
  1507. struct ggml_object * obj = ctx->objects_begin;
  1508. char * const mem_buffer = ctx->mem_buffer;
  1509. while (obj != NULL) {
  1510. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1511. struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
  1512. if (strcmp(cur->name, name) == 0) {
  1513. return cur;
  1514. }
  1515. }
  1516. obj = obj->next;
  1517. }
  1518. return NULL;
  1519. }
  1520. ////////////////////////////////////////////////////////////////////////////////
  1521. // ggml_dup
  1522. static struct ggml_tensor * ggml_dup_impl(
  1523. struct ggml_context * ctx,
  1524. struct ggml_tensor * a,
  1525. bool inplace) {
  1526. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1527. result->op = GGML_OP_DUP;
  1528. result->src[0] = a;
  1529. return result;
  1530. }
  1531. struct ggml_tensor * ggml_dup(
  1532. struct ggml_context * ctx,
  1533. struct ggml_tensor * a) {
  1534. return ggml_dup_impl(ctx, a, false);
  1535. }
  1536. struct ggml_tensor * ggml_dup_inplace(
  1537. struct ggml_context * ctx,
  1538. struct ggml_tensor * a) {
  1539. return ggml_dup_impl(ctx, a, true);
  1540. }
  1541. // ggml_add
  1542. static struct ggml_tensor * ggml_add_impl(
  1543. struct ggml_context * ctx,
  1544. struct ggml_tensor * a,
  1545. struct ggml_tensor * b,
  1546. bool inplace) {
  1547. GGML_ASSERT(ggml_can_repeat(b, a));
  1548. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1549. result->op = GGML_OP_ADD;
  1550. result->src[0] = a;
  1551. result->src[1] = b;
  1552. return result;
  1553. }
  1554. struct ggml_tensor * ggml_add(
  1555. struct ggml_context * ctx,
  1556. struct ggml_tensor * a,
  1557. struct ggml_tensor * b) {
  1558. return ggml_add_impl(ctx, a, b, false);
  1559. }
  1560. struct ggml_tensor * ggml_add_inplace(
  1561. struct ggml_context * ctx,
  1562. struct ggml_tensor * a,
  1563. struct ggml_tensor * b) {
  1564. return ggml_add_impl(ctx, a, b, true);
  1565. }
  1566. // ggml_add_cast
  1567. static struct ggml_tensor * ggml_add_cast_impl(
  1568. struct ggml_context * ctx,
  1569. struct ggml_tensor * a,
  1570. struct ggml_tensor * b,
  1571. enum ggml_type type) {
  1572. // TODO: support less-strict constraint
  1573. // GGML_ASSERT(ggml_can_repeat(b, a));
  1574. GGML_ASSERT(ggml_can_repeat_rows(b, a));
  1575. // currently only supported for quantized input and f16
  1576. GGML_ASSERT(ggml_is_quantized(a->type) ||
  1577. a->type == GGML_TYPE_F16 ||
  1578. a->type == GGML_TYPE_BF16);
  1579. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  1580. result->op = GGML_OP_ADD;
  1581. result->src[0] = a;
  1582. result->src[1] = b;
  1583. return result;
  1584. }
  1585. struct ggml_tensor * ggml_add_cast(
  1586. struct ggml_context * ctx,
  1587. struct ggml_tensor * a,
  1588. struct ggml_tensor * b,
  1589. enum ggml_type type) {
  1590. return ggml_add_cast_impl(ctx, a, b, type);
  1591. }
  1592. // ggml_add1
  1593. static struct ggml_tensor * ggml_add1_impl(
  1594. struct ggml_context * ctx,
  1595. struct ggml_tensor * a,
  1596. struct ggml_tensor * b,
  1597. bool inplace) {
  1598. GGML_ASSERT(ggml_is_scalar(b));
  1599. GGML_ASSERT(ggml_is_padded_1d(a));
  1600. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1601. result->op = GGML_OP_ADD1;
  1602. result->src[0] = a;
  1603. result->src[1] = b;
  1604. return result;
  1605. }
  1606. struct ggml_tensor * ggml_add1(
  1607. struct ggml_context * ctx,
  1608. struct ggml_tensor * a,
  1609. struct ggml_tensor * b) {
  1610. return ggml_add1_impl(ctx, a, b, false);
  1611. }
  1612. struct ggml_tensor * ggml_add1_inplace(
  1613. struct ggml_context * ctx,
  1614. struct ggml_tensor * a,
  1615. struct ggml_tensor * b) {
  1616. return ggml_add1_impl(ctx, a, b, true);
  1617. }
  1618. // ggml_acc
  1619. static struct ggml_tensor * ggml_acc_impl(
  1620. struct ggml_context * ctx,
  1621. struct ggml_tensor * a,
  1622. struct ggml_tensor * b,
  1623. size_t nb1,
  1624. size_t nb2,
  1625. size_t nb3,
  1626. size_t offset,
  1627. bool inplace) {
  1628. GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
  1629. GGML_ASSERT(ggml_is_contiguous(a));
  1630. GGML_ASSERT(a->type == GGML_TYPE_F32);
  1631. GGML_ASSERT(b->type == GGML_TYPE_F32);
  1632. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1633. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  1634. ggml_set_op_params(result, params, sizeof(params));
  1635. result->op = GGML_OP_ACC;
  1636. result->src[0] = a;
  1637. result->src[1] = b;
  1638. return result;
  1639. }
  1640. struct ggml_tensor * ggml_acc(
  1641. struct ggml_context * ctx,
  1642. struct ggml_tensor * a,
  1643. struct ggml_tensor * b,
  1644. size_t nb1,
  1645. size_t nb2,
  1646. size_t nb3,
  1647. size_t offset) {
  1648. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  1649. }
  1650. struct ggml_tensor * ggml_acc_inplace(
  1651. struct ggml_context * ctx,
  1652. struct ggml_tensor * a,
  1653. struct ggml_tensor * b,
  1654. size_t nb1,
  1655. size_t nb2,
  1656. size_t nb3,
  1657. size_t offset) {
  1658. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  1659. }
  1660. // ggml_sub
  1661. static struct ggml_tensor * ggml_sub_impl(
  1662. struct ggml_context * ctx,
  1663. struct ggml_tensor * a,
  1664. struct ggml_tensor * b,
  1665. bool inplace) {
  1666. GGML_ASSERT(ggml_can_repeat(b, a));
  1667. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1668. result->op = GGML_OP_SUB;
  1669. result->src[0] = a;
  1670. result->src[1] = b;
  1671. return result;
  1672. }
  1673. struct ggml_tensor * ggml_sub(
  1674. struct ggml_context * ctx,
  1675. struct ggml_tensor * a,
  1676. struct ggml_tensor * b) {
  1677. return ggml_sub_impl(ctx, a, b, false);
  1678. }
  1679. struct ggml_tensor * ggml_sub_inplace(
  1680. struct ggml_context * ctx,
  1681. struct ggml_tensor * a,
  1682. struct ggml_tensor * b) {
  1683. return ggml_sub_impl(ctx, a, b, true);
  1684. }
  1685. // ggml_mul
  1686. static struct ggml_tensor * ggml_mul_impl(
  1687. struct ggml_context * ctx,
  1688. struct ggml_tensor * a,
  1689. struct ggml_tensor * b,
  1690. bool inplace) {
  1691. GGML_ASSERT(ggml_can_repeat(b, a));
  1692. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1693. result->op = GGML_OP_MUL;
  1694. result->src[0] = a;
  1695. result->src[1] = b;
  1696. return result;
  1697. }
  1698. struct ggml_tensor * ggml_mul(
  1699. struct ggml_context * ctx,
  1700. struct ggml_tensor * a,
  1701. struct ggml_tensor * b) {
  1702. return ggml_mul_impl(ctx, a, b, false);
  1703. }
  1704. struct ggml_tensor * ggml_mul_inplace(
  1705. struct ggml_context * ctx,
  1706. struct ggml_tensor * a,
  1707. struct ggml_tensor * b) {
  1708. return ggml_mul_impl(ctx, a, b, true);
  1709. }
  1710. // ggml_div
  1711. static struct ggml_tensor * ggml_div_impl(
  1712. struct ggml_context * ctx,
  1713. struct ggml_tensor * a,
  1714. struct ggml_tensor * b,
  1715. bool inplace) {
  1716. GGML_ASSERT(ggml_can_repeat(b, a));
  1717. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1718. result->op = GGML_OP_DIV;
  1719. result->src[0] = a;
  1720. result->src[1] = b;
  1721. return result;
  1722. }
  1723. struct ggml_tensor * ggml_div(
  1724. struct ggml_context * ctx,
  1725. struct ggml_tensor * a,
  1726. struct ggml_tensor * b) {
  1727. return ggml_div_impl(ctx, a, b, false);
  1728. }
  1729. struct ggml_tensor * ggml_div_inplace(
  1730. struct ggml_context * ctx,
  1731. struct ggml_tensor * a,
  1732. struct ggml_tensor * b) {
  1733. return ggml_div_impl(ctx, a, b, true);
  1734. }
  1735. // ggml_sqr
  1736. static struct ggml_tensor * ggml_sqr_impl(
  1737. struct ggml_context * ctx,
  1738. struct ggml_tensor * a,
  1739. bool inplace) {
  1740. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1741. result->op = GGML_OP_SQR;
  1742. result->src[0] = a;
  1743. return result;
  1744. }
  1745. struct ggml_tensor * ggml_sqr(
  1746. struct ggml_context * ctx,
  1747. struct ggml_tensor * a) {
  1748. return ggml_sqr_impl(ctx, a, false);
  1749. }
  1750. struct ggml_tensor * ggml_sqr_inplace(
  1751. struct ggml_context * ctx,
  1752. struct ggml_tensor * a) {
  1753. return ggml_sqr_impl(ctx, a, true);
  1754. }
  1755. // ggml_sqrt
  1756. static struct ggml_tensor * ggml_sqrt_impl(
  1757. struct ggml_context * ctx,
  1758. struct ggml_tensor * a,
  1759. bool inplace) {
  1760. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1761. result->op = GGML_OP_SQRT;
  1762. result->src[0] = a;
  1763. return result;
  1764. }
  1765. struct ggml_tensor * ggml_sqrt(
  1766. struct ggml_context * ctx,
  1767. struct ggml_tensor * a) {
  1768. return ggml_sqrt_impl(ctx, a, false);
  1769. }
  1770. struct ggml_tensor * ggml_sqrt_inplace(
  1771. struct ggml_context * ctx,
  1772. struct ggml_tensor * a) {
  1773. return ggml_sqrt_impl(ctx, a, true);
  1774. }
  1775. // ggml_log
  1776. static struct ggml_tensor * ggml_log_impl(
  1777. struct ggml_context * ctx,
  1778. struct ggml_tensor * a,
  1779. bool inplace) {
  1780. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1781. result->op = GGML_OP_LOG;
  1782. result->src[0] = a;
  1783. return result;
  1784. }
  1785. struct ggml_tensor * ggml_log(
  1786. struct ggml_context * ctx,
  1787. struct ggml_tensor * a) {
  1788. return ggml_log_impl(ctx, a, false);
  1789. }
  1790. struct ggml_tensor * ggml_log_inplace(
  1791. struct ggml_context * ctx,
  1792. struct ggml_tensor * a) {
  1793. return ggml_log_impl(ctx, a, true);
  1794. }
  1795. // ggml_sin
  1796. static struct ggml_tensor * ggml_sin_impl(
  1797. struct ggml_context * ctx,
  1798. struct ggml_tensor * a,
  1799. bool inplace) {
  1800. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1801. result->op = GGML_OP_SIN;
  1802. result->src[0] = a;
  1803. return result;
  1804. }
  1805. struct ggml_tensor * ggml_sin(
  1806. struct ggml_context * ctx,
  1807. struct ggml_tensor * a) {
  1808. return ggml_sin_impl(ctx, a, false);
  1809. }
  1810. struct ggml_tensor * ggml_sin_inplace(
  1811. struct ggml_context * ctx,
  1812. struct ggml_tensor * a) {
  1813. return ggml_sin_impl(ctx, a, true);
  1814. }
  1815. // ggml_cos
  1816. static struct ggml_tensor * ggml_cos_impl(
  1817. struct ggml_context * ctx,
  1818. struct ggml_tensor * a,
  1819. bool inplace) {
  1820. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1821. result->op = GGML_OP_COS;
  1822. result->src[0] = a;
  1823. return result;
  1824. }
  1825. struct ggml_tensor * ggml_cos(
  1826. struct ggml_context * ctx,
  1827. struct ggml_tensor * a) {
  1828. return ggml_cos_impl(ctx, a, false);
  1829. }
  1830. struct ggml_tensor * ggml_cos_inplace(
  1831. struct ggml_context * ctx,
  1832. struct ggml_tensor * a) {
  1833. return ggml_cos_impl(ctx, a, true);
  1834. }
  1835. // ggml_sum
  1836. struct ggml_tensor * ggml_sum(
  1837. struct ggml_context * ctx,
  1838. struct ggml_tensor * a) {
  1839. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  1840. result->op = GGML_OP_SUM;
  1841. result->src[0] = a;
  1842. return result;
  1843. }
  1844. // ggml_sum_rows
  1845. struct ggml_tensor * ggml_sum_rows(
  1846. struct ggml_context * ctx,
  1847. struct ggml_tensor * a) {
  1848. int64_t ne[GGML_MAX_DIMS] = { 1 };
  1849. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  1850. ne[i] = a->ne[i];
  1851. }
  1852. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1853. result->op = GGML_OP_SUM_ROWS;
  1854. result->src[0] = a;
  1855. return result;
  1856. }
  1857. // ggml_mean
  1858. struct ggml_tensor * ggml_mean(
  1859. struct ggml_context * ctx,
  1860. struct ggml_tensor * a) {
  1861. int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  1862. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  1863. result->op = GGML_OP_MEAN;
  1864. result->src[0] = a;
  1865. return result;
  1866. }
  1867. // ggml_argmax
  1868. struct ggml_tensor * ggml_argmax(
  1869. struct ggml_context * ctx,
  1870. struct ggml_tensor * a) {
  1871. GGML_ASSERT(ggml_is_matrix(a));
  1872. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  1873. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
  1874. result->op = GGML_OP_ARGMAX;
  1875. result->src[0] = a;
  1876. return result;
  1877. }
  1878. // ggml_count_equal
  1879. struct ggml_tensor * ggml_count_equal(
  1880. struct ggml_context * ctx,
  1881. struct ggml_tensor * a,
  1882. struct ggml_tensor * b) {
  1883. GGML_ASSERT(ggml_are_same_shape(a, b));
  1884. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, 1);
  1885. result->op = GGML_OP_COUNT_EQUAL;
  1886. result->src[0] = a;
  1887. result->src[1] = b;
  1888. return result;
  1889. }
  1890. // ggml_repeat
  1891. struct ggml_tensor * ggml_repeat(
  1892. struct ggml_context * ctx,
  1893. struct ggml_tensor * a,
  1894. struct ggml_tensor * b) {
  1895. GGML_ASSERT(ggml_can_repeat(a, b));
  1896. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1897. result->op = GGML_OP_REPEAT;
  1898. result->src[0] = a;
  1899. return result;
  1900. }
  1901. // ggml_repeat_back
  1902. struct ggml_tensor * ggml_repeat_back(
  1903. struct ggml_context * ctx,
  1904. struct ggml_tensor * a,
  1905. struct ggml_tensor * b) {
  1906. GGML_ASSERT(ggml_can_repeat(b, a));
  1907. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1908. result->op = GGML_OP_REPEAT_BACK;
  1909. result->src[0] = a;
  1910. return result;
  1911. }
  1912. // ggml_concat
  1913. struct ggml_tensor * ggml_concat(
  1914. struct ggml_context * ctx,
  1915. struct ggml_tensor * a,
  1916. struct ggml_tensor * b,
  1917. int dim) {
  1918. GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
  1919. GGML_ASSERT(a->type == b->type);
  1920. int64_t ne[GGML_MAX_DIMS];
  1921. for (int d = 0; d < GGML_MAX_DIMS; ++d) {
  1922. if (d == dim) {
  1923. ne[d] = a->ne[d] + b->ne[d];
  1924. continue;
  1925. }
  1926. GGML_ASSERT(a->ne[d] == b->ne[d]);
  1927. ne[d] = a->ne[d];
  1928. }
  1929. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1930. ggml_set_op_params_i32(result, 0, dim);
  1931. result->op = GGML_OP_CONCAT;
  1932. result->src[0] = a;
  1933. result->src[1] = b;
  1934. return result;
  1935. }
  1936. // ggml_abs
  1937. struct ggml_tensor * ggml_abs(
  1938. struct ggml_context * ctx,
  1939. struct ggml_tensor * a) {
  1940. return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
  1941. }
  1942. struct ggml_tensor * ggml_abs_inplace(
  1943. struct ggml_context * ctx,
  1944. struct ggml_tensor * a) {
  1945. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
  1946. }
  1947. // ggml_sgn
  1948. struct ggml_tensor * ggml_sgn(
  1949. struct ggml_context * ctx,
  1950. struct ggml_tensor * a) {
  1951. return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
  1952. }
  1953. struct ggml_tensor * ggml_sgn_inplace(
  1954. struct ggml_context * ctx,
  1955. struct ggml_tensor * a) {
  1956. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
  1957. }
  1958. // ggml_neg
  1959. struct ggml_tensor * ggml_neg(
  1960. struct ggml_context * ctx,
  1961. struct ggml_tensor * a) {
  1962. return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
  1963. }
  1964. struct ggml_tensor * ggml_neg_inplace(
  1965. struct ggml_context * ctx,
  1966. struct ggml_tensor * a) {
  1967. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
  1968. }
  1969. // ggml_step
  1970. struct ggml_tensor * ggml_step(
  1971. struct ggml_context * ctx,
  1972. struct ggml_tensor * a) {
  1973. return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
  1974. }
  1975. struct ggml_tensor * ggml_step_inplace(
  1976. struct ggml_context * ctx,
  1977. struct ggml_tensor * a) {
  1978. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
  1979. }
  1980. // ggml_tanh
  1981. struct ggml_tensor * ggml_tanh(
  1982. struct ggml_context * ctx,
  1983. struct ggml_tensor * a) {
  1984. return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
  1985. }
  1986. struct ggml_tensor * ggml_tanh_inplace(
  1987. struct ggml_context * ctx,
  1988. struct ggml_tensor * a) {
  1989. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
  1990. }
  1991. // ggml_elu
  1992. struct ggml_tensor * ggml_elu(
  1993. struct ggml_context * ctx,
  1994. struct ggml_tensor * a) {
  1995. return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
  1996. }
  1997. struct ggml_tensor * ggml_elu_inplace(
  1998. struct ggml_context * ctx,
  1999. struct ggml_tensor * a) {
  2000. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
  2001. }
  2002. // ggml_relu
  2003. struct ggml_tensor * ggml_relu(
  2004. struct ggml_context * ctx,
  2005. struct ggml_tensor * a) {
  2006. return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
  2007. }
  2008. struct ggml_tensor * ggml_relu_inplace(
  2009. struct ggml_context * ctx,
  2010. struct ggml_tensor * a) {
  2011. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
  2012. }
  2013. // ggml_leaky_relu
  2014. struct ggml_tensor * ggml_leaky_relu(
  2015. struct ggml_context * ctx,
  2016. struct ggml_tensor * a,
  2017. float negative_slope,
  2018. bool inplace) {
  2019. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2020. ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
  2021. result->op = GGML_OP_LEAKY_RELU;
  2022. result->src[0] = a;
  2023. return result;
  2024. }
  2025. // ggml_sigmoid
  2026. struct ggml_tensor * ggml_sigmoid(
  2027. struct ggml_context * ctx,
  2028. struct ggml_tensor * a) {
  2029. return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
  2030. }
  2031. struct ggml_tensor * ggml_sigmoid_inplace(
  2032. struct ggml_context * ctx,
  2033. struct ggml_tensor * a) {
  2034. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
  2035. }
  2036. // ggml_gelu
  2037. struct ggml_tensor * ggml_gelu(
  2038. struct ggml_context * ctx,
  2039. struct ggml_tensor * a) {
  2040. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
  2041. }
  2042. struct ggml_tensor * ggml_gelu_inplace(
  2043. struct ggml_context * ctx,
  2044. struct ggml_tensor * a) {
  2045. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
  2046. }
  2047. // ggml_gelu_quick
  2048. struct ggml_tensor * ggml_gelu_quick(
  2049. struct ggml_context * ctx,
  2050. struct ggml_tensor * a) {
  2051. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2052. }
  2053. struct ggml_tensor * ggml_gelu_quick_inplace(
  2054. struct ggml_context * ctx,
  2055. struct ggml_tensor * a) {
  2056. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2057. }
  2058. // ggml_silu
  2059. struct ggml_tensor * ggml_silu(
  2060. struct ggml_context * ctx,
  2061. struct ggml_tensor * a) {
  2062. return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
  2063. }
  2064. struct ggml_tensor * ggml_silu_inplace(
  2065. struct ggml_context * ctx,
  2066. struct ggml_tensor * a) {
  2067. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
  2068. }
  2069. // ggml_silu_back
  2070. struct ggml_tensor * ggml_silu_back(
  2071. struct ggml_context * ctx,
  2072. struct ggml_tensor * a,
  2073. struct ggml_tensor * b) {
  2074. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2075. result->op = GGML_OP_SILU_BACK;
  2076. result->src[0] = a;
  2077. result->src[1] = b;
  2078. return result;
  2079. }
  2080. // ggml hardswish
  2081. struct ggml_tensor * ggml_hardswish(
  2082. struct ggml_context * ctx,
  2083. struct ggml_tensor * a) {
  2084. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
  2085. }
  2086. // ggml hardsigmoid
  2087. struct ggml_tensor * ggml_hardsigmoid(
  2088. struct ggml_context * ctx,
  2089. struct ggml_tensor * a) {
  2090. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
  2091. }
  2092. // ggml exp
  2093. struct ggml_tensor * ggml_exp(
  2094. struct ggml_context * ctx,
  2095. struct ggml_tensor * a) {
  2096. return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
  2097. }
  2098. struct ggml_tensor * ggml_exp_inplace(
  2099. struct ggml_context * ctx,
  2100. struct ggml_tensor * a) {
  2101. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
  2102. }
  2103. // ggml_norm
  2104. static struct ggml_tensor * ggml_norm_impl(
  2105. struct ggml_context * ctx,
  2106. struct ggml_tensor * a,
  2107. float eps,
  2108. bool inplace) {
  2109. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2110. ggml_set_op_params(result, &eps, sizeof(eps));
  2111. result->op = GGML_OP_NORM;
  2112. result->src[0] = a;
  2113. return result;
  2114. }
  2115. struct ggml_tensor * ggml_norm(
  2116. struct ggml_context * ctx,
  2117. struct ggml_tensor * a,
  2118. float eps) {
  2119. return ggml_norm_impl(ctx, a, eps, false);
  2120. }
  2121. struct ggml_tensor * ggml_norm_inplace(
  2122. struct ggml_context * ctx,
  2123. struct ggml_tensor * a,
  2124. float eps) {
  2125. return ggml_norm_impl(ctx, a, eps, true);
  2126. }
  2127. // ggml_rms_norm
  2128. static struct ggml_tensor * ggml_rms_norm_impl(
  2129. struct ggml_context * ctx,
  2130. struct ggml_tensor * a,
  2131. float eps,
  2132. bool inplace) {
  2133. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2134. ggml_set_op_params(result, &eps, sizeof(eps));
  2135. result->op = GGML_OP_RMS_NORM;
  2136. result->src[0] = a;
  2137. return result;
  2138. }
  2139. struct ggml_tensor * ggml_rms_norm(
  2140. struct ggml_context * ctx,
  2141. struct ggml_tensor * a,
  2142. float eps) {
  2143. return ggml_rms_norm_impl(ctx, a, eps, false);
  2144. }
  2145. struct ggml_tensor * ggml_rms_norm_inplace(
  2146. struct ggml_context * ctx,
  2147. struct ggml_tensor * a,
  2148. float eps) {
  2149. return ggml_rms_norm_impl(ctx, a, eps, true);
  2150. }
  2151. // ggml_rms_norm_back
  2152. struct ggml_tensor * ggml_rms_norm_back(
  2153. struct ggml_context * ctx,
  2154. struct ggml_tensor * a,
  2155. struct ggml_tensor * b,
  2156. float eps) {
  2157. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2158. ggml_set_op_params(result, &eps, sizeof(eps));
  2159. result->op = GGML_OP_RMS_NORM_BACK;
  2160. result->src[0] = a;
  2161. result->src[1] = b;
  2162. return result;
  2163. }
  2164. // ggml_group_norm
  2165. static struct ggml_tensor * ggml_group_norm_impl(
  2166. struct ggml_context * ctx,
  2167. struct ggml_tensor * a,
  2168. int n_groups,
  2169. float eps,
  2170. bool inplace) {
  2171. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2172. ggml_set_op_params_i32(result, 0, n_groups);
  2173. ggml_set_op_params_f32(result, 1, eps);
  2174. result->op = GGML_OP_GROUP_NORM;
  2175. result->src[0] = a;
  2176. return result;
  2177. }
  2178. struct ggml_tensor * ggml_group_norm(
  2179. struct ggml_context * ctx,
  2180. struct ggml_tensor * a,
  2181. int n_groups,
  2182. float eps) {
  2183. return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
  2184. }
  2185. struct ggml_tensor * ggml_group_norm_inplace(
  2186. struct ggml_context * ctx,
  2187. struct ggml_tensor * a,
  2188. int n_groups,
  2189. float eps) {
  2190. return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
  2191. }
  2192. // ggml_l2_norm
  2193. static struct ggml_tensor * ggml_l2_norm_impl(
  2194. struct ggml_context * ctx,
  2195. struct ggml_tensor * a,
  2196. float eps,
  2197. bool inplace) {
  2198. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2199. ggml_set_op_params_f32(result, 0, eps);
  2200. result->op = GGML_OP_L2_NORM;
  2201. result->src[0] = a;
  2202. return result;
  2203. }
  2204. struct ggml_tensor * ggml_l2_norm(
  2205. struct ggml_context * ctx,
  2206. struct ggml_tensor * a,
  2207. float eps) {
  2208. return ggml_l2_norm_impl(ctx, a, eps, false);
  2209. }
  2210. struct ggml_tensor * ggml_l2_norm_inplace(
  2211. struct ggml_context * ctx,
  2212. struct ggml_tensor * a,
  2213. float eps) {
  2214. return ggml_l2_norm_impl(ctx, a, eps, true);
  2215. }
  2216. // ggml_mul_mat
  2217. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2218. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2219. return (t0->ne[0] == t1->ne[0]) &&
  2220. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2221. (t1->ne[3]%t0->ne[3] == 0);
  2222. }
  2223. struct ggml_tensor * ggml_mul_mat(
  2224. struct ggml_context * ctx,
  2225. struct ggml_tensor * a,
  2226. struct ggml_tensor * b) {
  2227. GGML_ASSERT(ggml_can_mul_mat(a, b));
  2228. GGML_ASSERT(!ggml_is_transposed(a));
  2229. const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
  2230. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2231. result->op = GGML_OP_MUL_MAT;
  2232. result->src[0] = a;
  2233. result->src[1] = b;
  2234. return result;
  2235. }
  2236. void ggml_mul_mat_set_prec(
  2237. struct ggml_tensor * a,
  2238. enum ggml_prec prec) {
  2239. GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
  2240. const int32_t prec_i32 = (int32_t) prec;
  2241. ggml_set_op_params_i32(a, 0, prec_i32);
  2242. }
  2243. // ggml_mul_mat_id
  2244. /*
  2245. c = ggml_mul_mat_id(ctx, as, b, ids);
  2246. as -> [cols, rows, n_expert]
  2247. ids -> [n_experts_used, n_tokens] (i32)
  2248. b -> [cols, n_expert_used, n_tokens]
  2249. c -> [rows, n_expert_used, n_tokens]
  2250. in b, n_experts_used can be broadcasted to match the n_expert_used of ids
  2251. c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
  2252. */
  2253. struct ggml_tensor * ggml_mul_mat_id(
  2254. struct ggml_context * ctx,
  2255. struct ggml_tensor * as,
  2256. struct ggml_tensor * b,
  2257. struct ggml_tensor * ids) {
  2258. GGML_ASSERT(!ggml_is_transposed(as));
  2259. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  2260. GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
  2261. GGML_ASSERT(b->ne[3] == 1); // b is 3d
  2262. GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
  2263. GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
  2264. GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
  2265. GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
  2266. const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
  2267. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2268. result->op = GGML_OP_MUL_MAT_ID;
  2269. result->src[0] = as;
  2270. result->src[1] = b;
  2271. result->src[2] = ids;
  2272. return result;
  2273. }
  2274. // ggml_out_prod
  2275. static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2276. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2277. return (t0->ne[1] == t1->ne[1]) &&
  2278. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2279. (t1->ne[3]%t0->ne[3] == 0);
  2280. }
  2281. struct ggml_tensor * ggml_out_prod(
  2282. struct ggml_context * ctx,
  2283. struct ggml_tensor * a,
  2284. struct ggml_tensor * b) {
  2285. GGML_ASSERT(ggml_can_out_prod(a, b));
  2286. GGML_ASSERT(!ggml_is_transposed(a));
  2287. // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
  2288. const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
  2289. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2290. result->op = GGML_OP_OUT_PROD;
  2291. result->src[0] = a;
  2292. result->src[1] = b;
  2293. return result;
  2294. }
  2295. // ggml_scale
  2296. static struct ggml_tensor * ggml_scale_impl(
  2297. struct ggml_context * ctx,
  2298. struct ggml_tensor * a,
  2299. float s,
  2300. bool inplace) {
  2301. GGML_ASSERT(ggml_is_padded_1d(a));
  2302. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2303. ggml_set_op_params(result, &s, sizeof(s));
  2304. result->op = GGML_OP_SCALE;
  2305. result->src[0] = a;
  2306. return result;
  2307. }
  2308. struct ggml_tensor * ggml_scale(
  2309. struct ggml_context * ctx,
  2310. struct ggml_tensor * a,
  2311. float s) {
  2312. return ggml_scale_impl(ctx, a, s, false);
  2313. }
  2314. struct ggml_tensor * ggml_scale_inplace(
  2315. struct ggml_context * ctx,
  2316. struct ggml_tensor * a,
  2317. float s) {
  2318. return ggml_scale_impl(ctx, a, s, true);
  2319. }
  2320. // ggml_set
  2321. static struct ggml_tensor * ggml_set_impl(
  2322. struct ggml_context * ctx,
  2323. struct ggml_tensor * a,
  2324. struct ggml_tensor * b,
  2325. size_t nb1,
  2326. size_t nb2,
  2327. size_t nb3,
  2328. size_t offset,
  2329. bool inplace) {
  2330. GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
  2331. // make a view of the destination
  2332. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2333. GGML_ASSERT(offset < (size_t)(1 << 30));
  2334. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  2335. ggml_set_op_params(result, params, sizeof(params));
  2336. result->op = GGML_OP_SET;
  2337. result->src[0] = a;
  2338. result->src[1] = b;
  2339. return result;
  2340. }
  2341. struct ggml_tensor * ggml_set(
  2342. struct ggml_context * ctx,
  2343. struct ggml_tensor * a,
  2344. struct ggml_tensor * b,
  2345. size_t nb1,
  2346. size_t nb2,
  2347. size_t nb3,
  2348. size_t offset) {
  2349. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  2350. }
  2351. struct ggml_tensor * ggml_set_inplace(
  2352. struct ggml_context * ctx,
  2353. struct ggml_tensor * a,
  2354. struct ggml_tensor * b,
  2355. size_t nb1,
  2356. size_t nb2,
  2357. size_t nb3,
  2358. size_t offset) {
  2359. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  2360. }
  2361. struct ggml_tensor * ggml_set_1d(
  2362. struct ggml_context * ctx,
  2363. struct ggml_tensor * a,
  2364. struct ggml_tensor * b,
  2365. size_t offset) {
  2366. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
  2367. }
  2368. struct ggml_tensor * ggml_set_1d_inplace(
  2369. struct ggml_context * ctx,
  2370. struct ggml_tensor * a,
  2371. struct ggml_tensor * b,
  2372. size_t offset) {
  2373. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
  2374. }
  2375. struct ggml_tensor * ggml_set_2d(
  2376. struct ggml_context * ctx,
  2377. struct ggml_tensor * a,
  2378. struct ggml_tensor * b,
  2379. size_t nb1,
  2380. size_t offset) {
  2381. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
  2382. }
  2383. struct ggml_tensor * ggml_set_2d_inplace(
  2384. struct ggml_context * ctx,
  2385. struct ggml_tensor * a,
  2386. struct ggml_tensor * b,
  2387. size_t nb1,
  2388. size_t offset) {
  2389. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
  2390. }
  2391. // ggml_cpy
  2392. static struct ggml_tensor * ggml_cpy_impl(
  2393. struct ggml_context * ctx,
  2394. struct ggml_tensor * a,
  2395. struct ggml_tensor * b) {
  2396. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2397. // make a view of the destination
  2398. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  2399. if (strlen(b->name) > 0) {
  2400. ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
  2401. } else {
  2402. ggml_format_name(result, "%s (copy)", a->name);
  2403. }
  2404. result->op = GGML_OP_CPY;
  2405. result->src[0] = a;
  2406. result->src[1] = b;
  2407. return result;
  2408. }
  2409. struct ggml_tensor * ggml_cpy(
  2410. struct ggml_context * ctx,
  2411. struct ggml_tensor * a,
  2412. struct ggml_tensor * b) {
  2413. return ggml_cpy_impl(ctx, a, b);
  2414. }
  2415. struct ggml_tensor * ggml_cast(
  2416. struct ggml_context * ctx,
  2417. struct ggml_tensor * a,
  2418. enum ggml_type type) {
  2419. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  2420. ggml_format_name(result, "%s (copy)", a->name);
  2421. result->op = GGML_OP_CPY;
  2422. result->src[0] = a;
  2423. result->src[1] = result;
  2424. return result;
  2425. }
  2426. // ggml_cont
  2427. static struct ggml_tensor * ggml_cont_impl(
  2428. struct ggml_context * ctx,
  2429. struct ggml_tensor * a) {
  2430. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2431. ggml_format_name(result, "%s (cont)", a->name);
  2432. result->op = GGML_OP_CONT;
  2433. result->src[0] = a;
  2434. return result;
  2435. }
  2436. struct ggml_tensor * ggml_cont(
  2437. struct ggml_context * ctx,
  2438. struct ggml_tensor * a) {
  2439. return ggml_cont_impl(ctx, a);
  2440. }
  2441. // make contiguous, with new shape
  2442. GGML_API struct ggml_tensor * ggml_cont_1d(
  2443. struct ggml_context * ctx,
  2444. struct ggml_tensor * a,
  2445. int64_t ne0) {
  2446. return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
  2447. }
  2448. GGML_API struct ggml_tensor * ggml_cont_2d(
  2449. struct ggml_context * ctx,
  2450. struct ggml_tensor * a,
  2451. int64_t ne0,
  2452. int64_t ne1) {
  2453. return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
  2454. }
  2455. GGML_API struct ggml_tensor * ggml_cont_3d(
  2456. struct ggml_context * ctx,
  2457. struct ggml_tensor * a,
  2458. int64_t ne0,
  2459. int64_t ne1,
  2460. int64_t ne2) {
  2461. return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
  2462. }
  2463. struct ggml_tensor * ggml_cont_4d(
  2464. struct ggml_context * ctx,
  2465. struct ggml_tensor * a,
  2466. int64_t ne0,
  2467. int64_t ne1,
  2468. int64_t ne2,
  2469. int64_t ne3) {
  2470. GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
  2471. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  2472. ggml_format_name(result, "%s (cont)", a->name);
  2473. result->op = GGML_OP_CONT;
  2474. result->src[0] = a;
  2475. return result;
  2476. }
  2477. // ggml_reshape
  2478. struct ggml_tensor * ggml_reshape(
  2479. struct ggml_context * ctx,
  2480. struct ggml_tensor * a,
  2481. struct ggml_tensor * b) {
  2482. GGML_ASSERT(ggml_is_contiguous(a));
  2483. // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
  2484. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2485. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->ne, a, 0);
  2486. ggml_format_name(result, "%s (reshaped)", a->name);
  2487. result->op = GGML_OP_RESHAPE;
  2488. result->src[0] = a;
  2489. return result;
  2490. }
  2491. struct ggml_tensor * ggml_reshape_1d(
  2492. struct ggml_context * ctx,
  2493. struct ggml_tensor * a,
  2494. int64_t ne0) {
  2495. GGML_ASSERT(ggml_is_contiguous(a));
  2496. GGML_ASSERT(ggml_nelements(a) == ne0);
  2497. const int64_t ne[1] = { ne0 };
  2498. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
  2499. ggml_format_name(result, "%s (reshaped)", a->name);
  2500. result->op = GGML_OP_RESHAPE;
  2501. result->src[0] = a;
  2502. return result;
  2503. }
  2504. struct ggml_tensor * ggml_reshape_2d(
  2505. struct ggml_context * ctx,
  2506. struct ggml_tensor * a,
  2507. int64_t ne0,
  2508. int64_t ne1) {
  2509. GGML_ASSERT(ggml_is_contiguous(a));
  2510. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  2511. const int64_t ne[2] = { ne0, ne1 };
  2512. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
  2513. ggml_format_name(result, "%s (reshaped)", a->name);
  2514. result->op = GGML_OP_RESHAPE;
  2515. result->src[0] = a;
  2516. return result;
  2517. }
  2518. struct ggml_tensor * ggml_reshape_3d(
  2519. struct ggml_context * ctx,
  2520. struct ggml_tensor * a,
  2521. int64_t ne0,
  2522. int64_t ne1,
  2523. int64_t ne2) {
  2524. GGML_ASSERT(ggml_is_contiguous(a));
  2525. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  2526. const int64_t ne[3] = { ne0, ne1, ne2 };
  2527. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
  2528. ggml_format_name(result, "%s (reshaped)", a->name);
  2529. result->op = GGML_OP_RESHAPE;
  2530. result->src[0] = a;
  2531. return result;
  2532. }
  2533. struct ggml_tensor * ggml_reshape_4d(
  2534. struct ggml_context * ctx,
  2535. struct ggml_tensor * a,
  2536. int64_t ne0,
  2537. int64_t ne1,
  2538. int64_t ne2,
  2539. int64_t ne3) {
  2540. GGML_ASSERT(ggml_is_contiguous(a));
  2541. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
  2542. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2543. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
  2544. ggml_format_name(result, "%s (reshaped)", a->name);
  2545. result->op = GGML_OP_RESHAPE;
  2546. result->src[0] = a;
  2547. return result;
  2548. }
  2549. static struct ggml_tensor * ggml_view_impl(
  2550. struct ggml_context * ctx,
  2551. struct ggml_tensor * a,
  2552. int n_dims,
  2553. const int64_t * ne,
  2554. size_t offset) {
  2555. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
  2556. ggml_format_name(result, "%s (view)", a->name);
  2557. ggml_set_op_params(result, &offset, sizeof(offset));
  2558. result->op = GGML_OP_VIEW;
  2559. result->src[0] = a;
  2560. return result;
  2561. }
  2562. // ggml_view_1d
  2563. struct ggml_tensor * ggml_view_1d(
  2564. struct ggml_context * ctx,
  2565. struct ggml_tensor * a,
  2566. int64_t ne0,
  2567. size_t offset) {
  2568. struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
  2569. return result;
  2570. }
  2571. // ggml_view_2d
  2572. struct ggml_tensor * ggml_view_2d(
  2573. struct ggml_context * ctx,
  2574. struct ggml_tensor * a,
  2575. int64_t ne0,
  2576. int64_t ne1,
  2577. size_t nb1,
  2578. size_t offset) {
  2579. const int64_t ne[2] = { ne0, ne1 };
  2580. struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
  2581. result->nb[1] = nb1;
  2582. result->nb[2] = result->nb[1]*ne1;
  2583. result->nb[3] = result->nb[2];
  2584. return result;
  2585. }
  2586. // ggml_view_3d
  2587. struct ggml_tensor * ggml_view_3d(
  2588. struct ggml_context * ctx,
  2589. struct ggml_tensor * a,
  2590. int64_t ne0,
  2591. int64_t ne1,
  2592. int64_t ne2,
  2593. size_t nb1,
  2594. size_t nb2,
  2595. size_t offset) {
  2596. const int64_t ne[3] = { ne0, ne1, ne2 };
  2597. struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
  2598. result->nb[1] = nb1;
  2599. result->nb[2] = nb2;
  2600. result->nb[3] = result->nb[2]*ne2;
  2601. return result;
  2602. }
  2603. // ggml_view_4d
  2604. struct ggml_tensor * ggml_view_4d(
  2605. struct ggml_context * ctx,
  2606. struct ggml_tensor * a,
  2607. int64_t ne0,
  2608. int64_t ne1,
  2609. int64_t ne2,
  2610. int64_t ne3,
  2611. size_t nb1,
  2612. size_t nb2,
  2613. size_t nb3,
  2614. size_t offset) {
  2615. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2616. struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
  2617. result->nb[1] = nb1;
  2618. result->nb[2] = nb2;
  2619. result->nb[3] = nb3;
  2620. return result;
  2621. }
  2622. // ggml_permute
  2623. struct ggml_tensor * ggml_permute(
  2624. struct ggml_context * ctx,
  2625. struct ggml_tensor * a,
  2626. int axis0,
  2627. int axis1,
  2628. int axis2,
  2629. int axis3) {
  2630. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  2631. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  2632. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  2633. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  2634. GGML_ASSERT(axis0 != axis1);
  2635. GGML_ASSERT(axis0 != axis2);
  2636. GGML_ASSERT(axis0 != axis3);
  2637. GGML_ASSERT(axis1 != axis2);
  2638. GGML_ASSERT(axis1 != axis3);
  2639. GGML_ASSERT(axis2 != axis3);
  2640. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2641. ggml_format_name(result, "%s (permuted)", a->name);
  2642. int ne[GGML_MAX_DIMS];
  2643. int nb[GGML_MAX_DIMS];
  2644. ne[axis0] = a->ne[0];
  2645. ne[axis1] = a->ne[1];
  2646. ne[axis2] = a->ne[2];
  2647. ne[axis3] = a->ne[3];
  2648. nb[axis0] = a->nb[0];
  2649. nb[axis1] = a->nb[1];
  2650. nb[axis2] = a->nb[2];
  2651. nb[axis3] = a->nb[3];
  2652. result->ne[0] = ne[0];
  2653. result->ne[1] = ne[1];
  2654. result->ne[2] = ne[2];
  2655. result->ne[3] = ne[3];
  2656. result->nb[0] = nb[0];
  2657. result->nb[1] = nb[1];
  2658. result->nb[2] = nb[2];
  2659. result->nb[3] = nb[3];
  2660. result->op = GGML_OP_PERMUTE;
  2661. result->src[0] = a;
  2662. int32_t params[] = { axis0, axis1, axis2, axis3 };
  2663. ggml_set_op_params(result, params, sizeof(params));
  2664. return result;
  2665. }
  2666. // ggml_transpose
  2667. struct ggml_tensor * ggml_transpose(
  2668. struct ggml_context * ctx,
  2669. struct ggml_tensor * a) {
  2670. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2671. ggml_format_name(result, "%s (transposed)", a->name);
  2672. result->ne[0] = a->ne[1];
  2673. result->ne[1] = a->ne[0];
  2674. result->nb[0] = a->nb[1];
  2675. result->nb[1] = a->nb[0];
  2676. result->op = GGML_OP_TRANSPOSE;
  2677. result->src[0] = a;
  2678. return result;
  2679. }
  2680. // ggml_get_rows
  2681. struct ggml_tensor * ggml_get_rows(
  2682. struct ggml_context * ctx,
  2683. struct ggml_tensor * a,
  2684. struct ggml_tensor * b) {
  2685. GGML_ASSERT(a->ne[2] == b->ne[1]);
  2686. GGML_ASSERT(b->ne[3] == 1);
  2687. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2688. // TODO: implement non F32 return
  2689. enum ggml_type type = GGML_TYPE_F32;
  2690. if (a->type == GGML_TYPE_I32) {
  2691. type = a->type;
  2692. }
  2693. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
  2694. result->op = GGML_OP_GET_ROWS;
  2695. result->src[0] = a;
  2696. result->src[1] = b;
  2697. return result;
  2698. }
  2699. // ggml_get_rows_back
  2700. struct ggml_tensor * ggml_get_rows_back(
  2701. struct ggml_context * ctx,
  2702. struct ggml_tensor * a,
  2703. struct ggml_tensor * b,
  2704. struct ggml_tensor * c) {
  2705. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  2706. GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
  2707. // TODO: implement non F32 return
  2708. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  2709. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
  2710. result->op = GGML_OP_GET_ROWS_BACK;
  2711. result->src[0] = a;
  2712. result->src[1] = b;
  2713. return result;
  2714. }
  2715. // ggml_diag
  2716. struct ggml_tensor * ggml_diag(
  2717. struct ggml_context * ctx,
  2718. struct ggml_tensor * a) {
  2719. GGML_ASSERT(a->ne[1] == 1);
  2720. const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
  2721. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
  2722. result->op = GGML_OP_DIAG;
  2723. result->src[0] = a;
  2724. return result;
  2725. }
  2726. // ggml_diag_mask_inf
  2727. static struct ggml_tensor * ggml_diag_mask_inf_impl(
  2728. struct ggml_context * ctx,
  2729. struct ggml_tensor * a,
  2730. int n_past,
  2731. bool inplace) {
  2732. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2733. int32_t params[] = { n_past };
  2734. ggml_set_op_params(result, params, sizeof(params));
  2735. result->op = GGML_OP_DIAG_MASK_INF;
  2736. result->src[0] = a;
  2737. return result;
  2738. }
  2739. struct ggml_tensor * ggml_diag_mask_inf(
  2740. struct ggml_context * ctx,
  2741. struct ggml_tensor * a,
  2742. int n_past) {
  2743. return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
  2744. }
  2745. struct ggml_tensor * ggml_diag_mask_inf_inplace(
  2746. struct ggml_context * ctx,
  2747. struct ggml_tensor * a,
  2748. int n_past) {
  2749. return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
  2750. }
  2751. // ggml_diag_mask_zero
  2752. static struct ggml_tensor * ggml_diag_mask_zero_impl(
  2753. struct ggml_context * ctx,
  2754. struct ggml_tensor * a,
  2755. int n_past,
  2756. bool inplace) {
  2757. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2758. int32_t params[] = { n_past };
  2759. ggml_set_op_params(result, params, sizeof(params));
  2760. result->op = GGML_OP_DIAG_MASK_ZERO;
  2761. result->src[0] = a;
  2762. return result;
  2763. }
  2764. struct ggml_tensor * ggml_diag_mask_zero(
  2765. struct ggml_context * ctx,
  2766. struct ggml_tensor * a,
  2767. int n_past) {
  2768. return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
  2769. }
  2770. struct ggml_tensor * ggml_diag_mask_zero_inplace(
  2771. struct ggml_context * ctx,
  2772. struct ggml_tensor * a,
  2773. int n_past) {
  2774. return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
  2775. }
  2776. // ggml_soft_max
  2777. static struct ggml_tensor * ggml_soft_max_impl(
  2778. struct ggml_context * ctx,
  2779. struct ggml_tensor * a,
  2780. struct ggml_tensor * mask,
  2781. float scale,
  2782. float max_bias,
  2783. bool inplace) {
  2784. GGML_ASSERT(ggml_is_contiguous(a));
  2785. if (mask) {
  2786. GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
  2787. GGML_ASSERT(ggml_is_contiguous(mask));
  2788. GGML_ASSERT(ggml_is_matrix(mask));
  2789. GGML_ASSERT(mask->ne[0] == a->ne[0]);
  2790. GGML_ASSERT(mask->ne[1] >= a->ne[1]);
  2791. }
  2792. if (max_bias > 0.0f) {
  2793. GGML_ASSERT(mask);
  2794. }
  2795. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2796. float params[] = { scale, max_bias };
  2797. ggml_set_op_params(result, params, sizeof(params));
  2798. result->op = GGML_OP_SOFT_MAX;
  2799. result->src[0] = a;
  2800. result->src[1] = mask;
  2801. return result;
  2802. }
  2803. struct ggml_tensor * ggml_soft_max(
  2804. struct ggml_context * ctx,
  2805. struct ggml_tensor * a) {
  2806. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
  2807. }
  2808. struct ggml_tensor * ggml_soft_max_inplace(
  2809. struct ggml_context * ctx,
  2810. struct ggml_tensor * a) {
  2811. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
  2812. }
  2813. struct ggml_tensor * ggml_soft_max_ext(
  2814. struct ggml_context * ctx,
  2815. struct ggml_tensor * a,
  2816. struct ggml_tensor * mask,
  2817. float scale,
  2818. float max_bias) {
  2819. return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
  2820. }
  2821. // ggml_soft_max_ext_back
  2822. static struct ggml_tensor * ggml_soft_max_ext_back_impl(
  2823. struct ggml_context * ctx,
  2824. struct ggml_tensor * a,
  2825. struct ggml_tensor * b,
  2826. float scale,
  2827. float max_bias,
  2828. bool inplace) {
  2829. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2830. result->op = GGML_OP_SOFT_MAX_BACK;
  2831. result->src[0] = a;
  2832. result->src[1] = b;
  2833. memcpy((float *) result->op_params + 0, &scale, sizeof(float));
  2834. memcpy((float *) result->op_params + 1, &max_bias, sizeof(float));
  2835. return result;
  2836. }
  2837. struct ggml_tensor * ggml_soft_max_ext_back(
  2838. struct ggml_context * ctx,
  2839. struct ggml_tensor * a,
  2840. struct ggml_tensor * b,
  2841. float scale,
  2842. float max_bias) {
  2843. return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, false);
  2844. }
  2845. struct ggml_tensor * ggml_soft_max_ext_back_inplace(
  2846. struct ggml_context * ctx,
  2847. struct ggml_tensor * a,
  2848. struct ggml_tensor * b,
  2849. float scale,
  2850. float max_bias) {
  2851. return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, true);
  2852. }
  2853. // ggml_rope
  2854. static struct ggml_tensor * ggml_rope_impl(
  2855. struct ggml_context * ctx,
  2856. struct ggml_tensor * a,
  2857. struct ggml_tensor * b,
  2858. struct ggml_tensor * c,
  2859. int n_dims,
  2860. int mode,
  2861. int n_ctx_orig,
  2862. float freq_base,
  2863. float freq_scale,
  2864. float ext_factor,
  2865. float attn_factor,
  2866. float beta_fast,
  2867. float beta_slow,
  2868. bool inplace) {
  2869. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2870. GGML_ASSERT(ggml_is_vector(b));
  2871. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2872. GGML_ASSERT(a->ne[2] == b->ne[0]);
  2873. if (c) {
  2874. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2875. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2876. }
  2877. int sections[4] = {0, 0, 0, 0};
  2878. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2879. int32_t params[15] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2880. memcpy(params + 5, &freq_base, sizeof(float));
  2881. memcpy(params + 6, &freq_scale, sizeof(float));
  2882. memcpy(params + 7, &ext_factor, sizeof(float));
  2883. memcpy(params + 8, &attn_factor, sizeof(float));
  2884. memcpy(params + 9, &beta_fast, sizeof(float));
  2885. memcpy(params + 10, &beta_slow, sizeof(float));
  2886. memcpy(params + 11, &sections, sizeof(int)*4);
  2887. ggml_set_op_params(result, params, sizeof(params));
  2888. result->op = GGML_OP_ROPE;
  2889. result->src[0] = a;
  2890. result->src[1] = b;
  2891. result->src[2] = c;
  2892. return result;
  2893. }
  2894. struct ggml_tensor * ggml_rope(
  2895. struct ggml_context * ctx,
  2896. struct ggml_tensor * a,
  2897. struct ggml_tensor * b,
  2898. int n_dims,
  2899. int mode) {
  2900. return ggml_rope_impl(
  2901. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
  2902. );
  2903. }
  2904. struct ggml_tensor * ggml_rope_multi(
  2905. struct ggml_context * ctx,
  2906. struct ggml_tensor * a,
  2907. struct ggml_tensor * b,
  2908. struct ggml_tensor * c,
  2909. int n_dims,
  2910. int sections[4],
  2911. int mode,
  2912. int n_ctx_orig,
  2913. float freq_base,
  2914. float freq_scale,
  2915. float ext_factor,
  2916. float attn_factor,
  2917. float beta_fast,
  2918. float beta_slow) {
  2919. // Multimodal Rotary Position Embedding
  2920. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2921. GGML_ASSERT(ggml_is_vector(b));
  2922. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2923. GGML_ASSERT(a->ne[2] * 4 == b->ne[0]); // mrope expecting 4 position ids per token
  2924. if (c) {
  2925. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2926. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2927. }
  2928. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2929. int32_t params[11 + 4] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2930. memcpy(params + 5, &freq_base, sizeof(float));
  2931. memcpy(params + 6, &freq_scale, sizeof(float));
  2932. memcpy(params + 7, &ext_factor, sizeof(float));
  2933. memcpy(params + 8, &attn_factor, sizeof(float));
  2934. memcpy(params + 9, &beta_fast, sizeof(float));
  2935. memcpy(params + 10, &beta_slow, sizeof(float));
  2936. memcpy(&params[11], sections, sizeof(int)*4);
  2937. ggml_set_op_params(result, params, sizeof(params));
  2938. result->op = GGML_OP_ROPE;
  2939. result->src[0] = a;
  2940. result->src[1] = b;
  2941. result->src[2] = c;
  2942. return result;
  2943. }
  2944. struct ggml_tensor * ggml_rope_inplace(
  2945. struct ggml_context * ctx,
  2946. struct ggml_tensor * a,
  2947. struct ggml_tensor * b,
  2948. int n_dims,
  2949. int mode) {
  2950. return ggml_rope_impl(
  2951. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
  2952. );
  2953. }
  2954. struct ggml_tensor * ggml_rope_ext(
  2955. struct ggml_context * ctx,
  2956. struct ggml_tensor * a,
  2957. struct ggml_tensor * b,
  2958. struct ggml_tensor * c,
  2959. int n_dims,
  2960. int mode,
  2961. int n_ctx_orig,
  2962. float freq_base,
  2963. float freq_scale,
  2964. float ext_factor,
  2965. float attn_factor,
  2966. float beta_fast,
  2967. float beta_slow) {
  2968. return ggml_rope_impl(
  2969. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  2970. ext_factor, attn_factor, beta_fast, beta_slow, false
  2971. );
  2972. }
  2973. struct ggml_tensor * ggml_rope_ext_inplace(
  2974. struct ggml_context * ctx,
  2975. struct ggml_tensor * a,
  2976. struct ggml_tensor * b,
  2977. struct ggml_tensor * c,
  2978. int n_dims,
  2979. int mode,
  2980. int n_ctx_orig,
  2981. float freq_base,
  2982. float freq_scale,
  2983. float ext_factor,
  2984. float attn_factor,
  2985. float beta_fast,
  2986. float beta_slow) {
  2987. return ggml_rope_impl(
  2988. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  2989. ext_factor, attn_factor, beta_fast, beta_slow, true
  2990. );
  2991. }
  2992. struct ggml_tensor * ggml_rope_custom(
  2993. struct ggml_context * ctx,
  2994. struct ggml_tensor * a,
  2995. struct ggml_tensor * b,
  2996. int n_dims,
  2997. int mode,
  2998. int n_ctx_orig,
  2999. float freq_base,
  3000. float freq_scale,
  3001. float ext_factor,
  3002. float attn_factor,
  3003. float beta_fast,
  3004. float beta_slow) {
  3005. return ggml_rope_impl(
  3006. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3007. ext_factor, attn_factor, beta_fast, beta_slow, false
  3008. );
  3009. }
  3010. struct ggml_tensor * ggml_rope_custom_inplace(
  3011. struct ggml_context * ctx,
  3012. struct ggml_tensor * a,
  3013. struct ggml_tensor * b,
  3014. int n_dims,
  3015. int mode,
  3016. int n_ctx_orig,
  3017. float freq_base,
  3018. float freq_scale,
  3019. float ext_factor,
  3020. float attn_factor,
  3021. float beta_fast,
  3022. float beta_slow) {
  3023. return ggml_rope_impl(
  3024. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3025. ext_factor, attn_factor, beta_fast, beta_slow, true
  3026. );
  3027. }
  3028. // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
  3029. // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
  3030. static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
  3031. return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
  3032. }
  3033. void ggml_rope_yarn_corr_dims(
  3034. int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
  3035. ) {
  3036. // start and end correction dims
  3037. float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
  3038. float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
  3039. dims[0] = MAX(0, start);
  3040. dims[1] = MIN(n_dims - 1, end);
  3041. }
  3042. // ggml_rope_back
  3043. struct ggml_tensor * ggml_rope_ext_back(
  3044. struct ggml_context * ctx,
  3045. struct ggml_tensor * a,
  3046. struct ggml_tensor * b,
  3047. struct ggml_tensor * c,
  3048. int n_dims,
  3049. int mode,
  3050. int n_ctx_orig,
  3051. float freq_base,
  3052. float freq_scale,
  3053. float ext_factor,
  3054. float attn_factor,
  3055. float beta_fast,
  3056. float beta_slow) {
  3057. struct ggml_tensor * result = ggml_rope_ext(
  3058. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  3059. result->op = GGML_OP_ROPE_BACK;
  3060. return result;
  3061. }
  3062. struct ggml_tensor * ggml_rope_multi_back(
  3063. struct ggml_context * ctx,
  3064. struct ggml_tensor * a,
  3065. struct ggml_tensor * b,
  3066. struct ggml_tensor * c,
  3067. int n_dims,
  3068. int sections[4],
  3069. int mode,
  3070. int n_ctx_orig,
  3071. float freq_base,
  3072. float freq_scale,
  3073. float ext_factor,
  3074. float attn_factor,
  3075. float beta_fast,
  3076. float beta_slow) {
  3077. struct ggml_tensor * result = ggml_rope_multi(
  3078. ctx, a, b, c, n_dims, sections, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  3079. result->op = GGML_OP_ROPE_BACK;
  3080. return result;
  3081. }
  3082. // ggml_clamp
  3083. struct ggml_tensor * ggml_clamp(
  3084. struct ggml_context * ctx,
  3085. struct ggml_tensor * a,
  3086. float min,
  3087. float max) {
  3088. // TODO: when implement backward, fix this:
  3089. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3090. float params[] = { min, max };
  3091. ggml_set_op_params(result, params, sizeof(params));
  3092. result->op = GGML_OP_CLAMP;
  3093. result->src[0] = a;
  3094. return result;
  3095. }
  3096. static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3097. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  3098. }
  3099. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  3100. // a: [OC,IC, KH, KW]
  3101. // b: [N, IC, IH, IW]
  3102. // result: [N, OH, OW, IC*KH*KW]
  3103. struct ggml_tensor * ggml_im2col(
  3104. struct ggml_context * ctx,
  3105. struct ggml_tensor * a,
  3106. struct ggml_tensor * b,
  3107. int s0,
  3108. int s1,
  3109. int p0,
  3110. int p1,
  3111. int d0,
  3112. int d1,
  3113. bool is_2D,
  3114. enum ggml_type dst_type) {
  3115. if (is_2D) {
  3116. GGML_ASSERT(a->ne[2] == b->ne[2]);
  3117. } else {
  3118. //GGML_ASSERT(b->ne[1] % a->ne[1] == 0);
  3119. GGML_ASSERT(b->ne[1] == a->ne[1]);
  3120. GGML_ASSERT(b->ne[3] == 1);
  3121. }
  3122. const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
  3123. const int64_t OW = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
  3124. GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
  3125. GGML_ASSERT((OW > 0) && "b too small compared to a");
  3126. const int64_t ne[4] = {
  3127. is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
  3128. OW,
  3129. is_2D ? OH : b->ne[2],
  3130. is_2D ? b->ne[3] : 1,
  3131. };
  3132. struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
  3133. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3134. ggml_set_op_params(result, params, sizeof(params));
  3135. result->op = GGML_OP_IM2COL;
  3136. result->src[0] = a;
  3137. result->src[1] = b;
  3138. return result;
  3139. }
  3140. struct ggml_tensor * ggml_im2col_back(
  3141. struct ggml_context * ctx,
  3142. struct ggml_tensor * a,
  3143. struct ggml_tensor * b,
  3144. int64_t * ne,
  3145. int s0,
  3146. int s1,
  3147. int p0,
  3148. int p1,
  3149. int d0,
  3150. int d1,
  3151. bool is_2D) {
  3152. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3153. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3154. ggml_set_op_params(result, params, sizeof(params));
  3155. result->op = GGML_OP_IM2COL_BACK;
  3156. result->src[0] = a;
  3157. result->src[1] = b;
  3158. return result;
  3159. }
  3160. // ggml_conv_1d
  3161. struct ggml_tensor * ggml_conv_1d(
  3162. struct ggml_context * ctx,
  3163. struct ggml_tensor * a,
  3164. struct ggml_tensor * b,
  3165. int s0,
  3166. int p0,
  3167. int d0) {
  3168. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16); // [N, OL, IC * K]
  3169. struct ggml_tensor * result =
  3170. ggml_mul_mat(ctx,
  3171. ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
  3172. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2])); // [OC,IC, K] => [OC, IC * K]
  3173. result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
  3174. return result;
  3175. }
  3176. // ggml_conv_1d_ph
  3177. struct ggml_tensor* ggml_conv_1d_ph(
  3178. struct ggml_context * ctx,
  3179. struct ggml_tensor * a,
  3180. struct ggml_tensor * b,
  3181. int s,
  3182. int d) {
  3183. return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
  3184. }
  3185. // ggml_conv_1d_dw
  3186. struct ggml_tensor * ggml_conv_1d_dw(
  3187. struct ggml_context * ctx,
  3188. struct ggml_tensor * a,
  3189. struct ggml_tensor * b,
  3190. int s0,
  3191. int p0,
  3192. int d0) {
  3193. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], 1, a->ne[1], a->ne[2]);
  3194. struct ggml_tensor * new_b = ggml_reshape_4d(ctx, b, b->ne[0], 1, b->ne[1], b->ne[2]);
  3195. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a, new_b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16);
  3196. struct ggml_tensor * result = ggml_mul_mat(ctx, im2col, a);
  3197. result = ggml_reshape_3d(ctx, result, b->ne[0], b->ne[1], 1);
  3198. return result;
  3199. }
  3200. // ggml_conv_1d_dw_ph
  3201. struct ggml_tensor * ggml_conv_1d_dw_ph(
  3202. struct ggml_context * ctx,
  3203. struct ggml_tensor * a,
  3204. struct ggml_tensor * b,
  3205. int s0,
  3206. int d0) {
  3207. return ggml_conv_1d_dw(ctx, a, b, s0, a->ne[0] / 2, d0);
  3208. }
  3209. // ggml_conv_transpose_1d
  3210. static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3211. return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
  3212. }
  3213. GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
  3214. struct ggml_context * ctx,
  3215. struct ggml_tensor * a,
  3216. struct ggml_tensor * b,
  3217. int s0,
  3218. int p0,
  3219. int d0) {
  3220. GGML_ASSERT(ggml_is_matrix(b));
  3221. GGML_ASSERT(a->ne[2] == b->ne[1]);
  3222. GGML_ASSERT(a->ne[3] == 1);
  3223. GGML_ASSERT(p0 == 0);
  3224. GGML_ASSERT(d0 == 1);
  3225. const int64_t ne[4] = {
  3226. ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
  3227. a->ne[1], b->ne[2], 1,
  3228. };
  3229. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3230. int32_t params[] = { s0, p0, d0 };
  3231. ggml_set_op_params(result, params, sizeof(params));
  3232. result->op = GGML_OP_CONV_TRANSPOSE_1D;
  3233. result->src[0] = a;
  3234. result->src[1] = b;
  3235. return result;
  3236. }
  3237. // ggml_conv_2d
  3238. // a: [OC,IC, KH, KW]
  3239. // b: [N, IC, IH, IW]
  3240. // result: [N, OC, OH, OW]
  3241. struct ggml_tensor * ggml_conv_2d(
  3242. struct ggml_context * ctx,
  3243. struct ggml_tensor * a,
  3244. struct ggml_tensor * b,
  3245. int s0,
  3246. int s1,
  3247. int p0,
  3248. int p1,
  3249. int d0,
  3250. int d1) {
  3251. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type); // [N, OH, OW, IC * KH * KW]
  3252. struct ggml_tensor * result =
  3253. ggml_mul_mat(ctx,
  3254. 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]
  3255. 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]
  3256. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
  3257. result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
  3258. return result;
  3259. }
  3260. // ggml_conv_2d_sk_p0
  3261. struct ggml_tensor * ggml_conv_2d_sk_p0(
  3262. struct ggml_context * ctx,
  3263. struct ggml_tensor * a,
  3264. struct ggml_tensor * b) {
  3265. return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
  3266. }
  3267. // ggml_conv_2d_s1_ph
  3268. struct ggml_tensor * ggml_conv_2d_s1_ph(
  3269. struct ggml_context * ctx,
  3270. struct ggml_tensor * a,
  3271. struct ggml_tensor * b) {
  3272. return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
  3273. }
  3274. // ggml_conv_2d_dw
  3275. struct ggml_tensor * ggml_conv_2d_dw(
  3276. struct ggml_context * ctx,
  3277. struct ggml_tensor * a,
  3278. struct ggml_tensor * b,
  3279. int s0,
  3280. int s1,
  3281. int p0,
  3282. int p1,
  3283. int d0,
  3284. int d1) {
  3285. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
  3286. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
  3287. ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
  3288. s0, s1, p0, p1, d0, d1, true, GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
  3289. 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]
  3290. 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]
  3291. struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
  3292. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
  3293. return result;
  3294. }
  3295. // ggml_conv_2d_dw_direct
  3296. struct ggml_tensor * ggml_conv_2d_dw_direct(
  3297. struct ggml_context * ctx,
  3298. struct ggml_tensor * a,
  3299. struct ggml_tensor * b,
  3300. int stride0,
  3301. int stride1,
  3302. int pad0,
  3303. int pad1,
  3304. int dilation0,
  3305. int dilation1) {
  3306. GGML_ASSERT(a->ne[2] == 1);
  3307. GGML_ASSERT(a->ne[3] == b->ne[2]);
  3308. int64_t ne[4];
  3309. ne[0] = ggml_calc_conv_output_size(b->ne[0], a->ne[0], stride0, pad0, dilation0);
  3310. ne[1] = ggml_calc_conv_output_size(b->ne[1], a->ne[1], stride1, pad1, dilation1);
  3311. ne[2] = b->ne[2];
  3312. ne[3] = b->ne[3];
  3313. struct ggml_tensor * result = ggml_new_tensor(ctx, b->type, 4, ne);
  3314. if (ggml_is_contiguous_channels(b)) {
  3315. // Result will be permuted the same way as input (CWHN order)
  3316. const int64_t type_size = ggml_type_size(result->type);
  3317. GGML_ASSERT(ggml_blck_size(result->type) == 1);
  3318. result->nb[0] = result->ne[2] * type_size;
  3319. result->nb[1] = result->ne[0] * result->nb[0];
  3320. result->nb[2] = type_size;
  3321. }
  3322. int32_t params[] = { stride0, stride1, pad0, pad1, dilation0, dilation1 };
  3323. ggml_set_op_params(result, params, sizeof(params));
  3324. result->op = GGML_OP_CONV_2D_DW;
  3325. result->src[0] = a;
  3326. result->src[1] = b;
  3327. return result;
  3328. }
  3329. // ggml_conv_transpose_2d_p0
  3330. static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
  3331. return (ins - 1) * s - 2 * p + ks;
  3332. }
  3333. struct ggml_tensor * ggml_conv_transpose_2d_p0(
  3334. struct ggml_context * ctx,
  3335. struct ggml_tensor * a,
  3336. struct ggml_tensor * b,
  3337. int stride) {
  3338. GGML_ASSERT(a->ne[3] == b->ne[2]);
  3339. const int64_t ne[4] = {
  3340. ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
  3341. ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
  3342. a->ne[2], b->ne[3],
  3343. };
  3344. struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3345. ggml_set_op_params_i32(result, 0, stride);
  3346. result->op = GGML_OP_CONV_TRANSPOSE_2D;
  3347. result->src[0] = a;
  3348. result->src[1] = b;
  3349. return result;
  3350. }
  3351. // ggml_pool_*
  3352. static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
  3353. return (ins + 2 * p - ks) / s + 1;
  3354. }
  3355. // ggml_pool_1d
  3356. struct ggml_tensor * ggml_pool_1d(
  3357. struct ggml_context * ctx,
  3358. struct ggml_tensor * a,
  3359. enum ggml_op_pool op,
  3360. int k0,
  3361. int s0,
  3362. int p0) {
  3363. const int64_t ne[4] = {
  3364. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3365. a->ne[1],
  3366. a->ne[2],
  3367. a->ne[3],
  3368. };
  3369. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3370. int32_t params[] = { op, k0, s0, p0 };
  3371. ggml_set_op_params(result, params, sizeof(params));
  3372. result->op = GGML_OP_POOL_1D;
  3373. result->src[0] = a;
  3374. return result;
  3375. }
  3376. // ggml_pool_2d
  3377. struct ggml_tensor * ggml_pool_2d(
  3378. struct ggml_context * ctx,
  3379. struct ggml_tensor * a,
  3380. enum ggml_op_pool op,
  3381. int k0,
  3382. int k1,
  3383. int s0,
  3384. int s1,
  3385. float p0,
  3386. float p1) {
  3387. struct ggml_tensor * result;
  3388. const int64_t ne[4] = {
  3389. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3390. ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
  3391. a->ne[2],
  3392. a->ne[3],
  3393. };
  3394. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3395. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3396. ggml_set_op_params(result, params, sizeof(params));
  3397. result->op = GGML_OP_POOL_2D;
  3398. result->src[0] = a;
  3399. return result;
  3400. }
  3401. struct ggml_tensor * ggml_pool_2d_back(
  3402. struct ggml_context * ctx,
  3403. struct ggml_tensor * a,
  3404. struct ggml_tensor * af,
  3405. enum ggml_op_pool op,
  3406. int k0,
  3407. int k1,
  3408. int s0,
  3409. int s1,
  3410. float p0,
  3411. float p1) {
  3412. struct ggml_tensor * result;
  3413. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
  3414. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3415. ggml_set_op_params(result, params, sizeof(params));
  3416. result->op = GGML_OP_POOL_2D_BACK;
  3417. result->src[0] = a;
  3418. result->src[1] = af;
  3419. return result;
  3420. }
  3421. // ggml_upscale
  3422. static struct ggml_tensor * ggml_upscale_impl(
  3423. struct ggml_context * ctx,
  3424. struct ggml_tensor * a,
  3425. int ne0,
  3426. int ne1,
  3427. int ne2,
  3428. int ne3,
  3429. enum ggml_scale_mode mode) {
  3430. GGML_ASSERT(a->ne[0] <= ne0);
  3431. GGML_ASSERT(a->ne[1] <= ne1);
  3432. GGML_ASSERT(a->ne[2] <= ne2);
  3433. GGML_ASSERT(a->ne[3] <= ne3);
  3434. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  3435. ggml_set_op_params_i32(result, 0, mode);
  3436. result->op = GGML_OP_UPSCALE;
  3437. result->src[0] = a;
  3438. return result;
  3439. }
  3440. struct ggml_tensor * ggml_upscale(
  3441. struct ggml_context * ctx,
  3442. struct ggml_tensor * a,
  3443. int scale_factor,
  3444. enum ggml_scale_mode mode) {
  3445. return ggml_upscale_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3], mode);
  3446. }
  3447. struct ggml_tensor * ggml_upscale_ext(
  3448. struct ggml_context * ctx,
  3449. struct ggml_tensor * a,
  3450. int ne0,
  3451. int ne1,
  3452. int ne2,
  3453. int ne3,
  3454. enum ggml_scale_mode mode) {
  3455. return ggml_upscale_impl(ctx, a, ne0, ne1, ne2, ne3, mode);
  3456. }
  3457. // ggml_pad
  3458. struct ggml_tensor * ggml_pad(
  3459. struct ggml_context * ctx,
  3460. struct ggml_tensor * a,
  3461. int p0,
  3462. int p1,
  3463. int p2,
  3464. int p3) {
  3465. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3466. a->ne[0] + p0,
  3467. a->ne[1] + p1,
  3468. a->ne[2] + p2,
  3469. a->ne[3] + p3);
  3470. result->op = GGML_OP_PAD;
  3471. result->src[0] = a;
  3472. return result;
  3473. }
  3474. // ggml_pad_reflect_1d
  3475. struct ggml_tensor * ggml_pad_reflect_1d(
  3476. struct ggml_context * ctx,
  3477. struct ggml_tensor * a,
  3478. int p0,
  3479. int p1) {
  3480. GGML_ASSERT(p0 >= 0);
  3481. GGML_ASSERT(p1 >= 0);
  3482. GGML_ASSERT(p0 < a->ne[0]); // padding length on each size must be less than the
  3483. GGML_ASSERT(p1 < a->ne[0]); // existing length of the dimension being padded
  3484. GGML_ASSERT(ggml_is_contiguous(a));
  3485. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3486. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3487. a->ne[0] + p0 + p1,
  3488. a->ne[1],
  3489. a->ne[2],
  3490. a->ne[3]);
  3491. int32_t params[] = { p0, p1 };
  3492. ggml_set_op_params(result, params, sizeof(params));
  3493. result->op = GGML_OP_PAD_REFLECT_1D;
  3494. result->src[0] = a;
  3495. return result;
  3496. }
  3497. // ggml_arange
  3498. struct ggml_tensor * ggml_arange(
  3499. struct ggml_context * ctx,
  3500. float start,
  3501. float stop,
  3502. float step) {
  3503. GGML_ASSERT(stop > start);
  3504. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  3505. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
  3506. ggml_set_op_params_f32(result, 0, start);
  3507. ggml_set_op_params_f32(result, 1, stop);
  3508. ggml_set_op_params_f32(result, 2, step);
  3509. result->op = GGML_OP_ARANGE;
  3510. return result;
  3511. }
  3512. // ggml_timestep_embedding
  3513. struct ggml_tensor * ggml_timestep_embedding(
  3514. struct ggml_context * ctx,
  3515. struct ggml_tensor * timesteps,
  3516. int dim,
  3517. int max_period) {
  3518. int actual_dim = dim;
  3519. if (dim % 2 != 0) {
  3520. actual_dim = dim + 1;
  3521. }
  3522. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, actual_dim, timesteps->ne[0]);
  3523. ggml_set_op_params_i32(result, 0, dim);
  3524. ggml_set_op_params_i32(result, 1, max_period);
  3525. result->op = GGML_OP_TIMESTEP_EMBEDDING;
  3526. result->src[0] = timesteps;
  3527. return result;
  3528. }
  3529. // ggml_argsort
  3530. struct ggml_tensor * ggml_argsort(
  3531. struct ggml_context * ctx,
  3532. struct ggml_tensor * a,
  3533. enum ggml_sort_order order) {
  3534. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  3535. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
  3536. ggml_set_op_params_i32(result, 0, (int32_t) order);
  3537. result->op = GGML_OP_ARGSORT;
  3538. result->src[0] = a;
  3539. return result;
  3540. }
  3541. // ggml_top_k
  3542. struct ggml_tensor * ggml_top_k(
  3543. struct ggml_context * ctx,
  3544. struct ggml_tensor * a,
  3545. int k) {
  3546. GGML_ASSERT(a->ne[0] >= k);
  3547. struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
  3548. result = ggml_view_4d(ctx, result,
  3549. k, result->ne[1], result->ne[2], result->ne[3],
  3550. result->nb[1], result->nb[2], result->nb[3],
  3551. 0);
  3552. return result;
  3553. }
  3554. // ggml_flash_attn_ext
  3555. struct ggml_tensor * ggml_flash_attn_ext(
  3556. struct ggml_context * ctx,
  3557. struct ggml_tensor * q,
  3558. struct ggml_tensor * k,
  3559. struct ggml_tensor * v,
  3560. struct ggml_tensor * mask,
  3561. float scale,
  3562. float max_bias,
  3563. float logit_softcap) {
  3564. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3565. // TODO: check if vT can be multiplied by (k*qT)
  3566. if (mask) {
  3567. GGML_ASSERT(ggml_is_contiguous(mask));
  3568. GGML_ASSERT(mask->ne[2] == 1);
  3569. GGML_ASSERT(mask->ne[3] == 1);
  3570. GGML_ASSERT(mask->ne[1] >= GGML_PAD(q->ne[1], GGML_KQ_MASK_PAD) &&
  3571. "the Flash-Attention kernel requires the mask to be padded to GGML_KQ_MASK_PAD and at least n_queries big");
  3572. //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
  3573. }
  3574. if (max_bias > 0.0f) {
  3575. GGML_ASSERT(mask);
  3576. }
  3577. // permute(0, 2, 1, 3)
  3578. int64_t ne[4] = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] };
  3579. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3580. float params[] = { scale, max_bias, logit_softcap };
  3581. ggml_set_op_params(result, params, sizeof(params));
  3582. result->op = GGML_OP_FLASH_ATTN_EXT;
  3583. result->src[0] = q;
  3584. result->src[1] = k;
  3585. result->src[2] = v;
  3586. result->src[3] = mask;
  3587. return result;
  3588. }
  3589. void ggml_flash_attn_ext_set_prec(
  3590. struct ggml_tensor * a,
  3591. enum ggml_prec prec) {
  3592. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3593. const int32_t prec_i32 = (int32_t) prec;
  3594. ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
  3595. }
  3596. enum ggml_prec ggml_flash_attn_ext_get_prec(
  3597. const struct ggml_tensor * a) {
  3598. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3599. const int32_t prec_i32 = ggml_get_op_params_i32(a, 3);
  3600. return (enum ggml_prec) prec_i32;
  3601. }
  3602. // ggml_flash_attn_back
  3603. struct ggml_tensor * ggml_flash_attn_back(
  3604. struct ggml_context * ctx,
  3605. struct ggml_tensor * q,
  3606. struct ggml_tensor * k,
  3607. struct ggml_tensor * v,
  3608. struct ggml_tensor * d,
  3609. bool masked) {
  3610. GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
  3611. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3612. // TODO: check if vT can be multiplied by (k*qT)
  3613. // d shape [D,N,ne2,ne3]
  3614. // q shape [D,N,ne2,ne3]
  3615. // k shape [D,M,kvne2,ne3]
  3616. // v shape [M,D,kvne2,ne3]
  3617. const int64_t D = q->ne[0];
  3618. const int64_t N = q->ne[1];
  3619. const int64_t M = k->ne[1];
  3620. const int64_t ne2 = q->ne[2];
  3621. const int64_t ne3 = q->ne[3];
  3622. const int64_t kvne2 = k->ne[2];
  3623. GGML_ASSERT(k->ne[0] == D);
  3624. GGML_ASSERT(v->ne[0] == M);
  3625. GGML_ASSERT(v->ne[1] == D);
  3626. GGML_ASSERT(d->ne[0] == D);
  3627. GGML_ASSERT(d->ne[1] == N);
  3628. GGML_ASSERT(k->ne[2] == kvne2);
  3629. GGML_ASSERT(k->ne[3] == ne3);
  3630. GGML_ASSERT(v->ne[2] == kvne2);
  3631. GGML_ASSERT(v->ne[3] == ne3);
  3632. GGML_ASSERT(d->ne[2] == ne2);
  3633. GGML_ASSERT(d->ne[3] == ne3);
  3634. GGML_ASSERT(ne2 % kvne2 == 0);
  3635. // store gradients of q, k and v as continuous tensors concatenated in result.
  3636. // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
  3637. const int64_t elem_q = ggml_nelements(q);
  3638. const int64_t elem_k = ggml_nelements(k);
  3639. const int64_t elem_v = ggml_nelements(v);
  3640. enum ggml_type result_type = GGML_TYPE_F32;
  3641. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  3642. const size_t tsize = ggml_type_size(result_type);
  3643. const size_t offs_q = 0;
  3644. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  3645. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  3646. const size_t end = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
  3647. const size_t nelements = (end + tsize - 1)/tsize;
  3648. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
  3649. int32_t masked_i = masked ? 1 : 0;
  3650. ggml_set_op_params(result, &masked_i, sizeof(masked_i));
  3651. result->op = GGML_OP_FLASH_ATTN_BACK;
  3652. result->src[0] = q;
  3653. result->src[1] = k;
  3654. result->src[2] = v;
  3655. result->src[3] = d;
  3656. return result;
  3657. }
  3658. // ggml_ssm_conv
  3659. struct ggml_tensor * ggml_ssm_conv(
  3660. struct ggml_context * ctx,
  3661. struct ggml_tensor * sx,
  3662. struct ggml_tensor * c) {
  3663. GGML_ASSERT(ggml_is_3d(sx));
  3664. GGML_ASSERT(ggml_is_matrix(c));
  3665. const int64_t d_conv = c->ne[0];
  3666. const int64_t d_inner = c->ne[1];
  3667. const int64_t n_t = sx->ne[0] - d_conv + 1; // tokens per sequence
  3668. const int64_t n_s = sx->ne[2];
  3669. // TODO: maybe support other strides than 1?
  3670. // FIXME: this is always true?
  3671. GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
  3672. GGML_ASSERT(sx->ne[1] == d_inner);
  3673. GGML_ASSERT(n_t >= 0);
  3674. struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
  3675. result->op = GGML_OP_SSM_CONV;
  3676. result->src[0] = sx;
  3677. result->src[1] = c;
  3678. return result;
  3679. }
  3680. // ggml_ssm_scan
  3681. struct ggml_tensor * ggml_ssm_scan(
  3682. struct ggml_context * ctx,
  3683. struct ggml_tensor * s,
  3684. struct ggml_tensor * x,
  3685. struct ggml_tensor * dt,
  3686. struct ggml_tensor * A,
  3687. struct ggml_tensor * B,
  3688. struct ggml_tensor * C) {
  3689. GGML_ASSERT(ggml_is_contiguous(s));
  3690. GGML_ASSERT(ggml_is_contiguous(x));
  3691. GGML_ASSERT(ggml_is_contiguous(dt));
  3692. GGML_ASSERT(ggml_is_contiguous(A));
  3693. GGML_ASSERT(ggml_is_matrix(A));
  3694. GGML_ASSERT(ggml_is_3d(B));
  3695. GGML_ASSERT(ggml_is_3d(s));
  3696. GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
  3697. GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
  3698. GGML_ASSERT(ggml_are_same_shape(x, dt));
  3699. GGML_ASSERT(ggml_are_same_shape(B, C));
  3700. {
  3701. const int64_t d_state = s->ne[0];
  3702. const int64_t d_inner = s->ne[1];
  3703. const int64_t n_seq_tokens = x->ne[1];
  3704. const int64_t n_seqs = x->ne[2];
  3705. GGML_ASSERT(s->ne[2] == n_seqs);
  3706. GGML_ASSERT(x->ne[0] == d_inner);
  3707. GGML_ASSERT(A->ne[0] == d_state);
  3708. GGML_ASSERT(A->ne[1] == d_inner);
  3709. GGML_ASSERT(B->ne[0] == d_state);
  3710. GGML_ASSERT(B->ne[1] == n_seq_tokens);
  3711. GGML_ASSERT(B->ne[2] == n_seqs);
  3712. }
  3713. // concatenated y + ssm_states
  3714. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + ggml_nelements(s));
  3715. result->op = GGML_OP_SSM_SCAN;
  3716. result->src[0] = s;
  3717. result->src[1] = x;
  3718. result->src[2] = dt;
  3719. result->src[3] = A;
  3720. result->src[4] = B;
  3721. result->src[5] = C;
  3722. return result;
  3723. }
  3724. // ggml_win_part
  3725. struct ggml_tensor * ggml_win_part(
  3726. struct ggml_context * ctx,
  3727. struct ggml_tensor * a,
  3728. int w) {
  3729. GGML_ASSERT(a->ne[3] == 1);
  3730. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3731. // padding
  3732. const int px = (w - a->ne[1]%w)%w;
  3733. const int py = (w - a->ne[2]%w)%w;
  3734. const int npx = (px + a->ne[1])/w;
  3735. const int npy = (py + a->ne[2])/w;
  3736. const int np = npx*npy;
  3737. const int64_t ne[4] = { a->ne[0], w, w, np, };
  3738. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3739. int32_t params[] = { npx, npy, w };
  3740. ggml_set_op_params(result, params, sizeof(params));
  3741. result->op = GGML_OP_WIN_PART;
  3742. result->src[0] = a;
  3743. return result;
  3744. }
  3745. // ggml_win_unpart
  3746. struct ggml_tensor * ggml_win_unpart(
  3747. struct ggml_context * ctx,
  3748. struct ggml_tensor * a,
  3749. int w0,
  3750. int h0,
  3751. int w) {
  3752. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3753. const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
  3754. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
  3755. int32_t params[] = { w };
  3756. ggml_set_op_params(result, params, sizeof(params));
  3757. result->op = GGML_OP_WIN_UNPART;
  3758. result->src[0] = a;
  3759. return result;
  3760. }
  3761. // ggml_get_rel_pos
  3762. struct ggml_tensor * ggml_get_rel_pos(
  3763. struct ggml_context * ctx,
  3764. struct ggml_tensor * a,
  3765. int qh,
  3766. int kh) {
  3767. GGML_ASSERT(qh == kh);
  3768. GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
  3769. const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
  3770. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
  3771. result->op = GGML_OP_GET_REL_POS;
  3772. result->src[0] = a;
  3773. return result;
  3774. }
  3775. // ggml_add_rel_pos
  3776. static struct ggml_tensor * ggml_add_rel_pos_impl(
  3777. struct ggml_context * ctx,
  3778. struct ggml_tensor * a,
  3779. struct ggml_tensor * pw,
  3780. struct ggml_tensor * ph,
  3781. bool inplace) {
  3782. GGML_ASSERT(ggml_are_same_shape(pw, ph));
  3783. GGML_ASSERT(ggml_is_contiguous(a));
  3784. GGML_ASSERT(ggml_is_contiguous(pw));
  3785. GGML_ASSERT(ggml_is_contiguous(ph));
  3786. GGML_ASSERT(ph->type == GGML_TYPE_F32);
  3787. GGML_ASSERT(pw->type == GGML_TYPE_F32);
  3788. GGML_ASSERT(pw->ne[3] == a->ne[2]);
  3789. GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
  3790. GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
  3791. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3792. ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
  3793. result->op = GGML_OP_ADD_REL_POS;
  3794. result->src[0] = a;
  3795. result->src[1] = pw;
  3796. result->src[2] = ph;
  3797. return result;
  3798. }
  3799. struct ggml_tensor * ggml_add_rel_pos(
  3800. struct ggml_context * ctx,
  3801. struct ggml_tensor * a,
  3802. struct ggml_tensor * pw,
  3803. struct ggml_tensor * ph) {
  3804. return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
  3805. }
  3806. struct ggml_tensor * ggml_add_rel_pos_inplace(
  3807. struct ggml_context * ctx,
  3808. struct ggml_tensor * a,
  3809. struct ggml_tensor * pw,
  3810. struct ggml_tensor * ph) {
  3811. return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
  3812. }
  3813. // ggml_rwkv_wkv6
  3814. struct ggml_tensor * ggml_rwkv_wkv6(
  3815. struct ggml_context * ctx,
  3816. struct ggml_tensor * k,
  3817. struct ggml_tensor * v,
  3818. struct ggml_tensor * r,
  3819. struct ggml_tensor * tf,
  3820. struct ggml_tensor * td,
  3821. struct ggml_tensor * state) {
  3822. GGML_ASSERT(ggml_is_contiguous(k));
  3823. GGML_ASSERT(ggml_is_contiguous(v));
  3824. GGML_ASSERT(ggml_is_contiguous(r));
  3825. GGML_ASSERT(ggml_is_contiguous(tf));
  3826. GGML_ASSERT(ggml_is_contiguous(td));
  3827. GGML_ASSERT(ggml_is_contiguous(state));
  3828. const int64_t S = k->ne[0];
  3829. const int64_t H = k->ne[1];
  3830. const int64_t n_tokens = k->ne[2];
  3831. const int64_t n_seqs = state->ne[1];
  3832. {
  3833. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3834. GGML_ASSERT(r->ne[0] == S && r->ne[1] == H && r->ne[2] == n_tokens);
  3835. GGML_ASSERT(td->ne[0] == S && td->ne[1] == H && td->ne[2] == n_tokens);
  3836. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3837. }
  3838. // concat output and new_state
  3839. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3840. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3841. result->op = GGML_OP_RWKV_WKV6;
  3842. result->src[0] = k;
  3843. result->src[1] = v;
  3844. result->src[2] = r;
  3845. result->src[3] = tf;
  3846. result->src[4] = td;
  3847. result->src[5] = state;
  3848. return result;
  3849. }
  3850. // ggml_gated_linear_attn
  3851. struct ggml_tensor * ggml_gated_linear_attn(
  3852. struct ggml_context * ctx,
  3853. struct ggml_tensor * k,
  3854. struct ggml_tensor * v,
  3855. struct ggml_tensor * q,
  3856. struct ggml_tensor * g,
  3857. struct ggml_tensor * state,
  3858. float scale) {
  3859. GGML_ASSERT(ggml_is_contiguous(k));
  3860. GGML_ASSERT(ggml_is_contiguous(v));
  3861. GGML_ASSERT(ggml_is_contiguous(q));
  3862. GGML_ASSERT(ggml_is_contiguous(g));
  3863. GGML_ASSERT(ggml_is_contiguous(state));
  3864. const int64_t S = k->ne[0];
  3865. const int64_t H = k->ne[1];
  3866. const int64_t n_tokens = k->ne[2];
  3867. const int64_t n_seqs = state->ne[1];
  3868. {
  3869. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3870. GGML_ASSERT(q->ne[0] == S && q->ne[1] == H && q->ne[2] == n_tokens);
  3871. GGML_ASSERT(g->ne[0] == S && g->ne[1] == H && g->ne[2] == n_tokens);
  3872. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3873. }
  3874. // concat output and new_state
  3875. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3876. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3877. ggml_set_op_params_f32(result, 0, scale);
  3878. result->op = GGML_OP_GATED_LINEAR_ATTN;
  3879. result->src[0] = k;
  3880. result->src[1] = v;
  3881. result->src[2] = q;
  3882. result->src[3] = g;
  3883. result->src[4] = state;
  3884. return result;
  3885. }
  3886. // ggml_rwkv_wkv7
  3887. struct ggml_tensor * ggml_rwkv_wkv7(
  3888. struct ggml_context * ctx,
  3889. struct ggml_tensor * r,
  3890. struct ggml_tensor * w,
  3891. struct ggml_tensor * k,
  3892. struct ggml_tensor * v,
  3893. struct ggml_tensor * a,
  3894. struct ggml_tensor * b,
  3895. struct ggml_tensor * state) {
  3896. GGML_ASSERT(ggml_is_contiguous(r));
  3897. GGML_ASSERT(ggml_is_contiguous(w));
  3898. GGML_ASSERT(ggml_is_contiguous(k));
  3899. GGML_ASSERT(ggml_is_contiguous(v));
  3900. GGML_ASSERT(ggml_is_contiguous(a));
  3901. GGML_ASSERT(ggml_is_contiguous(b));
  3902. GGML_ASSERT(ggml_is_contiguous(state));
  3903. const int64_t S = k->ne[0];
  3904. const int64_t H = k->ne[1];
  3905. const int64_t n_tokens = k->ne[2];
  3906. const int64_t n_seqs = state->ne[1];
  3907. {
  3908. GGML_ASSERT(w->ne[0] == S && w->ne[1] == H && w->ne[2] == n_tokens);
  3909. GGML_ASSERT(k->ne[0] == S && k->ne[1] == H && k->ne[2] == n_tokens);
  3910. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3911. GGML_ASSERT(a->ne[0] == S && a->ne[1] == H && a->ne[2] == n_tokens);
  3912. GGML_ASSERT(b->ne[0] == S && b->ne[1] == H && b->ne[2] == n_tokens);
  3913. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3914. }
  3915. // concat output and new_state
  3916. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3917. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3918. result->op = GGML_OP_RWKV_WKV7;
  3919. result->src[0] = r;
  3920. result->src[1] = w;
  3921. result->src[2] = k;
  3922. result->src[3] = v;
  3923. result->src[4] = a;
  3924. result->src[5] = b;
  3925. result->src[6] = state;
  3926. return result;
  3927. }
  3928. // ggml_unary
  3929. static struct ggml_tensor * ggml_unary_impl(
  3930. struct ggml_context * ctx,
  3931. struct ggml_tensor * a,
  3932. enum ggml_unary_op op,
  3933. bool inplace) {
  3934. GGML_ASSERT(ggml_is_contiguous_1(a));
  3935. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3936. ggml_set_op_params_i32(result, 0, (int32_t) op);
  3937. result->op = GGML_OP_UNARY;
  3938. result->src[0] = a;
  3939. return result;
  3940. }
  3941. struct ggml_tensor * ggml_unary(
  3942. struct ggml_context * ctx,
  3943. struct ggml_tensor * a,
  3944. enum ggml_unary_op op) {
  3945. return ggml_unary_impl(ctx, a, op, false);
  3946. }
  3947. struct ggml_tensor * ggml_unary_inplace(
  3948. struct ggml_context * ctx,
  3949. struct ggml_tensor * a,
  3950. enum ggml_unary_op op) {
  3951. return ggml_unary_impl(ctx, a, op, true);
  3952. }
  3953. // ggml_map_custom1
  3954. static struct ggml_tensor * ggml_map_custom1_impl(
  3955. struct ggml_context * ctx,
  3956. struct ggml_tensor * a,
  3957. const ggml_custom1_op_t fun,
  3958. int n_tasks,
  3959. void * userdata,
  3960. bool inplace) {
  3961. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  3962. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3963. struct ggml_map_custom1_op_params params = {
  3964. /*.fun =*/ fun,
  3965. /*.n_tasks =*/ n_tasks,
  3966. /*.userdata =*/ userdata
  3967. };
  3968. ggml_set_op_params(result, &params, sizeof(params));
  3969. result->op = GGML_OP_MAP_CUSTOM1;
  3970. result->src[0] = a;
  3971. return result;
  3972. }
  3973. struct ggml_tensor * ggml_map_custom1(
  3974. struct ggml_context * ctx,
  3975. struct ggml_tensor * a,
  3976. const ggml_custom1_op_t fun,
  3977. int n_tasks,
  3978. void * userdata) {
  3979. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
  3980. }
  3981. struct ggml_tensor * ggml_map_custom1_inplace(
  3982. struct ggml_context * ctx,
  3983. struct ggml_tensor * a,
  3984. const ggml_custom1_op_t fun,
  3985. int n_tasks,
  3986. void * userdata) {
  3987. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
  3988. }
  3989. // ggml_map_custom2
  3990. static struct ggml_tensor * ggml_map_custom2_impl(
  3991. struct ggml_context * ctx,
  3992. struct ggml_tensor * a,
  3993. struct ggml_tensor * b,
  3994. const ggml_custom2_op_t fun,
  3995. int n_tasks,
  3996. void * userdata,
  3997. bool inplace) {
  3998. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  3999. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4000. struct ggml_map_custom2_op_params params = {
  4001. /*.fun =*/ fun,
  4002. /*.n_tasks =*/ n_tasks,
  4003. /*.userdata =*/ userdata
  4004. };
  4005. ggml_set_op_params(result, &params, sizeof(params));
  4006. result->op = GGML_OP_MAP_CUSTOM2;
  4007. result->src[0] = a;
  4008. result->src[1] = b;
  4009. return result;
  4010. }
  4011. struct ggml_tensor * ggml_map_custom2(
  4012. struct ggml_context * ctx,
  4013. struct ggml_tensor * a,
  4014. struct ggml_tensor * b,
  4015. const ggml_custom2_op_t fun,
  4016. int n_tasks,
  4017. void * userdata) {
  4018. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
  4019. }
  4020. struct ggml_tensor * ggml_map_custom2_inplace(
  4021. struct ggml_context * ctx,
  4022. struct ggml_tensor * a,
  4023. struct ggml_tensor * b,
  4024. const ggml_custom2_op_t fun,
  4025. int n_tasks,
  4026. void * userdata) {
  4027. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
  4028. }
  4029. // ggml_map_custom3
  4030. static struct ggml_tensor * ggml_map_custom3_impl(
  4031. struct ggml_context * ctx,
  4032. struct ggml_tensor * a,
  4033. struct ggml_tensor * b,
  4034. struct ggml_tensor * c,
  4035. const ggml_custom3_op_t fun,
  4036. int n_tasks,
  4037. void * userdata,
  4038. bool inplace) {
  4039. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4040. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4041. struct ggml_map_custom3_op_params params = {
  4042. /*.fun =*/ fun,
  4043. /*.n_tasks =*/ n_tasks,
  4044. /*.userdata =*/ userdata
  4045. };
  4046. ggml_set_op_params(result, &params, sizeof(params));
  4047. result->op = GGML_OP_MAP_CUSTOM3;
  4048. result->src[0] = a;
  4049. result->src[1] = b;
  4050. result->src[2] = c;
  4051. return result;
  4052. }
  4053. struct ggml_tensor * ggml_map_custom3(
  4054. struct ggml_context * ctx,
  4055. struct ggml_tensor * a,
  4056. struct ggml_tensor * b,
  4057. struct ggml_tensor * c,
  4058. const ggml_custom3_op_t fun,
  4059. int n_tasks,
  4060. void * userdata) {
  4061. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
  4062. }
  4063. struct ggml_tensor * ggml_map_custom3_inplace(
  4064. struct ggml_context * ctx,
  4065. struct ggml_tensor * a,
  4066. struct ggml_tensor * b,
  4067. struct ggml_tensor * c,
  4068. const ggml_custom3_op_t fun,
  4069. int n_tasks,
  4070. void * userdata) {
  4071. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
  4072. }
  4073. struct ggml_tensor * ggml_custom_4d(
  4074. struct ggml_context * ctx,
  4075. enum ggml_type type,
  4076. int64_t ne0,
  4077. int64_t ne1,
  4078. int64_t ne2,
  4079. int64_t ne3,
  4080. struct ggml_tensor ** args,
  4081. int n_args,
  4082. ggml_custom_op_t fun,
  4083. int n_tasks,
  4084. void * userdata) {
  4085. GGML_ASSERT(n_args < GGML_MAX_SRC);
  4086. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, ne0, ne1, ne2, ne3);
  4087. struct ggml_custom_op_params params = {
  4088. /*.fun =*/ fun,
  4089. /*.n_tasks =*/ n_tasks,
  4090. /*.userdata =*/ userdata
  4091. };
  4092. ggml_set_op_params(result, &params, sizeof(params));
  4093. result->op = GGML_OP_CUSTOM;
  4094. for (int i = 0; i < n_args; i++) {
  4095. result->src[i] = args[i];
  4096. }
  4097. return result;
  4098. }
  4099. struct ggml_tensor * ggml_custom_inplace(
  4100. struct ggml_context * ctx,
  4101. struct ggml_tensor * a,
  4102. struct ggml_tensor ** args,
  4103. int n_args,
  4104. ggml_custom_op_t fun,
  4105. int n_tasks,
  4106. void * userdata) {
  4107. GGML_ASSERT(n_args < GGML_MAX_SRC - 1);
  4108. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  4109. struct ggml_custom_op_params params = {
  4110. /*.fun =*/ fun,
  4111. /*.n_tasks =*/ n_tasks,
  4112. /*.userdata =*/ userdata
  4113. };
  4114. ggml_set_op_params(result, &params, sizeof(params));
  4115. result->op = GGML_OP_CUSTOM;
  4116. result->src[0] = a;
  4117. for (int i = 0; i < n_args; i++) {
  4118. result->src[i + 1] = args[i];
  4119. }
  4120. return result;
  4121. }
  4122. // ggml_cross_entropy_loss
  4123. struct ggml_tensor * ggml_cross_entropy_loss(
  4124. struct ggml_context * ctx,
  4125. struct ggml_tensor * a,
  4126. struct ggml_tensor * b) {
  4127. GGML_ASSERT(ggml_are_same_shape(a, b));
  4128. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  4129. result->op = GGML_OP_CROSS_ENTROPY_LOSS;
  4130. result->src[0] = a;
  4131. result->src[1] = b;
  4132. return result;
  4133. }
  4134. // ggml_cross_entropy_loss_back
  4135. struct ggml_tensor * ggml_cross_entropy_loss_back(
  4136. struct ggml_context * ctx,
  4137. struct ggml_tensor * a,
  4138. struct ggml_tensor * b,
  4139. struct ggml_tensor * c) {
  4140. GGML_ASSERT(ggml_is_scalar(a));
  4141. GGML_ASSERT(ggml_are_same_shape(b, c));
  4142. struct ggml_tensor * result = ggml_dup_tensor(ctx, b);
  4143. result->op = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
  4144. result->src[0] = a;
  4145. result->src[1] = b;
  4146. result->src[2] = c;
  4147. return result;
  4148. }
  4149. // opt_step_adamw
  4150. struct ggml_tensor * ggml_opt_step_adamw(
  4151. struct ggml_context * ctx,
  4152. struct ggml_tensor * a,
  4153. struct ggml_tensor * grad,
  4154. struct ggml_tensor * m,
  4155. struct ggml_tensor * v,
  4156. struct ggml_tensor * adamw_params) {
  4157. GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
  4158. GGML_ASSERT(ggml_are_same_shape(a, grad));
  4159. GGML_ASSERT(ggml_are_same_shape(a, m));
  4160. GGML_ASSERT(ggml_are_same_shape(a, v));
  4161. GGML_ASSERT(adamw_params->type == GGML_TYPE_F32);
  4162. GGML_ASSERT(ggml_nelements(adamw_params) == 7);
  4163. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  4164. result->op = GGML_OP_OPT_STEP_ADAMW;
  4165. result->src[0] = a;
  4166. result->src[1] = grad;
  4167. result->src[2] = m;
  4168. result->src[3] = v;
  4169. result->src[4] = adamw_params;
  4170. return result;
  4171. }
  4172. ////////////////////////////////////////////////////////////////////////////////
  4173. struct ggml_hash_set ggml_hash_set_new(size_t size) {
  4174. size = ggml_hash_size(size);
  4175. struct ggml_hash_set result;
  4176. result.size = size;
  4177. result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
  4178. result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
  4179. return result;
  4180. }
  4181. void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
  4182. memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
  4183. }
  4184. void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
  4185. GGML_FREE(hash_set->used);
  4186. GGML_FREE(hash_set->keys);
  4187. }
  4188. size_t ggml_hash_size(size_t min_sz) {
  4189. // next primes after powers of two
  4190. static const size_t primes[] = {
  4191. 2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
  4192. 2053, 4099, 8209, 16411, 32771, 65537, 131101,
  4193. 262147, 524309, 1048583, 2097169, 4194319, 8388617,
  4194. 16777259, 33554467, 67108879, 134217757, 268435459,
  4195. 536870923, 1073741827, 2147483659
  4196. };
  4197. static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
  4198. // find the smallest prime that is larger or equal than min_sz
  4199. size_t l = 0;
  4200. size_t r = n_primes;
  4201. while (l < r) {
  4202. size_t m = (l + r)/2;
  4203. if (primes[m] < min_sz) {
  4204. l = m + 1;
  4205. } else {
  4206. r = m;
  4207. }
  4208. }
  4209. size_t sz = l < n_primes ? primes[l] : min_sz | 1;
  4210. return sz;
  4211. }
  4212. struct hash_map {
  4213. struct ggml_hash_set set;
  4214. struct ggml_tensor ** vals;
  4215. };
  4216. static struct hash_map * ggml_new_hash_map(size_t size) {
  4217. struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
  4218. result->set = ggml_hash_set_new(size);
  4219. result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
  4220. return result;
  4221. }
  4222. static void ggml_hash_map_free(struct hash_map * map) {
  4223. ggml_hash_set_free(&map->set);
  4224. GGML_FREE(map->vals);
  4225. GGML_FREE(map);
  4226. }
  4227. // utility functions to change gradients
  4228. // isrc is the index of tensor in cgraph->visited_has_set.keys
  4229. // the corresponding gradient (accumulators) are also at position isrc
  4230. // if tensor has a gradient accumulator, modify that accumulator in-place
  4231. // else if there is no gradient for tensor, set the corresponding value
  4232. // else, just add/subtract/etc. the gradients
  4233. static void ggml_add_or_set(
  4234. struct ggml_context * ctx,
  4235. struct ggml_cgraph * cgraph,
  4236. size_t isrc,
  4237. struct ggml_tensor * tensor) {
  4238. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4239. GGML_ASSERT(src);
  4240. if (cgraph->grads[isrc]) {
  4241. cgraph->grads[isrc] = ggml_add_impl(ctx, cgraph->grads[isrc], tensor, /*inplace =*/ cgraph->grad_accs[isrc]);
  4242. } else {
  4243. cgraph->grads[isrc] = tensor;
  4244. }
  4245. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4246. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4247. }
  4248. static void ggml_acc_or_set(
  4249. struct ggml_context * ctx,
  4250. struct ggml_cgraph * cgraph,
  4251. size_t isrc,
  4252. struct ggml_tensor * tensor,
  4253. const size_t nb1,
  4254. const size_t nb2,
  4255. const size_t nb3,
  4256. const size_t offset) {
  4257. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4258. GGML_ASSERT(src);
  4259. if (cgraph->grads[isrc]) {
  4260. cgraph->grads[isrc] = ggml_acc_impl(ctx, cgraph->grads[isrc], tensor, nb1, nb2, nb3, offset, cgraph->grad_accs[isrc]);
  4261. } else {
  4262. struct ggml_tensor * a_zero = ggml_scale(ctx, src, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
  4263. cgraph->grads[isrc] = ggml_acc_impl(ctx, a_zero, tensor, nb1, nb2, nb3, offset, false);
  4264. }
  4265. ggml_format_name(cgraph->grads[isrc], "grad for %s", cgraph->visited_hash_set.keys[isrc]->name);
  4266. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4267. }
  4268. static void ggml_add1_or_set(
  4269. struct ggml_context * ctx,
  4270. struct ggml_cgraph * cgraph,
  4271. size_t isrc,
  4272. struct ggml_tensor * tensor) {
  4273. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4274. GGML_ASSERT(src);
  4275. if (cgraph->grads[isrc]) {
  4276. cgraph->grads[isrc] = ggml_add1_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4277. } else {
  4278. cgraph->grads[isrc] = ggml_repeat(ctx, tensor, src);
  4279. }
  4280. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4281. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4282. }
  4283. static void ggml_sub_or_set(
  4284. struct ggml_context * ctx,
  4285. struct ggml_cgraph * cgraph,
  4286. size_t isrc,
  4287. struct ggml_tensor * tensor) {
  4288. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4289. GGML_ASSERT(src);
  4290. if (cgraph->grads[isrc]) {
  4291. cgraph->grads[isrc] = ggml_sub_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4292. } else {
  4293. cgraph->grads[isrc] = ggml_neg(ctx, tensor);
  4294. }
  4295. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4296. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4297. }
  4298. static void ggml_compute_backward(
  4299. struct ggml_context * ctx, struct ggml_cgraph * cgraph, int i, const bool * grads_needed) {
  4300. struct ggml_tensor * tensor = cgraph->nodes[i];
  4301. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, tensor);
  4302. if (!grad) {
  4303. return;
  4304. }
  4305. struct ggml_tensor * src0 = tensor->src[0];
  4306. struct ggml_tensor * src1 = tensor->src[1];
  4307. struct ggml_tensor * src2 = tensor->src[2];
  4308. struct ggml_hash_set * hash_set = &cgraph->visited_hash_set;
  4309. const size_t isrc0 = src0 ? ggml_hash_find(hash_set, src0) : (size_t) -1;
  4310. const size_t isrc1 = src1 ? ggml_hash_find(hash_set, src1) : (size_t) -1;
  4311. const size_t isrc2 = src2 ? ggml_hash_find(hash_set, src2) : (size_t) -1;
  4312. const bool src0_needs_grads = src0 && isrc0 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc0) && grads_needed[isrc0];
  4313. const bool src1_needs_grads = src1 && isrc1 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc1) && grads_needed[isrc1];
  4314. const bool src2_needs_grads = src2 && isrc2 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc2) && grads_needed[isrc2];
  4315. switch (tensor->op) {
  4316. case GGML_OP_DUP: {
  4317. if (src0_needs_grads) {
  4318. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4319. }
  4320. } break;
  4321. case GGML_OP_ADD: {
  4322. if (src0_needs_grads) {
  4323. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4324. }
  4325. if (src1_needs_grads) {
  4326. struct ggml_tensor * tmp = grad;
  4327. if (!ggml_are_same_shape(src0, src1)) {
  4328. tmp = ggml_repeat_back(ctx, tmp, src1);
  4329. }
  4330. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4331. }
  4332. } break;
  4333. case GGML_OP_ADD1: {
  4334. if (src0_needs_grads) {
  4335. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4336. }
  4337. if (src1_needs_grads) {
  4338. ggml_add_or_set(ctx, cgraph, isrc1, ggml_mean(ctx, grad)); // TODO: should probably be sum instead of mean
  4339. }
  4340. } break;
  4341. case GGML_OP_ACC: {
  4342. if (src0_needs_grads) {
  4343. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4344. }
  4345. if (src1_needs_grads) {
  4346. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  4347. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  4348. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  4349. const size_t offset = ((int32_t *) tensor->op_params)[3];
  4350. struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
  4351. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4352. nb1, nb2, nb3, offset);
  4353. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4354. }
  4355. } break;
  4356. case GGML_OP_SUB: {
  4357. if (src0_needs_grads) {
  4358. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4359. }
  4360. if (src1_needs_grads) {
  4361. ggml_sub_or_set(ctx, cgraph, isrc1, grad);
  4362. }
  4363. } break;
  4364. case GGML_OP_MUL: {
  4365. if (src0_needs_grads) {
  4366. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, src1));
  4367. }
  4368. if (src1_needs_grads) {
  4369. struct ggml_tensor * tmp = ggml_mul(ctx, src0, grad);
  4370. if (!ggml_are_same_shape(src0, src1)) {
  4371. tmp = ggml_repeat_back(ctx, tmp, src1);
  4372. }
  4373. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4374. }
  4375. } break;
  4376. case GGML_OP_DIV: {
  4377. if (src0_needs_grads) {
  4378. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src1));
  4379. }
  4380. if (src1_needs_grads) {
  4381. ggml_sub_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1)));
  4382. }
  4383. } break;
  4384. case GGML_OP_SQR: {
  4385. if (src0_needs_grads) {
  4386. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_mul(ctx, src0, grad), 2.0f));
  4387. }
  4388. } break;
  4389. case GGML_OP_SQRT: {
  4390. if (src0_needs_grads) {
  4391. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_div(ctx, grad, tensor), 0.5f));
  4392. }
  4393. } break;
  4394. case GGML_OP_LOG: {
  4395. if (src0_needs_grads) {
  4396. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src0));
  4397. }
  4398. } break;
  4399. case GGML_OP_SIN: {
  4400. if (src0_needs_grads) {
  4401. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_cos(ctx, src0)));
  4402. }
  4403. } break;
  4404. case GGML_OP_COS: {
  4405. if (src0_needs_grads) {
  4406. ggml_sub_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sin(ctx, src0)));
  4407. }
  4408. } break;
  4409. case GGML_OP_SUM: {
  4410. if (src0_needs_grads) {
  4411. ggml_add1_or_set(ctx, cgraph, isrc0, grad);
  4412. }
  4413. } break;
  4414. case GGML_OP_SUM_ROWS: {
  4415. if (src0_needs_grads) {
  4416. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4417. }
  4418. } break;
  4419. case GGML_OP_MEAN: {
  4420. if (src0_needs_grads) {
  4421. ggml_add1_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], false));
  4422. }
  4423. } break;
  4424. case GGML_OP_REPEAT: {
  4425. if (src0_needs_grads) {
  4426. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat_back(ctx, grad, src0));
  4427. }
  4428. } break;
  4429. case GGML_OP_REPEAT_BACK: {
  4430. if (src0_needs_grads) {
  4431. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4432. }
  4433. } break;
  4434. case GGML_OP_RMS_NORM: {
  4435. if (src0_needs_grads) {
  4436. float eps;
  4437. memcpy(&eps, tensor->op_params, sizeof(float));
  4438. ggml_add_or_set(ctx, cgraph, isrc0, ggml_rms_norm_back(ctx, grad, src0, eps));
  4439. }
  4440. } break;
  4441. case GGML_OP_MUL_MAT: {
  4442. // https://cs231n.github.io/optimization-2/#staged
  4443. // # forward pass
  4444. // s0 = np.random.randn(5, 10)
  4445. // s1 = np.random.randn(10, 3)
  4446. // t = s0.dot(s1)
  4447. // # now suppose we had the gradient on t from above in the circuit
  4448. // dt = np.random.randn(*t.shape) # same shape as t
  4449. // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
  4450. // ds1 = t.T.dot(dt)
  4451. // tensor.shape [m,p,qq,rr]
  4452. // src0.shape [n,m,q1,r1]
  4453. // src1.shape [n,p,qq,rr]
  4454. if (src0_needs_grads) {
  4455. GGML_ASSERT(grad->ne[2] == src1->ne[2]);
  4456. GGML_ASSERT(grad->ne[3] == src1->ne[3]);
  4457. struct ggml_tensor * tmp =
  4458. ggml_out_prod(ctx, // [n,m,qq,rr]
  4459. src1, // [n,p,qq,rr]
  4460. grad); // [m,p,qq,rr]
  4461. if (!ggml_are_same_shape(tmp, src0)) {
  4462. GGML_ASSERT(tmp->ne[0] == src0->ne[0]);
  4463. GGML_ASSERT(tmp->ne[1] == src0->ne[1]);
  4464. GGML_ASSERT(tmp->ne[3] == 1);
  4465. const int64_t nr2 = tmp->ne[2] / src0->ne[2];
  4466. const size_t nb2 = tmp->nb[2] * nr2;
  4467. const size_t nb3 = tmp->nb[2];
  4468. tmp = ggml_view_4d(ctx, tmp, src0->ne[0], src0->ne[1], src0->ne[2], nr2, tmp->nb[1], nb2, nb3, 0);
  4469. tmp = ggml_repeat_back(ctx, tmp, src0);
  4470. }
  4471. ggml_add_or_set(ctx, cgraph, isrc0, tmp);
  4472. }
  4473. if (src1_needs_grads) {
  4474. ggml_add_or_set(ctx, cgraph, isrc1,
  4475. // ggml_mul_mat(ctx, // [n,p,qq,rr]
  4476. // ggml_cont(ctx, // [m,n,q1,r1]
  4477. // ggml_transpose(ctx, src0)), // [m,n,q1,r1]
  4478. // grad), // [m,p,qq,rr]
  4479. // when src0 is bigger than tensor->grad (this is mostly the case in llama),
  4480. // avoid transpose of src0, rather transpose smaller tensor->grad
  4481. // and then use ggml_out_prod
  4482. ggml_out_prod(ctx, // [n,p,qq,rr]
  4483. src0, // [n,m,q1,r1]
  4484. ggml_transpose(ctx, // [p,m,qq,rr]
  4485. grad))); // [m,p,qq,rr]
  4486. }
  4487. } break;
  4488. case GGML_OP_SCALE: {
  4489. if (src0_needs_grads) {
  4490. float s;
  4491. memcpy(&s, tensor->op_params, sizeof(float));
  4492. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, s, false));
  4493. }
  4494. } break;
  4495. case GGML_OP_SET: {
  4496. const size_t nb1 = ((const int32_t *) tensor->op_params)[0];
  4497. const size_t nb2 = ((const int32_t *) tensor->op_params)[1];
  4498. const size_t nb3 = ((const int32_t *) tensor->op_params)[2];
  4499. const size_t offset = ((const int32_t *) tensor->op_params)[3];
  4500. struct ggml_tensor * tensor_grad_view = NULL;
  4501. if (src0_needs_grads || src1_needs_grads) {
  4502. GGML_ASSERT(src0->type == tensor->type);
  4503. GGML_ASSERT(!cgraph->grads[isrc0] || cgraph->grads[isrc0]->type == grad->type);
  4504. GGML_ASSERT(!cgraph->grads[isrc1] || !src1_needs_grads || cgraph->grads[isrc1]->type == grad->type);
  4505. tensor_grad_view = ggml_view_4d(ctx,
  4506. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4507. nb1, nb2, nb3, offset);
  4508. }
  4509. if (src0_needs_grads) {
  4510. struct ggml_tensor * tmp = ggml_neg(ctx, tensor_grad_view);
  4511. ggml_add_or_set(ctx, cgraph, isrc0, ggml_acc_impl(ctx, grad, tmp, nb1, nb2, nb3, offset, false));
  4512. }
  4513. if (src1_needs_grads) {
  4514. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4515. }
  4516. } break;
  4517. case GGML_OP_CPY: {
  4518. // cpy overwrites value of src1 by src0 and returns view(src1)
  4519. // the overwriting is mathematically equivalent to:
  4520. // tensor = src0 * 1 + src1 * 0
  4521. if (src0_needs_grads) {
  4522. // dsrc0 = dtensor * 1
  4523. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4524. }
  4525. if (src1_needs_grads) {
  4526. // dsrc1 = dtensor * 0 -> noop
  4527. }
  4528. } break;
  4529. case GGML_OP_CONT: {
  4530. // same as cpy
  4531. if (src0_needs_grads) {
  4532. GGML_ASSERT(!cgraph->grads[isrc0] || ggml_is_contiguous(cgraph->grads[isrc0]));
  4533. GGML_ASSERT(ggml_is_contiguous(grad));
  4534. GGML_ASSERT(ggml_nelements(tensor) == ggml_nelements(src0));
  4535. ggml_add_or_set(ctx, cgraph, isrc0,
  4536. ggml_are_same_shape(tensor, src0) ? grad : ggml_reshape(ctx, grad, src0));
  4537. }
  4538. } break;
  4539. case GGML_OP_RESHAPE: {
  4540. if (src0_needs_grads) {
  4541. struct ggml_tensor * grad_cont = ggml_is_contiguous(grad) ? grad : ggml_cont(ctx, grad);
  4542. ggml_add_or_set(ctx, cgraph, isrc0, ggml_reshape(ctx, grad_cont, src0));
  4543. }
  4544. } break;
  4545. case GGML_OP_VIEW: {
  4546. if (src0_needs_grads) {
  4547. size_t offset;
  4548. memcpy(&offset, tensor->op_params, sizeof(offset));
  4549. size_t nb1 = tensor->nb[1];
  4550. size_t nb2 = tensor->nb[2];
  4551. size_t nb3 = tensor->nb[3];
  4552. if (cgraph->grads[isrc0] && src0->type != cgraph->grads[isrc0]->type) {
  4553. // gradient is typically F32, but src0 could be other type
  4554. size_t ng = ggml_element_size(cgraph->grads[isrc0]);
  4555. size_t n0 = ggml_element_size(src0);
  4556. GGML_ASSERT(offset % n0 == 0);
  4557. GGML_ASSERT(nb1 % n0 == 0);
  4558. GGML_ASSERT(nb2 % n0 == 0);
  4559. GGML_ASSERT(nb3 % n0 == 0);
  4560. offset = (offset / n0) * ng;
  4561. nb1 = (nb1 / n0) * ng;
  4562. nb2 = (nb2 / n0) * ng;
  4563. nb3 = (nb3 / n0) * ng;
  4564. }
  4565. ggml_acc_or_set(ctx, cgraph, isrc0, grad, nb1, nb2, nb3, offset);
  4566. }
  4567. } break;
  4568. case GGML_OP_PERMUTE: {
  4569. if (src0_needs_grads) {
  4570. const int32_t * axes = (const int32_t *) tensor->op_params;
  4571. const int axis0 = axes[0] & 0x3;
  4572. const int axis1 = axes[1] & 0x3;
  4573. const int axis2 = axes[2] & 0x3;
  4574. const int axis3 = axes[3] & 0x3;
  4575. int axb[4] = {0,0,0,0}; // axes backward
  4576. axb[axis0] = 0;
  4577. axb[axis1] = 1;
  4578. axb[axis2] = 2;
  4579. axb[axis3] = 3;
  4580. ggml_add_or_set(ctx, cgraph, isrc0, ggml_permute(ctx, grad, axb[0], axb[1], axb[2], axb[3]));
  4581. }
  4582. } break;
  4583. case GGML_OP_TRANSPOSE: {
  4584. if (src0_needs_grads) {
  4585. ggml_add_or_set(ctx, cgraph, isrc0, ggml_transpose(ctx, grad));
  4586. }
  4587. } break;
  4588. case GGML_OP_GET_ROWS: {
  4589. if (src0_needs_grads) {
  4590. ggml_add_or_set(ctx, cgraph, isrc0, ggml_get_rows_back(ctx, grad, src1, src0));
  4591. }
  4592. if (src1_needs_grads) {
  4593. // noop
  4594. }
  4595. } break;
  4596. case GGML_OP_DIAG_MASK_INF: {
  4597. if (src0_needs_grads) {
  4598. /* ggml_diag_mask_inf_impl() shouldn't be here */
  4599. /* ref: https://github.com/ggerganov/llama.cpp/pull/4203#discussion_r1412377992 */
  4600. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4601. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4602. }
  4603. } break;
  4604. case GGML_OP_DIAG_MASK_ZERO: {
  4605. if (src0_needs_grads) {
  4606. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4607. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4608. }
  4609. } break;
  4610. case GGML_OP_SOFT_MAX: {
  4611. if (src0_needs_grads) {
  4612. float scale = 1.0f;
  4613. float max_bias = 0.0f;
  4614. memcpy(&scale, (const float *) tensor->op_params + 0, sizeof(float));
  4615. memcpy(&max_bias, (const float *) tensor->op_params + 1, sizeof(float));
  4616. ggml_add_or_set(ctx, cgraph, isrc0, ggml_soft_max_ext_back(ctx, grad, tensor, scale, max_bias));
  4617. }
  4618. GGML_ASSERT((!src1 || !src1_needs_grads) && "backward pass for softmax mask not implemented");
  4619. } break;
  4620. case GGML_OP_ROPE: {
  4621. if (src0_needs_grads) {
  4622. //const int n_past = ((int32_t *) tensor->op_params)[0];
  4623. const int n_dims = ((const int32_t *) tensor->op_params)[1];
  4624. const int mode = ((const int32_t *) tensor->op_params)[2];
  4625. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  4626. const int n_ctx_orig = ((const int32_t *) tensor->op_params)[4];
  4627. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  4628. int sections[4] = {0, 0, 0, 0};
  4629. memcpy(&freq_base, (const float *) tensor->op_params + 5, sizeof(float));
  4630. memcpy(&freq_scale, (const float *) tensor->op_params + 6, sizeof(float));
  4631. memcpy(&ext_factor, (const float *) tensor->op_params + 7, sizeof(float));
  4632. memcpy(&attn_factor, (const float *) tensor->op_params + 8, sizeof(float));
  4633. memcpy(&beta_fast, (const float *) tensor->op_params + 9, sizeof(float));
  4634. memcpy(&beta_slow, (const float *) tensor->op_params + 10, sizeof(float));
  4635. memcpy(&sections, tensor->op_params + 11, sizeof(sections));
  4636. struct ggml_tensor * rope_back = grad->ne[2] == src1->ne[0] ?
  4637. ggml_rope_ext_back(ctx, grad, src1, src2, n_dims,
  4638. mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow) :
  4639. ggml_rope_multi_back(ctx, grad, src1, src2, n_dims, sections,
  4640. mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  4641. ggml_add_or_set(ctx, cgraph, isrc0, rope_back);
  4642. }
  4643. GGML_ASSERT((!src2 || !src2_needs_grads) && "gradients for freq factors not implemented");
  4644. } break;
  4645. case GGML_OP_IM2COL: {
  4646. if (src1_needs_grads) {
  4647. const int32_t s0 = ggml_get_op_params_i32(tensor, 0);
  4648. const int32_t s1 = ggml_get_op_params_i32(tensor, 1);
  4649. const int32_t p0 = ggml_get_op_params_i32(tensor, 2);
  4650. const int32_t p1 = ggml_get_op_params_i32(tensor, 3);
  4651. const int32_t d0 = ggml_get_op_params_i32(tensor, 4);
  4652. const int32_t d1 = ggml_get_op_params_i32(tensor, 5);
  4653. const bool is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
  4654. ggml_add_or_set(ctx, cgraph, isrc1, ggml_im2col_back(ctx, grad, src0, src1->ne, s0, s1, p0, p1, d0, d1, is_2D));
  4655. }
  4656. } break;
  4657. case GGML_OP_POOL_2D: {
  4658. if (src0_needs_grads) {
  4659. const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
  4660. const int32_t k0 = ggml_get_op_params_i32(tensor, 1);
  4661. const int32_t k1 = ggml_get_op_params_i32(tensor, 2);
  4662. const int32_t s0 = ggml_get_op_params_i32(tensor, 3);
  4663. const int32_t s1 = ggml_get_op_params_i32(tensor, 4);
  4664. const int32_t p0 = ggml_get_op_params_i32(tensor, 5);
  4665. const int32_t p1 = ggml_get_op_params_i32(tensor, 6);
  4666. ggml_add_or_set(ctx, cgraph, isrc0, ggml_pool_2d_back(ctx, grad, src0, op, k0, k1, s0, s1, p0, p1));
  4667. }
  4668. } break;
  4669. case GGML_OP_WIN_PART:
  4670. case GGML_OP_WIN_UNPART:
  4671. case GGML_OP_UNARY: {
  4672. switch (ggml_get_unary_op(tensor)) {
  4673. case GGML_UNARY_OP_ABS: {
  4674. if (src0_needs_grads) {
  4675. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_sgn(ctx, src0), grad));
  4676. }
  4677. } break;
  4678. case GGML_UNARY_OP_SGN: {
  4679. // noop
  4680. } break;
  4681. case GGML_UNARY_OP_NEG: {
  4682. if (src0_needs_grads) {
  4683. ggml_sub_or_set(ctx, cgraph, isrc0, grad);
  4684. }
  4685. } break;
  4686. case GGML_UNARY_OP_STEP: {
  4687. // noop
  4688. } break;
  4689. case GGML_UNARY_OP_RELU: {
  4690. if (src0_needs_grads) {
  4691. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_step(ctx, src0), grad));
  4692. }
  4693. } break;
  4694. case GGML_UNARY_OP_SILU: {
  4695. if (src0_needs_grads) {
  4696. ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0));
  4697. }
  4698. } break;
  4699. case GGML_UNARY_OP_EXP: {
  4700. if (src0_needs_grads) {
  4701. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad));
  4702. }
  4703. } break;
  4704. default: {
  4705. fprintf(stderr, "%s: unsupported unary op for backward pass: %s\n",
  4706. __func__, ggml_unary_op_name(ggml_get_unary_op(tensor)));
  4707. GGML_ABORT("fatal error");
  4708. } //break;
  4709. }
  4710. } break;
  4711. case GGML_OP_CROSS_ENTROPY_LOSS: {
  4712. if (src0_needs_grads) {
  4713. ggml_add_or_set(ctx, cgraph, isrc0, ggml_cross_entropy_loss_back(ctx, grad, src0, src1));
  4714. }
  4715. GGML_ASSERT(!src1_needs_grads && "backward pass for labels not implemented");
  4716. } break;
  4717. case GGML_OP_NONE: {
  4718. // noop
  4719. } break;
  4720. case GGML_OP_COUNT:
  4721. default: {
  4722. fprintf(stderr, "%s: unsupported ggml op for backward pass: %s\n", __func__, ggml_op_name(tensor->op));
  4723. GGML_ABORT("fatal error");
  4724. } //break;
  4725. }
  4726. GGML_ASSERT(!src0_needs_grads || ggml_are_same_shape(src0, cgraph->grads[isrc0]));
  4727. GGML_ASSERT(!src1_needs_grads || ggml_are_same_shape(src1, cgraph->grads[isrc1]));
  4728. GGML_ASSERT(!src2_needs_grads || ggml_are_same_shape(src2, cgraph->grads[isrc2]));
  4729. }
  4730. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  4731. // check if already visited
  4732. if (ggml_hash_insert(&cgraph->visited_hash_set, node) == GGML_HASHSET_ALREADY_EXISTS) {
  4733. return;
  4734. }
  4735. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  4736. const int k =
  4737. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
  4738. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
  4739. /* unknown order, just fall back to using i*/ i;
  4740. if (node->src[k]) {
  4741. ggml_visit_parents(cgraph, node->src[k]);
  4742. }
  4743. }
  4744. if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
  4745. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  4746. GGML_ASSERT(cgraph->n_leafs < cgraph->size);
  4747. if (strlen(node->name) == 0) {
  4748. ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
  4749. }
  4750. cgraph->leafs[cgraph->n_leafs] = node;
  4751. cgraph->n_leafs++;
  4752. } else {
  4753. GGML_ASSERT(cgraph->n_nodes < cgraph->size);
  4754. if (strlen(node->name) == 0) {
  4755. ggml_format_name(node, "node_%d", cgraph->n_nodes);
  4756. }
  4757. cgraph->nodes[cgraph->n_nodes] = node;
  4758. cgraph->n_nodes++;
  4759. }
  4760. }
  4761. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  4762. if (!expand) {
  4763. // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
  4764. ggml_graph_clear(cgraph);
  4765. }
  4766. const int n0 = cgraph->n_nodes;
  4767. ggml_visit_parents(cgraph, tensor);
  4768. const int n_new = cgraph->n_nodes - n0;
  4769. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  4770. if (n_new > 0) {
  4771. // the last added node should always be starting point
  4772. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  4773. }
  4774. }
  4775. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  4776. ggml_build_forward_impl(cgraph, tensor, true);
  4777. }
  4778. void ggml_build_backward_expand(
  4779. struct ggml_context * ctx_static,
  4780. struct ggml_context * ctx_compute,
  4781. struct ggml_cgraph * cgraph,
  4782. bool accumulate) {
  4783. GGML_ASSERT(cgraph->n_nodes > 0);
  4784. GGML_ASSERT(cgraph->grads);
  4785. GGML_ASSERT(cgraph->grad_accs);
  4786. const int n_nodes_f = cgraph->n_nodes;
  4787. memset(cgraph->grads, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4788. memset(cgraph->grad_accs, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4789. bool * grads_needed = calloc(cgraph->visited_hash_set.size, sizeof(bool));
  4790. {
  4791. bool any_params = false;
  4792. bool any_loss = false;
  4793. for (int i = 0; i < n_nodes_f; ++i) {
  4794. struct ggml_tensor * node = cgraph->nodes[i];
  4795. any_params = any_params || (node->flags & GGML_TENSOR_FLAG_PARAM);
  4796. any_loss = any_loss || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4797. }
  4798. GGML_ASSERT(any_params && "no trainable parameters found, did you forget to call ggml_set_param?");
  4799. GGML_ASSERT(any_loss && "no training loss found, did you forget to call ggml_set_loss?");
  4800. }
  4801. for (int i = 0; i < n_nodes_f; ++i) {
  4802. struct ggml_tensor * node = cgraph->nodes[i];
  4803. if (node->type == GGML_TYPE_I32) {
  4804. continue;
  4805. }
  4806. bool node_needs_grad = (node->flags & GGML_TENSOR_FLAG_PARAM) || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4807. bool ignore_src[GGML_MAX_SRC] = {false};
  4808. switch (node->op) {
  4809. // gradients in node->src[0] for one reason or another have no effect on output gradients
  4810. case GGML_OP_IM2COL: // only used for its shape
  4811. case GGML_OP_IM2COL_BACK: // same as IM2COL
  4812. ignore_src[0] = true;
  4813. break;
  4814. case GGML_OP_UNARY: {
  4815. const enum ggml_unary_op uop = ggml_get_unary_op(node);
  4816. // SGN and STEP unary ops are piecewise constant
  4817. if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
  4818. ignore_src[0] = true;
  4819. }
  4820. } break;
  4821. // gradients in node->src[1] for one reason or another have no effect on output gradients
  4822. case GGML_OP_CPY: // gradients in CPY target are irrelevant
  4823. case GGML_OP_GET_ROWS: // row indices not differentiable
  4824. case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
  4825. case GGML_OP_ROPE: // positions not differentiable
  4826. ignore_src[1] = true;
  4827. break;
  4828. default:
  4829. break;
  4830. }
  4831. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  4832. if (!node->src[j] || ignore_src[j] || !grads_needed[ggml_hash_find(&cgraph->visited_hash_set, node->src[j])]) {
  4833. continue;
  4834. }
  4835. GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
  4836. node_needs_grad = true;
  4837. break;
  4838. }
  4839. if (!node_needs_grad) {
  4840. continue;
  4841. }
  4842. // inplace operations are currently not supported
  4843. GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
  4844. node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
  4845. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  4846. GGML_ASSERT(igrad != GGML_HASHSET_FULL);
  4847. GGML_ASSERT(ggml_bitset_get(cgraph->visited_hash_set.used, igrad));
  4848. if ((accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) || (node->flags & GGML_TENSOR_FLAG_LOSS)) {
  4849. cgraph->grad_accs[igrad] = ggml_dup_tensor(ctx_static, node);
  4850. cgraph->grads[igrad] = cgraph->grad_accs[igrad];
  4851. ggml_format_name(cgraph->grad_accs[igrad], "grad acc for %s", node->name);
  4852. }
  4853. grads_needed[igrad] = true;
  4854. }
  4855. for (int i = n_nodes_f - 1; i >= 0; --i) {
  4856. // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
  4857. // use allocator to automatically make inplace operations
  4858. ggml_compute_backward(ctx_compute, cgraph, i, grads_needed);
  4859. }
  4860. free(grads_needed);
  4861. }
  4862. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  4863. void * ptr = *p;
  4864. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  4865. *p = (void *) ((char *) ptr + size);
  4866. return ptr;
  4867. }
  4868. static size_t ggml_graph_nbytes(size_t size, bool grads) {
  4869. size_t hash_size = ggml_hash_size(size * 2);
  4870. void * p = 0;
  4871. incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
  4872. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
  4873. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
  4874. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
  4875. if (grads) {
  4876. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
  4877. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grad_accs
  4878. }
  4879. incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4880. size_t nbytes = (size_t) p;
  4881. return nbytes;
  4882. }
  4883. size_t ggml_graph_overhead_custom(size_t size, bool grads) {
  4884. return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
  4885. }
  4886. size_t ggml_graph_overhead(void) {
  4887. return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
  4888. }
  4889. struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
  4890. const size_t obj_size = ggml_graph_nbytes(size, grads);
  4891. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
  4892. struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
  4893. // the size of the hash table is doubled since it needs to hold both nodes and leafs
  4894. size_t hash_size = ggml_hash_size(size * 2);
  4895. void * p = cgraph + 1;
  4896. struct ggml_tensor ** nodes_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4897. struct ggml_tensor ** leafs_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4898. struct ggml_tensor ** hash_keys_ptr = incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4899. struct ggml_tensor ** grads_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4900. struct ggml_tensor ** grad_accs_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4901. ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4902. // check that we allocated the correct amount of memory
  4903. assert(obj_size == (size_t)((char *)p - (char *)cgraph));
  4904. *cgraph = (struct ggml_cgraph) {
  4905. /*.size =*/ size,
  4906. /*.n_nodes =*/ 0,
  4907. /*.n_leafs =*/ 0,
  4908. /*.nodes =*/ nodes_ptr,
  4909. /*.grads =*/ grads_ptr,
  4910. /*.grad_accs =*/ grad_accs_ptr,
  4911. /*.leafs =*/ leafs_ptr,
  4912. /*.hash_table =*/ { hash_size, hash_used, hash_keys_ptr },
  4913. /*.order =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
  4914. };
  4915. ggml_hash_set_reset(&cgraph->visited_hash_set);
  4916. if (grads) {
  4917. memset(cgraph->grads, 0, hash_size*sizeof(struct ggml_tensor *));
  4918. memset(cgraph->grad_accs, 0, hash_size*sizeof(struct ggml_tensor *));
  4919. }
  4920. return cgraph;
  4921. }
  4922. struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
  4923. return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
  4924. }
  4925. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
  4926. struct ggml_cgraph cgraph = {
  4927. /*.size =*/ 0,
  4928. /*.n_nodes =*/ i1 - i0,
  4929. /*.n_leafs =*/ 0,
  4930. /*.nodes =*/ cgraph0->nodes + i0,
  4931. /*.grads =*/ NULL, // gradients would need visited_hash_set
  4932. /*.grad_accs =*/ NULL,
  4933. /*.leafs =*/ NULL,
  4934. /*.visited_hash_set =*/ { 0, NULL, NULL },
  4935. /*.order =*/ cgraph0->order,
  4936. };
  4937. return cgraph;
  4938. }
  4939. void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
  4940. GGML_ASSERT(dst->size >= src->n_leafs);
  4941. GGML_ASSERT(dst->size >= src->n_nodes);
  4942. GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
  4943. dst->n_leafs = src->n_leafs;
  4944. dst->n_nodes = src->n_nodes;
  4945. dst->order = src->order;
  4946. for (int i = 0; i < src->n_leafs; ++i) {
  4947. dst->leafs[i] = src->leafs[i];
  4948. }
  4949. for (int i = 0; i < src->n_nodes; ++i) {
  4950. dst->nodes[i] = src->nodes[i];
  4951. }
  4952. for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
  4953. // copy all hashset keys (tensors) that are in use
  4954. if (ggml_bitset_get(src->visited_hash_set.used, i)) {
  4955. ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
  4956. }
  4957. }
  4958. if (dst->grads) {
  4959. memset(dst->grads, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4960. memset(dst->grad_accs, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4961. }
  4962. if (src->grads) {
  4963. GGML_ASSERT(dst->grads != NULL);
  4964. GGML_ASSERT(dst->grad_accs != NULL);
  4965. for (int i = 0; i < src->n_nodes; ++i) {
  4966. const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
  4967. const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
  4968. GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
  4969. GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
  4970. GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
  4971. GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
  4972. dst->grads[igrad_dst] = src->grads[igrad_src];
  4973. dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
  4974. }
  4975. }
  4976. }
  4977. struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  4978. struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads != NULL);
  4979. ggml_graph_cpy(cgraph, result);
  4980. return result;
  4981. }
  4982. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  4983. if (ggml_is_empty(tensor)) {
  4984. return tensor;
  4985. }
  4986. if (tensor->buffer) {
  4987. ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
  4988. } else {
  4989. GGML_ASSERT(tensor->data);
  4990. memset(tensor->data, 0, ggml_nbytes(tensor));
  4991. }
  4992. return tensor;
  4993. }
  4994. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  4995. GGML_ASSERT(cgraph->grads != NULL);
  4996. for (int i = 0; i < cgraph->n_nodes; i++) {
  4997. struct ggml_tensor * node = cgraph->nodes[i];
  4998. struct ggml_tensor * grad_acc = ggml_graph_get_grad_acc(cgraph, node);
  4999. if (node->op == GGML_OP_OPT_STEP_ADAMW) {
  5000. // clear momenta
  5001. ggml_set_zero(node->src[2]);
  5002. ggml_set_zero(node->src[3]);
  5003. }
  5004. // initial gradients of loss should be 1, 0 otherwise
  5005. if (grad_acc) {
  5006. if (node->flags & GGML_TENSOR_FLAG_LOSS) {
  5007. GGML_ASSERT(grad_acc->type == GGML_TYPE_F32);
  5008. GGML_ASSERT(ggml_is_scalar(grad_acc));
  5009. const float onef = 1.0f;
  5010. if (grad_acc->buffer) {
  5011. ggml_backend_tensor_set(grad_acc, &onef, 0, sizeof(float));
  5012. } else {
  5013. GGML_ASSERT(grad_acc->data);
  5014. *((float *) grad_acc->data) = onef;
  5015. }
  5016. } else {
  5017. ggml_set_zero(grad_acc);
  5018. }
  5019. }
  5020. }
  5021. }
  5022. void ggml_graph_clear(struct ggml_cgraph * cgraph) {
  5023. cgraph->n_leafs = 0;
  5024. cgraph->n_nodes = 0;
  5025. ggml_hash_set_reset(&cgraph->visited_hash_set);
  5026. }
  5027. int ggml_graph_size(struct ggml_cgraph * cgraph) {
  5028. return cgraph->size;
  5029. }
  5030. struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
  5031. if (i < 0) {
  5032. GGML_ASSERT(cgraph->n_nodes + i >= 0);
  5033. return cgraph->nodes[cgraph->n_nodes + i];
  5034. }
  5035. GGML_ASSERT(i < cgraph->n_nodes);
  5036. return cgraph->nodes[i];
  5037. }
  5038. struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
  5039. return cgraph->nodes;
  5040. }
  5041. int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
  5042. return cgraph->n_nodes;
  5043. }
  5044. void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  5045. GGML_ASSERT(cgraph->size > cgraph->n_nodes);
  5046. cgraph->nodes[cgraph->n_nodes] = tensor;
  5047. cgraph->n_nodes++;
  5048. }
  5049. struct ggml_tensor * ggml_graph_get_tensor(const struct ggml_cgraph * cgraph, const char * name) {
  5050. for (int i = 0; i < cgraph->n_leafs; i++) {
  5051. struct ggml_tensor * leaf = cgraph->leafs[i];
  5052. if (strcmp(leaf->name, name) == 0) {
  5053. return leaf;
  5054. }
  5055. }
  5056. for (int i = 0; i < cgraph->n_nodes; i++) {
  5057. struct ggml_tensor * node = cgraph->nodes[i];
  5058. if (strcmp(node->name, name) == 0) {
  5059. return node;
  5060. }
  5061. }
  5062. return NULL;
  5063. }
  5064. struct ggml_tensor * ggml_graph_get_grad(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5065. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5066. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grads ? cgraph->grads[igrad] : NULL;
  5067. }
  5068. struct ggml_tensor * ggml_graph_get_grad_acc(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5069. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5070. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grad_accs ? cgraph->grad_accs[igrad] : NULL;
  5071. }
  5072. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  5073. GGML_LOG_INFO("=== GRAPH ===\n");
  5074. GGML_LOG_INFO("n_nodes = %d\n", cgraph->n_nodes);
  5075. for (int i = 0; i < cgraph->n_nodes; i++) {
  5076. struct ggml_tensor * node = cgraph->nodes[i];
  5077. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
  5078. i,
  5079. node->ne[0], node->ne[1], node->ne[2],
  5080. ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" :
  5081. ggml_graph_get_grad(cgraph, node) ? "g" : " ");
  5082. }
  5083. GGML_LOG_INFO("n_leafs = %d\n", cgraph->n_leafs);
  5084. for (int i = 0; i < cgraph->n_leafs; i++) {
  5085. struct ggml_tensor * node = cgraph->leafs[i];
  5086. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
  5087. i,
  5088. node->ne[0], node->ne[1],
  5089. ggml_op_name(node->op),
  5090. ggml_get_name(node));
  5091. }
  5092. GGML_LOG_INFO("========================================\n");
  5093. }
  5094. // check if node is part of the graph
  5095. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5096. if (cgraph == NULL) {
  5097. return true;
  5098. }
  5099. for (int i = 0; i < cgraph->n_nodes; i++) {
  5100. if (cgraph->nodes[i] == node) {
  5101. return true;
  5102. }
  5103. }
  5104. return false;
  5105. }
  5106. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5107. for (int i = 0; i < cgraph->n_nodes; i++) {
  5108. struct ggml_tensor * parent = cgraph->nodes[i];
  5109. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, parent);
  5110. if (grad == node) {
  5111. return parent;
  5112. }
  5113. }
  5114. return NULL;
  5115. }
  5116. 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) {
  5117. struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
  5118. struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
  5119. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
  5120. gparent0 ? (void *) gparent0 : (void *) parent,
  5121. gparent0 ? "g" : "x",
  5122. gparent ? (void *) gparent : (void *) node,
  5123. gparent ? "g" : "x",
  5124. gparent ? "empty" : "vee",
  5125. gparent ? "dashed" : "solid",
  5126. label);
  5127. }
  5128. static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  5129. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"%s\"; ]\n",
  5130. (void *) parent, "x",
  5131. (void *) node, "x",
  5132. label);
  5133. }
  5134. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  5135. char color[16];
  5136. FILE * fp = ggml_fopen(filename, "w");
  5137. GGML_ASSERT(fp);
  5138. fprintf(fp, "digraph G {\n");
  5139. fprintf(fp, " newrank = true;\n");
  5140. fprintf(fp, " rankdir = TB;\n");
  5141. for (int i = 0; i < gb->n_nodes; i++) {
  5142. struct ggml_tensor * node = gb->nodes[i];
  5143. struct ggml_tensor * grad = ggml_graph_get_grad(gb, node);
  5144. if (ggml_graph_get_parent(gb, node) != NULL) {
  5145. continue;
  5146. }
  5147. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  5148. snprintf(color, sizeof(color), "yellow");
  5149. } else if (grad) {
  5150. if (ggml_graph_find(gf, node)) {
  5151. snprintf(color, sizeof(color), "green");
  5152. } else {
  5153. snprintf(color, sizeof(color), "lightblue");
  5154. }
  5155. } else {
  5156. snprintf(color, sizeof(color), "white");
  5157. }
  5158. fprintf(fp, " \"%p\" [ "
  5159. "style = filled; fillcolor = %s; shape = record; "
  5160. "label=\"",
  5161. (void *) node, color);
  5162. if (strlen(node->name) > 0) {
  5163. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5164. } else {
  5165. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5166. }
  5167. if (ggml_is_matrix(node)) {
  5168. fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
  5169. } else {
  5170. fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
  5171. }
  5172. if (grad) {
  5173. fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(grad->op));
  5174. } else {
  5175. fprintf(fp, "\"; ]\n");
  5176. }
  5177. }
  5178. for (int i = 0; i < gb->n_leafs; i++) {
  5179. struct ggml_tensor * node = gb->leafs[i];
  5180. snprintf(color, sizeof(color), "pink");
  5181. fprintf(fp, " \"%p\" [ "
  5182. "style = filled; fillcolor = %s; shape = record; "
  5183. "label=\"<x>",
  5184. (void *) node, color);
  5185. if (strlen(node->name) > 0) {
  5186. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5187. } else {
  5188. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5189. }
  5190. fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
  5191. if (ggml_nelements(node) < 5 && node->data != NULL) {
  5192. fprintf(fp, " | (");
  5193. for (int j = 0; j < ggml_nelements(node); j++) {
  5194. // FIXME: use ggml-backend to obtain the tensor data
  5195. //if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
  5196. // fprintf(fp, "%d", ggml_get_i32_1d(node, j));
  5197. //}
  5198. //else if (node->type == GGML_TYPE_F32 ||
  5199. // node->type == GGML_TYPE_F16 ||
  5200. // node->type == GGML_TYPE_BF16) {
  5201. // fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
  5202. //}
  5203. //else
  5204. {
  5205. fprintf(fp, "#");
  5206. }
  5207. if (j < ggml_nelements(node) - 1) {
  5208. fprintf(fp, ", ");
  5209. }
  5210. }
  5211. fprintf(fp, ")");
  5212. }
  5213. fprintf(fp, "\"; ]\n");
  5214. }
  5215. for (int i = 0; i < gb->n_nodes; i++) {
  5216. struct ggml_tensor * node = gb->nodes[i];
  5217. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5218. if (node->src[j]) {
  5219. char label[16];
  5220. snprintf(label, sizeof(label), "src %d", j);
  5221. ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
  5222. }
  5223. }
  5224. }
  5225. for (int i = 0; i < gb->n_leafs; i++) {
  5226. struct ggml_tensor * node = gb->leafs[i];
  5227. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5228. if (node->src[j]) {
  5229. char label[16];
  5230. snprintf(label, sizeof(label), "src %d", j);
  5231. ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
  5232. }
  5233. }
  5234. }
  5235. fprintf(fp, "}\n");
  5236. fclose(fp);
  5237. GGML_LOG_INFO("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  5238. }
  5239. ////////////////////////////////////////////////////////////////////////////////
  5240. void ggml_set_input(struct ggml_tensor * tensor) {
  5241. tensor->flags |= GGML_TENSOR_FLAG_INPUT;
  5242. }
  5243. void ggml_set_output(struct ggml_tensor * tensor) {
  5244. tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
  5245. }
  5246. void ggml_set_param(struct ggml_context * ctx, struct ggml_tensor * tensor) {
  5247. GGML_UNUSED(ctx); // TODO: remove this parameter
  5248. tensor->flags |= GGML_TENSOR_FLAG_PARAM;
  5249. }
  5250. void ggml_set_loss(struct ggml_tensor * tensor) {
  5251. GGML_ASSERT(ggml_is_scalar(tensor));
  5252. GGML_ASSERT(tensor->type == GGML_TYPE_F32);
  5253. tensor->flags |= GGML_TENSOR_FLAG_LOSS;
  5254. }
  5255. ////////////////////////////////////////////////////////////////////////////////
  5256. void ggml_quantize_init(enum ggml_type type) {
  5257. ggml_critical_section_start();
  5258. switch (type) {
  5259. case GGML_TYPE_IQ2_XXS:
  5260. case GGML_TYPE_IQ2_XS:
  5261. case GGML_TYPE_IQ2_S:
  5262. case GGML_TYPE_IQ1_S:
  5263. case GGML_TYPE_IQ1_M: iq2xs_init_impl(type); break;
  5264. case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
  5265. case GGML_TYPE_IQ3_S: iq3xs_init_impl(512); break;
  5266. default: // nothing
  5267. break;
  5268. }
  5269. ggml_critical_section_end();
  5270. }
  5271. void ggml_quantize_free(void) {
  5272. ggml_critical_section_start();
  5273. iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
  5274. iq2xs_free_impl(GGML_TYPE_IQ2_XS);
  5275. iq2xs_free_impl(GGML_TYPE_IQ1_S);
  5276. iq3xs_free_impl(256);
  5277. ggml_critical_section_end();
  5278. }
  5279. bool ggml_quantize_requires_imatrix(enum ggml_type type) {
  5280. return
  5281. type == GGML_TYPE_IQ2_XXS ||
  5282. type == GGML_TYPE_IQ2_XS ||
  5283. type == GGML_TYPE_IQ1_S;// ||
  5284. //type == GGML_TYPE_IQ1_M;
  5285. }
  5286. size_t ggml_quantize_chunk(
  5287. enum ggml_type type,
  5288. const float * src,
  5289. void * dst,
  5290. int64_t start,
  5291. int64_t nrows,
  5292. int64_t n_per_row,
  5293. const float * imatrix) {
  5294. const int64_t n = (int64_t) nrows * n_per_row;
  5295. if (ggml_quantize_requires_imatrix(type)) {
  5296. GGML_ASSERT(imatrix != NULL);
  5297. }
  5298. GGML_ASSERT(start % type_traits[type].blck_size == 0);
  5299. GGML_ASSERT(start % n_per_row == 0);
  5300. ggml_quantize_init(type); // this is noop if already initialized
  5301. const size_t start_row = start / n_per_row;
  5302. const size_t row_size = ggml_row_size(type, n_per_row);
  5303. size_t result = 0;
  5304. switch (type) {
  5305. case GGML_TYPE_Q4_0: result = quantize_q4_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5306. case GGML_TYPE_Q4_1: result = quantize_q4_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5307. case GGML_TYPE_Q5_0: result = quantize_q5_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5308. case GGML_TYPE_Q5_1: result = quantize_q5_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5309. case GGML_TYPE_Q8_0: result = quantize_q8_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5310. case GGML_TYPE_Q2_K: result = quantize_q2_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5311. case GGML_TYPE_Q3_K: result = quantize_q3_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5312. case GGML_TYPE_Q4_K: result = quantize_q4_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5313. case GGML_TYPE_Q5_K: result = quantize_q5_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5314. case GGML_TYPE_Q6_K: result = quantize_q6_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5315. case GGML_TYPE_TQ1_0: result = quantize_tq1_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5316. case GGML_TYPE_TQ2_0: result = quantize_tq2_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5317. case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5318. case GGML_TYPE_IQ2_XS: result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5319. case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5320. case GGML_TYPE_IQ3_S: result = quantize_iq3_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5321. case GGML_TYPE_IQ2_S: result = quantize_iq2_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5322. case GGML_TYPE_IQ1_S: result = quantize_iq1_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5323. case GGML_TYPE_IQ1_M: result = quantize_iq1_m (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5324. case GGML_TYPE_IQ4_NL: result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5325. case GGML_TYPE_IQ4_XS: result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5326. case GGML_TYPE_F16:
  5327. {
  5328. size_t elemsize = sizeof(ggml_fp16_t);
  5329. ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
  5330. result = n * elemsize;
  5331. } break;
  5332. case GGML_TYPE_BF16:
  5333. {
  5334. size_t elemsize = sizeof(ggml_bf16_t);
  5335. ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
  5336. result = n * elemsize;
  5337. } break;
  5338. case GGML_TYPE_F32:
  5339. {
  5340. size_t elemsize = sizeof(float);
  5341. result = n * elemsize;
  5342. memcpy((uint8_t *)dst + start * elemsize, src + start, result);
  5343. } break;
  5344. default:
  5345. assert(false);
  5346. }
  5347. GGML_ASSERT(result == nrows * row_size);
  5348. return result;
  5349. }
  5350. ////////////////////////////////////////////////////////////////////////////////
  5351. void ggml_log_set(ggml_log_callback log_callback, void * user_data) {
  5352. g_logger_state.log_callback = log_callback ? log_callback : ggml_log_callback_default;
  5353. g_logger_state.log_callback_user_data = user_data;
  5354. }
  5355. void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
  5356. p->n_threads = n_threads;
  5357. p->prio = 0; // default priority (usually means normal or inherited)
  5358. p->poll = 50; // hybrid-polling enabled
  5359. p->strict_cpu = false; // no strict placement (all threads share same cpumask)
  5360. p->paused = false; // threads are ready to go
  5361. memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
  5362. }
  5363. struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
  5364. struct ggml_threadpool_params p;
  5365. ggml_threadpool_params_init(&p, n_threads);
  5366. return p;
  5367. }
  5368. bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
  5369. if (p0->n_threads != p1->n_threads ) return false;
  5370. if (p0->prio != p1->prio ) return false;
  5371. if (p0->poll != p1->poll ) return false;
  5372. if (p0->strict_cpu != p1->strict_cpu ) return false;
  5373. return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
  5374. }