ggml.c 219 KB

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