ggml.c 245 KB

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