ggml.c 204 KB

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