ggml.c 244 KB

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