ggml.c 207 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605
  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. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1038. if (tensor->ne[i] <= 0) {
  1039. return 0;
  1040. }
  1041. }
  1042. size_t nbytes;
  1043. const size_t blck_size = ggml_blck_size(tensor->type);
  1044. if (blck_size == 1) {
  1045. nbytes = ggml_type_size(tensor->type);
  1046. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1047. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  1048. }
  1049. }
  1050. else {
  1051. nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
  1052. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  1053. nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
  1054. }
  1055. }
  1056. return nbytes;
  1057. }
  1058. size_t ggml_nbytes_pad(const struct ggml_tensor * tensor) {
  1059. return GGML_PAD(ggml_nbytes(tensor), GGML_MEM_ALIGN);
  1060. }
  1061. int64_t ggml_blck_size(enum ggml_type type) {
  1062. return type_traits[type].blck_size;
  1063. }
  1064. size_t ggml_type_size(enum ggml_type type) {
  1065. return type_traits[type].type_size;
  1066. }
  1067. size_t ggml_row_size(enum ggml_type type, int64_t ne) {
  1068. assert(ne % ggml_blck_size(type) == 0);
  1069. return ggml_type_size(type)*ne/ggml_blck_size(type);
  1070. }
  1071. double ggml_type_sizef(enum ggml_type type) {
  1072. return ((double)(type_traits[type].type_size))/type_traits[type].blck_size;
  1073. }
  1074. const char * ggml_type_name(enum ggml_type type) {
  1075. return type < GGML_TYPE_COUNT ? type_traits[type].type_name : "NONE";
  1076. }
  1077. bool ggml_is_quantized(enum ggml_type type) {
  1078. return type_traits[type].is_quantized;
  1079. }
  1080. const char * ggml_op_name(enum ggml_op op) {
  1081. return GGML_OP_NAME[op];
  1082. }
  1083. const char * ggml_op_symbol(enum ggml_op op) {
  1084. return GGML_OP_SYMBOL[op];
  1085. }
  1086. const char * ggml_unary_op_name(enum ggml_unary_op op) {
  1087. return GGML_UNARY_OP_NAME[op];
  1088. }
  1089. const char * ggml_op_desc(const struct ggml_tensor * t) {
  1090. if (t->op == GGML_OP_UNARY) {
  1091. enum ggml_unary_op uop = ggml_get_unary_op(t);
  1092. return ggml_unary_op_name(uop);
  1093. }
  1094. return ggml_op_name(t->op);
  1095. }
  1096. size_t ggml_element_size(const struct ggml_tensor * tensor) {
  1097. return ggml_type_size(tensor->type);
  1098. }
  1099. bool ggml_is_scalar(const struct ggml_tensor * tensor) {
  1100. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1101. return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1102. }
  1103. bool ggml_is_vector(const struct ggml_tensor * tensor) {
  1104. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1105. return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1106. }
  1107. bool ggml_is_matrix(const struct ggml_tensor * tensor) {
  1108. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1109. return tensor->ne[2] == 1 && tensor->ne[3] == 1;
  1110. }
  1111. bool ggml_is_3d(const struct ggml_tensor * tensor) {
  1112. return tensor->ne[3] == 1;
  1113. }
  1114. int ggml_n_dims(const struct ggml_tensor * tensor) {
  1115. for (int i = GGML_MAX_DIMS - 1; i >= 1; --i) {
  1116. if (tensor->ne[i] > 1) {
  1117. return i + 1;
  1118. }
  1119. }
  1120. return 1;
  1121. }
  1122. enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype) {
  1123. enum ggml_type wtype = GGML_TYPE_COUNT;
  1124. switch (ftype) {
  1125. case GGML_FTYPE_ALL_F32: wtype = GGML_TYPE_F32; break;
  1126. case GGML_FTYPE_MOSTLY_F16: wtype = GGML_TYPE_F16; break;
  1127. case GGML_FTYPE_MOSTLY_BF16: wtype = GGML_TYPE_BF16; break;
  1128. case GGML_FTYPE_MOSTLY_Q4_0: wtype = GGML_TYPE_Q4_0; break;
  1129. case GGML_FTYPE_MOSTLY_Q4_1: wtype = GGML_TYPE_Q4_1; break;
  1130. case GGML_FTYPE_MOSTLY_Q5_0: wtype = GGML_TYPE_Q5_0; break;
  1131. case GGML_FTYPE_MOSTLY_Q5_1: wtype = GGML_TYPE_Q5_1; break;
  1132. case GGML_FTYPE_MOSTLY_Q8_0: wtype = GGML_TYPE_Q8_0; break;
  1133. case GGML_FTYPE_MOSTLY_Q2_K: wtype = GGML_TYPE_Q2_K; break;
  1134. case GGML_FTYPE_MOSTLY_Q3_K: wtype = GGML_TYPE_Q3_K; break;
  1135. case GGML_FTYPE_MOSTLY_Q4_K: wtype = GGML_TYPE_Q4_K; break;
  1136. case GGML_FTYPE_MOSTLY_Q5_K: wtype = GGML_TYPE_Q5_K; break;
  1137. case GGML_FTYPE_MOSTLY_Q6_K: wtype = GGML_TYPE_Q6_K; break;
  1138. case GGML_FTYPE_MOSTLY_IQ2_XXS: wtype = GGML_TYPE_IQ2_XXS; break;
  1139. case GGML_FTYPE_MOSTLY_IQ2_XS: wtype = GGML_TYPE_IQ2_XS; break;
  1140. case GGML_FTYPE_MOSTLY_IQ3_XXS: wtype = GGML_TYPE_IQ3_XXS; break;
  1141. case GGML_FTYPE_MOSTLY_IQ1_S: wtype = GGML_TYPE_IQ1_S; break;
  1142. case GGML_FTYPE_MOSTLY_IQ1_M: wtype = GGML_TYPE_IQ1_M; break;
  1143. case GGML_FTYPE_MOSTLY_IQ4_NL: wtype = GGML_TYPE_IQ4_NL; break;
  1144. case GGML_FTYPE_MOSTLY_IQ4_XS: wtype = GGML_TYPE_IQ4_XS; break;
  1145. case GGML_FTYPE_MOSTLY_IQ3_S: wtype = GGML_TYPE_IQ3_S; break;
  1146. case GGML_FTYPE_MOSTLY_IQ2_S: wtype = GGML_TYPE_IQ2_S; break;
  1147. case GGML_FTYPE_UNKNOWN: wtype = GGML_TYPE_COUNT; break;
  1148. case GGML_FTYPE_MOSTLY_Q4_1_SOME_F16: wtype = GGML_TYPE_COUNT; break;
  1149. }
  1150. GGML_ASSERT(wtype != GGML_TYPE_COUNT);
  1151. return wtype;
  1152. }
  1153. size_t ggml_tensor_overhead(void) {
  1154. return GGML_OBJECT_SIZE + GGML_TENSOR_SIZE;
  1155. }
  1156. bool ggml_is_transposed(const struct ggml_tensor * tensor) {
  1157. return tensor->nb[0] > tensor->nb[1];
  1158. }
  1159. static bool ggml_is_contiguous_n(const struct ggml_tensor * tensor, int n) {
  1160. size_t next_nb = ggml_type_size(tensor->type);
  1161. if (tensor->ne[0] != ggml_blck_size(tensor->type) && tensor->nb[0] != next_nb) {
  1162. return false;
  1163. }
  1164. next_nb *= tensor->ne[0]/ggml_blck_size(tensor->type);
  1165. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1166. if (tensor->ne[i] != 1) {
  1167. if (i > n) {
  1168. if (tensor->nb[i] != next_nb) {
  1169. return false;
  1170. }
  1171. next_nb *= tensor->ne[i];
  1172. } else {
  1173. // this dimension does not need to be contiguous
  1174. next_nb = tensor->ne[i]*tensor->nb[i];
  1175. }
  1176. }
  1177. }
  1178. return true;
  1179. }
  1180. bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
  1181. return ggml_is_contiguous_0(tensor);
  1182. }
  1183. bool ggml_is_contiguous_0(const struct ggml_tensor * tensor) {
  1184. return ggml_is_contiguous_n(tensor, 0);
  1185. }
  1186. bool ggml_is_contiguous_1(const struct ggml_tensor * tensor) {
  1187. return ggml_is_contiguous_n(tensor, 1);
  1188. }
  1189. bool ggml_is_contiguous_2(const struct ggml_tensor * tensor) {
  1190. return ggml_is_contiguous_n(tensor, 2);
  1191. }
  1192. bool ggml_is_permuted(const struct ggml_tensor * tensor) {
  1193. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1194. return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
  1195. }
  1196. static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
  1197. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1198. return
  1199. tensor->nb[0] == ggml_type_size(tensor->type) &&
  1200. tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
  1201. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1202. }
  1203. bool ggml_is_empty(const struct ggml_tensor * tensor) {
  1204. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  1205. if (tensor->ne[i] == 0) {
  1206. // empty if any dimension has no elements
  1207. return true;
  1208. }
  1209. }
  1210. return false;
  1211. }
  1212. bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1213. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1214. return
  1215. (t0->ne[0] == t1->ne[0]) &&
  1216. (t0->ne[1] == t1->ne[1]) &&
  1217. (t0->ne[2] == t1->ne[2]) &&
  1218. (t0->ne[3] == t1->ne[3]);
  1219. }
  1220. bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1221. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1222. return
  1223. (t0->nb[0] == t1->nb[0]) &&
  1224. (t0->nb[1] == t1->nb[1]) &&
  1225. (t0->nb[2] == t1->nb[2]) &&
  1226. (t0->nb[3] == t1->nb[3]);
  1227. }
  1228. // check if t1 can be represented as a repetition of t0
  1229. bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1230. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1231. return ggml_is_empty(t0) ? ggml_is_empty(t1) :
  1232. (t1->ne[0]%t0->ne[0] == 0) &&
  1233. (t1->ne[1]%t0->ne[1] == 0) &&
  1234. (t1->ne[2]%t0->ne[2] == 0) &&
  1235. (t1->ne[3]%t0->ne[3] == 0);
  1236. }
  1237. static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  1238. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  1239. return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
  1240. }
  1241. // assert that pointer is aligned to GGML_MEM_ALIGN
  1242. #define GGML_ASSERT_ALIGNED(ptr) \
  1243. GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
  1244. ////////////////////////////////////////////////////////////////////////////////
  1245. struct ggml_context * ggml_init(struct ggml_init_params params) {
  1246. static bool is_first_call = true;
  1247. ggml_critical_section_start();
  1248. if (is_first_call) {
  1249. // initialize time system (required on Windows)
  1250. ggml_time_init();
  1251. for (int i = 0; i < (1 << 16); ++i) {
  1252. union {
  1253. uint16_t u16;
  1254. ggml_fp16_t fp16;
  1255. } u = {i};
  1256. ggml_table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(u.fp16);
  1257. }
  1258. is_first_call = false;
  1259. }
  1260. ggml_critical_section_end();
  1261. struct ggml_context * ctx = GGML_MALLOC(sizeof(struct ggml_context));
  1262. // allow to call ggml_init with 0 size
  1263. if (params.mem_size == 0) {
  1264. params.mem_size = GGML_MEM_ALIGN;
  1265. }
  1266. const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
  1267. *ctx = (struct ggml_context) {
  1268. /*.mem_size =*/ mem_size,
  1269. /*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : ggml_aligned_malloc(mem_size),
  1270. /*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
  1271. /*.no_alloc =*/ params.no_alloc,
  1272. /*.n_objects =*/ 0,
  1273. /*.objects_begin =*/ NULL,
  1274. /*.objects_end =*/ NULL,
  1275. };
  1276. GGML_ASSERT(ctx->mem_buffer != NULL);
  1277. GGML_ASSERT_ALIGNED(ctx->mem_buffer);
  1278. GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
  1279. return ctx;
  1280. }
  1281. void ggml_reset(struct ggml_context * ctx) {
  1282. if (ctx == NULL) {
  1283. return;
  1284. }
  1285. ctx->n_objects = 0;
  1286. ctx->objects_begin = NULL;
  1287. ctx->objects_end = NULL;
  1288. }
  1289. void ggml_free(struct ggml_context * ctx) {
  1290. if (ctx == NULL) {
  1291. return;
  1292. }
  1293. if (ctx->mem_buffer_owned) {
  1294. ggml_aligned_free(ctx->mem_buffer, ctx->mem_size);
  1295. }
  1296. GGML_FREE(ctx);
  1297. }
  1298. size_t ggml_used_mem(const struct ggml_context * ctx) {
  1299. return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
  1300. }
  1301. bool ggml_get_no_alloc(struct ggml_context * ctx) {
  1302. return ctx->no_alloc;
  1303. }
  1304. void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
  1305. ctx->no_alloc = no_alloc;
  1306. }
  1307. void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
  1308. return ctx->mem_buffer;
  1309. }
  1310. size_t ggml_get_mem_size(const struct ggml_context * ctx) {
  1311. return ctx->mem_size;
  1312. }
  1313. size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
  1314. size_t max_size = 0;
  1315. for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
  1316. size_t bytes = ggml_nbytes(tensor);
  1317. max_size = MAX(max_size, bytes);
  1318. }
  1319. return max_size;
  1320. }
  1321. ////////////////////////////////////////////////////////////////////////////////
  1322. static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
  1323. // always insert objects at the end of the context's memory pool
  1324. struct ggml_object * obj_cur = ctx->objects_end;
  1325. const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
  1326. const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
  1327. const size_t cur_end = cur_offs + cur_size;
  1328. // align to GGML_MEM_ALIGN
  1329. size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
  1330. char * const mem_buffer = ctx->mem_buffer;
  1331. struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
  1332. if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
  1333. GGML_LOG_WARN("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
  1334. __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
  1335. #ifndef NDEBUG
  1336. GGML_ABORT("not enough space in the context's memory pool");
  1337. #endif
  1338. return NULL;
  1339. }
  1340. *obj_new = (struct ggml_object) {
  1341. .offs = cur_end + GGML_OBJECT_SIZE,
  1342. .size = size_needed,
  1343. .next = NULL,
  1344. .type = type,
  1345. };
  1346. GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
  1347. if (obj_cur != NULL) {
  1348. obj_cur->next = obj_new;
  1349. } else {
  1350. // this is the first object in this context
  1351. ctx->objects_begin = obj_new;
  1352. }
  1353. ctx->objects_end = obj_new;
  1354. //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
  1355. return obj_new;
  1356. }
  1357. static struct ggml_tensor * ggml_new_tensor_impl(
  1358. struct ggml_context * ctx,
  1359. enum ggml_type type,
  1360. int n_dims,
  1361. const int64_t * ne,
  1362. struct ggml_tensor * view_src,
  1363. size_t view_offs) {
  1364. GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
  1365. GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
  1366. // find the base tensor and absolute offset
  1367. if (view_src != NULL && view_src->view_src != NULL) {
  1368. view_offs += view_src->view_offs;
  1369. view_src = view_src->view_src;
  1370. }
  1371. size_t data_size = ggml_row_size(type, ne[0]);
  1372. for (int i = 1; i < n_dims; i++) {
  1373. data_size *= ne[i];
  1374. }
  1375. GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
  1376. void * data = view_src != NULL ? view_src->data : NULL;
  1377. if (data != NULL) {
  1378. data = (char *) data + view_offs;
  1379. }
  1380. size_t obj_alloc_size = 0;
  1381. if (view_src == NULL && !ctx->no_alloc) {
  1382. // allocate tensor data in the context's memory pool
  1383. obj_alloc_size = data_size;
  1384. }
  1385. struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
  1386. GGML_ASSERT(obj_new);
  1387. struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
  1388. *result = (struct ggml_tensor) {
  1389. /*.type =*/ type,
  1390. /*.buffer =*/ NULL,
  1391. /*.ne =*/ { 1, 1, 1, 1 },
  1392. /*.nb =*/ { 0, 0, 0, 0 },
  1393. /*.op =*/ GGML_OP_NONE,
  1394. /*.op_params =*/ { 0 },
  1395. /*.flags =*/ 0,
  1396. /*.src =*/ { NULL },
  1397. /*.view_src =*/ view_src,
  1398. /*.view_offs =*/ view_offs,
  1399. /*.data =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
  1400. /*.name =*/ { 0 },
  1401. /*.extra =*/ NULL,
  1402. /*.padding =*/ { 0 },
  1403. };
  1404. // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
  1405. //GGML_ASSERT_ALIGNED(result->data);
  1406. for (int i = 0; i < n_dims; i++) {
  1407. result->ne[i] = ne[i];
  1408. }
  1409. result->nb[0] = ggml_type_size(type);
  1410. result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
  1411. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  1412. result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
  1413. }
  1414. ctx->n_objects++;
  1415. return result;
  1416. }
  1417. struct ggml_tensor * ggml_new_tensor(
  1418. struct ggml_context * ctx,
  1419. enum ggml_type type,
  1420. int n_dims,
  1421. const int64_t * ne) {
  1422. return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
  1423. }
  1424. struct ggml_tensor * ggml_new_tensor_1d(
  1425. struct ggml_context * ctx,
  1426. enum ggml_type type,
  1427. int64_t ne0) {
  1428. return ggml_new_tensor(ctx, type, 1, &ne0);
  1429. }
  1430. struct ggml_tensor * ggml_new_tensor_2d(
  1431. struct ggml_context * ctx,
  1432. enum ggml_type type,
  1433. int64_t ne0,
  1434. int64_t ne1) {
  1435. const int64_t ne[2] = { ne0, ne1 };
  1436. return ggml_new_tensor(ctx, type, 2, ne);
  1437. }
  1438. struct ggml_tensor * ggml_new_tensor_3d(
  1439. struct ggml_context * ctx,
  1440. enum ggml_type type,
  1441. int64_t ne0,
  1442. int64_t ne1,
  1443. int64_t ne2) {
  1444. const int64_t ne[3] = { ne0, ne1, ne2 };
  1445. return ggml_new_tensor(ctx, type, 3, ne);
  1446. }
  1447. struct ggml_tensor * ggml_new_tensor_4d(
  1448. struct ggml_context * ctx,
  1449. enum ggml_type type,
  1450. int64_t ne0,
  1451. int64_t ne1,
  1452. int64_t ne2,
  1453. int64_t ne3) {
  1454. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  1455. return ggml_new_tensor(ctx, type, 4, ne);
  1456. }
  1457. void * ggml_new_buffer(struct ggml_context * ctx, size_t nbytes) {
  1458. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, nbytes);
  1459. return (uint8_t *)ctx->mem_buffer + obj->offs;
  1460. }
  1461. struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
  1462. return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
  1463. }
  1464. void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
  1465. const int64_t ne2 = tensor->ne[2];
  1466. const int64_t ne1 = tensor->ne[1];
  1467. const int64_t ne0 = tensor->ne[0];
  1468. const int64_t i3_ = (i/(ne2*ne1*ne0));
  1469. const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
  1470. const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
  1471. const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
  1472. if (i0) {
  1473. * i0 = i0_;
  1474. }
  1475. if (i1) {
  1476. * i1 = i1_;
  1477. }
  1478. if (i2) {
  1479. * i2 = i2_;
  1480. }
  1481. if (i3) {
  1482. * i3 = i3_;
  1483. }
  1484. }
  1485. void * ggml_get_data(const struct ggml_tensor * tensor) {
  1486. return tensor->data;
  1487. }
  1488. float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
  1489. assert(tensor->type == GGML_TYPE_F32);
  1490. return (float *)(tensor->data);
  1491. }
  1492. enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
  1493. GGML_ASSERT(tensor->op == GGML_OP_UNARY);
  1494. return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
  1495. }
  1496. const char * ggml_get_name(const struct ggml_tensor * tensor) {
  1497. return tensor->name;
  1498. }
  1499. struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
  1500. size_t i;
  1501. for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
  1502. tensor->name[i] = name[i];
  1503. }
  1504. tensor->name[i] = '\0';
  1505. return tensor;
  1506. }
  1507. struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
  1508. va_list args;
  1509. va_start(args, fmt);
  1510. vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
  1511. va_end(args);
  1512. return tensor;
  1513. }
  1514. struct ggml_tensor * ggml_view_tensor(
  1515. struct ggml_context * ctx,
  1516. struct ggml_tensor * src) {
  1517. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
  1518. ggml_format_name(result, "%s (view)", src->name);
  1519. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  1520. result->nb[i] = src->nb[i];
  1521. }
  1522. return result;
  1523. }
  1524. struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
  1525. struct ggml_object * obj = ctx->objects_begin;
  1526. char * const mem_buffer = ctx->mem_buffer;
  1527. while (obj != NULL) {
  1528. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1529. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1530. }
  1531. obj = obj->next;
  1532. }
  1533. return NULL;
  1534. }
  1535. struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
  1536. struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
  1537. obj = obj->next;
  1538. char * const mem_buffer = ctx->mem_buffer;
  1539. while (obj != NULL) {
  1540. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1541. return (struct ggml_tensor *)(mem_buffer + obj->offs);
  1542. }
  1543. obj = obj->next;
  1544. }
  1545. return NULL;
  1546. }
  1547. struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
  1548. struct ggml_object * obj = ctx->objects_begin;
  1549. char * const mem_buffer = ctx->mem_buffer;
  1550. while (obj != NULL) {
  1551. if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
  1552. struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
  1553. if (strcmp(cur->name, name) == 0) {
  1554. return cur;
  1555. }
  1556. }
  1557. obj = obj->next;
  1558. }
  1559. return NULL;
  1560. }
  1561. ////////////////////////////////////////////////////////////////////////////////
  1562. // ggml_dup
  1563. static struct ggml_tensor * ggml_dup_impl(
  1564. struct ggml_context * ctx,
  1565. struct ggml_tensor * a,
  1566. bool inplace) {
  1567. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1568. result->op = GGML_OP_DUP;
  1569. result->src[0] = a;
  1570. return result;
  1571. }
  1572. struct ggml_tensor * ggml_dup(
  1573. struct ggml_context * ctx,
  1574. struct ggml_tensor * a) {
  1575. return ggml_dup_impl(ctx, a, false);
  1576. }
  1577. struct ggml_tensor * ggml_dup_inplace(
  1578. struct ggml_context * ctx,
  1579. struct ggml_tensor * a) {
  1580. return ggml_dup_impl(ctx, a, true);
  1581. }
  1582. // ggml_add
  1583. static struct ggml_tensor * ggml_add_impl(
  1584. struct ggml_context * ctx,
  1585. struct ggml_tensor * a,
  1586. struct ggml_tensor * b,
  1587. bool inplace) {
  1588. GGML_ASSERT(ggml_can_repeat(b, a));
  1589. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1590. result->op = GGML_OP_ADD;
  1591. result->src[0] = a;
  1592. result->src[1] = b;
  1593. return result;
  1594. }
  1595. struct ggml_tensor * ggml_add(
  1596. struct ggml_context * ctx,
  1597. struct ggml_tensor * a,
  1598. struct ggml_tensor * b) {
  1599. return ggml_add_impl(ctx, a, b, false);
  1600. }
  1601. struct ggml_tensor * ggml_add_inplace(
  1602. struct ggml_context * ctx,
  1603. struct ggml_tensor * a,
  1604. struct ggml_tensor * b) {
  1605. return ggml_add_impl(ctx, a, b, true);
  1606. }
  1607. // ggml_add_cast
  1608. static struct ggml_tensor * ggml_add_cast_impl(
  1609. struct ggml_context * ctx,
  1610. struct ggml_tensor * a,
  1611. struct ggml_tensor * b,
  1612. enum ggml_type type) {
  1613. // TODO: support less-strict constraint
  1614. // GGML_ASSERT(ggml_can_repeat(b, a));
  1615. GGML_ASSERT(ggml_can_repeat_rows(b, a));
  1616. // currently only supported for quantized input and f16
  1617. GGML_ASSERT(ggml_is_quantized(a->type) ||
  1618. a->type == GGML_TYPE_F16 ||
  1619. a->type == GGML_TYPE_BF16);
  1620. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  1621. result->op = GGML_OP_ADD;
  1622. result->src[0] = a;
  1623. result->src[1] = b;
  1624. return result;
  1625. }
  1626. struct ggml_tensor * ggml_add_cast(
  1627. struct ggml_context * ctx,
  1628. struct ggml_tensor * a,
  1629. struct ggml_tensor * b,
  1630. enum ggml_type type) {
  1631. return ggml_add_cast_impl(ctx, a, b, type);
  1632. }
  1633. // ggml_add1
  1634. static struct ggml_tensor * ggml_add1_impl(
  1635. struct ggml_context * ctx,
  1636. struct ggml_tensor * a,
  1637. struct ggml_tensor * b,
  1638. bool inplace) {
  1639. GGML_ASSERT(ggml_is_scalar(b));
  1640. GGML_ASSERT(ggml_is_padded_1d(a));
  1641. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1642. result->op = GGML_OP_ADD1;
  1643. result->src[0] = a;
  1644. result->src[1] = b;
  1645. return result;
  1646. }
  1647. struct ggml_tensor * ggml_add1(
  1648. struct ggml_context * ctx,
  1649. struct ggml_tensor * a,
  1650. struct ggml_tensor * b) {
  1651. return ggml_add1_impl(ctx, a, b, false);
  1652. }
  1653. struct ggml_tensor * ggml_add1_inplace(
  1654. struct ggml_context * ctx,
  1655. struct ggml_tensor * a,
  1656. struct ggml_tensor * b) {
  1657. return ggml_add1_impl(ctx, a, b, true);
  1658. }
  1659. // ggml_acc
  1660. static struct ggml_tensor * ggml_acc_impl(
  1661. struct ggml_context * ctx,
  1662. struct ggml_tensor * a,
  1663. struct ggml_tensor * b,
  1664. size_t nb1,
  1665. size_t nb2,
  1666. size_t nb3,
  1667. size_t offset,
  1668. bool inplace) {
  1669. GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
  1670. GGML_ASSERT(ggml_is_contiguous(a));
  1671. GGML_ASSERT(a->type == GGML_TYPE_F32);
  1672. GGML_ASSERT(b->type == GGML_TYPE_F32);
  1673. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1674. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  1675. ggml_set_op_params(result, params, sizeof(params));
  1676. result->op = GGML_OP_ACC;
  1677. result->src[0] = a;
  1678. result->src[1] = b;
  1679. return result;
  1680. }
  1681. struct ggml_tensor * ggml_acc(
  1682. struct ggml_context * ctx,
  1683. struct ggml_tensor * a,
  1684. struct ggml_tensor * b,
  1685. size_t nb1,
  1686. size_t nb2,
  1687. size_t nb3,
  1688. size_t offset) {
  1689. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  1690. }
  1691. struct ggml_tensor * ggml_acc_inplace(
  1692. struct ggml_context * ctx,
  1693. struct ggml_tensor * a,
  1694. struct ggml_tensor * b,
  1695. size_t nb1,
  1696. size_t nb2,
  1697. size_t nb3,
  1698. size_t offset) {
  1699. return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  1700. }
  1701. // ggml_sub
  1702. static struct ggml_tensor * ggml_sub_impl(
  1703. struct ggml_context * ctx,
  1704. struct ggml_tensor * a,
  1705. struct ggml_tensor * b,
  1706. bool inplace) {
  1707. GGML_ASSERT(ggml_can_repeat(b, a));
  1708. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1709. result->op = GGML_OP_SUB;
  1710. result->src[0] = a;
  1711. result->src[1] = b;
  1712. return result;
  1713. }
  1714. struct ggml_tensor * ggml_sub(
  1715. struct ggml_context * ctx,
  1716. struct ggml_tensor * a,
  1717. struct ggml_tensor * b) {
  1718. return ggml_sub_impl(ctx, a, b, false);
  1719. }
  1720. struct ggml_tensor * ggml_sub_inplace(
  1721. struct ggml_context * ctx,
  1722. struct ggml_tensor * a,
  1723. struct ggml_tensor * b) {
  1724. return ggml_sub_impl(ctx, a, b, true);
  1725. }
  1726. // ggml_mul
  1727. static struct ggml_tensor * ggml_mul_impl(
  1728. struct ggml_context * ctx,
  1729. struct ggml_tensor * a,
  1730. struct ggml_tensor * b,
  1731. bool inplace) {
  1732. GGML_ASSERT(ggml_can_repeat(b, a));
  1733. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1734. result->op = GGML_OP_MUL;
  1735. result->src[0] = a;
  1736. result->src[1] = b;
  1737. return result;
  1738. }
  1739. struct ggml_tensor * ggml_mul(
  1740. struct ggml_context * ctx,
  1741. struct ggml_tensor * a,
  1742. struct ggml_tensor * b) {
  1743. return ggml_mul_impl(ctx, a, b, false);
  1744. }
  1745. struct ggml_tensor * ggml_mul_inplace(
  1746. struct ggml_context * ctx,
  1747. struct ggml_tensor * a,
  1748. struct ggml_tensor * b) {
  1749. return ggml_mul_impl(ctx, a, b, true);
  1750. }
  1751. // ggml_div
  1752. static struct ggml_tensor * ggml_div_impl(
  1753. struct ggml_context * ctx,
  1754. struct ggml_tensor * a,
  1755. struct ggml_tensor * b,
  1756. bool inplace) {
  1757. GGML_ASSERT(ggml_can_repeat(b, a));
  1758. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1759. result->op = GGML_OP_DIV;
  1760. result->src[0] = a;
  1761. result->src[1] = b;
  1762. return result;
  1763. }
  1764. struct ggml_tensor * ggml_div(
  1765. struct ggml_context * ctx,
  1766. struct ggml_tensor * a,
  1767. struct ggml_tensor * b) {
  1768. return ggml_div_impl(ctx, a, b, false);
  1769. }
  1770. struct ggml_tensor * ggml_div_inplace(
  1771. struct ggml_context * ctx,
  1772. struct ggml_tensor * a,
  1773. struct ggml_tensor * b) {
  1774. return ggml_div_impl(ctx, a, b, true);
  1775. }
  1776. // ggml_sqr
  1777. static struct ggml_tensor * ggml_sqr_impl(
  1778. struct ggml_context * ctx,
  1779. struct ggml_tensor * a,
  1780. bool inplace) {
  1781. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1782. result->op = GGML_OP_SQR;
  1783. result->src[0] = a;
  1784. return result;
  1785. }
  1786. struct ggml_tensor * ggml_sqr(
  1787. struct ggml_context * ctx,
  1788. struct ggml_tensor * a) {
  1789. return ggml_sqr_impl(ctx, a, false);
  1790. }
  1791. struct ggml_tensor * ggml_sqr_inplace(
  1792. struct ggml_context * ctx,
  1793. struct ggml_tensor * a) {
  1794. return ggml_sqr_impl(ctx, a, true);
  1795. }
  1796. // ggml_sqrt
  1797. static struct ggml_tensor * ggml_sqrt_impl(
  1798. struct ggml_context * ctx,
  1799. struct ggml_tensor * a,
  1800. bool inplace) {
  1801. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1802. result->op = GGML_OP_SQRT;
  1803. result->src[0] = a;
  1804. return result;
  1805. }
  1806. struct ggml_tensor * ggml_sqrt(
  1807. struct ggml_context * ctx,
  1808. struct ggml_tensor * a) {
  1809. return ggml_sqrt_impl(ctx, a, false);
  1810. }
  1811. struct ggml_tensor * ggml_sqrt_inplace(
  1812. struct ggml_context * ctx,
  1813. struct ggml_tensor * a) {
  1814. return ggml_sqrt_impl(ctx, a, true);
  1815. }
  1816. // ggml_log
  1817. static struct ggml_tensor * ggml_log_impl(
  1818. struct ggml_context * ctx,
  1819. struct ggml_tensor * a,
  1820. bool inplace) {
  1821. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1822. result->op = GGML_OP_LOG;
  1823. result->src[0] = a;
  1824. return result;
  1825. }
  1826. struct ggml_tensor * ggml_log(
  1827. struct ggml_context * ctx,
  1828. struct ggml_tensor * a) {
  1829. return ggml_log_impl(ctx, a, false);
  1830. }
  1831. struct ggml_tensor * ggml_log_inplace(
  1832. struct ggml_context * ctx,
  1833. struct ggml_tensor * a) {
  1834. return ggml_log_impl(ctx, a, true);
  1835. }
  1836. // ggml_sin
  1837. static struct ggml_tensor * ggml_sin_impl(
  1838. struct ggml_context * ctx,
  1839. struct ggml_tensor * a,
  1840. bool inplace) {
  1841. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1842. result->op = GGML_OP_SIN;
  1843. result->src[0] = a;
  1844. return result;
  1845. }
  1846. struct ggml_tensor * ggml_sin(
  1847. struct ggml_context * ctx,
  1848. struct ggml_tensor * a) {
  1849. return ggml_sin_impl(ctx, a, false);
  1850. }
  1851. struct ggml_tensor * ggml_sin_inplace(
  1852. struct ggml_context * ctx,
  1853. struct ggml_tensor * a) {
  1854. return ggml_sin_impl(ctx, a, true);
  1855. }
  1856. // ggml_cos
  1857. static struct ggml_tensor * ggml_cos_impl(
  1858. struct ggml_context * ctx,
  1859. struct ggml_tensor * a,
  1860. bool inplace) {
  1861. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  1862. result->op = GGML_OP_COS;
  1863. result->src[0] = a;
  1864. return result;
  1865. }
  1866. struct ggml_tensor * ggml_cos(
  1867. struct ggml_context * ctx,
  1868. struct ggml_tensor * a) {
  1869. return ggml_cos_impl(ctx, a, false);
  1870. }
  1871. struct ggml_tensor * ggml_cos_inplace(
  1872. struct ggml_context * ctx,
  1873. struct ggml_tensor * a) {
  1874. return ggml_cos_impl(ctx, a, true);
  1875. }
  1876. // ggml_sum
  1877. struct ggml_tensor * ggml_sum(
  1878. struct ggml_context * ctx,
  1879. struct ggml_tensor * a) {
  1880. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  1881. result->op = GGML_OP_SUM;
  1882. result->src[0] = a;
  1883. return result;
  1884. }
  1885. // ggml_sum_rows
  1886. struct ggml_tensor * ggml_sum_rows(
  1887. struct ggml_context * ctx,
  1888. struct ggml_tensor * a) {
  1889. int64_t ne[GGML_MAX_DIMS] = { 1 };
  1890. for (int i = 1; i < GGML_MAX_DIMS; ++i) {
  1891. ne[i] = a->ne[i];
  1892. }
  1893. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1894. result->op = GGML_OP_SUM_ROWS;
  1895. result->src[0] = a;
  1896. return result;
  1897. }
  1898. // ggml_mean
  1899. struct ggml_tensor * ggml_mean(
  1900. struct ggml_context * ctx,
  1901. struct ggml_tensor * a) {
  1902. int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
  1903. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  1904. result->op = GGML_OP_MEAN;
  1905. result->src[0] = a;
  1906. return result;
  1907. }
  1908. // ggml_argmax
  1909. struct ggml_tensor * ggml_argmax(
  1910. struct ggml_context * ctx,
  1911. struct ggml_tensor * a) {
  1912. GGML_ASSERT(ggml_is_matrix(a));
  1913. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  1914. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
  1915. result->op = GGML_OP_ARGMAX;
  1916. result->src[0] = a;
  1917. return result;
  1918. }
  1919. // ggml_count_equal
  1920. struct ggml_tensor * ggml_count_equal(
  1921. struct ggml_context * ctx,
  1922. struct ggml_tensor * a,
  1923. struct ggml_tensor * b) {
  1924. GGML_ASSERT(ggml_are_same_shape(a, b));
  1925. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, 1);
  1926. result->op = GGML_OP_COUNT_EQUAL;
  1927. result->src[0] = a;
  1928. result->src[1] = b;
  1929. return result;
  1930. }
  1931. // ggml_repeat
  1932. struct ggml_tensor * ggml_repeat(
  1933. struct ggml_context * ctx,
  1934. struct ggml_tensor * a,
  1935. struct ggml_tensor * b) {
  1936. GGML_ASSERT(ggml_can_repeat(a, b));
  1937. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1938. result->op = GGML_OP_REPEAT;
  1939. result->src[0] = a;
  1940. return result;
  1941. }
  1942. // ggml_repeat_back
  1943. struct ggml_tensor * ggml_repeat_back(
  1944. struct ggml_context * ctx,
  1945. struct ggml_tensor * a,
  1946. struct ggml_tensor * b) {
  1947. GGML_ASSERT(ggml_can_repeat(b, a));
  1948. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
  1949. result->op = GGML_OP_REPEAT_BACK;
  1950. result->src[0] = a;
  1951. return result;
  1952. }
  1953. // ggml_concat
  1954. struct ggml_tensor * ggml_concat(
  1955. struct ggml_context * ctx,
  1956. struct ggml_tensor * a,
  1957. struct ggml_tensor * b,
  1958. int dim) {
  1959. GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
  1960. GGML_ASSERT(a->type == b->type);
  1961. int64_t ne[GGML_MAX_DIMS];
  1962. for (int d = 0; d < GGML_MAX_DIMS; ++d) {
  1963. if (d == dim) {
  1964. ne[d] = a->ne[d] + b->ne[d];
  1965. continue;
  1966. }
  1967. GGML_ASSERT(a->ne[d] == b->ne[d]);
  1968. ne[d] = a->ne[d];
  1969. }
  1970. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
  1971. ggml_set_op_params_i32(result, 0, dim);
  1972. result->op = GGML_OP_CONCAT;
  1973. result->src[0] = a;
  1974. result->src[1] = b;
  1975. return result;
  1976. }
  1977. // ggml_abs
  1978. struct ggml_tensor * ggml_abs(
  1979. struct ggml_context * ctx,
  1980. struct ggml_tensor * a) {
  1981. return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
  1982. }
  1983. struct ggml_tensor * ggml_abs_inplace(
  1984. struct ggml_context * ctx,
  1985. struct ggml_tensor * a) {
  1986. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
  1987. }
  1988. // ggml_sgn
  1989. struct ggml_tensor * ggml_sgn(
  1990. struct ggml_context * ctx,
  1991. struct ggml_tensor * a) {
  1992. return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
  1993. }
  1994. struct ggml_tensor * ggml_sgn_inplace(
  1995. struct ggml_context * ctx,
  1996. struct ggml_tensor * a) {
  1997. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
  1998. }
  1999. // ggml_neg
  2000. struct ggml_tensor * ggml_neg(
  2001. struct ggml_context * ctx,
  2002. struct ggml_tensor * a) {
  2003. return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
  2004. }
  2005. struct ggml_tensor * ggml_neg_inplace(
  2006. struct ggml_context * ctx,
  2007. struct ggml_tensor * a) {
  2008. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
  2009. }
  2010. // ggml_step
  2011. struct ggml_tensor * ggml_step(
  2012. struct ggml_context * ctx,
  2013. struct ggml_tensor * a) {
  2014. return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
  2015. }
  2016. struct ggml_tensor * ggml_step_inplace(
  2017. struct ggml_context * ctx,
  2018. struct ggml_tensor * a) {
  2019. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
  2020. }
  2021. // ggml_tanh
  2022. struct ggml_tensor * ggml_tanh(
  2023. struct ggml_context * ctx,
  2024. struct ggml_tensor * a) {
  2025. return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
  2026. }
  2027. struct ggml_tensor * ggml_tanh_inplace(
  2028. struct ggml_context * ctx,
  2029. struct ggml_tensor * a) {
  2030. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
  2031. }
  2032. // ggml_elu
  2033. struct ggml_tensor * ggml_elu(
  2034. struct ggml_context * ctx,
  2035. struct ggml_tensor * a) {
  2036. return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
  2037. }
  2038. struct ggml_tensor * ggml_elu_inplace(
  2039. struct ggml_context * ctx,
  2040. struct ggml_tensor * a) {
  2041. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
  2042. }
  2043. // ggml_relu
  2044. struct ggml_tensor * ggml_relu(
  2045. struct ggml_context * ctx,
  2046. struct ggml_tensor * a) {
  2047. return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
  2048. }
  2049. struct ggml_tensor * ggml_relu_inplace(
  2050. struct ggml_context * ctx,
  2051. struct ggml_tensor * a) {
  2052. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
  2053. }
  2054. // ggml_leaky_relu
  2055. struct ggml_tensor * ggml_leaky_relu(
  2056. struct ggml_context * ctx,
  2057. struct ggml_tensor * a,
  2058. float negative_slope,
  2059. bool inplace) {
  2060. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2061. ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
  2062. result->op = GGML_OP_LEAKY_RELU;
  2063. result->src[0] = a;
  2064. return result;
  2065. }
  2066. // ggml_sigmoid
  2067. struct ggml_tensor * ggml_sigmoid(
  2068. struct ggml_context * ctx,
  2069. struct ggml_tensor * a) {
  2070. return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
  2071. }
  2072. struct ggml_tensor * ggml_sigmoid_inplace(
  2073. struct ggml_context * ctx,
  2074. struct ggml_tensor * a) {
  2075. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
  2076. }
  2077. // ggml_gelu
  2078. struct ggml_tensor * ggml_gelu(
  2079. struct ggml_context * ctx,
  2080. struct ggml_tensor * a) {
  2081. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
  2082. }
  2083. struct ggml_tensor * ggml_gelu_inplace(
  2084. struct ggml_context * ctx,
  2085. struct ggml_tensor * a) {
  2086. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
  2087. }
  2088. // ggml_gelu_quick
  2089. struct ggml_tensor * ggml_gelu_quick(
  2090. struct ggml_context * ctx,
  2091. struct ggml_tensor * a) {
  2092. return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2093. }
  2094. struct ggml_tensor * ggml_gelu_quick_inplace(
  2095. struct ggml_context * ctx,
  2096. struct ggml_tensor * a) {
  2097. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
  2098. }
  2099. // ggml_silu
  2100. struct ggml_tensor * ggml_silu(
  2101. struct ggml_context * ctx,
  2102. struct ggml_tensor * a) {
  2103. return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
  2104. }
  2105. struct ggml_tensor * ggml_silu_inplace(
  2106. struct ggml_context * ctx,
  2107. struct ggml_tensor * a) {
  2108. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
  2109. }
  2110. // ggml_silu_back
  2111. struct ggml_tensor * ggml_silu_back(
  2112. struct ggml_context * ctx,
  2113. struct ggml_tensor * a,
  2114. struct ggml_tensor * b) {
  2115. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2116. result->op = GGML_OP_SILU_BACK;
  2117. result->src[0] = a;
  2118. result->src[1] = b;
  2119. return result;
  2120. }
  2121. // ggml hardswish
  2122. struct ggml_tensor * ggml_hardswish(
  2123. struct ggml_context * ctx,
  2124. struct ggml_tensor * a) {
  2125. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
  2126. }
  2127. // ggml hardsigmoid
  2128. struct ggml_tensor * ggml_hardsigmoid(
  2129. struct ggml_context * ctx,
  2130. struct ggml_tensor * a) {
  2131. return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
  2132. }
  2133. // ggml exp
  2134. struct ggml_tensor * ggml_exp(
  2135. struct ggml_context * ctx,
  2136. struct ggml_tensor * a) {
  2137. return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
  2138. }
  2139. struct ggml_tensor * ggml_exp_inplace(
  2140. struct ggml_context * ctx,
  2141. struct ggml_tensor * a) {
  2142. return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
  2143. }
  2144. // ggml_norm
  2145. static struct ggml_tensor * ggml_norm_impl(
  2146. struct ggml_context * ctx,
  2147. struct ggml_tensor * a,
  2148. float eps,
  2149. bool inplace) {
  2150. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2151. ggml_set_op_params(result, &eps, sizeof(eps));
  2152. result->op = GGML_OP_NORM;
  2153. result->src[0] = a;
  2154. return result;
  2155. }
  2156. struct ggml_tensor * ggml_norm(
  2157. struct ggml_context * ctx,
  2158. struct ggml_tensor * a,
  2159. float eps) {
  2160. return ggml_norm_impl(ctx, a, eps, false);
  2161. }
  2162. struct ggml_tensor * ggml_norm_inplace(
  2163. struct ggml_context * ctx,
  2164. struct ggml_tensor * a,
  2165. float eps) {
  2166. return ggml_norm_impl(ctx, a, eps, true);
  2167. }
  2168. // ggml_rms_norm
  2169. static struct ggml_tensor * ggml_rms_norm_impl(
  2170. struct ggml_context * ctx,
  2171. struct ggml_tensor * a,
  2172. float eps,
  2173. bool inplace) {
  2174. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2175. ggml_set_op_params(result, &eps, sizeof(eps));
  2176. result->op = GGML_OP_RMS_NORM;
  2177. result->src[0] = a;
  2178. return result;
  2179. }
  2180. struct ggml_tensor * ggml_rms_norm(
  2181. struct ggml_context * ctx,
  2182. struct ggml_tensor * a,
  2183. float eps) {
  2184. return ggml_rms_norm_impl(ctx, a, eps, false);
  2185. }
  2186. struct ggml_tensor * ggml_rms_norm_inplace(
  2187. struct ggml_context * ctx,
  2188. struct ggml_tensor * a,
  2189. float eps) {
  2190. return ggml_rms_norm_impl(ctx, a, eps, true);
  2191. }
  2192. // ggml_rms_norm_back
  2193. struct ggml_tensor * ggml_rms_norm_back(
  2194. struct ggml_context * ctx,
  2195. struct ggml_tensor * a,
  2196. struct ggml_tensor * b,
  2197. float eps) {
  2198. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2199. ggml_set_op_params(result, &eps, sizeof(eps));
  2200. result->op = GGML_OP_RMS_NORM_BACK;
  2201. result->src[0] = a;
  2202. result->src[1] = b;
  2203. return result;
  2204. }
  2205. // ggml_group_norm
  2206. static struct ggml_tensor * ggml_group_norm_impl(
  2207. struct ggml_context * ctx,
  2208. struct ggml_tensor * a,
  2209. int n_groups,
  2210. float eps,
  2211. bool inplace) {
  2212. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2213. ggml_set_op_params_i32(result, 0, n_groups);
  2214. ggml_set_op_params_f32(result, 1, eps);
  2215. result->op = GGML_OP_GROUP_NORM;
  2216. result->src[0] = a;
  2217. return result;
  2218. }
  2219. struct ggml_tensor * ggml_group_norm(
  2220. struct ggml_context * ctx,
  2221. struct ggml_tensor * a,
  2222. int n_groups,
  2223. float eps) {
  2224. return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
  2225. }
  2226. struct ggml_tensor * ggml_group_norm_inplace(
  2227. struct ggml_context * ctx,
  2228. struct ggml_tensor * a,
  2229. int n_groups,
  2230. float eps) {
  2231. return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
  2232. }
  2233. // ggml_l2_norm
  2234. static struct ggml_tensor * ggml_l2_norm_impl(
  2235. struct ggml_context * ctx,
  2236. struct ggml_tensor * a,
  2237. float eps,
  2238. bool inplace) {
  2239. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2240. ggml_set_op_params_f32(result, 0, eps);
  2241. result->op = GGML_OP_L2_NORM;
  2242. result->src[0] = a;
  2243. return result;
  2244. }
  2245. struct ggml_tensor * ggml_l2_norm(
  2246. struct ggml_context * ctx,
  2247. struct ggml_tensor * a,
  2248. float eps) {
  2249. return ggml_l2_norm_impl(ctx, a, eps, false);
  2250. }
  2251. struct ggml_tensor * ggml_l2_norm_inplace(
  2252. struct ggml_context * ctx,
  2253. struct ggml_tensor * a,
  2254. float eps) {
  2255. return ggml_l2_norm_impl(ctx, a, eps, true);
  2256. }
  2257. // ggml_mul_mat
  2258. static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2259. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2260. return (t0->ne[0] == t1->ne[0]) &&
  2261. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2262. (t1->ne[3]%t0->ne[3] == 0);
  2263. }
  2264. struct ggml_tensor * ggml_mul_mat(
  2265. struct ggml_context * ctx,
  2266. struct ggml_tensor * a,
  2267. struct ggml_tensor * b) {
  2268. GGML_ASSERT(ggml_can_mul_mat(a, b));
  2269. GGML_ASSERT(!ggml_is_transposed(a));
  2270. const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
  2271. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2272. result->op = GGML_OP_MUL_MAT;
  2273. result->src[0] = a;
  2274. result->src[1] = b;
  2275. return result;
  2276. }
  2277. void ggml_mul_mat_set_prec(
  2278. struct ggml_tensor * a,
  2279. enum ggml_prec prec) {
  2280. GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
  2281. const int32_t prec_i32 = (int32_t) prec;
  2282. ggml_set_op_params_i32(a, 0, prec_i32);
  2283. }
  2284. // ggml_mul_mat_id
  2285. /*
  2286. c = ggml_mul_mat_id(ctx, as, b, ids);
  2287. as -> [cols, rows, n_expert]
  2288. ids -> [n_experts_used, n_tokens] (i32)
  2289. b -> [cols, n_expert_used, n_tokens]
  2290. c -> [rows, n_expert_used, n_tokens]
  2291. in b, n_experts_used can be broadcasted to match the n_expert_used of ids
  2292. c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
  2293. */
  2294. struct ggml_tensor * ggml_mul_mat_id(
  2295. struct ggml_context * ctx,
  2296. struct ggml_tensor * as,
  2297. struct ggml_tensor * b,
  2298. struct ggml_tensor * ids) {
  2299. GGML_ASSERT(!ggml_is_transposed(as));
  2300. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  2301. GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
  2302. GGML_ASSERT(b->ne[3] == 1); // b is 3d
  2303. GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
  2304. GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
  2305. GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
  2306. GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
  2307. const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
  2308. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2309. result->op = GGML_OP_MUL_MAT_ID;
  2310. result->src[0] = as;
  2311. result->src[1] = b;
  2312. result->src[2] = ids;
  2313. return result;
  2314. }
  2315. // ggml_out_prod
  2316. static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
  2317. static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
  2318. return (t0->ne[1] == t1->ne[1]) &&
  2319. (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
  2320. (t1->ne[3]%t0->ne[3] == 0);
  2321. }
  2322. struct ggml_tensor * ggml_out_prod(
  2323. struct ggml_context * ctx,
  2324. struct ggml_tensor * a,
  2325. struct ggml_tensor * b) {
  2326. GGML_ASSERT(ggml_can_out_prod(a, b));
  2327. GGML_ASSERT(!ggml_is_transposed(a));
  2328. // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
  2329. const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
  2330. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  2331. result->op = GGML_OP_OUT_PROD;
  2332. result->src[0] = a;
  2333. result->src[1] = b;
  2334. return result;
  2335. }
  2336. // ggml_scale
  2337. static struct ggml_tensor * ggml_scale_impl(
  2338. struct ggml_context * ctx,
  2339. struct ggml_tensor * a,
  2340. float s,
  2341. bool inplace) {
  2342. GGML_ASSERT(ggml_is_padded_1d(a));
  2343. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2344. ggml_set_op_params(result, &s, sizeof(s));
  2345. result->op = GGML_OP_SCALE;
  2346. result->src[0] = a;
  2347. return result;
  2348. }
  2349. struct ggml_tensor * ggml_scale(
  2350. struct ggml_context * ctx,
  2351. struct ggml_tensor * a,
  2352. float s) {
  2353. return ggml_scale_impl(ctx, a, s, false);
  2354. }
  2355. struct ggml_tensor * ggml_scale_inplace(
  2356. struct ggml_context * ctx,
  2357. struct ggml_tensor * a,
  2358. float s) {
  2359. return ggml_scale_impl(ctx, a, s, true);
  2360. }
  2361. // ggml_set
  2362. static struct ggml_tensor * ggml_set_impl(
  2363. struct ggml_context * ctx,
  2364. struct ggml_tensor * a,
  2365. struct ggml_tensor * b,
  2366. size_t nb1,
  2367. size_t nb2,
  2368. size_t nb3,
  2369. size_t offset,
  2370. bool inplace) {
  2371. GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
  2372. // make a view of the destination
  2373. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2374. GGML_ASSERT(offset < (size_t)(1 << 30));
  2375. int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
  2376. ggml_set_op_params(result, params, sizeof(params));
  2377. result->op = GGML_OP_SET;
  2378. result->src[0] = a;
  2379. result->src[1] = b;
  2380. return result;
  2381. }
  2382. struct ggml_tensor * ggml_set(
  2383. struct ggml_context * ctx,
  2384. struct ggml_tensor * a,
  2385. struct ggml_tensor * b,
  2386. size_t nb1,
  2387. size_t nb2,
  2388. size_t nb3,
  2389. size_t offset) {
  2390. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
  2391. }
  2392. struct ggml_tensor * ggml_set_inplace(
  2393. struct ggml_context * ctx,
  2394. struct ggml_tensor * a,
  2395. struct ggml_tensor * b,
  2396. size_t nb1,
  2397. size_t nb2,
  2398. size_t nb3,
  2399. size_t offset) {
  2400. return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
  2401. }
  2402. struct ggml_tensor * ggml_set_1d(
  2403. struct ggml_context * ctx,
  2404. struct ggml_tensor * a,
  2405. struct ggml_tensor * b,
  2406. size_t offset) {
  2407. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
  2408. }
  2409. struct ggml_tensor * ggml_set_1d_inplace(
  2410. struct ggml_context * ctx,
  2411. struct ggml_tensor * a,
  2412. struct ggml_tensor * b,
  2413. size_t offset) {
  2414. return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
  2415. }
  2416. struct ggml_tensor * ggml_set_2d(
  2417. struct ggml_context * ctx,
  2418. struct ggml_tensor * a,
  2419. struct ggml_tensor * b,
  2420. size_t nb1,
  2421. size_t offset) {
  2422. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
  2423. }
  2424. struct ggml_tensor * ggml_set_2d_inplace(
  2425. struct ggml_context * ctx,
  2426. struct ggml_tensor * a,
  2427. struct ggml_tensor * b,
  2428. size_t nb1,
  2429. size_t offset) {
  2430. return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
  2431. }
  2432. // ggml_cpy
  2433. static struct ggml_tensor * ggml_cpy_impl(
  2434. struct ggml_context * ctx,
  2435. struct ggml_tensor * a,
  2436. struct ggml_tensor * b) {
  2437. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2438. // make a view of the destination
  2439. struct ggml_tensor * result = ggml_view_tensor(ctx, b);
  2440. if (strlen(b->name) > 0) {
  2441. ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
  2442. } else {
  2443. ggml_format_name(result, "%s (copy)", a->name);
  2444. }
  2445. result->op = GGML_OP_CPY;
  2446. result->src[0] = a;
  2447. result->src[1] = b;
  2448. return result;
  2449. }
  2450. struct ggml_tensor * ggml_cpy(
  2451. struct ggml_context * ctx,
  2452. struct ggml_tensor * a,
  2453. struct ggml_tensor * b) {
  2454. return ggml_cpy_impl(ctx, a, b);
  2455. }
  2456. struct ggml_tensor * ggml_cast(
  2457. struct ggml_context * ctx,
  2458. struct ggml_tensor * a,
  2459. enum ggml_type type) {
  2460. struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
  2461. ggml_format_name(result, "%s (copy)", a->name);
  2462. result->op = GGML_OP_CPY;
  2463. result->src[0] = a;
  2464. result->src[1] = result;
  2465. return result;
  2466. }
  2467. // ggml_cont
  2468. static struct ggml_tensor * ggml_cont_impl(
  2469. struct ggml_context * ctx,
  2470. struct ggml_tensor * a) {
  2471. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2472. ggml_format_name(result, "%s (cont)", a->name);
  2473. result->op = GGML_OP_CONT;
  2474. result->src[0] = a;
  2475. return result;
  2476. }
  2477. struct ggml_tensor * ggml_cont(
  2478. struct ggml_context * ctx,
  2479. struct ggml_tensor * a) {
  2480. return ggml_cont_impl(ctx, a);
  2481. }
  2482. // make contiguous, with new shape
  2483. GGML_API struct ggml_tensor * ggml_cont_1d(
  2484. struct ggml_context * ctx,
  2485. struct ggml_tensor * a,
  2486. int64_t ne0) {
  2487. return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
  2488. }
  2489. GGML_API struct ggml_tensor * ggml_cont_2d(
  2490. struct ggml_context * ctx,
  2491. struct ggml_tensor * a,
  2492. int64_t ne0,
  2493. int64_t ne1) {
  2494. return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
  2495. }
  2496. GGML_API struct ggml_tensor * ggml_cont_3d(
  2497. struct ggml_context * ctx,
  2498. struct ggml_tensor * a,
  2499. int64_t ne0,
  2500. int64_t ne1,
  2501. int64_t ne2) {
  2502. return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
  2503. }
  2504. struct ggml_tensor * ggml_cont_4d(
  2505. struct ggml_context * ctx,
  2506. struct ggml_tensor * a,
  2507. int64_t ne0,
  2508. int64_t ne1,
  2509. int64_t ne2,
  2510. int64_t ne3) {
  2511. GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
  2512. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  2513. ggml_format_name(result, "%s (cont)", a->name);
  2514. result->op = GGML_OP_CONT;
  2515. result->src[0] = a;
  2516. return result;
  2517. }
  2518. // ggml_reshape
  2519. struct ggml_tensor * ggml_reshape(
  2520. struct ggml_context * ctx,
  2521. struct ggml_tensor * a,
  2522. struct ggml_tensor * b) {
  2523. GGML_ASSERT(ggml_is_contiguous(a));
  2524. // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
  2525. GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
  2526. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->ne, a, 0);
  2527. ggml_format_name(result, "%s (reshaped)", a->name);
  2528. result->op = GGML_OP_RESHAPE;
  2529. result->src[0] = a;
  2530. return result;
  2531. }
  2532. struct ggml_tensor * ggml_reshape_1d(
  2533. struct ggml_context * ctx,
  2534. struct ggml_tensor * a,
  2535. int64_t ne0) {
  2536. GGML_ASSERT(ggml_is_contiguous(a));
  2537. GGML_ASSERT(ggml_nelements(a) == ne0);
  2538. const int64_t ne[1] = { ne0 };
  2539. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
  2540. ggml_format_name(result, "%s (reshaped)", a->name);
  2541. result->op = GGML_OP_RESHAPE;
  2542. result->src[0] = a;
  2543. return result;
  2544. }
  2545. struct ggml_tensor * ggml_reshape_2d(
  2546. struct ggml_context * ctx,
  2547. struct ggml_tensor * a,
  2548. int64_t ne0,
  2549. int64_t ne1) {
  2550. GGML_ASSERT(ggml_is_contiguous(a));
  2551. GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
  2552. const int64_t ne[2] = { ne0, ne1 };
  2553. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
  2554. ggml_format_name(result, "%s (reshaped)", a->name);
  2555. result->op = GGML_OP_RESHAPE;
  2556. result->src[0] = a;
  2557. return result;
  2558. }
  2559. struct ggml_tensor * ggml_reshape_3d(
  2560. struct ggml_context * ctx,
  2561. struct ggml_tensor * a,
  2562. int64_t ne0,
  2563. int64_t ne1,
  2564. int64_t ne2) {
  2565. GGML_ASSERT(ggml_is_contiguous(a));
  2566. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
  2567. const int64_t ne[3] = { ne0, ne1, ne2 };
  2568. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
  2569. ggml_format_name(result, "%s (reshaped)", a->name);
  2570. result->op = GGML_OP_RESHAPE;
  2571. result->src[0] = a;
  2572. return result;
  2573. }
  2574. struct ggml_tensor * ggml_reshape_4d(
  2575. struct ggml_context * ctx,
  2576. struct ggml_tensor * a,
  2577. int64_t ne0,
  2578. int64_t ne1,
  2579. int64_t ne2,
  2580. int64_t ne3) {
  2581. GGML_ASSERT(ggml_is_contiguous(a));
  2582. GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
  2583. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2584. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
  2585. ggml_format_name(result, "%s (reshaped)", a->name);
  2586. result->op = GGML_OP_RESHAPE;
  2587. result->src[0] = a;
  2588. return result;
  2589. }
  2590. static struct ggml_tensor * ggml_view_impl(
  2591. struct ggml_context * ctx,
  2592. struct ggml_tensor * a,
  2593. int n_dims,
  2594. const int64_t * ne,
  2595. size_t offset) {
  2596. struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
  2597. ggml_format_name(result, "%s (view)", a->name);
  2598. ggml_set_op_params(result, &offset, sizeof(offset));
  2599. result->op = GGML_OP_VIEW;
  2600. result->src[0] = a;
  2601. return result;
  2602. }
  2603. // ggml_view_1d
  2604. struct ggml_tensor * ggml_view_1d(
  2605. struct ggml_context * ctx,
  2606. struct ggml_tensor * a,
  2607. int64_t ne0,
  2608. size_t offset) {
  2609. struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
  2610. return result;
  2611. }
  2612. // ggml_view_2d
  2613. struct ggml_tensor * ggml_view_2d(
  2614. struct ggml_context * ctx,
  2615. struct ggml_tensor * a,
  2616. int64_t ne0,
  2617. int64_t ne1,
  2618. size_t nb1,
  2619. size_t offset) {
  2620. const int64_t ne[2] = { ne0, ne1 };
  2621. struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
  2622. result->nb[1] = nb1;
  2623. result->nb[2] = result->nb[1]*ne1;
  2624. result->nb[3] = result->nb[2];
  2625. return result;
  2626. }
  2627. // ggml_view_3d
  2628. struct ggml_tensor * ggml_view_3d(
  2629. struct ggml_context * ctx,
  2630. struct ggml_tensor * a,
  2631. int64_t ne0,
  2632. int64_t ne1,
  2633. int64_t ne2,
  2634. size_t nb1,
  2635. size_t nb2,
  2636. size_t offset) {
  2637. const int64_t ne[3] = { ne0, ne1, ne2 };
  2638. struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
  2639. result->nb[1] = nb1;
  2640. result->nb[2] = nb2;
  2641. result->nb[3] = result->nb[2]*ne2;
  2642. return result;
  2643. }
  2644. // ggml_view_4d
  2645. struct ggml_tensor * ggml_view_4d(
  2646. struct ggml_context * ctx,
  2647. struct ggml_tensor * a,
  2648. int64_t ne0,
  2649. int64_t ne1,
  2650. int64_t ne2,
  2651. int64_t ne3,
  2652. size_t nb1,
  2653. size_t nb2,
  2654. size_t nb3,
  2655. size_t offset) {
  2656. const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
  2657. struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
  2658. result->nb[1] = nb1;
  2659. result->nb[2] = nb2;
  2660. result->nb[3] = nb3;
  2661. return result;
  2662. }
  2663. // ggml_permute
  2664. struct ggml_tensor * ggml_permute(
  2665. struct ggml_context * ctx,
  2666. struct ggml_tensor * a,
  2667. int axis0,
  2668. int axis1,
  2669. int axis2,
  2670. int axis3) {
  2671. GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
  2672. GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
  2673. GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
  2674. GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
  2675. GGML_ASSERT(axis0 != axis1);
  2676. GGML_ASSERT(axis0 != axis2);
  2677. GGML_ASSERT(axis0 != axis3);
  2678. GGML_ASSERT(axis1 != axis2);
  2679. GGML_ASSERT(axis1 != axis3);
  2680. GGML_ASSERT(axis2 != axis3);
  2681. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2682. ggml_format_name(result, "%s (permuted)", a->name);
  2683. int ne[GGML_MAX_DIMS];
  2684. int nb[GGML_MAX_DIMS];
  2685. ne[axis0] = a->ne[0];
  2686. ne[axis1] = a->ne[1];
  2687. ne[axis2] = a->ne[2];
  2688. ne[axis3] = a->ne[3];
  2689. nb[axis0] = a->nb[0];
  2690. nb[axis1] = a->nb[1];
  2691. nb[axis2] = a->nb[2];
  2692. nb[axis3] = a->nb[3];
  2693. result->ne[0] = ne[0];
  2694. result->ne[1] = ne[1];
  2695. result->ne[2] = ne[2];
  2696. result->ne[3] = ne[3];
  2697. result->nb[0] = nb[0];
  2698. result->nb[1] = nb[1];
  2699. result->nb[2] = nb[2];
  2700. result->nb[3] = nb[3];
  2701. result->op = GGML_OP_PERMUTE;
  2702. result->src[0] = a;
  2703. int32_t params[] = { axis0, axis1, axis2, axis3 };
  2704. ggml_set_op_params(result, params, sizeof(params));
  2705. return result;
  2706. }
  2707. // ggml_transpose
  2708. struct ggml_tensor * ggml_transpose(
  2709. struct ggml_context * ctx,
  2710. struct ggml_tensor * a) {
  2711. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  2712. ggml_format_name(result, "%s (transposed)", a->name);
  2713. result->ne[0] = a->ne[1];
  2714. result->ne[1] = a->ne[0];
  2715. result->nb[0] = a->nb[1];
  2716. result->nb[1] = a->nb[0];
  2717. result->op = GGML_OP_TRANSPOSE;
  2718. result->src[0] = a;
  2719. return result;
  2720. }
  2721. // ggml_get_rows
  2722. struct ggml_tensor * ggml_get_rows(
  2723. struct ggml_context * ctx,
  2724. struct ggml_tensor * a,
  2725. struct ggml_tensor * b) {
  2726. GGML_ASSERT(a->ne[2] == b->ne[1]);
  2727. GGML_ASSERT(b->ne[3] == 1);
  2728. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2729. // TODO: implement non F32 return
  2730. enum ggml_type type = GGML_TYPE_F32;
  2731. if (a->type == GGML_TYPE_I32) {
  2732. type = a->type;
  2733. }
  2734. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
  2735. result->op = GGML_OP_GET_ROWS;
  2736. result->src[0] = a;
  2737. result->src[1] = b;
  2738. return result;
  2739. }
  2740. // ggml_get_rows_back
  2741. struct ggml_tensor * ggml_get_rows_back(
  2742. struct ggml_context * ctx,
  2743. struct ggml_tensor * a,
  2744. struct ggml_tensor * b,
  2745. struct ggml_tensor * c) {
  2746. GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
  2747. GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
  2748. // TODO: implement non F32 return
  2749. //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
  2750. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
  2751. result->op = GGML_OP_GET_ROWS_BACK;
  2752. result->src[0] = a;
  2753. result->src[1] = b;
  2754. return result;
  2755. }
  2756. // ggml_diag
  2757. struct ggml_tensor * ggml_diag(
  2758. struct ggml_context * ctx,
  2759. struct ggml_tensor * a) {
  2760. GGML_ASSERT(a->ne[1] == 1);
  2761. const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
  2762. struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
  2763. result->op = GGML_OP_DIAG;
  2764. result->src[0] = a;
  2765. return result;
  2766. }
  2767. // ggml_diag_mask_inf
  2768. static struct ggml_tensor * ggml_diag_mask_inf_impl(
  2769. struct ggml_context * ctx,
  2770. struct ggml_tensor * a,
  2771. int n_past,
  2772. bool inplace) {
  2773. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2774. int32_t params[] = { n_past };
  2775. ggml_set_op_params(result, params, sizeof(params));
  2776. result->op = GGML_OP_DIAG_MASK_INF;
  2777. result->src[0] = a;
  2778. return result;
  2779. }
  2780. struct ggml_tensor * ggml_diag_mask_inf(
  2781. struct ggml_context * ctx,
  2782. struct ggml_tensor * a,
  2783. int n_past) {
  2784. return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
  2785. }
  2786. struct ggml_tensor * ggml_diag_mask_inf_inplace(
  2787. struct ggml_context * ctx,
  2788. struct ggml_tensor * a,
  2789. int n_past) {
  2790. return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
  2791. }
  2792. // ggml_diag_mask_zero
  2793. static struct ggml_tensor * ggml_diag_mask_zero_impl(
  2794. struct ggml_context * ctx,
  2795. struct ggml_tensor * a,
  2796. int n_past,
  2797. bool inplace) {
  2798. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2799. int32_t params[] = { n_past };
  2800. ggml_set_op_params(result, params, sizeof(params));
  2801. result->op = GGML_OP_DIAG_MASK_ZERO;
  2802. result->src[0] = a;
  2803. return result;
  2804. }
  2805. struct ggml_tensor * ggml_diag_mask_zero(
  2806. struct ggml_context * ctx,
  2807. struct ggml_tensor * a,
  2808. int n_past) {
  2809. return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
  2810. }
  2811. struct ggml_tensor * ggml_diag_mask_zero_inplace(
  2812. struct ggml_context * ctx,
  2813. struct ggml_tensor * a,
  2814. int n_past) {
  2815. return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
  2816. }
  2817. // ggml_soft_max
  2818. static struct ggml_tensor * ggml_soft_max_impl(
  2819. struct ggml_context * ctx,
  2820. struct ggml_tensor * a,
  2821. struct ggml_tensor * mask,
  2822. float scale,
  2823. float max_bias,
  2824. bool inplace) {
  2825. GGML_ASSERT(ggml_is_contiguous(a));
  2826. if (mask) {
  2827. GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
  2828. GGML_ASSERT(ggml_is_contiguous(mask));
  2829. GGML_ASSERT(ggml_is_matrix(mask));
  2830. GGML_ASSERT(mask->ne[0] == a->ne[0]);
  2831. GGML_ASSERT(mask->ne[1] >= a->ne[1]);
  2832. }
  2833. if (max_bias > 0.0f) {
  2834. GGML_ASSERT(mask);
  2835. }
  2836. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2837. float params[] = { scale, max_bias };
  2838. ggml_set_op_params(result, params, sizeof(params));
  2839. result->op = GGML_OP_SOFT_MAX;
  2840. result->src[0] = a;
  2841. result->src[1] = mask;
  2842. return result;
  2843. }
  2844. struct ggml_tensor * ggml_soft_max(
  2845. struct ggml_context * ctx,
  2846. struct ggml_tensor * a) {
  2847. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
  2848. }
  2849. struct ggml_tensor * ggml_soft_max_inplace(
  2850. struct ggml_context * ctx,
  2851. struct ggml_tensor * a) {
  2852. return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
  2853. }
  2854. struct ggml_tensor * ggml_soft_max_ext(
  2855. struct ggml_context * ctx,
  2856. struct ggml_tensor * a,
  2857. struct ggml_tensor * mask,
  2858. float scale,
  2859. float max_bias) {
  2860. return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
  2861. }
  2862. // ggml_soft_max_ext_back
  2863. static struct ggml_tensor * ggml_soft_max_ext_back_impl(
  2864. struct ggml_context * ctx,
  2865. struct ggml_tensor * a,
  2866. struct ggml_tensor * b,
  2867. float scale,
  2868. float max_bias,
  2869. bool inplace) {
  2870. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2871. result->op = GGML_OP_SOFT_MAX_BACK;
  2872. result->src[0] = a;
  2873. result->src[1] = b;
  2874. memcpy((float *) result->op_params + 0, &scale, sizeof(float));
  2875. memcpy((float *) result->op_params + 1, &max_bias, sizeof(float));
  2876. return result;
  2877. }
  2878. struct ggml_tensor * ggml_soft_max_ext_back(
  2879. struct ggml_context * ctx,
  2880. struct ggml_tensor * a,
  2881. struct ggml_tensor * b,
  2882. float scale,
  2883. float max_bias) {
  2884. return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, false);
  2885. }
  2886. struct ggml_tensor * ggml_soft_max_ext_back_inplace(
  2887. struct ggml_context * ctx,
  2888. struct ggml_tensor * a,
  2889. struct ggml_tensor * b,
  2890. float scale,
  2891. float max_bias) {
  2892. return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, true);
  2893. }
  2894. // ggml_rope
  2895. static struct ggml_tensor * ggml_rope_impl(
  2896. struct ggml_context * ctx,
  2897. struct ggml_tensor * a,
  2898. struct ggml_tensor * b,
  2899. struct ggml_tensor * c,
  2900. int n_dims,
  2901. int mode,
  2902. int n_ctx_orig,
  2903. float freq_base,
  2904. float freq_scale,
  2905. float ext_factor,
  2906. float attn_factor,
  2907. float beta_fast,
  2908. float beta_slow,
  2909. bool inplace) {
  2910. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2911. GGML_ASSERT(ggml_is_vector(b));
  2912. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2913. GGML_ASSERT(a->ne[2] == b->ne[0]);
  2914. if (c) {
  2915. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2916. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2917. }
  2918. int sections[4] = {0, 0, 0, 0};
  2919. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  2920. int32_t params[15] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2921. memcpy(params + 5, &freq_base, sizeof(float));
  2922. memcpy(params + 6, &freq_scale, sizeof(float));
  2923. memcpy(params + 7, &ext_factor, sizeof(float));
  2924. memcpy(params + 8, &attn_factor, sizeof(float));
  2925. memcpy(params + 9, &beta_fast, sizeof(float));
  2926. memcpy(params + 10, &beta_slow, sizeof(float));
  2927. memcpy(params + 11, &sections, sizeof(int)*4);
  2928. ggml_set_op_params(result, params, sizeof(params));
  2929. result->op = GGML_OP_ROPE;
  2930. result->src[0] = a;
  2931. result->src[1] = b;
  2932. result->src[2] = c;
  2933. return result;
  2934. }
  2935. struct ggml_tensor * ggml_rope(
  2936. struct ggml_context * ctx,
  2937. struct ggml_tensor * a,
  2938. struct ggml_tensor * b,
  2939. int n_dims,
  2940. int mode) {
  2941. return ggml_rope_impl(
  2942. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
  2943. );
  2944. }
  2945. struct ggml_tensor * ggml_rope_multi(
  2946. struct ggml_context * ctx,
  2947. struct ggml_tensor * a,
  2948. struct ggml_tensor * b,
  2949. struct ggml_tensor * c,
  2950. int n_dims,
  2951. int sections[4],
  2952. int mode,
  2953. int n_ctx_orig,
  2954. float freq_base,
  2955. float freq_scale,
  2956. float ext_factor,
  2957. float attn_factor,
  2958. float beta_fast,
  2959. float beta_slow) {
  2960. // Multimodal Rotary Position Embedding
  2961. GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
  2962. GGML_ASSERT(ggml_is_vector(b));
  2963. GGML_ASSERT(b->type == GGML_TYPE_I32);
  2964. GGML_ASSERT(a->ne[2] * 4 == b->ne[0]); // mrope expecting 4 position ids per token
  2965. if (c) {
  2966. GGML_ASSERT(c->type == GGML_TYPE_F32);
  2967. GGML_ASSERT(c->ne[0] >= n_dims / 2);
  2968. }
  2969. struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
  2970. int32_t params[11 + 4] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
  2971. memcpy(params + 5, &freq_base, sizeof(float));
  2972. memcpy(params + 6, &freq_scale, sizeof(float));
  2973. memcpy(params + 7, &ext_factor, sizeof(float));
  2974. memcpy(params + 8, &attn_factor, sizeof(float));
  2975. memcpy(params + 9, &beta_fast, sizeof(float));
  2976. memcpy(params + 10, &beta_slow, sizeof(float));
  2977. memcpy(&params[11], sections, sizeof(int)*4);
  2978. ggml_set_op_params(result, params, sizeof(params));
  2979. result->op = GGML_OP_ROPE;
  2980. result->src[0] = a;
  2981. result->src[1] = b;
  2982. result->src[2] = c;
  2983. return result;
  2984. }
  2985. struct ggml_tensor * ggml_rope_inplace(
  2986. struct ggml_context * ctx,
  2987. struct ggml_tensor * a,
  2988. struct ggml_tensor * b,
  2989. int n_dims,
  2990. int mode) {
  2991. return ggml_rope_impl(
  2992. ctx, a, b, NULL, n_dims, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
  2993. );
  2994. }
  2995. struct ggml_tensor * ggml_rope_ext(
  2996. struct ggml_context * ctx,
  2997. struct ggml_tensor * a,
  2998. struct ggml_tensor * b,
  2999. struct ggml_tensor * c,
  3000. int n_dims,
  3001. int mode,
  3002. int n_ctx_orig,
  3003. float freq_base,
  3004. float freq_scale,
  3005. float ext_factor,
  3006. float attn_factor,
  3007. float beta_fast,
  3008. float beta_slow) {
  3009. return ggml_rope_impl(
  3010. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3011. ext_factor, attn_factor, beta_fast, beta_slow, false
  3012. );
  3013. }
  3014. struct ggml_tensor * ggml_rope_ext_inplace(
  3015. struct ggml_context * ctx,
  3016. struct ggml_tensor * a,
  3017. struct ggml_tensor * b,
  3018. struct ggml_tensor * c,
  3019. int n_dims,
  3020. int mode,
  3021. int n_ctx_orig,
  3022. float freq_base,
  3023. float freq_scale,
  3024. float ext_factor,
  3025. float attn_factor,
  3026. float beta_fast,
  3027. float beta_slow) {
  3028. return ggml_rope_impl(
  3029. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3030. ext_factor, attn_factor, beta_fast, beta_slow, true
  3031. );
  3032. }
  3033. struct ggml_tensor * ggml_rope_custom(
  3034. struct ggml_context * ctx,
  3035. struct ggml_tensor * a,
  3036. struct ggml_tensor * b,
  3037. int n_dims,
  3038. int mode,
  3039. int n_ctx_orig,
  3040. float freq_base,
  3041. float freq_scale,
  3042. float ext_factor,
  3043. float attn_factor,
  3044. float beta_fast,
  3045. float beta_slow) {
  3046. return ggml_rope_impl(
  3047. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3048. ext_factor, attn_factor, beta_fast, beta_slow, false
  3049. );
  3050. }
  3051. struct ggml_tensor * ggml_rope_custom_inplace(
  3052. struct ggml_context * ctx,
  3053. struct ggml_tensor * a,
  3054. struct ggml_tensor * b,
  3055. int n_dims,
  3056. int mode,
  3057. int n_ctx_orig,
  3058. float freq_base,
  3059. float freq_scale,
  3060. float ext_factor,
  3061. float attn_factor,
  3062. float beta_fast,
  3063. float beta_slow) {
  3064. return ggml_rope_impl(
  3065. ctx, a, b, NULL, n_dims, mode, n_ctx_orig, freq_base, freq_scale,
  3066. ext_factor, attn_factor, beta_fast, beta_slow, true
  3067. );
  3068. }
  3069. // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
  3070. // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
  3071. static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
  3072. return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
  3073. }
  3074. void ggml_rope_yarn_corr_dims(
  3075. int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
  3076. ) {
  3077. // start and end correction dims
  3078. float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
  3079. float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
  3080. dims[0] = MAX(0, start);
  3081. dims[1] = MIN(n_dims - 1, end);
  3082. }
  3083. // ggml_rope_back
  3084. struct ggml_tensor * ggml_rope_ext_back(
  3085. struct ggml_context * ctx,
  3086. struct ggml_tensor * a,
  3087. struct ggml_tensor * b,
  3088. struct ggml_tensor * c,
  3089. int n_dims,
  3090. int mode,
  3091. int n_ctx_orig,
  3092. float freq_base,
  3093. float freq_scale,
  3094. float ext_factor,
  3095. float attn_factor,
  3096. float beta_fast,
  3097. float beta_slow) {
  3098. struct ggml_tensor * result = ggml_rope_ext(
  3099. ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  3100. result->op = GGML_OP_ROPE_BACK;
  3101. return result;
  3102. }
  3103. struct ggml_tensor * ggml_rope_multi_back(
  3104. struct ggml_context * ctx,
  3105. struct ggml_tensor * a,
  3106. struct ggml_tensor * b,
  3107. struct ggml_tensor * c,
  3108. int n_dims,
  3109. int sections[4],
  3110. int mode,
  3111. int n_ctx_orig,
  3112. float freq_base,
  3113. float freq_scale,
  3114. float ext_factor,
  3115. float attn_factor,
  3116. float beta_fast,
  3117. float beta_slow) {
  3118. struct ggml_tensor * result = ggml_rope_multi(
  3119. ctx, a, b, c, n_dims, sections, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  3120. result->op = GGML_OP_ROPE_BACK;
  3121. return result;
  3122. }
  3123. // ggml_clamp
  3124. struct ggml_tensor * ggml_clamp(
  3125. struct ggml_context * ctx,
  3126. struct ggml_tensor * a,
  3127. float min,
  3128. float max) {
  3129. // TODO: when implement backward, fix this:
  3130. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  3131. float params[] = { min, max };
  3132. ggml_set_op_params(result, params, sizeof(params));
  3133. result->op = GGML_OP_CLAMP;
  3134. result->src[0] = a;
  3135. return result;
  3136. }
  3137. static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3138. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  3139. }
  3140. // im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
  3141. // a: [OC,IC, KH, KW]
  3142. // b: [N, IC, IH, IW]
  3143. // result: [N, OH, OW, IC*KH*KW]
  3144. struct ggml_tensor * ggml_im2col(
  3145. struct ggml_context * ctx,
  3146. struct ggml_tensor * a,
  3147. struct ggml_tensor * b,
  3148. int s0,
  3149. int s1,
  3150. int p0,
  3151. int p1,
  3152. int d0,
  3153. int d1,
  3154. bool is_2D,
  3155. enum ggml_type dst_type) {
  3156. if (is_2D) {
  3157. GGML_ASSERT(a->ne[2] == b->ne[2]);
  3158. } else {
  3159. //GGML_ASSERT(b->ne[1] % a->ne[1] == 0);
  3160. GGML_ASSERT(b->ne[1] == a->ne[1]);
  3161. GGML_ASSERT(b->ne[3] == 1);
  3162. }
  3163. const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
  3164. const int64_t OW = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
  3165. GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
  3166. GGML_ASSERT((OW > 0) && "b too small compared to a");
  3167. const int64_t ne[4] = {
  3168. is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
  3169. OW,
  3170. is_2D ? OH : b->ne[2],
  3171. is_2D ? b->ne[3] : 1,
  3172. };
  3173. struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
  3174. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3175. ggml_set_op_params(result, params, sizeof(params));
  3176. result->op = GGML_OP_IM2COL;
  3177. result->src[0] = a;
  3178. result->src[1] = b;
  3179. return result;
  3180. }
  3181. struct ggml_tensor * ggml_im2col_back(
  3182. struct ggml_context * ctx,
  3183. struct ggml_tensor * a,
  3184. struct ggml_tensor * b,
  3185. int64_t * ne,
  3186. int s0,
  3187. int s1,
  3188. int p0,
  3189. int p1,
  3190. int d0,
  3191. int d1,
  3192. bool is_2D) {
  3193. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3194. int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
  3195. ggml_set_op_params(result, params, sizeof(params));
  3196. result->op = GGML_OP_IM2COL_BACK;
  3197. result->src[0] = a;
  3198. result->src[1] = b;
  3199. return result;
  3200. }
  3201. // ggml_conv_1d
  3202. struct ggml_tensor * ggml_conv_1d(
  3203. struct ggml_context * ctx,
  3204. struct ggml_tensor * a,
  3205. struct ggml_tensor * b,
  3206. int s0,
  3207. int p0,
  3208. int d0) {
  3209. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16); // [N, OL, IC * K]
  3210. struct ggml_tensor * result =
  3211. ggml_mul_mat(ctx,
  3212. ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
  3213. ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2])); // [OC,IC, K] => [OC, IC * K]
  3214. result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
  3215. return result;
  3216. }
  3217. // ggml_conv_1d_ph
  3218. struct ggml_tensor* ggml_conv_1d_ph(
  3219. struct ggml_context * ctx,
  3220. struct ggml_tensor * a,
  3221. struct ggml_tensor * b,
  3222. int s,
  3223. int d) {
  3224. return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
  3225. }
  3226. // ggml_conv_1d_dw
  3227. struct ggml_tensor * ggml_conv_1d_dw(
  3228. struct ggml_context * ctx,
  3229. struct ggml_tensor * a,
  3230. struct ggml_tensor * b,
  3231. int s0,
  3232. int p0,
  3233. int d0) {
  3234. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], 1, a->ne[1], a->ne[2]);
  3235. struct ggml_tensor * new_b = ggml_reshape_4d(ctx, b, b->ne[0], 1, b->ne[1], b->ne[2]);
  3236. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a, new_b, s0, 0, p0, 0, d0, 0, false, GGML_TYPE_F16);
  3237. struct ggml_tensor * result = ggml_mul_mat(ctx, im2col, a);
  3238. result = ggml_reshape_3d(ctx, result, b->ne[0], b->ne[1], 1);
  3239. return result;
  3240. }
  3241. // ggml_conv_1d_dw_ph
  3242. struct ggml_tensor * ggml_conv_1d_dw_ph(
  3243. struct ggml_context * ctx,
  3244. struct ggml_tensor * a,
  3245. struct ggml_tensor * b,
  3246. int s0,
  3247. int d0) {
  3248. return ggml_conv_1d_dw(ctx, a, b, s0, a->ne[0] / 2, d0);
  3249. }
  3250. // ggml_conv_transpose_1d
  3251. static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
  3252. return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
  3253. }
  3254. GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
  3255. struct ggml_context * ctx,
  3256. struct ggml_tensor * a,
  3257. struct ggml_tensor * b,
  3258. int s0,
  3259. int p0,
  3260. int d0) {
  3261. GGML_ASSERT(ggml_is_matrix(b));
  3262. GGML_ASSERT(a->ne[2] == b->ne[1]);
  3263. GGML_ASSERT(a->ne[3] == 1);
  3264. GGML_ASSERT(p0 == 0);
  3265. GGML_ASSERT(d0 == 1);
  3266. const int64_t ne[4] = {
  3267. ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
  3268. a->ne[1], b->ne[2], 1,
  3269. };
  3270. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3271. int32_t params[] = { s0, p0, d0 };
  3272. ggml_set_op_params(result, params, sizeof(params));
  3273. result->op = GGML_OP_CONV_TRANSPOSE_1D;
  3274. result->src[0] = a;
  3275. result->src[1] = b;
  3276. return result;
  3277. }
  3278. // ggml_conv_2d
  3279. // a: [OC,IC, KH, KW]
  3280. // b: [N, IC, IH, IW]
  3281. // result: [N, OC, OH, OW]
  3282. struct ggml_tensor * ggml_conv_2d(
  3283. struct ggml_context * ctx,
  3284. struct ggml_tensor * a,
  3285. struct ggml_tensor * b,
  3286. int s0,
  3287. int s1,
  3288. int p0,
  3289. int p1,
  3290. int d0,
  3291. int d1) {
  3292. struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type); // [N, OH, OW, IC * KH * KW]
  3293. struct ggml_tensor * result =
  3294. ggml_mul_mat(ctx,
  3295. 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]
  3296. 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]
  3297. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
  3298. result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
  3299. return result;
  3300. }
  3301. // ggml_conv_2d_sk_p0
  3302. struct ggml_tensor * ggml_conv_2d_sk_p0(
  3303. struct ggml_context * ctx,
  3304. struct ggml_tensor * a,
  3305. struct ggml_tensor * b) {
  3306. return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
  3307. }
  3308. // ggml_conv_2d_s1_ph
  3309. struct ggml_tensor * ggml_conv_2d_s1_ph(
  3310. struct ggml_context * ctx,
  3311. struct ggml_tensor * a,
  3312. struct ggml_tensor * b) {
  3313. return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
  3314. }
  3315. // ggml_conv_2d_dw
  3316. struct ggml_tensor * ggml_conv_2d_dw(
  3317. struct ggml_context * ctx,
  3318. struct ggml_tensor * a,
  3319. struct ggml_tensor * b,
  3320. int s0,
  3321. int s1,
  3322. int p0,
  3323. int p1,
  3324. int d0,
  3325. int d1) {
  3326. struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
  3327. struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
  3328. ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
  3329. s0, s1, p0, p1, d0, d1, true, GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
  3330. 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]
  3331. 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]
  3332. struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
  3333. result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
  3334. return result;
  3335. }
  3336. // ggml_conv_transpose_2d_p0
  3337. static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
  3338. return (ins - 1) * s - 2 * p + ks;
  3339. }
  3340. struct ggml_tensor * ggml_conv_transpose_2d_p0(
  3341. struct ggml_context * ctx,
  3342. struct ggml_tensor * a,
  3343. struct ggml_tensor * b,
  3344. int stride) {
  3345. GGML_ASSERT(a->ne[3] == b->ne[2]);
  3346. const int64_t ne[4] = {
  3347. ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
  3348. ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
  3349. a->ne[2], b->ne[3],
  3350. };
  3351. struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3352. ggml_set_op_params_i32(result, 0, stride);
  3353. result->op = GGML_OP_CONV_TRANSPOSE_2D;
  3354. result->src[0] = a;
  3355. result->src[1] = b;
  3356. return result;
  3357. }
  3358. // ggml_pool_*
  3359. static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
  3360. return (ins + 2 * p - ks) / s + 1;
  3361. }
  3362. // ggml_pool_1d
  3363. struct ggml_tensor * ggml_pool_1d(
  3364. struct ggml_context * ctx,
  3365. struct ggml_tensor * a,
  3366. enum ggml_op_pool op,
  3367. int k0,
  3368. int s0,
  3369. int p0) {
  3370. const int64_t ne[4] = {
  3371. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3372. a->ne[1],
  3373. a->ne[2],
  3374. a->ne[3],
  3375. };
  3376. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3377. int32_t params[] = { op, k0, s0, p0 };
  3378. ggml_set_op_params(result, params, sizeof(params));
  3379. result->op = GGML_OP_POOL_1D;
  3380. result->src[0] = a;
  3381. return result;
  3382. }
  3383. // ggml_pool_2d
  3384. struct ggml_tensor * ggml_pool_2d(
  3385. struct ggml_context * ctx,
  3386. struct ggml_tensor * a,
  3387. enum ggml_op_pool op,
  3388. int k0,
  3389. int k1,
  3390. int s0,
  3391. int s1,
  3392. float p0,
  3393. float p1) {
  3394. struct ggml_tensor * result;
  3395. const int64_t ne[4] = {
  3396. ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
  3397. ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
  3398. a->ne[2],
  3399. a->ne[3],
  3400. };
  3401. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3402. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3403. ggml_set_op_params(result, params, sizeof(params));
  3404. result->op = GGML_OP_POOL_2D;
  3405. result->src[0] = a;
  3406. return result;
  3407. }
  3408. struct ggml_tensor * ggml_pool_2d_back(
  3409. struct ggml_context * ctx,
  3410. struct ggml_tensor * a,
  3411. struct ggml_tensor * af,
  3412. enum ggml_op_pool op,
  3413. int k0,
  3414. int k1,
  3415. int s0,
  3416. int s1,
  3417. float p0,
  3418. float p1) {
  3419. struct ggml_tensor * result;
  3420. result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
  3421. int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
  3422. ggml_set_op_params(result, params, sizeof(params));
  3423. result->op = GGML_OP_POOL_2D_BACK;
  3424. result->src[0] = a;
  3425. result->src[1] = af;
  3426. return result;
  3427. }
  3428. // ggml_upscale
  3429. static struct ggml_tensor * ggml_upscale_impl(
  3430. struct ggml_context * ctx,
  3431. struct ggml_tensor * a,
  3432. int ne0,
  3433. int ne1,
  3434. int ne2,
  3435. int ne3) {
  3436. GGML_ASSERT(a->ne[0] <= ne0);
  3437. GGML_ASSERT(a->ne[1] <= ne1);
  3438. GGML_ASSERT(a->ne[2] <= ne2);
  3439. GGML_ASSERT(a->ne[3] <= ne3);
  3440. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
  3441. result->op = GGML_OP_UPSCALE;
  3442. result->src[0] = a;
  3443. return result;
  3444. }
  3445. struct ggml_tensor * ggml_upscale(
  3446. struct ggml_context * ctx,
  3447. struct ggml_tensor * a,
  3448. int scale_factor) {
  3449. return ggml_upscale_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3]);
  3450. }
  3451. struct ggml_tensor * ggml_upscale_ext(
  3452. struct ggml_context * ctx,
  3453. struct ggml_tensor * a,
  3454. int ne0,
  3455. int ne1,
  3456. int ne2,
  3457. int ne3) {
  3458. return ggml_upscale_impl(ctx, a, ne0, ne1, ne2, ne3);
  3459. }
  3460. // ggml_pad
  3461. struct ggml_tensor * ggml_pad(
  3462. struct ggml_context * ctx,
  3463. struct ggml_tensor * a,
  3464. int p0,
  3465. int p1,
  3466. int p2,
  3467. int p3) {
  3468. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3469. a->ne[0] + p0,
  3470. a->ne[1] + p1,
  3471. a->ne[2] + p2,
  3472. a->ne[3] + p3);
  3473. result->op = GGML_OP_PAD;
  3474. result->src[0] = a;
  3475. return result;
  3476. }
  3477. // ggml_pad_reflect_1d
  3478. struct ggml_tensor * ggml_pad_reflect_1d(
  3479. struct ggml_context * ctx,
  3480. struct ggml_tensor * a,
  3481. int p0,
  3482. int p1) {
  3483. GGML_ASSERT(p0 >= 0);
  3484. GGML_ASSERT(p1 >= 0);
  3485. GGML_ASSERT(p0 < a->ne[0]); // padding length on each size must be less than the
  3486. GGML_ASSERT(p1 < a->ne[0]); // existing length of the dimension being padded
  3487. GGML_ASSERT(ggml_is_contiguous(a));
  3488. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3489. struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
  3490. a->ne[0] + p0 + p1,
  3491. a->ne[1],
  3492. a->ne[2],
  3493. a->ne[3]);
  3494. int32_t params[] = { p0, p1 };
  3495. ggml_set_op_params(result, params, sizeof(params));
  3496. result->op = GGML_OP_PAD_REFLECT_1D;
  3497. result->src[0] = a;
  3498. return result;
  3499. }
  3500. // ggml_arange
  3501. struct ggml_tensor * ggml_arange(
  3502. struct ggml_context * ctx,
  3503. float start,
  3504. float stop,
  3505. float step) {
  3506. GGML_ASSERT(stop > start);
  3507. const int64_t steps = (int64_t) ceilf((stop - start) / step);
  3508. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
  3509. ggml_set_op_params_f32(result, 0, start);
  3510. ggml_set_op_params_f32(result, 1, stop);
  3511. ggml_set_op_params_f32(result, 2, step);
  3512. result->op = GGML_OP_ARANGE;
  3513. return result;
  3514. }
  3515. // ggml_timestep_embedding
  3516. struct ggml_tensor * ggml_timestep_embedding(
  3517. struct ggml_context * ctx,
  3518. struct ggml_tensor * timesteps,
  3519. int dim,
  3520. int max_period) {
  3521. int actual_dim = dim;
  3522. if (dim % 2 != 0) {
  3523. actual_dim = dim + 1;
  3524. }
  3525. struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, actual_dim, timesteps->ne[0]);
  3526. ggml_set_op_params_i32(result, 0, dim);
  3527. ggml_set_op_params_i32(result, 1, max_period);
  3528. result->op = GGML_OP_TIMESTEP_EMBEDDING;
  3529. result->src[0] = timesteps;
  3530. return result;
  3531. }
  3532. // ggml_argsort
  3533. struct ggml_tensor * ggml_argsort(
  3534. struct ggml_context * ctx,
  3535. struct ggml_tensor * a,
  3536. enum ggml_sort_order order) {
  3537. GGML_ASSERT(a->ne[0] <= INT32_MAX);
  3538. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
  3539. ggml_set_op_params_i32(result, 0, (int32_t) order);
  3540. result->op = GGML_OP_ARGSORT;
  3541. result->src[0] = a;
  3542. return result;
  3543. }
  3544. // ggml_top_k
  3545. struct ggml_tensor * ggml_top_k(
  3546. struct ggml_context * ctx,
  3547. struct ggml_tensor * a,
  3548. int k) {
  3549. GGML_ASSERT(a->ne[0] >= k);
  3550. struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
  3551. result = ggml_view_4d(ctx, result,
  3552. k, result->ne[1], result->ne[2], result->ne[3],
  3553. result->nb[1], result->nb[2], result->nb[3],
  3554. 0);
  3555. return result;
  3556. }
  3557. // ggml_flash_attn_ext
  3558. struct ggml_tensor * ggml_flash_attn_ext(
  3559. struct ggml_context * ctx,
  3560. struct ggml_tensor * q,
  3561. struct ggml_tensor * k,
  3562. struct ggml_tensor * v,
  3563. struct ggml_tensor * mask,
  3564. float scale,
  3565. float max_bias,
  3566. float logit_softcap) {
  3567. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3568. // TODO: check if vT can be multiplied by (k*qT)
  3569. if (mask) {
  3570. GGML_ASSERT(ggml_is_contiguous(mask));
  3571. GGML_ASSERT(mask->ne[2] == 1);
  3572. GGML_ASSERT(mask->ne[3] == 1);
  3573. GGML_ASSERT(mask->ne[1] >= GGML_PAD(q->ne[1], GGML_KQ_MASK_PAD) &&
  3574. "the Flash-Attention kernel requires the mask to be padded to GGML_KQ_MASK_PAD and at least n_queries big");
  3575. //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
  3576. }
  3577. if (max_bias > 0.0f) {
  3578. GGML_ASSERT(mask);
  3579. }
  3580. // permute(0, 2, 1, 3)
  3581. int64_t ne[4] = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] };
  3582. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3583. float params[] = { scale, max_bias, logit_softcap };
  3584. ggml_set_op_params(result, params, sizeof(params));
  3585. result->op = GGML_OP_FLASH_ATTN_EXT;
  3586. result->src[0] = q;
  3587. result->src[1] = k;
  3588. result->src[2] = v;
  3589. result->src[3] = mask;
  3590. return result;
  3591. }
  3592. void ggml_flash_attn_ext_set_prec(
  3593. struct ggml_tensor * a,
  3594. enum ggml_prec prec) {
  3595. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3596. const int32_t prec_i32 = (int32_t) prec;
  3597. ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
  3598. }
  3599. enum ggml_prec ggml_flash_attn_ext_get_prec(
  3600. const struct ggml_tensor * a) {
  3601. GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
  3602. const int32_t prec_i32 = ggml_get_op_params_i32(a, 3);
  3603. return (enum ggml_prec) prec_i32;
  3604. }
  3605. // ggml_flash_attn_back
  3606. struct ggml_tensor * ggml_flash_attn_back(
  3607. struct ggml_context * ctx,
  3608. struct ggml_tensor * q,
  3609. struct ggml_tensor * k,
  3610. struct ggml_tensor * v,
  3611. struct ggml_tensor * d,
  3612. bool masked) {
  3613. GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
  3614. GGML_ASSERT(ggml_can_mul_mat(k, q));
  3615. // TODO: check if vT can be multiplied by (k*qT)
  3616. // d shape [D,N,ne2,ne3]
  3617. // q shape [D,N,ne2,ne3]
  3618. // k shape [D,M,kvne2,ne3]
  3619. // v shape [M,D,kvne2,ne3]
  3620. const int64_t D = q->ne[0];
  3621. const int64_t N = q->ne[1];
  3622. const int64_t M = k->ne[1];
  3623. const int64_t ne2 = q->ne[2];
  3624. const int64_t ne3 = q->ne[3];
  3625. const int64_t kvne2 = k->ne[2];
  3626. GGML_ASSERT(k->ne[0] == D);
  3627. GGML_ASSERT(v->ne[0] == M);
  3628. GGML_ASSERT(v->ne[1] == D);
  3629. GGML_ASSERT(d->ne[0] == D);
  3630. GGML_ASSERT(d->ne[1] == N);
  3631. GGML_ASSERT(k->ne[2] == kvne2);
  3632. GGML_ASSERT(k->ne[3] == ne3);
  3633. GGML_ASSERT(v->ne[2] == kvne2);
  3634. GGML_ASSERT(v->ne[3] == ne3);
  3635. GGML_ASSERT(d->ne[2] == ne2);
  3636. GGML_ASSERT(d->ne[3] == ne3);
  3637. GGML_ASSERT(ne2 % kvne2 == 0);
  3638. // store gradients of q, k and v as continuous tensors concatenated in result.
  3639. // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
  3640. const int64_t elem_q = ggml_nelements(q);
  3641. const int64_t elem_k = ggml_nelements(k);
  3642. const int64_t elem_v = ggml_nelements(v);
  3643. enum ggml_type result_type = GGML_TYPE_F32;
  3644. GGML_ASSERT(ggml_blck_size(result_type) == 1);
  3645. const size_t tsize = ggml_type_size(result_type);
  3646. const size_t offs_q = 0;
  3647. const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
  3648. const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
  3649. const size_t end = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
  3650. const size_t nelements = (end + tsize - 1)/tsize;
  3651. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
  3652. int32_t masked_i = masked ? 1 : 0;
  3653. ggml_set_op_params(result, &masked_i, sizeof(masked_i));
  3654. result->op = GGML_OP_FLASH_ATTN_BACK;
  3655. result->src[0] = q;
  3656. result->src[1] = k;
  3657. result->src[2] = v;
  3658. result->src[3] = d;
  3659. return result;
  3660. }
  3661. // ggml_ssm_conv
  3662. struct ggml_tensor * ggml_ssm_conv(
  3663. struct ggml_context * ctx,
  3664. struct ggml_tensor * sx,
  3665. struct ggml_tensor * c) {
  3666. GGML_ASSERT(ggml_is_3d(sx));
  3667. GGML_ASSERT(ggml_is_matrix(c));
  3668. const int64_t d_conv = c->ne[0];
  3669. const int64_t d_inner = c->ne[1];
  3670. const int64_t n_t = sx->ne[0] - d_conv + 1; // tokens per sequence
  3671. const int64_t n_s = sx->ne[2];
  3672. // TODO: maybe support other strides than 1?
  3673. // FIXME: this is always true?
  3674. GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
  3675. GGML_ASSERT(sx->ne[1] == d_inner);
  3676. GGML_ASSERT(n_t >= 0);
  3677. struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
  3678. result->op = GGML_OP_SSM_CONV;
  3679. result->src[0] = sx;
  3680. result->src[1] = c;
  3681. return result;
  3682. }
  3683. // ggml_ssm_scan
  3684. struct ggml_tensor * ggml_ssm_scan(
  3685. struct ggml_context * ctx,
  3686. struct ggml_tensor * s,
  3687. struct ggml_tensor * x,
  3688. struct ggml_tensor * dt,
  3689. struct ggml_tensor * A,
  3690. struct ggml_tensor * B,
  3691. struct ggml_tensor * C) {
  3692. GGML_ASSERT(ggml_is_contiguous(s));
  3693. GGML_ASSERT(ggml_is_contiguous(x));
  3694. GGML_ASSERT(ggml_is_contiguous(dt));
  3695. GGML_ASSERT(ggml_is_contiguous(A));
  3696. GGML_ASSERT(ggml_is_matrix(A));
  3697. GGML_ASSERT(ggml_is_3d(B));
  3698. GGML_ASSERT(ggml_is_3d(s));
  3699. GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
  3700. GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
  3701. GGML_ASSERT(ggml_are_same_shape(x, dt));
  3702. GGML_ASSERT(ggml_are_same_shape(B, C));
  3703. {
  3704. const int64_t d_state = s->ne[0];
  3705. const int64_t d_inner = s->ne[1];
  3706. const int64_t n_seq_tokens = x->ne[1];
  3707. const int64_t n_seqs = x->ne[2];
  3708. GGML_ASSERT(s->ne[2] == n_seqs);
  3709. GGML_ASSERT(x->ne[0] == d_inner);
  3710. GGML_ASSERT(A->ne[0] == d_state);
  3711. GGML_ASSERT(A->ne[1] == d_inner);
  3712. GGML_ASSERT(B->ne[0] == d_state);
  3713. GGML_ASSERT(B->ne[1] == n_seq_tokens);
  3714. GGML_ASSERT(B->ne[2] == n_seqs);
  3715. }
  3716. // concatenated y + ssm_states
  3717. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + ggml_nelements(s));
  3718. result->op = GGML_OP_SSM_SCAN;
  3719. result->src[0] = s;
  3720. result->src[1] = x;
  3721. result->src[2] = dt;
  3722. result->src[3] = A;
  3723. result->src[4] = B;
  3724. result->src[5] = C;
  3725. return result;
  3726. }
  3727. // ggml_win_part
  3728. struct ggml_tensor * ggml_win_part(
  3729. struct ggml_context * ctx,
  3730. struct ggml_tensor * a,
  3731. int w) {
  3732. GGML_ASSERT(a->ne[3] == 1);
  3733. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3734. // padding
  3735. const int px = (w - a->ne[1]%w)%w;
  3736. const int py = (w - a->ne[2]%w)%w;
  3737. const int npx = (px + a->ne[1])/w;
  3738. const int npy = (py + a->ne[2])/w;
  3739. const int np = npx*npy;
  3740. const int64_t ne[4] = { a->ne[0], w, w, np, };
  3741. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3742. int32_t params[] = { npx, npy, w };
  3743. ggml_set_op_params(result, params, sizeof(params));
  3744. result->op = GGML_OP_WIN_PART;
  3745. result->src[0] = a;
  3746. return result;
  3747. }
  3748. // ggml_win_unpart
  3749. struct ggml_tensor * ggml_win_unpart(
  3750. struct ggml_context * ctx,
  3751. struct ggml_tensor * a,
  3752. int w0,
  3753. int h0,
  3754. int w) {
  3755. GGML_ASSERT(a->type == GGML_TYPE_F32);
  3756. const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
  3757. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
  3758. int32_t params[] = { w };
  3759. ggml_set_op_params(result, params, sizeof(params));
  3760. result->op = GGML_OP_WIN_UNPART;
  3761. result->src[0] = a;
  3762. return result;
  3763. }
  3764. // ggml_get_rel_pos
  3765. struct ggml_tensor * ggml_get_rel_pos(
  3766. struct ggml_context * ctx,
  3767. struct ggml_tensor * a,
  3768. int qh,
  3769. int kh) {
  3770. GGML_ASSERT(qh == kh);
  3771. GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
  3772. const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
  3773. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
  3774. result->op = GGML_OP_GET_REL_POS;
  3775. result->src[0] = a;
  3776. return result;
  3777. }
  3778. // ggml_add_rel_pos
  3779. static struct ggml_tensor * ggml_add_rel_pos_impl(
  3780. struct ggml_context * ctx,
  3781. struct ggml_tensor * a,
  3782. struct ggml_tensor * pw,
  3783. struct ggml_tensor * ph,
  3784. bool inplace) {
  3785. GGML_ASSERT(ggml_are_same_shape(pw, ph));
  3786. GGML_ASSERT(ggml_is_contiguous(a));
  3787. GGML_ASSERT(ggml_is_contiguous(pw));
  3788. GGML_ASSERT(ggml_is_contiguous(ph));
  3789. GGML_ASSERT(ph->type == GGML_TYPE_F32);
  3790. GGML_ASSERT(pw->type == GGML_TYPE_F32);
  3791. GGML_ASSERT(pw->ne[3] == a->ne[2]);
  3792. GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
  3793. GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
  3794. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3795. ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
  3796. result->op = GGML_OP_ADD_REL_POS;
  3797. result->src[0] = a;
  3798. result->src[1] = pw;
  3799. result->src[2] = ph;
  3800. return result;
  3801. }
  3802. struct ggml_tensor * ggml_add_rel_pos(
  3803. struct ggml_context * ctx,
  3804. struct ggml_tensor * a,
  3805. struct ggml_tensor * pw,
  3806. struct ggml_tensor * ph) {
  3807. return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
  3808. }
  3809. struct ggml_tensor * ggml_add_rel_pos_inplace(
  3810. struct ggml_context * ctx,
  3811. struct ggml_tensor * a,
  3812. struct ggml_tensor * pw,
  3813. struct ggml_tensor * ph) {
  3814. return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
  3815. }
  3816. // ggml_rwkv_wkv6
  3817. struct ggml_tensor * ggml_rwkv_wkv6(
  3818. struct ggml_context * ctx,
  3819. struct ggml_tensor * k,
  3820. struct ggml_tensor * v,
  3821. struct ggml_tensor * r,
  3822. struct ggml_tensor * tf,
  3823. struct ggml_tensor * td,
  3824. struct ggml_tensor * state) {
  3825. GGML_ASSERT(ggml_is_contiguous(k));
  3826. GGML_ASSERT(ggml_is_contiguous(v));
  3827. GGML_ASSERT(ggml_is_contiguous(r));
  3828. GGML_ASSERT(ggml_is_contiguous(tf));
  3829. GGML_ASSERT(ggml_is_contiguous(td));
  3830. GGML_ASSERT(ggml_is_contiguous(state));
  3831. const int64_t S = k->ne[0];
  3832. const int64_t H = k->ne[1];
  3833. const int64_t n_tokens = k->ne[2];
  3834. const int64_t n_seqs = state->ne[1];
  3835. {
  3836. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3837. GGML_ASSERT(r->ne[0] == S && r->ne[1] == H && r->ne[2] == n_tokens);
  3838. GGML_ASSERT(td->ne[0] == S && td->ne[1] == H && td->ne[2] == n_tokens);
  3839. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3840. }
  3841. // concat output and new_state
  3842. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3843. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3844. result->op = GGML_OP_RWKV_WKV6;
  3845. result->src[0] = k;
  3846. result->src[1] = v;
  3847. result->src[2] = r;
  3848. result->src[3] = tf;
  3849. result->src[4] = td;
  3850. result->src[5] = state;
  3851. return result;
  3852. }
  3853. // ggml_gated_linear_attn
  3854. struct ggml_tensor * ggml_gated_linear_attn(
  3855. struct ggml_context * ctx,
  3856. struct ggml_tensor * k,
  3857. struct ggml_tensor * v,
  3858. struct ggml_tensor * q,
  3859. struct ggml_tensor * g,
  3860. struct ggml_tensor * state,
  3861. float scale) {
  3862. GGML_ASSERT(ggml_is_contiguous(k));
  3863. GGML_ASSERT(ggml_is_contiguous(v));
  3864. GGML_ASSERT(ggml_is_contiguous(q));
  3865. GGML_ASSERT(ggml_is_contiguous(g));
  3866. GGML_ASSERT(ggml_is_contiguous(state));
  3867. const int64_t S = k->ne[0];
  3868. const int64_t H = k->ne[1];
  3869. const int64_t n_tokens = k->ne[2];
  3870. const int64_t n_seqs = state->ne[1];
  3871. {
  3872. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3873. GGML_ASSERT(q->ne[0] == S && q->ne[1] == H && q->ne[2] == n_tokens);
  3874. GGML_ASSERT(g->ne[0] == S && g->ne[1] == H && g->ne[2] == n_tokens);
  3875. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3876. }
  3877. // concat output and new_state
  3878. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3879. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3880. ggml_set_op_params_f32(result, 0, scale);
  3881. result->op = GGML_OP_GATED_LINEAR_ATTN;
  3882. result->src[0] = k;
  3883. result->src[1] = v;
  3884. result->src[2] = q;
  3885. result->src[3] = g;
  3886. result->src[4] = state;
  3887. return result;
  3888. }
  3889. // ggml_rwkv_wkv7
  3890. struct ggml_tensor * ggml_rwkv_wkv7(
  3891. struct ggml_context * ctx,
  3892. struct ggml_tensor * r,
  3893. struct ggml_tensor * w,
  3894. struct ggml_tensor * k,
  3895. struct ggml_tensor * v,
  3896. struct ggml_tensor * a,
  3897. struct ggml_tensor * b,
  3898. struct ggml_tensor * state) {
  3899. GGML_ASSERT(ggml_is_contiguous(r));
  3900. GGML_ASSERT(ggml_is_contiguous(w));
  3901. GGML_ASSERT(ggml_is_contiguous(k));
  3902. GGML_ASSERT(ggml_is_contiguous(v));
  3903. GGML_ASSERT(ggml_is_contiguous(a));
  3904. GGML_ASSERT(ggml_is_contiguous(b));
  3905. GGML_ASSERT(ggml_is_contiguous(state));
  3906. const int64_t S = k->ne[0];
  3907. const int64_t H = k->ne[1];
  3908. const int64_t n_tokens = k->ne[2];
  3909. const int64_t n_seqs = state->ne[1];
  3910. {
  3911. GGML_ASSERT(w->ne[0] == S && w->ne[1] == H && w->ne[2] == n_tokens);
  3912. GGML_ASSERT(k->ne[0] == S && k->ne[1] == H && k->ne[2] == n_tokens);
  3913. GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
  3914. GGML_ASSERT(a->ne[0] == S && a->ne[1] == H && a->ne[2] == n_tokens);
  3915. GGML_ASSERT(b->ne[0] == S && b->ne[1] == H && b->ne[2] == n_tokens);
  3916. GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
  3917. }
  3918. // concat output and new_state
  3919. const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
  3920. struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3921. result->op = GGML_OP_RWKV_WKV7;
  3922. result->src[0] = r;
  3923. result->src[1] = w;
  3924. result->src[2] = k;
  3925. result->src[3] = v;
  3926. result->src[4] = a;
  3927. result->src[5] = b;
  3928. result->src[6] = state;
  3929. return result;
  3930. }
  3931. // ggml_unary
  3932. static struct ggml_tensor * ggml_unary_impl(
  3933. struct ggml_context * ctx,
  3934. struct ggml_tensor * a,
  3935. enum ggml_unary_op op,
  3936. bool inplace) {
  3937. GGML_ASSERT(ggml_is_contiguous_1(a));
  3938. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3939. ggml_set_op_params_i32(result, 0, (int32_t) op);
  3940. result->op = GGML_OP_UNARY;
  3941. result->src[0] = a;
  3942. return result;
  3943. }
  3944. struct ggml_tensor * ggml_unary(
  3945. struct ggml_context * ctx,
  3946. struct ggml_tensor * a,
  3947. enum ggml_unary_op op) {
  3948. return ggml_unary_impl(ctx, a, op, false);
  3949. }
  3950. struct ggml_tensor * ggml_unary_inplace(
  3951. struct ggml_context * ctx,
  3952. struct ggml_tensor * a,
  3953. enum ggml_unary_op op) {
  3954. return ggml_unary_impl(ctx, a, op, true);
  3955. }
  3956. // ggml_map_unary
  3957. static struct ggml_tensor * ggml_map_unary_impl_f32(
  3958. struct ggml_context * ctx,
  3959. struct ggml_tensor * a,
  3960. const ggml_unary_op_f32_t fun,
  3961. bool inplace) {
  3962. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3963. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3964. result->op = GGML_OP_MAP_UNARY;
  3965. result->src[0] = a;
  3966. return result;
  3967. }
  3968. struct ggml_tensor * ggml_map_unary_f32(
  3969. struct ggml_context * ctx,
  3970. struct ggml_tensor * a,
  3971. const ggml_unary_op_f32_t fun) {
  3972. return ggml_map_unary_impl_f32(ctx, a, fun, false);
  3973. }
  3974. struct ggml_tensor * ggml_map_unary_inplace_f32(
  3975. struct ggml_context * ctx,
  3976. struct ggml_tensor * a,
  3977. const ggml_unary_op_f32_t fun) {
  3978. return ggml_map_unary_impl_f32(ctx, a, fun, true);
  3979. }
  3980. // ggml_map_binary
  3981. static struct ggml_tensor * ggml_map_binary_impl_f32(
  3982. struct ggml_context * ctx,
  3983. struct ggml_tensor * a,
  3984. struct ggml_tensor * b,
  3985. const ggml_binary_op_f32_t fun,
  3986. bool inplace) {
  3987. GGML_ASSERT(ggml_are_same_shape(a, b));
  3988. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  3989. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  3990. result->op = GGML_OP_MAP_BINARY;
  3991. result->src[0] = a;
  3992. result->src[1] = b;
  3993. return result;
  3994. }
  3995. struct ggml_tensor * ggml_map_binary_f32(
  3996. struct ggml_context * ctx,
  3997. struct ggml_tensor * a,
  3998. struct ggml_tensor * b,
  3999. const ggml_binary_op_f32_t fun) {
  4000. return ggml_map_binary_impl_f32(ctx, a, b, fun, false);
  4001. }
  4002. struct ggml_tensor * ggml_map_binary_inplace_f32(
  4003. struct ggml_context * ctx,
  4004. struct ggml_tensor * a,
  4005. struct ggml_tensor * b,
  4006. const ggml_binary_op_f32_t fun) {
  4007. return ggml_map_binary_impl_f32(ctx, a, b, fun, true);
  4008. }
  4009. // ggml_map_custom1_f32
  4010. static struct ggml_tensor * ggml_map_custom1_impl_f32(
  4011. struct ggml_context * ctx,
  4012. struct ggml_tensor * a,
  4013. const ggml_custom1_op_f32_t fun,
  4014. bool inplace) {
  4015. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4016. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  4017. result->op = GGML_OP_MAP_CUSTOM1_F32;
  4018. result->src[0] = a;
  4019. return result;
  4020. }
  4021. struct ggml_tensor * ggml_map_custom1_f32(
  4022. struct ggml_context * ctx,
  4023. struct ggml_tensor * a,
  4024. const ggml_custom1_op_f32_t fun) {
  4025. return ggml_map_custom1_impl_f32(ctx, a, fun, false);
  4026. }
  4027. struct ggml_tensor * ggml_map_custom1_inplace_f32(
  4028. struct ggml_context * ctx,
  4029. struct ggml_tensor * a,
  4030. const ggml_custom1_op_f32_t fun) {
  4031. return ggml_map_custom1_impl_f32(ctx, a, fun, true);
  4032. }
  4033. // ggml_map_custom2_f32
  4034. static struct ggml_tensor * ggml_map_custom2_impl_f32(
  4035. struct ggml_context * ctx,
  4036. struct ggml_tensor * a,
  4037. struct ggml_tensor * b,
  4038. const ggml_custom2_op_f32_t fun,
  4039. bool inplace) {
  4040. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4041. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  4042. result->op = GGML_OP_MAP_CUSTOM2_F32;
  4043. result->src[0] = a;
  4044. result->src[1] = b;
  4045. return result;
  4046. }
  4047. struct ggml_tensor * ggml_map_custom2_f32(
  4048. struct ggml_context * ctx,
  4049. struct ggml_tensor * a,
  4050. struct ggml_tensor * b,
  4051. const ggml_custom2_op_f32_t fun) {
  4052. return ggml_map_custom2_impl_f32(ctx, a, b, fun, false);
  4053. }
  4054. struct ggml_tensor * ggml_map_custom2_inplace_f32(
  4055. struct ggml_context * ctx,
  4056. struct ggml_tensor * a,
  4057. struct ggml_tensor * b,
  4058. const ggml_custom2_op_f32_t fun) {
  4059. return ggml_map_custom2_impl_f32(ctx, a, b, fun, true);
  4060. }
  4061. // ggml_map_custom3_f32
  4062. static struct ggml_tensor * ggml_map_custom3_impl_f32(
  4063. struct ggml_context * ctx,
  4064. struct ggml_tensor * a,
  4065. struct ggml_tensor * b,
  4066. struct ggml_tensor * c,
  4067. const ggml_custom3_op_f32_t fun,
  4068. bool inplace) {
  4069. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4070. ggml_set_op_params(result, (const void *) &fun, sizeof(fun));
  4071. result->op = GGML_OP_MAP_CUSTOM3_F32;
  4072. result->src[0] = a;
  4073. result->src[1] = b;
  4074. result->src[2] = c;
  4075. return result;
  4076. }
  4077. struct ggml_tensor * ggml_map_custom3_f32(
  4078. struct ggml_context * ctx,
  4079. struct ggml_tensor * a,
  4080. struct ggml_tensor * b,
  4081. struct ggml_tensor * c,
  4082. const ggml_custom3_op_f32_t fun) {
  4083. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, false);
  4084. }
  4085. struct ggml_tensor * ggml_map_custom3_inplace_f32(
  4086. struct ggml_context * ctx,
  4087. struct ggml_tensor * a,
  4088. struct ggml_tensor * b,
  4089. struct ggml_tensor * c,
  4090. const ggml_custom3_op_f32_t fun) {
  4091. return ggml_map_custom3_impl_f32(ctx, a, b, c, fun, true);
  4092. }
  4093. // ggml_map_custom1
  4094. static struct ggml_tensor * ggml_map_custom1_impl(
  4095. struct ggml_context * ctx,
  4096. struct ggml_tensor * a,
  4097. const ggml_custom1_op_t fun,
  4098. int n_tasks,
  4099. void * userdata,
  4100. bool inplace) {
  4101. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4102. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4103. struct ggml_map_custom1_op_params params = {
  4104. /*.fun =*/ fun,
  4105. /*.n_tasks =*/ n_tasks,
  4106. /*.userdata =*/ userdata
  4107. };
  4108. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4109. result->op = GGML_OP_MAP_CUSTOM1;
  4110. result->src[0] = a;
  4111. return result;
  4112. }
  4113. struct ggml_tensor * ggml_map_custom1(
  4114. struct ggml_context * ctx,
  4115. struct ggml_tensor * a,
  4116. const ggml_custom1_op_t fun,
  4117. int n_tasks,
  4118. void * userdata) {
  4119. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
  4120. }
  4121. struct ggml_tensor * ggml_map_custom1_inplace(
  4122. struct ggml_context * ctx,
  4123. struct ggml_tensor * a,
  4124. const ggml_custom1_op_t fun,
  4125. int n_tasks,
  4126. void * userdata) {
  4127. return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
  4128. }
  4129. // ggml_map_custom2
  4130. static struct ggml_tensor * ggml_map_custom2_impl(
  4131. struct ggml_context * ctx,
  4132. struct ggml_tensor * a,
  4133. struct ggml_tensor * b,
  4134. const ggml_custom2_op_t fun,
  4135. int n_tasks,
  4136. void * userdata,
  4137. bool inplace) {
  4138. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4139. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4140. struct ggml_map_custom2_op_params params = {
  4141. /*.fun =*/ fun,
  4142. /*.n_tasks =*/ n_tasks,
  4143. /*.userdata =*/ userdata
  4144. };
  4145. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4146. result->op = GGML_OP_MAP_CUSTOM2;
  4147. result->src[0] = a;
  4148. result->src[1] = b;
  4149. return result;
  4150. }
  4151. struct ggml_tensor * ggml_map_custom2(
  4152. struct ggml_context * ctx,
  4153. struct ggml_tensor * a,
  4154. struct ggml_tensor * b,
  4155. const ggml_custom2_op_t fun,
  4156. int n_tasks,
  4157. void * userdata) {
  4158. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
  4159. }
  4160. struct ggml_tensor * ggml_map_custom2_inplace(
  4161. struct ggml_context * ctx,
  4162. struct ggml_tensor * a,
  4163. struct ggml_tensor * b,
  4164. const ggml_custom2_op_t fun,
  4165. int n_tasks,
  4166. void * userdata) {
  4167. return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
  4168. }
  4169. // ggml_map_custom3
  4170. static struct ggml_tensor * ggml_map_custom3_impl(
  4171. struct ggml_context * ctx,
  4172. struct ggml_tensor * a,
  4173. struct ggml_tensor * b,
  4174. struct ggml_tensor * c,
  4175. const ggml_custom3_op_t fun,
  4176. int n_tasks,
  4177. void * userdata,
  4178. bool inplace) {
  4179. GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
  4180. struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
  4181. struct ggml_map_custom3_op_params params = {
  4182. /*.fun =*/ fun,
  4183. /*.n_tasks =*/ n_tasks,
  4184. /*.userdata =*/ userdata
  4185. };
  4186. ggml_set_op_params(result, (const void *) &params, sizeof(params));
  4187. result->op = GGML_OP_MAP_CUSTOM3;
  4188. result->src[0] = a;
  4189. result->src[1] = b;
  4190. result->src[2] = c;
  4191. return result;
  4192. }
  4193. struct ggml_tensor * ggml_map_custom3(
  4194. struct ggml_context * ctx,
  4195. struct ggml_tensor * a,
  4196. struct ggml_tensor * b,
  4197. struct ggml_tensor * c,
  4198. const ggml_custom3_op_t fun,
  4199. int n_tasks,
  4200. void * userdata) {
  4201. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
  4202. }
  4203. struct ggml_tensor * ggml_map_custom3_inplace(
  4204. struct ggml_context * ctx,
  4205. struct ggml_tensor * a,
  4206. struct ggml_tensor * b,
  4207. struct ggml_tensor * c,
  4208. const ggml_custom3_op_t fun,
  4209. int n_tasks,
  4210. void * userdata) {
  4211. return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
  4212. }
  4213. // ggml_cross_entropy_loss
  4214. struct ggml_tensor * ggml_cross_entropy_loss(
  4215. struct ggml_context * ctx,
  4216. struct ggml_tensor * a,
  4217. struct ggml_tensor * b) {
  4218. GGML_ASSERT(ggml_are_same_shape(a, b));
  4219. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
  4220. result->op = GGML_OP_CROSS_ENTROPY_LOSS;
  4221. result->src[0] = a;
  4222. result->src[1] = b;
  4223. return result;
  4224. }
  4225. // ggml_cross_entropy_loss_back
  4226. struct ggml_tensor * ggml_cross_entropy_loss_back(
  4227. struct ggml_context * ctx,
  4228. struct ggml_tensor * a,
  4229. struct ggml_tensor * b,
  4230. struct ggml_tensor * c) {
  4231. GGML_ASSERT(ggml_is_scalar(a));
  4232. GGML_ASSERT(ggml_are_same_shape(b, c));
  4233. struct ggml_tensor * result = ggml_dup_tensor(ctx, b);
  4234. result->op = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
  4235. result->src[0] = a;
  4236. result->src[1] = b;
  4237. result->src[2] = c;
  4238. return result;
  4239. }
  4240. // opt_step_adamw
  4241. struct ggml_tensor * ggml_opt_step_adamw(
  4242. struct ggml_context * ctx,
  4243. struct ggml_tensor * a,
  4244. struct ggml_tensor * grad,
  4245. struct ggml_tensor * m,
  4246. struct ggml_tensor * v,
  4247. struct ggml_tensor * adamw_params) {
  4248. GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
  4249. GGML_ASSERT(ggml_are_same_shape(a, grad));
  4250. GGML_ASSERT(ggml_are_same_shape(a, m));
  4251. GGML_ASSERT(ggml_are_same_shape(a, v));
  4252. GGML_ASSERT(adamw_params->type == GGML_TYPE_F32);
  4253. GGML_ASSERT(ggml_nelements(adamw_params) == 7);
  4254. struct ggml_tensor * result = ggml_view_tensor(ctx, a);
  4255. result->op = GGML_OP_OPT_STEP_ADAMW;
  4256. result->src[0] = a;
  4257. result->src[1] = grad;
  4258. result->src[2] = m;
  4259. result->src[3] = v;
  4260. result->src[4] = adamw_params;
  4261. return result;
  4262. }
  4263. ////////////////////////////////////////////////////////////////////////////////
  4264. struct ggml_hash_set ggml_hash_set_new(size_t size) {
  4265. size = ggml_hash_size(size);
  4266. struct ggml_hash_set result;
  4267. result.size = size;
  4268. result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
  4269. result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
  4270. return result;
  4271. }
  4272. void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
  4273. memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
  4274. }
  4275. void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
  4276. GGML_FREE(hash_set->used);
  4277. GGML_FREE(hash_set->keys);
  4278. }
  4279. size_t ggml_hash_size(size_t min_sz) {
  4280. // next primes after powers of two
  4281. static const size_t primes[] = {
  4282. 2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
  4283. 2053, 4099, 8209, 16411, 32771, 65537, 131101,
  4284. 262147, 524309, 1048583, 2097169, 4194319, 8388617,
  4285. 16777259, 33554467, 67108879, 134217757, 268435459,
  4286. 536870923, 1073741827, 2147483659
  4287. };
  4288. static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
  4289. // find the smallest prime that is larger or equal than min_sz
  4290. size_t l = 0;
  4291. size_t r = n_primes;
  4292. while (l < r) {
  4293. size_t m = (l + r)/2;
  4294. if (primes[m] < min_sz) {
  4295. l = m + 1;
  4296. } else {
  4297. r = m;
  4298. }
  4299. }
  4300. size_t sz = l < n_primes ? primes[l] : min_sz | 1;
  4301. return sz;
  4302. }
  4303. struct hash_map {
  4304. struct ggml_hash_set set;
  4305. struct ggml_tensor ** vals;
  4306. };
  4307. static struct hash_map * ggml_new_hash_map(size_t size) {
  4308. struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
  4309. result->set = ggml_hash_set_new(size);
  4310. result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
  4311. return result;
  4312. }
  4313. static void ggml_hash_map_free(struct hash_map * map) {
  4314. ggml_hash_set_free(&map->set);
  4315. GGML_FREE(map->vals);
  4316. GGML_FREE(map);
  4317. }
  4318. // utility functions to change gradients
  4319. // isrc is the index of tensor in cgraph->visited_has_set.keys
  4320. // the corresponding gradient (accumulators) are also at position isrc
  4321. // if tensor has a gradient accumulator, modify that accumulator in-place
  4322. // else if there is no gradient for tensor, set the corresponding value
  4323. // else, just add/subtract/etc. the gradients
  4324. static void ggml_add_or_set(
  4325. struct ggml_context * ctx,
  4326. struct ggml_cgraph * cgraph,
  4327. size_t isrc,
  4328. struct ggml_tensor * tensor) {
  4329. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4330. GGML_ASSERT(src);
  4331. if (cgraph->grads[isrc]) {
  4332. cgraph->grads[isrc] = ggml_add_impl(ctx, cgraph->grads[isrc], tensor, /*inplace =*/ cgraph->grad_accs[isrc]);
  4333. } else {
  4334. cgraph->grads[isrc] = tensor;
  4335. }
  4336. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4337. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4338. }
  4339. static void ggml_acc_or_set(
  4340. struct ggml_context * ctx,
  4341. struct ggml_cgraph * cgraph,
  4342. size_t isrc,
  4343. struct ggml_tensor * tensor,
  4344. const size_t nb1,
  4345. const size_t nb2,
  4346. const size_t nb3,
  4347. const size_t offset) {
  4348. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4349. GGML_ASSERT(src);
  4350. if (cgraph->grads[isrc]) {
  4351. cgraph->grads[isrc] = ggml_acc_impl(ctx, cgraph->grads[isrc], tensor, nb1, nb2, nb3, offset, cgraph->grad_accs[isrc]);
  4352. } else {
  4353. struct ggml_tensor * a_zero = ggml_scale(ctx, src, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
  4354. cgraph->grads[isrc] = ggml_acc_impl(ctx, a_zero, tensor, nb1, nb2, nb3, offset, false);
  4355. }
  4356. ggml_format_name(cgraph->grads[isrc], "grad for %s", cgraph->visited_hash_set.keys[isrc]->name);
  4357. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4358. }
  4359. static void ggml_add1_or_set(
  4360. struct ggml_context * ctx,
  4361. struct ggml_cgraph * cgraph,
  4362. size_t isrc,
  4363. struct ggml_tensor * tensor) {
  4364. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4365. GGML_ASSERT(src);
  4366. if (cgraph->grads[isrc]) {
  4367. cgraph->grads[isrc] = ggml_add1_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4368. } else {
  4369. cgraph->grads[isrc] = ggml_repeat(ctx, tensor, src);
  4370. }
  4371. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4372. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4373. }
  4374. static void ggml_sub_or_set(
  4375. struct ggml_context * ctx,
  4376. struct ggml_cgraph * cgraph,
  4377. size_t isrc,
  4378. struct ggml_tensor * tensor) {
  4379. struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
  4380. GGML_ASSERT(src);
  4381. if (cgraph->grads[isrc]) {
  4382. cgraph->grads[isrc] = ggml_sub_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
  4383. } else {
  4384. cgraph->grads[isrc] = ggml_neg(ctx, tensor);
  4385. }
  4386. ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
  4387. ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
  4388. }
  4389. static void ggml_compute_backward(
  4390. struct ggml_context * ctx, struct ggml_cgraph * cgraph, int i, const bool * grads_needed) {
  4391. struct ggml_tensor * tensor = cgraph->nodes[i];
  4392. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, tensor);
  4393. if (!grad) {
  4394. return;
  4395. }
  4396. struct ggml_tensor * src0 = tensor->src[0];
  4397. struct ggml_tensor * src1 = tensor->src[1];
  4398. struct ggml_tensor * src2 = tensor->src[2];
  4399. struct ggml_hash_set * hash_set = &cgraph->visited_hash_set;
  4400. const size_t isrc0 = src0 ? ggml_hash_find(hash_set, src0) : (size_t) -1;
  4401. const size_t isrc1 = src1 ? ggml_hash_find(hash_set, src1) : (size_t) -1;
  4402. const size_t isrc2 = src2 ? ggml_hash_find(hash_set, src2) : (size_t) -1;
  4403. const bool src0_needs_grads = src0 && isrc0 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc0) && grads_needed[isrc0];
  4404. const bool src1_needs_grads = src1 && isrc1 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc1) && grads_needed[isrc1];
  4405. const bool src2_needs_grads = src2 && isrc2 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc2) && grads_needed[isrc2];
  4406. switch (tensor->op) {
  4407. case GGML_OP_DUP: {
  4408. if (src0_needs_grads) {
  4409. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4410. }
  4411. } break;
  4412. case GGML_OP_ADD: {
  4413. if (src0_needs_grads) {
  4414. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4415. }
  4416. if (src1_needs_grads) {
  4417. struct ggml_tensor * tmp = grad;
  4418. if (!ggml_are_same_shape(src0, src1)) {
  4419. tmp = ggml_repeat_back(ctx, tmp, src1);
  4420. }
  4421. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4422. }
  4423. } break;
  4424. case GGML_OP_ADD1: {
  4425. if (src0_needs_grads) {
  4426. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4427. }
  4428. if (src1_needs_grads) {
  4429. ggml_add_or_set(ctx, cgraph, isrc1, ggml_mean(ctx, grad)); // TODO: should probably be sum instead of mean
  4430. }
  4431. } break;
  4432. case GGML_OP_ACC: {
  4433. if (src0_needs_grads) {
  4434. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4435. }
  4436. if (src1_needs_grads) {
  4437. const size_t nb1 = ((int32_t *) tensor->op_params)[0];
  4438. const size_t nb2 = ((int32_t *) tensor->op_params)[1];
  4439. const size_t nb3 = ((int32_t *) tensor->op_params)[2];
  4440. const size_t offset = ((int32_t *) tensor->op_params)[3];
  4441. struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
  4442. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4443. nb1, nb2, nb3, offset);
  4444. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4445. }
  4446. } break;
  4447. case GGML_OP_SUB: {
  4448. if (src0_needs_grads) {
  4449. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4450. }
  4451. if (src1_needs_grads) {
  4452. ggml_sub_or_set(ctx, cgraph, isrc1, grad);
  4453. }
  4454. } break;
  4455. case GGML_OP_MUL: {
  4456. if (src0_needs_grads) {
  4457. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, src1));
  4458. }
  4459. if (src1_needs_grads) {
  4460. struct ggml_tensor * tmp = ggml_mul(ctx, src0, grad);
  4461. if (!ggml_are_same_shape(src0, src1)) {
  4462. tmp = ggml_repeat_back(ctx, tmp, src1);
  4463. }
  4464. ggml_add_or_set(ctx, cgraph, isrc1, tmp);
  4465. }
  4466. } break;
  4467. case GGML_OP_DIV: {
  4468. if (src0_needs_grads) {
  4469. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src1));
  4470. }
  4471. if (src1_needs_grads) {
  4472. ggml_sub_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1)));
  4473. }
  4474. } break;
  4475. case GGML_OP_SQR: {
  4476. if (src0_needs_grads) {
  4477. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_mul(ctx, src0, grad), 2.0f));
  4478. }
  4479. } break;
  4480. case GGML_OP_SQRT: {
  4481. if (src0_needs_grads) {
  4482. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_div(ctx, grad, tensor), 0.5f));
  4483. }
  4484. } break;
  4485. case GGML_OP_LOG: {
  4486. if (src0_needs_grads) {
  4487. ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src0));
  4488. }
  4489. } break;
  4490. case GGML_OP_SIN: {
  4491. if (src0_needs_grads) {
  4492. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_cos(ctx, src0)));
  4493. }
  4494. } break;
  4495. case GGML_OP_COS: {
  4496. if (src0_needs_grads) {
  4497. ggml_sub_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sin(ctx, src0)));
  4498. }
  4499. } break;
  4500. case GGML_OP_SUM: {
  4501. if (src0_needs_grads) {
  4502. ggml_add1_or_set(ctx, cgraph, isrc0, grad);
  4503. }
  4504. } break;
  4505. case GGML_OP_SUM_ROWS: {
  4506. if (src0_needs_grads) {
  4507. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4508. }
  4509. } break;
  4510. case GGML_OP_MEAN: {
  4511. if (src0_needs_grads) {
  4512. ggml_add1_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], false));
  4513. }
  4514. } break;
  4515. case GGML_OP_REPEAT: {
  4516. if (src0_needs_grads) {
  4517. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat_back(ctx, grad, src0));
  4518. }
  4519. } break;
  4520. case GGML_OP_REPEAT_BACK: {
  4521. if (src0_needs_grads) {
  4522. ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
  4523. }
  4524. } break;
  4525. case GGML_OP_RMS_NORM: {
  4526. if (src0_needs_grads) {
  4527. float eps;
  4528. memcpy(&eps, tensor->op_params, sizeof(float));
  4529. ggml_add_or_set(ctx, cgraph, isrc0, ggml_rms_norm_back(ctx, grad, src0, eps));
  4530. }
  4531. } break;
  4532. case GGML_OP_MUL_MAT: {
  4533. // https://cs231n.github.io/optimization-2/#staged
  4534. // # forward pass
  4535. // s0 = np.random.randn(5, 10)
  4536. // s1 = np.random.randn(10, 3)
  4537. // t = s0.dot(s1)
  4538. // # now suppose we had the gradient on t from above in the circuit
  4539. // dt = np.random.randn(*t.shape) # same shape as t
  4540. // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
  4541. // ds1 = t.T.dot(dt)
  4542. // tensor.shape [m,p,qq,rr]
  4543. // src0.shape [n,m,q1,r1]
  4544. // src1.shape [n,p,qq,rr]
  4545. if (src0_needs_grads) {
  4546. GGML_ASSERT(grad->ne[2] == src1->ne[2]);
  4547. GGML_ASSERT(grad->ne[3] == src1->ne[3]);
  4548. struct ggml_tensor * tmp =
  4549. ggml_out_prod(ctx, // [n,m,qq,rr]
  4550. src1, // [n,p,qq,rr]
  4551. grad); // [m,p,qq,rr]
  4552. if (!ggml_are_same_shape(tmp, src0)) {
  4553. GGML_ASSERT(tmp->ne[0] == src0->ne[0]);
  4554. GGML_ASSERT(tmp->ne[1] == src0->ne[1]);
  4555. GGML_ASSERT(tmp->ne[3] == 1);
  4556. const int64_t nr2 = tmp->ne[2] / src0->ne[2];
  4557. const size_t nb2 = tmp->nb[2] * nr2;
  4558. const size_t nb3 = tmp->nb[2];
  4559. tmp = ggml_view_4d(ctx, tmp, src0->ne[0], src0->ne[1], src0->ne[2], nr2, tmp->nb[1], nb2, nb3, 0);
  4560. tmp = ggml_repeat_back(ctx, tmp, src0);
  4561. }
  4562. ggml_add_or_set(ctx, cgraph, isrc0, tmp);
  4563. }
  4564. if (src1_needs_grads) {
  4565. ggml_add_or_set(ctx, cgraph, isrc1,
  4566. // ggml_mul_mat(ctx, // [n,p,qq,rr]
  4567. // ggml_cont(ctx, // [m,n,q1,r1]
  4568. // ggml_transpose(ctx, src0)), // [m,n,q1,r1]
  4569. // grad), // [m,p,qq,rr]
  4570. // when src0 is bigger than tensor->grad (this is mostly the case in llama),
  4571. // avoid transpose of src0, rather transpose smaller tensor->grad
  4572. // and then use ggml_out_prod
  4573. ggml_out_prod(ctx, // [n,p,qq,rr]
  4574. src0, // [n,m,q1,r1]
  4575. ggml_transpose(ctx, // [p,m,qq,rr]
  4576. grad))); // [m,p,qq,rr]
  4577. }
  4578. } break;
  4579. case GGML_OP_SCALE: {
  4580. if (src0_needs_grads) {
  4581. float s;
  4582. memcpy(&s, tensor->op_params, sizeof(float));
  4583. ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, s, false));
  4584. }
  4585. } break;
  4586. case GGML_OP_SET: {
  4587. const size_t nb1 = ((const int32_t *) tensor->op_params)[0];
  4588. const size_t nb2 = ((const int32_t *) tensor->op_params)[1];
  4589. const size_t nb3 = ((const int32_t *) tensor->op_params)[2];
  4590. const size_t offset = ((const int32_t *) tensor->op_params)[3];
  4591. struct ggml_tensor * tensor_grad_view = NULL;
  4592. if (src0_needs_grads || src1_needs_grads) {
  4593. GGML_ASSERT(src0->type == tensor->type);
  4594. GGML_ASSERT(!cgraph->grads[isrc0] || cgraph->grads[isrc0]->type == grad->type);
  4595. GGML_ASSERT(!cgraph->grads[isrc1] || !src1_needs_grads || cgraph->grads[isrc1]->type == grad->type);
  4596. tensor_grad_view = ggml_view_4d(ctx,
  4597. grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
  4598. nb1, nb2, nb3, offset);
  4599. }
  4600. if (src0_needs_grads) {
  4601. struct ggml_tensor * tmp = ggml_neg(ctx, tensor_grad_view);
  4602. ggml_add_or_set(ctx, cgraph, isrc0, ggml_acc_impl(ctx, grad, tmp, nb1, nb2, nb3, offset, false));
  4603. }
  4604. if (src1_needs_grads) {
  4605. ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
  4606. }
  4607. } break;
  4608. case GGML_OP_CPY: {
  4609. // cpy overwrites value of src1 by src0 and returns view(src1)
  4610. // the overwriting is mathematically equivalent to:
  4611. // tensor = src0 * 1 + src1 * 0
  4612. if (src0_needs_grads) {
  4613. // dsrc0 = dtensor * 1
  4614. ggml_add_or_set(ctx, cgraph, isrc0, grad);
  4615. }
  4616. if (src1_needs_grads) {
  4617. // dsrc1 = dtensor * 0 -> noop
  4618. }
  4619. } break;
  4620. case GGML_OP_CONT: {
  4621. // same as cpy
  4622. if (src0_needs_grads) {
  4623. GGML_ASSERT(!cgraph->grads[isrc0] || ggml_is_contiguous(cgraph->grads[isrc0]));
  4624. GGML_ASSERT(ggml_is_contiguous(grad));
  4625. GGML_ASSERT(ggml_nelements(tensor) == ggml_nelements(src0));
  4626. ggml_add_or_set(ctx, cgraph, isrc0,
  4627. ggml_are_same_shape(tensor, src0) ? grad : ggml_reshape(ctx, grad, src0));
  4628. }
  4629. } break;
  4630. case GGML_OP_RESHAPE: {
  4631. if (src0_needs_grads) {
  4632. struct ggml_tensor * grad_cont = ggml_is_contiguous(grad) ? grad : ggml_cont(ctx, grad);
  4633. ggml_add_or_set(ctx, cgraph, isrc0, ggml_reshape(ctx, grad_cont, src0));
  4634. }
  4635. } break;
  4636. case GGML_OP_VIEW: {
  4637. if (src0_needs_grads) {
  4638. size_t offset;
  4639. memcpy(&offset, tensor->op_params, sizeof(offset));
  4640. size_t nb1 = tensor->nb[1];
  4641. size_t nb2 = tensor->nb[2];
  4642. size_t nb3 = tensor->nb[3];
  4643. if (cgraph->grads[isrc0] && src0->type != cgraph->grads[isrc0]->type) {
  4644. // gradient is typically F32, but src0 could be other type
  4645. size_t ng = ggml_element_size(cgraph->grads[isrc0]);
  4646. size_t n0 = ggml_element_size(src0);
  4647. GGML_ASSERT(offset % n0 == 0);
  4648. GGML_ASSERT(nb1 % n0 == 0);
  4649. GGML_ASSERT(nb2 % n0 == 0);
  4650. GGML_ASSERT(nb3 % n0 == 0);
  4651. offset = (offset / n0) * ng;
  4652. nb1 = (nb1 / n0) * ng;
  4653. nb2 = (nb2 / n0) * ng;
  4654. nb3 = (nb3 / n0) * ng;
  4655. }
  4656. ggml_acc_or_set(ctx, cgraph, isrc0, grad, nb1, nb2, nb3, offset);
  4657. }
  4658. } break;
  4659. case GGML_OP_PERMUTE: {
  4660. if (src0_needs_grads) {
  4661. const int32_t * axes = (const int32_t *) tensor->op_params;
  4662. const int axis0 = axes[0] & 0x3;
  4663. const int axis1 = axes[1] & 0x3;
  4664. const int axis2 = axes[2] & 0x3;
  4665. const int axis3 = axes[3] & 0x3;
  4666. int axb[4] = {0,0,0,0}; // axes backward
  4667. axb[axis0] = 0;
  4668. axb[axis1] = 1;
  4669. axb[axis2] = 2;
  4670. axb[axis3] = 3;
  4671. ggml_add_or_set(ctx, cgraph, isrc0, ggml_permute(ctx, grad, axb[0], axb[1], axb[2], axb[3]));
  4672. }
  4673. } break;
  4674. case GGML_OP_TRANSPOSE: {
  4675. if (src0_needs_grads) {
  4676. ggml_add_or_set(ctx, cgraph, isrc0, ggml_transpose(ctx, grad));
  4677. }
  4678. } break;
  4679. case GGML_OP_GET_ROWS: {
  4680. if (src0_needs_grads) {
  4681. ggml_add_or_set(ctx, cgraph, isrc0, ggml_get_rows_back(ctx, grad, src1, src0));
  4682. }
  4683. if (src1_needs_grads) {
  4684. // noop
  4685. }
  4686. } break;
  4687. case GGML_OP_DIAG_MASK_INF: {
  4688. if (src0_needs_grads) {
  4689. /* ggml_diag_mask_inf_impl() shouldn't be here */
  4690. /* ref: https://github.com/ggerganov/llama.cpp/pull/4203#discussion_r1412377992 */
  4691. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4692. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4693. }
  4694. } break;
  4695. case GGML_OP_DIAG_MASK_ZERO: {
  4696. if (src0_needs_grads) {
  4697. const int n_past = ((const int32_t *) tensor->op_params)[0];
  4698. ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
  4699. }
  4700. } break;
  4701. case GGML_OP_SOFT_MAX: {
  4702. if (src0_needs_grads) {
  4703. float scale = 1.0f;
  4704. float max_bias = 0.0f;
  4705. memcpy(&scale, (const float *) tensor->op_params + 0, sizeof(float));
  4706. memcpy(&max_bias, (const float *) tensor->op_params + 1, sizeof(float));
  4707. ggml_add_or_set(ctx, cgraph, isrc0, ggml_soft_max_ext_back(ctx, grad, tensor, scale, max_bias));
  4708. }
  4709. GGML_ASSERT((!src1 || !src1_needs_grads) && "backward pass for softmax mask not implemented");
  4710. } break;
  4711. case GGML_OP_ROPE: {
  4712. if (src0_needs_grads) {
  4713. //const int n_past = ((int32_t *) tensor->op_params)[0];
  4714. const int n_dims = ((const int32_t *) tensor->op_params)[1];
  4715. const int mode = ((const int32_t *) tensor->op_params)[2];
  4716. //const int n_ctx = ((int32_t *) tensor->op_params)[3];
  4717. const int n_ctx_orig = ((const int32_t *) tensor->op_params)[4];
  4718. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  4719. int sections[4] = {0, 0, 0, 0};
  4720. memcpy(&freq_base, (const float *) tensor->op_params + 5, sizeof(float));
  4721. memcpy(&freq_scale, (const float *) tensor->op_params + 6, sizeof(float));
  4722. memcpy(&ext_factor, (const float *) tensor->op_params + 7, sizeof(float));
  4723. memcpy(&attn_factor, (const float *) tensor->op_params + 8, sizeof(float));
  4724. memcpy(&beta_fast, (const float *) tensor->op_params + 9, sizeof(float));
  4725. memcpy(&beta_slow, (const float *) tensor->op_params + 10, sizeof(float));
  4726. memcpy(&sections, tensor->op_params + 11, sizeof(sections));
  4727. struct ggml_tensor * rope_back = grad->ne[2] == src1->ne[0] ?
  4728. ggml_rope_ext_back(ctx, grad, src1, src2, n_dims,
  4729. mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow) :
  4730. ggml_rope_multi_back(ctx, grad, src1, src2, n_dims, sections,
  4731. mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  4732. ggml_add_or_set(ctx, cgraph, isrc0, rope_back);
  4733. }
  4734. GGML_ASSERT((!src2 || !src2_needs_grads) && "gradients for freq factors not implemented");
  4735. } break;
  4736. case GGML_OP_IM2COL: {
  4737. if (src1_needs_grads) {
  4738. const int32_t s0 = ggml_get_op_params_i32(tensor, 0);
  4739. const int32_t s1 = ggml_get_op_params_i32(tensor, 1);
  4740. const int32_t p0 = ggml_get_op_params_i32(tensor, 2);
  4741. const int32_t p1 = ggml_get_op_params_i32(tensor, 3);
  4742. const int32_t d0 = ggml_get_op_params_i32(tensor, 4);
  4743. const int32_t d1 = ggml_get_op_params_i32(tensor, 5);
  4744. const bool is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
  4745. ggml_add_or_set(ctx, cgraph, isrc1, ggml_im2col_back(ctx, grad, src0, src1->ne, s0, s1, p0, p1, d0, d1, is_2D));
  4746. }
  4747. } break;
  4748. case GGML_OP_POOL_2D: {
  4749. if (src0_needs_grads) {
  4750. const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
  4751. const int32_t k0 = ggml_get_op_params_i32(tensor, 1);
  4752. const int32_t k1 = ggml_get_op_params_i32(tensor, 2);
  4753. const int32_t s0 = ggml_get_op_params_i32(tensor, 3);
  4754. const int32_t s1 = ggml_get_op_params_i32(tensor, 4);
  4755. const int32_t p0 = ggml_get_op_params_i32(tensor, 5);
  4756. const int32_t p1 = ggml_get_op_params_i32(tensor, 6);
  4757. ggml_add_or_set(ctx, cgraph, isrc0, ggml_pool_2d_back(ctx, grad, src0, op, k0, k1, s0, s1, p0, p1));
  4758. }
  4759. } break;
  4760. case GGML_OP_WIN_PART:
  4761. case GGML_OP_WIN_UNPART:
  4762. case GGML_OP_UNARY: {
  4763. switch (ggml_get_unary_op(tensor)) {
  4764. case GGML_UNARY_OP_ABS: {
  4765. if (src0_needs_grads) {
  4766. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_sgn(ctx, src0), grad));
  4767. }
  4768. } break;
  4769. case GGML_UNARY_OP_SGN: {
  4770. // noop
  4771. } break;
  4772. case GGML_UNARY_OP_NEG: {
  4773. if (src0_needs_grads) {
  4774. ggml_sub_or_set(ctx, cgraph, isrc0, grad);
  4775. }
  4776. } break;
  4777. case GGML_UNARY_OP_STEP: {
  4778. // noop
  4779. } break;
  4780. case GGML_UNARY_OP_RELU: {
  4781. if (src0_needs_grads) {
  4782. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_step(ctx, src0), grad));
  4783. }
  4784. } break;
  4785. case GGML_UNARY_OP_SILU: {
  4786. if (src0_needs_grads) {
  4787. ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0));
  4788. }
  4789. } break;
  4790. case GGML_UNARY_OP_EXP: {
  4791. if (src0_needs_grads) {
  4792. ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad));
  4793. }
  4794. } break;
  4795. default: {
  4796. fprintf(stderr, "%s: unsupported unary op for backward pass: %s\n",
  4797. __func__, ggml_unary_op_name(ggml_get_unary_op(tensor)));
  4798. GGML_ABORT("fatal error");
  4799. } //break;
  4800. }
  4801. } break;
  4802. case GGML_OP_CROSS_ENTROPY_LOSS: {
  4803. if (src0_needs_grads) {
  4804. ggml_add_or_set(ctx, cgraph, isrc0, ggml_cross_entropy_loss_back(ctx, grad, src0, src1));
  4805. }
  4806. GGML_ASSERT(!src1_needs_grads && "backward pass for labels not implemented");
  4807. } break;
  4808. case GGML_OP_NONE: {
  4809. // noop
  4810. } break;
  4811. case GGML_OP_COUNT:
  4812. default: {
  4813. fprintf(stderr, "%s: unsupported ggml op for backward pass: %s\n", __func__, ggml_op_name(tensor->op));
  4814. GGML_ABORT("fatal error");
  4815. } //break;
  4816. }
  4817. GGML_ASSERT(!src0_needs_grads || ggml_are_same_shape(src0, cgraph->grads[isrc0]));
  4818. GGML_ASSERT(!src1_needs_grads || ggml_are_same_shape(src1, cgraph->grads[isrc1]));
  4819. GGML_ASSERT(!src2_needs_grads || ggml_are_same_shape(src2, cgraph->grads[isrc2]));
  4820. }
  4821. static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
  4822. // check if already visited
  4823. if (ggml_hash_insert(&cgraph->visited_hash_set, node) == GGML_HASHSET_ALREADY_EXISTS) {
  4824. return;
  4825. }
  4826. for (int i = 0; i < GGML_MAX_SRC; ++i) {
  4827. const int k =
  4828. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
  4829. (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
  4830. /* unknown order, just fall back to using i*/ i;
  4831. if (node->src[k]) {
  4832. ggml_visit_parents(cgraph, node->src[k]);
  4833. }
  4834. }
  4835. if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
  4836. // reached a leaf node, not part of the gradient graph (e.g. a constant)
  4837. GGML_ASSERT(cgraph->n_leafs < cgraph->size);
  4838. if (strlen(node->name) == 0) {
  4839. ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
  4840. }
  4841. cgraph->leafs[cgraph->n_leafs] = node;
  4842. cgraph->n_leafs++;
  4843. } else {
  4844. GGML_ASSERT(cgraph->n_nodes < cgraph->size);
  4845. if (strlen(node->name) == 0) {
  4846. ggml_format_name(node, "node_%d", cgraph->n_nodes);
  4847. }
  4848. cgraph->nodes[cgraph->n_nodes] = node;
  4849. cgraph->n_nodes++;
  4850. }
  4851. }
  4852. static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
  4853. if (!expand) {
  4854. // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
  4855. ggml_graph_clear(cgraph);
  4856. }
  4857. const int n0 = cgraph->n_nodes;
  4858. ggml_visit_parents(cgraph, tensor);
  4859. const int n_new = cgraph->n_nodes - n0;
  4860. GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
  4861. if (n_new > 0) {
  4862. // the last added node should always be starting point
  4863. GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
  4864. }
  4865. }
  4866. void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  4867. ggml_build_forward_impl(cgraph, tensor, true);
  4868. }
  4869. void ggml_build_backward_expand(
  4870. struct ggml_context * ctx_static,
  4871. struct ggml_context * ctx_compute,
  4872. struct ggml_cgraph * cgraph,
  4873. bool accumulate) {
  4874. GGML_ASSERT(cgraph->n_nodes > 0);
  4875. GGML_ASSERT(cgraph->grads);
  4876. GGML_ASSERT(cgraph->grad_accs);
  4877. const int n_nodes_f = cgraph->n_nodes;
  4878. memset(cgraph->grads, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4879. memset(cgraph->grad_accs, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
  4880. bool * grads_needed = calloc(cgraph->visited_hash_set.size, sizeof(bool));
  4881. {
  4882. bool any_params = false;
  4883. bool any_loss = false;
  4884. for (int i = 0; i < n_nodes_f; ++i) {
  4885. struct ggml_tensor * node = cgraph->nodes[i];
  4886. any_params = any_params || (node->flags & GGML_TENSOR_FLAG_PARAM);
  4887. any_loss = any_loss || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4888. }
  4889. GGML_ASSERT(any_params && "no trainable parameters found, did you forget to call ggml_set_param?");
  4890. GGML_ASSERT(any_loss && "no training loss found, did you forget to call ggml_set_loss?");
  4891. }
  4892. for (int i = 0; i < n_nodes_f; ++i) {
  4893. struct ggml_tensor * node = cgraph->nodes[i];
  4894. if (node->type == GGML_TYPE_I32) {
  4895. continue;
  4896. }
  4897. bool node_needs_grad = (node->flags & GGML_TENSOR_FLAG_PARAM) || (node->flags & GGML_TENSOR_FLAG_LOSS);
  4898. bool ignore_src[GGML_MAX_SRC] = {false};
  4899. switch (node->op) {
  4900. // gradients in node->src[0] for one reason or another have no effect on output gradients
  4901. case GGML_OP_IM2COL: // only used for its shape
  4902. case GGML_OP_IM2COL_BACK: // same as IM2COL
  4903. ignore_src[0] = true;
  4904. break;
  4905. case GGML_OP_UNARY: {
  4906. const enum ggml_unary_op uop = ggml_get_unary_op(node);
  4907. // SGN and STEP unary ops are piecewise constant
  4908. if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
  4909. ignore_src[0] = true;
  4910. }
  4911. } break;
  4912. // gradients in node->src[1] for one reason or another have no effect on output gradients
  4913. case GGML_OP_CPY: // gradients in CPY target are irrelevant
  4914. case GGML_OP_GET_ROWS: // row indices not differentiable
  4915. case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
  4916. case GGML_OP_ROPE: // positions not differentiable
  4917. ignore_src[1] = true;
  4918. break;
  4919. default:
  4920. break;
  4921. }
  4922. for (int j = 0; j < GGML_MAX_SRC; ++j) {
  4923. if (!node->src[j] || ignore_src[j] || !grads_needed[ggml_hash_find(&cgraph->visited_hash_set, node->src[j])]) {
  4924. continue;
  4925. }
  4926. GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
  4927. node_needs_grad = true;
  4928. break;
  4929. }
  4930. if (!node_needs_grad) {
  4931. continue;
  4932. }
  4933. // inplace operations are currently not supported
  4934. GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
  4935. node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
  4936. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  4937. GGML_ASSERT(igrad != GGML_HASHSET_FULL);
  4938. GGML_ASSERT(ggml_bitset_get(cgraph->visited_hash_set.used, igrad));
  4939. if ((accumulate && (node->flags & GGML_TENSOR_FLAG_PARAM)) || (node->flags & GGML_TENSOR_FLAG_LOSS)) {
  4940. cgraph->grad_accs[igrad] = ggml_dup_tensor(ctx_static, node);
  4941. cgraph->grads[igrad] = cgraph->grad_accs[igrad];
  4942. ggml_format_name(cgraph->grad_accs[igrad], "grad acc for %s", node->name);
  4943. }
  4944. grads_needed[igrad] = true;
  4945. }
  4946. for (int i = n_nodes_f - 1; i >= 0; --i) {
  4947. // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
  4948. // use allocator to automatically make inplace operations
  4949. ggml_compute_backward(ctx_compute, cgraph, i, grads_needed);
  4950. }
  4951. free(grads_needed);
  4952. }
  4953. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  4954. void * ptr = *p;
  4955. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  4956. *p = (void *) ((char *) ptr + size);
  4957. return ptr;
  4958. }
  4959. static size_t ggml_graph_nbytes(size_t size, bool grads) {
  4960. size_t hash_size = ggml_hash_size(size * 2);
  4961. void * p = 0;
  4962. incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
  4963. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
  4964. incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
  4965. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
  4966. if (grads) {
  4967. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
  4968. incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grad_accs
  4969. }
  4970. incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4971. size_t nbytes = (size_t) p;
  4972. return nbytes;
  4973. }
  4974. size_t ggml_graph_overhead_custom(size_t size, bool grads) {
  4975. return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
  4976. }
  4977. size_t ggml_graph_overhead(void) {
  4978. return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
  4979. }
  4980. struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
  4981. const size_t obj_size = ggml_graph_nbytes(size, grads);
  4982. struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
  4983. struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
  4984. // the size of the hash table is doubled since it needs to hold both nodes and leafs
  4985. size_t hash_size = ggml_hash_size(size * 2);
  4986. void * p = cgraph + 1;
  4987. struct ggml_tensor ** nodes_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4988. struct ggml_tensor ** leafs_ptr = incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4989. struct ggml_tensor ** hash_keys_ptr = incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
  4990. struct ggml_tensor ** grads_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4991. struct ggml_tensor ** grad_accs_ptr = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
  4992. ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
  4993. // check that we allocated the correct amount of memory
  4994. assert(obj_size == (size_t)((char *)p - (char *)cgraph));
  4995. *cgraph = (struct ggml_cgraph) {
  4996. /*.size =*/ size,
  4997. /*.n_nodes =*/ 0,
  4998. /*.n_leafs =*/ 0,
  4999. /*.nodes =*/ nodes_ptr,
  5000. /*.grads =*/ grads_ptr,
  5001. /*.grad_accs =*/ grad_accs_ptr,
  5002. /*.leafs =*/ leafs_ptr,
  5003. /*.hash_table =*/ { hash_size, hash_used, hash_keys_ptr },
  5004. /*.order =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
  5005. };
  5006. ggml_hash_set_reset(&cgraph->visited_hash_set);
  5007. if (grads) {
  5008. memset(cgraph->grads, 0, hash_size*sizeof(struct ggml_tensor *));
  5009. memset(cgraph->grad_accs, 0, hash_size*sizeof(struct ggml_tensor *));
  5010. }
  5011. return cgraph;
  5012. }
  5013. struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
  5014. return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
  5015. }
  5016. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
  5017. struct ggml_cgraph cgraph = {
  5018. /*.size =*/ 0,
  5019. /*.n_nodes =*/ i1 - i0,
  5020. /*.n_leafs =*/ 0,
  5021. /*.nodes =*/ cgraph0->nodes + i0,
  5022. /*.grads =*/ NULL, // gradients would need visited_hash_set
  5023. /*.grad_accs =*/ NULL,
  5024. /*.leafs =*/ NULL,
  5025. /*.visited_hash_set =*/ { 0, NULL, NULL },
  5026. /*.order =*/ cgraph0->order,
  5027. };
  5028. return cgraph;
  5029. }
  5030. void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
  5031. GGML_ASSERT(dst->size >= src->n_leafs);
  5032. GGML_ASSERT(dst->size >= src->n_nodes);
  5033. GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
  5034. dst->n_leafs = src->n_leafs;
  5035. dst->n_nodes = src->n_nodes;
  5036. dst->order = src->order;
  5037. for (int i = 0; i < src->n_leafs; ++i) {
  5038. dst->leafs[i] = src->leafs[i];
  5039. }
  5040. for (int i = 0; i < src->n_nodes; ++i) {
  5041. dst->nodes[i] = src->nodes[i];
  5042. }
  5043. for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
  5044. // copy all hashset keys (tensors) that are in use
  5045. if (ggml_bitset_get(src->visited_hash_set.used, i)) {
  5046. ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
  5047. }
  5048. }
  5049. if (dst->grads) {
  5050. memset(dst->grads, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  5051. memset(dst->grad_accs, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
  5052. }
  5053. if (src->grads) {
  5054. GGML_ASSERT(dst->grads != NULL);
  5055. GGML_ASSERT(dst->grad_accs != NULL);
  5056. for (int i = 0; i < src->n_nodes; ++i) {
  5057. const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
  5058. const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
  5059. GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
  5060. GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
  5061. GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
  5062. GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
  5063. dst->grads[igrad_dst] = src->grads[igrad_src];
  5064. dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
  5065. }
  5066. }
  5067. }
  5068. struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
  5069. struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads != NULL);
  5070. ggml_graph_cpy(cgraph, result);
  5071. return result;
  5072. }
  5073. struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
  5074. if (ggml_is_empty(tensor)) {
  5075. return tensor;
  5076. }
  5077. if (tensor->buffer) {
  5078. ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
  5079. } else {
  5080. GGML_ASSERT(tensor->data);
  5081. memset(tensor->data, 0, ggml_nbytes(tensor));
  5082. }
  5083. return tensor;
  5084. }
  5085. void ggml_graph_reset(struct ggml_cgraph * cgraph) {
  5086. GGML_ASSERT(cgraph->grads != NULL);
  5087. for (int i = 0; i < cgraph->n_nodes; i++) {
  5088. struct ggml_tensor * node = cgraph->nodes[i];
  5089. struct ggml_tensor * grad_acc = ggml_graph_get_grad_acc(cgraph, node);
  5090. if (node->op == GGML_OP_OPT_STEP_ADAMW) {
  5091. // clear momenta
  5092. ggml_set_zero(node->src[2]);
  5093. ggml_set_zero(node->src[3]);
  5094. }
  5095. // initial gradients of loss should be 1, 0 otherwise
  5096. if (grad_acc) {
  5097. if (node->flags & GGML_TENSOR_FLAG_LOSS) {
  5098. GGML_ASSERT(grad_acc->type == GGML_TYPE_F32);
  5099. GGML_ASSERT(ggml_is_scalar(grad_acc));
  5100. const float onef = 1.0f;
  5101. if (grad_acc->buffer) {
  5102. ggml_backend_tensor_set(grad_acc, &onef, 0, sizeof(float));
  5103. } else {
  5104. GGML_ASSERT(grad_acc->data);
  5105. *((float *) grad_acc->data) = onef;
  5106. }
  5107. } else {
  5108. ggml_set_zero(grad_acc);
  5109. }
  5110. }
  5111. }
  5112. }
  5113. void ggml_graph_clear(struct ggml_cgraph * cgraph) {
  5114. cgraph->n_leafs = 0;
  5115. cgraph->n_nodes = 0;
  5116. ggml_hash_set_reset(&cgraph->visited_hash_set);
  5117. }
  5118. int ggml_graph_size(struct ggml_cgraph * cgraph) {
  5119. return cgraph->size;
  5120. }
  5121. struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
  5122. if (i < 0) {
  5123. GGML_ASSERT(cgraph->n_nodes + i >= 0);
  5124. return cgraph->nodes[cgraph->n_nodes + i];
  5125. }
  5126. GGML_ASSERT(i < cgraph->n_nodes);
  5127. return cgraph->nodes[i];
  5128. }
  5129. struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
  5130. return cgraph->nodes;
  5131. }
  5132. int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
  5133. return cgraph->n_nodes;
  5134. }
  5135. void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
  5136. GGML_ASSERT(cgraph->size > cgraph->n_nodes);
  5137. cgraph->nodes[cgraph->n_nodes] = tensor;
  5138. cgraph->n_nodes++;
  5139. }
  5140. struct ggml_tensor * ggml_graph_get_tensor(const struct ggml_cgraph * cgraph, const char * name) {
  5141. for (int i = 0; i < cgraph->n_leafs; i++) {
  5142. struct ggml_tensor * leaf = cgraph->leafs[i];
  5143. if (strcmp(leaf->name, name) == 0) {
  5144. return leaf;
  5145. }
  5146. }
  5147. for (int i = 0; i < cgraph->n_nodes; i++) {
  5148. struct ggml_tensor * node = cgraph->nodes[i];
  5149. if (strcmp(node->name, name) == 0) {
  5150. return node;
  5151. }
  5152. }
  5153. return NULL;
  5154. }
  5155. struct ggml_tensor * ggml_graph_get_grad(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5156. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5157. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grads ? cgraph->grads[igrad] : NULL;
  5158. }
  5159. struct ggml_tensor * ggml_graph_get_grad_acc(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5160. const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
  5161. return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grad_accs ? cgraph->grad_accs[igrad] : NULL;
  5162. }
  5163. void ggml_graph_print(const struct ggml_cgraph * cgraph) {
  5164. GGML_LOG_INFO("=== GRAPH ===\n");
  5165. GGML_LOG_INFO("n_nodes = %d\n", cgraph->n_nodes);
  5166. for (int i = 0; i < cgraph->n_nodes; i++) {
  5167. struct ggml_tensor * node = cgraph->nodes[i];
  5168. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
  5169. i,
  5170. node->ne[0], node->ne[1], node->ne[2],
  5171. ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" :
  5172. ggml_graph_get_grad(cgraph, node) ? "g" : " ");
  5173. }
  5174. GGML_LOG_INFO("n_leafs = %d\n", cgraph->n_leafs);
  5175. for (int i = 0; i < cgraph->n_leafs; i++) {
  5176. struct ggml_tensor * node = cgraph->leafs[i];
  5177. GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
  5178. i,
  5179. node->ne[0], node->ne[1],
  5180. ggml_op_name(node->op),
  5181. ggml_get_name(node));
  5182. }
  5183. GGML_LOG_INFO("========================================\n");
  5184. }
  5185. // check if node is part of the graph
  5186. static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5187. if (cgraph == NULL) {
  5188. return true;
  5189. }
  5190. for (int i = 0; i < cgraph->n_nodes; i++) {
  5191. if (cgraph->nodes[i] == node) {
  5192. return true;
  5193. }
  5194. }
  5195. return false;
  5196. }
  5197. static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
  5198. for (int i = 0; i < cgraph->n_nodes; i++) {
  5199. struct ggml_tensor * parent = cgraph->nodes[i];
  5200. struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, parent);
  5201. if (grad == node) {
  5202. return parent;
  5203. }
  5204. }
  5205. return NULL;
  5206. }
  5207. 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) {
  5208. struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
  5209. struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
  5210. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
  5211. gparent0 ? (void *) gparent0 : (void *) parent,
  5212. gparent0 ? "g" : "x",
  5213. gparent ? (void *) gparent : (void *) node,
  5214. gparent ? "g" : "x",
  5215. gparent ? "empty" : "vee",
  5216. gparent ? "dashed" : "solid",
  5217. label);
  5218. }
  5219. static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label) {
  5220. fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"%s\"; ]\n",
  5221. (void *) parent, "x",
  5222. (void *) node, "x",
  5223. label);
  5224. }
  5225. void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
  5226. char color[16];
  5227. FILE * fp = ggml_fopen(filename, "w");
  5228. GGML_ASSERT(fp);
  5229. fprintf(fp, "digraph G {\n");
  5230. fprintf(fp, " newrank = true;\n");
  5231. fprintf(fp, " rankdir = TB;\n");
  5232. for (int i = 0; i < gb->n_nodes; i++) {
  5233. struct ggml_tensor * node = gb->nodes[i];
  5234. struct ggml_tensor * grad = ggml_graph_get_grad(gb, node);
  5235. if (ggml_graph_get_parent(gb, node) != NULL) {
  5236. continue;
  5237. }
  5238. if (node->flags & GGML_TENSOR_FLAG_PARAM) {
  5239. snprintf(color, sizeof(color), "yellow");
  5240. } else if (grad) {
  5241. if (ggml_graph_find(gf, node)) {
  5242. snprintf(color, sizeof(color), "green");
  5243. } else {
  5244. snprintf(color, sizeof(color), "lightblue");
  5245. }
  5246. } else {
  5247. snprintf(color, sizeof(color), "white");
  5248. }
  5249. fprintf(fp, " \"%p\" [ "
  5250. "style = filled; fillcolor = %s; shape = record; "
  5251. "label=\"",
  5252. (void *) node, color);
  5253. if (strlen(node->name) > 0) {
  5254. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5255. } else {
  5256. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5257. }
  5258. if (ggml_is_matrix(node)) {
  5259. fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
  5260. } else {
  5261. fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
  5262. }
  5263. if (grad) {
  5264. fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(grad->op));
  5265. } else {
  5266. fprintf(fp, "\"; ]\n");
  5267. }
  5268. }
  5269. for (int i = 0; i < gb->n_leafs; i++) {
  5270. struct ggml_tensor * node = gb->leafs[i];
  5271. snprintf(color, sizeof(color), "pink");
  5272. fprintf(fp, " \"%p\" [ "
  5273. "style = filled; fillcolor = %s; shape = record; "
  5274. "label=\"<x>",
  5275. (void *) node, color);
  5276. if (strlen(node->name) > 0) {
  5277. fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
  5278. } else {
  5279. fprintf(fp, "(%s)|", ggml_type_name(node->type));
  5280. }
  5281. fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
  5282. if (ggml_nelements(node) < 5 && node->data != NULL) {
  5283. fprintf(fp, " | (");
  5284. for (int j = 0; j < ggml_nelements(node); j++) {
  5285. // FIXME: use ggml-backend to obtain the tensor data
  5286. //if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
  5287. // fprintf(fp, "%d", ggml_get_i32_1d(node, j));
  5288. //}
  5289. //else if (node->type == GGML_TYPE_F32 ||
  5290. // node->type == GGML_TYPE_F16 ||
  5291. // node->type == GGML_TYPE_BF16) {
  5292. // fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
  5293. //}
  5294. //else
  5295. {
  5296. fprintf(fp, "#");
  5297. }
  5298. if (j < ggml_nelements(node) - 1) {
  5299. fprintf(fp, ", ");
  5300. }
  5301. }
  5302. fprintf(fp, ")");
  5303. }
  5304. fprintf(fp, "\"; ]\n");
  5305. }
  5306. for (int i = 0; i < gb->n_nodes; i++) {
  5307. struct ggml_tensor * node = gb->nodes[i];
  5308. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5309. if (node->src[j]) {
  5310. char label[16];
  5311. snprintf(label, sizeof(label), "src %d", j);
  5312. ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
  5313. }
  5314. }
  5315. }
  5316. for (int i = 0; i < gb->n_leafs; i++) {
  5317. struct ggml_tensor * node = gb->leafs[i];
  5318. for (int j = 0; j < GGML_MAX_SRC; j++) {
  5319. if (node->src[j]) {
  5320. char label[16];
  5321. snprintf(label, sizeof(label), "src %d", j);
  5322. ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
  5323. }
  5324. }
  5325. }
  5326. fprintf(fp, "}\n");
  5327. fclose(fp);
  5328. GGML_LOG_INFO("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
  5329. }
  5330. ////////////////////////////////////////////////////////////////////////////////
  5331. void ggml_set_input(struct ggml_tensor * tensor) {
  5332. tensor->flags |= GGML_TENSOR_FLAG_INPUT;
  5333. }
  5334. void ggml_set_output(struct ggml_tensor * tensor) {
  5335. tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
  5336. }
  5337. void ggml_set_param(struct ggml_context * ctx, struct ggml_tensor * tensor) {
  5338. GGML_UNUSED(ctx); // TODO: remove this parameter
  5339. tensor->flags |= GGML_TENSOR_FLAG_PARAM;
  5340. }
  5341. void ggml_set_loss(struct ggml_tensor * tensor) {
  5342. GGML_ASSERT(ggml_is_scalar(tensor));
  5343. GGML_ASSERT(tensor->type == GGML_TYPE_F32);
  5344. tensor->flags |= GGML_TENSOR_FLAG_LOSS;
  5345. }
  5346. ////////////////////////////////////////////////////////////////////////////////
  5347. void ggml_quantize_init(enum ggml_type type) {
  5348. ggml_critical_section_start();
  5349. switch (type) {
  5350. case GGML_TYPE_IQ2_XXS:
  5351. case GGML_TYPE_IQ2_XS:
  5352. case GGML_TYPE_IQ2_S:
  5353. case GGML_TYPE_IQ1_S:
  5354. case GGML_TYPE_IQ1_M: iq2xs_init_impl(type); break;
  5355. case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
  5356. case GGML_TYPE_IQ3_S: iq3xs_init_impl(512); break;
  5357. default: // nothing
  5358. break;
  5359. }
  5360. ggml_critical_section_end();
  5361. }
  5362. void ggml_quantize_free(void) {
  5363. ggml_critical_section_start();
  5364. iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
  5365. iq2xs_free_impl(GGML_TYPE_IQ2_XS);
  5366. iq2xs_free_impl(GGML_TYPE_IQ1_S);
  5367. iq3xs_free_impl(256);
  5368. ggml_critical_section_end();
  5369. }
  5370. bool ggml_quantize_requires_imatrix(enum ggml_type type) {
  5371. return
  5372. type == GGML_TYPE_IQ2_XXS ||
  5373. type == GGML_TYPE_IQ2_XS ||
  5374. type == GGML_TYPE_IQ1_S;// ||
  5375. //type == GGML_TYPE_IQ1_M;
  5376. }
  5377. size_t ggml_quantize_chunk(
  5378. enum ggml_type type,
  5379. const float * src,
  5380. void * dst,
  5381. int64_t start,
  5382. int64_t nrows,
  5383. int64_t n_per_row,
  5384. const float * imatrix) {
  5385. const int64_t n = (int64_t) nrows * n_per_row;
  5386. if (ggml_quantize_requires_imatrix(type)) {
  5387. GGML_ASSERT(imatrix != NULL);
  5388. }
  5389. GGML_ASSERT(start % type_traits[type].blck_size == 0);
  5390. GGML_ASSERT(start % n_per_row == 0);
  5391. ggml_quantize_init(type); // this is noop if already initialized
  5392. const size_t start_row = start / n_per_row;
  5393. const size_t row_size = ggml_row_size(type, n_per_row);
  5394. size_t result = 0;
  5395. switch (type) {
  5396. case GGML_TYPE_Q4_0: result = quantize_q4_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5397. case GGML_TYPE_Q4_1: result = quantize_q4_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5398. case GGML_TYPE_Q5_0: result = quantize_q5_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5399. case GGML_TYPE_Q5_1: result = quantize_q5_1(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5400. case GGML_TYPE_Q8_0: result = quantize_q8_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5401. case GGML_TYPE_Q2_K: result = quantize_q2_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5402. case GGML_TYPE_Q3_K: result = quantize_q3_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5403. case GGML_TYPE_Q4_K: result = quantize_q4_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5404. case GGML_TYPE_Q5_K: result = quantize_q5_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5405. case GGML_TYPE_Q6_K: result = quantize_q6_K(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5406. case GGML_TYPE_TQ1_0: result = quantize_tq1_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5407. case GGML_TYPE_TQ2_0: result = quantize_tq2_0(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5408. case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5409. case GGML_TYPE_IQ2_XS: result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5410. case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5411. case GGML_TYPE_IQ3_S: result = quantize_iq3_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5412. case GGML_TYPE_IQ2_S: result = quantize_iq2_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5413. case GGML_TYPE_IQ1_S: result = quantize_iq1_s (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5414. case GGML_TYPE_IQ1_M: result = quantize_iq1_m (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5415. case GGML_TYPE_IQ4_NL: result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5416. case GGML_TYPE_IQ4_XS: result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
  5417. case GGML_TYPE_F16:
  5418. {
  5419. size_t elemsize = sizeof(ggml_fp16_t);
  5420. ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
  5421. result = n * elemsize;
  5422. } break;
  5423. case GGML_TYPE_BF16:
  5424. {
  5425. size_t elemsize = sizeof(ggml_bf16_t);
  5426. ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
  5427. result = n * elemsize;
  5428. } break;
  5429. case GGML_TYPE_F32:
  5430. {
  5431. size_t elemsize = sizeof(float);
  5432. result = n * elemsize;
  5433. memcpy((uint8_t *)dst + start * elemsize, src + start, result);
  5434. } break;
  5435. default:
  5436. assert(false);
  5437. }
  5438. GGML_ASSERT(result == nrows * row_size);
  5439. return result;
  5440. }
  5441. ////////////////////////////////////////////////////////////////////////////////
  5442. void ggml_log_set(ggml_log_callback log_callback, void * user_data) {
  5443. g_logger_state.log_callback = log_callback ? log_callback : ggml_log_callback_default;
  5444. g_logger_state.log_callback_user_data = user_data;
  5445. }
  5446. void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
  5447. p->n_threads = n_threads;
  5448. p->prio = 0; // default priority (usually means normal or inherited)
  5449. p->poll = 50; // hybrid-polling enabled
  5450. p->strict_cpu = false; // no strict placement (all threads share same cpumask)
  5451. p->paused = false; // threads are ready to go
  5452. memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
  5453. }
  5454. struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
  5455. struct ggml_threadpool_params p;
  5456. ggml_threadpool_params_init(&p, n_threads);
  5457. return p;
  5458. }
  5459. bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
  5460. if (p0->n_threads != p1->n_threads ) return false;
  5461. if (p0->prio != p1->prio ) return false;
  5462. if (p0->poll != p1->poll ) return false;
  5463. if (p0->strict_cpu != p1->strict_cpu ) return false;
  5464. return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
  5465. }