ggml.c 207 KB

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