1
0

llama.cpp 596 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUDA
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #include <algorithm>
  55. #include <array>
  56. #include <cassert>
  57. #include <cfloat>
  58. #include <cinttypes>
  59. #include <climits>
  60. #include <cmath>
  61. #include <cstdarg>
  62. #include <cstddef>
  63. #include <cstdint>
  64. #include <cstdio>
  65. #include <cstring>
  66. #include <ctime>
  67. #include <cwctype>
  68. #include <forward_list>
  69. #include <fstream>
  70. #include <functional>
  71. #include <initializer_list>
  72. #include <locale>
  73. #include <map>
  74. #include <memory>
  75. #include <mutex>
  76. #include <numeric>
  77. #include <queue>
  78. #include <random>
  79. #include <regex>
  80. #include <set>
  81. #include <sstream>
  82. #include <thread>
  83. #include <type_traits>
  84. #include <unordered_map>
  85. #if defined(_MSC_VER)
  86. #pragma warning(disable: 4244 4267) // possible loss of data
  87. #endif
  88. #ifdef __GNUC__
  89. #ifdef __MINGW32__
  90. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  93. #endif
  94. #else
  95. #define LLAMA_ATTRIBUTE_FORMAT(...)
  96. #endif
  97. #define LLAMA_MAX_NODES 8192
  98. #define LLAMA_MAX_EXPERTS 8
  99. //
  100. // logging
  101. //
  102. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  103. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  104. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  105. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  106. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  107. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  108. //
  109. // helpers
  110. //
  111. static size_t utf8_len(char src) {
  112. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  113. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  114. return lookup[highbits];
  115. }
  116. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  117. std::string result;
  118. for (size_t pos = 0; ; pos += search.length()) {
  119. auto new_pos = s.find(search, pos);
  120. if (new_pos == std::string::npos) {
  121. result += s.substr(pos, s.size() - pos);
  122. break;
  123. }
  124. result += s.substr(pos, new_pos - pos) + replace;
  125. pos = new_pos;
  126. }
  127. s = std::move(result);
  128. }
  129. static bool is_float_close(float a, float b, float abs_tol) {
  130. // Check for non-negative tolerance
  131. if (abs_tol < 0.0) {
  132. throw std::invalid_argument("Tolerance must be non-negative");
  133. }
  134. // Exact equality check
  135. if (a == b) {
  136. return true;
  137. }
  138. // Check for infinities
  139. if (std::isinf(a) || std::isinf(b)) {
  140. return false;
  141. }
  142. // Regular comparison using the provided absolute tolerance
  143. return std::fabs(b - a) <= abs_tol;
  144. }
  145. static void zeros(std::ofstream & file, size_t n) {
  146. char zero = 0;
  147. for (size_t i = 0; i < n; ++i) {
  148. file.write(&zero, 1);
  149. }
  150. }
  151. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  152. static std::string format(const char * fmt, ...) {
  153. va_list ap;
  154. va_list ap2;
  155. va_start(ap, fmt);
  156. va_copy(ap2, ap);
  157. int size = vsnprintf(NULL, 0, fmt, ap);
  158. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  159. std::vector<char> buf(size + 1);
  160. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  161. GGML_ASSERT(size2 == size);
  162. va_end(ap2);
  163. va_end(ap);
  164. return std::string(buf.data(), size);
  165. }
  166. //
  167. // gguf constants (sync with gguf.py)
  168. //
  169. enum llm_arch {
  170. LLM_ARCH_LLAMA,
  171. LLM_ARCH_FALCON,
  172. LLM_ARCH_BAICHUAN,
  173. LLM_ARCH_GROK,
  174. LLM_ARCH_GPT2,
  175. LLM_ARCH_GPTJ,
  176. LLM_ARCH_GPTNEOX,
  177. LLM_ARCH_MPT,
  178. LLM_ARCH_STARCODER,
  179. LLM_ARCH_PERSIMMON,
  180. LLM_ARCH_REFACT,
  181. LLM_ARCH_BERT,
  182. LLM_ARCH_NOMIC_BERT,
  183. LLM_ARCH_BLOOM,
  184. LLM_ARCH_STABLELM,
  185. LLM_ARCH_QWEN,
  186. LLM_ARCH_QWEN2,
  187. LLM_ARCH_PHI2,
  188. LLM_ARCH_PLAMO,
  189. LLM_ARCH_CODESHELL,
  190. LLM_ARCH_ORION,
  191. LLM_ARCH_INTERNLM2,
  192. LLM_ARCH_MINICPM,
  193. LLM_ARCH_GEMMA,
  194. LLM_ARCH_STARCODER2,
  195. LLM_ARCH_MAMBA,
  196. LLM_ARCH_COMMAND_R,
  197. LLM_ARCH_UNKNOWN,
  198. };
  199. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  200. { LLM_ARCH_LLAMA, "llama" },
  201. { LLM_ARCH_FALCON, "falcon" },
  202. { LLM_ARCH_GROK, "grok" },
  203. { LLM_ARCH_GPT2, "gpt2" },
  204. { LLM_ARCH_GPTJ, "gptj" },
  205. { LLM_ARCH_GPTNEOX, "gptneox" },
  206. { LLM_ARCH_MPT, "mpt" },
  207. { LLM_ARCH_BAICHUAN, "baichuan" },
  208. { LLM_ARCH_STARCODER, "starcoder" },
  209. { LLM_ARCH_PERSIMMON, "persimmon" },
  210. { LLM_ARCH_REFACT, "refact" },
  211. { LLM_ARCH_BERT, "bert" },
  212. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  213. { LLM_ARCH_BLOOM, "bloom" },
  214. { LLM_ARCH_STABLELM, "stablelm" },
  215. { LLM_ARCH_QWEN, "qwen" },
  216. { LLM_ARCH_QWEN2, "qwen2" },
  217. { LLM_ARCH_PHI2, "phi2" },
  218. { LLM_ARCH_PLAMO, "plamo" },
  219. { LLM_ARCH_CODESHELL, "codeshell" },
  220. { LLM_ARCH_ORION, "orion" },
  221. { LLM_ARCH_INTERNLM2, "internlm2" },
  222. { LLM_ARCH_MINICPM, "minicpm" },
  223. { LLM_ARCH_GEMMA, "gemma" },
  224. { LLM_ARCH_STARCODER2, "starcoder2" },
  225. { LLM_ARCH_MAMBA, "mamba" },
  226. { LLM_ARCH_COMMAND_R, "command-r" },
  227. { LLM_ARCH_UNKNOWN, "(unknown)" },
  228. };
  229. enum llm_kv {
  230. LLM_KV_GENERAL_ARCHITECTURE,
  231. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  232. LLM_KV_GENERAL_ALIGNMENT,
  233. LLM_KV_GENERAL_NAME,
  234. LLM_KV_GENERAL_AUTHOR,
  235. LLM_KV_GENERAL_URL,
  236. LLM_KV_GENERAL_DESCRIPTION,
  237. LLM_KV_GENERAL_LICENSE,
  238. LLM_KV_GENERAL_SOURCE_URL,
  239. LLM_KV_GENERAL_SOURCE_HF_REPO,
  240. LLM_KV_VOCAB_SIZE,
  241. LLM_KV_CONTEXT_LENGTH,
  242. LLM_KV_EMBEDDING_LENGTH,
  243. LLM_KV_BLOCK_COUNT,
  244. LLM_KV_FEED_FORWARD_LENGTH,
  245. LLM_KV_USE_PARALLEL_RESIDUAL,
  246. LLM_KV_TENSOR_DATA_LAYOUT,
  247. LLM_KV_EXPERT_COUNT,
  248. LLM_KV_EXPERT_USED_COUNT,
  249. LLM_KV_POOLING_TYPE,
  250. LLM_KV_LOGIT_SCALE,
  251. LLM_KV_ATTENTION_HEAD_COUNT,
  252. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  253. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  254. LLM_KV_ATTENTION_CLAMP_KQV,
  255. LLM_KV_ATTENTION_KEY_LENGTH,
  256. LLM_KV_ATTENTION_VALUE_LENGTH,
  257. LLM_KV_ATTENTION_LAYERNORM_EPS,
  258. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  259. LLM_KV_ATTENTION_CAUSAL,
  260. LLM_KV_ROPE_DIMENSION_COUNT,
  261. LLM_KV_ROPE_FREQ_BASE,
  262. LLM_KV_ROPE_SCALE_LINEAR,
  263. LLM_KV_ROPE_SCALING_TYPE,
  264. LLM_KV_ROPE_SCALING_FACTOR,
  265. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  266. LLM_KV_ROPE_SCALING_FINETUNED,
  267. LLM_KV_SPLIT_NO,
  268. LLM_KV_SPLIT_COUNT,
  269. LLM_KV_SPLIT_TENSORS_COUNT,
  270. LLM_KV_SSM_INNER_SIZE,
  271. LLM_KV_SSM_CONV_KERNEL,
  272. LLM_KV_SSM_STATE_SIZE,
  273. LLM_KV_SSM_TIME_STEP_RANK,
  274. LLM_KV_TOKENIZER_MODEL,
  275. LLM_KV_TOKENIZER_LIST,
  276. LLM_KV_TOKENIZER_TOKEN_TYPE,
  277. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  278. LLM_KV_TOKENIZER_SCORES,
  279. LLM_KV_TOKENIZER_MERGES,
  280. LLM_KV_TOKENIZER_BOS_ID,
  281. LLM_KV_TOKENIZER_EOS_ID,
  282. LLM_KV_TOKENIZER_UNK_ID,
  283. LLM_KV_TOKENIZER_SEP_ID,
  284. LLM_KV_TOKENIZER_PAD_ID,
  285. LLM_KV_TOKENIZER_ADD_BOS,
  286. LLM_KV_TOKENIZER_ADD_EOS,
  287. LLM_KV_TOKENIZER_ADD_PREFIX,
  288. LLM_KV_TOKENIZER_HF_JSON,
  289. LLM_KV_TOKENIZER_RWKV,
  290. };
  291. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  292. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  293. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  294. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  295. { LLM_KV_GENERAL_NAME, "general.name" },
  296. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  297. { LLM_KV_GENERAL_URL, "general.url" },
  298. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  299. { LLM_KV_GENERAL_LICENSE, "general.license" },
  300. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  301. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  302. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  303. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  304. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  305. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  306. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  307. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  308. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  309. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  310. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  311. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  312. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  313. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  314. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  315. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  316. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  317. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  318. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  319. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  320. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  321. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  322. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  323. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  324. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  325. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  326. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  327. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  328. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  329. { LLM_KV_SPLIT_NO, "split.no" },
  330. { LLM_KV_SPLIT_COUNT, "split.count" },
  331. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  332. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  333. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  334. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  335. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  336. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  337. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  338. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  339. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  340. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  341. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  342. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  343. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  344. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  345. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  346. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  347. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  348. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  349. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  350. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  351. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  352. };
  353. struct LLM_KV {
  354. LLM_KV(llm_arch arch) : arch(arch) {}
  355. llm_arch arch;
  356. std::string operator()(llm_kv kv) const {
  357. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  358. }
  359. };
  360. enum llm_tensor {
  361. LLM_TENSOR_TOKEN_EMBD,
  362. LLM_TENSOR_TOKEN_EMBD_NORM,
  363. LLM_TENSOR_TOKEN_TYPES,
  364. LLM_TENSOR_POS_EMBD,
  365. LLM_TENSOR_OUTPUT,
  366. LLM_TENSOR_OUTPUT_NORM,
  367. LLM_TENSOR_ROPE_FREQS,
  368. LLM_TENSOR_ATTN_Q,
  369. LLM_TENSOR_ATTN_K,
  370. LLM_TENSOR_ATTN_V,
  371. LLM_TENSOR_ATTN_QKV,
  372. LLM_TENSOR_ATTN_OUT,
  373. LLM_TENSOR_ATTN_NORM,
  374. LLM_TENSOR_ATTN_NORM_2,
  375. LLM_TENSOR_ATTN_OUT_NORM,
  376. LLM_TENSOR_ATTN_ROT_EMBD,
  377. LLM_TENSOR_FFN_GATE_INP,
  378. LLM_TENSOR_FFN_NORM,
  379. LLM_TENSOR_FFN_GATE,
  380. LLM_TENSOR_FFN_DOWN,
  381. LLM_TENSOR_FFN_UP,
  382. LLM_TENSOR_FFN_ACT,
  383. LLM_TENSOR_FFN_DOWN_EXP,
  384. LLM_TENSOR_FFN_GATE_EXP,
  385. LLM_TENSOR_FFN_UP_EXP,
  386. LLM_TENSOR_ATTN_Q_NORM,
  387. LLM_TENSOR_ATTN_K_NORM,
  388. LLM_TENSOR_LAYER_OUT_NORM,
  389. LLM_TENSOR_SSM_IN,
  390. LLM_TENSOR_SSM_CONV1D,
  391. LLM_TENSOR_SSM_X,
  392. LLM_TENSOR_SSM_DT,
  393. LLM_TENSOR_SSM_A,
  394. LLM_TENSOR_SSM_D,
  395. LLM_TENSOR_SSM_OUT,
  396. };
  397. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  398. {
  399. LLM_ARCH_LLAMA,
  400. {
  401. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  402. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  403. { LLM_TENSOR_OUTPUT, "output" },
  404. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  405. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  406. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  407. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  408. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  409. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  410. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  411. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  412. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  413. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  414. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  415. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  416. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  417. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  418. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  419. },
  420. },
  421. {
  422. LLM_ARCH_BAICHUAN,
  423. {
  424. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  425. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  426. { LLM_TENSOR_OUTPUT, "output" },
  427. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  428. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  429. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  430. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  431. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  432. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  433. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  434. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  435. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  436. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  437. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  438. },
  439. },
  440. {
  441. LLM_ARCH_FALCON,
  442. {
  443. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  444. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  445. { LLM_TENSOR_OUTPUT, "output" },
  446. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  447. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  448. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  449. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  450. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  451. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  452. },
  453. },
  454. {
  455. LLM_ARCH_GROK,
  456. {
  457. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  458. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  459. { LLM_TENSOR_OUTPUT, "output" },
  460. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  461. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  462. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  463. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  464. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  465. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  466. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  467. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  468. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  469. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  470. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  471. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  472. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  473. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  474. },
  475. },
  476. {
  477. LLM_ARCH_GPT2,
  478. {
  479. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  480. { LLM_TENSOR_POS_EMBD, "position_embd" },
  481. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  482. { LLM_TENSOR_OUTPUT, "output" },
  483. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  484. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  485. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  486. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  487. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  488. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  489. },
  490. },
  491. {
  492. LLM_ARCH_GPTJ,
  493. {
  494. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  495. },
  496. },
  497. {
  498. LLM_ARCH_GPTNEOX,
  499. {
  500. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  501. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  502. { LLM_TENSOR_OUTPUT, "output" },
  503. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  504. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  505. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  506. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  507. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  508. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  509. },
  510. },
  511. {
  512. LLM_ARCH_PERSIMMON,
  513. {
  514. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  515. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  516. { LLM_TENSOR_OUTPUT, "output"},
  517. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  518. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  519. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  520. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  521. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  522. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  523. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  524. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  525. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  526. },
  527. },
  528. {
  529. LLM_ARCH_MPT,
  530. {
  531. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  532. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  533. { LLM_TENSOR_OUTPUT, "output"},
  534. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  535. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  536. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  537. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  538. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  539. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  540. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  541. },
  542. },
  543. {
  544. LLM_ARCH_STARCODER,
  545. {
  546. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  547. { LLM_TENSOR_POS_EMBD, "position_embd" },
  548. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  549. { LLM_TENSOR_OUTPUT, "output" },
  550. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  551. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  552. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  553. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  554. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  555. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  556. },
  557. },
  558. {
  559. LLM_ARCH_REFACT,
  560. {
  561. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  562. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  563. { LLM_TENSOR_OUTPUT, "output" },
  564. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  565. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  566. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  567. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  568. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  569. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  570. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  571. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  572. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  573. },
  574. },
  575. {
  576. LLM_ARCH_BERT,
  577. {
  578. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  579. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  580. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  581. { LLM_TENSOR_POS_EMBD, "position_embd" },
  582. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  583. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  584. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  585. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  586. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  587. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  588. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  589. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  590. },
  591. },
  592. {
  593. LLM_ARCH_NOMIC_BERT,
  594. {
  595. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  596. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  597. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  598. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  599. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  600. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  601. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  602. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  603. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  604. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  605. },
  606. },
  607. {
  608. LLM_ARCH_BLOOM,
  609. {
  610. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  611. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  612. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  613. { LLM_TENSOR_OUTPUT, "output" },
  614. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  615. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  616. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  617. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  618. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  619. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  620. },
  621. },
  622. {
  623. LLM_ARCH_STABLELM,
  624. {
  625. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  626. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  627. { LLM_TENSOR_OUTPUT, "output" },
  628. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  629. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  630. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  631. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  632. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  633. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  634. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  635. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  636. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  637. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  638. },
  639. },
  640. {
  641. LLM_ARCH_QWEN,
  642. {
  643. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  644. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  645. { LLM_TENSOR_OUTPUT, "output" },
  646. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  647. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  648. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  649. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  650. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  651. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  652. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  653. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  654. },
  655. },
  656. {
  657. LLM_ARCH_QWEN2,
  658. {
  659. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  660. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  661. { LLM_TENSOR_OUTPUT, "output" },
  662. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  663. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  664. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  665. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  666. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  667. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  668. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  669. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  670. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  671. },
  672. },
  673. {
  674. LLM_ARCH_PHI2,
  675. {
  676. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  677. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  678. { LLM_TENSOR_OUTPUT, "output" },
  679. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  680. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  681. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  682. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  683. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  684. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_PLAMO,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  696. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  697. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  698. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  699. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  700. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  701. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  702. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  703. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  704. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  705. },
  706. },
  707. {
  708. LLM_ARCH_CODESHELL,
  709. {
  710. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  711. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  712. { LLM_TENSOR_OUTPUT, "output" },
  713. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  714. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  715. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  716. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  717. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  718. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  719. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  720. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  721. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  722. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  723. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  724. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  725. },
  726. },
  727. {
  728. LLM_ARCH_ORION,
  729. {
  730. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  731. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  732. { LLM_TENSOR_OUTPUT, "output" },
  733. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  736. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  737. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  738. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  739. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  740. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  741. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  742. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  743. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  744. },
  745. },
  746. {
  747. LLM_ARCH_INTERNLM2,
  748. {
  749. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  750. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  751. { LLM_TENSOR_OUTPUT, "output" },
  752. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  753. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  754. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  755. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  758. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_MINICPM,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  768. { LLM_TENSOR_OUTPUT, "output" },
  769. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  770. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  771. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  772. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  773. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  774. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  775. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  776. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  777. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  778. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  779. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  780. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  781. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  782. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  783. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  784. },
  785. },
  786. {
  787. LLM_ARCH_GEMMA,
  788. {
  789. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  790. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  791. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  792. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  793. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  794. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  795. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  796. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  797. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  798. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  799. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  800. },
  801. },
  802. {
  803. LLM_ARCH_STARCODER2,
  804. {
  805. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  806. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  807. { LLM_TENSOR_OUTPUT, "output" },
  808. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  809. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  810. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  811. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  812. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  813. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  814. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  815. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  816. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  817. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  818. },
  819. },
  820. {
  821. LLM_ARCH_MAMBA,
  822. {
  823. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  824. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  825. { LLM_TENSOR_OUTPUT, "output" },
  826. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  827. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  828. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  829. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  830. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  831. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  832. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  833. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  834. },
  835. },
  836. {
  837. LLM_ARCH_COMMAND_R,
  838. {
  839. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  840. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  841. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  842. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  843. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  844. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  845. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  846. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  847. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  848. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  849. },
  850. },
  851. {
  852. LLM_ARCH_UNKNOWN,
  853. {
  854. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  855. },
  856. },
  857. };
  858. static llm_arch llm_arch_from_string(const std::string & name) {
  859. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  860. if (kv.second == name) {
  861. return kv.first;
  862. }
  863. }
  864. return LLM_ARCH_UNKNOWN;
  865. }
  866. // helper to handle gguf constants
  867. // usage:
  868. //
  869. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  870. //
  871. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  872. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  873. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  874. //
  875. struct LLM_TN {
  876. LLM_TN(llm_arch arch) : arch(arch) {}
  877. llm_arch arch;
  878. std::string operator()(llm_tensor tensor) const {
  879. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  880. return "__missing__";
  881. }
  882. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  883. }
  884. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  885. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  886. return "__missing__";
  887. }
  888. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  889. }
  890. std::string operator()(llm_tensor tensor, int bid) const {
  891. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  892. return "__missing__";
  893. }
  894. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  895. }
  896. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  897. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  898. return "__missing__";
  899. }
  900. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  901. }
  902. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  903. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  904. return "__missing__";
  905. }
  906. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  907. }
  908. };
  909. //
  910. // gguf helpers
  911. //
  912. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  913. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  914. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  915. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  916. };
  917. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  918. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  919. if (kv.second == name) {
  920. return (llama_rope_scaling_type) kv.first;
  921. }
  922. }
  923. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  924. }
  925. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  926. switch (type) {
  927. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  928. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  929. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  930. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  931. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  932. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  933. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  934. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  935. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  936. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  937. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  938. default: return format("unknown type %d", type);
  939. }
  940. }
  941. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  942. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  943. switch (type) {
  944. case GGUF_TYPE_STRING:
  945. return gguf_get_val_str(ctx_gguf, i);
  946. case GGUF_TYPE_ARRAY:
  947. {
  948. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  949. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  950. const void * data = gguf_get_arr_data(ctx_gguf, i);
  951. std::stringstream ss;
  952. ss << "[";
  953. for (int j = 0; j < arr_n; j++) {
  954. if (arr_type == GGUF_TYPE_STRING) {
  955. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  956. // escape quotes
  957. replace_all(val, "\\", "\\\\");
  958. replace_all(val, "\"", "\\\"");
  959. ss << '"' << val << '"';
  960. } else if (arr_type == GGUF_TYPE_ARRAY) {
  961. ss << "???";
  962. } else {
  963. ss << gguf_data_to_str(arr_type, data, j);
  964. }
  965. if (j < arr_n - 1) {
  966. ss << ", ";
  967. }
  968. }
  969. ss << "]";
  970. return ss.str();
  971. }
  972. default:
  973. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  974. }
  975. }
  976. //
  977. // llama helpers
  978. //
  979. #if defined(_WIN32)
  980. static std::string llama_format_win_err(DWORD err) {
  981. LPSTR buf;
  982. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  983. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  984. if (!size) {
  985. return "FormatMessageA failed";
  986. }
  987. std::string ret(buf, size);
  988. LocalFree(buf);
  989. return ret;
  990. }
  991. #endif
  992. template <typename T>
  993. struct no_init {
  994. T value;
  995. no_init() { /* do nothing */ }
  996. };
  997. struct llama_file {
  998. // use FILE * so we don't have to re-open the file to mmap
  999. FILE * fp;
  1000. size_t size;
  1001. llama_file(const char * fname, const char * mode) {
  1002. fp = ggml_fopen(fname, mode);
  1003. if (fp == NULL) {
  1004. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1005. }
  1006. seek(0, SEEK_END);
  1007. size = tell();
  1008. seek(0, SEEK_SET);
  1009. }
  1010. size_t tell() const {
  1011. #ifdef _WIN32
  1012. __int64 ret = _ftelli64(fp);
  1013. #else
  1014. long ret = std::ftell(fp);
  1015. #endif
  1016. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1017. return (size_t) ret;
  1018. }
  1019. void seek(size_t offset, int whence) const {
  1020. #ifdef _WIN32
  1021. int ret = _fseeki64(fp, (__int64) offset, whence);
  1022. #else
  1023. int ret = std::fseek(fp, (long) offset, whence);
  1024. #endif
  1025. GGML_ASSERT(ret == 0); // same
  1026. }
  1027. void read_raw(void * ptr, size_t len) const {
  1028. if (len == 0) {
  1029. return;
  1030. }
  1031. errno = 0;
  1032. std::size_t ret = std::fread(ptr, len, 1, fp);
  1033. if (ferror(fp)) {
  1034. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1035. }
  1036. if (ret != 1) {
  1037. throw std::runtime_error("unexpectedly reached end of file");
  1038. }
  1039. }
  1040. uint32_t read_u32() const {
  1041. uint32_t ret;
  1042. read_raw(&ret, sizeof(ret));
  1043. return ret;
  1044. }
  1045. void write_raw(const void * ptr, size_t len) const {
  1046. if (len == 0) {
  1047. return;
  1048. }
  1049. errno = 0;
  1050. size_t ret = std::fwrite(ptr, len, 1, fp);
  1051. if (ret != 1) {
  1052. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1053. }
  1054. }
  1055. void write_u32(std::uint32_t val) const {
  1056. write_raw(&val, sizeof(val));
  1057. }
  1058. ~llama_file() {
  1059. if (fp) {
  1060. std::fclose(fp);
  1061. }
  1062. }
  1063. };
  1064. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1065. struct llama_mmap {
  1066. void * addr;
  1067. size_t size;
  1068. llama_mmap(const llama_mmap &) = delete;
  1069. #ifdef _POSIX_MAPPED_FILES
  1070. static constexpr bool SUPPORTED = true;
  1071. // list of mapped fragments (first_offset, last_offset)
  1072. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1073. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1074. size = file->size;
  1075. int fd = fileno(file->fp);
  1076. int flags = MAP_SHARED;
  1077. // prefetch/readahead impairs performance on NUMA systems
  1078. if (numa) { prefetch = 0; }
  1079. #ifdef __linux__
  1080. // advise the kernel to read the file sequentially (increases readahead)
  1081. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1082. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1083. strerror(errno));
  1084. }
  1085. if (prefetch) { flags |= MAP_POPULATE; }
  1086. #endif
  1087. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1088. if (addr == MAP_FAILED) { // NOLINT
  1089. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1090. }
  1091. if (prefetch > 0) {
  1092. // advise the kernel to preload the mapped memory
  1093. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1094. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1095. strerror(errno));
  1096. }
  1097. }
  1098. if (numa) {
  1099. // advise the kernel not to use readahead
  1100. // (because the next page might not belong on the same node)
  1101. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1102. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1103. strerror(errno));
  1104. }
  1105. }
  1106. // initialize list of mapped_fragments
  1107. mapped_fragments.emplace_back(0, file->size);
  1108. }
  1109. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1110. // align first to the next page
  1111. size_t offset_in_page = *first & (page_size - 1);
  1112. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1113. *first += offset_to_page;
  1114. // align last to the previous page
  1115. *last = *last & ~(page_size - 1);
  1116. if (*last <= *first) {
  1117. *last = *first;
  1118. }
  1119. }
  1120. // partially unmap the file in the range [first, last)
  1121. void unmap_fragment(size_t first, size_t last) {
  1122. // note: this function must not be called multiple times with overlapping ranges
  1123. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1124. int page_size = sysconf(_SC_PAGESIZE);
  1125. align_range(&first, &last, page_size);
  1126. size_t len = last - first;
  1127. if (len == 0) {
  1128. return;
  1129. }
  1130. GGML_ASSERT(first % page_size == 0);
  1131. GGML_ASSERT(last % page_size == 0);
  1132. GGML_ASSERT(last > first);
  1133. void * next_page_start = (uint8_t *) addr + first;
  1134. // unmap the range
  1135. if (munmap(next_page_start, len)) {
  1136. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1137. }
  1138. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1139. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1140. for (const auto & frag : mapped_fragments) {
  1141. if (frag.first < first && frag.second > last) {
  1142. // the range is in the middle of the fragment, split it
  1143. new_mapped_fragments.emplace_back(frag.first, first);
  1144. new_mapped_fragments.emplace_back(last, frag.second);
  1145. } else if (frag.first < first && frag.second > first) {
  1146. // the range starts in the middle of the fragment
  1147. new_mapped_fragments.emplace_back(frag.first, first);
  1148. } else if (frag.first < last && frag.second > last) {
  1149. // the range ends in the middle of the fragment
  1150. new_mapped_fragments.emplace_back(last, frag.second);
  1151. } else if (frag.first >= first && frag.second <= last) {
  1152. // the range covers the entire fragment
  1153. } else {
  1154. // the range is outside the fragment
  1155. new_mapped_fragments.push_back(frag);
  1156. }
  1157. }
  1158. mapped_fragments = std::move(new_mapped_fragments);
  1159. }
  1160. ~llama_mmap() {
  1161. for (const auto & frag : mapped_fragments) {
  1162. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1163. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1164. }
  1165. }
  1166. }
  1167. #elif defined(_WIN32)
  1168. static constexpr bool SUPPORTED = true;
  1169. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1170. GGML_UNUSED(numa);
  1171. size = file->size;
  1172. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1173. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1174. if (hMapping == NULL) {
  1175. DWORD error = GetLastError();
  1176. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1177. }
  1178. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1179. DWORD error = GetLastError();
  1180. CloseHandle(hMapping);
  1181. if (addr == NULL) {
  1182. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1183. }
  1184. if (prefetch > 0) {
  1185. #if _WIN32_WINNT >= 0x602
  1186. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1187. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1188. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1189. // may fail on pre-Windows 8 systems
  1190. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1191. if (pPrefetchVirtualMemory) {
  1192. // advise the kernel to preload the mapped memory
  1193. WIN32_MEMORY_RANGE_ENTRY range;
  1194. range.VirtualAddress = addr;
  1195. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1196. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1197. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1198. llama_format_win_err(GetLastError()).c_str());
  1199. }
  1200. }
  1201. #else
  1202. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1203. #endif
  1204. }
  1205. }
  1206. void unmap_fragment(size_t first, size_t last) {
  1207. // not supported
  1208. GGML_UNUSED(first);
  1209. GGML_UNUSED(last);
  1210. }
  1211. ~llama_mmap() {
  1212. if (!UnmapViewOfFile(addr)) {
  1213. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1214. llama_format_win_err(GetLastError()).c_str());
  1215. }
  1216. }
  1217. #else
  1218. static constexpr bool SUPPORTED = false;
  1219. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1220. GGML_UNUSED(file);
  1221. GGML_UNUSED(prefetch);
  1222. GGML_UNUSED(numa);
  1223. throw std::runtime_error("mmap not supported");
  1224. }
  1225. void unmap_fragment(size_t first, size_t last) {
  1226. GGML_UNUSED(first);
  1227. GGML_UNUSED(last);
  1228. throw std::runtime_error("mmap not supported");
  1229. }
  1230. #endif
  1231. };
  1232. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1233. // Represents some region of memory being locked using mlock or VirtualLock;
  1234. // will automatically unlock on destruction.
  1235. struct llama_mlock {
  1236. void * addr = NULL;
  1237. size_t size = 0;
  1238. bool failed_already = false;
  1239. llama_mlock() {}
  1240. llama_mlock(const llama_mlock &) = delete;
  1241. ~llama_mlock() {
  1242. if (size) {
  1243. raw_unlock(addr, size);
  1244. }
  1245. }
  1246. void init(void * ptr) {
  1247. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1248. addr = ptr;
  1249. }
  1250. void grow_to(size_t target_size) {
  1251. GGML_ASSERT(addr);
  1252. if (failed_already) {
  1253. return;
  1254. }
  1255. size_t granularity = lock_granularity();
  1256. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1257. if (target_size > size) {
  1258. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1259. size = target_size;
  1260. } else {
  1261. failed_already = true;
  1262. }
  1263. }
  1264. }
  1265. #ifdef _POSIX_MEMLOCK_RANGE
  1266. static constexpr bool SUPPORTED = true;
  1267. static size_t lock_granularity() {
  1268. return (size_t) sysconf(_SC_PAGESIZE);
  1269. }
  1270. #ifdef __APPLE__
  1271. #define MLOCK_SUGGESTION \
  1272. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1273. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1274. #else
  1275. #define MLOCK_SUGGESTION \
  1276. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1277. #endif
  1278. bool raw_lock(const void * addr, size_t size) const {
  1279. if (!mlock(addr, size)) {
  1280. return true;
  1281. }
  1282. char* errmsg = std::strerror(errno);
  1283. bool suggest = (errno == ENOMEM);
  1284. // Check if the resource limit is fine after all
  1285. struct rlimit lock_limit;
  1286. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1287. suggest = false;
  1288. }
  1289. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1290. suggest = false;
  1291. }
  1292. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1293. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1294. return false;
  1295. }
  1296. #undef MLOCK_SUGGESTION
  1297. static void raw_unlock(void * addr, size_t size) {
  1298. if (munlock(addr, size)) {
  1299. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1300. }
  1301. }
  1302. #elif defined(_WIN32)
  1303. static constexpr bool SUPPORTED = true;
  1304. static size_t lock_granularity() {
  1305. SYSTEM_INFO si;
  1306. GetSystemInfo(&si);
  1307. return (size_t) si.dwPageSize;
  1308. }
  1309. bool raw_lock(void * ptr, size_t len) const {
  1310. for (int tries = 1; ; tries++) {
  1311. if (VirtualLock(ptr, len)) {
  1312. return true;
  1313. }
  1314. if (tries == 2) {
  1315. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1316. len, size, llama_format_win_err(GetLastError()).c_str());
  1317. return false;
  1318. }
  1319. // It failed but this was only the first try; increase the working
  1320. // set size and try again.
  1321. SIZE_T min_ws_size, max_ws_size;
  1322. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1323. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1324. llama_format_win_err(GetLastError()).c_str());
  1325. return false;
  1326. }
  1327. // Per MSDN: "The maximum number of pages that a process can lock
  1328. // is equal to the number of pages in its minimum working set minus
  1329. // a small overhead."
  1330. // Hopefully a megabyte is enough overhead:
  1331. size_t increment = len + 1048576;
  1332. // The minimum must be <= the maximum, so we need to increase both:
  1333. min_ws_size += increment;
  1334. max_ws_size += increment;
  1335. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1336. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1337. llama_format_win_err(GetLastError()).c_str());
  1338. return false;
  1339. }
  1340. }
  1341. }
  1342. static void raw_unlock(void * ptr, size_t len) {
  1343. if (!VirtualUnlock(ptr, len)) {
  1344. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1345. llama_format_win_err(GetLastError()).c_str());
  1346. }
  1347. }
  1348. #else
  1349. static constexpr bool SUPPORTED = false;
  1350. static size_t lock_granularity() {
  1351. return (size_t) 65536;
  1352. }
  1353. bool raw_lock(const void * addr, size_t len) const {
  1354. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1355. return false;
  1356. }
  1357. static void raw_unlock(const void * addr, size_t len) {}
  1358. #endif
  1359. };
  1360. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1361. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1362. std::vector<char> result(8, 0);
  1363. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1364. if (n_tokens < 0) {
  1365. result.resize(-n_tokens);
  1366. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1367. GGML_ASSERT(check == -n_tokens);
  1368. }
  1369. else {
  1370. result.resize(n_tokens);
  1371. }
  1372. return std::string(result.data(), result.size());
  1373. }
  1374. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1375. ggml_backend_buffer_type_t buft = nullptr;
  1376. #if defined(GGML_USE_CUDA)
  1377. // host buffers should only be used when data is expected to be copied to/from the GPU
  1378. if (host_buffer) {
  1379. buft = ggml_backend_cuda_host_buffer_type();
  1380. }
  1381. #elif defined(GGML_USE_SYCL)
  1382. if (host_buffer) {
  1383. buft = ggml_backend_sycl_host_buffer_type();
  1384. }
  1385. #elif defined(GGML_USE_CPU_HBM)
  1386. buft = ggml_backend_cpu_hbm_buffer_type();
  1387. #elif defined(GGML_USE_VULKAN)
  1388. if (host_buffer) {
  1389. buft = ggml_backend_vk_host_buffer_type();
  1390. }
  1391. #endif
  1392. if (buft == nullptr) {
  1393. buft = ggml_backend_cpu_buffer_type();
  1394. }
  1395. return buft;
  1396. GGML_UNUSED(host_buffer);
  1397. }
  1398. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1399. ggml_backend_buffer_type_t buft = nullptr;
  1400. #ifdef GGML_USE_METAL
  1401. buft = ggml_backend_metal_buffer_type();
  1402. #elif defined(GGML_USE_CUDA)
  1403. buft = ggml_backend_cuda_buffer_type(gpu);
  1404. #elif defined(GGML_USE_VULKAN)
  1405. buft = ggml_backend_vk_buffer_type(gpu);
  1406. #elif defined(GGML_USE_SYCL)
  1407. buft = ggml_backend_sycl_buffer_type(gpu);
  1408. #elif defined(GGML_USE_CLBLAST)
  1409. buft = ggml_backend_opencl_buffer_type();
  1410. #elif defined(GGML_USE_KOMPUTE)
  1411. buft = ggml_backend_kompute_buffer_type(gpu);
  1412. if (buft == nullptr) {
  1413. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1414. }
  1415. #endif
  1416. if (buft == nullptr) {
  1417. buft = llama_default_buffer_type_cpu(true);
  1418. }
  1419. return buft;
  1420. GGML_UNUSED(gpu);
  1421. }
  1422. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1423. ggml_backend_buffer_type_t buft = nullptr;
  1424. #ifdef GGML_USE_CUDA
  1425. if (ggml_backend_cuda_get_device_count() > 1) {
  1426. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1427. }
  1428. #endif
  1429. #ifdef GGML_USE_SYCL
  1430. if (ggml_backend_sycl_get_device_count() > 1) {
  1431. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1432. }
  1433. #endif
  1434. if (buft == nullptr) {
  1435. buft = llama_default_buffer_type_offload(fallback_gpu);
  1436. }
  1437. return buft;
  1438. GGML_UNUSED(tensor_split);
  1439. }
  1440. static size_t llama_get_device_count() {
  1441. #if defined(GGML_USE_CUDA)
  1442. return ggml_backend_cuda_get_device_count();
  1443. #elif defined(GGML_USE_SYCL)
  1444. return ggml_backend_sycl_get_device_count();
  1445. #elif defined(GGML_USE_VULKAN)
  1446. return ggml_backend_vk_get_device_count();
  1447. #else
  1448. return 1;
  1449. #endif
  1450. }
  1451. static size_t llama_get_device_memory(int device) {
  1452. #if defined(GGML_USE_CUDA)
  1453. size_t total;
  1454. size_t free;
  1455. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1456. return free;
  1457. #elif defined(GGML_USE_SYCL)
  1458. size_t total;
  1459. size_t free;
  1460. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1461. return free;
  1462. #elif defined(GGML_USE_VULKAN)
  1463. size_t total;
  1464. size_t free;
  1465. ggml_backend_vk_get_device_memory(device, &total, &free);
  1466. return free;
  1467. #else
  1468. return 1;
  1469. GGML_UNUSED(device);
  1470. #endif
  1471. }
  1472. //
  1473. // globals
  1474. //
  1475. struct llama_state {
  1476. llama_state() {
  1477. #ifdef GGML_USE_METAL
  1478. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1479. #endif
  1480. }
  1481. // We save the log callback globally
  1482. ggml_log_callback log_callback = llama_log_callback_default;
  1483. void * log_callback_user_data = nullptr;
  1484. };
  1485. static llama_state g_state;
  1486. // available llama models
  1487. enum e_model {
  1488. MODEL_UNKNOWN,
  1489. MODEL_17M,
  1490. MODEL_22M,
  1491. MODEL_33M,
  1492. MODEL_109M,
  1493. MODEL_137M,
  1494. MODEL_335M,
  1495. MODEL_0_5B,
  1496. MODEL_1B,
  1497. MODEL_2B,
  1498. MODEL_3B,
  1499. MODEL_4B,
  1500. MODEL_7B,
  1501. MODEL_8B,
  1502. MODEL_13B,
  1503. MODEL_14B,
  1504. MODEL_15B,
  1505. MODEL_20B,
  1506. MODEL_30B,
  1507. MODEL_34B,
  1508. MODEL_35B,
  1509. MODEL_40B,
  1510. MODEL_65B,
  1511. MODEL_70B,
  1512. MODEL_314B,
  1513. MODEL_SMALL,
  1514. MODEL_MEDIUM,
  1515. MODEL_LARGE,
  1516. MODEL_XL,
  1517. };
  1518. static const size_t kiB = 1024;
  1519. static const size_t MiB = 1024*kiB;
  1520. static const size_t GiB = 1024*MiB;
  1521. struct llama_hparams {
  1522. bool vocab_only;
  1523. bool rope_finetuned;
  1524. uint32_t n_vocab;
  1525. uint32_t n_ctx_train; // context size the model was trained on
  1526. uint32_t n_embd;
  1527. uint32_t n_head;
  1528. uint32_t n_head_kv;
  1529. uint32_t n_layer;
  1530. uint32_t n_rot;
  1531. uint32_t n_embd_head_k; // dimension of keys (d_k). d_q is assumed to be the same, but there are n_head q heads, and only n_head_kv k-v heads
  1532. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1533. uint32_t n_ff;
  1534. uint32_t n_expert = 0;
  1535. uint32_t n_expert_used = 0;
  1536. uint32_t n_vocab_type = 0; // for BERT-style token types
  1537. float f_norm_eps;
  1538. float f_norm_rms_eps;
  1539. float rope_freq_base_train;
  1540. float rope_freq_scale_train;
  1541. uint32_t n_yarn_orig_ctx;
  1542. // for State Space Models
  1543. uint32_t ssm_d_conv = 0;
  1544. uint32_t ssm_d_inner = 0;
  1545. uint32_t ssm_d_state = 0;
  1546. uint32_t ssm_dt_rank = 0;
  1547. float f_clamp_kqv = 0.0f;
  1548. float f_max_alibi_bias = 0.0f;
  1549. float f_logit_scale = 0.0f;
  1550. bool causal_attn = true;
  1551. bool need_kq_pos = false;
  1552. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1553. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1554. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1555. bool operator!=(const llama_hparams & other) const {
  1556. if (this->vocab_only != other.vocab_only) return true;
  1557. if (this->n_vocab != other.n_vocab) return true;
  1558. if (this->n_ctx_train != other.n_ctx_train) return true;
  1559. if (this->n_embd != other.n_embd) return true;
  1560. if (this->n_head != other.n_head) return true;
  1561. if (this->n_head_kv != other.n_head_kv) return true;
  1562. if (this->n_layer != other.n_layer) return true;
  1563. if (this->n_rot != other.n_rot) return true;
  1564. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1565. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1566. if (this->n_ff != other.n_ff) return true;
  1567. if (this->n_expert != other.n_expert) return true;
  1568. if (this->n_expert_used != other.n_expert_used) return true;
  1569. if (this->rope_finetuned != other.rope_finetuned) return true;
  1570. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1571. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1572. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1573. if (this->ssm_d_state != other.ssm_d_state) return true;
  1574. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1575. const float EPSILON = 1e-9f;
  1576. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1577. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1578. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1579. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1580. return false;
  1581. }
  1582. uint32_t n_gqa() const {
  1583. if (n_head_kv == 0) {
  1584. return 0;
  1585. }
  1586. return n_head/n_head_kv;
  1587. }
  1588. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1589. return n_embd_head_k * n_head_kv;
  1590. }
  1591. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1592. return n_embd_head_v * n_head_kv;
  1593. }
  1594. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1595. // corresponds to Mamba's conv_states size
  1596. // TODO: maybe support other convolution strides than 1
  1597. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1598. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1599. }
  1600. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1601. // corresponds to Mamba's ssm_states size
  1602. return ssm_d_state * ssm_d_inner;
  1603. }
  1604. };
  1605. struct llama_cparams {
  1606. uint32_t n_ctx; // context size used during inference
  1607. uint32_t n_batch;
  1608. uint32_t n_ubatch;
  1609. uint32_t n_threads; // number of threads to use for generation
  1610. uint32_t n_threads_batch; // number of threads to use for batch processing
  1611. float rope_freq_base;
  1612. float rope_freq_scale;
  1613. uint32_t n_yarn_orig_ctx;
  1614. // These hyperparameters are not exposed in GGUF, because all
  1615. // existing YaRN models use the same values for them.
  1616. float yarn_ext_factor;
  1617. float yarn_attn_factor;
  1618. float yarn_beta_fast;
  1619. float yarn_beta_slow;
  1620. float defrag_thold;
  1621. bool embeddings;
  1622. bool causal_attn;
  1623. bool offload_kqv;
  1624. enum llama_pooling_type pooling_type;
  1625. ggml_backend_sched_eval_callback cb_eval;
  1626. void * cb_eval_user_data;
  1627. };
  1628. struct llama_layer {
  1629. // normalization
  1630. struct ggml_tensor * attn_norm;
  1631. struct ggml_tensor * attn_norm_b;
  1632. struct ggml_tensor * attn_norm_2;
  1633. struct ggml_tensor * attn_norm_2_b;
  1634. struct ggml_tensor * attn_q_norm;
  1635. struct ggml_tensor * attn_q_norm_b;
  1636. struct ggml_tensor * attn_k_norm;
  1637. struct ggml_tensor * attn_k_norm_b;
  1638. struct ggml_tensor * attn_out_norm;
  1639. struct ggml_tensor * attn_out_norm_b;
  1640. // attention
  1641. struct ggml_tensor * wq;
  1642. struct ggml_tensor * wk;
  1643. struct ggml_tensor * wv;
  1644. struct ggml_tensor * wo;
  1645. struct ggml_tensor * wqkv;
  1646. // attention bias
  1647. struct ggml_tensor * bq;
  1648. struct ggml_tensor * bk;
  1649. struct ggml_tensor * bv;
  1650. struct ggml_tensor * bo;
  1651. struct ggml_tensor * bqkv;
  1652. // normalization
  1653. struct ggml_tensor * ffn_norm;
  1654. struct ggml_tensor * ffn_norm_b;
  1655. struct ggml_tensor * layer_out_norm;
  1656. struct ggml_tensor * layer_out_norm_b;
  1657. // ff
  1658. struct ggml_tensor * ffn_gate; // w1
  1659. struct ggml_tensor * ffn_down; // w2
  1660. struct ggml_tensor * ffn_up; // w3
  1661. // ff MoE
  1662. struct ggml_tensor * ffn_gate_inp;
  1663. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1664. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1665. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1666. // ff bias
  1667. struct ggml_tensor * ffn_down_b; // b2
  1668. struct ggml_tensor * ffn_up_b; // b3
  1669. struct ggml_tensor * ffn_act;
  1670. // mamba proj
  1671. struct ggml_tensor * ssm_in;
  1672. struct ggml_tensor * ssm_x;
  1673. struct ggml_tensor * ssm_dt;
  1674. struct ggml_tensor * ssm_out;
  1675. // mamba
  1676. struct ggml_tensor * ssm_conv1d;
  1677. struct ggml_tensor * ssm_a;
  1678. struct ggml_tensor * ssm_d;
  1679. // mamba bias
  1680. struct ggml_tensor * ssm_conv1d_b;
  1681. struct ggml_tensor * ssm_dt_b;
  1682. };
  1683. struct llama_kv_cell {
  1684. llama_pos pos = -1;
  1685. llama_pos delta = 0;
  1686. int32_t src = 0; // used by recurrent state models to copy states
  1687. std::set<llama_seq_id> seq_id;
  1688. bool has_seq_id(const llama_seq_id & id) const {
  1689. return seq_id.find(id) != seq_id.end();
  1690. }
  1691. bool is_empty() const {
  1692. return seq_id.empty();
  1693. }
  1694. bool is_same_seq(const llama_kv_cell & other) const {
  1695. return seq_id == other.seq_id;
  1696. }
  1697. };
  1698. // ring-buffer of cached KV data
  1699. struct llama_kv_cache {
  1700. bool has_shift = false;
  1701. bool do_defrag = false;
  1702. bool do_copy = false;
  1703. // with recurrent state models, a cell can hold the state for more than one past token
  1704. bool recurrent = false;
  1705. // Note: The value of head isn't only used to optimize searching
  1706. // for a free KV slot. llama_decode_internal also uses it, so it
  1707. // cannot be freely changed after a slot has been allocated.
  1708. uint32_t head = 0;
  1709. uint32_t size = 0;
  1710. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1711. // computed before each graph build
  1712. uint32_t n = 0;
  1713. ggml_type type_k = GGML_TYPE_F16;
  1714. ggml_type type_v = GGML_TYPE_F16;
  1715. std::vector<llama_kv_cell> cells;
  1716. std::vector<struct ggml_tensor *> k_l; // per layer
  1717. std::vector<struct ggml_tensor *> v_l;
  1718. std::vector<struct ggml_context *> ctxs;
  1719. std::vector<ggml_backend_buffer_t> bufs;
  1720. size_t total_size() const {
  1721. size_t size = 0;
  1722. for (ggml_backend_buffer_t buf : bufs) {
  1723. size += ggml_backend_buffer_get_size(buf);
  1724. }
  1725. return size;
  1726. }
  1727. ~llama_kv_cache() {
  1728. for (struct ggml_context * ctx : ctxs) {
  1729. ggml_free(ctx);
  1730. }
  1731. for (ggml_backend_buffer_t buf : bufs) {
  1732. ggml_backend_buffer_free(buf);
  1733. }
  1734. }
  1735. };
  1736. struct llama_control_vector {
  1737. std::vector<struct ggml_tensor *> tensors; // per layer
  1738. std::vector<struct ggml_context *> ctxs;
  1739. std::vector<ggml_backend_buffer_t> bufs;
  1740. int32_t layer_start = -1;
  1741. int32_t layer_end = -1;
  1742. ggml_tensor * tensor_for(int il) const {
  1743. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1744. return nullptr;
  1745. }
  1746. return tensors[il];
  1747. }
  1748. ~llama_control_vector() {
  1749. for (struct ggml_context * ctx : ctxs) {
  1750. ggml_free(ctx);
  1751. }
  1752. for (ggml_backend_buffer_t buf : bufs) {
  1753. ggml_backend_buffer_free(buf);
  1754. }
  1755. }
  1756. };
  1757. struct llama_vocab {
  1758. using id = int32_t;
  1759. using token = std::string;
  1760. using ttype = llama_token_type;
  1761. struct token_data {
  1762. token text;
  1763. float score;
  1764. ttype type;
  1765. };
  1766. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1767. std::unordered_map<token, id> token_to_id;
  1768. std::vector<token_data> id_to_token;
  1769. std::unordered_map<token, id> special_tokens_cache;
  1770. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1771. // default LLaMA special tokens
  1772. id special_bos_id = 1;
  1773. id special_eos_id = 2;
  1774. id special_unk_id = 0;
  1775. id special_sep_id = -1;
  1776. id special_pad_id = -1;
  1777. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1778. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1779. id linefeed_id = 13;
  1780. id special_prefix_id = 32007;
  1781. id special_middle_id = 32009;
  1782. id special_suffix_id = 32008;
  1783. id special_eot_id = 32010;
  1784. bool add_space_prefix = true;
  1785. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1786. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1787. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1788. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1789. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1790. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1791. if (it == bpe_ranks.end()) {
  1792. return -1;
  1793. }
  1794. return it->second;
  1795. }
  1796. };
  1797. struct llama_model {
  1798. e_model type = MODEL_UNKNOWN;
  1799. llm_arch arch = LLM_ARCH_UNKNOWN;
  1800. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1801. std::string name = "n/a";
  1802. llama_hparams hparams = {};
  1803. llama_vocab vocab;
  1804. struct ggml_tensor * tok_embd;
  1805. struct ggml_tensor * type_embd;
  1806. struct ggml_tensor * pos_embd;
  1807. struct ggml_tensor * tok_norm;
  1808. struct ggml_tensor * tok_norm_b;
  1809. struct ggml_tensor * output_norm;
  1810. struct ggml_tensor * output_norm_b;
  1811. struct ggml_tensor * output;
  1812. struct ggml_tensor * output_b;
  1813. std::vector<llama_layer> layers;
  1814. llama_split_mode split_mode;
  1815. int main_gpu;
  1816. int n_gpu_layers;
  1817. // gguf metadata
  1818. std::unordered_map<std::string, std::string> gguf_kv;
  1819. // layer -> buffer type mapping
  1820. struct layer_buft {
  1821. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1822. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1823. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1824. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1825. ggml_backend_buffer_type_t buft; // everything else
  1826. };
  1827. layer_buft buft_input;
  1828. layer_buft buft_output;
  1829. std::vector<layer_buft> buft_layer;
  1830. // contexts where the model tensors metadata is stored
  1831. std::vector<struct ggml_context *> ctxs;
  1832. // the model memory buffers for the tensor data
  1833. std::vector<ggml_backend_buffer_t> bufs;
  1834. // model memory mapped files
  1835. llama_mmaps mappings;
  1836. // objects representing data potentially being locked in memory
  1837. llama_mlocks mlock_bufs;
  1838. llama_mlocks mlock_mmaps;
  1839. // for quantize-stats only
  1840. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1841. int64_t t_load_us = 0;
  1842. int64_t t_start_us = 0;
  1843. ~llama_model() {
  1844. for (struct ggml_context * ctx : ctxs) {
  1845. ggml_free(ctx);
  1846. }
  1847. for (ggml_backend_buffer_t buf : bufs) {
  1848. #ifdef GGML_USE_CUDA
  1849. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1850. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1851. }
  1852. #endif
  1853. ggml_backend_buffer_free(buf);
  1854. }
  1855. }
  1856. };
  1857. struct llama_context {
  1858. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1859. ~llama_context() {
  1860. ggml_backend_sched_free(sched);
  1861. for (ggml_backend_t backend : backends) {
  1862. ggml_backend_free(backend);
  1863. }
  1864. #ifdef GGML_USE_VULKAN
  1865. ggml_vk_free_cpu_assist();
  1866. #endif
  1867. ggml_backend_buffer_free(buf_output);
  1868. }
  1869. llama_cparams cparams;
  1870. std::vector<ggml_backend_t> backends;
  1871. #ifdef GGML_USE_METAL
  1872. ggml_backend_t backend_metal = nullptr;
  1873. #endif
  1874. ggml_backend_t backend_cpu = nullptr;
  1875. const llama_model & model;
  1876. // key + value cache for the self attention
  1877. struct llama_kv_cache kv_self;
  1878. std::mt19937 rng;
  1879. bool has_evaluated_once = false;
  1880. int64_t t_start_us;
  1881. int64_t t_load_us;
  1882. int64_t t_sample_us = 0;
  1883. int64_t t_p_eval_us = 0;
  1884. int64_t t_eval_us = 0;
  1885. int64_t t_compute_start_us = 0;
  1886. int64_t n_queued_tokens = 0;
  1887. int32_t n_sample = 0; // number of tokens sampled
  1888. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1889. int32_t n_eval = 0; // number of eval calls
  1890. // host buffer for the model output (logits and embeddings)
  1891. ggml_backend_buffer_t buf_output = nullptr;
  1892. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1893. size_t logits_size = 0;
  1894. float * logits = nullptr;
  1895. #ifndef NDEBUG
  1896. // guard against access to unset logits
  1897. std::vector<bool> logits_valid;
  1898. #endif
  1899. bool logits_all = false;
  1900. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1901. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1902. size_t embd_size = 0;
  1903. float * embd = nullptr;
  1904. // sequence embeddings output (map of [n_embd] vectors)
  1905. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1906. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1907. // memory buffers used to evaluate the model
  1908. std::vector<uint8_t> buf_compute_meta;
  1909. ggml_backend_sched_t sched = nullptr;
  1910. ggml_abort_callback abort_callback = nullptr;
  1911. void * abort_callback_data = nullptr;
  1912. // input tensors
  1913. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1914. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1915. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1916. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1917. struct ggml_tensor * inp_KQ_pos; // F32 [kv_size]
  1918. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1919. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1920. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1921. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1922. struct ggml_tensor * inp_s_mask; // F32 [1, kv_size]
  1923. struct ggml_tensor * inp_s_seq; // I32 [kv_size, n_batch]
  1924. // control vectors
  1925. struct llama_control_vector cvec;
  1926. #ifdef GGML_USE_MPI
  1927. ggml_mpi_context * ctx_mpi = NULL;
  1928. #endif
  1929. };
  1930. //
  1931. // kv cache helpers
  1932. //
  1933. static bool llama_kv_cache_init(
  1934. struct llama_kv_cache & cache,
  1935. const llama_model & model,
  1936. ggml_type type_k,
  1937. ggml_type type_v,
  1938. uint32_t kv_size,
  1939. bool offload) {
  1940. const struct llama_hparams & hparams = model.hparams;
  1941. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1942. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1943. const int64_t n_layer = hparams.n_layer;
  1944. cache.has_shift = false;
  1945. // TODO: find a nicer way to add other recurrent model architectures
  1946. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1947. // TODO: support mixed reccurent Transformer architectues
  1948. // NOTE: (!a || b) is a logical implication (a -> b)
  1949. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1950. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1951. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1952. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1953. cache.head = 0;
  1954. cache.size = kv_size;
  1955. cache.used = 0;
  1956. cache.type_k = type_k;
  1957. cache.type_v = type_v;
  1958. cache.cells.clear();
  1959. cache.cells.resize(kv_size);
  1960. if (cache.recurrent) {
  1961. // init state copy sources
  1962. for (uint32_t i = 0; i < cache.size; ++i) {
  1963. cache.cells[i].src = i;
  1964. }
  1965. }
  1966. #ifdef GGML_USE_CLBLAST
  1967. offload = false;
  1968. #endif
  1969. // count used buffer types
  1970. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1971. if (offload) {
  1972. for (int64_t i = 0; i < n_layer; ++i) {
  1973. buft_layer_count[model.buft_layer[i].buft]++;
  1974. }
  1975. } else {
  1976. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1977. }
  1978. // create a context for each buffer type
  1979. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1980. for (auto & it : buft_layer_count) {
  1981. int n_layers = it.second;
  1982. struct ggml_init_params params = {
  1983. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1984. /*.mem_buffer =*/ NULL,
  1985. /*.no_alloc =*/ true,
  1986. };
  1987. ggml_context * ctx = ggml_init(params);
  1988. if (!ctx) {
  1989. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1990. return false;
  1991. }
  1992. ctx_map[it.first] = ctx;
  1993. cache.ctxs.push_back(ctx);
  1994. }
  1995. cache.k_l.reserve(n_layer);
  1996. cache.v_l.reserve(n_layer);
  1997. for (int i = 0; i < (int) n_layer; i++) {
  1998. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1999. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2000. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2001. ggml_format_name(k, "cache_k_l%d", i);
  2002. ggml_format_name(v, "cache_v_l%d", i);
  2003. cache.k_l.push_back(k);
  2004. cache.v_l.push_back(v);
  2005. }
  2006. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2007. for (auto it : ctx_map) {
  2008. ggml_backend_buffer_type_t buft = it.first;
  2009. ggml_context * ctx = it.second;
  2010. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2011. if (!buf) {
  2012. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2013. return false;
  2014. }
  2015. ggml_backend_buffer_clear(buf, 0);
  2016. LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
  2017. cache.bufs.push_back(buf);
  2018. }
  2019. return true;
  2020. }
  2021. // find an empty slot of size "n_tokens" in the cache
  2022. // updates the cache head
  2023. // Note: On success, it's important that cache.head points
  2024. // to the first cell of the slot.
  2025. static bool llama_kv_cache_find_slot(
  2026. struct llama_kv_cache & cache,
  2027. const struct llama_batch & batch) {
  2028. const uint32_t n_ctx = cache.size;
  2029. const uint32_t n_tokens = batch.n_tokens;
  2030. if (cache.recurrent) {
  2031. // For recurrent state architectures (like Mamba),
  2032. // each KV cache cell can store the state for a whole sequence.
  2033. llama_seq_id min = cache.size - 1;
  2034. llama_seq_id max = 0;
  2035. for (uint32_t i = 0; i < n_tokens; ++i) {
  2036. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2037. llama_seq_id seq_id = batch.seq_id[i][j];
  2038. // make sure it's a valid seq_id
  2039. if ((uint32_t) seq_id < cache.size) {
  2040. if (seq_id > max) {
  2041. max = seq_id;
  2042. }
  2043. if (seq_id < min) {
  2044. min = seq_id;
  2045. }
  2046. // Assuming the tokens are in-order
  2047. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2048. // What should happen when the pos backtracks or skips a value?
  2049. // Clearing the state mid-batch would require special-casing which isn't done.
  2050. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2051. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2052. }
  2053. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2054. cache.used += 1;
  2055. }
  2056. cache.cells[seq_id].pos = batch.pos[i];
  2057. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2058. } else {
  2059. // too big seq_id
  2060. // TODO: would it be possible to resize the KV cache size instead?
  2061. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2062. return false;
  2063. }
  2064. }
  2065. }
  2066. // allow getting the range of used cells, from head to head + n
  2067. cache.head = min;
  2068. cache.n = max - min + 1;
  2069. // sanity check
  2070. return max >= min;
  2071. }
  2072. // otherwise, one cell per token.
  2073. if (n_tokens > n_ctx) {
  2074. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2075. return false;
  2076. }
  2077. uint32_t n_tested = 0;
  2078. while (true) {
  2079. if (cache.head + n_tokens > n_ctx) {
  2080. n_tested += n_ctx - cache.head;
  2081. cache.head = 0;
  2082. continue;
  2083. }
  2084. bool found = true;
  2085. for (uint32_t i = 0; i < n_tokens; i++) {
  2086. if (cache.cells[cache.head + i].pos >= 0) {
  2087. found = false;
  2088. cache.head += i + 1;
  2089. n_tested += i + 1;
  2090. break;
  2091. }
  2092. }
  2093. if (found) {
  2094. break;
  2095. }
  2096. if (n_tested >= n_ctx) {
  2097. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2098. return false;
  2099. }
  2100. }
  2101. for (uint32_t i = 0; i < n_tokens; i++) {
  2102. cache.cells[cache.head + i].pos = batch.pos[i];
  2103. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2104. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2105. }
  2106. }
  2107. cache.used += n_tokens;
  2108. return true;
  2109. }
  2110. // find how many cells are currently in use
  2111. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2112. for (uint32_t i = cache.size; i > 0; --i) {
  2113. const llama_kv_cell & cell = cache.cells[i - 1];
  2114. if (cell.pos >= 0 && !cell.is_empty()) {
  2115. return i;
  2116. }
  2117. }
  2118. return 0;
  2119. }
  2120. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2121. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2122. cache.cells[i].pos = -1;
  2123. cache.cells[i].seq_id.clear();
  2124. }
  2125. cache.head = 0;
  2126. cache.used = 0;
  2127. }
  2128. static bool llama_kv_cache_seq_rm(
  2129. struct llama_kv_cache & cache,
  2130. llama_seq_id seq_id,
  2131. llama_pos p0,
  2132. llama_pos p1) {
  2133. uint32_t new_head = cache.size;
  2134. if (p0 < 0) p0 = 0;
  2135. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2136. // models like Mamba can't have a state partially erased
  2137. if (cache.recurrent) {
  2138. if (seq_id >= (int64_t) cache.size) {
  2139. // could be fatal
  2140. return false;
  2141. }
  2142. if (0 <= seq_id) {
  2143. // partial intersection is invalid
  2144. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2145. return false;
  2146. }
  2147. } else {
  2148. // seq_id is negative, then the range should include everything or nothing
  2149. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2150. return false;
  2151. }
  2152. }
  2153. }
  2154. for (uint32_t i = 0; i < cache.size; ++i) {
  2155. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2156. if (seq_id < 0) {
  2157. cache.cells[i].seq_id.clear();
  2158. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2159. cache.cells[i].seq_id.erase(seq_id);
  2160. } else {
  2161. continue;
  2162. }
  2163. if (cache.cells[i].is_empty()) {
  2164. // keep count of the number of used cells
  2165. if (cache.cells[i].pos >= 0) cache.used--;
  2166. cache.cells[i].pos = -1;
  2167. if (new_head == cache.size) new_head = i;
  2168. }
  2169. }
  2170. }
  2171. // If we freed up a slot, set head to it so searching can start there.
  2172. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2173. return true;
  2174. }
  2175. static void llama_kv_cache_seq_cp(
  2176. struct llama_kv_cache & cache,
  2177. llama_seq_id seq_id_src,
  2178. llama_seq_id seq_id_dst,
  2179. llama_pos p0,
  2180. llama_pos p1) {
  2181. if (p0 < 0) p0 = 0;
  2182. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2183. if (cache.recurrent) {
  2184. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2185. seq_id_src = cache.cells[seq_id_src].src;
  2186. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2187. // intent to "copy from"
  2188. // supports copy chains thanks to taking the source of the source
  2189. cache.cells[seq_id_dst].src = seq_id_src;
  2190. // preserve the "keep or clear" status of the copied sequence
  2191. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2192. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2193. } else {
  2194. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2195. }
  2196. cache.do_copy = true;
  2197. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2198. }
  2199. return;
  2200. }
  2201. // otherwise, this is the KV cache of a Transformer-like model
  2202. cache.head = 0;
  2203. for (uint32_t i = 0; i < cache.size; ++i) {
  2204. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2205. cache.cells[i].seq_id.insert(seq_id_dst);
  2206. }
  2207. }
  2208. }
  2209. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2210. uint32_t new_head = cache.size;
  2211. for (uint32_t i = 0; i < cache.size; ++i) {
  2212. if (!cache.cells[i].has_seq_id(seq_id)) {
  2213. if (cache.cells[i].pos >= 0) cache.used--;
  2214. cache.cells[i].pos = -1;
  2215. cache.cells[i].seq_id.clear();
  2216. if (new_head == cache.size) new_head = i;
  2217. } else {
  2218. cache.cells[i].seq_id.clear();
  2219. cache.cells[i].seq_id.insert(seq_id);
  2220. }
  2221. }
  2222. // If we freed up a slot, set head to it so searching can start there.
  2223. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2224. }
  2225. static void llama_kv_cache_seq_add(
  2226. struct llama_kv_cache & cache,
  2227. llama_seq_id seq_id,
  2228. llama_pos p0,
  2229. llama_pos p1,
  2230. llama_pos delta) {
  2231. uint32_t new_head = cache.size;
  2232. if (p0 < 0) p0 = 0;
  2233. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2234. if (cache.recurrent) {
  2235. // for Mamba-like models, only the pos needs to be shifted
  2236. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2237. llama_kv_cell & cell = cache.cells[seq_id];
  2238. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2239. cell.pos += delta;
  2240. }
  2241. }
  2242. return;
  2243. }
  2244. for (uint32_t i = 0; i < cache.size; ++i) {
  2245. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2246. cache.has_shift = true;
  2247. cache.cells[i].pos += delta;
  2248. cache.cells[i].delta += delta;
  2249. if (cache.cells[i].pos < 0) {
  2250. if (!cache.cells[i].is_empty()) {
  2251. cache.used--;
  2252. }
  2253. cache.cells[i].pos = -1;
  2254. cache.cells[i].seq_id.clear();
  2255. if (new_head == cache.size) {
  2256. new_head = i;
  2257. }
  2258. }
  2259. }
  2260. }
  2261. // If we freed up a slot, set head to it so searching can start there.
  2262. // Otherwise we just start the next search from the beginning.
  2263. cache.head = new_head != cache.size ? new_head : 0;
  2264. }
  2265. static void llama_kv_cache_seq_div(
  2266. struct llama_kv_cache & cache,
  2267. llama_seq_id seq_id,
  2268. llama_pos p0,
  2269. llama_pos p1,
  2270. int d) {
  2271. if (p0 < 0) p0 = 0;
  2272. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2273. if (cache.recurrent) {
  2274. // for Mamba-like models, only the pos needs to be changed
  2275. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2276. llama_kv_cell & cell = cache.cells[seq_id];
  2277. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2278. cell.pos /= d;
  2279. }
  2280. }
  2281. return;
  2282. }
  2283. for (uint32_t i = 0; i < cache.size; ++i) {
  2284. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2285. cache.has_shift = true;
  2286. {
  2287. llama_pos p_old = cache.cells[i].pos;
  2288. cache.cells[i].pos /= d;
  2289. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2290. }
  2291. }
  2292. }
  2293. }
  2294. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2295. llama_pos result = 0;
  2296. for (uint32_t i = 0; i < cache.size; ++i) {
  2297. if (cache.cells[i].has_seq_id(seq_id)) {
  2298. result = std::max(result, cache.cells[i].pos);
  2299. }
  2300. }
  2301. return result;
  2302. }
  2303. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2304. cache.do_defrag = true;
  2305. }
  2306. //
  2307. // model loading and saving
  2308. //
  2309. enum llama_fver {
  2310. GGUF_FILE_VERSION_V1 = 1,
  2311. GGUF_FILE_VERSION_V2 = 2,
  2312. GGUF_FILE_VERSION_V3 = 3,
  2313. };
  2314. static const char * llama_file_version_name(llama_fver version) {
  2315. switch (version) {
  2316. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2317. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2318. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2319. }
  2320. return "unknown";
  2321. }
  2322. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2323. char buf[256];
  2324. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2325. for (size_t i = 1; i < ne.size(); i++) {
  2326. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2327. }
  2328. return buf;
  2329. }
  2330. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2331. char buf[256];
  2332. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2333. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2334. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2335. }
  2336. return buf;
  2337. }
  2338. namespace GGUFMeta {
  2339. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2340. struct GKV_Base_Type {
  2341. static constexpr gguf_type gt = gt_;
  2342. static T getter(const gguf_context * ctx, const int kid) {
  2343. return gfun(ctx, kid);
  2344. }
  2345. };
  2346. template<typename T> struct GKV_Base;
  2347. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2348. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2349. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2350. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2351. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2352. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2353. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2354. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2355. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2356. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2357. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2358. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2359. template<> struct GKV_Base<std::string> {
  2360. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2361. static std::string getter(const gguf_context * ctx, const int kid) {
  2362. return gguf_get_val_str(ctx, kid);
  2363. }
  2364. };
  2365. struct ArrayInfo {
  2366. const gguf_type gt;
  2367. const size_t length;
  2368. const void * data;
  2369. };
  2370. template<> struct GKV_Base<ArrayInfo> {
  2371. public:
  2372. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2373. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2374. return ArrayInfo {
  2375. gguf_get_arr_type(ctx, k),
  2376. size_t(gguf_get_arr_n(ctx, k)),
  2377. gguf_get_arr_data(ctx, k),
  2378. };
  2379. }
  2380. };
  2381. template<typename T>
  2382. class GKV : public GKV_Base<T> {
  2383. GKV() = delete;
  2384. public:
  2385. static T get_kv(const gguf_context * ctx, const int k) {
  2386. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2387. if (kt != GKV::gt) {
  2388. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2389. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2390. }
  2391. return GKV::getter(ctx, k);
  2392. }
  2393. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2394. switch (ty) {
  2395. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2396. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2397. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2398. }
  2399. return "unknown";
  2400. }
  2401. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2402. if (!ovrd) { return false; }
  2403. if (ovrd->tag == expected_type) {
  2404. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2405. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2406. switch (ovrd->tag) {
  2407. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2408. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2409. } break;
  2410. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2411. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2412. } break;
  2413. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2414. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2415. } break;
  2416. default:
  2417. // Shouldn't be possible to end up here, but just in case...
  2418. throw std::runtime_error(
  2419. format("Unsupported attempt to override %s type for metadata key %s\n",
  2420. override_type_to_str(ovrd->tag), ovrd->key));
  2421. }
  2422. return true;
  2423. }
  2424. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2425. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2426. return false;
  2427. }
  2428. template<typename OT>
  2429. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2430. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2431. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2432. target = ovrd->bool_value;
  2433. return true;
  2434. }
  2435. return false;
  2436. }
  2437. template<typename OT>
  2438. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2439. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2440. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2441. target = ovrd->int_value;
  2442. return true;
  2443. }
  2444. return false;
  2445. }
  2446. template<typename OT>
  2447. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2448. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2449. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2450. target = ovrd->float_value;
  2451. return true;
  2452. }
  2453. return false;
  2454. }
  2455. template<typename OT>
  2456. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2457. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2458. (void)target;
  2459. (void)ovrd;
  2460. if (!ovrd) { return false; }
  2461. // Currently, we should never end up here so it would be a bug if we do.
  2462. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2463. ovrd ? ovrd->key : "NULL"));
  2464. }
  2465. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2466. if (try_override<T>(target, ovrd)) {
  2467. return true;
  2468. }
  2469. if (k < 0) { return false; }
  2470. target = get_kv(ctx, k);
  2471. return true;
  2472. }
  2473. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2474. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2475. }
  2476. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2477. return set(ctx, key.c_str(), target, ovrd);
  2478. }
  2479. };
  2480. }
  2481. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2482. struct llama_model_loader {
  2483. int n_kv = 0;
  2484. int n_tensors = 0;
  2485. int n_created = 0;
  2486. int64_t n_elements = 0;
  2487. size_t n_bytes = 0;
  2488. bool use_mmap = false;
  2489. llama_files files;
  2490. llama_ftype ftype;
  2491. llama_fver fver;
  2492. llama_mmaps mappings;
  2493. // Holds information on a model weights
  2494. struct llama_tensor_weights {
  2495. uint16_t idx; // source file index
  2496. size_t offs; // tensor data offset in the original file
  2497. ggml_tensor * tensor;
  2498. llama_tensor_weights(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2499. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2500. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2501. }
  2502. };
  2503. std::vector<llama_tensor_weights> weights;
  2504. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2505. struct gguf_context * meta = NULL;
  2506. std::vector<ggml_context *> contexts;
  2507. std::string arch_name;
  2508. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2509. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2510. int trace = 0;
  2511. if (getenv("LLAMA_TRACE")) {
  2512. trace = atoi(getenv("LLAMA_TRACE"));
  2513. }
  2514. if (param_overrides_p != nullptr) {
  2515. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2516. kv_overrides.insert({std::string(p->key), *p});
  2517. }
  2518. }
  2519. struct ggml_context * ctx = NULL;
  2520. struct gguf_init_params params = {
  2521. /*.no_alloc = */ true,
  2522. /*.ctx = */ &ctx,
  2523. };
  2524. meta = gguf_init_from_file(fname.c_str(), params);
  2525. if (!meta) {
  2526. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2527. }
  2528. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2529. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2530. // Save tensors data offset of the main file.
  2531. // For subsidiary files, `meta` tensor data offset must not be used,
  2532. // so we build a unified tensors index for weights.
  2533. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2534. weights.emplace_back(llama_tensor_weights(0, cur->name, meta, cur));
  2535. }
  2536. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2537. contexts.emplace_back(ctx);
  2538. uint16_t n_split = 0;
  2539. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2540. // Load additional GGML contexts
  2541. if (n_split > 1) {
  2542. uint16_t idx = 0;
  2543. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2544. if (idx != 0) {
  2545. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2546. }
  2547. char split_prefix[PATH_MAX] = {0};
  2548. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2549. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2550. }
  2551. if (trace > 0) {
  2552. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2553. }
  2554. char split_path[PATH_MAX] = {0};
  2555. for (idx = 1; idx < n_split; idx++) {
  2556. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2557. struct gguf_init_params split_params = {
  2558. /*.no_alloc = */ true,
  2559. /*.ctx = */ &ctx,
  2560. };
  2561. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2562. if (!ctx_gguf) {
  2563. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2564. }
  2565. // Save tensors data offset info of the shard.
  2566. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2567. weights.emplace_back(llama_tensor_weights(idx, cur->name, ctx_gguf, cur));
  2568. }
  2569. files.emplace_back(new llama_file(split_path, "rb"));
  2570. contexts.emplace_back(ctx);
  2571. gguf_free(ctx_gguf);
  2572. }
  2573. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2574. // sanity check
  2575. {
  2576. const int n_tensors_loaded = (int) weights.size();
  2577. if (n_tensors != n_tensors_loaded) {
  2578. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2579. }
  2580. }
  2581. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2582. }
  2583. n_kv = gguf_get_n_kv(meta);
  2584. n_tensors = weights.size();
  2585. fver = (enum llama_fver) gguf_get_version(meta);
  2586. for (auto & w : weights) {
  2587. n_elements += ggml_nelements(w.tensor);
  2588. n_bytes += ggml_nbytes(w.tensor);
  2589. }
  2590. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2591. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2592. // determine file type based on the number of tensors for each quantization and print meta data
  2593. // TODO: make optional
  2594. {
  2595. std::map<enum ggml_type, uint32_t> n_type;
  2596. uint32_t n_type_max = 0;
  2597. enum ggml_type type_max = GGML_TYPE_F32;
  2598. for (int i = 0; i < n_tensors; i++) {
  2599. const ggml_tensor * tensor = weights.at(i).tensor;
  2600. enum ggml_type type = tensor->type;
  2601. n_type[type]++;
  2602. if (n_type_max < n_type[type]) {
  2603. n_type_max = n_type[type];
  2604. type_max = type;
  2605. }
  2606. if (trace > 0) {
  2607. const uint16_t sid = weights.at(i).idx;
  2608. LLAMA_LOG_INFO("%s: - tensor %4d, split %2d: %32s %-8s [ %s ]\n", __func__, i, sid, ggml_get_name(tensor), ggml_type_name(type), llama_format_tensor_shape(tensor).c_str());
  2609. }
  2610. }
  2611. switch (type_max) {
  2612. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2613. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2614. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2615. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2616. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2617. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2618. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2619. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2620. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2621. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2622. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2623. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2624. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2625. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2626. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2627. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2628. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2629. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2630. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2631. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2632. default:
  2633. {
  2634. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2635. ftype = LLAMA_FTYPE_ALL_F32;
  2636. } break;
  2637. }
  2638. // this is a way to mark that we have "guessed" the file type
  2639. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2640. {
  2641. const int kid = gguf_find_key(meta, "general.file_type");
  2642. if (kid >= 0) {
  2643. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2644. }
  2645. }
  2646. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2647. for (int i = 0; i < n_kv; i++) {
  2648. const char * name = gguf_get_key(meta, i);
  2649. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2650. const std::string type_name =
  2651. type == GGUF_TYPE_ARRAY
  2652. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2653. : gguf_type_name(type);
  2654. std::string value = gguf_kv_to_str(meta, i);
  2655. const size_t MAX_VALUE_LEN = 40;
  2656. if (value.size() > MAX_VALUE_LEN) {
  2657. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2658. }
  2659. replace_all(value, "\n", "\\n");
  2660. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2661. }
  2662. // print type counts
  2663. for (auto & kv : n_type) {
  2664. if (kv.second == 0) {
  2665. continue;
  2666. }
  2667. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2668. }
  2669. }
  2670. if (!llama_mmap::SUPPORTED) {
  2671. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2672. use_mmap = false;
  2673. }
  2674. this->use_mmap = use_mmap;
  2675. }
  2676. ~llama_model_loader() {
  2677. if (meta) {
  2678. gguf_free(meta);
  2679. }
  2680. for (auto * ctx : contexts) {
  2681. ggml_free(ctx);
  2682. }
  2683. }
  2684. template<typename T>
  2685. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2686. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2687. const int kid = gguf_find_key(meta, key.c_str());
  2688. if (kid < 0) {
  2689. if (required) {
  2690. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2691. }
  2692. return false;
  2693. }
  2694. struct GGUFMeta::ArrayInfo arr_info =
  2695. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2696. result = arr_info.length;
  2697. return true;
  2698. }
  2699. template<typename T>
  2700. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2701. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2702. return get_arr_n(llm_kv(kid), result, required);
  2703. }
  2704. template<typename T>
  2705. bool get_key(const std::string & key, T & result, const bool required = true) {
  2706. auto it = kv_overrides.find(key);
  2707. const struct llama_model_kv_override * override =
  2708. it != kv_overrides.end() ? &it->second : nullptr;
  2709. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2710. if (required && !found) {
  2711. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2712. }
  2713. return found;
  2714. }
  2715. template<typename T>
  2716. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2717. return get_key(llm_kv(kid), result, required);
  2718. }
  2719. std::string get_arch_name() const {
  2720. return arch_name;
  2721. }
  2722. enum llm_arch get_arch() const {
  2723. return llm_kv.arch;
  2724. }
  2725. const char * get_tensor_name(int i) const {
  2726. return weights.at(i).tensor->name;
  2727. }
  2728. const llama_tensor_weights & get_weights(const char * name) const {
  2729. for (const auto & weight : weights) {
  2730. if (strcmp(name, weight.tensor->name) == 0) {
  2731. return weight;
  2732. }
  2733. }
  2734. throw std::runtime_error(format("tensor %s not found", name));
  2735. }
  2736. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2737. try {
  2738. return get_weights(name).tensor;
  2739. } catch (const std::runtime_error & e) {
  2740. return NULL;
  2741. }
  2742. }
  2743. struct ggml_tensor * get_tensor_meta(int i) const {
  2744. return get_tensor_meta(get_tensor_name(i));
  2745. }
  2746. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2747. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2748. ggml_set_name(tensor, ggml_get_name(cur));
  2749. n_created++;
  2750. return tensor;
  2751. }
  2752. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2753. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2754. if (cur == NULL) {
  2755. if (!required) {
  2756. return NULL;
  2757. }
  2758. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2759. }
  2760. {
  2761. bool is_ok = true;
  2762. for (size_t i = 0; i < ne.size(); ++i) {
  2763. if (ne[i] != cur->ne[i]) {
  2764. is_ok = false;
  2765. break;
  2766. }
  2767. }
  2768. if (!is_ok) {
  2769. throw std::runtime_error(
  2770. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2771. __func__, name.c_str(),
  2772. llama_format_tensor_shape(ne).c_str(),
  2773. llama_format_tensor_shape(cur).c_str()));
  2774. }
  2775. }
  2776. return create_tensor_for(ctx, cur);
  2777. }
  2778. void done_getting_tensors() const {
  2779. if (n_created != n_tensors) {
  2780. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2781. }
  2782. }
  2783. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2784. if (use_mmap) {
  2785. mappings.reserve(files.size());
  2786. mmaps_used.reserve(files.size());
  2787. for (const auto & file : files) {
  2788. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2789. mmaps_used.emplace_back(std::make_pair(mapping->size, 0));
  2790. if (mlock_mmaps) {
  2791. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2792. mlock_mmap->init(mapping->addr);
  2793. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2794. }
  2795. mappings.emplace_back(std::move(mapping));
  2796. }
  2797. }
  2798. // compute the total size of all tensors for progress reporting
  2799. for (auto & w : weights) {
  2800. size_data += ggml_nbytes(w.tensor);
  2801. }
  2802. }
  2803. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2804. GGML_ASSERT(!mappings.empty());
  2805. const auto & mapping = mappings.at(idx);
  2806. *first = mapping->size;
  2807. *last = 0;
  2808. *addr = mapping->addr;
  2809. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2810. const auto & w = get_weights(ggml_get_name(tensor));
  2811. if (w.idx != idx) {
  2812. continue;
  2813. }
  2814. *first = std::min(*first, w.offs);
  2815. *last = std::max(*last, w.offs + ggml_nbytes(tensor));
  2816. }
  2817. }
  2818. // for backwards compatibility, does not support ggml-backend
  2819. void load_data_for(struct ggml_tensor * cur) const {
  2820. const auto & w = get_weights(ggml_get_name(cur));
  2821. if (use_mmap) {
  2822. const auto & mapping = mappings.at(w.idx);
  2823. if (cur->data == nullptr) {
  2824. cur->data = (uint8_t *)mapping->addr + w.offs;
  2825. } else {
  2826. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2827. }
  2828. } else {
  2829. GGML_ASSERT(cur->data != nullptr);
  2830. GGML_ASSERT(w.idx < files.size());
  2831. const auto & file = files.at(w.idx);
  2832. file->seek(w.offs, SEEK_SET);
  2833. file->read_raw(cur->data, ggml_nbytes(cur));
  2834. }
  2835. }
  2836. size_t size_done = 0;
  2837. size_t size_data = 0;
  2838. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2839. // Returns false if cancelled by progress_callback
  2840. bool load_all_data(
  2841. struct ggml_context * ctx,
  2842. llama_buf_map & bufs_mmap,
  2843. llama_mlocks * lmlocks,
  2844. llama_progress_callback progress_callback,
  2845. void * progress_callback_user_data) {
  2846. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2847. std::vector<no_init<uint8_t>> read_buf;
  2848. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2849. if (progress_callback) {
  2850. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2851. return false;
  2852. }
  2853. }
  2854. const auto & w = get_weights(ggml_get_name(cur));
  2855. size_t n_size = ggml_nbytes(cur);
  2856. if (use_mmap) {
  2857. const auto & mapping = mappings.at(w.idx);
  2858. ggml_backend_buffer_t buf_mmap = nullptr;
  2859. if (bufs_mmap.count(w.idx)) {
  2860. buf_mmap = bufs_mmap.at(w.idx);
  2861. }
  2862. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2863. if (buf_mmap && cur->data == nullptr) {
  2864. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + w.offs);
  2865. if (lmlocks) {
  2866. const auto & lmlock = lmlocks->at(w.idx);
  2867. lmlock->grow_to(w.offs + ggml_nbytes(cur));
  2868. }
  2869. auto & mmap_used = mmaps_used[w.idx];
  2870. mmap_used.first = std::min(mmap_used.first, w.offs);
  2871. mmap_used.second = std::max(mmap_used.second, w.offs + n_size);
  2872. } else {
  2873. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + w.offs, 0, n_size);
  2874. }
  2875. } else {
  2876. GGML_ASSERT(w.idx < files.size());
  2877. const auto & file = files.at(w.idx);
  2878. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2879. file->seek(w.offs, SEEK_SET);
  2880. file->read_raw(cur->data, ggml_nbytes(cur));
  2881. } else {
  2882. read_buf.resize(ggml_nbytes(cur));
  2883. file->seek(w.offs, SEEK_SET);
  2884. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2885. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2886. }
  2887. }
  2888. size_done += n_size;
  2889. }
  2890. // check if this is the last call and do final cleanup
  2891. if (size_done >= size_data) {
  2892. // unmap offloaded tensors and metadata
  2893. if (use_mmap) {
  2894. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2895. const auto & mmap_used = mmaps_used.at(idx);
  2896. auto & mapping = mappings.at(idx);
  2897. mapping->unmap_fragment(0, mmap_used.first);
  2898. if (mmap_used.second != 0) {
  2899. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2900. }
  2901. }
  2902. }
  2903. if (progress_callback) {
  2904. // Even though the model is done loading, we still honor
  2905. // cancellation since we need to free allocations.
  2906. return progress_callback(1.0f, progress_callback_user_data);
  2907. }
  2908. }
  2909. return true;
  2910. }
  2911. };
  2912. template<>
  2913. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2914. uint32_t tmp;
  2915. const bool found = get_key(kid, tmp, required);
  2916. if (found) {
  2917. result = (enum llama_pooling_type) tmp;
  2918. } else {
  2919. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2920. }
  2921. return found;
  2922. }
  2923. //
  2924. // load LLaMA models
  2925. //
  2926. static const char * llama_model_arch_name(llm_arch arch) {
  2927. auto it = LLM_ARCH_NAMES.find(arch);
  2928. if (it == LLM_ARCH_NAMES.end()) {
  2929. return "unknown";
  2930. }
  2931. return it->second;
  2932. }
  2933. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2934. if (ftype & LLAMA_FTYPE_GUESSED) {
  2935. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2936. }
  2937. switch (ftype) {
  2938. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2939. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2940. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2941. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2942. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2943. return "Q4_1, some F16";
  2944. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2945. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2946. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2947. // K-quants
  2948. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2949. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2950. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2951. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2952. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2953. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2954. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2955. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2956. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2957. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2958. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2959. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2960. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2961. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2962. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2963. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2964. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2965. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2966. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2967. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2968. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2969. default: return "unknown, may not work";
  2970. }
  2971. }
  2972. static const char * llama_model_type_name(e_model type) {
  2973. switch (type) {
  2974. case MODEL_22M: return "22M";
  2975. case MODEL_33M: return "33M";
  2976. case MODEL_109M: return "109M";
  2977. case MODEL_137M: return "137M";
  2978. case MODEL_0_5B: return "0.5B";
  2979. case MODEL_1B: return "1B";
  2980. case MODEL_2B: return "2B";
  2981. case MODEL_3B: return "3B";
  2982. case MODEL_7B: return "7B";
  2983. case MODEL_8B: return "8B";
  2984. case MODEL_13B: return "13B";
  2985. case MODEL_14B: return "14B";
  2986. case MODEL_15B: return "15B";
  2987. case MODEL_20B: return "20B";
  2988. case MODEL_30B: return "30B";
  2989. case MODEL_34B: return "34B";
  2990. case MODEL_35B: return "35B";
  2991. case MODEL_40B: return "40B";
  2992. case MODEL_65B: return "65B";
  2993. case MODEL_70B: return "70B";
  2994. case MODEL_314B: return "314B";
  2995. case MODEL_SMALL: return "0.1B";
  2996. case MODEL_MEDIUM: return "0.4B";
  2997. case MODEL_LARGE: return "0.8B";
  2998. case MODEL_XL: return "1.5B";
  2999. default: return "?B";
  3000. }
  3001. }
  3002. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3003. switch (type) {
  3004. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3005. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3006. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3007. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3008. default: return "unknown";
  3009. }
  3010. }
  3011. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3012. model.arch = ml.get_arch();
  3013. if (model.arch == LLM_ARCH_UNKNOWN) {
  3014. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3015. }
  3016. }
  3017. static void llm_load_hparams(
  3018. llama_model_loader & ml,
  3019. llama_model & model) {
  3020. auto & hparams = model.hparams;
  3021. const gguf_context * ctx = ml.meta;
  3022. // get metadata as string
  3023. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3024. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3025. if (type == GGUF_TYPE_ARRAY) {
  3026. continue;
  3027. }
  3028. const char * name = gguf_get_key(ctx, i);
  3029. const std::string value = gguf_kv_to_str(ctx, i);
  3030. model.gguf_kv.emplace(name, value);
  3031. }
  3032. // get general kv
  3033. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3034. // get hparams kv
  3035. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3036. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3037. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3038. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3039. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3040. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3041. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3042. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3043. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3044. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3045. if (hparams.n_expert > 0) {
  3046. GGML_ASSERT(hparams.n_expert_used > 0);
  3047. } else {
  3048. GGML_ASSERT(hparams.n_expert_used == 0);
  3049. }
  3050. // n_head_kv is optional, default to n_head
  3051. hparams.n_head_kv = hparams.n_head;
  3052. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3053. bool rope_finetuned = false;
  3054. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3055. hparams.rope_finetuned = rope_finetuned;
  3056. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3057. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3058. // rope_freq_base (optional)
  3059. hparams.rope_freq_base_train = 10000.0f;
  3060. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3061. std::string rope_scaling("linear");
  3062. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3063. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3064. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3065. // rope_freq_scale (inverse of the kv) is optional
  3066. float ropescale = 0.0f;
  3067. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3068. // try the old key name
  3069. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3070. }
  3071. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3072. // sanity check for n_rot (optional)
  3073. {
  3074. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3075. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3076. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3077. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3078. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3079. }
  3080. }
  3081. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3082. // gpt-j n_rot = rotary_dim
  3083. }
  3084. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3085. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3086. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3087. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3088. // arch-specific KVs
  3089. switch (model.arch) {
  3090. case LLM_ARCH_LLAMA:
  3091. {
  3092. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3093. switch (hparams.n_layer) {
  3094. case 22: model.type = e_model::MODEL_1B; break;
  3095. case 26: model.type = e_model::MODEL_3B; break;
  3096. case 32: model.type = e_model::MODEL_7B; break;
  3097. case 40: model.type = e_model::MODEL_13B; break;
  3098. case 48: model.type = e_model::MODEL_34B; break;
  3099. case 60: model.type = e_model::MODEL_30B; break;
  3100. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3101. default: model.type = e_model::MODEL_UNKNOWN;
  3102. }
  3103. } break;
  3104. case LLM_ARCH_MINICPM:
  3105. {
  3106. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3107. switch (hparams.n_layer) {
  3108. case 40: model.type = e_model::MODEL_2B; break;
  3109. default: model.type = e_model::MODEL_UNKNOWN;
  3110. }
  3111. } break;
  3112. case LLM_ARCH_GROK:
  3113. {
  3114. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3115. switch (hparams.n_layer) {
  3116. case 64: model.type = e_model::MODEL_314B; break;
  3117. default: model.type = e_model::MODEL_UNKNOWN;
  3118. }
  3119. } break;
  3120. case LLM_ARCH_FALCON:
  3121. {
  3122. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3123. switch (hparams.n_layer) {
  3124. case 32: model.type = e_model::MODEL_7B; break;
  3125. case 60: model.type = e_model::MODEL_40B; break;
  3126. default: model.type = e_model::MODEL_UNKNOWN;
  3127. }
  3128. } break;
  3129. case LLM_ARCH_BAICHUAN:
  3130. {
  3131. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3132. switch (hparams.n_layer) {
  3133. case 32: model.type = e_model::MODEL_7B; break;
  3134. case 40: model.type = e_model::MODEL_13B; break;
  3135. default: model.type = e_model::MODEL_UNKNOWN;
  3136. }
  3137. if (model.type == e_model::MODEL_13B) {
  3138. // TODO: become GGUF KV parameter
  3139. hparams.f_max_alibi_bias = 8.0f;
  3140. }
  3141. } break;
  3142. case LLM_ARCH_STARCODER:
  3143. {
  3144. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3145. switch (hparams.n_layer) {
  3146. case 24: model.type = e_model::MODEL_1B; break;
  3147. case 36: model.type = e_model::MODEL_3B; break;
  3148. case 42: model.type = e_model::MODEL_7B; break;
  3149. case 40: model.type = e_model::MODEL_15B; break;
  3150. default: model.type = e_model::MODEL_UNKNOWN;
  3151. }
  3152. } break;
  3153. case LLM_ARCH_PERSIMMON:
  3154. {
  3155. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3156. switch (hparams.n_layer) {
  3157. case 36: model.type = e_model::MODEL_8B; break;
  3158. default: model.type = e_model::MODEL_UNKNOWN;
  3159. }
  3160. } break;
  3161. case LLM_ARCH_REFACT:
  3162. {
  3163. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3164. switch (hparams.n_layer) {
  3165. case 32: model.type = e_model::MODEL_1B; break;
  3166. default: model.type = e_model::MODEL_UNKNOWN;
  3167. }
  3168. // TODO: become GGUF KV parameter
  3169. hparams.f_max_alibi_bias = 8.0f;
  3170. } break;
  3171. case LLM_ARCH_BERT:
  3172. {
  3173. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3174. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3175. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3176. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3177. switch (hparams.n_layer) {
  3178. case 3:
  3179. model.type = e_model::MODEL_17M; break; // bge-micro
  3180. case 6:
  3181. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3182. case 12:
  3183. switch (hparams.n_embd) {
  3184. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3185. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3186. } break;
  3187. case 24:
  3188. model.type = e_model::MODEL_335M; break; // bge-large
  3189. }
  3190. } break;
  3191. case LLM_ARCH_NOMIC_BERT:
  3192. {
  3193. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3194. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3195. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3196. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3197. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3198. model.type = e_model::MODEL_137M;
  3199. }
  3200. } break;
  3201. case LLM_ARCH_BLOOM:
  3202. {
  3203. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3204. switch (hparams.n_layer) {
  3205. case 24: model.type = e_model::MODEL_1B; break;
  3206. case 30:
  3207. switch (hparams.n_embd) {
  3208. case 2560: model.type = e_model::MODEL_3B; break;
  3209. case 4096: model.type = e_model::MODEL_7B; break;
  3210. } break;
  3211. }
  3212. // TODO: become GGUF KV parameter
  3213. hparams.f_max_alibi_bias = 8.0f;
  3214. } break;
  3215. case LLM_ARCH_MPT:
  3216. {
  3217. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3218. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3219. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3220. switch (hparams.n_layer) {
  3221. case 32: model.type = e_model::MODEL_7B; break;
  3222. case 48: model.type = e_model::MODEL_30B; break;
  3223. default: model.type = e_model::MODEL_UNKNOWN;
  3224. }
  3225. } break;
  3226. case LLM_ARCH_STABLELM:
  3227. {
  3228. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3229. switch (hparams.n_layer) {
  3230. case 24: model.type = e_model::MODEL_1B; break;
  3231. case 32: model.type = e_model::MODEL_3B; break;
  3232. default: model.type = e_model::MODEL_UNKNOWN;
  3233. }
  3234. } break;
  3235. case LLM_ARCH_QWEN:
  3236. {
  3237. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3238. switch (hparams.n_layer) {
  3239. case 32: model.type = e_model::MODEL_7B; break;
  3240. case 40: model.type = e_model::MODEL_13B; break;
  3241. default: model.type = e_model::MODEL_UNKNOWN;
  3242. }
  3243. } break;
  3244. case LLM_ARCH_QWEN2:
  3245. {
  3246. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3247. switch (hparams.n_layer) {
  3248. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3249. case 32: model.type = e_model::MODEL_7B; break;
  3250. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3251. case 80: model.type = e_model::MODEL_70B; break;
  3252. default: model.type = e_model::MODEL_UNKNOWN;
  3253. }
  3254. } break;
  3255. case LLM_ARCH_PHI2:
  3256. {
  3257. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3258. switch (hparams.n_layer) {
  3259. case 24: model.type = e_model::MODEL_1B; break;
  3260. case 32: model.type = e_model::MODEL_3B; break;
  3261. default: model.type = e_model::MODEL_UNKNOWN;
  3262. }
  3263. } break;
  3264. case LLM_ARCH_PLAMO:
  3265. {
  3266. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3267. switch (hparams.n_layer) {
  3268. case 40: model.type = e_model::MODEL_13B; break;
  3269. default: model.type = e_model::MODEL_UNKNOWN;
  3270. }
  3271. } break;
  3272. case LLM_ARCH_GPT2:
  3273. {
  3274. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3275. switch (hparams.n_layer) {
  3276. case 12: model.type = e_model::MODEL_SMALL; break;
  3277. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3278. case 36: model.type = e_model::MODEL_LARGE; break;
  3279. case 48: model.type = e_model::MODEL_XL; break;
  3280. default: model.type = e_model::MODEL_UNKNOWN;
  3281. }
  3282. } break;
  3283. case LLM_ARCH_CODESHELL:
  3284. {
  3285. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3286. switch (hparams.n_layer) {
  3287. case 42: model.type = e_model::MODEL_SMALL; break;
  3288. default: model.type = e_model::MODEL_UNKNOWN;
  3289. }
  3290. } break;
  3291. case LLM_ARCH_ORION:
  3292. {
  3293. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3294. switch (hparams.n_layer) {
  3295. case 40: model.type = e_model::MODEL_14B; break;
  3296. default: model.type = e_model::MODEL_UNKNOWN;
  3297. }
  3298. } break;
  3299. case LLM_ARCH_INTERNLM2:
  3300. {
  3301. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3302. switch (hparams.n_layer) {
  3303. case 32: model.type = e_model::MODEL_7B; break;
  3304. case 48: model.type = e_model::MODEL_20B; break;
  3305. default: model.type = e_model::MODEL_UNKNOWN;
  3306. }
  3307. } break;
  3308. case LLM_ARCH_GEMMA:
  3309. {
  3310. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3311. switch (hparams.n_layer) {
  3312. case 18: model.type = e_model::MODEL_2B; break;
  3313. case 28: model.type = e_model::MODEL_7B; break;
  3314. default: model.type = e_model::MODEL_UNKNOWN;
  3315. }
  3316. } break;
  3317. case LLM_ARCH_STARCODER2:
  3318. {
  3319. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3320. switch (hparams.n_layer) {
  3321. case 30: model.type = e_model::MODEL_3B; break;
  3322. case 32: model.type = e_model::MODEL_7B; break;
  3323. case 40: model.type = e_model::MODEL_15B; break;
  3324. default: model.type = e_model::MODEL_UNKNOWN;
  3325. }
  3326. } break;
  3327. case LLM_ARCH_MAMBA:
  3328. {
  3329. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3330. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3331. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3332. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3333. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3334. switch (hparams.n_layer) {
  3335. case 24:
  3336. switch (hparams.n_embd) {
  3337. case 768: model.type = e_model::MODEL_SMALL; break;
  3338. default: model.type = e_model::MODEL_UNKNOWN;
  3339. } break;
  3340. case 48:
  3341. switch (hparams.n_embd) {
  3342. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3343. case 1536: model.type = e_model::MODEL_LARGE; break;
  3344. case 2048: model.type = e_model::MODEL_XL; break;
  3345. default: model.type = e_model::MODEL_UNKNOWN;
  3346. } break;
  3347. case 64:
  3348. switch (hparams.n_embd) {
  3349. case 2560: model.type = e_model::MODEL_3B; break;
  3350. default: model.type = e_model::MODEL_UNKNOWN;
  3351. } break;
  3352. default: model.type = e_model::MODEL_UNKNOWN;
  3353. }
  3354. } break;
  3355. case LLM_ARCH_COMMAND_R:
  3356. {
  3357. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3358. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3359. switch (hparams.n_layer) {
  3360. case 40: model.type = e_model::MODEL_35B; break;
  3361. default: model.type = e_model::MODEL_UNKNOWN;
  3362. }
  3363. } break;
  3364. default: (void)0;
  3365. }
  3366. model.ftype = ml.ftype;
  3367. if (hparams.f_max_alibi_bias > 0.0f) {
  3368. hparams.need_kq_pos = true;
  3369. }
  3370. hparams.rope_type = llama_rope_type(&model);
  3371. }
  3372. // TODO: This should probably be in llama.h
  3373. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3374. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3375. static void llm_load_vocab(
  3376. llama_model_loader & ml,
  3377. llama_model & model) {
  3378. auto & vocab = model.vocab;
  3379. struct gguf_context * ctx = ml.meta;
  3380. const auto kv = LLM_KV(model.arch);
  3381. // determine vocab type
  3382. {
  3383. std::string tokenizer_name;
  3384. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3385. if (tokenizer_name == "no_vocab") {
  3386. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3387. // default special tokens
  3388. vocab.special_bos_id = -1;
  3389. vocab.special_eos_id = -1;
  3390. vocab.special_unk_id = -1;
  3391. vocab.special_sep_id = -1;
  3392. vocab.special_pad_id = -1;
  3393. vocab.linefeed_id = -1;
  3394. return;
  3395. } else if (tokenizer_name == "llama") {
  3396. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3397. // default special tokens
  3398. vocab.special_bos_id = 1;
  3399. vocab.special_eos_id = 2;
  3400. vocab.special_unk_id = 0;
  3401. vocab.special_sep_id = -1;
  3402. vocab.special_pad_id = -1;
  3403. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3404. if (add_space_prefix_keyidx != -1) {
  3405. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3406. } // The default value of add_space_prefix is true.
  3407. } else if (tokenizer_name == "gpt2") {
  3408. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3409. // read bpe merges and populate bpe ranks
  3410. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3411. if (merges_keyidx == -1) {
  3412. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3413. }
  3414. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3415. for (int i = 0; i < n_merges; i++) {
  3416. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3417. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3418. std::string first;
  3419. std::string second;
  3420. const size_t pos = word.find(' ', 1);
  3421. if (pos != std::string::npos) {
  3422. first = word.substr(0, pos);
  3423. second = word.substr(pos + 1);
  3424. }
  3425. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3426. }
  3427. // default special tokens
  3428. vocab.special_bos_id = 11;
  3429. vocab.special_eos_id = 11;
  3430. vocab.special_unk_id = -1;
  3431. vocab.special_sep_id = -1;
  3432. vocab.special_pad_id = -1;
  3433. } else if (tokenizer_name == "bert") {
  3434. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3435. // default special tokens
  3436. vocab.special_bos_id = 101;
  3437. vocab.special_eos_id = 102;
  3438. vocab.special_unk_id = 100;
  3439. vocab.special_sep_id = -1;
  3440. vocab.special_pad_id = -1;
  3441. vocab.add_space_prefix = false;
  3442. } else {
  3443. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3444. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3445. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3446. }
  3447. }
  3448. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3449. if (token_idx == -1) {
  3450. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3451. }
  3452. const float * scores = nullptr;
  3453. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3454. if (score_idx != -1) {
  3455. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3456. }
  3457. const int * toktypes = nullptr;
  3458. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3459. if (toktype_idx != -1) {
  3460. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3461. }
  3462. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3463. vocab.id_to_token.resize(n_vocab);
  3464. for (uint32_t i = 0; i < n_vocab; i++) {
  3465. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3466. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3467. vocab.token_to_id[word] = i;
  3468. auto & token_data = vocab.id_to_token[i];
  3469. token_data.text = std::move(word);
  3470. token_data.score = scores ? scores[i] : 0.0f;
  3471. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3472. }
  3473. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3474. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3475. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3476. try {
  3477. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3478. } catch (const std::exception & e) {
  3479. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3480. vocab.linefeed_id = vocab.special_pad_id;
  3481. }
  3482. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3483. vocab.linefeed_id = vocab.special_pad_id;
  3484. } else {
  3485. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3486. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3487. vocab.linefeed_id = ids[0];
  3488. }
  3489. // special tokens
  3490. {
  3491. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3492. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3493. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3494. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3495. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3496. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3497. };
  3498. for (const auto & it : special_token_types) {
  3499. const std::string & key = kv(std::get<0>(it));
  3500. int32_t & id = std::get<1>(it);
  3501. uint32_t new_id;
  3502. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3503. continue;
  3504. }
  3505. if (new_id >= vocab.id_to_token.size()) {
  3506. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3507. __func__, key.c_str(), new_id, id);
  3508. } else {
  3509. id = new_id;
  3510. }
  3511. }
  3512. // Handle add_bos_token and add_eos_token
  3513. {
  3514. bool temp = true;
  3515. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3516. vocab.special_add_bos = int(temp);
  3517. }
  3518. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3519. vocab.special_add_eos = int(temp);
  3520. }
  3521. }
  3522. }
  3523. // build special tokens cache
  3524. {
  3525. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3526. // and will always be correctly labeled in 'added_tokens.json' etc.
  3527. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3528. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3529. // are special tokens.
  3530. // From testing, this appears to correlate 1:1 with special tokens.
  3531. //
  3532. // Counting special tokens and verifying in only one direction
  3533. // is sufficient to detect difference in those two sets.
  3534. //
  3535. uint32_t special_tokens_count_by_type = 0;
  3536. uint32_t special_tokens_count_from_verification = 0;
  3537. bool special_tokens_definition_mismatch = false;
  3538. for (const auto & t : vocab.token_to_id) {
  3539. const auto & token = t.first;
  3540. const auto & id = t.second;
  3541. // Count all non-normal tokens in the vocab while iterating
  3542. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3543. special_tokens_count_by_type++;
  3544. }
  3545. // Skip single character tokens
  3546. if (token.length() > 1) {
  3547. bool is_tokenizable = false;
  3548. // Split token string representation in two, in all possible ways
  3549. // and check if both halves can be matched to a valid token
  3550. for (unsigned i = 1; i < token.length();) {
  3551. const auto left = token.substr(0, i);
  3552. const auto right = token.substr(i);
  3553. // check if we didnt partition in the middle of a utf sequence
  3554. auto utf = utf8_len(left.at(left.length() - 1));
  3555. if (utf == 1) {
  3556. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3557. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3558. is_tokenizable = true;
  3559. break;
  3560. }
  3561. i++;
  3562. } else {
  3563. // skip over the rest of multibyte utf sequence
  3564. i += utf - 1;
  3565. }
  3566. }
  3567. if (!is_tokenizable) {
  3568. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3569. // it's faster to re-filter them here, since there are way less candidates now
  3570. // Calculate a total "utf" length of a token string representation
  3571. size_t utf8_str_len = 0;
  3572. for (unsigned i = 0; i < token.length();) {
  3573. utf8_str_len++;
  3574. i += utf8_len(token.at(i));
  3575. }
  3576. // And skip the ones which are one character
  3577. if (utf8_str_len > 1) {
  3578. // At this point what we have left are special tokens only
  3579. vocab.special_tokens_cache[token] = id;
  3580. // Count manually found special tokens
  3581. special_tokens_count_from_verification++;
  3582. // If this manually found special token is not marked as such, flag a mismatch
  3583. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3584. special_tokens_definition_mismatch = true;
  3585. }
  3586. }
  3587. }
  3588. }
  3589. }
  3590. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3591. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3592. __func__,
  3593. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3594. special_tokens_count_by_type, vocab.id_to_token.size()
  3595. );
  3596. } else {
  3597. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3598. __func__,
  3599. special_tokens_count_from_verification, vocab.id_to_token.size()
  3600. );
  3601. }
  3602. }
  3603. }
  3604. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3605. const auto & hparams = model.hparams;
  3606. const auto & vocab = model.vocab;
  3607. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3608. // hparams
  3609. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3610. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3611. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3612. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3613. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3614. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3615. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3616. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3617. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3618. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3619. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3620. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3621. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3622. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3623. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3624. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3625. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3626. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3627. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3628. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3629. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3630. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3631. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3632. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3633. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3634. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3635. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3636. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3637. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3638. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3639. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3640. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3641. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3642. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3643. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3644. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3645. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3646. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3647. if (ml.n_elements >= 1e12) {
  3648. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3649. } else if (ml.n_elements >= 1e9) {
  3650. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3651. } else if (ml.n_elements >= 1e6) {
  3652. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3653. } else {
  3654. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3655. }
  3656. if (ml.n_bytes < GiB) {
  3657. LLAMA_LOG_INFO("%s: model size = %.2f MiB (%.2f BPW) \n", __func__, ml.n_bytes/1024.0/1024.0, ml.n_bytes*8.0/ml.n_elements);
  3658. } else {
  3659. LLAMA_LOG_INFO("%s: model size = %.2f GiB (%.2f BPW) \n", __func__, ml.n_bytes/1024.0/1024.0/1024.0, ml.n_bytes*8.0/ml.n_elements);
  3660. }
  3661. // general kv
  3662. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3663. // special tokens
  3664. if (vocab.special_bos_id != -1) { LLAMA_LOG_INFO( "%s: BOS token = %d '%s'\n", __func__, vocab.special_bos_id, vocab.id_to_token[vocab.special_bos_id].text.c_str() ); }
  3665. if (vocab.special_eos_id != -1) { LLAMA_LOG_INFO( "%s: EOS token = %d '%s'\n", __func__, vocab.special_eos_id, vocab.id_to_token[vocab.special_eos_id].text.c_str() ); }
  3666. if (vocab.special_unk_id != -1) { LLAMA_LOG_INFO( "%s: UNK token = %d '%s'\n", __func__, vocab.special_unk_id, vocab.id_to_token[vocab.special_unk_id].text.c_str() ); }
  3667. if (vocab.special_sep_id != -1) { LLAMA_LOG_INFO( "%s: SEP token = %d '%s'\n", __func__, vocab.special_sep_id, vocab.id_to_token[vocab.special_sep_id].text.c_str() ); }
  3668. if (vocab.special_pad_id != -1) { LLAMA_LOG_INFO( "%s: PAD token = %d '%s'\n", __func__, vocab.special_pad_id, vocab.id_to_token[vocab.special_pad_id].text.c_str() ); }
  3669. if (vocab.linefeed_id != -1) { LLAMA_LOG_INFO( "%s: LF token = %d '%s'\n", __func__, vocab.linefeed_id, vocab.id_to_token[vocab.linefeed_id].text.c_str() ); }
  3670. }
  3671. // Returns false if cancelled by progress_callback
  3672. static bool llm_load_tensors(
  3673. llama_model_loader & ml,
  3674. llama_model & model,
  3675. int n_gpu_layers,
  3676. enum llama_split_mode split_mode,
  3677. int main_gpu,
  3678. const float * tensor_split,
  3679. bool use_mlock,
  3680. llama_progress_callback progress_callback,
  3681. void * progress_callback_user_data) {
  3682. model.t_start_us = ggml_time_us();
  3683. auto & hparams = model.hparams;
  3684. model.split_mode = split_mode;
  3685. model.main_gpu = main_gpu;
  3686. model.n_gpu_layers = n_gpu_layers;
  3687. const int64_t n_layer = hparams.n_layer;
  3688. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3689. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3690. model.buft_input = llama_default_buffer_type_cpu(true);
  3691. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3692. model.buft_layer.resize(n_layer);
  3693. // assign cpu layers
  3694. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3695. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3696. }
  3697. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3698. // calculate the split points
  3699. int device_count = llama_get_device_count();
  3700. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3701. std::vector<float> splits(device_count);
  3702. if (all_zero) {
  3703. // default split, by free memory
  3704. for (int i = 0; i < device_count; ++i) {
  3705. splits[i] = llama_get_device_memory(i);
  3706. }
  3707. } else {
  3708. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3709. }
  3710. // sum and normalize the splits to get the split points
  3711. float split_sum = 0.0f;
  3712. for (int i = 0; i < device_count; ++i) {
  3713. split_sum += splits[i];
  3714. splits[i] = split_sum;
  3715. }
  3716. for (int i = 0; i < device_count; ++i) {
  3717. splits[i] /= split_sum;
  3718. }
  3719. // assign the repeating layers to the devices according to the splits
  3720. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3721. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3722. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3723. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3724. }
  3725. // assign the output layer
  3726. if (n_gpu_layers > n_layer) {
  3727. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3728. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3729. } else {
  3730. model.buft_output = llama_default_buffer_type_cpu(true);
  3731. }
  3732. } else {
  3733. ggml_backend_buffer_type_t split_buft;
  3734. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3735. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3736. } else {
  3737. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3738. split_buft = llama_default_buffer_type_offload(main_gpu);
  3739. }
  3740. // assign the repeating layers
  3741. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3742. model.buft_layer[i] = {
  3743. split_buft,
  3744. llama_default_buffer_type_offload(main_gpu)
  3745. };
  3746. }
  3747. // assign the output layer
  3748. if (n_gpu_layers > n_layer) {
  3749. model.buft_output = {
  3750. split_buft,
  3751. llama_default_buffer_type_offload(main_gpu)
  3752. };
  3753. } else {
  3754. model.buft_output = llama_default_buffer_type_cpu(true);
  3755. }
  3756. }
  3757. // count used buffer types
  3758. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3759. buft_layer_count[model.buft_input.buft]++;
  3760. buft_layer_count[model.buft_input.buft_matrix]++;
  3761. buft_layer_count[model.buft_output.buft]++;
  3762. buft_layer_count[model.buft_output.buft_matrix]++;
  3763. for (int64_t i = 0; i < n_layer; ++i) {
  3764. buft_layer_count[model.buft_layer[i].buft]++;
  3765. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3766. }
  3767. // create one context per buffer type
  3768. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3769. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3770. for (auto & it : buft_layer_count) {
  3771. struct ggml_init_params params = {
  3772. /*.mem_size =*/ ctx_size,
  3773. /*.mem_buffer =*/ NULL,
  3774. /*.no_alloc =*/ true,
  3775. };
  3776. ggml_context * ctx = ggml_init(params);
  3777. if (!ctx) {
  3778. throw std::runtime_error(format("failed to create context"));
  3779. }
  3780. ctx_map[it.first] = ctx;
  3781. model.ctxs.push_back(ctx);
  3782. }
  3783. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3784. // create tensors for the weights
  3785. {
  3786. const int64_t n_embd = hparams.n_embd;
  3787. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3788. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3789. const int64_t n_embd_gqa = n_embd_v_gqa;
  3790. const int64_t n_vocab = hparams.n_vocab;
  3791. const int64_t n_vocab_type = hparams.n_vocab_type;
  3792. const int64_t n_ff = hparams.n_ff;
  3793. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3794. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3795. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3796. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3797. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3798. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3799. model.layers.resize(n_layer);
  3800. const auto tn = LLM_TN(model.arch);
  3801. switch (model.arch) {
  3802. case LLM_ARCH_LLAMA:
  3803. case LLM_ARCH_REFACT:
  3804. case LLM_ARCH_MINICPM:
  3805. {
  3806. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3807. // output
  3808. {
  3809. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3810. if (model.arch != LLM_ARCH_MINICPM){
  3811. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3812. // if output is NULL, init from the input tok embed
  3813. if (model.output == NULL) {
  3814. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3815. ml.n_created--; // artificial tensor
  3816. ml.size_data += ggml_nbytes(model.output);
  3817. }
  3818. }
  3819. }
  3820. for (int i = 0; i < n_layer; ++i) {
  3821. ggml_context * ctx_layer = ctx_for_layer(i);
  3822. ggml_context * ctx_split = ctx_for_layer_split(i);
  3823. auto & layer = model.layers[i];
  3824. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3825. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3826. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3827. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3828. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3829. // optional bias tensors
  3830. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3831. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3832. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3833. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3834. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3835. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3836. if (layer.ffn_gate_inp == nullptr) {
  3837. GGML_ASSERT(hparams.n_expert == 0);
  3838. GGML_ASSERT(hparams.n_expert_used == 0);
  3839. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3840. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3841. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3842. } else {
  3843. GGML_ASSERT(hparams.n_expert > 0);
  3844. GGML_ASSERT(hparams.n_expert_used > 0);
  3845. // MoE branch
  3846. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3847. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3848. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3849. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3850. }
  3851. }
  3852. }
  3853. } break;
  3854. case LLM_ARCH_GROK:
  3855. {
  3856. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3857. // output
  3858. {
  3859. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3860. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3861. // if output is NULL, init from the input tok embed
  3862. if (model.output == NULL) {
  3863. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3864. ml.n_created--; // artificial tensor
  3865. ml.size_data += ggml_nbytes(model.output);
  3866. }
  3867. }
  3868. for (int i = 0; i < n_layer; ++i) {
  3869. ggml_context * ctx_layer = ctx_for_layer(i);
  3870. ggml_context * ctx_split = ctx_for_layer_split(i);
  3871. auto & layer = model.layers[i];
  3872. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3873. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3874. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3875. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3876. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3877. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3878. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3879. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd});
  3880. GGML_ASSERT(hparams.n_expert > 0);
  3881. GGML_ASSERT(hparams.n_expert_used > 0);
  3882. // MoE branch
  3883. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3884. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3885. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3886. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3887. }
  3888. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3889. }
  3890. } break;
  3891. case LLM_ARCH_BAICHUAN:
  3892. {
  3893. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3894. {
  3895. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3896. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3897. }
  3898. for (int i = 0; i < n_layer; ++i) {
  3899. ggml_context * ctx_layer = ctx_for_layer(i);
  3900. ggml_context * ctx_split = ctx_for_layer_split(i);
  3901. auto & layer = model.layers[i];
  3902. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3903. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3904. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3905. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3906. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3907. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3908. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3909. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3910. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3911. }
  3912. } break;
  3913. case LLM_ARCH_FALCON:
  3914. {
  3915. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3916. // output
  3917. {
  3918. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3919. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3920. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3921. if (!model.output) {
  3922. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3923. ml.n_created--; // artificial tensor
  3924. ml.size_data += ggml_nbytes(model.output);
  3925. }
  3926. }
  3927. for (int i = 0; i < n_layer; ++i) {
  3928. ggml_context * ctx_layer = ctx_for_layer(i);
  3929. ggml_context * ctx_split = ctx_for_layer_split(i);
  3930. auto & layer = model.layers[i];
  3931. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3932. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3933. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  3934. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  3935. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3936. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3937. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3938. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3939. }
  3940. } break;
  3941. case LLM_ARCH_STARCODER:
  3942. {
  3943. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3944. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3945. // output
  3946. {
  3947. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3948. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3949. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3950. }
  3951. for (int i = 0; i < n_layer; ++i) {
  3952. ggml_context * ctx_layer = ctx_for_layer(i);
  3953. ggml_context * ctx_split = ctx_for_layer_split(i);
  3954. auto & layer = model.layers[i];
  3955. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3956. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3957. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3958. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3959. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3960. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3961. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3962. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3963. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3964. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3965. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3966. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3967. }
  3968. } break;
  3969. case LLM_ARCH_PERSIMMON:
  3970. {
  3971. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3972. {
  3973. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3974. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3975. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3976. }
  3977. for (int i = 0; i < n_layer; ++i) {
  3978. ggml_context * ctx_layer = ctx_for_layer(i);
  3979. ggml_context * ctx_split = ctx_for_layer_split(i);
  3980. auto & layer = model.layers[i];
  3981. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3982. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3983. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3984. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3985. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3986. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3987. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3988. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3989. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3990. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3991. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3992. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3993. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3994. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3995. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3996. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3997. }
  3998. } break;
  3999. case LLM_ARCH_BERT:
  4000. case LLM_ARCH_NOMIC_BERT:
  4001. {
  4002. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4003. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4004. if (model.arch == LLM_ARCH_BERT) {
  4005. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4006. }
  4007. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4008. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4009. for (int i = 0; i < n_layer; ++i) {
  4010. ggml_context * ctx_layer = ctx_for_layer(i);
  4011. ggml_context * ctx_split = ctx_for_layer_split(i);
  4012. auto & layer = model.layers[i];
  4013. if (model.arch == LLM_ARCH_BERT) {
  4014. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4015. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4016. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4017. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4018. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4019. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4020. } else {
  4021. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4022. }
  4023. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4024. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4025. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4026. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4027. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4028. if (model.arch == LLM_ARCH_BERT) {
  4029. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4030. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4031. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4032. } else {
  4033. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4034. }
  4035. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4036. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4037. }
  4038. } break;
  4039. case LLM_ARCH_BLOOM:
  4040. {
  4041. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4042. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4043. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4044. // output
  4045. {
  4046. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4047. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4048. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4049. }
  4050. for (int i = 0; i < n_layer; ++i) {
  4051. ggml_context * ctx_layer = ctx_for_layer(i);
  4052. ggml_context * ctx_split = ctx_for_layer_split(i);
  4053. auto & layer = model.layers[i];
  4054. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4055. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4056. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4057. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4058. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4059. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4060. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4061. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4062. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4063. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4064. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4065. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4066. }
  4067. } break;
  4068. case LLM_ARCH_MPT:
  4069. {
  4070. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4071. // output
  4072. {
  4073. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4074. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4075. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4076. if (!model.output) {
  4077. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4078. ml.n_created--; // artificial tensor
  4079. ml.size_data += ggml_nbytes(model.output);
  4080. }
  4081. }
  4082. for (int i = 0; i < n_layer; ++i) {
  4083. ggml_context * ctx_layer = ctx_for_layer(i);
  4084. ggml_context * ctx_split = ctx_for_layer_split(i);
  4085. auto & layer = model.layers[i];
  4086. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4087. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4088. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4089. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4090. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4091. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4092. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4093. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4094. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4095. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4096. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4097. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4098. // AWQ ScaleActivation layer
  4099. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4100. }
  4101. } break;
  4102. case LLM_ARCH_STABLELM:
  4103. {
  4104. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4105. // output
  4106. {
  4107. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4108. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4109. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4110. }
  4111. for (int i = 0; i < n_layer; ++i) {
  4112. ggml_context * ctx_layer = ctx_for_layer(i);
  4113. ggml_context * ctx_split = ctx_for_layer_split(i);
  4114. auto & layer = model.layers[i];
  4115. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4116. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4117. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4118. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4119. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4120. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4121. // optional bias tensors, present in Stable LM 2 1.6B
  4122. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4123. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4124. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4125. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4126. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4127. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4128. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4129. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4130. }
  4131. } break;
  4132. case LLM_ARCH_QWEN:
  4133. {
  4134. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4135. // output
  4136. {
  4137. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4138. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4139. }
  4140. for (int i = 0; i < n_layer; ++i) {
  4141. ggml_context * ctx_layer = ctx_for_layer(i);
  4142. ggml_context * ctx_split = ctx_for_layer_split(i);
  4143. auto & layer = model.layers[i];
  4144. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4145. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4146. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4147. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4148. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4149. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4150. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4151. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4152. }
  4153. } break;
  4154. case LLM_ARCH_QWEN2:
  4155. {
  4156. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4157. // output
  4158. {
  4159. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4160. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4161. }
  4162. for (int i = 0; i < n_layer; ++i) {
  4163. ggml_context * ctx_layer = ctx_for_layer(i);
  4164. ggml_context * ctx_split = ctx_for_layer_split(i);
  4165. auto & layer = model.layers[i];
  4166. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4167. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4168. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4169. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4170. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4171. // optional bias tensors
  4172. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4173. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4174. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4175. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4176. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4177. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4178. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4179. }
  4180. } break;
  4181. case LLM_ARCH_PHI2:
  4182. {
  4183. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4184. // output
  4185. {
  4186. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4187. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4188. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4189. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4190. }
  4191. for (int i = 0; i < n_layer; ++i) {
  4192. ggml_context * ctx_layer = ctx_for_layer(i);
  4193. ggml_context * ctx_split = ctx_for_layer_split(i);
  4194. auto & layer = model.layers[i];
  4195. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4196. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4197. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4198. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4199. if (layer.wqkv == nullptr) {
  4200. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4201. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4202. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4203. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4204. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4205. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4206. }
  4207. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4208. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4209. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4210. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4211. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4212. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4213. }
  4214. } break;
  4215. case LLM_ARCH_PLAMO:
  4216. {
  4217. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4218. // output
  4219. {
  4220. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4221. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4222. }
  4223. for (int i = 0; i < n_layer; ++i) {
  4224. ggml_context * ctx_layer = ctx_for_layer(i);
  4225. ggml_context * ctx_split = ctx_for_layer_split(i);
  4226. auto & layer = model.layers[i];
  4227. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4228. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4229. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4230. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4231. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4232. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4233. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4234. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4235. }
  4236. } break;
  4237. case LLM_ARCH_GPT2:
  4238. {
  4239. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4240. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4241. // output
  4242. {
  4243. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4244. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4245. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4246. }
  4247. for (int i = 0; i < n_layer; ++i) {
  4248. ggml_context * ctx_layer = ctx_for_layer(i);
  4249. ggml_context * ctx_split = ctx_for_layer_split(i);
  4250. auto & layer = model.layers[i];
  4251. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4252. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4253. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4254. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4255. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4256. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4257. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4258. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4259. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4260. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4261. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4262. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4263. }
  4264. } break;
  4265. case LLM_ARCH_CODESHELL:
  4266. {
  4267. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4268. // output
  4269. {
  4270. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4271. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4272. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4273. }
  4274. for (int i = 0; i < n_layer; ++i) {
  4275. ggml_context * ctx_layer = ctx_for_layer(i);
  4276. ggml_context * ctx_split = ctx_for_layer_split(i);
  4277. auto & layer = model.layers[i];
  4278. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4279. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4280. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4281. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4282. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4283. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4284. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4285. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4286. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4287. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4288. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4289. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4290. }
  4291. } break;
  4292. case LLM_ARCH_ORION:
  4293. {
  4294. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4295. {
  4296. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4297. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4298. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4299. }
  4300. for (int i = 0; i < n_layer; ++i) {
  4301. ggml_context * ctx_layer = ctx_for_layer(i);
  4302. ggml_context * ctx_split = ctx_for_layer_split(i);
  4303. auto & layer = model.layers[i];
  4304. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4305. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4306. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4307. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4308. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4309. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4310. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4311. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4312. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4313. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4314. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4315. }
  4316. } break;
  4317. case LLM_ARCH_INTERNLM2:
  4318. {
  4319. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4320. // output
  4321. {
  4322. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4323. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4324. }
  4325. for (int i = 0; i < n_layer; ++i) {
  4326. ggml_context * ctx_layer = ctx_for_layer(i);
  4327. ggml_context * ctx_split = ctx_for_layer_split(i);
  4328. auto & layer = model.layers[i];
  4329. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4330. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4331. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4332. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4333. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4334. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4335. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4336. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4337. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4338. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4339. }
  4340. } break;
  4341. case LLM_ARCH_GEMMA:
  4342. {
  4343. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4344. // output
  4345. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4346. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  4347. ml.n_created--; // artificial tensor
  4348. ml.size_data += ggml_nbytes(model.output);
  4349. const int64_t n_ff = hparams.n_ff;
  4350. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4351. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4352. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4353. for (uint32_t i = 0; i < n_layer; ++i) {
  4354. ggml_context * ctx_layer = ctx_for_layer(i);
  4355. ggml_context * ctx_split = ctx_for_layer_split(i);
  4356. auto & layer = model.layers[i];
  4357. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4358. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4359. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4360. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4361. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4362. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4363. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4364. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4365. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4366. }
  4367. } break;
  4368. case LLM_ARCH_STARCODER2:
  4369. {
  4370. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4371. // output
  4372. {
  4373. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4374. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4375. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4376. // if output is NULL, init from the input tok embed
  4377. if (model.output == NULL) {
  4378. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4379. ml.n_created--; // artificial tensor
  4380. ml.size_data += ggml_nbytes(model.output);
  4381. }
  4382. }
  4383. for (int i = 0; i < n_layer; ++i) {
  4384. ggml_context * ctx_layer = ctx_for_layer(i);
  4385. ggml_context * ctx_split = ctx_for_layer_split(i);
  4386. auto & layer = model.layers[i];
  4387. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4388. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4389. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4390. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4391. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4392. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4393. // optional bias tensors
  4394. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4395. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4396. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4397. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4398. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4399. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4400. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4401. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4402. // optional bias tensors
  4403. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4404. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4405. }
  4406. } break;
  4407. case LLM_ARCH_MAMBA:
  4408. {
  4409. const int64_t d_conv = hparams.ssm_d_conv;
  4410. const int64_t d_inner = hparams.ssm_d_inner;
  4411. const int64_t d_state = hparams.ssm_d_state;
  4412. const int64_t dt_rank = hparams.ssm_dt_rank;
  4413. // only an expansion factor of 2 is supported for now
  4414. GGML_ASSERT(2 * n_embd == d_inner);
  4415. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4416. // output
  4417. {
  4418. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4419. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4420. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4421. if (model.output == NULL) {
  4422. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4423. ml.n_created--; // artificial tensor
  4424. ml.size_data += ggml_nbytes(model.output);
  4425. }
  4426. }
  4427. for (int i = 0; i < n_layer; ++i) {
  4428. ggml_context * ctx_layer = ctx_for_layer(i);
  4429. ggml_context * ctx_split = ctx_for_layer_split(i);
  4430. auto & layer = model.layers[i];
  4431. // norm
  4432. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4433. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4434. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4435. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4436. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4437. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4438. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4439. // no "weight" suffix for these
  4440. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4441. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4442. // out_proj
  4443. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4444. }
  4445. } break;
  4446. case LLM_ARCH_COMMAND_R:
  4447. {
  4448. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4449. // output
  4450. {
  4451. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4452. // init output from the input tok embed
  4453. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4454. ml.n_created--; // artificial tensor
  4455. ml.size_data += ggml_nbytes(model.output);
  4456. }
  4457. for (int i = 0; i < n_layer; ++i) {
  4458. ggml_context * ctx_layer = ctx_for_layer(i);
  4459. ggml_context * ctx_split = ctx_for_layer_split(i);
  4460. auto & layer = model.layers[i];
  4461. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4462. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4463. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4464. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4465. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4466. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4467. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4468. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4469. }
  4470. } break;
  4471. default:
  4472. throw std::runtime_error("unknown architecture");
  4473. }
  4474. }
  4475. ml.done_getting_tensors();
  4476. ml.init_mappings(true, &model.mlock_mmaps);
  4477. model.mappings.reserve(ml.mappings.size());
  4478. // create the backend buffers
  4479. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4480. ctx_bufs.reserve(ctx_map.size());
  4481. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4482. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4483. model.bufs.reserve(n_max_backend_buffer);
  4484. for (auto & it : ctx_map) {
  4485. ggml_backend_buffer_type_t buft = it.first;
  4486. ggml_context * ctx = it.second;
  4487. llama_buf_map bufs;
  4488. bufs.reserve(n_max_backend_buffer);
  4489. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4490. // this is important for metal with apple silicon: if the entire model could be mapped to a metal buffer, then we could just use metal for all layers
  4491. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4492. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4493. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4494. void * addr = nullptr;
  4495. size_t first, last;
  4496. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4497. if (first >= last) {
  4498. continue;
  4499. }
  4500. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4501. if (buf == nullptr) {
  4502. throw std::runtime_error("unable to allocate backend CPU buffer");
  4503. }
  4504. model.bufs.push_back(buf);
  4505. bufs.emplace(idx, buf);
  4506. #ifdef GGML_USE_CUDA
  4507. if (n_layer >= n_gpu_layers) {
  4508. ggml_backend_cuda_register_host_buffer(
  4509. ggml_backend_buffer_get_base(buf),
  4510. ggml_backend_buffer_get_size(buf));
  4511. }
  4512. #endif
  4513. }
  4514. }
  4515. #ifdef GGML_USE_METAL
  4516. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4517. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4518. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4519. void * addr = nullptr;
  4520. size_t first, last;
  4521. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4522. if (first >= last) {
  4523. continue;
  4524. }
  4525. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4526. if (buf == nullptr) {
  4527. throw std::runtime_error("unable to allocate backend metal buffer");
  4528. }
  4529. model.bufs.push_back(buf);
  4530. bufs.emplace(idx, buf);
  4531. }
  4532. }
  4533. #endif
  4534. else {
  4535. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4536. if (buf == nullptr) {
  4537. throw std::runtime_error("unable to allocate backend buffer");
  4538. }
  4539. model.bufs.push_back(buf);
  4540. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4541. model.mlock_bufs.emplace_back(new llama_mlock);
  4542. auto & mlock_buf = model.mlock_bufs.back();
  4543. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4544. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4545. }
  4546. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4547. bufs.emplace(idx, buf);
  4548. }
  4549. }
  4550. if (bufs.empty()) {
  4551. throw std::runtime_error("failed to allocate buffer");
  4552. }
  4553. for (auto & buf : bufs) {
  4554. // indicate that this buffer contains weights
  4555. // this is used by ggml_backend_sched to improve op scheduling -> ops that use a weight are preferably scheduled to the backend that contains the weight
  4556. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4557. }
  4558. ctx_bufs.emplace_back(ctx, bufs);
  4559. }
  4560. if (llama_supports_gpu_offload()) {
  4561. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4562. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4563. if (n_gpu_layers > (int) hparams.n_layer) {
  4564. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4565. }
  4566. const int max_backend_supported_layers = hparams.n_layer + 1;
  4567. const int max_offloadable_layers = hparams.n_layer + 1;
  4568. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4569. }
  4570. // print memory requirements
  4571. for (ggml_backend_buffer_t buf : model.bufs) {
  4572. LLAMA_LOG_INFO("%s: %10s buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  4573. }
  4574. // populate tensors_by_name
  4575. for (ggml_context * ctx : model.ctxs) {
  4576. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4577. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4578. }
  4579. }
  4580. // load tensor data
  4581. for (auto & it : ctx_bufs) {
  4582. ggml_context * ctx = it.first;
  4583. auto & bufs = it.second;
  4584. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4585. return false;
  4586. }
  4587. }
  4588. for (auto & mapping : ml.mappings) {
  4589. model.mappings.emplace_back(std::move(mapping));
  4590. }
  4591. // loading time will be recalculate after the first eval, so
  4592. // we take page faults deferred by mmap() into consideration
  4593. model.t_load_us = ggml_time_us() - model.t_start_us;
  4594. return true;
  4595. }
  4596. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4597. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4598. try {
  4599. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4600. model.hparams.vocab_only = params.vocab_only;
  4601. try {
  4602. llm_load_arch(ml, model);
  4603. } catch(const std::exception & e) {
  4604. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4605. }
  4606. try {
  4607. llm_load_hparams(ml, model);
  4608. } catch(const std::exception & e) {
  4609. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4610. }
  4611. try {
  4612. llm_load_vocab(ml, model);
  4613. } catch(const std::exception & e) {
  4614. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4615. }
  4616. llm_load_print_meta(ml, model);
  4617. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4618. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4619. throw std::runtime_error("vocab size mismatch");
  4620. }
  4621. if (params.vocab_only) {
  4622. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4623. return 0;
  4624. }
  4625. #ifdef GGML_USE_KOMPUTE
  4626. if (params.n_gpu_layers > 0 && (
  4627. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4628. || !(
  4629. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4630. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4631. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4632. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4633. )
  4634. )) {
  4635. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4636. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4637. params.n_gpu_layers = 0;
  4638. }
  4639. #endif
  4640. #ifdef GGML_USE_SYCL
  4641. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4642. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4643. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4644. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4645. } else {
  4646. ggml_backend_sycl_set_mul_device_mode();
  4647. }
  4648. #endif
  4649. if (!llm_load_tensors(
  4650. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4651. params.progress_callback, params.progress_callback_user_data
  4652. )) {
  4653. return -2;
  4654. }
  4655. } catch (const std::exception & err) {
  4656. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4657. return -1;
  4658. }
  4659. return 0;
  4660. }
  4661. //
  4662. // llm_build
  4663. //
  4664. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4665. enum llm_ffn_op_type {
  4666. LLM_FFN_SILU,
  4667. LLM_FFN_GELU,
  4668. LLM_FFN_RELU,
  4669. LLM_FFN_RELU_SQR,
  4670. };
  4671. enum llm_ffn_gate_type {
  4672. LLM_FFN_SEQ,
  4673. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4674. };
  4675. enum llm_norm_type {
  4676. LLM_NORM,
  4677. LLM_NORM_RMS,
  4678. };
  4679. static struct ggml_tensor * llm_build_inp_embd(
  4680. struct ggml_context * ctx,
  4681. struct llama_context & lctx,
  4682. const llama_hparams & hparams,
  4683. const llama_batch & batch,
  4684. struct ggml_tensor * tok_embd,
  4685. const llm_build_cb & cb) {
  4686. const int64_t n_embd = hparams.n_embd;
  4687. struct ggml_tensor * inpL;
  4688. if (batch.token) {
  4689. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4690. cb(lctx.inp_tokens, "inp_tokens", -1);
  4691. ggml_set_input(lctx.inp_tokens);
  4692. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4693. } else {
  4694. #ifdef GGML_USE_MPI
  4695. GGML_ASSERT(false && "not implemented");
  4696. #endif
  4697. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4698. inpL = lctx.inp_embd;
  4699. ggml_set_input(lctx.inp_embd);
  4700. }
  4701. cb(inpL, "inp_embd", -1);
  4702. return inpL;
  4703. }
  4704. static void llm_build_kv_store(
  4705. struct ggml_context * ctx,
  4706. const llama_hparams & hparams,
  4707. const llama_kv_cache & kv,
  4708. struct ggml_cgraph * graph,
  4709. struct ggml_tensor * k_cur,
  4710. struct ggml_tensor * v_cur,
  4711. int64_t n_ctx,
  4712. int32_t n_tokens,
  4713. int32_t kv_head,
  4714. const llm_build_cb & cb,
  4715. int64_t il) {
  4716. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4717. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4718. GGML_ASSERT(kv.size == n_ctx);
  4719. // compute the transposed [n_tokens, n_embd] V matrix
  4720. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4721. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4722. cb(v_cur_t, "v_cur_t", il);
  4723. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4724. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4725. cb(k_cache_view, "k_cache_view", il);
  4726. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4727. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4728. (kv_head)*ggml_element_size(kv.v_l[il]));
  4729. cb(v_cache_view, "v_cache_view", il);
  4730. // important: storing RoPE-ed version of K in the KV cache!
  4731. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4732. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4733. }
  4734. static struct ggml_tensor * llm_build_norm(
  4735. struct ggml_context * ctx,
  4736. struct ggml_tensor * cur,
  4737. const llama_hparams & hparams,
  4738. struct ggml_tensor * mw,
  4739. struct ggml_tensor * mb,
  4740. llm_norm_type type,
  4741. const llm_build_cb & cb,
  4742. int il) {
  4743. switch (type) {
  4744. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4745. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4746. }
  4747. if (mw || mb) {
  4748. cb(cur, "norm", il);
  4749. }
  4750. if (mw) {
  4751. cur = ggml_mul(ctx, cur, mw);
  4752. if (mb) {
  4753. cb(cur, "norm_w", il);
  4754. }
  4755. }
  4756. if (mb) {
  4757. cur = ggml_add(ctx, cur, mb);
  4758. }
  4759. return cur;
  4760. }
  4761. static struct ggml_tensor * llm_build_ffn(
  4762. struct ggml_context * ctx,
  4763. struct ggml_tensor * cur,
  4764. struct ggml_tensor * up,
  4765. struct ggml_tensor * up_b,
  4766. struct ggml_tensor * gate,
  4767. struct ggml_tensor * gate_b,
  4768. struct ggml_tensor * down,
  4769. struct ggml_tensor * down_b,
  4770. struct ggml_tensor * act_scales,
  4771. llm_ffn_op_type type_op,
  4772. llm_ffn_gate_type type_gate,
  4773. const llm_build_cb & cb,
  4774. int il) {
  4775. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4776. cb(tmp, "ffn_up", il);
  4777. if (up_b) {
  4778. tmp = ggml_add(ctx, tmp, up_b);
  4779. cb(tmp, "ffn_up_b", il);
  4780. }
  4781. if (gate) {
  4782. switch (type_gate) {
  4783. case LLM_FFN_SEQ:
  4784. {
  4785. cur = ggml_mul_mat(ctx, gate, tmp);
  4786. cb(cur, "ffn_gate", il);
  4787. } break;
  4788. case LLM_FFN_PAR:
  4789. {
  4790. cur = ggml_mul_mat(ctx, gate, cur);
  4791. cb(cur, "ffn_gate", il);
  4792. } break;
  4793. }
  4794. if (gate_b) {
  4795. cur = ggml_add(ctx, cur, gate_b);
  4796. cb(cur, "ffn_gate_b", il);
  4797. }
  4798. } else {
  4799. cur = tmp;
  4800. }
  4801. switch (type_op) {
  4802. case LLM_FFN_SILU:
  4803. {
  4804. cur = ggml_silu(ctx, cur);
  4805. cb(cur, "ffn_silu", il);
  4806. } break;
  4807. case LLM_FFN_GELU:
  4808. {
  4809. cur = ggml_gelu(ctx, cur);
  4810. cb(cur, "ffn_gelu", il);
  4811. if (act_scales != NULL) {
  4812. cur = ggml_div(ctx, cur, act_scales);
  4813. cb(cur, "ffn_act", il);
  4814. }
  4815. } break;
  4816. case LLM_FFN_RELU:
  4817. {
  4818. cur = ggml_relu(ctx, cur);
  4819. cb(cur, "ffn_relu", il);
  4820. } break;
  4821. case LLM_FFN_RELU_SQR:
  4822. {
  4823. cur = ggml_relu(ctx, cur);
  4824. cb(cur, "ffn_relu", il);
  4825. cur = ggml_sqr(ctx, cur);
  4826. cb(cur, "ffn_sqr(relu)", il);
  4827. } break;
  4828. }
  4829. if (type_gate == LLM_FFN_PAR) {
  4830. cur = ggml_mul(ctx, cur, tmp);
  4831. cb(cur, "ffn_gate_par", il);
  4832. }
  4833. cur = ggml_mul_mat(ctx, down, cur);
  4834. if (down_b) {
  4835. cb(cur, "ffn_down", il);
  4836. }
  4837. if (down_b) {
  4838. cur = ggml_add(ctx, cur, down_b);
  4839. }
  4840. return cur;
  4841. }
  4842. // if max_alibi_bias > 0 then apply ALiBi
  4843. static struct ggml_tensor * llm_build_kqv(
  4844. struct ggml_context * ctx,
  4845. const llama_model & model,
  4846. const llama_hparams & hparams,
  4847. const llama_kv_cache & kv,
  4848. struct ggml_cgraph * graph,
  4849. struct ggml_tensor * wo,
  4850. struct ggml_tensor * wo_b,
  4851. struct ggml_tensor * q_cur,
  4852. struct ggml_tensor * kq_mask,
  4853. struct ggml_tensor * kq_pos,
  4854. int64_t n_ctx,
  4855. int32_t n_tokens,
  4856. int32_t n_kv,
  4857. float kq_scale,
  4858. const llm_build_cb & cb,
  4859. int il) {
  4860. const int64_t n_head = hparams.n_head;
  4861. const int64_t n_head_kv = hparams.n_head_kv;
  4862. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4863. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4864. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4865. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4866. cb(q, "q", il);
  4867. struct ggml_tensor * k =
  4868. ggml_view_3d(ctx, kv.k_l[il],
  4869. n_embd_head_k, n_kv, n_head_kv,
  4870. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4871. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4872. 0);
  4873. cb(k, "k", il);
  4874. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4875. cb(kq, "kq", il);
  4876. if (model.arch == LLM_ARCH_PHI2) {
  4877. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4878. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4879. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4880. }
  4881. if (model.arch == LLM_ARCH_GROK) {
  4882. // need to do the following:
  4883. // multiply by attn_output_multiplyer of 0.08838834764831845
  4884. // and then :
  4885. // kq = 30 * tanh(kq / 30)
  4886. // before the softmax below
  4887. //try from phi2
  4888. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4889. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  4890. kq = ggml_scale(ctx, kq, 30);
  4891. }
  4892. #if defined(GGML_USE_KOMPUTE)
  4893. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4894. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4895. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4896. if (hparams.f_max_alibi_bias > 0.0f) {
  4897. kq = ggml_scale(ctx, kq, kq_scale);
  4898. cb(kq, "kq_scaled", il);
  4899. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4900. cb(kq, "kq_scaled_alibi", il);
  4901. kq = ggml_add(ctx, kq, kq_mask);
  4902. cb(kq, "kq_masked", il);
  4903. kq = ggml_soft_max(ctx, kq);
  4904. cb(kq, "kq_soft_max", il);
  4905. } else
  4906. #endif
  4907. {
  4908. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4909. cb(kq, "kq_soft_max_ext", il);
  4910. }
  4911. GGML_ASSERT(kv.size == n_ctx);
  4912. // split cached v into n_head heads
  4913. struct ggml_tensor * v =
  4914. ggml_view_3d(ctx, kv.v_l[il],
  4915. n_kv, n_embd_head_v, n_head_kv,
  4916. ggml_element_size(kv.v_l[il])*n_ctx,
  4917. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4918. 0);
  4919. cb(v, "v", il);
  4920. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4921. cb(kqv, "kqv", il);
  4922. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4923. cb(kqv_merged, "kqv_merged", il);
  4924. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4925. cb(cur, "kqv_merged_cont", il);
  4926. ggml_build_forward_expand(graph, cur);
  4927. cur = ggml_mul_mat(ctx, wo, cur);
  4928. if (wo_b) {
  4929. cb(cur, "kqv_wo", il);
  4930. }
  4931. if (wo_b) {
  4932. cur = ggml_add(ctx, cur, wo_b);
  4933. }
  4934. return cur;
  4935. }
  4936. static struct ggml_tensor * llm_build_kv(
  4937. struct ggml_context * ctx,
  4938. const llama_model & model,
  4939. const llama_hparams & hparams,
  4940. const llama_kv_cache & kv,
  4941. struct ggml_cgraph * graph,
  4942. struct ggml_tensor * wo,
  4943. struct ggml_tensor * wo_b,
  4944. struct ggml_tensor * k_cur,
  4945. struct ggml_tensor * v_cur,
  4946. struct ggml_tensor * q_cur,
  4947. struct ggml_tensor * kq_mask,
  4948. struct ggml_tensor * kq_pos,
  4949. int64_t n_ctx,
  4950. int32_t n_tokens,
  4951. int32_t kv_head,
  4952. int32_t n_kv,
  4953. float kq_scale,
  4954. const llm_build_cb & cb,
  4955. int il) {
  4956. // these nodes are added to the graph together so that they are not reordered
  4957. // by doing so, the number of splits in the graph is reduced
  4958. ggml_build_forward_expand(graph, q_cur);
  4959. ggml_build_forward_expand(graph, k_cur);
  4960. ggml_build_forward_expand(graph, v_cur);
  4961. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4962. struct ggml_tensor * cur;
  4963. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4964. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4965. cb(cur, "kqv_out", il);
  4966. return cur;
  4967. }
  4968. struct llm_build_context {
  4969. const llama_model & model;
  4970. llama_context & lctx;
  4971. const llama_hparams & hparams;
  4972. const llama_cparams & cparams;
  4973. const llama_batch & batch;
  4974. const llama_kv_cache & kv_self;
  4975. const int64_t n_embd;
  4976. const int64_t n_layer;
  4977. const int64_t n_rot;
  4978. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4979. const int64_t n_head;
  4980. const int64_t n_head_kv;
  4981. const int64_t n_embd_head_k;
  4982. const int64_t n_embd_k_gqa;
  4983. const int64_t n_embd_head_v;
  4984. const int64_t n_embd_v_gqa;
  4985. const int64_t n_expert;
  4986. const int64_t n_expert_used;
  4987. const float freq_base;
  4988. const float freq_scale;
  4989. const float ext_factor;
  4990. const float attn_factor;
  4991. const float beta_fast;
  4992. const float beta_slow;
  4993. const float norm_eps;
  4994. const float norm_rms_eps;
  4995. const int32_t n_tokens;
  4996. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4997. const int32_t kv_head; // index of where we store new KV data in the cache
  4998. const int32_t n_orig_ctx;
  4999. const enum llama_pooling_type pooling_type;
  5000. const enum llama_rope_type rope_type;
  5001. const llm_build_cb & cb;
  5002. std::vector<uint8_t> & buf_compute_meta;
  5003. struct ggml_context * ctx0 = nullptr;
  5004. // TODO: consider making the entire interface noexcept
  5005. llm_build_context(
  5006. llama_context & lctx,
  5007. const llama_batch & batch,
  5008. const llm_build_cb & cb,
  5009. bool worst_case) :
  5010. model (lctx.model),
  5011. lctx (lctx),
  5012. hparams (model.hparams),
  5013. cparams (lctx.cparams),
  5014. batch (batch),
  5015. kv_self (lctx.kv_self),
  5016. n_embd (hparams.n_embd),
  5017. n_layer (hparams.n_layer),
  5018. n_rot (hparams.n_rot),
  5019. n_ctx (cparams.n_ctx),
  5020. n_head (hparams.n_head),
  5021. n_head_kv (hparams.n_head_kv),
  5022. n_embd_head_k (hparams.n_embd_head_k),
  5023. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5024. n_embd_head_v (hparams.n_embd_head_v),
  5025. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5026. n_expert (hparams.n_expert),
  5027. n_expert_used (hparams.n_expert_used),
  5028. freq_base (cparams.rope_freq_base),
  5029. freq_scale (cparams.rope_freq_scale),
  5030. ext_factor (cparams.yarn_ext_factor),
  5031. attn_factor (cparams.yarn_attn_factor),
  5032. beta_fast (cparams.yarn_beta_fast),
  5033. beta_slow (cparams.yarn_beta_slow),
  5034. norm_eps (hparams.f_norm_eps),
  5035. norm_rms_eps (hparams.f_norm_rms_eps),
  5036. n_tokens (batch.n_tokens),
  5037. n_kv (worst_case ? kv_self.size : kv_self.n),
  5038. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5039. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5040. pooling_type (cparams.pooling_type),
  5041. rope_type (hparams.rope_type),
  5042. cb (cb),
  5043. buf_compute_meta (lctx.buf_compute_meta) {
  5044. // all initializations should be done in init()
  5045. }
  5046. void init() {
  5047. struct ggml_init_params params = {
  5048. /*.mem_size =*/ buf_compute_meta.size(),
  5049. /*.mem_buffer =*/ buf_compute_meta.data(),
  5050. /*.no_alloc =*/ true,
  5051. };
  5052. ctx0 = ggml_init(params);
  5053. lctx.inp_tokens = nullptr;
  5054. lctx.inp_embd = nullptr;
  5055. lctx.inp_pos = nullptr;
  5056. lctx.inp_KQ_mask = nullptr;
  5057. lctx.inp_KQ_pos = nullptr;
  5058. lctx.inp_K_shift = nullptr;
  5059. lctx.inp_mean = nullptr;
  5060. lctx.inp_cls = nullptr;
  5061. lctx.inp_s_copy = nullptr;
  5062. lctx.inp_s_mask = nullptr;
  5063. lctx.inp_s_seq = nullptr;
  5064. }
  5065. void free() {
  5066. if (ctx0) {
  5067. ggml_free(ctx0);
  5068. ctx0 = nullptr;
  5069. }
  5070. }
  5071. struct ggml_cgraph * build_k_shift() {
  5072. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5073. GGML_ASSERT(kv_self.size == n_ctx);
  5074. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5075. cb(lctx.inp_K_shift, "K_shift", -1);
  5076. ggml_set_input(lctx.inp_K_shift);
  5077. for (int il = 0; il < n_layer; ++il) {
  5078. struct ggml_tensor * tmp =
  5079. // we rotate only the first n_rot dimensions
  5080. ggml_rope_custom_inplace(ctx0,
  5081. ggml_view_3d(ctx0, kv_self.k_l[il],
  5082. n_embd_head_k, n_head_kv, n_ctx,
  5083. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5084. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5085. 0),
  5086. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5087. ext_factor, attn_factor, beta_fast, beta_slow);
  5088. cb(tmp, "K_shifted", il);
  5089. ggml_build_forward_expand(gf, tmp);
  5090. }
  5091. return gf;
  5092. }
  5093. struct ggml_cgraph * build_s_copy() {
  5094. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5095. GGML_ASSERT(kv_self.recurrent);
  5096. struct ggml_tensor * state_copy = build_inp_s_copy();
  5097. for (int il = 0; il < n_layer; ++il) {
  5098. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5099. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5100. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5101. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5102. // TODO: name the intermediate tensors with cb()
  5103. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5104. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5105. }
  5106. return gf;
  5107. }
  5108. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5109. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5110. for (uint32_t i = 0; i < ids.size(); ++i) {
  5111. const uint32_t id = ids[i];
  5112. if (i == id || id == ids.size()) {
  5113. continue;
  5114. }
  5115. uint32_t nm = 1;
  5116. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5117. nm++;
  5118. }
  5119. for (int il = 0; il < n_layer; ++il) {
  5120. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5121. n_embd_k_gqa, nm,
  5122. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5123. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5124. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5125. n_embd_k_gqa, nm,
  5126. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5127. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5128. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5129. nm, n_embd_v_gqa,
  5130. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5131. ggml_row_size(kv_self.v_l[il]->type, i));
  5132. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5133. nm, n_embd_v_gqa,
  5134. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5135. ggml_row_size(kv_self.v_l[il]->type, id));
  5136. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5137. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5138. }
  5139. i += nm - 1;
  5140. }
  5141. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5142. return gf;
  5143. }
  5144. struct ggml_tensor * build_inp_pos() {
  5145. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5146. cb(lctx.inp_pos, "inp_pos", -1);
  5147. ggml_set_input(lctx.inp_pos);
  5148. return lctx.inp_pos;
  5149. }
  5150. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5151. if (causal) {
  5152. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5153. } else {
  5154. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5155. }
  5156. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5157. ggml_set_input(lctx.inp_KQ_mask);
  5158. return lctx.inp_KQ_mask;
  5159. }
  5160. struct ggml_tensor * build_inp_KQ_pos() {
  5161. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5162. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5163. ggml_set_input(lctx.inp_KQ_pos);
  5164. return lctx.inp_KQ_pos;
  5165. }
  5166. struct ggml_tensor * build_inp_mean() {
  5167. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5168. cb(lctx.inp_mean, "inp_mean", -1);
  5169. ggml_set_input(lctx.inp_mean);
  5170. return lctx.inp_mean;
  5171. }
  5172. struct ggml_tensor * build_inp_cls() {
  5173. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5174. cb(lctx.inp_cls, "inp_cls", -1);
  5175. ggml_set_input(lctx.inp_cls);
  5176. return lctx.inp_cls;
  5177. }
  5178. struct ggml_tensor * build_inp_s_copy() {
  5179. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5180. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5181. ggml_set_input(lctx.inp_s_copy);
  5182. return lctx.inp_s_copy;
  5183. }
  5184. struct ggml_tensor * build_inp_s_mask() {
  5185. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5186. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5187. ggml_set_input(lctx.inp_s_mask);
  5188. return lctx.inp_s_mask;
  5189. }
  5190. struct ggml_tensor * build_inp_s_seq() {
  5191. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5192. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5193. ggml_set_input(lctx.inp_s_seq);
  5194. return lctx.inp_s_seq;
  5195. }
  5196. struct ggml_cgraph * build_llama() {
  5197. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5198. const int64_t n_embd_head = hparams.n_embd_head_v;
  5199. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5200. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5201. struct ggml_tensor * cur;
  5202. struct ggml_tensor * inpL;
  5203. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5204. // inp_pos - contains the positions
  5205. struct ggml_tensor * inp_pos = build_inp_pos();
  5206. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5207. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5208. for (int il = 0; il < n_layer; ++il) {
  5209. struct ggml_tensor * inpSA = inpL;
  5210. // norm
  5211. cur = llm_build_norm(ctx0, inpL, hparams,
  5212. model.layers[il].attn_norm, NULL,
  5213. LLM_NORM_RMS, cb, il);
  5214. cb(cur, "attn_norm", il);
  5215. // self-attention
  5216. {
  5217. // compute Q and K and RoPE them
  5218. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5219. cb(Qcur, "Qcur", il);
  5220. if (model.layers[il].bq) {
  5221. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5222. cb(Qcur, "Qcur", il);
  5223. }
  5224. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5225. cb(Kcur, "Kcur", il);
  5226. if (model.layers[il].bk) {
  5227. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5228. cb(Kcur, "Kcur", il);
  5229. }
  5230. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5231. cb(Vcur, "Vcur", il);
  5232. if (model.layers[il].bv) {
  5233. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5234. cb(Vcur, "Vcur", il);
  5235. }
  5236. Qcur = ggml_rope_custom(
  5237. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5238. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5239. ext_factor, attn_factor, beta_fast, beta_slow
  5240. );
  5241. cb(Qcur, "Qcur", il);
  5242. Kcur = ggml_rope_custom(
  5243. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5244. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5245. ext_factor, attn_factor, beta_fast, beta_slow
  5246. );
  5247. cb(Kcur, "Kcur", il);
  5248. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5249. model.layers[il].wo, model.layers[il].bo,
  5250. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5251. }
  5252. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5253. cb(ffn_inp, "ffn_inp", il);
  5254. // feed-forward network
  5255. if (model.layers[il].ffn_gate_inp == nullptr) {
  5256. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5257. model.layers[il].ffn_norm, NULL,
  5258. LLM_NORM_RMS, cb, il);
  5259. cb(cur, "ffn_norm", il);
  5260. cur = llm_build_ffn(ctx0, cur,
  5261. model.layers[il].ffn_up, NULL,
  5262. model.layers[il].ffn_gate, NULL,
  5263. model.layers[il].ffn_down, NULL,
  5264. NULL,
  5265. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5266. cb(cur, "ffn_out", il);
  5267. } else {
  5268. // MoE branch
  5269. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5270. model.layers[il].ffn_norm, NULL,
  5271. LLM_NORM_RMS, cb, il);
  5272. cb(cur, "ffn_norm", il);
  5273. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5274. cb(logits, "ffn_moe_logits", il);
  5275. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5276. cb(probs, "ffn_moe_probs", il);
  5277. // select experts
  5278. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5279. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5280. ggml_tensor * weights = ggml_get_rows(ctx0,
  5281. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5282. cb(weights, "ffn_moe_weights", il);
  5283. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5284. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5285. cb(weights_sum, "ffn_moe_weights_sum", il);
  5286. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5287. cb(weights, "ffn_moe_weights_norm", il);
  5288. // compute expert outputs
  5289. ggml_tensor * moe_out = nullptr;
  5290. for (int i = 0; i < n_expert_used; ++i) {
  5291. ggml_tensor * cur_expert;
  5292. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5293. cb(cur_up, "ffn_moe_up", il);
  5294. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5295. cb(cur_gate, "ffn_moe_gate", il);
  5296. cur_gate = ggml_silu(ctx0, cur_gate);
  5297. cb(cur_gate, "ffn_moe_silu", il);
  5298. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5299. cb(cur_expert, "ffn_moe_gate_par", il);
  5300. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5301. cb(cur_expert, "ffn_moe_down", il);
  5302. cur_expert = ggml_mul(ctx0, cur_expert,
  5303. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5304. cb(cur_expert, "ffn_moe_weighted", il);
  5305. if (i == 0) {
  5306. moe_out = cur_expert;
  5307. } else {
  5308. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5309. cb(moe_out, "ffn_moe_out", il);
  5310. }
  5311. }
  5312. cur = moe_out;
  5313. }
  5314. cur = ggml_add(ctx0, cur, ffn_inp);
  5315. cb(cur, "ffn_out", il);
  5316. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5317. if (layer_dir != nullptr) {
  5318. cur = ggml_add(ctx0, cur, layer_dir);
  5319. }
  5320. cb(cur, "l_out", il);
  5321. // input for next layer
  5322. inpL = cur;
  5323. }
  5324. cur = inpL;
  5325. cur = llm_build_norm(ctx0, cur, hparams,
  5326. model.output_norm, NULL,
  5327. LLM_NORM_RMS, cb, -1);
  5328. cb(cur, "result_norm", -1);
  5329. // lm_head
  5330. cur = ggml_mul_mat(ctx0, model.output, cur);
  5331. cb(cur, "result_output", -1);
  5332. ggml_build_forward_expand(gf, cur);
  5333. return gf;
  5334. }
  5335. struct ggml_cgraph * build_baichuan() {
  5336. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5337. const int64_t n_embd_head = hparams.n_embd_head_v;
  5338. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5339. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5340. struct ggml_tensor * cur;
  5341. struct ggml_tensor * inpL;
  5342. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5343. // inp_pos - contains the positions
  5344. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5345. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5346. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5347. // positions of the tokens in the KV cache
  5348. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5349. for (int il = 0; il < n_layer; ++il) {
  5350. struct ggml_tensor * inpSA = inpL;
  5351. cur = llm_build_norm(ctx0, inpL, hparams,
  5352. model.layers[il].attn_norm, NULL,
  5353. LLM_NORM_RMS, cb, il);
  5354. cb(cur, "attn_norm", il);
  5355. // self-attention
  5356. {
  5357. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5358. cb(Qcur, "Qcur", il);
  5359. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5360. cb(Kcur, "Kcur", il);
  5361. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5362. cb(Vcur, "Vcur", il);
  5363. switch (model.type) {
  5364. case MODEL_7B:
  5365. Qcur = ggml_rope_custom(
  5366. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5367. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5368. ext_factor, attn_factor, beta_fast, beta_slow
  5369. );
  5370. Kcur = ggml_rope_custom(
  5371. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5372. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5373. ext_factor, attn_factor, beta_fast, beta_slow
  5374. );
  5375. break;
  5376. case MODEL_13B:
  5377. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5378. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5379. break;
  5380. default:
  5381. GGML_ASSERT(false);
  5382. }
  5383. cb(Qcur, "Qcur", il);
  5384. cb(Kcur, "Kcur", il);
  5385. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5386. model.layers[il].wo, NULL,
  5387. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5388. }
  5389. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5390. cb(ffn_inp, "ffn_inp", il);
  5391. // feed-forward network
  5392. {
  5393. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5394. model.layers[il].ffn_norm, NULL,
  5395. LLM_NORM_RMS, cb, il);
  5396. cb(cur, "ffn_norm", il);
  5397. cur = llm_build_ffn(ctx0, cur,
  5398. model.layers[il].ffn_up, NULL,
  5399. model.layers[il].ffn_gate, NULL,
  5400. model.layers[il].ffn_down, NULL,
  5401. NULL,
  5402. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5403. cb(cur, "ffn_out", il);
  5404. }
  5405. cur = ggml_add(ctx0, cur, ffn_inp);
  5406. cb(cur, "l_out", il);
  5407. // input for next layer
  5408. inpL = cur;
  5409. }
  5410. cur = inpL;
  5411. cur = llm_build_norm(ctx0, cur, hparams,
  5412. model.output_norm, NULL,
  5413. LLM_NORM_RMS, cb, -1);
  5414. cb(cur, "result_norm", -1);
  5415. // lm_head
  5416. cur = ggml_mul_mat(ctx0, model.output, cur);
  5417. cb(cur, "result_output", -1);
  5418. ggml_build_forward_expand(gf, cur);
  5419. return gf;
  5420. }
  5421. struct ggml_cgraph * build_falcon() {
  5422. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5423. const int64_t n_embd_head = hparams.n_embd_head_v;
  5424. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5425. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5426. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5427. struct ggml_tensor * cur;
  5428. struct ggml_tensor * inpL;
  5429. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5430. // inp_pos - contains the positions
  5431. struct ggml_tensor * inp_pos = build_inp_pos();
  5432. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5433. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5434. for (int il = 0; il < n_layer; ++il) {
  5435. struct ggml_tensor * attn_norm;
  5436. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5437. model.layers[il].attn_norm,
  5438. model.layers[il].attn_norm_b,
  5439. LLM_NORM, cb, il);
  5440. cb(attn_norm, "attn_norm", il);
  5441. // self-attention
  5442. {
  5443. if (model.layers[il].attn_norm_2) {
  5444. // Falcon-40B
  5445. cur = llm_build_norm(ctx0, inpL, hparams,
  5446. model.layers[il].attn_norm_2,
  5447. model.layers[il].attn_norm_2_b,
  5448. LLM_NORM, cb, il);
  5449. cb(cur, "attn_norm_2", il);
  5450. } else {
  5451. cur = attn_norm;
  5452. }
  5453. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5454. cb(cur, "wqkv", il);
  5455. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5456. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5457. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  5458. cb(Qcur, "Qcur", il);
  5459. cb(Kcur, "Kcur", il);
  5460. cb(Vcur, "Vcur", il);
  5461. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5462. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5463. // using mode = 2 for neox mode
  5464. Qcur = ggml_rope_custom(
  5465. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5466. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5467. );
  5468. cb(Qcur, "Qcur", il);
  5469. Kcur = ggml_rope_custom(
  5470. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5471. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5472. );
  5473. cb(Kcur, "Kcur", il);
  5474. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5475. model.layers[il].wo, NULL,
  5476. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5477. }
  5478. struct ggml_tensor * ffn_inp = cur;
  5479. // feed forward
  5480. {
  5481. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5482. model.layers[il].ffn_up, NULL,
  5483. NULL, NULL,
  5484. model.layers[il].ffn_down, NULL,
  5485. NULL,
  5486. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5487. cb(cur, "ffn_out", il);
  5488. }
  5489. cur = ggml_add(ctx0, cur, ffn_inp);
  5490. cb(cur, "l_out", il);
  5491. cur = ggml_add(ctx0, cur, inpL);
  5492. cb(cur, "l_out", il);
  5493. // input for next layer
  5494. inpL = cur;
  5495. }
  5496. cur = inpL;
  5497. // norm
  5498. cur = llm_build_norm(ctx0, cur, hparams,
  5499. model.output_norm,
  5500. model.output_norm_b,
  5501. LLM_NORM, cb, -1);
  5502. cb(cur, "result_norm", -1);
  5503. cur = ggml_mul_mat(ctx0, model.output, cur);
  5504. cb(cur, "result_output", -1);
  5505. ggml_build_forward_expand(gf, cur);
  5506. return gf;
  5507. }
  5508. struct ggml_cgraph * build_grok() {
  5509. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5510. const int64_t n_embd_head = hparams.n_embd_head_v;
  5511. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5512. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5513. struct ggml_tensor * cur;
  5514. struct ggml_tensor * inpL;
  5515. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5516. // multiply by embedding_multiplier_scale of 78.38367176906169
  5517. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5518. // inp_pos - contains the positions
  5519. struct ggml_tensor * inp_pos = build_inp_pos();
  5520. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5521. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5522. for (int il = 0; il < n_layer; ++il) {
  5523. struct ggml_tensor * inpSA = inpL;
  5524. // norm
  5525. cur = llm_build_norm(ctx0, inpL, hparams,
  5526. model.layers[il].attn_norm, NULL,
  5527. LLM_NORM_RMS, cb, il);
  5528. cb(cur, "attn_norm", il);
  5529. // self-attention
  5530. {
  5531. // compute Q and K and RoPE them
  5532. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5533. cb(Qcur, "Qcur", il);
  5534. if (model.layers[il].bq) {
  5535. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5536. cb(Qcur, "Qcur", il);
  5537. }
  5538. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5539. cb(Kcur, "Kcur", il);
  5540. if (model.layers[il].bk) {
  5541. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5542. cb(Kcur, "Kcur", il);
  5543. }
  5544. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5545. cb(Vcur, "Vcur", il);
  5546. if (model.layers[il].bv) {
  5547. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5548. cb(Vcur, "Vcur", il);
  5549. }
  5550. Qcur = ggml_rope_custom(
  5551. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5552. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5553. ext_factor, attn_factor, beta_fast, beta_slow
  5554. );
  5555. cb(Qcur, "Qcur", il);
  5556. Kcur = ggml_rope_custom(
  5557. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5558. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5559. ext_factor, attn_factor, beta_fast, beta_slow
  5560. );
  5561. cb(Kcur, "Kcur", il);
  5562. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5563. model.layers[il].wo, model.layers[il].bo,
  5564. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5565. }
  5566. // Grok
  5567. // if attn_out_norm is present then apply it before adding the input
  5568. if (model.layers[il].attn_out_norm) {
  5569. cur = llm_build_norm(ctx0, cur, hparams,
  5570. model.layers[il].attn_out_norm, NULL,
  5571. LLM_NORM_RMS, cb, il);
  5572. cb(cur, "attn_out_norm", il);
  5573. }
  5574. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5575. cb(ffn_inp, "ffn_inp", il);
  5576. // feed-forward network
  5577. // MoE branch
  5578. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5579. model.layers[il].ffn_norm, NULL,
  5580. LLM_NORM_RMS, cb, il);
  5581. cb(cur, "ffn_norm", il);
  5582. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5583. cb(logits, "ffn_moe_logits", il);
  5584. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5585. cb(probs, "ffn_moe_probs", il);
  5586. // select experts
  5587. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5588. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5589. ggml_tensor * weights = ggml_get_rows(ctx0,
  5590. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5591. cb(weights, "ffn_moe_weights", il);
  5592. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5593. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5594. cb(weights_sum, "ffn_moe_weights_sum", il);
  5595. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5596. cb(weights, "ffn_moe_weights_norm", il);
  5597. // compute expert outputs
  5598. ggml_tensor * moe_out = nullptr;
  5599. for (int i = 0; i < n_expert_used; ++i) {
  5600. ggml_tensor * cur_expert;
  5601. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5602. cb(cur_up, "ffn_moe_up", il);
  5603. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5604. cb(cur_gate, "ffn_moe_gate", il);
  5605. //GeLU
  5606. cur_gate = ggml_gelu(ctx0, cur_gate);
  5607. cb(cur_gate, "ffn_moe_gelu", il);
  5608. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5609. cb(cur_expert, "ffn_moe_gate_par", il);
  5610. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5611. cb(cur_expert, "ffn_moe_down", il);
  5612. cur_expert = ggml_mul(ctx0, cur_expert,
  5613. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5614. cb(cur_expert, "ffn_moe_weighted", il);
  5615. if (i == 0) {
  5616. moe_out = cur_expert;
  5617. } else {
  5618. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5619. cb(moe_out, "ffn_moe_out", il);
  5620. }
  5621. }
  5622. cur = moe_out;
  5623. // Grok
  5624. // if layer_out_norm is present then apply it before adding the input
  5625. // Idea: maybe ffn_out_norm is a better name
  5626. if (model.layers[il].layer_out_norm) {
  5627. cur = llm_build_norm(ctx0, cur, hparams,
  5628. model.layers[il].layer_out_norm, NULL,
  5629. LLM_NORM_RMS, cb, il);
  5630. cb(cur, "layer_out_norm", il);
  5631. }
  5632. cur = ggml_add(ctx0, cur, ffn_inp);
  5633. cb(cur, "ffn_out", il);
  5634. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5635. if (layer_dir != nullptr) {
  5636. cur = ggml_add(ctx0, cur, layer_dir);
  5637. }
  5638. cb(cur, "l_out", il);
  5639. // input for next layer
  5640. inpL = cur;
  5641. }
  5642. cur = inpL;
  5643. cur = llm_build_norm(ctx0, cur, hparams,
  5644. model.output_norm, NULL,
  5645. LLM_NORM_RMS, cb, -1);
  5646. cb(cur, "result_norm", -1);
  5647. // lm_head
  5648. cur = ggml_mul_mat(ctx0, model.output, cur);
  5649. // Grok
  5650. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5651. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5652. cb(cur, "result_output", -1);
  5653. ggml_build_forward_expand(gf, cur);
  5654. return gf;
  5655. }
  5656. struct ggml_cgraph * build_starcoder() {
  5657. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5658. const int64_t n_embd_head = hparams.n_embd_head_v;
  5659. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5660. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5661. struct ggml_tensor * cur;
  5662. struct ggml_tensor * inpL;
  5663. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5664. // inp_pos - contains the positions
  5665. struct ggml_tensor * inp_pos = build_inp_pos();
  5666. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5667. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5668. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5669. cb(pos, "pos_embd", -1);
  5670. inpL = ggml_add(ctx0, inpL, pos);
  5671. cb(inpL, "inpL", -1);
  5672. for (int il = 0; il < n_layer; ++il) {
  5673. cur = llm_build_norm(ctx0, inpL, hparams,
  5674. model.layers[il].attn_norm,
  5675. model.layers[il].attn_norm_b,
  5676. LLM_NORM, cb, il);
  5677. cb(cur, "attn_norm", il);
  5678. // self-attention
  5679. {
  5680. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5681. cb(cur, "wqkv", il);
  5682. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5683. cb(cur, "bqkv", il);
  5684. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5685. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5686. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  5687. cb(Qcur, "Qcur", il);
  5688. cb(Kcur, "Kcur", il);
  5689. cb(Vcur, "Vcur", il);
  5690. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5691. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5692. model.layers[il].wo, model.layers[il].bo,
  5693. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5694. }
  5695. // add the input
  5696. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5697. cb(ffn_inp, "ffn_inp", il);
  5698. // FF
  5699. {
  5700. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5701. model.layers[il].ffn_norm,
  5702. model.layers[il].ffn_norm_b,
  5703. LLM_NORM, cb, il);
  5704. cb(cur, "ffn_norm", il);
  5705. cur = llm_build_ffn(ctx0, cur,
  5706. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5707. NULL, NULL,
  5708. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5709. NULL,
  5710. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5711. cb(cur, "ffn_out", il);
  5712. }
  5713. inpL = ggml_add(ctx0, cur, ffn_inp);
  5714. cb(inpL, "l_out", il);
  5715. }
  5716. cur = llm_build_norm(ctx0, inpL, hparams,
  5717. model.output_norm,
  5718. model.output_norm_b,
  5719. LLM_NORM, cb, -1);
  5720. cb(cur, "result_norm", -1);
  5721. cur = ggml_mul_mat(ctx0, model.output, cur);
  5722. cb(cur, "result_output", -1);
  5723. ggml_build_forward_expand(gf, cur);
  5724. return gf;
  5725. }
  5726. struct ggml_cgraph * build_persimmon() {
  5727. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5728. const int64_t n_embd_head = hparams.n_embd_head_v;
  5729. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5730. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5731. struct ggml_tensor * cur;
  5732. struct ggml_tensor * inpL;
  5733. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5734. // inp_pos - contains the positions
  5735. struct ggml_tensor * inp_pos = build_inp_pos();
  5736. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5737. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5738. for (int il = 0; il < n_layer; ++il) {
  5739. struct ggml_tensor * residual = inpL;
  5740. cur = llm_build_norm(ctx0, inpL, hparams,
  5741. model.layers[il].attn_norm,
  5742. model.layers[il].attn_norm_b,
  5743. LLM_NORM, cb, il);
  5744. cb(cur, "attn_norm", il);
  5745. // self attention
  5746. {
  5747. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5748. cb(cur, "wqkv", il);
  5749. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5750. cb(cur, "bqkv", il);
  5751. // split qkv
  5752. GGML_ASSERT(n_head_kv == n_head);
  5753. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5754. cb(tmpqkv, "tmpqkv", il);
  5755. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5756. cb(tmpqkv_perm, "tmpqkv", il);
  5757. struct ggml_tensor * tmpq = ggml_view_3d(
  5758. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5759. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5760. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5761. 0
  5762. );
  5763. cb(tmpq, "tmpq", il);
  5764. struct ggml_tensor * tmpk = ggml_view_3d(
  5765. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5766. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5767. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5768. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5769. );
  5770. cb(tmpk, "tmpk", il);
  5771. // Q/K Layernorm
  5772. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5773. model.layers[il].attn_q_norm,
  5774. model.layers[il].attn_q_norm_b,
  5775. LLM_NORM, cb, il);
  5776. cb(tmpq, "tmpq", il);
  5777. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5778. model.layers[il].attn_k_norm,
  5779. model.layers[il].attn_k_norm_b,
  5780. LLM_NORM, cb, il);
  5781. cb(tmpk, "tmpk", il);
  5782. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5783. struct ggml_tensor * qrot = ggml_view_3d(
  5784. ctx0, tmpq, n_rot, n_head, n_tokens,
  5785. ggml_element_size(tmpq) * n_embd_head,
  5786. ggml_element_size(tmpq) * n_embd_head * n_head,
  5787. 0
  5788. );
  5789. cb(qrot, "qrot", il);
  5790. struct ggml_tensor * krot = ggml_view_3d(
  5791. ctx0, tmpk, n_rot, n_head, n_tokens,
  5792. ggml_element_size(tmpk) * n_embd_head,
  5793. ggml_element_size(tmpk) * n_embd_head * n_head,
  5794. 0
  5795. );
  5796. cb(krot, "krot", il);
  5797. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5798. struct ggml_tensor * qpass = ggml_view_3d(
  5799. ctx0, tmpq, n_rot, n_head, n_tokens,
  5800. ggml_element_size(tmpq) * n_embd_head,
  5801. ggml_element_size(tmpq) * n_embd_head * n_head,
  5802. ggml_element_size(tmpq) * n_rot
  5803. );
  5804. cb(qpass, "qpass", il);
  5805. struct ggml_tensor * kpass = ggml_view_3d(
  5806. ctx0, tmpk, n_rot, n_head, n_tokens,
  5807. ggml_element_size(tmpk) * n_embd_head,
  5808. ggml_element_size(tmpk) * n_embd_head * n_head,
  5809. ggml_element_size(tmpk) * n_rot
  5810. );
  5811. cb(kpass, "kpass", il);
  5812. struct ggml_tensor * qrotated = ggml_rope_custom(
  5813. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5814. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5815. );
  5816. cb(qrotated, "qrotated", il);
  5817. struct ggml_tensor * krotated = ggml_rope_custom(
  5818. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5819. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5820. );
  5821. cb(krotated, "krotated", il);
  5822. // ggml currently only supports concatenation on dim=2
  5823. // so we need to permute qrot, qpass, concat, then permute back.
  5824. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5825. cb(qrotated, "qrotated", il);
  5826. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5827. cb(krotated, "krotated", il);
  5828. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5829. cb(qpass, "qpass", il);
  5830. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5831. cb(kpass, "kpass", il);
  5832. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5833. cb(Qcur, "Qcur", il);
  5834. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5835. cb(Kcur, "Kcur", il);
  5836. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5837. cb(Q, "Q", il);
  5838. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5839. cb(Kcur, "Kcur", il);
  5840. struct ggml_tensor * Vcur = ggml_view_3d(
  5841. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5842. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5843. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5844. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5845. );
  5846. cb(Vcur, "Vcur", il);
  5847. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5848. model.layers[il].wo, model.layers[il].bo,
  5849. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5850. }
  5851. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5852. cb(ffn_inp, "ffn_inp", il);
  5853. // feed-forward network
  5854. {
  5855. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5856. model.layers[il].ffn_norm,
  5857. model.layers[il].ffn_norm_b,
  5858. LLM_NORM, cb, il);
  5859. cb(cur, "ffn_norm", il);
  5860. cur = llm_build_ffn(ctx0, cur,
  5861. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5862. NULL, NULL,
  5863. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5864. NULL,
  5865. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5866. cb(cur, "ffn_out", il);
  5867. }
  5868. cur = ggml_add(ctx0, cur, ffn_inp);
  5869. cb(cur, "l_out", il);
  5870. inpL = cur;
  5871. }
  5872. cur = inpL;
  5873. cur = llm_build_norm(ctx0, cur, hparams,
  5874. model.output_norm,
  5875. model.output_norm_b,
  5876. LLM_NORM, cb, -1);
  5877. cb(cur, "result_norm", -1);
  5878. cur = ggml_mul_mat(ctx0, model.output, cur);
  5879. cb(cur, "result_output", -1);
  5880. ggml_build_forward_expand(gf, cur);
  5881. return gf;
  5882. }
  5883. struct ggml_cgraph * build_refact() {
  5884. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5885. const int64_t n_embd_head = hparams.n_embd_head_v;
  5886. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5887. struct ggml_tensor * cur;
  5888. struct ggml_tensor * inpL;
  5889. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5890. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5891. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5892. // positions of the tokens in the KV cache
  5893. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5894. for (int il = 0; il < n_layer; ++il) {
  5895. struct ggml_tensor * inpSA = inpL;
  5896. cur = llm_build_norm(ctx0, inpL, hparams,
  5897. model.layers[il].attn_norm, NULL,
  5898. LLM_NORM_RMS, cb, il);
  5899. cb(cur, "attn_norm", il);
  5900. // self-attention
  5901. {
  5902. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5903. cb(Qcur, "Qcur", il);
  5904. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5905. cb(Kcur, "Kcur", il);
  5906. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5907. cb(Vcur, "Vcur", il);
  5908. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5909. cb(Kcur, "Kcur", il);
  5910. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5911. cb(Qcur, "Qcur", il);
  5912. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5913. model.layers[il].wo, NULL,
  5914. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5915. }
  5916. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5917. cb(ffn_inp, "ffn_inp", il);
  5918. // feed-forward network
  5919. {
  5920. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5921. model.layers[il].ffn_norm, NULL,
  5922. LLM_NORM_RMS, cb, il);
  5923. cb(cur, "ffn_norm", il);
  5924. cur = llm_build_ffn(ctx0, cur,
  5925. model.layers[il].ffn_up, NULL,
  5926. model.layers[il].ffn_gate, NULL,
  5927. model.layers[il].ffn_down, NULL,
  5928. NULL,
  5929. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5930. cb(cur, "ffn_out", il);
  5931. }
  5932. cur = ggml_add(ctx0, cur, ffn_inp);
  5933. cb(cur, "l_out", il);
  5934. // input for next layer
  5935. inpL = cur;
  5936. }
  5937. cur = inpL;
  5938. cur = llm_build_norm(ctx0, cur, hparams,
  5939. model.output_norm, NULL,
  5940. LLM_NORM_RMS, cb, -1);
  5941. cb(cur, "result_norm", -1);
  5942. // lm_head
  5943. cur = ggml_mul_mat(ctx0, model.output, cur);
  5944. cb(cur, "result_output", -1);
  5945. ggml_build_forward_expand(gf, cur);
  5946. return gf;
  5947. }
  5948. struct ggml_cgraph * build_bert() {
  5949. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5950. const int64_t n_embd_head = hparams.n_embd_head_v;
  5951. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5952. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5953. struct ggml_tensor * cur;
  5954. struct ggml_tensor * inpL;
  5955. struct ggml_tensor * inp_pos = build_inp_pos();
  5956. struct ggml_tensor * inp_mean = build_inp_mean();
  5957. struct ggml_tensor * inp_cls = build_inp_cls();
  5958. // construct input embeddings (token, type, position)
  5959. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5960. // token types are hardcoded to zero ("Sentence A")
  5961. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5962. inpL = ggml_add(ctx0, inpL, type_row0);
  5963. if (model.arch == LLM_ARCH_BERT) {
  5964. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5965. }
  5966. cb(inpL, "inp_embd", -1);
  5967. // embed layer norm
  5968. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5969. cb(inpL, "inp_norm", -1);
  5970. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5971. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  5972. // iterate layers
  5973. for (int il = 0; il < n_layer; ++il) {
  5974. struct ggml_tensor * cur = inpL;
  5975. struct ggml_tensor * Qcur;
  5976. struct ggml_tensor * Kcur;
  5977. struct ggml_tensor * Vcur;
  5978. // self-attention
  5979. if (model.arch == LLM_ARCH_BERT) {
  5980. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5981. cb(Qcur, "Qcur", il);
  5982. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5983. cb(Kcur, "Kcur", il);
  5984. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5985. cb(Vcur, "Vcur", il);
  5986. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5987. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5988. } else {
  5989. // compute Q and K and RoPE them
  5990. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5991. cb(cur, "wqkv", il);
  5992. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5993. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5994. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  5995. cb(Qcur, "Qcur", il);
  5996. cb(Kcur, "Kcur", il);
  5997. cb(Vcur, "Vcur", il);
  5998. Qcur = ggml_rope_custom(
  5999. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6000. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6001. ext_factor, attn_factor, beta_fast, beta_slow
  6002. );
  6003. cb(Qcur, "Qcur", il);
  6004. Kcur = ggml_rope_custom(
  6005. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6006. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6007. ext_factor, attn_factor, beta_fast, beta_slow
  6008. );
  6009. cb(Kcur, "Kcur", il);
  6010. }
  6011. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6012. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6013. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6014. cb(kq, "kq", il);
  6015. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6016. cb(kq, "kq_soft_max_ext", il);
  6017. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6018. cb(v, "v", il);
  6019. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6020. cb(kqv, "kqv", il);
  6021. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6022. cb(kqv_merged, "kqv_merged", il);
  6023. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6024. cb(cur, "kqv_merged_cont", il);
  6025. ggml_build_forward_expand(gf, cur);
  6026. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6027. if (model.layers[il].bo) {
  6028. cb(cur, "kqv_wo", il);
  6029. }
  6030. if (model.layers[il].bo) {
  6031. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6032. }
  6033. cb(cur, "kqv_out", il);
  6034. // re-add the layer input
  6035. cur = ggml_add(ctx0, cur, inpL);
  6036. // attention layer norm
  6037. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6038. struct ggml_tensor * ffn_inp = cur;
  6039. cb(ffn_inp, "ffn_inp", il);
  6040. // feed-forward network
  6041. if (model.arch == LLM_ARCH_BERT) {
  6042. cur = llm_build_ffn(ctx0, cur,
  6043. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6044. NULL, NULL,
  6045. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6046. NULL,
  6047. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6048. } else {
  6049. cur = llm_build_ffn(ctx0, cur,
  6050. model.layers[il].ffn_up, NULL,
  6051. model.layers[il].ffn_gate, NULL,
  6052. model.layers[il].ffn_down, NULL,
  6053. NULL,
  6054. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6055. }
  6056. cb(cur, "ffn_out", il);
  6057. // attentions bypass the intermediate layer
  6058. cur = ggml_add(ctx0, cur, ffn_inp);
  6059. // output layer norm
  6060. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6061. // input for next layer
  6062. inpL = cur;
  6063. }
  6064. // final output
  6065. cur = inpL;
  6066. cb(cur, "result_embd", -1);
  6067. // pooling layer
  6068. switch (pooling_type) {
  6069. case LLAMA_POOLING_TYPE_NONE:
  6070. {
  6071. // nop
  6072. } break;
  6073. case LLAMA_POOLING_TYPE_MEAN:
  6074. {
  6075. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6076. cb(cur, "result_embd_pooled", -1);
  6077. } break;
  6078. case LLAMA_POOLING_TYPE_CLS:
  6079. {
  6080. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6081. cb(cur, "result_embd_pooled", -1);
  6082. } break;
  6083. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6084. {
  6085. GGML_ASSERT(false && "Invalid pooling type");
  6086. } break;
  6087. }
  6088. ggml_build_forward_expand(gf, cur);
  6089. return gf;
  6090. }
  6091. struct ggml_cgraph * build_bloom() {
  6092. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6093. const int64_t n_embd_head = hparams.n_embd_head_v;
  6094. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6095. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6096. struct ggml_tensor * cur;
  6097. struct ggml_tensor * inpL;
  6098. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6099. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6100. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6101. // positions of the tokens in the KV cache
  6102. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6103. inpL = llm_build_norm(ctx0, inpL, hparams,
  6104. model.tok_norm,
  6105. model.tok_norm_b,
  6106. LLM_NORM, cb, -1);
  6107. cb(inpL, "inp_norm", -1);
  6108. for (int il = 0; il < n_layer; ++il) {
  6109. cur = llm_build_norm(ctx0, inpL, hparams,
  6110. model.layers[il].attn_norm,
  6111. model.layers[il].attn_norm_b,
  6112. LLM_NORM, cb, il);
  6113. cb(cur, "attn_norm", il);
  6114. // self-attention
  6115. {
  6116. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6117. cb(cur, "wqkv", il);
  6118. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6119. cb(cur, "bqkv", il);
  6120. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6121. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6122. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  6123. cb(Qcur, "Qcur", il);
  6124. cb(Kcur, "Kcur", il);
  6125. cb(Vcur, "Vcur", il);
  6126. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6127. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6128. model.layers[il].wo, model.layers[il].bo,
  6129. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6130. }
  6131. // Add the input
  6132. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6133. cb(ffn_inp, "ffn_inp", il);
  6134. // FF
  6135. {
  6136. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6137. model.layers[il].ffn_norm,
  6138. model.layers[il].ffn_norm_b,
  6139. LLM_NORM, cb, il);
  6140. cb(cur, "ffn_norm", il);
  6141. cur = llm_build_ffn(ctx0, cur,
  6142. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6143. NULL, NULL,
  6144. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6145. NULL,
  6146. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6147. cb(cur, "ffn_out", il);
  6148. }
  6149. inpL = ggml_add(ctx0, cur, ffn_inp);
  6150. cb(inpL, "l_out", il);
  6151. }
  6152. cur = llm_build_norm(ctx0, inpL, hparams,
  6153. model.output_norm,
  6154. model.output_norm_b,
  6155. LLM_NORM, cb, -1);
  6156. cb(cur, "result_norm", -1);
  6157. cur = ggml_mul_mat(ctx0, model.output, cur);
  6158. cb(cur, "result_output", -1);
  6159. ggml_build_forward_expand(gf, cur);
  6160. return gf;
  6161. }
  6162. struct ggml_cgraph * build_mpt() {
  6163. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6164. const int64_t n_embd_head = hparams.n_embd_head_v;
  6165. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6166. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6167. struct ggml_tensor * cur;
  6168. struct ggml_tensor * inpL;
  6169. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6170. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6171. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6172. // positions of the tokens in the KV cache
  6173. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6174. for (int il = 0; il < n_layer; ++il) {
  6175. struct ggml_tensor * attn_norm;
  6176. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6177. model.layers[il].attn_norm,
  6178. model.layers[il].attn_norm_b,
  6179. LLM_NORM, cb, il);
  6180. cb(attn_norm, "attn_norm", il);
  6181. // self-attention
  6182. {
  6183. cur = attn_norm;
  6184. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6185. cb(cur, "wqkv", il);
  6186. if (model.layers[il].bqkv){
  6187. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6188. cb(cur, "bqkv", il);
  6189. }
  6190. if (hparams.f_clamp_kqv > 0.0f) {
  6191. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6192. cb(cur, "wqkv_clamped", il);
  6193. }
  6194. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6195. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6196. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  6197. cb(Qcur, "Qcur", il);
  6198. cb(Kcur, "Kcur", il);
  6199. cb(Vcur, "Vcur", il);
  6200. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6201. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6202. model.layers[il].wo, model.layers[il].bo,
  6203. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6204. }
  6205. // Add the input
  6206. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6207. cb(ffn_inp, "ffn_inp", il);
  6208. // feed forward
  6209. {
  6210. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6211. model.layers[il].ffn_norm,
  6212. model.layers[il].ffn_norm_b,
  6213. LLM_NORM, cb, il);
  6214. cb(cur, "ffn_norm", il);
  6215. cur = llm_build_ffn(ctx0, cur,
  6216. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6217. NULL, NULL,
  6218. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6219. model.layers[il].ffn_act,
  6220. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6221. cb(cur, "ffn_out", il);
  6222. }
  6223. cur = ggml_add(ctx0, cur, ffn_inp);
  6224. cb(cur, "l_out", il);
  6225. // input for next layer
  6226. inpL = cur;
  6227. }
  6228. cur = inpL;
  6229. cur = llm_build_norm(ctx0, cur, hparams,
  6230. model.output_norm,
  6231. model.output_norm_b,
  6232. LLM_NORM, cb, -1);
  6233. cb(cur, "result_norm", -1);
  6234. cur = ggml_mul_mat(ctx0, model.output, cur);
  6235. cb(cur, "result_output", -1);
  6236. ggml_build_forward_expand(gf, cur);
  6237. return gf;
  6238. }
  6239. struct ggml_cgraph * build_stablelm() {
  6240. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6241. const int64_t n_embd_head = hparams.n_embd_head_v;
  6242. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6243. struct ggml_tensor * cur;
  6244. struct ggml_tensor * inpL;
  6245. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6246. // inp_pos - contains the positions
  6247. struct ggml_tensor * inp_pos = build_inp_pos();
  6248. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6249. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6250. for (int il = 0; il < n_layer; ++il) {
  6251. struct ggml_tensor * inpSA = inpL;
  6252. // norm
  6253. cur = llm_build_norm(ctx0, inpL, hparams,
  6254. model.layers[il].attn_norm,
  6255. model.layers[il].attn_norm_b,
  6256. LLM_NORM, cb, il);
  6257. cb(cur, "attn_norm", il);
  6258. // self-attention
  6259. {
  6260. // compute Q and K and RoPE them
  6261. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6262. cb(Qcur, "Qcur", il);
  6263. if (model.layers[il].bq) {
  6264. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6265. cb(Qcur, "Qcur", il);
  6266. }
  6267. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6268. cb(Kcur, "Kcur", il);
  6269. if (model.layers[il].bk) {
  6270. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6271. cb(Kcur, "Kcur", il);
  6272. }
  6273. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6274. cb(Vcur, "Vcur", il);
  6275. if (model.layers[il].bv) {
  6276. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6277. cb(Vcur, "Vcur", il);
  6278. }
  6279. Qcur = ggml_rope_custom(
  6280. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6281. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6282. ext_factor, attn_factor, beta_fast, beta_slow
  6283. );
  6284. cb(Qcur, "Qcur", il);
  6285. Kcur = ggml_rope_custom(
  6286. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6287. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6288. ext_factor, attn_factor, beta_fast, beta_slow
  6289. );
  6290. cb(Kcur, "Kcur", il);
  6291. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6292. model.layers[il].wo, NULL,
  6293. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6294. }
  6295. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6296. cb(ffn_inp, "ffn_inp", il);
  6297. // feed-forward network
  6298. {
  6299. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6300. model.layers[il].ffn_norm,
  6301. model.layers[il].ffn_norm_b,
  6302. LLM_NORM, cb, il);
  6303. cb(cur, "ffn_norm", il);
  6304. cur = llm_build_ffn(ctx0, cur,
  6305. model.layers[il].ffn_up, NULL,
  6306. model.layers[il].ffn_gate, NULL,
  6307. model.layers[il].ffn_down, NULL,
  6308. NULL,
  6309. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6310. cb(cur, "ffn_out", il);
  6311. }
  6312. cur = ggml_add(ctx0, cur, ffn_inp);
  6313. cb(cur, "l_out", il);
  6314. // input for next layer
  6315. inpL = cur;
  6316. }
  6317. cur = inpL;
  6318. cur = llm_build_norm(ctx0, cur, hparams,
  6319. model.output_norm,
  6320. model.output_norm_b,
  6321. LLM_NORM, cb, -1);
  6322. cb(cur, "result_norm", -1);
  6323. // lm_head
  6324. cur = ggml_mul_mat(ctx0, model.output, cur);
  6325. cb(cur, "result_output", -1);
  6326. ggml_build_forward_expand(gf, cur);
  6327. return gf;
  6328. }
  6329. struct ggml_cgraph * build_qwen() {
  6330. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6331. const int64_t n_embd_head = hparams.n_embd_head_v;
  6332. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6333. struct ggml_tensor * cur;
  6334. struct ggml_tensor * inpL;
  6335. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6336. // inp_pos - contains the positions
  6337. struct ggml_tensor * inp_pos = build_inp_pos();
  6338. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6339. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6340. for (int il = 0; il < n_layer; ++il) {
  6341. struct ggml_tensor * inpSA = inpL;
  6342. cur = llm_build_norm(ctx0, inpL, hparams,
  6343. model.layers[il].attn_norm, NULL,
  6344. LLM_NORM_RMS, cb, il);
  6345. cb(cur, "attn_norm", il);
  6346. // self-attention
  6347. {
  6348. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6349. cb(cur, "wqkv", il);
  6350. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6351. cb(cur, "bqkv", il);
  6352. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6353. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6354. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6355. cb(Qcur, "Qcur", il);
  6356. cb(Kcur, "Kcur", il);
  6357. cb(Vcur, "Vcur", il);
  6358. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6359. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6360. // using mode = 2 for neox mode
  6361. Qcur = ggml_rope_custom(
  6362. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6363. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6364. );
  6365. cb(Qcur, "Qcur", il);
  6366. Kcur = ggml_rope_custom(
  6367. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6368. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6369. );
  6370. cb(Kcur, "Kcur", il);
  6371. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6372. model.layers[il].wo, NULL,
  6373. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6374. }
  6375. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6376. cb(ffn_inp, "ffn_inp", il);
  6377. // feed-forward forward
  6378. {
  6379. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6380. model.layers[il].ffn_norm, NULL,
  6381. LLM_NORM_RMS, cb, il);
  6382. cb(cur, "ffn_norm", il);
  6383. cur = llm_build_ffn(ctx0, cur,
  6384. model.layers[il].ffn_up, NULL,
  6385. model.layers[il].ffn_gate, NULL,
  6386. model.layers[il].ffn_down, NULL,
  6387. NULL,
  6388. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6389. cb(cur, "ffn_out", il);
  6390. }
  6391. cur = ggml_add(ctx0, cur, ffn_inp);
  6392. cb(cur, "l_out", il);
  6393. // input for next layer
  6394. inpL = cur;
  6395. }
  6396. cur = inpL;
  6397. cur = llm_build_norm(ctx0, cur, hparams,
  6398. model.output_norm, NULL,
  6399. LLM_NORM_RMS, cb, -1);
  6400. cb(cur, "result_norm", -1);
  6401. // lm_head
  6402. cur = ggml_mul_mat(ctx0, model.output, cur);
  6403. cb(cur, "result_output", -1);
  6404. ggml_build_forward_expand(gf, cur);
  6405. return gf;
  6406. }
  6407. struct ggml_cgraph * build_qwen2() {
  6408. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6409. const int64_t n_embd_head = hparams.n_embd_head_v;
  6410. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6411. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6412. struct ggml_tensor * cur;
  6413. struct ggml_tensor * inpL;
  6414. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6415. // inp_pos - contains the positions
  6416. struct ggml_tensor * inp_pos = build_inp_pos();
  6417. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6418. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6419. for (int il = 0; il < n_layer; ++il) {
  6420. struct ggml_tensor * inpSA = inpL;
  6421. // norm
  6422. cur = llm_build_norm(ctx0, inpL, hparams,
  6423. model.layers[il].attn_norm, NULL,
  6424. LLM_NORM_RMS, cb, il);
  6425. cb(cur, "attn_norm", il);
  6426. // self-attention
  6427. {
  6428. // compute Q and K and RoPE them
  6429. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6430. cb(Qcur, "Qcur", il);
  6431. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6432. cb(Qcur, "Qcur", il);
  6433. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6434. cb(Kcur, "Kcur", il);
  6435. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6436. cb(Kcur, "Kcur", il);
  6437. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6438. cb(Vcur, "Vcur", il);
  6439. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6440. cb(Vcur, "Vcur", il);
  6441. // these nodes are added to the graph together so that they are not reordered
  6442. // by doing so, the number of splits in the graph is reduced
  6443. ggml_build_forward_expand(gf, Qcur);
  6444. ggml_build_forward_expand(gf, Kcur);
  6445. ggml_build_forward_expand(gf, Vcur);
  6446. Qcur = ggml_rope_custom(
  6447. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6448. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6449. ext_factor, attn_factor, beta_fast, beta_slow
  6450. );
  6451. cb(Qcur, "Qcur", il);
  6452. Kcur = ggml_rope_custom(
  6453. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6454. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6455. ext_factor, attn_factor, beta_fast, beta_slow
  6456. );
  6457. cb(Kcur, "Kcur", il);
  6458. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6459. model.layers[il].wo, model.layers[il].bo,
  6460. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6461. }
  6462. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6463. cb(ffn_inp, "ffn_inp", il);
  6464. // feed-forward network
  6465. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6466. model.layers[il].ffn_norm, NULL,
  6467. LLM_NORM_RMS, cb, il);
  6468. cb(cur, "ffn_norm", il);
  6469. cur = llm_build_ffn(ctx0, cur,
  6470. model.layers[il].ffn_up, NULL,
  6471. model.layers[il].ffn_gate, NULL,
  6472. model.layers[il].ffn_down, NULL,
  6473. NULL,
  6474. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6475. cb(cur, "ffn_out", il);
  6476. cur = ggml_add(ctx0, cur, ffn_inp);
  6477. cb(cur, "l_out", il);
  6478. // input for next layer
  6479. inpL = cur;
  6480. }
  6481. cur = inpL;
  6482. cur = llm_build_norm(ctx0, cur, hparams,
  6483. model.output_norm, NULL,
  6484. LLM_NORM_RMS, cb, -1);
  6485. cb(cur, "result_norm", -1);
  6486. // lm_head
  6487. cur = ggml_mul_mat(ctx0, model.output, cur);
  6488. cb(cur, "result_output", -1);
  6489. ggml_build_forward_expand(gf, cur);
  6490. return gf;
  6491. }
  6492. struct ggml_cgraph * build_phi2() {
  6493. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6494. const int64_t n_embd_head = hparams.n_embd_head_v;
  6495. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6496. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6497. struct ggml_tensor * cur;
  6498. struct ggml_tensor * attn_norm_output;
  6499. struct ggml_tensor * ffn_output;
  6500. struct ggml_tensor * inpL;
  6501. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6502. // inp_pos - contains the positions
  6503. struct ggml_tensor * inp_pos = build_inp_pos();
  6504. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6505. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6506. for (int il = 0; il < n_layer; ++il) {
  6507. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6508. model.layers[il].attn_norm,
  6509. model.layers[il].attn_norm_b,
  6510. LLM_NORM, cb, il);
  6511. cb(attn_norm_output, "attn_norm", il);
  6512. // self-attention
  6513. {
  6514. struct ggml_tensor * Qcur = nullptr;
  6515. struct ggml_tensor * Kcur = nullptr;
  6516. struct ggml_tensor * Vcur = nullptr;
  6517. if (model.layers[il].wqkv) {
  6518. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6519. cb(cur, "wqkv", il);
  6520. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6521. cb(cur, "bqkv", il);
  6522. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6523. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6524. Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  6525. } else {
  6526. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6527. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6528. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6529. }
  6530. cb(Qcur, "Qcur", il);
  6531. cb(Kcur, "Kcur", il);
  6532. cb(Vcur, "Vcur", il);
  6533. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6534. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6535. Qcur = ggml_rope_custom(
  6536. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6537. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6538. );
  6539. cb(Qcur, "Qcur", il);
  6540. // with phi2, we scale the Q to avoid precision issues
  6541. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6542. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6543. cb(Qcur, "Qcur", il);
  6544. Kcur = ggml_rope_custom(
  6545. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6546. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6547. );
  6548. cb(Kcur, "Kcur", il);
  6549. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6550. model.layers[il].wo, model.layers[il].bo,
  6551. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6552. }
  6553. // FF
  6554. {
  6555. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6556. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6557. NULL, NULL,
  6558. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6559. NULL,
  6560. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6561. cb(ffn_output, "ffn_out", il);
  6562. }
  6563. cur = ggml_add(ctx0, cur, ffn_output);
  6564. cb(cur, "l_out", il);
  6565. cur = ggml_add(ctx0, cur, inpL);
  6566. cb(cur, "l_out", il);
  6567. inpL = cur;
  6568. }
  6569. cur = llm_build_norm(ctx0, inpL, hparams,
  6570. model.output_norm,
  6571. model.output_norm_b,
  6572. LLM_NORM, cb, -1);
  6573. cb(cur, "result_norm", -1);
  6574. cur = ggml_mul_mat(ctx0, model.output, cur);
  6575. cb(cur, "result_output_no_bias", -1);
  6576. cur = ggml_add(ctx0, cur, model.output_b);
  6577. cb(cur, "result_output", -1);
  6578. ggml_build_forward_expand(gf, cur);
  6579. return gf;
  6580. }
  6581. struct ggml_cgraph * build_plamo() {
  6582. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6583. const int64_t n_embd_head = hparams.n_embd_head_v;
  6584. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6585. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6586. struct ggml_tensor * cur;
  6587. struct ggml_tensor * inpL;
  6588. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6589. // inp_pos - contains the positions
  6590. struct ggml_tensor * inp_pos = build_inp_pos();
  6591. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6592. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6593. for (int il = 0; il < n_layer; ++il) {
  6594. // norm
  6595. cur = llm_build_norm(ctx0, inpL, hparams,
  6596. model.layers[il].attn_norm, NULL,
  6597. LLM_NORM_RMS, cb, il);
  6598. cb(cur, "attn_norm", il);
  6599. struct ggml_tensor * attention_norm = cur;
  6600. // self-attention
  6601. {
  6602. // compute Q and K and RoPE them
  6603. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6604. cb(Qcur, "Qcur", il);
  6605. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6606. cb(Kcur, "Kcur", il);
  6607. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6608. cb(Vcur, "Vcur", il);
  6609. Qcur = ggml_rope_custom(
  6610. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6611. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6612. ext_factor, attn_factor, beta_fast, beta_slow);
  6613. cb(Qcur, "Qcur", il);
  6614. Kcur = ggml_rope_custom(
  6615. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6616. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6617. ext_factor, attn_factor, beta_fast, beta_slow);
  6618. cb(Kcur, "Kcur", il);
  6619. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6620. model.layers[il].wo, NULL,
  6621. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6622. }
  6623. struct ggml_tensor * sa_out = cur;
  6624. cur = attention_norm;
  6625. // feed-forward network
  6626. {
  6627. cur = llm_build_ffn(ctx0, cur,
  6628. model.layers[il].ffn_up, NULL,
  6629. model.layers[il].ffn_gate, NULL,
  6630. model.layers[il].ffn_down, NULL,
  6631. NULL,
  6632. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6633. cb(cur, "ffn_out", il);
  6634. }
  6635. cur = ggml_add(ctx0, cur, sa_out);
  6636. cb(cur, "l_out", il);
  6637. cur = ggml_add(ctx0, cur, inpL);
  6638. cb(cur, "l_out", il);
  6639. // input for next layer
  6640. inpL = cur;
  6641. }
  6642. cur = inpL;
  6643. cur = llm_build_norm(ctx0, cur, hparams,
  6644. model.output_norm, NULL,
  6645. LLM_NORM_RMS, cb, -1);
  6646. cb(cur, "result_norm", -1);
  6647. // lm_head
  6648. cur = ggml_mul_mat(ctx0, model.output, cur);
  6649. cb(cur, "result_output", -1);
  6650. ggml_build_forward_expand(gf, cur);
  6651. return gf;
  6652. }
  6653. struct ggml_cgraph * build_gpt2() {
  6654. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6655. const int64_t n_embd_head = hparams.n_embd_head_v;
  6656. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6657. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6658. struct ggml_tensor * cur;
  6659. struct ggml_tensor * pos;
  6660. struct ggml_tensor * inpL;
  6661. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6662. // inp_pos - contains the positions
  6663. struct ggml_tensor * inp_pos = build_inp_pos();
  6664. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6665. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6666. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6667. cb(pos, "pos_embd", -1);
  6668. inpL = ggml_add(ctx0, inpL, pos);
  6669. cb(inpL, "inpL", -1);
  6670. for (int il = 0; il < n_layer; ++il) {
  6671. cur = llm_build_norm(ctx0, inpL, hparams,
  6672. model.layers[il].attn_norm,
  6673. model.layers[il].attn_norm_b,
  6674. LLM_NORM, cb, il);
  6675. cb(cur, "attn_norm", il);
  6676. // self-attention
  6677. {
  6678. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6679. cb(cur, "wqkv", il);
  6680. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6681. cb(cur, "bqkv", il);
  6682. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6683. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6684. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  6685. cb(Qcur, "Qcur", il);
  6686. cb(Kcur, "Kcur", il);
  6687. cb(Vcur, "Vcur", il);
  6688. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6689. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6690. model.layers[il].wo, model.layers[il].bo,
  6691. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6692. }
  6693. // add the input
  6694. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6695. cb(ffn_inp, "ffn_inp", il);
  6696. // FF
  6697. {
  6698. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6699. model.layers[il].ffn_norm,
  6700. model.layers[il].ffn_norm_b,
  6701. LLM_NORM, cb, il);
  6702. cb(cur, "ffn_norm", il);
  6703. cur = llm_build_ffn(ctx0, cur,
  6704. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6705. NULL, NULL,
  6706. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6707. NULL,
  6708. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6709. cb(cur, "ffn_out", il);
  6710. }
  6711. inpL = ggml_add(ctx0, cur, ffn_inp);
  6712. cb(inpL, "l_out", il);
  6713. }
  6714. cur = llm_build_norm(ctx0, inpL, hparams,
  6715. model.output_norm,
  6716. model.output_norm_b,
  6717. LLM_NORM, cb, -1);
  6718. cb(cur, "result_norm", -1);
  6719. cur = ggml_mul_mat(ctx0, model.output, cur);
  6720. cb(cur, "result_output", -1);
  6721. ggml_build_forward_expand(gf, cur);
  6722. return gf;
  6723. }
  6724. struct ggml_cgraph * build_codeshell() {
  6725. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6726. const int64_t n_embd_head = hparams.n_embd_head_v;
  6727. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6728. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6729. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6730. struct ggml_tensor * cur;
  6731. struct ggml_tensor * inpL;
  6732. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6733. // inp_pos - contains the positions
  6734. struct ggml_tensor * inp_pos = build_inp_pos();
  6735. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6736. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6737. for (int il = 0; il < n_layer; ++il) {
  6738. cur = llm_build_norm(ctx0, inpL, hparams,
  6739. model.layers[il].attn_norm,
  6740. model.layers[il].attn_norm_b,
  6741. LLM_NORM, cb, il);
  6742. cb(cur, "attn_norm", il);
  6743. // self-attention
  6744. {
  6745. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6746. cb(cur, "wqkv", il);
  6747. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6748. cb(cur, "bqkv", il);
  6749. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6750. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6751. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd + n_embd_gqa)));
  6752. cb(tmpq, "tmpq", il);
  6753. cb(tmpk, "tmpk", il);
  6754. cb(Vcur, "Vcur", il);
  6755. struct ggml_tensor * Qcur = ggml_rope_custom(
  6756. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  6757. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6758. ext_factor, attn_factor, beta_fast, beta_slow
  6759. );
  6760. cb(Qcur, "Qcur", il);
  6761. struct ggml_tensor * Kcur = ggml_rope_custom(
  6762. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6763. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6764. ext_factor, attn_factor, beta_fast, beta_slow
  6765. );
  6766. cb(Kcur, "Kcur", il);
  6767. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6768. model.layers[il].wo, model.layers[il].bo,
  6769. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6770. }
  6771. // add the input
  6772. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6773. cb(ffn_inp, "ffn_inp", il);
  6774. // FF
  6775. {
  6776. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6777. model.layers[il].ffn_norm,
  6778. model.layers[il].ffn_norm_b,
  6779. LLM_NORM, cb, il);
  6780. cb(cur, "ffn_norm", il);
  6781. cur = llm_build_ffn(ctx0, cur,
  6782. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6783. NULL, NULL,
  6784. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6785. NULL,
  6786. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6787. cb(cur, "ffn_out", il);
  6788. }
  6789. inpL = ggml_add(ctx0, cur, ffn_inp);
  6790. cb(inpL, "l_out", il);
  6791. }
  6792. cur = llm_build_norm(ctx0, inpL, hparams,
  6793. model.output_norm,
  6794. model.output_norm_b,
  6795. LLM_NORM, cb, -1);
  6796. cb(cur, "result_norm", -1);
  6797. cur = ggml_mul_mat(ctx0, model.output, cur);
  6798. cb(cur, "result_output", -1);
  6799. ggml_build_forward_expand(gf, cur);
  6800. return gf;
  6801. }
  6802. struct ggml_cgraph * build_orion() {
  6803. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6804. const int64_t n_embd_head = hparams.n_embd_head_v;
  6805. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6806. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6807. struct ggml_tensor * cur;
  6808. struct ggml_tensor * inpL;
  6809. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6810. // inp_pos - contains the positions
  6811. struct ggml_tensor * inp_pos = build_inp_pos();
  6812. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6813. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6814. for (int il = 0; il < n_layer; ++il) {
  6815. struct ggml_tensor * inpSA = inpL;
  6816. // norm
  6817. cur = llm_build_norm(ctx0, inpL, hparams,
  6818. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6819. LLM_NORM, cb, il);
  6820. cb(cur, "attn_norm", il);
  6821. // self-attention
  6822. {
  6823. // compute Q and K and RoPE them
  6824. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6825. cb(Qcur, "Qcur", il);
  6826. // if (model.layers[il].bq) {
  6827. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6828. // cb(Qcur, "Qcur", il);
  6829. // }
  6830. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6831. cb(Kcur, "Kcur", il);
  6832. // if (model.layers[il].bk) {
  6833. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6834. // cb(Kcur, "Kcur", il);
  6835. // }
  6836. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6837. cb(Vcur, "Vcur", il);
  6838. // if (model.layers[il].bv) {
  6839. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6840. // cb(Vcur, "Vcur", il);
  6841. // }
  6842. Qcur = ggml_rope_custom(
  6843. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6844. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6845. ext_factor, attn_factor, beta_fast, beta_slow
  6846. );
  6847. cb(Qcur, "Qcur", il);
  6848. Kcur = ggml_rope_custom(
  6849. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6850. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6851. ext_factor, attn_factor, beta_fast, beta_slow
  6852. );
  6853. cb(Kcur, "Kcur", il);
  6854. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6855. model.layers[il].wo, NULL,
  6856. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6857. }
  6858. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6859. cb(ffn_inp, "ffn_inp", il);
  6860. // feed-forward network
  6861. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6862. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6863. LLM_NORM, cb, il);
  6864. cb(cur, "ffn_norm", il);
  6865. cur = llm_build_ffn(ctx0, cur,
  6866. model.layers[il].ffn_up, NULL,
  6867. model.layers[il].ffn_gate, NULL,
  6868. model.layers[il].ffn_down, NULL,
  6869. NULL,
  6870. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6871. cb(cur, "ffn_out", il);
  6872. cur = ggml_add(ctx0, cur, ffn_inp);
  6873. cb(cur, "l_out", il);
  6874. // input for next layer
  6875. inpL = cur;
  6876. }
  6877. cur = inpL;
  6878. cur = llm_build_norm(ctx0, cur, hparams,
  6879. model.output_norm, model.output_norm_b,
  6880. LLM_NORM, cb, -1);
  6881. cb(cur, "result_norm", -1);
  6882. // lm_head
  6883. cur = ggml_mul_mat(ctx0, model.output, cur);
  6884. cb(cur, "result_output", -1);
  6885. ggml_build_forward_expand(gf, cur);
  6886. return gf;
  6887. }
  6888. struct ggml_cgraph * build_internlm2() {
  6889. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6890. const int64_t n_embd_head = hparams.n_embd_head_v;
  6891. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6892. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6893. struct ggml_tensor * cur;
  6894. struct ggml_tensor * inpL;
  6895. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6896. // inp_pos - contains the positions
  6897. struct ggml_tensor * inp_pos = build_inp_pos();
  6898. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6899. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6900. for (int il = 0; il < n_layer; ++il) {
  6901. struct ggml_tensor * inpSA = inpL;
  6902. // norm
  6903. cur = llm_build_norm(ctx0, inpL, hparams,
  6904. model.layers[il].attn_norm, NULL,
  6905. LLM_NORM_RMS, cb, il);
  6906. cb(cur, "attn_norm", il);
  6907. // self-attention
  6908. {
  6909. // compute Q and K and RoPE them
  6910. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6911. cb(Qcur, "Qcur", il);
  6912. if (model.layers[il].bq) {
  6913. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6914. cb(Qcur, "Qcur", il);
  6915. }
  6916. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6917. cb(Kcur, "Kcur", il);
  6918. if (model.layers[il].bk) {
  6919. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6920. cb(Kcur, "Kcur", il);
  6921. }
  6922. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6923. cb(Vcur, "Vcur", il);
  6924. if (model.layers[il].bv) {
  6925. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6926. cb(Vcur, "Vcur", il);
  6927. }
  6928. Qcur = ggml_rope_custom(
  6929. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6930. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6931. ext_factor, attn_factor, beta_fast, beta_slow
  6932. );
  6933. cb(Qcur, "Qcur", il);
  6934. Kcur = ggml_rope_custom(
  6935. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6936. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6937. ext_factor, attn_factor, beta_fast, beta_slow
  6938. );
  6939. cb(Kcur, "Kcur", il);
  6940. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6941. model.layers[il].wo, model.layers[il].bo,
  6942. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6943. }
  6944. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6945. cb(ffn_inp, "ffn_inp", il);
  6946. // feed-forward network
  6947. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6948. model.layers[il].ffn_norm, NULL,
  6949. LLM_NORM_RMS, cb, il);
  6950. cb(cur, "ffn_norm", il);
  6951. cur = llm_build_ffn(ctx0, cur,
  6952. model.layers[il].ffn_up, NULL,
  6953. model.layers[il].ffn_gate, NULL,
  6954. model.layers[il].ffn_down, NULL,
  6955. NULL,
  6956. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6957. cb(cur, "ffn_out", il);
  6958. cur = ggml_add(ctx0, cur, ffn_inp);
  6959. cb(cur, "l_out", il);
  6960. // input for next layer
  6961. inpL = cur;
  6962. }
  6963. cur = inpL;
  6964. cur = llm_build_norm(ctx0, cur, hparams,
  6965. model.output_norm, NULL,
  6966. LLM_NORM_RMS, cb, -1);
  6967. cb(cur, "result_norm", -1);
  6968. // lm_head
  6969. cur = ggml_mul_mat(ctx0, model.output, cur);
  6970. cb(cur, "result_output", -1);
  6971. ggml_build_forward_expand(gf, cur);
  6972. return gf;
  6973. }
  6974. // ref: https://arxiv.org/abs/2203.03466
  6975. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6976. // based on the original build_llama() function
  6977. struct ggml_cgraph * build_minicpm() {
  6978. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6979. const int64_t n_embd_head = hparams.n_embd_head_v;
  6980. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6981. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6982. const int64_t n_embd = hparams.n_embd;
  6983. //TODO: if the model varies, these parameters need to be read from the model
  6984. const int64_t n_embd_base = 256;
  6985. const float scale_embd = 12.0f;
  6986. const float scale_depth = 1.4f;
  6987. struct ggml_tensor * cur;
  6988. struct ggml_tensor * inpL;
  6989. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6990. // scale the input embeddings
  6991. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6992. cb(inpL, "inp_scaled", -1);
  6993. // inp_pos - contains the positions
  6994. struct ggml_tensor * inp_pos = build_inp_pos();
  6995. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6996. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6997. for (int il = 0; il < n_layer; ++il) {
  6998. struct ggml_tensor * inpSA = inpL;
  6999. // norm
  7000. cur = llm_build_norm(ctx0, inpL, hparams,
  7001. model.layers[il].attn_norm, NULL,
  7002. LLM_NORM_RMS, cb, il);
  7003. cb(cur, "attn_norm", il);
  7004. // self-attention
  7005. {
  7006. // compute Q and K and RoPE them
  7007. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7008. cb(Qcur, "Qcur", il);
  7009. if (model.layers[il].bq) {
  7010. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7011. cb(Qcur, "Qcur", il);
  7012. }
  7013. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7014. cb(Kcur, "Kcur", il);
  7015. if (model.layers[il].bk) {
  7016. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7017. cb(Kcur, "Kcur", il);
  7018. }
  7019. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7020. cb(Vcur, "Vcur", il);
  7021. if (model.layers[il].bv) {
  7022. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7023. cb(Vcur, "Vcur", il);
  7024. }
  7025. Qcur = ggml_rope_custom(
  7026. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7027. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7028. ext_factor, attn_factor, beta_fast, beta_slow
  7029. );
  7030. cb(Qcur, "Qcur", il);
  7031. Kcur = ggml_rope_custom(
  7032. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7033. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7034. ext_factor, attn_factor, beta_fast, beta_slow
  7035. );
  7036. cb(Kcur, "Kcur", il);
  7037. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7038. model.layers[il].wo, model.layers[il].bo,
  7039. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7040. }
  7041. // scale_res - scale the hidden states for residual connection
  7042. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7043. cur = ggml_scale(ctx0, cur, scale_res);
  7044. cb(cur, "hidden_scaled", -1);
  7045. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7046. cb(ffn_inp, "ffn_inp", il);
  7047. // feed-forward network
  7048. {
  7049. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7050. model.layers[il].ffn_norm, NULL,
  7051. LLM_NORM_RMS, cb, il);
  7052. cb(cur, "ffn_norm", il);
  7053. cur = llm_build_ffn(ctx0, cur,
  7054. model.layers[il].ffn_up, NULL,
  7055. model.layers[il].ffn_gate, NULL,
  7056. model.layers[il].ffn_down, NULL,
  7057. NULL,
  7058. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7059. cb(cur, "ffn_out", il);
  7060. }
  7061. // scale the hidden states for residual connection
  7062. cur = ggml_scale(ctx0, cur, scale_res);
  7063. cb(cur, "hidden_scaled_ffn", -1);
  7064. cur = ggml_add(ctx0, cur, ffn_inp);
  7065. cb(cur, "l_out", il);
  7066. // input for next layer
  7067. inpL = cur;
  7068. }
  7069. cur = inpL;
  7070. cur = llm_build_norm(ctx0, cur, hparams,
  7071. model.output_norm, NULL,
  7072. LLM_NORM_RMS, cb, -1);
  7073. cb(cur, "result_norm", -1);
  7074. // lm_head scaling
  7075. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7076. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7077. cb(cur, "lmhead_scaling", -1);
  7078. // lm_head
  7079. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7080. cb(cur, "result_output", -1);
  7081. ggml_build_forward_expand(gf, cur);
  7082. return gf;
  7083. }
  7084. struct ggml_cgraph * build_gemma() {
  7085. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7086. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7087. struct ggml_tensor * cur;
  7088. struct ggml_tensor * inpL;
  7089. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7090. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7091. cb(inpL, "inp_scaled", -1);
  7092. // inp_pos - contains the positions
  7093. struct ggml_tensor * inp_pos = build_inp_pos();
  7094. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7095. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7096. for (int il = 0; il < n_layer; ++il) {
  7097. // norm
  7098. cur = llm_build_norm(ctx0, inpL, hparams,
  7099. model.layers[il].attn_norm, NULL,
  7100. LLM_NORM_RMS, cb, il);
  7101. cb(cur, "attn_norm", il);
  7102. // self-attention
  7103. {
  7104. // compute Q and K and RoPE them
  7105. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7106. cb(Qcur, "Qcur", il);
  7107. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7108. cb(Kcur, "Kcur", il);
  7109. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7110. cb(Vcur, "Vcur", il);
  7111. Qcur = ggml_rope_custom(
  7112. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7113. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7114. ext_factor, attn_factor, beta_fast, beta_slow);
  7115. cb(Qcur, "Qcur", il);
  7116. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7117. cb(Qcur, "Qcur_scaled", il);
  7118. Kcur = ggml_rope_custom(
  7119. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7120. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7121. ext_factor, attn_factor, beta_fast, beta_slow);
  7122. cb(Kcur, "Kcur", il);
  7123. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7124. model.layers[il].wo, NULL,
  7125. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7126. }
  7127. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7128. cb(sa_out, "sa_out", il);
  7129. cur = llm_build_norm(ctx0, sa_out, hparams,
  7130. model.layers[il].ffn_norm, NULL,
  7131. LLM_NORM_RMS, cb, il);
  7132. cb(cur, "ffn_norm", il);
  7133. // feed-forward network
  7134. {
  7135. cur = llm_build_ffn(ctx0, cur,
  7136. model.layers[il].ffn_up, NULL,
  7137. model.layers[il].ffn_gate, NULL,
  7138. model.layers[il].ffn_down, NULL,
  7139. NULL,
  7140. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7141. cb(cur, "ffn_out", il);
  7142. }
  7143. cur = ggml_add(ctx0, cur, sa_out);
  7144. cb(cur, "l_out", il);
  7145. // input for next layer
  7146. inpL = cur;
  7147. }
  7148. cur = inpL;
  7149. cur = llm_build_norm(ctx0, cur, hparams,
  7150. model.output_norm, NULL,
  7151. LLM_NORM_RMS, cb, -1);
  7152. cb(cur, "result_norm", -1);
  7153. // lm_head
  7154. cur = ggml_mul_mat(ctx0, model.output, cur);
  7155. cb(cur, "result_output", -1);
  7156. ggml_build_forward_expand(gf, cur);
  7157. return gf;
  7158. }
  7159. struct ggml_cgraph * build_starcoder2() {
  7160. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7161. const int64_t n_embd_head = hparams.n_embd_head_v;
  7162. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7163. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7164. struct ggml_tensor * cur;
  7165. struct ggml_tensor * inpL;
  7166. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7167. // inp_pos - contains the positions
  7168. struct ggml_tensor * inp_pos = build_inp_pos();
  7169. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7170. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7171. for (int il = 0; il < n_layer; ++il) {
  7172. struct ggml_tensor * inpSA = inpL;
  7173. // norm
  7174. cur = llm_build_norm(ctx0, inpL, hparams,
  7175. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7176. LLM_NORM, cb, il);
  7177. cb(cur, "attn_norm", il);
  7178. // self-attention
  7179. {
  7180. // compute Q and K and RoPE them
  7181. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7182. cb(Qcur, "Qcur", il);
  7183. if (model.layers[il].bq) {
  7184. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7185. cb(Qcur, "Qcur", il);
  7186. }
  7187. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7188. cb(Kcur, "Kcur", il);
  7189. if (model.layers[il].bk) {
  7190. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7191. cb(Kcur, "Kcur", il);
  7192. }
  7193. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7194. cb(Vcur, "Vcur", il);
  7195. if (model.layers[il].bv) {
  7196. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7197. cb(Vcur, "Vcur", il);
  7198. }
  7199. Qcur = ggml_rope_custom(
  7200. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7201. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7202. ext_factor, attn_factor, beta_fast, beta_slow
  7203. );
  7204. cb(Qcur, "Qcur", il);
  7205. Kcur = ggml_rope_custom(
  7206. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7207. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7208. ext_factor, attn_factor, beta_fast, beta_slow
  7209. );
  7210. cb(Kcur, "Kcur", il);
  7211. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7212. model.layers[il].wo, model.layers[il].bo,
  7213. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7214. }
  7215. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7216. cb(ffn_inp, "ffn_inp", il);
  7217. // feed-forward network
  7218. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7219. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7220. LLM_NORM, cb, il);
  7221. cb(cur, "ffn_norm", il);
  7222. cur = llm_build_ffn(ctx0, cur,
  7223. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7224. NULL, NULL,
  7225. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7226. NULL,
  7227. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7228. cb(cur, "ffn_out", il);
  7229. cur = ggml_add(ctx0, cur, ffn_inp);
  7230. cb(cur, "l_out", il);
  7231. // input for next layer
  7232. inpL = cur;
  7233. }
  7234. cur = inpL;
  7235. cur = llm_build_norm(ctx0, cur, hparams,
  7236. model.output_norm, model.output_norm_b,
  7237. LLM_NORM, cb, -1);
  7238. cb(cur, "result_norm", -1);
  7239. // lm_head
  7240. cur = ggml_mul_mat(ctx0, model.output, cur);
  7241. cb(cur, "result_output", -1);
  7242. ggml_build_forward_expand(gf, cur);
  7243. return gf;
  7244. }
  7245. struct ggml_cgraph * build_mamba() {
  7246. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7247. const int64_t d_model = n_embd;
  7248. const int64_t d_conv = hparams.ssm_d_conv;
  7249. const int64_t d_inner = hparams.ssm_d_inner;
  7250. GGML_ASSERT(2 * d_model == d_inner);
  7251. const int64_t d_state = hparams.ssm_d_state;
  7252. const int64_t dt_rank = hparams.ssm_dt_rank;
  7253. struct ggml_tensor * cur;
  7254. struct ggml_tensor * inpL;
  7255. // {n_embd, n_tokens}
  7256. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7257. struct ggml_tensor * state_mask = build_inp_s_mask();
  7258. struct ggml_tensor * state_seq = build_inp_s_seq();
  7259. for (int il = 0; il < n_layer; ++il) {
  7260. // (ab)using the KV cache to store the states
  7261. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7262. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7263. // clear states of sequences which are starting at the beginning of this batch
  7264. {
  7265. conv_states = ggml_mul(ctx0,
  7266. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7267. state_mask);
  7268. ssm_states = ggml_mul(ctx0,
  7269. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7270. state_mask);
  7271. }
  7272. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7273. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7274. // norm
  7275. cur = llm_build_norm(ctx0, inpL, hparams,
  7276. model.layers[il].attn_norm, NULL,
  7277. LLM_NORM_RMS, cb, il);
  7278. cb(cur, "attn_norm", il);
  7279. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7280. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7281. // split the above in two
  7282. // => {d_inner, n_tokens}
  7283. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7284. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7285. // conv
  7286. {
  7287. // Custom operator which is needed only to ease simultaneous sequence processing.
  7288. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7289. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7290. // then element-wise multiply that with the conv1d weigth,
  7291. // then sum the elements of each row,
  7292. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7293. // then permute away the ne[0] dimension,
  7294. // and then you're left with the resulting x tensor.
  7295. // The new conv_states is the last (d_conv - 1) columns
  7296. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7297. // For simultaneous sequences, it's more complicated.
  7298. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7299. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7300. ggml_build_forward_expand(gf,
  7301. ggml_cpy(ctx0,
  7302. ggml_view_2d(ctx0, x_conv, d_conv - 1, d_inner*n_kv, d_conv*ggml_element_size(x_conv), (1+d_inner*n_tokens)*ggml_element_size(x_conv)),
  7303. ggml_view_1d(ctx0, kv_self.k_l[il], (d_conv - 1)*(d_inner)*(n_kv), kv_head*(d_conv - 1)*(d_inner)*ggml_element_size(x_conv))));
  7304. // extract x from x_conv
  7305. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7306. // bias
  7307. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7308. x = ggml_silu(ctx0, x);
  7309. }
  7310. // ssm
  7311. {
  7312. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7313. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7314. // split
  7315. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7316. struct ggml_tensor * B = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*dt_rank);
  7317. struct ggml_tensor * C = ggml_view_2d(ctx0, x_db, d_state, n_tokens, x_db->nb[1], ggml_element_size(x_db)*(dt_rank+d_state));
  7318. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7319. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7320. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7321. // Custom operator to optimize the parallel associative scan
  7322. // as described in the Annex D of the Mamba paper.
  7323. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7324. // because only a single tensor can be returned.
  7325. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7326. // store last states (the second part of y_ssm_states)
  7327. ggml_build_forward_expand(gf,
  7328. ggml_cpy(ctx0,
  7329. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7330. ggml_view_1d(ctx0, kv_self.v_l[il], d_state*d_inner*n_kv, kv_head*d_state*d_inner*ggml_element_size(ssm_states))));
  7331. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7332. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7333. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7334. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7335. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7336. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7337. }
  7338. // residual
  7339. cur = ggml_add(ctx0, cur, inpL);
  7340. cb(cur, "l_out", il);
  7341. // input for next layer
  7342. inpL = cur;
  7343. }
  7344. // final rmsnorm
  7345. cur = llm_build_norm(ctx0, inpL, hparams,
  7346. model.output_norm, NULL,
  7347. LLM_NORM_RMS, cb, -1);
  7348. cb(cur, "result_norm", -1);
  7349. // lm_head
  7350. cur = ggml_mul_mat(ctx0, model.output, cur);
  7351. cb(cur, "result_output", -1);
  7352. ggml_build_forward_expand(gf, cur);
  7353. return gf;
  7354. }
  7355. struct ggml_cgraph * build_command_r() {
  7356. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7357. const int64_t n_embd_head = hparams.n_embd_head_v;
  7358. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7359. const float f_logit_scale = hparams.f_logit_scale;
  7360. struct ggml_tensor * cur;
  7361. struct ggml_tensor * inpL;
  7362. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7363. // inp_pos - contains the positions
  7364. struct ggml_tensor * inp_pos = build_inp_pos();
  7365. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7366. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7367. for (int il = 0; il < n_layer; ++il) {
  7368. // norm
  7369. cur = llm_build_norm(ctx0, inpL, hparams,
  7370. model.layers[il].attn_norm, NULL,
  7371. LLM_NORM, cb, il);
  7372. cb(cur, "attn_norm", il);
  7373. struct ggml_tensor * ffn_inp = cur;
  7374. // self-attention
  7375. {
  7376. // compute Q and K and RoPE them
  7377. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7378. cb(Qcur, "Qcur", il);
  7379. if (model.layers[il].bq) {
  7380. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7381. cb(Qcur, "Qcur", il);
  7382. }
  7383. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7384. cb(Kcur, "Kcur", il);
  7385. if (model.layers[il].bk) {
  7386. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7387. cb(Kcur, "Kcur", il);
  7388. }
  7389. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7390. cb(Vcur, "Vcur", il);
  7391. if (model.layers[il].bv) {
  7392. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7393. cb(Vcur, "Vcur", il);
  7394. }
  7395. Qcur = ggml_rope_custom(
  7396. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7397. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7398. ext_factor, attn_factor, beta_fast, beta_slow
  7399. );
  7400. cb(Qcur, "Qcur", il);
  7401. Kcur = ggml_rope_custom(
  7402. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7403. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7404. ext_factor, attn_factor, beta_fast, beta_slow
  7405. );
  7406. cb(Kcur, "Kcur", il);
  7407. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7408. model.layers[il].wo, model.layers[il].bo,
  7409. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7410. }
  7411. struct ggml_tensor * attn_out = cur;
  7412. // feed-forward network
  7413. {
  7414. cur = llm_build_ffn(ctx0, ffn_inp,
  7415. model.layers[il].ffn_up, NULL,
  7416. model.layers[il].ffn_gate, NULL,
  7417. model.layers[il].ffn_down, NULL,
  7418. NULL,
  7419. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7420. cb(cur, "ffn_out", il);
  7421. }
  7422. // add together residual + FFN + self-attention
  7423. cur = ggml_add(ctx0, cur, inpL);
  7424. cur = ggml_add(ctx0, cur, attn_out);
  7425. cb(cur, "l_out", il);
  7426. // input for next layer
  7427. inpL = cur;
  7428. }
  7429. cur = inpL;
  7430. cur = llm_build_norm(ctx0, cur, hparams,
  7431. model.output_norm, NULL,
  7432. LLM_NORM, cb, -1);
  7433. cb(cur, "result_norm", -1);
  7434. // lm_head
  7435. cur = ggml_mul_mat(ctx0, model.output, cur);
  7436. if (f_logit_scale) {
  7437. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7438. }
  7439. cb(cur, "result_output", -1);
  7440. ggml_build_forward_expand(gf, cur);
  7441. return gf;
  7442. }
  7443. };
  7444. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7445. llama_batch dummy;
  7446. dummy.n_tokens = 0;
  7447. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7448. struct llm_build_context llm(lctx, dummy, cb, false);
  7449. llm.init();
  7450. struct ggml_cgraph * result = llm.build_defrag(ids);
  7451. llm.free();
  7452. return result;
  7453. }
  7454. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7455. llama_batch dummy;
  7456. dummy.n_tokens = 0;
  7457. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7458. struct llm_build_context llm(lctx, dummy, cb, false);
  7459. llm.init();
  7460. struct ggml_cgraph * result = llm.build_k_shift();
  7461. llm.free();
  7462. return result;
  7463. }
  7464. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7465. llama_batch dummy;
  7466. dummy.n_tokens = 0;
  7467. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7468. struct llm_build_context llm(lctx, dummy, cb, false);
  7469. llm.init();
  7470. struct ggml_cgraph * result = llm.build_s_copy();
  7471. llm.free();
  7472. return result;
  7473. }
  7474. static struct ggml_cgraph * llama_build_graph(
  7475. llama_context & lctx,
  7476. const llama_batch & batch,
  7477. bool worst_case) {
  7478. const auto & model = lctx.model;
  7479. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7480. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7481. if (il >= 0) {
  7482. ggml_format_name(cur, "%s-%d", name, il);
  7483. } else {
  7484. ggml_set_name(cur, name);
  7485. }
  7486. if (!lctx.cparams.offload_kqv) {
  7487. if (strcmp(name, "kqv_merged_cont") == 0) {
  7488. // all nodes between the KV store and the attention output are run on the CPU
  7489. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7490. }
  7491. }
  7492. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7493. // FIXME: fix in ggml_backend_sched
  7494. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7495. if (batch.n_tokens < 32 || full_offload) {
  7496. if (il != -1 && strcmp(name, "norm") == 0) {
  7497. for (auto * backend : lctx.backends) {
  7498. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7499. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7500. break;
  7501. }
  7502. }
  7503. }
  7504. }
  7505. };
  7506. struct ggml_cgraph * result = NULL;
  7507. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7508. llm.init();
  7509. switch (model.arch) {
  7510. case LLM_ARCH_LLAMA:
  7511. {
  7512. result = llm.build_llama();
  7513. } break;
  7514. case LLM_ARCH_BAICHUAN:
  7515. {
  7516. result = llm.build_baichuan();
  7517. } break;
  7518. case LLM_ARCH_FALCON:
  7519. {
  7520. result = llm.build_falcon();
  7521. } break;
  7522. case LLM_ARCH_GROK:
  7523. {
  7524. result = llm.build_grok();
  7525. } break;
  7526. case LLM_ARCH_STARCODER:
  7527. {
  7528. result = llm.build_starcoder();
  7529. } break;
  7530. case LLM_ARCH_PERSIMMON:
  7531. {
  7532. result = llm.build_persimmon();
  7533. } break;
  7534. case LLM_ARCH_REFACT:
  7535. {
  7536. result = llm.build_refact();
  7537. } break;
  7538. case LLM_ARCH_BERT:
  7539. case LLM_ARCH_NOMIC_BERT:
  7540. {
  7541. result = llm.build_bert();
  7542. } break;
  7543. case LLM_ARCH_BLOOM:
  7544. {
  7545. result = llm.build_bloom();
  7546. } break;
  7547. case LLM_ARCH_MPT:
  7548. {
  7549. result = llm.build_mpt();
  7550. } break;
  7551. case LLM_ARCH_STABLELM:
  7552. {
  7553. result = llm.build_stablelm();
  7554. } break;
  7555. case LLM_ARCH_QWEN:
  7556. {
  7557. result = llm.build_qwen();
  7558. } break;
  7559. case LLM_ARCH_QWEN2:
  7560. {
  7561. result = llm.build_qwen2();
  7562. } break;
  7563. case LLM_ARCH_PHI2:
  7564. {
  7565. result = llm.build_phi2();
  7566. } break;
  7567. case LLM_ARCH_PLAMO:
  7568. {
  7569. result = llm.build_plamo();
  7570. } break;
  7571. case LLM_ARCH_GPT2:
  7572. {
  7573. result = llm.build_gpt2();
  7574. } break;
  7575. case LLM_ARCH_CODESHELL:
  7576. {
  7577. result = llm.build_codeshell();
  7578. } break;
  7579. case LLM_ARCH_ORION:
  7580. {
  7581. result = llm.build_orion();
  7582. } break;
  7583. case LLM_ARCH_INTERNLM2:
  7584. {
  7585. result = llm.build_internlm2();
  7586. } break;
  7587. case LLM_ARCH_MINICPM:
  7588. {
  7589. result = llm.build_minicpm();
  7590. } break;
  7591. case LLM_ARCH_GEMMA:
  7592. {
  7593. result = llm.build_gemma();
  7594. } break;
  7595. case LLM_ARCH_STARCODER2:
  7596. {
  7597. result = llm.build_starcoder2();
  7598. } break;
  7599. case LLM_ARCH_MAMBA:
  7600. {
  7601. result = llm.build_mamba();
  7602. } break;
  7603. case LLM_ARCH_COMMAND_R:
  7604. {
  7605. result = llm.build_command_r();
  7606. } break;
  7607. default:
  7608. GGML_ASSERT(false);
  7609. }
  7610. llm.free();
  7611. return result;
  7612. }
  7613. static void llama_set_k_shift(llama_context & lctx) {
  7614. const int64_t kv_size = lctx.kv_self.size;
  7615. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7616. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7617. for (int i = 0; i < kv_size; ++i) {
  7618. data[i] = lctx.kv_self.cells[i].delta;
  7619. }
  7620. }
  7621. static void llama_set_s_copy(llama_context & lctx) {
  7622. const int64_t kv_size = lctx.kv_self.size;
  7623. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7624. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7625. for (int i = 0; i < kv_size; ++i) {
  7626. data[i] = lctx.kv_self.cells[i].src;
  7627. }
  7628. }
  7629. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7630. //
  7631. // set input data
  7632. //
  7633. const auto & hparams = lctx.model.hparams;
  7634. const auto & cparams = lctx.cparams;
  7635. const auto & kv_self = lctx.kv_self;
  7636. if (batch.token) {
  7637. const int64_t n_tokens = batch.n_tokens;
  7638. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7639. }
  7640. if (batch.embd) {
  7641. const int64_t n_embd = hparams.n_embd;
  7642. const int64_t n_tokens = batch.n_tokens;
  7643. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7644. }
  7645. if (batch.pos && lctx.inp_pos) {
  7646. const int64_t n_tokens = batch.n_tokens;
  7647. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7648. }
  7649. GGML_ASSERT(
  7650. (hparams.causal_attn || !cparams.causal_attn) &&
  7651. "non-causal attention with generative models is not supported"
  7652. );
  7653. if (lctx.inp_KQ_mask) {
  7654. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7655. if (cparams.causal_attn) {
  7656. const int64_t n_kv = kv_self.n;
  7657. const int64_t n_tokens = batch.n_tokens;
  7658. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7659. float * data = (float *) lctx.inp_KQ_mask->data;
  7660. // For causal attention, use only the previous KV cells
  7661. // of the correct sequence for each token of the batch.
  7662. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7663. for (int h = 0; h < 1; ++h) {
  7664. for (int j = 0; j < n_tokens; ++j) {
  7665. const llama_pos pos = batch.pos[j];
  7666. const llama_seq_id seq_id = batch.seq_id[j][0];
  7667. for (int i = 0; i < n_kv; ++i) {
  7668. float f;
  7669. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7670. f = -INFINITY;
  7671. } else {
  7672. f = 0.0f;
  7673. }
  7674. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  7675. }
  7676. }
  7677. }
  7678. } else {
  7679. // when using kv cache, the mask needs to match the kv cache size
  7680. const int64_t n_tokens = batch.n_tokens;
  7681. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  7682. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7683. float * data = (float *) lctx.inp_KQ_mask->data;
  7684. for (int h = 0; h < 1; ++h) {
  7685. for (int j = 0; j < n_tokens; ++j) {
  7686. const llama_seq_id seq_id = batch.seq_id[j][0];
  7687. for (int i = 0; i < n_tokens; ++i) {
  7688. float f = -INFINITY;
  7689. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  7690. if (batch.seq_id[i][s] == seq_id) {
  7691. f = 0.0f;
  7692. break;
  7693. }
  7694. }
  7695. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  7696. }
  7697. for (int i = n_tokens; i < n_stride; ++i) {
  7698. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  7699. }
  7700. }
  7701. }
  7702. }
  7703. }
  7704. if (hparams.need_kq_pos) {
  7705. const int64_t n_kv = kv_self.n;
  7706. GGML_ASSERT(lctx.inp_KQ_pos);
  7707. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  7708. float * data = (float *) lctx.inp_KQ_pos->data;
  7709. for (int i = 0; i < n_kv; ++i) {
  7710. data[i] = float(lctx.kv_self.cells[i].pos);
  7711. }
  7712. }
  7713. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  7714. const int64_t n_tokens = batch.n_tokens;
  7715. GGML_ASSERT(lctx.inp_mean);
  7716. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  7717. float * data = (float *) lctx.inp_mean->data;
  7718. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  7719. std::vector<uint64_t> sum(n_tokens, 0);
  7720. for (int i = 0; i < n_tokens; ++i) {
  7721. const llama_seq_id seq_id = batch.seq_id[i][0];
  7722. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  7723. sum[seq_id] += 1;
  7724. }
  7725. std::vector<float> div(n_tokens, 0.0f);
  7726. for (int i = 0; i < n_tokens; ++i) {
  7727. const uint64_t s = sum[i];
  7728. if (s > 0) {
  7729. div[i] = 1.0f/float(s);
  7730. }
  7731. }
  7732. for (int i = 0; i < n_tokens; ++i) {
  7733. const llama_seq_id seq_id = batch.seq_id[i][0];
  7734. data[seq_id*n_tokens + i] = div[seq_id];
  7735. }
  7736. }
  7737. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  7738. const int64_t n_tokens = batch.n_tokens;
  7739. GGML_ASSERT(lctx.inp_cls);
  7740. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  7741. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  7742. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  7743. for (int i = 0; i < n_tokens; ++i) {
  7744. const llama_seq_id seq_id = batch.seq_id[i][0];
  7745. const llama_pos pos = batch.pos[i];
  7746. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  7747. if (pos == 0) {
  7748. data[seq_id] = i;
  7749. }
  7750. }
  7751. }
  7752. if (kv_self.recurrent) {
  7753. const int64_t n_kv = kv_self.n;
  7754. if (lctx.inp_s_mask) {
  7755. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  7756. float * data = (float *) lctx.inp_s_mask->data;
  7757. // states which are not affected by the current batch are left untouched
  7758. for (int i = 0; i < n_kv; ++i) {
  7759. llama_seq_id seq_id = i + lctx.kv_self.head;
  7760. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  7761. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  7762. data[i] = (float) has_self_seq;
  7763. // ensure current sequences will be kept
  7764. if (!has_self_seq && kv_cell.pos >= 0) {
  7765. kv_cell.seq_id.insert(seq_id);
  7766. }
  7767. }
  7768. }
  7769. // For Mamba (and other recurrent architectures),
  7770. // update the correct state(s)/sequence(s) for each token of the batch.
  7771. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  7772. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  7773. if (lctx.inp_s_seq) {
  7774. const int64_t n_tokens = batch.n_tokens;
  7775. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  7776. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  7777. for (int j = 0; j < n_tokens; ++j) {
  7778. const int32_t n_seq = batch.n_seq_id[j];
  7779. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  7780. for (int i = 0; i < n_kv; ++i) {
  7781. if (i < n_seq) {
  7782. // for this type of model, the head is the minimum seq_id of the batch
  7783. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  7784. } else {
  7785. data[j*n_kv + i] = -1;
  7786. }
  7787. }
  7788. }
  7789. }
  7790. }
  7791. }
  7792. static void llama_graph_compute(
  7793. llama_context & lctx,
  7794. ggml_cgraph * gf,
  7795. int n_threads) {
  7796. #ifdef GGML_USE_MPI
  7797. const int64_t n_layer = lctx.model.hparams.n_layer;
  7798. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  7799. #endif
  7800. #ifdef GGML_USE_METAL
  7801. if (ggml_backend_is_metal(lctx.backend_metal)) {
  7802. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  7803. }
  7804. #endif
  7805. if (lctx.backend_cpu != nullptr) {
  7806. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  7807. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  7808. }
  7809. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  7810. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  7811. #ifdef GGML_USE_MPI
  7812. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  7813. #endif
  7814. }
  7815. // decode a batch of tokens by evaluating the transformer
  7816. //
  7817. // - lctx: llama context
  7818. // - batch: batch to evaluate
  7819. //
  7820. // return 0 on success
  7821. // return positive int on warning
  7822. // return negative int on error
  7823. //
  7824. static int llama_decode_internal(
  7825. llama_context & lctx,
  7826. llama_batch batch_all) { // TODO: rename back to batch
  7827. const uint32_t n_tokens_all = batch_all.n_tokens;
  7828. if (n_tokens_all == 0) {
  7829. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  7830. return -1;
  7831. }
  7832. const auto & model = lctx.model;
  7833. const auto & hparams = model.hparams;
  7834. const auto & cparams = lctx.cparams;
  7835. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  7836. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  7837. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  7838. if (lctx.t_compute_start_us == 0) {
  7839. lctx.t_compute_start_us = ggml_time_us();
  7840. }
  7841. lctx.n_queued_tokens += n_tokens_all;
  7842. #ifdef GGML_USE_MPI
  7843. // TODO: needs fix after #3228
  7844. GGML_ASSERT(false && "not implemented");
  7845. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  7846. #endif
  7847. auto & kv_self = lctx.kv_self;
  7848. const int64_t n_embd = hparams.n_embd;
  7849. const int64_t n_vocab = hparams.n_vocab;
  7850. auto * logits_out = lctx.logits;
  7851. #ifndef NDEBUG
  7852. auto & logits_valid = lctx.logits_valid;
  7853. logits_valid.clear();
  7854. logits_valid.resize(n_tokens_all);
  7855. memset(logits_out, 0, lctx.logits_size*sizeof(float));
  7856. #endif
  7857. const auto n_ubatch = cparams.n_ubatch;
  7858. std::vector<llama_pos> pos;
  7859. std::vector<int32_t> n_seq_id;
  7860. std::vector<llama_seq_id *> seq_id_arr;
  7861. std::vector<std::vector<llama_seq_id>> seq_id;
  7862. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  7863. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  7864. llama_batch u_batch = {
  7865. /* .n_tokens = */ (int32_t) n_tokens,
  7866. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  7867. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  7868. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  7869. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  7870. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  7871. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  7872. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  7873. /* .all_pos_1 = */ batch_all.all_pos_1,
  7874. /* .all_seq_id = */ batch_all.all_seq_id,
  7875. };
  7876. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  7877. GGML_ASSERT(n_threads > 0);
  7878. // helpers for smoother batch API transition
  7879. // after deprecating the llama_eval calls, these will be removed
  7880. if (u_batch.pos == nullptr) {
  7881. pos.resize(n_tokens);
  7882. for (uint32_t i = 0; i < n_tokens; i++) {
  7883. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  7884. }
  7885. u_batch.pos = pos.data();
  7886. }
  7887. if (u_batch.seq_id == nullptr) {
  7888. n_seq_id.resize(n_tokens);
  7889. seq_id.resize(n_tokens);
  7890. seq_id_arr.resize(n_tokens);
  7891. for (uint32_t i = 0; i < n_tokens; i++) {
  7892. n_seq_id[i] = 1;
  7893. seq_id[i].resize(1);
  7894. seq_id[i][0] = u_batch.all_seq_id;
  7895. seq_id_arr[i] = seq_id[i].data();
  7896. }
  7897. u_batch.n_seq_id = n_seq_id.data();
  7898. u_batch.seq_id = seq_id_arr.data();
  7899. }
  7900. // non-causal masks do not use the KV cache
  7901. if (hparams.causal_attn) {
  7902. llama_kv_cache_update(&lctx);
  7903. // if we have enough unused cells before the current head ->
  7904. // better to start searching from the beginning of the cache, hoping to fill it
  7905. if (kv_self.head > kv_self.used + 2*n_tokens) {
  7906. kv_self.head = 0;
  7907. }
  7908. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  7909. return 1;
  7910. }
  7911. if (!kv_self.recurrent) {
  7912. // a heuristic, to avoid attending the full cache if it is not yet utilized
  7913. // after enough generations, the benefit from this heuristic disappears
  7914. // if we start defragmenting the cache, the benefit from this will be more important
  7915. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  7916. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  7917. }
  7918. }
  7919. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  7920. ggml_backend_sched_reset(lctx.sched);
  7921. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  7922. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  7923. // the output is always the last tensor in the graph
  7924. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  7925. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  7926. if (!hparams.causal_attn) {
  7927. res = nullptr; // do not extract logits for embedding models such as BERT
  7928. // token or sequence embeddings
  7929. embd = gf->nodes[gf->n_nodes - 1];
  7930. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  7931. } else {
  7932. if (strcmp(res->name, "result_output") == 0) {
  7933. // the token embeddings could be the second to last tensor, or the third to last tensor
  7934. if (strcmp(embd->name, "result_norm") != 0) {
  7935. embd = gf->nodes[gf->n_nodes - 3];
  7936. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  7937. }
  7938. } else {
  7939. GGML_ASSERT(false && "missing result_output tensor");
  7940. }
  7941. }
  7942. // LLAMA_LOG_INFO("graph build time: %.3f ms (%d nodes, %d leafs)\n", (ggml_time_us() - t_start_us)/1000.0, gf->n_nodes, gf->n_leafs);
  7943. // for big prompts, if BLAS is enabled, it is better to use only one thread
  7944. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  7945. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  7946. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  7947. // with the BLAS calls. need a better solution
  7948. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  7949. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  7950. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  7951. n_threads = std::min(4, n_threads);
  7952. }
  7953. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7954. llama_set_inputs(lctx, u_batch);
  7955. llama_graph_compute(lctx, gf, n_threads);
  7956. // update the kv ring buffer
  7957. {
  7958. kv_self.head += n_tokens;
  7959. // Ensure kv cache head points to a valid index.
  7960. if (kv_self.head >= kv_self.size) {
  7961. kv_self.head = 0;
  7962. }
  7963. }
  7964. #ifdef GGML_PERF
  7965. // print timing information per ggml operation (for debugging purposes)
  7966. // requires GGML_PERF to be defined
  7967. ggml_graph_print(gf);
  7968. #endif
  7969. // plot the computation graph in dot format (for debugging purposes)
  7970. //if (n_past%100 == 0) {
  7971. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  7972. //}
  7973. // extract logits
  7974. // TODO: do not compute and extract logits if only embeddings are needed
  7975. // update the graphs to skip "result_output" if logits are not needed
  7976. if (res) {
  7977. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  7978. GGML_ASSERT(backend_res != nullptr);
  7979. if (u_batch.logits) {
  7980. int32_t i_first = -1;
  7981. for (uint32_t i = 0; i < n_tokens; i++) {
  7982. if (u_batch.logits[i] && i_first == -1) {
  7983. i_first = (int32_t) i;
  7984. }
  7985. if (u_batch.logits[i] == 0 || i == n_tokens - 1) {
  7986. if (i_first != -1) {
  7987. int i_last = u_batch.logits[i] == 0 ? i : i + 1;
  7988. // extract logits for the range [i_first, i_last)
  7989. // group the requests to minimize the number of calls to the backend
  7990. ggml_backend_tensor_get_async(backend_res, res,
  7991. logits_out + n_vocab*(cur_token + i_first),
  7992. i_first*n_vocab*sizeof(float),
  7993. (i_last - i_first)*n_vocab*sizeof(float));
  7994. i_first = -1;
  7995. }
  7996. }
  7997. #ifndef NDEBUG
  7998. logits_valid[cur_token + i] = u_batch.logits[i] != 0;;
  7999. #endif
  8000. }
  8001. } else if (lctx.logits_all) {
  8002. ggml_backend_tensor_get_async(backend_res, res, logits_out + n_vocab*cur_token, 0, n_vocab*n_tokens*sizeof(float));
  8003. #ifndef NDEBUG
  8004. std::fill(logits_valid.begin() + cur_token, logits_valid.begin() + cur_token + n_tokens, true);
  8005. #endif
  8006. } else {
  8007. if (cur_token + n_tokens >= n_tokens_all) {
  8008. ggml_backend_tensor_get_async(backend_res, res, logits_out, n_vocab*(n_tokens - 1)*sizeof(float), n_vocab*sizeof(float));
  8009. #ifndef NDEBUG
  8010. logits_valid[0] = true;
  8011. #endif
  8012. }
  8013. }
  8014. }
  8015. // extract embeddings
  8016. if (cparams.embeddings && embd) {
  8017. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8018. GGML_ASSERT(backend_embd != nullptr);
  8019. switch (cparams.pooling_type) {
  8020. case LLAMA_POOLING_TYPE_NONE:
  8021. {
  8022. // extract token embeddings
  8023. auto & embd_out = lctx.embd;
  8024. if (u_batch.logits) {
  8025. //embd_out.resize(n_embd * n_tokens);
  8026. for (uint32_t i = 0; i < n_tokens; i++) {
  8027. if (u_batch.logits[i] == 0) {
  8028. continue;
  8029. }
  8030. ggml_backend_tensor_get_async(backend_embd, embd, embd_out + n_embd*(i + cur_token), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  8031. }
  8032. }
  8033. } break;
  8034. case LLAMA_POOLING_TYPE_CLS:
  8035. case LLAMA_POOLING_TYPE_MEAN:
  8036. {
  8037. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8038. // extract sequence embeddings
  8039. auto & embd_seq_out = lctx.embd_seq;
  8040. embd_seq_out.clear();
  8041. for (uint32_t i = 0; i < n_tokens; i++) {
  8042. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8043. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8044. continue;
  8045. }
  8046. embd_seq_out[seq_id].resize(n_embd);
  8047. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8048. }
  8049. } break;
  8050. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8051. {
  8052. GGML_ASSERT(false && "unknown pooling type");
  8053. } break;
  8054. }
  8055. }
  8056. }
  8057. // wait for the computation to finish (automatically done when obtaining the model output)
  8058. //llama_synchronize(&lctx);
  8059. // decide if we need to defrag the kv cache
  8060. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8061. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8062. // queue defragmentation for next llama_kv_cache_update
  8063. if (fragmentation > cparams.defrag_thold) {
  8064. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8065. llama_kv_cache_defrag(kv_self);
  8066. }
  8067. }
  8068. return 0;
  8069. }
  8070. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8071. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8072. auto & kv_self = lctx.kv_self;
  8073. const auto & hparams = lctx.model.hparams;
  8074. const uint32_t n_layer = hparams.n_layer;
  8075. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8076. const uint32_t n_used = kv_self.used;
  8077. assert(n_used <= n_kv);
  8078. //const int64_t t_start = ggml_time_us();
  8079. // number of cells moved
  8080. uint32_t n_moves = 0;
  8081. // each move requires 6*n_layer tensors (see build_defrag)
  8082. // - source view, destination view, copy operation
  8083. // - x2 for keys and values
  8084. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8085. // determine which KV cells to move where
  8086. //
  8087. // cell i moves to ids[i]
  8088. //
  8089. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8090. //
  8091. std::vector<uint32_t> ids(n_kv, n_kv);
  8092. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8093. const auto & cell0 = kv_self.cells[i0];
  8094. if (!cell0.is_empty()) {
  8095. ids[i0] = i0;
  8096. continue;
  8097. }
  8098. // found a hole - fill it with data from the end of the cache
  8099. uint32_t nh = 1;
  8100. // determine the size of the hole
  8101. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8102. nh++;
  8103. }
  8104. uint32_t nf = 0;
  8105. uint32_t is = n_kv - 1;
  8106. // starting from the end, find nh non-empty cells
  8107. for (; is > i0; --is) {
  8108. const auto & cell1 = kv_self.cells[is];
  8109. if (cell1.is_empty() || ids[is] != n_kv) {
  8110. continue;
  8111. }
  8112. // non-empty cell which is not yet moved
  8113. nf++;
  8114. if (nf == nh) {
  8115. break;
  8116. }
  8117. }
  8118. // this can only happen if `n_used` is not accurate, which would be a bug
  8119. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8120. nf = 0;
  8121. uint32_t i1 = is;
  8122. // are we moving a continuous block of memory?
  8123. bool cont = false;
  8124. // should we stop searching for the next move?
  8125. bool stop = false;
  8126. // go back and move the nf cells to the hole
  8127. for (; i1 < n_kv; ++i1) {
  8128. auto & cell1 = kv_self.cells[i1];
  8129. if (cell1.is_empty() || ids[i1] != n_kv) {
  8130. if (n_moves == max_moves) {
  8131. stop = true;
  8132. break;
  8133. }
  8134. cont = false;
  8135. continue;
  8136. }
  8137. // this cell goes to (i0 + nf)
  8138. ids[i1] = i0 + nf;
  8139. // move the cell meta data
  8140. kv_self.cells[i0 + nf] = cell1;
  8141. // clear the old cell and move the head there
  8142. cell1 = llama_kv_cell();
  8143. kv_self.head = n_used;
  8144. if (!cont) {
  8145. n_moves++;
  8146. cont = true;
  8147. }
  8148. nf++;
  8149. if (nf == nh) {
  8150. break;
  8151. }
  8152. }
  8153. if (stop || n_moves == max_moves) {
  8154. break;
  8155. }
  8156. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8157. i0 += nh - 1;
  8158. }
  8159. if (n_moves == 0) {
  8160. return;
  8161. }
  8162. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8163. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8164. #if 0
  8165. // CPU defrag
  8166. //
  8167. // TODO: optimizations are possible:
  8168. // - multiple threads
  8169. // - avoid copying to the host memory when already there
  8170. //
  8171. // likely not worth the effort, as we have ggml_graph based defrag
  8172. //
  8173. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8174. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8175. const uint32_t kv_size = kv_self.size;
  8176. std::vector<uint8_t> buf_k;
  8177. std::vector<uint8_t> buf_v;
  8178. for (uint32_t il = 0; il < n_layer; ++il) {
  8179. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8180. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8181. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8182. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8183. buf_k.resize(k_size);
  8184. buf_v.resize(v_size);
  8185. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8186. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8187. // batch move [i, i+nm) to [id, id+nm)
  8188. // note: cells can move only to a lower index
  8189. for (uint32_t i = 0; i < n_kv; ++i) {
  8190. const uint32_t id = ids[i];
  8191. if (i == id || id == n_kv) {
  8192. continue;
  8193. }
  8194. uint32_t nm = 1;
  8195. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8196. nm++;
  8197. }
  8198. // move keys
  8199. {
  8200. const int64_t os = i*k_size_row;
  8201. const int64_t od = id*k_size_row;
  8202. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8203. }
  8204. // move values (note: they are transposed)
  8205. {
  8206. const int64_t os = i;
  8207. const int64_t od = id;
  8208. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8209. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  8210. }
  8211. }
  8212. i += nm - 1;
  8213. }
  8214. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8215. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8216. }
  8217. #else
  8218. // ggml_graph defrag
  8219. ggml_backend_sched_reset(lctx.sched);
  8220. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8221. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8222. #endif
  8223. //const int64_t t_end = ggml_time_us();
  8224. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8225. }
  8226. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8227. bool need_reserve = false;
  8228. // apply K-shift if needed
  8229. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8230. {
  8231. ggml_backend_sched_reset(lctx.sched);
  8232. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8233. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8234. llama_set_k_shift(lctx);
  8235. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8236. need_reserve = true;
  8237. }
  8238. {
  8239. auto & kv_self = lctx.kv_self;
  8240. kv_self.has_shift = false;
  8241. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8242. kv_self.cells[i].delta = 0;
  8243. }
  8244. }
  8245. }
  8246. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8247. {
  8248. ggml_backend_sched_reset(lctx.sched);
  8249. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8250. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8251. llama_set_s_copy(lctx);
  8252. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8253. need_reserve = true;
  8254. }
  8255. {
  8256. auto & kv_self = lctx.kv_self;
  8257. kv_self.do_copy = false;
  8258. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8259. kv_self.cells[i].src = i;
  8260. }
  8261. }
  8262. }
  8263. // defragment the KV cache if needed
  8264. if (lctx.kv_self.do_defrag) {
  8265. llama_kv_cache_defrag_internal(lctx);
  8266. need_reserve = true;
  8267. lctx.kv_self.do_defrag = false;
  8268. }
  8269. // reserve a worst case graph again
  8270. if (need_reserve) {
  8271. // TODO: extract to a function
  8272. // build worst-case graph
  8273. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8274. int n_past = lctx.cparams.n_ctx - n_tokens;
  8275. llama_token token = llama_token_bos(&lctx.model); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  8276. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8277. // initialize scheduler with the worst-case graph
  8278. ggml_backend_sched_reset(lctx.sched);
  8279. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8280. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8281. }
  8282. }
  8283. }
  8284. //
  8285. // tokenizer
  8286. //
  8287. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8288. return vocab.type;
  8289. }
  8290. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8291. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8292. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8293. }
  8294. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8295. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8296. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8297. }
  8298. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8299. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8300. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8301. }
  8302. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8303. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8304. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8305. }
  8306. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8307. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8308. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8309. }
  8310. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8311. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8312. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8313. const auto& token_data = vocab.id_to_token.at(id);
  8314. switch (llama_vocab_get_type(vocab)) {
  8315. case LLAMA_VOCAB_TYPE_SPM: {
  8316. auto buf = token_data.text.substr(3, 2);
  8317. return strtol(buf.c_str(), NULL, 16);
  8318. }
  8319. case LLAMA_VOCAB_TYPE_BPE: {
  8320. GGML_ASSERT(false);
  8321. return unicode_utf8_to_byte(token_data.text);
  8322. }
  8323. case LLAMA_VOCAB_TYPE_WPM: {
  8324. GGML_ASSERT(false);
  8325. }
  8326. default:
  8327. GGML_ASSERT(false);
  8328. }
  8329. }
  8330. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8331. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8332. static const char * hex = "0123456789ABCDEF";
  8333. switch (llama_vocab_get_type(vocab)) {
  8334. case LLAMA_VOCAB_TYPE_SPM: {
  8335. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8336. auto token = vocab.token_to_id.find(buf);
  8337. if (token != vocab.token_to_id.end()) {
  8338. return (*token).second;
  8339. }
  8340. // Try to fall back to just the byte as a string
  8341. const char buf2[2] = { (char)ch, 0 };
  8342. return vocab.token_to_id.at(buf2);
  8343. }
  8344. case LLAMA_VOCAB_TYPE_WPM:
  8345. case LLAMA_VOCAB_TYPE_BPE: {
  8346. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8347. }
  8348. default:
  8349. GGML_ASSERT(false);
  8350. }
  8351. }
  8352. static void llama_escape_whitespace(std::string & text) {
  8353. replace_all(text, " ", "\xe2\x96\x81");
  8354. }
  8355. static void llama_unescape_whitespace(std::string & word) {
  8356. replace_all(word, "\xe2\x96\x81", " ");
  8357. }
  8358. struct llm_symbol {
  8359. using index = int;
  8360. index prev;
  8361. index next;
  8362. const char * text;
  8363. size_t n;
  8364. };
  8365. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8366. // SPM tokenizer
  8367. // original implementation:
  8368. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8369. struct llm_bigram_spm {
  8370. struct comparator {
  8371. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8372. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8373. }
  8374. };
  8375. using queue_storage = std::vector<llm_bigram_spm>;
  8376. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8377. llm_symbol::index left;
  8378. llm_symbol::index right;
  8379. float score;
  8380. size_t size;
  8381. };
  8382. struct llm_tokenizer_spm {
  8383. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8384. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8385. // split string into utf8 chars
  8386. int index = 0;
  8387. size_t offs = 0;
  8388. while (offs < text.size()) {
  8389. llm_symbol sym;
  8390. size_t len = utf8_len(text[offs]);
  8391. sym.text = text.c_str() + offs;
  8392. sym.n = std::min(len, text.size() - offs);
  8393. offs += sym.n;
  8394. sym.prev = index - 1;
  8395. sym.next = offs == text.size() ? -1 : index + 1;
  8396. index++;
  8397. symbols.emplace_back(sym);
  8398. }
  8399. // seed the work queue with all possible 2-character tokens.
  8400. for (size_t i = 1; i < symbols.size(); ++i) {
  8401. try_add_bigram(i - 1, i);
  8402. }
  8403. // keep substituting the highest frequency pairs for as long as we can.
  8404. while (!work_queue.empty()) {
  8405. auto bigram = work_queue.top();
  8406. work_queue.pop();
  8407. auto & left_sym = symbols[bigram.left];
  8408. auto & right_sym = symbols[bigram.right];
  8409. // if one of the symbols already got merged, skip it.
  8410. if (left_sym.n == 0 || right_sym.n == 0 ||
  8411. left_sym.n + right_sym.n != bigram.size) {
  8412. continue;
  8413. }
  8414. // merge the right sym into the left one
  8415. left_sym.n += right_sym.n;
  8416. right_sym.n = 0;
  8417. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8418. // remove the right sym from the chain
  8419. left_sym.next = right_sym.next;
  8420. if (right_sym.next >= 0) {
  8421. symbols[right_sym.next].prev = bigram.left;
  8422. }
  8423. // find more substitutions
  8424. try_add_bigram(left_sym.prev, bigram.left);
  8425. try_add_bigram(bigram.left, left_sym.next);
  8426. }
  8427. for (int i = 0; i != -1; i = symbols[i].next) {
  8428. auto & symbol = symbols[i];
  8429. resegment(symbol, output);
  8430. }
  8431. }
  8432. private:
  8433. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8434. auto text = std::string(symbol.text, symbol.n);
  8435. auto token = vocab.token_to_id.find(text);
  8436. // Do we need to support is_unused?
  8437. if (token != vocab.token_to_id.end()) {
  8438. output.push_back((*token).second);
  8439. return;
  8440. }
  8441. const auto p = rev_merge.find(text);
  8442. if (p == rev_merge.end()) {
  8443. // output any symbols that did not form tokens as bytes.
  8444. output.reserve(output.size() + symbol.n);
  8445. for (int j = 0; j < (int)symbol.n; ++j) {
  8446. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8447. output.push_back(token_id);
  8448. }
  8449. return;
  8450. }
  8451. resegment(symbols[p->second.first], output);
  8452. resegment(symbols[p->second.second], output);
  8453. }
  8454. void try_add_bigram(int left, int right) {
  8455. if (left == -1 || right == -1) {
  8456. return;
  8457. }
  8458. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8459. auto token = vocab.token_to_id.find(text);
  8460. if (token == vocab.token_to_id.end()) {
  8461. return;
  8462. }
  8463. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8464. return;
  8465. }
  8466. const auto & tok_data = vocab.id_to_token[(*token).second];
  8467. llm_bigram_spm bigram;
  8468. bigram.left = left;
  8469. bigram.right = right;
  8470. bigram.score = tok_data.score;
  8471. bigram.size = text.size();
  8472. work_queue.push(bigram);
  8473. // Do we need to support is_unused?
  8474. rev_merge[text] = std::make_pair(left, right);
  8475. }
  8476. const llama_vocab & vocab;
  8477. std::vector<llm_symbol> symbols;
  8478. llm_bigram_spm::queue work_queue;
  8479. std::map<std::string, std::pair<int, int>> rev_merge;
  8480. };
  8481. // BPE tokenizer
  8482. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8483. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8484. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8485. struct llm_bigram_bpe {
  8486. struct comparator {
  8487. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8488. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8489. }
  8490. };
  8491. using queue_storage = std::vector<llm_bigram_bpe>;
  8492. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8493. llm_symbol::index left;
  8494. llm_symbol::index right;
  8495. std::string text;
  8496. int rank;
  8497. size_t size;
  8498. };
  8499. struct llm_tokenizer_bpe {
  8500. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8501. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8502. int final_prev_index = -1;
  8503. auto word_collection = bpe_gpt2_preprocess(text);
  8504. symbols_final.clear();
  8505. for (auto & word : word_collection) {
  8506. work_queue = llm_bigram_bpe::queue();
  8507. symbols.clear();
  8508. int index = 0;
  8509. size_t offset = 0;
  8510. while (offset < word.size()) {
  8511. llm_symbol sym;
  8512. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8513. sym.text = word.c_str() + offset;
  8514. sym.n = char_len;
  8515. offset += sym.n;
  8516. sym.prev = index - 1;
  8517. sym.next = offset == word.size() ? -1 : index + 1;
  8518. index++;
  8519. symbols.emplace_back(sym);
  8520. }
  8521. for (size_t i = 1; i < symbols.size(); ++i) {
  8522. add_new_bigram(i - 1, i);
  8523. }
  8524. // build token(s)
  8525. while (!work_queue.empty()) {
  8526. auto bigram = work_queue.top();
  8527. work_queue.pop();
  8528. auto & left_symbol = symbols[bigram.left];
  8529. auto & right_symbol = symbols[bigram.right];
  8530. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8531. continue;
  8532. }
  8533. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8534. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8535. if (left_token + right_token != bigram.text) {
  8536. continue; // Skip this bigram if it's outdated
  8537. }
  8538. // merge the right sym into the left one
  8539. left_symbol.n += right_symbol.n;
  8540. right_symbol.n = 0;
  8541. // remove the right sym from the chain
  8542. left_symbol.next = right_symbol.next;
  8543. if (right_symbol.next >= 0) {
  8544. symbols[right_symbol.next].prev = bigram.left;
  8545. }
  8546. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8547. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8548. }
  8549. // add the fnished tokens to the final list keeping correct order for next and prev
  8550. for (auto & sym : symbols) {
  8551. if (sym.n > 0) {
  8552. sym.prev = final_prev_index;
  8553. sym.next = -1;
  8554. if (final_prev_index != -1) {
  8555. symbols_final[final_prev_index].next = symbols_final.size();
  8556. }
  8557. symbols_final.emplace_back(sym);
  8558. final_prev_index = symbols_final.size() - 1;
  8559. }
  8560. }
  8561. }
  8562. symbols = symbols_final;
  8563. if (!symbols.empty()) {
  8564. for (int i = 0; i != -1; i = symbols[i].next) {
  8565. auto & symbol = symbols[i];
  8566. if (symbol.n == 0) {
  8567. continue;
  8568. }
  8569. const std::string str = std::string(symbol.text, symbol.n);
  8570. const auto token = vocab.token_to_id.find(str);
  8571. if (token == vocab.token_to_id.end()) {
  8572. for (auto j = str.begin(); j != str.end(); ++j) {
  8573. std::string byte_str(1, *j);
  8574. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8575. if (token_multibyte == vocab.token_to_id.end()) {
  8576. throw std::runtime_error("ERROR: byte not found in vocab");
  8577. }
  8578. output.push_back((*token_multibyte).second);
  8579. }
  8580. } else {
  8581. output.push_back((*token).second);
  8582. }
  8583. }
  8584. }
  8585. }
  8586. private:
  8587. void add_new_bigram(int left, int right) {
  8588. if (left == -1 || right == -1) {
  8589. return;
  8590. }
  8591. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8592. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8593. int rank_found = -1;
  8594. rank_found = vocab.find_bpe_rank(left_token, right_token);
  8595. if (rank_found < 0) {
  8596. return;
  8597. }
  8598. llm_bigram_bpe bigram;
  8599. bigram.left = left;
  8600. bigram.right = right;
  8601. bigram.text = left_token + right_token;
  8602. bigram.size = left_token.size() + right_token.size();
  8603. bigram.rank = rank_found;
  8604. work_queue.push(bigram);
  8605. }
  8606. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  8607. std::vector<std::string> bpe_words;
  8608. std::vector<std::string> bpe_encoded_words;
  8609. std::string token = "";
  8610. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  8611. bool collecting_numeric = false;
  8612. bool collecting_letter = false;
  8613. bool collecting_special = false;
  8614. bool collecting_whitespace_lookahead = false;
  8615. bool collecting = false;
  8616. std::vector<std::string> text_utf;
  8617. text_utf.reserve(text.size());
  8618. bpe_words.reserve(text.size());
  8619. bpe_encoded_words.reserve(text.size());
  8620. const auto cpts = unicode_cpts_from_utf8(text);
  8621. for (size_t i = 0; i < cpts.size(); ++i)
  8622. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  8623. for (int i = 0; i < (int)text_utf.size(); i++) {
  8624. const std::string & utf_char = text_utf[i];
  8625. bool split_condition = false;
  8626. int bytes_remain = text_utf.size() - i;
  8627. // forward backward lookups
  8628. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  8629. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  8630. // handling contractions
  8631. if (!split_condition && bytes_remain >= 2) {
  8632. // 's|'t|'m|'d
  8633. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  8634. split_condition = true;
  8635. }
  8636. if (split_condition) {
  8637. if (token.size()) {
  8638. bpe_words.emplace_back(token); // push previous content as token
  8639. }
  8640. token = utf_char + utf_char_next;
  8641. bpe_words.emplace_back(token);
  8642. token = "";
  8643. i++;
  8644. continue;
  8645. }
  8646. }
  8647. if (!split_condition && bytes_remain >= 3) {
  8648. // 're|'ve|'ll
  8649. if (utf_char == "\'" && (
  8650. (utf_char_next == "r" && utf_char_next_next == "e") ||
  8651. (utf_char_next == "v" && utf_char_next_next == "e") ||
  8652. (utf_char_next == "l" && utf_char_next_next == "l"))
  8653. ) {
  8654. split_condition = true;
  8655. }
  8656. if (split_condition) {
  8657. // current token + next token can be defined
  8658. if (token.size()) {
  8659. bpe_words.emplace_back(token); // push previous content as token
  8660. }
  8661. token = utf_char + utf_char_next + utf_char_next_next;
  8662. bpe_words.emplace_back(token); // the contraction
  8663. token = "";
  8664. i += 2;
  8665. continue;
  8666. }
  8667. }
  8668. if (!split_condition && !collecting) {
  8669. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  8670. collecting_letter = true;
  8671. collecting = true;
  8672. }
  8673. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8674. collecting_numeric = true;
  8675. collecting = true;
  8676. }
  8677. else if (
  8678. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  8679. (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && unicode_cpt_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  8680. ) {
  8681. collecting_special = true;
  8682. collecting = true;
  8683. }
  8684. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  8685. collecting_whitespace_lookahead = true;
  8686. collecting = true;
  8687. }
  8688. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  8689. split_condition = true;
  8690. }
  8691. }
  8692. else if (!split_condition && collecting) {
  8693. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  8694. split_condition = true;
  8695. }
  8696. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  8697. split_condition = true;
  8698. }
  8699. else if (collecting_special && (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  8700. split_condition = true;
  8701. }
  8702. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8703. split_condition = true;
  8704. }
  8705. }
  8706. if (utf_char_next == "") {
  8707. split_condition = true; // final
  8708. token += utf_char;
  8709. }
  8710. if (split_condition) {
  8711. if (token.size()) {
  8712. bpe_words.emplace_back(token);
  8713. }
  8714. token = utf_char;
  8715. collecting = false;
  8716. collecting_letter = false;
  8717. collecting_numeric = false;
  8718. collecting_special = false;
  8719. collecting_whitespace_lookahead = false;
  8720. }
  8721. else {
  8722. token += utf_char;
  8723. }
  8724. }
  8725. for (std::string & word : bpe_words) {
  8726. std::string encoded_token = "";
  8727. for (char & c : word) {
  8728. encoded_token += unicode_byte_to_utf8(c);
  8729. }
  8730. bpe_encoded_words.emplace_back(encoded_token);
  8731. }
  8732. return bpe_encoded_words;
  8733. }
  8734. const llama_vocab & vocab;
  8735. std::vector<llm_symbol> symbols;
  8736. std::vector<llm_symbol> symbols_final;
  8737. llm_bigram_bpe::queue work_queue;
  8738. };
  8739. struct llm_tokenizer_wpm {
  8740. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  8741. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8742. auto * token_map = &vocab.token_to_id;
  8743. // normalize and split by whitespace
  8744. std::vector<std::string> words = preprocess(text);
  8745. // bos token prepended already
  8746. // find the longest tokens that form the words
  8747. for (const std::string &word : words) {
  8748. // skip empty words
  8749. if (word.size() == 0) {
  8750. continue;
  8751. }
  8752. // prepend phantom space
  8753. std::string word1 = "\xe2\x96\x81" + word;
  8754. int n = word1.size();
  8755. // we're at the start of a new word
  8756. int i = 0;
  8757. bool match_any = false;
  8758. // move through character position in word
  8759. while (i < n) {
  8760. // loop through possible match length
  8761. bool match = false;
  8762. for (int j = n; j > i; j--) {
  8763. auto it = token_map->find(word1.substr(i, j - i));
  8764. if (it != token_map->end()) {
  8765. output.push_back(it->second);
  8766. match = true;
  8767. match_any = true;
  8768. i = j;
  8769. break;
  8770. }
  8771. }
  8772. // must be an unknown character
  8773. if (!match) {
  8774. i++;
  8775. }
  8776. }
  8777. // we didn't find any matches for this word
  8778. if (!match_any) {
  8779. output.push_back(vocab.special_unk_id);
  8780. }
  8781. }
  8782. // append eos token
  8783. output.push_back(vocab.special_eos_id);
  8784. }
  8785. std::vector<std::string> preprocess(const std::string & text) {
  8786. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  8787. // strip accents, strip control, uniformize whitespace,
  8788. // to lowercase, pad chinese characters, pad punctuation
  8789. std::string new_str = "";
  8790. for (uint32_t code : cpts_nfd) {
  8791. int type = unicode_cpt_type(code);
  8792. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  8793. continue;
  8794. }
  8795. code = to_lower(code);
  8796. if (type == CODEPOINT_TYPE_WHITESPACE) {
  8797. code = ' ';
  8798. }
  8799. std::string s = unicode_cpt_to_utf8(code);
  8800. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  8801. new_str += " ";
  8802. new_str += s;
  8803. new_str += " ";
  8804. } else {
  8805. new_str += s;
  8806. }
  8807. }
  8808. // split by whitespace
  8809. uint64_t l = 0;
  8810. uint64_t r = 0;
  8811. std::vector<std::string> words;
  8812. while (r < new_str.size()) {
  8813. // if is whitespace
  8814. if (isspace(new_str[r])) {
  8815. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  8816. l = r + 1;
  8817. r = l;
  8818. } else {
  8819. r += 1;
  8820. }
  8821. }
  8822. if (r > l) {
  8823. words.push_back(new_str.substr(l, (r - l)));
  8824. }
  8825. return words;
  8826. }
  8827. uint32_t to_lower(uint32_t code) {
  8828. static const std::locale locale("en_US.UTF-8");
  8829. #if defined(_WIN32)
  8830. if (code > 0xFFFF) {
  8831. return code;
  8832. }
  8833. #endif
  8834. return std::tolower(wchar_t(code), locale);
  8835. }
  8836. bool is_ascii_punct(uint32_t code) {
  8837. return code < 256 && ispunct(code);
  8838. }
  8839. bool is_chinese_char(uint32_t cpt) {
  8840. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  8841. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  8842. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  8843. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  8844. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  8845. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  8846. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  8847. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  8848. (cpt >= 0x3000 && cpt <= 0x303F) ||
  8849. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  8850. return true; // NOLINT
  8851. }
  8852. return false;
  8853. }
  8854. const llama_vocab & vocab;
  8855. };
  8856. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  8857. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  8858. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  8859. } FRAGMENT_BUFFER_VARIANT_TYPE;
  8860. struct fragment_buffer_variant {
  8861. fragment_buffer_variant(llama_vocab::id _token)
  8862. :
  8863. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  8864. token(_token),
  8865. raw_text(_dummy),
  8866. offset(0),
  8867. length(0) {}
  8868. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  8869. :
  8870. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  8871. token((llama_vocab::id) - 1),
  8872. raw_text(_raw_text),
  8873. offset(_offset),
  8874. length(_length){
  8875. GGML_ASSERT(_offset >= 0);
  8876. GGML_ASSERT(_length >= 1);
  8877. GGML_ASSERT(offset + length <= raw_text.length());
  8878. }
  8879. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  8880. const llama_vocab::id token;
  8881. const std::string _dummy;
  8882. const std::string & raw_text;
  8883. const uint64_t offset;
  8884. const uint64_t length;
  8885. };
  8886. // #define PRETOKENIZERDEBUG
  8887. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  8888. // for each special token
  8889. for (const auto & st: vocab.special_tokens_cache) {
  8890. const auto & special_token = st.first;
  8891. const auto & special_id = st.second;
  8892. // for each text fragment
  8893. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  8894. while (it != buffer.end()) {
  8895. auto & fragment = (*it);
  8896. // if a fragment is text ( not yet processed )
  8897. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8898. auto * raw_text = &(fragment.raw_text);
  8899. auto raw_text_base_offset = fragment.offset;
  8900. auto raw_text_base_length = fragment.length;
  8901. // loop over the text
  8902. while (true) {
  8903. // find the first occurrence of a given special token in this fragment
  8904. // passing offset argument only limit the "search area" but match coordinates
  8905. // are still relative to the source full raw_text
  8906. auto match = raw_text->find(special_token, raw_text_base_offset);
  8907. // no occurrences found, stop processing this fragment for a given special token
  8908. if (match == std::string::npos) break;
  8909. // check if match is within bounds of offset <-> length
  8910. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  8911. #ifdef PRETOKENIZERDEBUG
  8912. LLAMA_LOG_WARN("FF: (%ld %ld %ld) '%s'\n", raw_text->length(), raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  8913. #endif
  8914. auto source = std::distance(buffer.begin(), it);
  8915. // if match is further than base offset
  8916. // then we have some text to the left of it
  8917. if (match > raw_text_base_offset) {
  8918. // left
  8919. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  8920. const int64_t left_reminder_length = match - raw_text_base_offset;
  8921. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  8922. #ifdef PRETOKENIZERDEBUG
  8923. LLAMA_LOG_WARN("FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  8924. #endif
  8925. it++;
  8926. }
  8927. // special token
  8928. buffer.emplace_after(it, special_id);
  8929. it++;
  8930. // right
  8931. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  8932. const int64_t right_reminder_offset = match + special_token.length();
  8933. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  8934. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  8935. #ifdef PRETOKENIZERDEBUG
  8936. LLAMA_LOG_WARN("FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  8937. #endif
  8938. it++;
  8939. if (source == 0) {
  8940. buffer.erase_after(buffer.before_begin());
  8941. } else {
  8942. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8943. }
  8944. // repeat for the right side
  8945. raw_text_base_offset = right_reminder_offset;
  8946. raw_text_base_length = right_reminder_length;
  8947. #ifdef PRETOKENIZERDEBUG
  8948. LLAMA_LOG_WARN("RR: (%ld %ld) '%s'\n", raw_text_base_offset, raw_text_base_length, raw_text->substr(raw_text_base_offset, raw_text_base_length).c_str());
  8949. #endif
  8950. } else {
  8951. if (source == 0) {
  8952. buffer.erase_after(buffer.before_begin());
  8953. } else {
  8954. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8955. }
  8956. break;
  8957. }
  8958. }
  8959. }
  8960. it++;
  8961. }
  8962. }
  8963. }
  8964. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  8965. std::vector<llama_vocab::id> output;
  8966. // OG tokenizer behavior:
  8967. //
  8968. // tokenizer.encode('', add_bos=True) returns [1]
  8969. // tokenizer.encode('', add_bos=False) returns []
  8970. if (bos && vocab.special_bos_id != -1) {
  8971. output.push_back(vocab.special_bos_id);
  8972. }
  8973. if (raw_text.empty()) {
  8974. return output;
  8975. }
  8976. std::forward_list<fragment_buffer_variant> fragment_buffer;
  8977. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  8978. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  8979. switch (vocab.type) {
  8980. case LLAMA_VOCAB_TYPE_SPM:
  8981. {
  8982. for (const auto & fragment : fragment_buffer) {
  8983. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8984. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  8985. // TODO: It's likely possible to get rid of this string copy entirely
  8986. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  8987. // and passing 'add space prefix' as bool argument
  8988. //
  8989. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8990. if (&fragment == &fragment_buffer.front()) {
  8991. if (vocab.add_space_prefix) {
  8992. raw_text = " " + raw_text; // prefix with space if the first token is not special
  8993. }
  8994. }
  8995. #ifdef PRETOKENIZERDEBUG
  8996. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8997. #endif
  8998. llm_tokenizer_spm tokenizer(vocab);
  8999. llama_escape_whitespace(raw_text);
  9000. tokenizer.tokenize(raw_text, output);
  9001. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9002. output.push_back(fragment.token);
  9003. }
  9004. }
  9005. } break;
  9006. case LLAMA_VOCAB_TYPE_BPE:
  9007. {
  9008. for (const auto & fragment : fragment_buffer) {
  9009. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9010. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9011. #ifdef PRETOKENIZERDEBUG
  9012. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9013. #endif
  9014. llm_tokenizer_bpe tokenizer(vocab);
  9015. tokenizer.tokenize(raw_text, output);
  9016. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9017. output.push_back(fragment.token);
  9018. }
  9019. }
  9020. } break;
  9021. case LLAMA_VOCAB_TYPE_WPM:
  9022. {
  9023. for (const auto & fragment : fragment_buffer) {
  9024. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9025. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9026. #ifdef PRETOKENIZERDEBUG
  9027. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9028. #endif
  9029. llm_tokenizer_wpm tokenizer(vocab);
  9030. tokenizer.tokenize(raw_text, output);
  9031. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9032. output.push_back(fragment.token);
  9033. }
  9034. }
  9035. } break;
  9036. case LLAMA_VOCAB_TYPE_NONE:
  9037. GGML_ASSERT(false);
  9038. }
  9039. return output;
  9040. }
  9041. //
  9042. // grammar - internal
  9043. //
  9044. struct llama_partial_utf8 {
  9045. uint32_t value; // bit value so far (unshifted)
  9046. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  9047. };
  9048. struct llama_grammar {
  9049. const std::vector<std::vector<llama_grammar_element>> rules;
  9050. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9051. // buffer for partially generated UTF-8 sequence from accepted tokens
  9052. llama_partial_utf8 partial_utf8;
  9053. };
  9054. struct llama_grammar_candidate {
  9055. size_t index;
  9056. const uint32_t * code_points;
  9057. llama_partial_utf8 partial_utf8;
  9058. };
  9059. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9060. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9061. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9062. const std::string & src,
  9063. llama_partial_utf8 partial_start) {
  9064. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9065. const char * pos = src.c_str();
  9066. std::vector<uint32_t> code_points;
  9067. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9068. code_points.reserve(src.size() + 1);
  9069. uint32_t value = partial_start.value;
  9070. int n_remain = partial_start.n_remain;
  9071. // continue previous decode, if applicable
  9072. while (*pos != 0 && n_remain > 0) {
  9073. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9074. if ((next_byte >> 6) != 2) {
  9075. // invalid sequence, abort
  9076. code_points.push_back(0);
  9077. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9078. }
  9079. value = (value << 6) + (next_byte & 0x3F);
  9080. ++pos;
  9081. --n_remain;
  9082. }
  9083. if (partial_start.n_remain > 0 && n_remain == 0) {
  9084. code_points.push_back(value);
  9085. }
  9086. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9087. while (*pos != 0) {
  9088. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9089. uint8_t highbits = first_byte >> 4;
  9090. n_remain = lookup[highbits] - 1;
  9091. if (n_remain < 0) {
  9092. // invalid sequence, abort
  9093. code_points.clear();
  9094. code_points.push_back(0);
  9095. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9096. }
  9097. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9098. value = first_byte & mask;
  9099. ++pos;
  9100. while (*pos != 0 && n_remain > 0) {
  9101. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9102. ++pos;
  9103. --n_remain;
  9104. }
  9105. if (n_remain == 0) {
  9106. code_points.push_back(value);
  9107. }
  9108. }
  9109. code_points.push_back(0);
  9110. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9111. }
  9112. // returns true iff pos points to the end of one of the definitions of a rule
  9113. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9114. switch (pos->type) {
  9115. case LLAMA_GRETYPE_END: return true; // NOLINT
  9116. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9117. default: return false;
  9118. }
  9119. }
  9120. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9121. // asserts that pos is pointing to a char range element
  9122. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9123. const llama_grammar_element * pos,
  9124. const uint32_t chr) {
  9125. bool found = false;
  9126. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9127. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9128. do {
  9129. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9130. // inclusive range, e.g. [a-z]
  9131. found = found || (pos->value <= chr && chr <= pos[1].value);
  9132. pos += 2;
  9133. } else {
  9134. // exact char match, e.g. [a] or "a"
  9135. found = found || pos->value == chr;
  9136. pos += 1;
  9137. }
  9138. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9139. return std::make_pair(found == is_positive_char, pos);
  9140. }
  9141. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9142. // range at pos (regular or inverse range)
  9143. // asserts that pos is pointing to a char range element
  9144. static bool llama_grammar_match_partial_char(
  9145. const llama_grammar_element * pos,
  9146. const llama_partial_utf8 partial_utf8) {
  9147. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9148. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9149. uint32_t partial_value = partial_utf8.value;
  9150. int n_remain = partial_utf8.n_remain;
  9151. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9152. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9153. return false;
  9154. }
  9155. // range of possible code points this partial UTF-8 sequence could complete to
  9156. uint32_t low = partial_value << (n_remain * 6);
  9157. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9158. if (low == 0) {
  9159. if (n_remain == 2) {
  9160. low = 1 << 11;
  9161. } else if (n_remain == 3) {
  9162. low = 1 << 16;
  9163. }
  9164. }
  9165. do {
  9166. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9167. // inclusive range, e.g. [a-z]
  9168. if (pos->value <= high && low <= pos[1].value) {
  9169. return is_positive_char;
  9170. }
  9171. pos += 2;
  9172. } else {
  9173. // exact char match, e.g. [a] or "a"
  9174. if (low <= pos->value && pos->value <= high) {
  9175. return is_positive_char;
  9176. }
  9177. pos += 1;
  9178. }
  9179. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9180. return !is_positive_char;
  9181. }
  9182. // transforms a grammar pushdown stack into N possible stacks, all ending
  9183. // at a character range (terminal element)
  9184. static void llama_grammar_advance_stack(
  9185. const std::vector<std::vector<llama_grammar_element>> & rules,
  9186. const std::vector<const llama_grammar_element *> & stack,
  9187. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9188. if (stack.empty()) {
  9189. new_stacks.emplace_back(stack);
  9190. return;
  9191. }
  9192. const llama_grammar_element * pos = stack.back();
  9193. switch (pos->type) {
  9194. case LLAMA_GRETYPE_RULE_REF: {
  9195. const size_t rule_id = static_cast<size_t>(pos->value);
  9196. const llama_grammar_element * subpos = rules[rule_id].data();
  9197. do {
  9198. // init new stack without the top (pos)
  9199. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9200. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9201. // if this rule ref is followed by another element, add that to stack
  9202. new_stack.push_back(pos + 1);
  9203. }
  9204. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9205. // if alternate is nonempty, add to stack
  9206. new_stack.push_back(subpos);
  9207. }
  9208. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9209. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9210. // scan to end of alternate def
  9211. subpos++;
  9212. }
  9213. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9214. // there's another alternate def of this rule to process
  9215. subpos++;
  9216. } else {
  9217. break;
  9218. }
  9219. } while (true);
  9220. break;
  9221. }
  9222. case LLAMA_GRETYPE_CHAR:
  9223. case LLAMA_GRETYPE_CHAR_NOT:
  9224. new_stacks.emplace_back(stack);
  9225. break;
  9226. default:
  9227. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9228. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9229. // those
  9230. GGML_ASSERT(false);
  9231. }
  9232. }
  9233. // takes a set of possible pushdown stacks on a grammar, which are required to
  9234. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9235. // produces the N possible stacks if the given char is accepted at those
  9236. // positions
  9237. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9238. const std::vector<std::vector<llama_grammar_element>> & rules,
  9239. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9240. const uint32_t chr) {
  9241. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9242. for (const auto & stack : stacks) {
  9243. if (stack.empty()) {
  9244. continue;
  9245. }
  9246. auto match = llama_grammar_match_char(stack.back(), chr);
  9247. if (match.first) {
  9248. const llama_grammar_element * pos = match.second;
  9249. // update top of stack to next element, if any
  9250. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9251. if (!llama_grammar_is_end_of_sequence(pos)) {
  9252. new_stack.push_back(pos);
  9253. }
  9254. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9255. }
  9256. }
  9257. return new_stacks;
  9258. }
  9259. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9260. const std::vector<std::vector<llama_grammar_element>> & rules,
  9261. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9262. const std::vector<llama_grammar_candidate> & candidates);
  9263. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9264. const std::vector<std::vector<llama_grammar_element>> & rules,
  9265. const std::vector<const llama_grammar_element *> & stack,
  9266. const std::vector<llama_grammar_candidate> & candidates) {
  9267. std::vector<llama_grammar_candidate> rejects;
  9268. if (stack.empty()) {
  9269. for (const auto & tok : candidates) {
  9270. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9271. rejects.push_back(tok);
  9272. }
  9273. }
  9274. return rejects;
  9275. }
  9276. const llama_grammar_element * stack_pos = stack.back();
  9277. std::vector<llama_grammar_candidate> next_candidates;
  9278. for (const auto & tok : candidates) {
  9279. if (*tok.code_points == 0) {
  9280. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9281. // that cannot satisfy this position in grammar
  9282. if (tok.partial_utf8.n_remain != 0 &&
  9283. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9284. rejects.push_back(tok);
  9285. }
  9286. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9287. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9288. } else {
  9289. rejects.push_back(tok);
  9290. }
  9291. }
  9292. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9293. // update top of stack to next element, if any
  9294. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9295. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9296. stack_after.push_back(stack_pos_after);
  9297. }
  9298. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9299. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9300. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9301. for (const auto & tok : next_rejects) {
  9302. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9303. }
  9304. return rejects;
  9305. }
  9306. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9307. const std::vector<std::vector<llama_grammar_element>> & rules,
  9308. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9309. const std::vector<llama_grammar_candidate> & candidates) {
  9310. GGML_ASSERT(!stacks.empty()); // REVIEW
  9311. if (candidates.empty()) {
  9312. return std::vector<llama_grammar_candidate>();
  9313. }
  9314. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9315. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9316. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9317. }
  9318. return rejects;
  9319. }
  9320. //
  9321. // grammar - external
  9322. //
  9323. struct llama_grammar * llama_grammar_init(
  9324. const llama_grammar_element ** rules,
  9325. size_t n_rules,
  9326. size_t start_rule_index) {
  9327. const llama_grammar_element * pos;
  9328. // copy rule definitions into vectors
  9329. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9330. for (size_t i = 0; i < n_rules; i++) {
  9331. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9332. vec_rules[i].push_back(*pos);
  9333. }
  9334. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9335. }
  9336. // loop over alternates of start rule to build initial stacks
  9337. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9338. pos = vec_rules[start_rule_index].data();
  9339. do {
  9340. std::vector<const llama_grammar_element *> stack;
  9341. if (!llama_grammar_is_end_of_sequence(pos)) {
  9342. // if alternate is nonempty, add to stack
  9343. stack.push_back(pos);
  9344. }
  9345. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9346. while (!llama_grammar_is_end_of_sequence(pos)) {
  9347. // scan to end of alternate def
  9348. pos++;
  9349. }
  9350. if (pos->type == LLAMA_GRETYPE_ALT) {
  9351. // there's another alternate def of this rule to process
  9352. pos++;
  9353. } else {
  9354. break;
  9355. }
  9356. } while (true);
  9357. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9358. }
  9359. void llama_grammar_free(struct llama_grammar * grammar) {
  9360. delete grammar;
  9361. }
  9362. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9363. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9364. // redirect elements in stacks to point to new rules
  9365. for (size_t is = 0; is < result->stacks.size(); is++) {
  9366. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9367. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9368. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9369. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9370. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9371. }
  9372. }
  9373. }
  9374. }
  9375. }
  9376. return result;
  9377. }
  9378. //
  9379. // sampling
  9380. //
  9381. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9382. if (seed == LLAMA_DEFAULT_SEED) {
  9383. seed = time(NULL);
  9384. }
  9385. ctx->rng.seed(seed);
  9386. }
  9387. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9388. GGML_ASSERT(candidates->size > 0);
  9389. const int64_t t_start_sample_us = ggml_time_us();
  9390. // Sort the logits in descending order
  9391. if (!candidates->sorted) {
  9392. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9393. return a.logit > b.logit;
  9394. });
  9395. candidates->sorted = true;
  9396. }
  9397. float max_l = candidates->data[0].logit;
  9398. float cum_sum = 0.0f;
  9399. for (size_t i = 0; i < candidates->size; ++i) {
  9400. float p = expf(candidates->data[i].logit - max_l);
  9401. candidates->data[i].p = p;
  9402. cum_sum += p;
  9403. }
  9404. for (size_t i = 0; i < candidates->size; ++i) {
  9405. candidates->data[i].p /= cum_sum;
  9406. }
  9407. if (ctx) {
  9408. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9409. }
  9410. }
  9411. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9412. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9413. // if (k >= (int32_t)candidates->size) {
  9414. // return;
  9415. // }
  9416. const int64_t t_start_sample_us = ggml_time_us();
  9417. if (k <= 0) {
  9418. k = candidates->size;
  9419. }
  9420. k = std::max(k, (int) min_keep);
  9421. k = std::min(k, (int) candidates->size);
  9422. // Sort scores in descending order
  9423. if (!candidates->sorted) {
  9424. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9425. return a.logit > b.logit;
  9426. };
  9427. if (k <= 128) {
  9428. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9429. } else {
  9430. constexpr int nbuckets = 128;
  9431. constexpr float bucket_low = -10.0f;
  9432. constexpr float bucket_high = 10.0f;
  9433. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9434. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9435. std::vector<int> bucket_idx(candidates->size);
  9436. std::vector<int> histo(nbuckets, 0);
  9437. for (int i = 0; i < (int)candidates->size; ++i) {
  9438. const float val = candidates->data[i].logit;
  9439. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9440. ib = std::max(0, std::min(nbuckets-1, ib));
  9441. bucket_idx[i] = ib;
  9442. ++histo[ib];
  9443. }
  9444. int nhave = 0;
  9445. int ib = nbuckets - 1;
  9446. for ( ; ib >= 0; --ib) {
  9447. nhave += histo[ib];
  9448. if (nhave >= k) break;
  9449. }
  9450. std::vector<llama_token_data> tmp_tokens(nhave);
  9451. auto ptr = tmp_tokens.data();
  9452. std::vector<llama_token_data*> bucket_ptrs;
  9453. bucket_ptrs.reserve(nbuckets - ib);
  9454. for (int j = nbuckets - 1; j >= ib; --j) {
  9455. bucket_ptrs.push_back(ptr);
  9456. ptr += histo[j];
  9457. }
  9458. for (int i = 0; i < (int)candidates->size; ++i) {
  9459. int j = bucket_idx[i];
  9460. if (j >= ib) {
  9461. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9462. }
  9463. }
  9464. ptr = tmp_tokens.data();
  9465. int ndone = 0;
  9466. for (int j = nbuckets-1; j > ib; --j) {
  9467. std::sort(ptr, ptr + histo[j], comp);
  9468. ptr += histo[j];
  9469. ndone += histo[j];
  9470. }
  9471. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9472. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9473. }
  9474. candidates->sorted = true;
  9475. }
  9476. candidates->size = k;
  9477. if (ctx) {
  9478. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9479. }
  9480. }
  9481. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9482. if (p >= 1.0f) {
  9483. return;
  9484. }
  9485. llama_sample_softmax(ctx, candidates);
  9486. const int64_t t_start_sample_us = ggml_time_us();
  9487. // Compute the cumulative probabilities
  9488. float cum_sum = 0.0f;
  9489. size_t last_idx = candidates->size;
  9490. for (size_t i = 0; i < candidates->size; ++i) {
  9491. cum_sum += candidates->data[i].p;
  9492. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9493. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9494. if (cum_sum >= p && i + 1 >= min_keep) {
  9495. last_idx = i + 1;
  9496. break;
  9497. }
  9498. }
  9499. // Resize the output vector to keep only the top-p tokens
  9500. candidates->size = last_idx;
  9501. if (ctx) {
  9502. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9503. }
  9504. }
  9505. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9506. if (p <= 0.0f || !candidates->size) {
  9507. return;
  9508. }
  9509. const int64_t t_start_sample_us = ggml_time_us();
  9510. bool min_p_applied = false;
  9511. // if the candidates aren't sorted, try the unsorted implementation first
  9512. if (!candidates->sorted) {
  9513. std::vector<llama_token_data> filtered_tokens;
  9514. float max_logit = -FLT_MAX;
  9515. for (size_t i = 0; i < candidates->size; ++i) {
  9516. max_logit = std::max(max_logit, candidates->data[i].logit);
  9517. }
  9518. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9519. for (size_t i = 0; i < candidates->size; ++i) {
  9520. if (candidates->data[i].logit >= min_logit) {
  9521. filtered_tokens.push_back(candidates->data[i]);
  9522. }
  9523. }
  9524. // if we have enough values the operation was a success
  9525. if (filtered_tokens.size() >= min_keep) {
  9526. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9527. candidates->size = filtered_tokens.size();
  9528. min_p_applied = true;
  9529. }
  9530. }
  9531. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9532. if (!min_p_applied) {
  9533. // Sort the logits in descending order
  9534. if (!candidates->sorted) {
  9535. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9536. return a.logit > b.logit;
  9537. });
  9538. candidates->sorted = true;
  9539. }
  9540. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9541. size_t i = 1; // first token always matches
  9542. for (; i < candidates->size; ++i) {
  9543. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9544. break; // prob too small
  9545. }
  9546. }
  9547. // Resize the output vector to keep only the matching tokens
  9548. candidates->size = i;
  9549. }
  9550. if (ctx) {
  9551. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9552. }
  9553. }
  9554. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9555. if (z >= 1.0f || candidates->size <= 2) {
  9556. return;
  9557. }
  9558. llama_sample_softmax(nullptr, candidates);
  9559. const int64_t t_start_sample_us = ggml_time_us();
  9560. // Compute the first and second derivatives
  9561. std::vector<float> first_derivatives(candidates->size - 1);
  9562. std::vector<float> second_derivatives(candidates->size - 2);
  9563. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9564. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9565. }
  9566. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9567. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9568. }
  9569. // Calculate absolute value of second derivatives
  9570. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9571. second_derivatives[i] = std::abs(second_derivatives[i]);
  9572. }
  9573. // Normalize the second derivatives
  9574. {
  9575. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9576. if (second_derivatives_sum > 1e-6f) {
  9577. for (float & value : second_derivatives) {
  9578. value /= second_derivatives_sum;
  9579. }
  9580. } else {
  9581. for (float & value : second_derivatives) {
  9582. value = 1.0f / second_derivatives.size();
  9583. }
  9584. }
  9585. }
  9586. float cum_sum = 0.0f;
  9587. size_t last_idx = candidates->size;
  9588. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9589. cum_sum += second_derivatives[i];
  9590. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9591. if (cum_sum > z && i >= min_keep) {
  9592. last_idx = i;
  9593. break;
  9594. }
  9595. }
  9596. // Resize the output vector to keep only the tokens above the tail location
  9597. candidates->size = last_idx;
  9598. if (ctx) {
  9599. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9600. }
  9601. }
  9602. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9603. // Reference implementation:
  9604. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  9605. if (p >= 1.0f) {
  9606. return;
  9607. }
  9608. // Compute the softmax of logits and calculate entropy
  9609. llama_sample_softmax(nullptr, candidates);
  9610. const int64_t t_start_sample_us = ggml_time_us();
  9611. float entropy = 0.0f;
  9612. for (size_t i = 0; i < candidates->size; ++i) {
  9613. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  9614. }
  9615. // Compute the absolute difference between negative log probability and entropy for each candidate
  9616. std::vector<float> shifted_scores;
  9617. for (size_t i = 0; i < candidates->size; ++i) {
  9618. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  9619. shifted_scores.push_back(shifted_score);
  9620. }
  9621. // Sort tokens based on the shifted_scores and their corresponding indices
  9622. std::vector<size_t> indices(candidates->size);
  9623. std::iota(indices.begin(), indices.end(), 0);
  9624. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  9625. return shifted_scores[a] < shifted_scores[b];
  9626. });
  9627. // Compute the cumulative probabilities
  9628. float cum_sum = 0.0f;
  9629. size_t last_idx = indices.size();
  9630. for (size_t i = 0; i < indices.size(); ++i) {
  9631. size_t idx = indices[i];
  9632. cum_sum += candidates->data[idx].p;
  9633. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  9634. if (cum_sum > p && i >= min_keep - 1) {
  9635. last_idx = i + 1;
  9636. break;
  9637. }
  9638. }
  9639. // Resize the output vector to keep only the locally typical tokens
  9640. std::vector<llama_token_data> new_candidates;
  9641. for (size_t i = 0; i < last_idx; ++i) {
  9642. size_t idx = indices[i];
  9643. new_candidates.push_back(candidates->data[idx]);
  9644. }
  9645. // Replace the data in candidates with the new_candidates data
  9646. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  9647. candidates->size = new_candidates.size();
  9648. candidates->sorted = false;
  9649. if (ctx) {
  9650. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9651. }
  9652. }
  9653. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  9654. const int64_t t_start_sample_us = ggml_time_us();
  9655. // no need to do anything if there is only one (or zero) candidates
  9656. if(candidates_p->size <= 1) {
  9657. return;
  9658. }
  9659. // Calculate maximum possible entropy
  9660. float max_entropy = -logf(1.0f / candidates_p->size);
  9661. llama_sample_softmax(nullptr, candidates_p);
  9662. // Calculate entropy of the softmax probabilities
  9663. float entropy = 0.0f;
  9664. for (size_t i = 0; i < candidates_p->size; ++i) {
  9665. float prob = candidates_p->data[i].p;
  9666. if (prob > 0.0f) { // Ensure no log(0)
  9667. entropy -= prob * logf(prob);
  9668. }
  9669. }
  9670. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  9671. float normalized_entropy = entropy / max_entropy;
  9672. // Map the normalized entropy to the desired temperature range using the power function
  9673. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  9674. #ifdef DEBUG
  9675. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  9676. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  9677. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  9678. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  9679. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  9680. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  9681. #endif
  9682. // Apply the dynamically calculated temperature scaling
  9683. for (size_t i = 0; i < candidates_p->size; ++i) {
  9684. candidates_p->data[i].logit /= dyn_temp;
  9685. }
  9686. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  9687. double max_l_double = candidates_p->data[0].logit;
  9688. double cum_sum_double = 0.0;
  9689. for (size_t i = 0; i < candidates_p->size; ++i) {
  9690. double p = exp(candidates_p->data[i].logit - max_l_double);
  9691. candidates_p->data[i].p = p; // Store the scaled probability
  9692. cum_sum_double += p;
  9693. }
  9694. for (size_t i = 0; i < candidates_p->size; ++i) {
  9695. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  9696. }
  9697. #ifdef DEBUG
  9698. // Print the updated top 25 probabilities after temperature scaling
  9699. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  9700. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  9701. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  9702. }
  9703. #endif
  9704. if (ctx) {
  9705. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9706. }
  9707. }
  9708. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  9709. const int64_t t_start_sample_us = ggml_time_us();
  9710. for (size_t i = 0; i < candidates_p->size; ++i) {
  9711. candidates_p->data[i].logit /= temp;
  9712. }
  9713. if (ctx) {
  9714. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9715. }
  9716. }
  9717. void llama_sample_repetition_penalties(
  9718. struct llama_context * ctx,
  9719. llama_token_data_array * candidates,
  9720. const llama_token * last_tokens,
  9721. size_t penalty_last_n,
  9722. float penalty_repeat,
  9723. float penalty_freq,
  9724. float penalty_present) {
  9725. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  9726. return;
  9727. }
  9728. const int64_t t_start_sample_us = ggml_time_us();
  9729. // Create a frequency map to count occurrences of each token in last_tokens
  9730. std::unordered_map<llama_token, int> token_count;
  9731. for (size_t i = 0; i < penalty_last_n; ++i) {
  9732. token_count[last_tokens[i]]++;
  9733. }
  9734. // Apply frequency and presence penalties to the candidates
  9735. for (size_t i = 0; i < candidates->size; ++i) {
  9736. const auto token_iter = token_count.find(candidates->data[i].id);
  9737. if (token_iter == token_count.end()) {
  9738. continue;
  9739. }
  9740. const int count = token_iter->second;
  9741. // The academic publication that described this technique actually just only divided, but that would cause tokens with negative logits to become more likely, which is obviously wrong.
  9742. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  9743. if (candidates->data[i].logit <= 0) {
  9744. candidates->data[i].logit *= penalty_repeat;
  9745. } else {
  9746. candidates->data[i].logit /= penalty_repeat;
  9747. }
  9748. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  9749. }
  9750. candidates->sorted = false;
  9751. if (ctx) {
  9752. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9753. }
  9754. }
  9755. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  9756. GGML_ASSERT(ctx);
  9757. const int64_t t_start_sample_us = ggml_time_us();
  9758. bool allow_eos = false;
  9759. for (const auto & stack : grammar->stacks) {
  9760. if (stack.empty()) {
  9761. allow_eos = true;
  9762. break;
  9763. }
  9764. }
  9765. const llama_token eos = llama_token_eos(&ctx->model);
  9766. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  9767. candidates_decoded.reserve(candidates->size);
  9768. std::vector<llama_grammar_candidate> candidates_grammar;
  9769. candidates_grammar.reserve(candidates->size);
  9770. for (size_t i = 0; i < candidates->size; ++i) {
  9771. const llama_token id = candidates->data[i].id;
  9772. const std::string piece = llama_token_to_piece(ctx, id);
  9773. if (id == eos) {
  9774. if (!allow_eos) {
  9775. candidates->data[i].logit = -INFINITY;
  9776. }
  9777. } else if (piece.empty() || piece[0] == 0) {
  9778. candidates->data[i].logit = -INFINITY;
  9779. } else {
  9780. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  9781. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  9782. }
  9783. }
  9784. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  9785. for (const auto & reject : rejects) {
  9786. candidates->data[reject.index].logit = -INFINITY;
  9787. }
  9788. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9789. }
  9790. static void llama_log_softmax(float * array, size_t size) {
  9791. float max_l = *std::max_element(array, array + size);
  9792. float sum = 0.f;
  9793. for (size_t i = 0; i < size; ++i) {
  9794. float p = expf(array[i] - max_l);
  9795. sum += p;
  9796. array[i] = p;
  9797. }
  9798. for (size_t i = 0; i < size; ++i) {
  9799. array[i] = logf(array[i] / sum);
  9800. }
  9801. }
  9802. void llama_sample_apply_guidance(
  9803. struct llama_context * ctx,
  9804. float * logits,
  9805. float * logits_guidance,
  9806. float scale) {
  9807. GGML_ASSERT(ctx);
  9808. const auto t_start_sample_us = ggml_time_us();
  9809. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  9810. llama_log_softmax(logits, n_vocab);
  9811. llama_log_softmax(logits_guidance, n_vocab);
  9812. for (int i = 0; i < n_vocab; ++i) {
  9813. auto & l = logits[i];
  9814. const auto & g = logits_guidance[i];
  9815. l = scale * (l - g) + g;
  9816. }
  9817. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9818. }
  9819. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  9820. GGML_ASSERT(ctx);
  9821. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  9822. int64_t t_start_sample_us;
  9823. t_start_sample_us = ggml_time_us();
  9824. llama_sample_softmax(nullptr, candidates);
  9825. // Estimate s_hat using the most probable m tokens
  9826. float s_hat = 0.0;
  9827. float sum_ti_bi = 0.0;
  9828. float sum_ti_sq = 0.0;
  9829. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  9830. float t_i = logf(float(i + 2) / float(i + 1));
  9831. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  9832. sum_ti_bi += t_i * b_i;
  9833. sum_ti_sq += t_i * t_i;
  9834. }
  9835. s_hat = sum_ti_bi / sum_ti_sq;
  9836. // Compute k from the estimated s_hat and target surprise value
  9837. float epsilon_hat = s_hat - 1;
  9838. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  9839. // Sample the next word X using top-k sampling
  9840. llama_sample_top_k(nullptr, candidates, int(k), 1);
  9841. if (ctx) {
  9842. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9843. }
  9844. llama_token X = llama_sample_token(ctx, candidates);
  9845. t_start_sample_us = ggml_time_us();
  9846. // Compute error as the difference between observed surprise and target surprise value
  9847. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9848. return candidate.id == X;
  9849. }));
  9850. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9851. float e = observed_surprise - tau;
  9852. // Update mu using the learning rate and error
  9853. *mu = *mu - eta * e;
  9854. if (ctx) {
  9855. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9856. }
  9857. return X;
  9858. }
  9859. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  9860. int64_t t_start_sample_us;
  9861. t_start_sample_us = ggml_time_us();
  9862. llama_sample_softmax(ctx, candidates);
  9863. // Truncate the words with surprise values greater than mu
  9864. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9865. return -log2f(candidate.p) > *mu;
  9866. }));
  9867. if (candidates->size == 0) {
  9868. candidates->size = 1;
  9869. }
  9870. if (ctx) {
  9871. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9872. }
  9873. // Normalize the probabilities of the remaining words
  9874. llama_sample_softmax(ctx, candidates);
  9875. // Sample the next word X from the remaining words
  9876. llama_token X = llama_sample_token(ctx, candidates);
  9877. t_start_sample_us = ggml_time_us();
  9878. // Compute error as the difference between observed surprise and target surprise value
  9879. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9880. return candidate.id == X;
  9881. }));
  9882. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9883. float e = observed_surprise - tau;
  9884. // Update mu using the learning rate and error
  9885. *mu = *mu - eta * e;
  9886. if (ctx) {
  9887. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9888. }
  9889. return X;
  9890. }
  9891. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  9892. const int64_t t_start_sample_us = ggml_time_us();
  9893. // Find max element
  9894. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9895. return a.logit < b.logit;
  9896. });
  9897. llama_token result = max_iter->id;
  9898. if (ctx) {
  9899. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9900. ctx->n_sample++;
  9901. }
  9902. return result;
  9903. }
  9904. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  9905. GGML_ASSERT(ctx);
  9906. const int64_t t_start_sample_us = ggml_time_us();
  9907. llama_sample_softmax(nullptr, candidates);
  9908. std::vector<float> probs;
  9909. probs.reserve(candidates->size);
  9910. for (size_t i = 0; i < candidates->size; ++i) {
  9911. probs.push_back(candidates->data[i].p);
  9912. }
  9913. std::discrete_distribution<> dist(probs.begin(), probs.end());
  9914. auto & rng = ctx->rng;
  9915. int idx = dist(rng);
  9916. llama_token result = candidates->data[idx].id;
  9917. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9918. ctx->n_sample++;
  9919. return result;
  9920. }
  9921. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  9922. const int64_t t_start_sample_us = ggml_time_us();
  9923. if (token == llama_token_eos(&ctx->model)) {
  9924. for (const auto & stack : grammar->stacks) {
  9925. if (stack.empty()) {
  9926. return;
  9927. }
  9928. }
  9929. GGML_ASSERT(false);
  9930. }
  9931. const std::string piece = llama_token_to_piece(ctx, token);
  9932. // Note terminating 0 in decoded string
  9933. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  9934. const auto & code_points = decoded.first;
  9935. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  9936. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  9937. }
  9938. grammar->partial_utf8 = decoded.second;
  9939. GGML_ASSERT(!grammar->stacks.empty());
  9940. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9941. }
  9942. //
  9943. // Beam search
  9944. //
  9945. struct llama_beam {
  9946. std::vector<llama_token> tokens;
  9947. float p; // Cumulative beam probability (renormalized relative to all beams)
  9948. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  9949. // Sort beams by probability. In case of ties, prefer beams at eob.
  9950. bool operator<(const llama_beam & rhs) const {
  9951. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  9952. }
  9953. // Shift off first n tokens and discard them.
  9954. void shift_tokens(const size_t n) {
  9955. if (n) {
  9956. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  9957. tokens.resize(tokens.size() - n);
  9958. }
  9959. }
  9960. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  9961. };
  9962. // A struct for calculating logit-related info.
  9963. struct llama_logit_info {
  9964. const float * const logits;
  9965. const int n_vocab;
  9966. const float max_l;
  9967. const float normalizer;
  9968. struct sum_exp {
  9969. float max_l;
  9970. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  9971. };
  9972. llama_logit_info(llama_context * ctx)
  9973. : logits(llama_get_logits(ctx))
  9974. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  9975. , max_l(*std::max_element(logits, logits + n_vocab))
  9976. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  9977. { }
  9978. llama_token_data get_token_data(const llama_token token_id) const {
  9979. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  9980. return {token_id, logits[token_id], p};
  9981. }
  9982. // Return top k token_data by logit.
  9983. std::vector<llama_token_data> top_k(size_t k) {
  9984. std::vector<llama_token_data> min_heap; // min-heap by logit
  9985. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  9986. min_heap.reserve(k_min);
  9987. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  9988. min_heap.push_back(get_token_data(token_id));
  9989. }
  9990. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  9991. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  9992. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  9993. if (min_heap.front().logit < logits[token_id]) {
  9994. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  9995. min_heap.back().id = token_id;
  9996. min_heap.back().logit = logits[token_id];
  9997. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  9998. }
  9999. }
  10000. return min_heap;
  10001. }
  10002. float probability_from_logit(float logit) const {
  10003. return normalizer * std::exp(logit - max_l);
  10004. }
  10005. };
  10006. struct llama_beam_search_data {
  10007. llama_context * ctx;
  10008. size_t n_beams;
  10009. int n_past;
  10010. int n_predict;
  10011. std::vector<llama_beam> beams;
  10012. std::vector<llama_beam> next_beams;
  10013. // Re-calculated on each loop iteration
  10014. size_t common_prefix_length;
  10015. // Used to communicate to/from callback on beams state.
  10016. std::vector<llama_beam_view> beam_views;
  10017. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10018. : ctx(ctx)
  10019. , n_beams(n_beams)
  10020. , n_past(n_past)
  10021. , n_predict(n_predict)
  10022. , beam_views(n_beams) {
  10023. beams.reserve(n_beams);
  10024. next_beams.reserve(n_beams);
  10025. }
  10026. // Collapse beams to a single beam given by index.
  10027. void collapse_beams(const size_t beam_idx) {
  10028. if (0u < beam_idx) {
  10029. std::swap(beams[0], beams[beam_idx]);
  10030. }
  10031. beams.resize(1);
  10032. }
  10033. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10034. // The repetitive patterns below reflect the 2 stages of heaps:
  10035. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10036. // * If the heap is full and a new element is found that should be included, pop the
  10037. // least element to the back(), replace it with the new, then push it into the heap.
  10038. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10039. // Min-heaps use a greater-than comparator.
  10040. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10041. if (beam.eob) {
  10042. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10043. if (next_beams.size() < n_beams) {
  10044. next_beams.push_back(std::move(beam));
  10045. if (next_beams.size() == n_beams) {
  10046. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10047. }
  10048. } else if (next_beams.front().p < beam.p) {
  10049. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10050. next_beams.back() = std::move(beam);
  10051. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10052. }
  10053. } else {
  10054. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10055. if (!beam.tokens.empty()) {
  10056. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10057. }
  10058. llama_logit_info logit_info(ctx);
  10059. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10060. size_t i=0;
  10061. if (next_beams.size() < n_beams) {
  10062. for (; next_beams.size() < n_beams ; ++i) {
  10063. llama_beam next_beam = beam;
  10064. next_beam.tokens.push_back(next_tokens[i].id);
  10065. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10066. next_beams.push_back(std::move(next_beam));
  10067. }
  10068. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10069. } else {
  10070. for (; next_beams.front().p == 0.0f ; ++i) {
  10071. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10072. next_beams.back() = beam;
  10073. next_beams.back().tokens.push_back(next_tokens[i].id);
  10074. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10075. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10076. }
  10077. }
  10078. for (; i < n_beams ; ++i) {
  10079. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10080. if (next_beams.front().p < next_p) {
  10081. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10082. next_beams.back() = beam;
  10083. next_beams.back().tokens.push_back(next_tokens[i].id);
  10084. next_beams.back().p = next_p;
  10085. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10086. }
  10087. }
  10088. }
  10089. }
  10090. // Find common_prefix_length based on beams.
  10091. // Requires beams is not empty.
  10092. size_t find_common_prefix_length() {
  10093. size_t common_prefix_length = beams[0].tokens.size();
  10094. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10095. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10096. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10097. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10098. common_prefix_length = j;
  10099. break;
  10100. }
  10101. }
  10102. }
  10103. return common_prefix_length;
  10104. }
  10105. // Construct beams_state to send back to caller via the callback function.
  10106. // Side effect: set common_prefix_length = find_common_prefix_length();
  10107. llama_beams_state get_beams_state(const bool last_call) {
  10108. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10109. beam_views[i] = beams[i].view();
  10110. }
  10111. common_prefix_length = find_common_prefix_length();
  10112. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10113. }
  10114. // Loop:
  10115. // * while i < n_predict, AND
  10116. // * any of the beams have not yet reached end-of-beam (eob), AND
  10117. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10118. // (since all other beam probabilities can only decrease)
  10119. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10120. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10121. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10122. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10123. !beams[top_beam_index()].eob ; ++i) {
  10124. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10125. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10126. if (common_prefix_length) {
  10127. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10128. n_past += common_prefix_length;
  10129. }
  10130. // Zero-out next_beam probabilities to place them last in following min-heap.
  10131. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10132. for (llama_beam & beam : beams) {
  10133. beam.shift_tokens(common_prefix_length);
  10134. fill_next_beams_by_top_probabilities(beam);
  10135. }
  10136. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10137. beams.swap(next_beams);
  10138. renormalize_beam_probabilities(beams);
  10139. }
  10140. collapse_beams(top_beam_index());
  10141. callback(callback_data, get_beams_state(true));
  10142. }
  10143. // As beams grow, the cumulative probabilities decrease.
  10144. // Renormalize them to avoid floating point underflow.
  10145. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10146. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10147. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10148. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10149. }
  10150. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10151. size_t top_beam_index() {
  10152. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10153. }
  10154. // Copy (p,eob) for each beam which may have been changed by the callback.
  10155. void update_beams_from_beam_views() {
  10156. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10157. beams[i].p = beam_views[i].p;
  10158. beams[i].eob = beam_views[i].eob;
  10159. }
  10160. }
  10161. };
  10162. void llama_beam_search(llama_context * ctx,
  10163. llama_beam_search_callback_fn_t callback, void * callback_data,
  10164. size_t n_beams, int n_past, int n_predict) {
  10165. assert(ctx);
  10166. const int64_t t_start_sample_us = ggml_time_us();
  10167. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10168. beam_search_data.loop(callback, callback_data);
  10169. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10170. ctx->n_sample++;
  10171. }
  10172. //
  10173. // quantization
  10174. //
  10175. struct quantize_state_internal {
  10176. const llama_model & model;
  10177. const llama_model_quantize_params * params;
  10178. int n_attention_wv = 0;
  10179. int n_ffn_down = 0;
  10180. int n_ffn_gate = 0;
  10181. int n_ffn_up = 0;
  10182. int i_attention_wv = 0;
  10183. int i_ffn_down = 0;
  10184. int i_ffn_gate = 0;
  10185. int i_ffn_up = 0;
  10186. int n_k_quantized = 0;
  10187. int n_fallback = 0;
  10188. bool has_imatrix = false;
  10189. // used to figure out if a model shares tok_embd with the output weight
  10190. bool has_output = false;
  10191. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10192. : model(model)
  10193. , params(params)
  10194. {}
  10195. };
  10196. static void llama_tensor_dequantize_internal(
  10197. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10198. const size_t nelements, const int nthread
  10199. ) {
  10200. if (output.size() < nelements) {
  10201. output.resize(nelements);
  10202. }
  10203. float * f32_output = (float *) output.data();
  10204. ggml_type_traits_t qtype;
  10205. if (ggml_is_quantized(tensor->type)) {
  10206. qtype = ggml_internal_get_type_traits(tensor->type);
  10207. if (qtype.to_float == NULL) {
  10208. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10209. }
  10210. } else if (tensor->type != GGML_TYPE_F16) {
  10211. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10212. }
  10213. if (nthread < 2) {
  10214. if (tensor->type == GGML_TYPE_F16) {
  10215. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10216. } else if (ggml_is_quantized(tensor->type)) {
  10217. qtype.to_float(tensor->data, f32_output, nelements);
  10218. } else {
  10219. GGML_ASSERT(false); // unreachable
  10220. }
  10221. return;
  10222. }
  10223. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10224. size_t block_size_bytes = ggml_type_size(tensor->type);
  10225. GGML_ASSERT(nelements % block_size == 0);
  10226. size_t nblocks = nelements / block_size;
  10227. size_t blocks_per_thread = nblocks / nthread;
  10228. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10229. size_t in_buff_offs = 0;
  10230. size_t out_buff_offs = 0;
  10231. for (int tnum = 0; tnum < nthread; tnum++) {
  10232. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10233. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10234. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10235. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10236. if (typ == GGML_TYPE_F16) {
  10237. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10238. } else {
  10239. qtype.to_float(inbuf, outbuf, nels);
  10240. }
  10241. };
  10242. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10243. in_buff_offs += thr_block_bytes;
  10244. out_buff_offs += thr_elems;
  10245. }
  10246. for (auto & w : workers) { w.join(); }
  10247. workers.clear();
  10248. }
  10249. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10250. const std::string name = ggml_get_name(tensor);
  10251. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10252. const llm_arch arch = qs.model.arch;
  10253. const auto tn = LLM_TN(arch);
  10254. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10255. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10256. };
  10257. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10258. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10259. if (n_expert > 1) {
  10260. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10261. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10262. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10263. // tensor name.
  10264. n_layer /= n_expert;
  10265. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10266. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10267. }
  10268. if (i_layer < 0 || i_layer >= n_layer) {
  10269. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10270. }
  10271. }
  10272. return std::make_pair(i_layer, n_layer);
  10273. };
  10274. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10275. // with the quantization of the output tensor
  10276. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10277. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10278. new_type = qs.params->output_tensor_type;
  10279. } else {
  10280. int nx = tensor->ne[0];
  10281. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10282. new_type = GGML_TYPE_Q8_0;
  10283. }
  10284. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10285. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10286. new_type = GGML_TYPE_Q5_K;
  10287. }
  10288. else if (new_type != GGML_TYPE_Q8_0) {
  10289. new_type = GGML_TYPE_Q6_K;
  10290. }
  10291. }
  10292. } else if (name == "token_embd.weight") {
  10293. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10294. new_type = qs.params->token_embedding_type;
  10295. } else {
  10296. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  10297. new_type = GGML_TYPE_Q2_K;
  10298. }
  10299. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10300. new_type = GGML_TYPE_IQ3_S;
  10301. }
  10302. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10303. new_type = GGML_TYPE_IQ3_S;
  10304. }
  10305. }
  10306. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10307. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10308. if (name.find("attn_v.weight") != std::string::npos) {
  10309. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10310. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10311. ++qs.i_attention_wv;
  10312. }
  10313. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10314. new_type = GGML_TYPE_Q4_K;
  10315. }
  10316. else if (name.find("ffn_down") != std::string::npos) {
  10317. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10318. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10319. }
  10320. ++qs.i_ffn_down;
  10321. }
  10322. else if (name.find("attn_output.weight") != std::string::npos) {
  10323. if (qs.model.hparams.n_expert == 8) {
  10324. new_type = GGML_TYPE_Q5_K;
  10325. } else {
  10326. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  10327. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10328. }
  10329. }
  10330. } else if (name.find("attn_v.weight") != std::string::npos) {
  10331. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10332. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10333. }
  10334. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10335. new_type = GGML_TYPE_Q4_K;
  10336. }
  10337. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10338. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10339. }
  10340. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10341. new_type = GGML_TYPE_Q4_K;
  10342. }
  10343. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10344. new_type = GGML_TYPE_Q4_K;
  10345. }
  10346. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10347. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10348. }
  10349. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10350. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10351. new_type = GGML_TYPE_Q5_K;
  10352. }
  10353. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10354. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10355. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10356. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10357. (qs.i_attention_wv < qs.n_attention_wv/8 || qs.i_attention_wv >= 7*qs.n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  10358. if (qs.model.type == MODEL_70B) {
  10359. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10360. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10361. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10362. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10363. }
  10364. if (qs.model.hparams.n_expert == 8) {
  10365. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10366. // TODO: explore better strategies
  10367. new_type = GGML_TYPE_Q8_0;
  10368. }
  10369. ++qs.i_attention_wv;
  10370. } else if (name.find("attn_k.weight") != std::string::npos) {
  10371. if (qs.model.hparams.n_expert == 8) {
  10372. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10373. // TODO: explore better strategies
  10374. new_type = GGML_TYPE_Q8_0;
  10375. }
  10376. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10377. new_type = GGML_TYPE_IQ3_XXS;
  10378. }
  10379. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10380. new_type = GGML_TYPE_IQ2_S;
  10381. }
  10382. } else if (name.find("attn_q.weight") != std::string::npos) {
  10383. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10384. new_type = GGML_TYPE_IQ3_XXS;
  10385. }
  10386. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10387. new_type = GGML_TYPE_IQ2_S;
  10388. }
  10389. } else if (name.find("ffn_down") != std::string::npos) {
  10390. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10391. int i_layer = info.first, n_layer = info.second;
  10392. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10393. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10394. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10395. }
  10396. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10397. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10398. }
  10399. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10400. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10401. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10402. : GGML_TYPE_Q3_K;
  10403. }
  10404. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10405. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10406. new_type = GGML_TYPE_Q4_K;
  10407. }
  10408. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10409. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10410. }
  10411. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10412. if (arch == LLM_ARCH_FALCON) {
  10413. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10414. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10415. } else {
  10416. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10417. }
  10418. }
  10419. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10420. new_type = GGML_TYPE_Q5_K;
  10421. }
  10422. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10423. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10424. new_type = GGML_TYPE_Q5_K;
  10425. }
  10426. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10427. && qs.has_imatrix && i_layer < n_layer/8) {
  10428. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10429. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10430. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10431. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10432. }
  10433. ++qs.i_ffn_down;
  10434. } else if (name.find("attn_output.weight") != std::string::npos) {
  10435. if (arch != LLM_ARCH_FALCON) {
  10436. if (qs.model.hparams.n_expert == 8) {
  10437. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10438. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10439. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10440. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10441. new_type = GGML_TYPE_Q5_K;
  10442. }
  10443. } else {
  10444. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10445. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10446. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10447. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10448. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10449. }
  10450. } else {
  10451. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10452. }
  10453. }
  10454. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10455. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10456. new_type = GGML_TYPE_Q4_K;
  10457. }
  10458. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10459. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10460. }
  10461. else if (name.find("ffn_gate") != std::string::npos) {
  10462. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10463. int i_layer = info.first, n_layer = info.second;
  10464. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10465. new_type = GGML_TYPE_IQ3_XXS;
  10466. }
  10467. ++qs.i_ffn_gate;
  10468. }
  10469. else if (name.find("ffn_up") != std::string::npos) {
  10470. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10471. int i_layer = info.first, n_layer = info.second;
  10472. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10473. new_type = GGML_TYPE_IQ3_XXS;
  10474. }
  10475. ++qs.i_ffn_up;
  10476. }
  10477. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10478. //}
  10479. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10480. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10481. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10482. //}
  10483. // This can be used to reduce the size of the Q5_K_S model.
  10484. // The associated PPL increase is fully in line with the size reduction
  10485. //else {
  10486. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10487. //}
  10488. bool convert_incompatible_tensor = false;
  10489. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10490. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10491. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10492. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  10493. int nx = tensor->ne[0];
  10494. int ny = tensor->ne[1];
  10495. if (nx % QK_K != 0) {
  10496. LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for %s", __func__, nx, ny, QK_K, ggml_type_name(new_type));
  10497. convert_incompatible_tensor = true;
  10498. } else {
  10499. ++qs.n_k_quantized;
  10500. }
  10501. }
  10502. if (convert_incompatible_tensor) {
  10503. switch (new_type) {
  10504. case GGML_TYPE_IQ2_XXS:
  10505. case GGML_TYPE_IQ2_XS:
  10506. case GGML_TYPE_IQ2_S:
  10507. case GGML_TYPE_IQ3_XXS:
  10508. case GGML_TYPE_IQ3_S:
  10509. case GGML_TYPE_IQ1_S:
  10510. case GGML_TYPE_Q2_K:
  10511. case GGML_TYPE_Q3_K:
  10512. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10513. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10514. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10515. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10516. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10517. }
  10518. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10519. ++qs.n_fallback;
  10520. }
  10521. return new_type;
  10522. }
  10523. static size_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int chunk_size, int nrows, int n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  10524. std::mutex mutex;
  10525. int counter = 0;
  10526. size_t new_size = 0;
  10527. if (nthread < 2) {
  10528. // single-thread
  10529. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10530. }
  10531. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10532. nrows, n_per_row, imatrix]() {
  10533. const int nrows_per_chunk = chunk_size / n_per_row;
  10534. size_t local_size = 0;
  10535. while (true) {
  10536. std::unique_lock<std::mutex> lock(mutex);
  10537. int first_row = counter; counter += nrows_per_chunk;
  10538. if (first_row >= nrows) {
  10539. if (local_size > 0) {
  10540. new_size += local_size;
  10541. }
  10542. break;
  10543. }
  10544. lock.unlock();
  10545. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10546. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10547. }
  10548. };
  10549. for (int it = 0; it < nthread - 1; ++it) {
  10550. workers.emplace_back(compute);
  10551. }
  10552. compute();
  10553. for (auto & w : workers) { w.join(); }
  10554. workers.clear();
  10555. return new_size;
  10556. }
  10557. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10558. ggml_type default_type;
  10559. llama_ftype ftype = params->ftype;
  10560. switch (params->ftype) {
  10561. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10562. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10563. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10564. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10565. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10566. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10567. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10568. // K-quants
  10569. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10570. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10571. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10572. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10573. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10574. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10575. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10576. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10577. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10578. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10579. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10580. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10581. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10582. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10583. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10584. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10585. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10586. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10587. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10588. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10589. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10590. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10591. }
  10592. int nthread = params->nthread;
  10593. if (nthread <= 0) {
  10594. nthread = std::thread::hardware_concurrency();
  10595. }
  10596. // mmap consistently increases speed Linux, and also increases speed on Windows with
  10597. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  10598. #if defined(__linux__) || defined(_WIN32)
  10599. constexpr bool use_mmap = true;
  10600. #else
  10601. constexpr bool use_mmap = false;
  10602. #endif
  10603. llama_model_kv_override * kv_overrides = nullptr;
  10604. if (params->kv_overrides) {
  10605. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  10606. kv_overrides = v->data();
  10607. }
  10608. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  10609. ml.init_mappings(false); // no prefetching?
  10610. llama_model model;
  10611. llm_load_arch(ml, model);
  10612. llm_load_hparams(ml, model);
  10613. struct quantize_state_internal qs(model, params);
  10614. if (params->only_copy) {
  10615. ftype = model.ftype;
  10616. }
  10617. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  10618. if (params->imatrix) {
  10619. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  10620. if (imatrix_data) {
  10621. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  10622. qs.has_imatrix = true;
  10623. }
  10624. }
  10625. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  10626. struct gguf_context * ctx_out = gguf_init_empty();
  10627. // copy the KV pairs from the input file
  10628. gguf_set_kv (ctx_out, ml.meta);
  10629. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  10630. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  10631. if (params->kv_overrides) {
  10632. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  10633. for (auto & o : overrides) {
  10634. if (o.key[0] == 0) break;
  10635. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  10636. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  10637. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  10638. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  10639. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  10640. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  10641. } else {
  10642. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  10643. }
  10644. }
  10645. }
  10646. for (int i = 0; i < ml.n_tensors; ++i) {
  10647. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10648. const std::string name = ggml_get_name(meta);
  10649. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10650. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  10651. ++qs.n_attention_wv;
  10652. } else if (name.find("ffn_down") != std::string::npos) {
  10653. ++qs.n_ffn_down;
  10654. } else if (name.find("ffn_gate") != std::string::npos) {
  10655. ++qs.n_ffn_gate;
  10656. } else if (name.find("ffn_up") != std::string::npos) {
  10657. ++qs.n_ffn_up;
  10658. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  10659. qs.has_output = true;
  10660. }
  10661. }
  10662. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t) qs.n_attention_wv != model.hparams.n_layer) {
  10663. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  10664. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  10665. }
  10666. size_t total_size_org = 0;
  10667. size_t total_size_new = 0;
  10668. std::vector<std::thread> workers;
  10669. workers.reserve(nthread);
  10670. int idx = 0;
  10671. std::vector<no_init<uint8_t>> read_data;
  10672. std::vector<no_init<uint8_t>> work;
  10673. std::vector<no_init<float>> f32_conv_buf;
  10674. // populate the original tensors so we get an initial meta data
  10675. for (int i = 0; i < ml.n_tensors; ++i) {
  10676. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10677. gguf_add_tensor(ctx_out, meta);
  10678. }
  10679. std::ofstream fout(fname_out, std::ios::binary);
  10680. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  10681. const size_t meta_size = gguf_get_meta_size(ctx_out);
  10682. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  10683. // placeholder for the meta data
  10684. ::zeros(fout, meta_size);
  10685. for (int i = 0; i < ml.n_tensors; ++i) {
  10686. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  10687. const std::string name = ggml_get_name(tensor);
  10688. if (!ml.use_mmap) {
  10689. if (read_data.size() < ggml_nbytes(tensor)) {
  10690. read_data.resize(ggml_nbytes(tensor));
  10691. }
  10692. tensor->data = read_data.data();
  10693. }
  10694. ml.load_data_for(tensor);
  10695. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  10696. ++idx, ml.n_tensors,
  10697. ggml_get_name(tensor),
  10698. llama_format_tensor_shape(tensor).c_str(),
  10699. ggml_type_name(tensor->type));
  10700. // This used to be a regex, but <regex> has an extreme cost to compile times.
  10701. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  10702. // quantize only 2D tensors
  10703. quantize &= (ggml_n_dims(tensor) == 2);
  10704. quantize &= params->quantize_output_tensor || name != "output.weight";
  10705. quantize &= !params->only_copy;
  10706. // do not quantize expert gating tensors
  10707. // NOTE: can't use LLM_TN here because the layer number is not known
  10708. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  10709. // do not quantize positional embeddings and token types (BERT)
  10710. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  10711. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  10712. // do not quantize Mamba's small yet 2D weights
  10713. // NOTE: can't use LLM_TN here because the layer number is not known
  10714. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  10715. quantize &= name.find("ssm_x.weight") == std::string::npos;
  10716. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  10717. enum ggml_type new_type;
  10718. void * new_data;
  10719. size_t new_size;
  10720. if (quantize) {
  10721. new_type = default_type;
  10722. // get more optimal quantization type based on the tensor shape, layer, etc.
  10723. if (!params->pure && ggml_is_quantized(default_type)) {
  10724. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  10725. }
  10726. // If we've decided to quantize to the same type the tensor is already
  10727. // in then there's nothing to do.
  10728. quantize = tensor->type != new_type;
  10729. }
  10730. if (!quantize) {
  10731. new_type = tensor->type;
  10732. new_data = tensor->data;
  10733. new_size = ggml_nbytes(tensor);
  10734. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  10735. } else {
  10736. const size_t nelements = ggml_nelements(tensor);
  10737. const float * imatrix = nullptr;
  10738. if (imatrix_data) {
  10739. auto it = imatrix_data->find(tensor->name);
  10740. if (it == imatrix_data->end()) {
  10741. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  10742. } else {
  10743. if (it->second.size() == (size_t)tensor->ne[0]) {
  10744. imatrix = it->second.data();
  10745. } else {
  10746. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  10747. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  10748. }
  10749. }
  10750. }
  10751. if ((new_type == GGML_TYPE_IQ2_XXS ||
  10752. new_type == GGML_TYPE_IQ2_XS ||
  10753. new_type == GGML_TYPE_IQ2_S ||
  10754. new_type == GGML_TYPE_IQ1_S ||
  10755. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  10756. LLAMA_LOG_ERROR("\n\n============================================================\n");
  10757. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  10758. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  10759. LLAMA_LOG_ERROR("============================================================\n\n");
  10760. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  10761. }
  10762. float * f32_data;
  10763. if (tensor->type == GGML_TYPE_F32) {
  10764. f32_data = (float *) tensor->data;
  10765. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  10766. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  10767. } else {
  10768. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  10769. f32_data = (float *) f32_conv_buf.data();
  10770. }
  10771. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  10772. fflush(stdout);
  10773. if (work.size() < nelements * 4) {
  10774. work.resize(nelements * 4); // upper bound on size
  10775. }
  10776. new_data = work.data();
  10777. const int n_per_row = tensor->ne[0];
  10778. const int nrows = nelements / n_per_row;
  10779. static const int min_chunk_size = 32 * 512;
  10780. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  10781. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  10782. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  10783. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  10784. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  10785. }
  10786. total_size_org += ggml_nbytes(tensor);
  10787. total_size_new += new_size;
  10788. // update the gguf meta data as we go
  10789. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  10790. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  10791. // write tensor data + padding
  10792. fout.write((const char *) new_data, new_size);
  10793. zeros(fout, GGML_PAD(new_size, align) - new_size);
  10794. }
  10795. // go back to beginning of file and write the updated meta data
  10796. {
  10797. fout.seekp(0);
  10798. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  10799. gguf_get_meta_data(ctx_out, data.data());
  10800. fout.write((const char *) data.data(), data.size());
  10801. }
  10802. fout.close();
  10803. gguf_free(ctx_out);
  10804. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  10805. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  10806. if (qs.n_fallback > 0) {
  10807. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  10808. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  10809. }
  10810. }
  10811. static int llama_apply_lora_from_file_internal(
  10812. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  10813. ) {
  10814. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  10815. const int64_t t_start_lora_us = ggml_time_us();
  10816. llama_file fin(path_lora, "rb");
  10817. // verify magic and version
  10818. {
  10819. uint32_t magic = fin.read_u32();
  10820. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  10821. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  10822. return 1;
  10823. }
  10824. uint32_t format_version = fin.read_u32();
  10825. if (format_version != 1) {
  10826. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  10827. return 1;
  10828. }
  10829. }
  10830. int32_t lora_r = fin.read_u32();
  10831. int32_t lora_alpha = fin.read_u32();
  10832. float scaling = scale * (float)lora_alpha / (float)lora_r;
  10833. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  10834. // load base model
  10835. std::unique_ptr<llama_model_loader> ml;
  10836. if (path_base_model) {
  10837. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  10838. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  10839. ml->init_mappings(/*prefetch*/ false); // no prefetching
  10840. }
  10841. struct tensor_meta {
  10842. std::string name;
  10843. ggml_type type;
  10844. int32_t ne[2];
  10845. size_t offset;
  10846. };
  10847. std::map<std::string, tensor_meta> tensor_meta_map;
  10848. // load all tensor meta
  10849. while (true) {
  10850. if (fin.tell() == fin.size) {
  10851. // eof
  10852. break;
  10853. }
  10854. int32_t n_dims;
  10855. int32_t name_len;
  10856. int32_t ftype;
  10857. fin.read_raw(&n_dims, sizeof(n_dims));
  10858. fin.read_raw(&name_len, sizeof(name_len));
  10859. fin.read_raw(&ftype, sizeof(ftype));
  10860. if (n_dims != 1 && n_dims != 2) {
  10861. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  10862. return 1;
  10863. }
  10864. int32_t ne[2] = { 1, 1 };
  10865. for (int i = 0; i < n_dims; ++i) {
  10866. fin.read_raw(&ne[i], sizeof(ne[i]));
  10867. }
  10868. std::string name;
  10869. {
  10870. GGML_ASSERT(name_len < GGML_MAX_NAME);
  10871. char buf[GGML_MAX_NAME];
  10872. fin.read_raw(buf, name_len);
  10873. name = std::string(buf, name_len);
  10874. }
  10875. // check for lora suffix
  10876. std::string lora_suffix;
  10877. if (name.length() > 6) {
  10878. lora_suffix = name.substr(name.length() - 6);
  10879. }
  10880. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  10881. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  10882. return 1;
  10883. }
  10884. // tensor type
  10885. ggml_type wtype;
  10886. switch (ftype) {
  10887. case 0: wtype = GGML_TYPE_F32; break;
  10888. case 1: wtype = GGML_TYPE_F16; break;
  10889. default:
  10890. {
  10891. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  10892. __func__, ftype);
  10893. return 1;
  10894. }
  10895. }
  10896. // data offset
  10897. size_t offset = fin.tell();
  10898. offset = (offset + 31) & -32;
  10899. // skip tensor data
  10900. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  10901. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  10902. }
  10903. bool warned = false;
  10904. int n_tensors = 0;
  10905. // apply
  10906. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  10907. if (backend_cpu == nullptr) {
  10908. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  10909. return 1;
  10910. }
  10911. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  10912. std::vector<no_init<uint8_t>> read_buf;
  10913. for (const auto & it : model.tensors_by_name) {
  10914. const std::string & base_name = it.first;
  10915. ggml_tensor * model_t = it.second;
  10916. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  10917. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  10918. continue;
  10919. }
  10920. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  10921. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  10922. ggml_init_params lora_init_params = {
  10923. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  10924. /* .mem_buffer */ nullptr,
  10925. /* .no_alloc */ true,
  10926. };
  10927. ggml_context * lora_ctx = ggml_init(lora_init_params);
  10928. if (lora_ctx == nullptr) {
  10929. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  10930. ggml_backend_free(backend_cpu);
  10931. return 1;
  10932. }
  10933. // create tensors
  10934. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  10935. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  10936. ggml_set_name(loraA, metaA.name.c_str());
  10937. ggml_set_name(loraB, metaB.name.c_str());
  10938. ggml_tensor * base_t;
  10939. if (ml) {
  10940. if (!ml->get_tensor_meta(base_name.c_str())) {
  10941. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  10942. return 1;
  10943. }
  10944. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  10945. } else {
  10946. base_t = ggml_dup_tensor(lora_ctx, model_t);
  10947. }
  10948. ggml_set_name(base_t, base_name.c_str());
  10949. // allocate in backend buffer
  10950. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10951. if (lora_buf == nullptr) {
  10952. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  10953. return 1;
  10954. }
  10955. // load tensor data
  10956. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  10957. read_buf.resize(ggml_nbytes(tensor));
  10958. fin.seek(tensor_meta.offset, SEEK_SET);
  10959. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  10960. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  10961. };
  10962. load_tensor(metaA, loraA);
  10963. load_tensor(metaB, loraB);
  10964. // load base model tensor data
  10965. if (ml) {
  10966. ml->load_data_for(base_t);
  10967. } else {
  10968. ggml_backend_tensor_copy(model_t, base_t);
  10969. }
  10970. if (ggml_is_quantized(base_t->type) && !warned) {
  10971. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  10972. "use a f16 or f32 base model with --lora-base\n", __func__);
  10973. warned = true;
  10974. }
  10975. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  10976. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  10977. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  10978. ggml_free(lora_ctx);
  10979. ggml_backend_buffer_free(lora_buf);
  10980. ggml_backend_free(backend_cpu);
  10981. return 1;
  10982. }
  10983. auto build_lora_graph = [&]() {
  10984. // w = w + BA*s
  10985. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  10986. ggml_set_name(BA, "BA");
  10987. if (scaling != 1.0f) {
  10988. BA = ggml_scale(lora_ctx, BA, scaling);
  10989. ggml_set_name(BA, "BA_scaled");
  10990. }
  10991. ggml_tensor * r;
  10992. r = ggml_add_inplace(lora_ctx, base_t, BA);
  10993. ggml_set_name(r, "r_add");
  10994. if (base_t->type != model_t->type) {
  10995. // convert the result to the model type
  10996. r = ggml_cast(lora_ctx, r, model_t->type);
  10997. ggml_set_name(r, "r_cast");
  10998. }
  10999. return r;
  11000. };
  11001. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11002. ggml_tensor * r = build_lora_graph();
  11003. ggml_build_forward_expand(gf, r);
  11004. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11005. if (graph_buf == nullptr) {
  11006. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11007. ggml_free(lora_ctx);
  11008. ggml_backend_buffer_free(lora_buf);
  11009. ggml_backend_free(backend_cpu);
  11010. return 1;
  11011. }
  11012. ggml_backend_graph_compute(backend_cpu, gf);
  11013. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11014. #if 0
  11015. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11016. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11017. // sched compute
  11018. ggml_build_forward_expand(gf, build_graph());
  11019. ggml_backend_sched_init_measure(sched, gf);
  11020. // create the graph again, since the previous one was destroyed by the measure
  11021. ggml_graph_clear(gf);
  11022. ggml_build_forward_expand(gf, build_graph());
  11023. ggml_backend_sched_graph_compute(sched, gf);
  11024. ggml_backend_sched_free(sched);
  11025. #endif
  11026. ggml_backend_buffer_free(lora_buf);
  11027. ggml_backend_buffer_free(graph_buf);
  11028. ggml_free(lora_ctx);
  11029. n_tensors++;
  11030. if (n_tensors % 4 == 0) {
  11031. LLAMA_LOG_INFO(".");
  11032. }
  11033. }
  11034. ggml_backend_free(backend_cpu);
  11035. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11036. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11037. return 0;
  11038. }
  11039. //
  11040. // interface implementation
  11041. //
  11042. struct llama_model_params llama_model_default_params() {
  11043. struct llama_model_params result = {
  11044. /*.n_gpu_layers =*/ 0,
  11045. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11046. /*.main_gpu =*/ 0,
  11047. /*.tensor_split =*/ nullptr,
  11048. /*.progress_callback =*/ nullptr,
  11049. /*.progress_callback_user_data =*/ nullptr,
  11050. /*.kv_overrides =*/ nullptr,
  11051. /*.vocab_only =*/ false,
  11052. /*.use_mmap =*/ true,
  11053. /*.use_mlock =*/ false,
  11054. };
  11055. #ifdef GGML_USE_METAL
  11056. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11057. result.n_gpu_layers = 999;
  11058. #endif
  11059. return result;
  11060. }
  11061. struct llama_context_params llama_context_default_params() {
  11062. struct llama_context_params result = {
  11063. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11064. /*.n_ctx =*/ 512,
  11065. /*.n_batch =*/ 2048,
  11066. /*.n_ubatch =*/ 512,
  11067. /*.n_seq_max =*/ 1,
  11068. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11069. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11070. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11071. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11072. /*.rope_freq_base =*/ 0.0f,
  11073. /*.rope_freq_scale =*/ 0.0f,
  11074. /*.yarn_ext_factor =*/ -1.0f,
  11075. /*.yarn_attn_factor =*/ 1.0f,
  11076. /*.yarn_beta_fast =*/ 32.0f,
  11077. /*.yarn_beta_slow =*/ 1.0f,
  11078. /*.yarn_orig_ctx =*/ 0,
  11079. /*.defrag_thold =*/ -1.0f,
  11080. /*.cb_eval =*/ nullptr,
  11081. /*.cb_eval_user_data =*/ nullptr,
  11082. /*.type_k =*/ GGML_TYPE_F16,
  11083. /*.type_v =*/ GGML_TYPE_F16,
  11084. /*.logits_all =*/ false,
  11085. /*.embeddings =*/ false,
  11086. /*.offload_kqv =*/ true,
  11087. /*.abort_callback =*/ nullptr,
  11088. /*.abort_callback_data =*/ nullptr,
  11089. };
  11090. return result;
  11091. }
  11092. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11093. struct llama_model_quantize_params result = {
  11094. /*.nthread =*/ 0,
  11095. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11096. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11097. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11098. /*.allow_requantize =*/ false,
  11099. /*.quantize_output_tensor =*/ true,
  11100. /*.only_copy =*/ false,
  11101. /*.pure =*/ false,
  11102. /*.imatrix =*/ nullptr,
  11103. /*.kv_overrides =*/ nullptr,
  11104. };
  11105. return result;
  11106. }
  11107. size_t llama_max_devices(void) {
  11108. #if defined(GGML_USE_METAL)
  11109. return 1;
  11110. #elif defined(GGML_USE_CUDA)
  11111. return GGML_CUDA_MAX_DEVICES;
  11112. #elif defined(GGML_USE_SYCL)
  11113. return GGML_SYCL_MAX_DEVICES;
  11114. #elif defined(GGML_USE_VULKAN)
  11115. return GGML_VK_MAX_DEVICES;
  11116. #else
  11117. return 1;
  11118. #endif
  11119. }
  11120. bool llama_supports_mmap(void) {
  11121. return llama_mmap::SUPPORTED;
  11122. }
  11123. bool llama_supports_mlock(void) {
  11124. return llama_mlock::SUPPORTED;
  11125. }
  11126. bool llama_supports_gpu_offload(void) {
  11127. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11128. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11129. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11130. return true;
  11131. #else
  11132. return false;
  11133. #endif
  11134. }
  11135. void llama_backend_init(void) {
  11136. ggml_time_init();
  11137. // needed to initialize f16 tables
  11138. {
  11139. struct ggml_init_params params = { 0, NULL, false };
  11140. struct ggml_context * ctx = ggml_init(params);
  11141. ggml_free(ctx);
  11142. }
  11143. #ifdef GGML_USE_MPI
  11144. ggml_mpi_backend_init();
  11145. #endif
  11146. }
  11147. void llama_numa_init(enum ggml_numa_strategy numa) {
  11148. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11149. ggml_numa_init(numa);
  11150. }
  11151. }
  11152. void llama_backend_free(void) {
  11153. #ifdef GGML_USE_MPI
  11154. ggml_mpi_backend_free();
  11155. #endif
  11156. ggml_quantize_free();
  11157. }
  11158. int64_t llama_time_us(void) {
  11159. return ggml_time_us();
  11160. }
  11161. struct llama_model * llama_load_model_from_file(
  11162. const char * path_model,
  11163. struct llama_model_params params) {
  11164. ggml_time_init();
  11165. llama_model * model = new llama_model;
  11166. unsigned cur_percentage = 0;
  11167. if (params.progress_callback == NULL) {
  11168. params.progress_callback_user_data = &cur_percentage;
  11169. params.progress_callback = [](float progress, void * ctx) {
  11170. unsigned * cur_percentage_p = (unsigned *) ctx;
  11171. unsigned percentage = (unsigned) (100 * progress);
  11172. while (percentage > *cur_percentage_p) {
  11173. *cur_percentage_p = percentage;
  11174. LLAMA_LOG_INFO(".");
  11175. if (percentage >= 100) {
  11176. LLAMA_LOG_INFO("\n");
  11177. }
  11178. }
  11179. return true;
  11180. };
  11181. }
  11182. int status = llama_model_load(path_model, *model, params);
  11183. GGML_ASSERT(status <= 0);
  11184. if (status < 0) {
  11185. if (status == -1) {
  11186. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11187. } else if (status == -2) {
  11188. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11189. }
  11190. delete model;
  11191. return nullptr;
  11192. }
  11193. return model;
  11194. }
  11195. void llama_free_model(struct llama_model * model) {
  11196. delete model;
  11197. }
  11198. struct llama_context * llama_new_context_with_model(
  11199. struct llama_model * model,
  11200. struct llama_context_params params) {
  11201. if (!model) {
  11202. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11203. return nullptr;
  11204. }
  11205. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11206. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11207. return nullptr;
  11208. }
  11209. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11210. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11211. return nullptr;
  11212. }
  11213. llama_context * ctx = new llama_context(*model);
  11214. const auto & hparams = model->hparams;
  11215. auto & cparams = ctx->cparams;
  11216. // TODO: maybe add n_seq_max here too
  11217. cparams.n_threads = params.n_threads;
  11218. cparams.n_threads_batch = params.n_threads_batch;
  11219. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11220. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11221. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11222. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11223. cparams.defrag_thold = params.defrag_thold;
  11224. cparams.embeddings = params.embeddings;
  11225. cparams.offload_kqv = params.offload_kqv;
  11226. cparams.pooling_type = params.pooling_type;
  11227. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11228. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11229. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11230. // this is necessary due to kv_self.n being padded later during inference
  11231. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11232. // with causal attention, the batch size is limited by the context size
  11233. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11234. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11235. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11236. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11237. hparams.n_ctx_train;
  11238. cparams.cb_eval = params.cb_eval;
  11239. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11240. auto rope_scaling_type = params.rope_scaling_type;
  11241. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11242. rope_scaling_type = hparams.rope_scaling_type_train;
  11243. }
  11244. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11245. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11246. }
  11247. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11248. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11249. }
  11250. cparams.causal_attn = hparams.causal_attn;
  11251. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11252. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11253. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11254. } else {
  11255. cparams.pooling_type = hparams.pooling_type;
  11256. }
  11257. }
  11258. if (params.seed == LLAMA_DEFAULT_SEED) {
  11259. params.seed = time(NULL);
  11260. }
  11261. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11262. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11263. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11264. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11265. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11266. ctx->abort_callback = params.abort_callback;
  11267. ctx->abort_callback_data = params.abort_callback_data;
  11268. ctx->rng = std::mt19937(params.seed);
  11269. ctx->logits_all = params.logits_all;
  11270. uint32_t kv_size = cparams.n_ctx;
  11271. ggml_type type_k = params.type_k;
  11272. ggml_type type_v = params.type_v;
  11273. // Mamba only needs a constant number of KV cache cells per sequence
  11274. if (model->arch == LLM_ARCH_MAMBA) {
  11275. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11276. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11277. // it's probably best to keep as much precision as possible for the states
  11278. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11279. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11280. }
  11281. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11282. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11283. if (!hparams.vocab_only) {
  11284. // initialize backends
  11285. #ifdef GGML_USE_METAL
  11286. if (model->n_gpu_layers > 0) {
  11287. ctx->backend_metal = ggml_backend_metal_init();
  11288. if (ctx->backend_metal == nullptr) {
  11289. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11290. llama_free(ctx);
  11291. return nullptr;
  11292. }
  11293. ctx->backends.push_back(ctx->backend_metal);
  11294. }
  11295. #elif defined(GGML_USE_CUDA)
  11296. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11297. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11298. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11299. if (backend == nullptr) {
  11300. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11301. llama_free(ctx);
  11302. return nullptr;
  11303. }
  11304. ctx->backends.push_back(backend);
  11305. } else {
  11306. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11307. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11308. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11309. if (backend == nullptr) {
  11310. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11311. llama_free(ctx);
  11312. return nullptr;
  11313. }
  11314. ctx->backends.push_back(backend);
  11315. }
  11316. }
  11317. #elif defined(GGML_USE_VULKAN)
  11318. if (model->n_gpu_layers > 0) {
  11319. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11320. ggml_backend_t backend = ggml_backend_vk_init(device);
  11321. if (backend == nullptr) {
  11322. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11323. llama_free(ctx);
  11324. return nullptr;
  11325. }
  11326. ctx->backends.push_back(backend);
  11327. }
  11328. }
  11329. #elif defined(GGML_USE_SYCL)
  11330. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11331. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11332. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11333. if (backend == nullptr) {
  11334. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11335. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11336. llama_free(ctx);
  11337. return nullptr;
  11338. }
  11339. ctx->backends.push_back(backend);
  11340. } else {
  11341. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11342. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11343. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11344. if (backend == nullptr) {
  11345. int id_list[GGML_SYCL_MAX_DEVICES];
  11346. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11347. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11348. llama_free(ctx);
  11349. return nullptr;
  11350. }
  11351. ctx->backends.push_back(backend);
  11352. }
  11353. }
  11354. #elif defined(GGML_USE_KOMPUTE)
  11355. if (model->n_gpu_layers > 0) {
  11356. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11357. if (backend == nullptr) {
  11358. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11359. llama_free(ctx);
  11360. return nullptr;
  11361. }
  11362. ctx->backends.push_back(backend);
  11363. }
  11364. #endif
  11365. ctx->backend_cpu = ggml_backend_cpu_init();
  11366. if (ctx->backend_cpu == nullptr) {
  11367. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11368. llama_free(ctx);
  11369. return nullptr;
  11370. }
  11371. ctx->backends.push_back(ctx->backend_cpu);
  11372. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11373. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11374. llama_free(ctx);
  11375. return nullptr;
  11376. }
  11377. {
  11378. size_t memory_size_k = 0;
  11379. size_t memory_size_v = 0;
  11380. for (auto & k : ctx->kv_self.k_l) {
  11381. memory_size_k += ggml_nbytes(k);
  11382. }
  11383. for (auto & v : ctx->kv_self.v_l) {
  11384. memory_size_v += ggml_nbytes(v);
  11385. }
  11386. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11387. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11388. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11389. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11390. }
  11391. // graph outputs buffer
  11392. {
  11393. // resized during inference, reserve maximum
  11394. ctx->logits_size = hparams.n_vocab*cparams.n_batch;
  11395. ctx->embd_size = params.embeddings ? hparams.n_embd*cparams.n_batch : 0;
  11396. const size_t buf_output_size = (ctx->logits_size + ctx->embd_size)*sizeof(float);
  11397. ctx->buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buf_output_size);
  11398. if (ctx->buf_output == nullptr) {
  11399. LLAMA_LOG_ERROR("%s: failed to allocate logits buffer\n", __func__);
  11400. llama_free(ctx);
  11401. return nullptr;
  11402. }
  11403. ggml_backend_buffer_clear(ctx->buf_output, 0);
  11404. ctx->logits = (float *) ggml_backend_buffer_get_base(ctx->buf_output);
  11405. if (params.embeddings) {
  11406. ctx->embd = ctx->logits + ctx->logits_size;
  11407. }
  11408. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11409. ggml_backend_buffer_name(ctx->buf_output),
  11410. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11411. }
  11412. // scheduler and compute buffers
  11413. {
  11414. // buffer types used for the compute buffer of each backend
  11415. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11416. for (auto * backend : ctx->backends) {
  11417. if (ggml_backend_is_cpu(backend)) {
  11418. // use host buffers for the CPU backend compute buffer
  11419. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11420. } else {
  11421. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11422. }
  11423. }
  11424. // buffer used to store the computation graph and the tensor meta data
  11425. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11426. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11427. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11428. #ifndef GGML_USE_CUDA
  11429. // pipeline parallelism requires support for async compute and events
  11430. // currently this is only implemented in the CUDA backend
  11431. pipeline_parallel = false;
  11432. #endif
  11433. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11434. if (pipeline_parallel) {
  11435. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11436. }
  11437. // build worst-case graph
  11438. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11439. int n_past = cparams.n_ctx - n_tokens;
  11440. llama_token token = llama_token_bos(&ctx->model); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  11441. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11442. // initialize scheduler with the worst-case graph
  11443. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11444. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11445. llama_free(ctx);
  11446. return nullptr;
  11447. }
  11448. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11449. ggml_backend_t backend = ctx->backends[i];
  11450. ggml_backend_buffer_type_t buft = backend_buft[i];
  11451. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11452. if (size > 1) {
  11453. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11454. ggml_backend_buft_name(buft),
  11455. size / 1024.0 / 1024.0);
  11456. }
  11457. }
  11458. // note: the number of splits during measure is higher than during inference due to the kv shift
  11459. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11460. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  11461. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  11462. }
  11463. }
  11464. #ifdef GGML_USE_MPI
  11465. ctx->ctx_mpi = ggml_mpi_init();
  11466. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11467. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11468. // TODO: needs fix after #3228
  11469. GGML_ASSERT(false && "not implemented");
  11470. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11471. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11472. llama_backend_free();
  11473. exit(1);
  11474. }
  11475. #endif
  11476. return ctx;
  11477. }
  11478. void llama_free(struct llama_context * ctx) {
  11479. delete ctx;
  11480. }
  11481. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11482. return &ctx->model;
  11483. }
  11484. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11485. return ctx->cparams.n_ctx;
  11486. }
  11487. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11488. return ctx->cparams.n_batch;
  11489. }
  11490. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11491. return ctx->cparams.n_ubatch;
  11492. }
  11493. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11494. return ctx->kv_self.size;
  11495. }
  11496. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11497. return model->vocab.type;
  11498. }
  11499. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11500. switch (model->arch) {
  11501. // these models do not use RoPE
  11502. case LLM_ARCH_GPT2:
  11503. case LLM_ARCH_GPTJ:
  11504. case LLM_ARCH_GPTNEOX:
  11505. case LLM_ARCH_MPT:
  11506. case LLM_ARCH_REFACT:
  11507. case LLM_ARCH_BLOOM:
  11508. case LLM_ARCH_MAMBA:
  11509. return LLAMA_ROPE_TYPE_NONE;
  11510. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11511. case LLM_ARCH_LLAMA:
  11512. case LLM_ARCH_BAICHUAN:
  11513. case LLM_ARCH_STARCODER:
  11514. case LLM_ARCH_PLAMO:
  11515. case LLM_ARCH_CODESHELL:
  11516. case LLM_ARCH_ORION:
  11517. case LLM_ARCH_INTERNLM2:
  11518. case LLM_ARCH_MINICPM:
  11519. case LLM_ARCH_COMMAND_R:
  11520. return LLAMA_ROPE_TYPE_NORM;
  11521. // the pairs of head values are offset by n_rot/2
  11522. case LLM_ARCH_FALCON:
  11523. case LLM_ARCH_GROK:
  11524. case LLM_ARCH_PERSIMMON:
  11525. case LLM_ARCH_BERT:
  11526. case LLM_ARCH_NOMIC_BERT:
  11527. case LLM_ARCH_STABLELM:
  11528. case LLM_ARCH_QWEN:
  11529. case LLM_ARCH_QWEN2:
  11530. case LLM_ARCH_PHI2:
  11531. case LLM_ARCH_GEMMA:
  11532. case LLM_ARCH_STARCODER2:
  11533. return LLAMA_ROPE_TYPE_NEOX;
  11534. // all model arches should be listed explicitly here
  11535. case LLM_ARCH_UNKNOWN:
  11536. GGML_ASSERT(false && "unknown architecture");
  11537. break;
  11538. }
  11539. return LLAMA_ROPE_TYPE_NONE;
  11540. }
  11541. int32_t llama_n_vocab(const struct llama_model * model) {
  11542. return model->hparams.n_vocab;
  11543. }
  11544. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11545. return model->hparams.n_ctx_train;
  11546. }
  11547. int32_t llama_n_embd(const struct llama_model * model) {
  11548. return model->hparams.n_embd;
  11549. }
  11550. int32_t llama_n_layer(const struct llama_model * model) {
  11551. return model->hparams.n_layer;
  11552. }
  11553. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11554. return model->hparams.rope_freq_scale_train;
  11555. }
  11556. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11557. const auto & it = model->gguf_kv.find(key);
  11558. if (it == model->gguf_kv.end()) {
  11559. if (buf_size > 0) {
  11560. buf[0] = '\0';
  11561. }
  11562. return -1;
  11563. }
  11564. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11565. }
  11566. int32_t llama_model_meta_count(const struct llama_model * model) {
  11567. return (int)model->gguf_kv.size();
  11568. }
  11569. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11570. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11571. if (buf_size > 0) {
  11572. buf[0] = '\0';
  11573. }
  11574. return -1;
  11575. }
  11576. auto it = model->gguf_kv.begin();
  11577. std::advance(it, i);
  11578. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11579. }
  11580. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11581. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11582. if (buf_size > 0) {
  11583. buf[0] = '\0';
  11584. }
  11585. return -1;
  11586. }
  11587. auto it = model->gguf_kv.begin();
  11588. std::advance(it, i);
  11589. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11590. }
  11591. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  11592. return snprintf(buf, buf_size, "%s %s %s",
  11593. llama_model_arch_name(model->arch),
  11594. llama_model_type_name(model->type),
  11595. llama_model_ftype_name(model->ftype).c_str());
  11596. }
  11597. uint64_t llama_model_size(const struct llama_model * model) {
  11598. uint64_t size = 0;
  11599. for (const auto & it : model->tensors_by_name) {
  11600. size += ggml_nbytes(it.second);
  11601. }
  11602. return size;
  11603. }
  11604. uint64_t llama_model_n_params(const struct llama_model * model) {
  11605. uint64_t nparams = 0;
  11606. for (const auto & it : model->tensors_by_name) {
  11607. nparams += ggml_nelements(it.second);
  11608. }
  11609. return nparams;
  11610. }
  11611. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  11612. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  11613. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  11614. return it.first == name;
  11615. });
  11616. if (it == model->tensors_by_name.end()) {
  11617. return nullptr;
  11618. }
  11619. return it->second;
  11620. }
  11621. uint32_t llama_model_quantize(
  11622. const char * fname_inp,
  11623. const char * fname_out,
  11624. const llama_model_quantize_params * params) {
  11625. try {
  11626. llama_model_quantize_internal(fname_inp, fname_out, params);
  11627. return 0;
  11628. } catch (const std::exception & err) {
  11629. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  11630. return 1;
  11631. }
  11632. }
  11633. int32_t llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  11634. try {
  11635. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  11636. } catch (const std::exception & err) {
  11637. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  11638. return 1;
  11639. }
  11640. }
  11641. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  11642. GGML_ASSERT(cvec.tensors.empty());
  11643. GGML_ASSERT(cvec.ctxs.empty());
  11644. GGML_ASSERT(cvec.bufs.empty());
  11645. // count layer buffer types
  11646. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  11647. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  11648. buft_layer_count[model.buft_layer[i].buft]++;
  11649. }
  11650. // allocate contexts
  11651. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  11652. for (auto & it : buft_layer_count) {
  11653. int n_layers = it.second;
  11654. struct ggml_init_params params = {
  11655. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  11656. /*.mem_buffer =*/ NULL,
  11657. /*.no_alloc =*/ true,
  11658. };
  11659. ggml_context * ctx = ggml_init(params);
  11660. if (!ctx) {
  11661. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  11662. return 1;
  11663. }
  11664. ctx_map[it.first] = ctx;
  11665. }
  11666. // make tensors
  11667. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  11668. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11669. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  11670. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  11671. cvec.tensors.push_back(tensor);
  11672. }
  11673. // allocate tensors / buffers and zero
  11674. for (auto it : ctx_map) {
  11675. ggml_backend_buffer_type_t buft = it.first;
  11676. ggml_context * ctx = it.second;
  11677. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  11678. if (!buf) {
  11679. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  11680. return false;
  11681. }
  11682. ggml_backend_buffer_clear(buf, 0);
  11683. cvec.ctxs.push_back(ctx);
  11684. cvec.bufs.push_back(buf);
  11685. }
  11686. return true;
  11687. }
  11688. int32_t llama_control_vector_apply(struct llama_context * lctx, const float * data, size_t len, int32_t n_embd, int32_t il_start, int32_t il_end) {
  11689. const llama_model & model = lctx->model;
  11690. llama_control_vector & cvec = lctx->cvec;
  11691. if (data == nullptr) {
  11692. // disable the current control vector (but leave allocated for later)
  11693. cvec.layer_start = -1;
  11694. cvec.layer_end = -1;
  11695. return 0;
  11696. }
  11697. if (n_embd != (int) model.hparams.n_embd) {
  11698. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  11699. return 1;
  11700. }
  11701. if (cvec.tensors.empty()) {
  11702. if (!llama_control_vector_init(cvec, model)) {
  11703. return 1;
  11704. }
  11705. }
  11706. cvec.layer_start = il_start;
  11707. cvec.layer_end = il_end;
  11708. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11709. assert(cvec.tensors[il] != nullptr);
  11710. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  11711. if (off + n_embd <= len) {
  11712. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  11713. }
  11714. }
  11715. return 0;
  11716. }
  11717. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  11718. struct llama_kv_cache_view result = {
  11719. /*.n_cells = */ 0,
  11720. /*.n_seq_max = */ n_seq_max,
  11721. /*.token_count = */ 0,
  11722. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  11723. /*.max_contiguous = */ 0,
  11724. /*.max_contiguous_idx = */ -1,
  11725. /*.cells = */ nullptr,
  11726. /*.cells_sequences = */ nullptr,
  11727. };
  11728. return result;
  11729. }
  11730. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  11731. if (view->cells != nullptr) {
  11732. free(view->cells);
  11733. view->cells = nullptr;
  11734. }
  11735. if (view->cells_sequences != nullptr) {
  11736. free(view->cells_sequences);
  11737. view->cells_sequences = nullptr;
  11738. }
  11739. }
  11740. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  11741. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  11742. view->n_cells = int32_t(ctx->kv_self.size);
  11743. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  11744. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  11745. view->cells = (struct llama_kv_cache_view_cell *)p;
  11746. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  11747. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  11748. view->cells_sequences = (llama_seq_id *)p;
  11749. }
  11750. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  11751. llama_kv_cache_view_cell * c_curr = view->cells;
  11752. llama_seq_id * cs_curr = view->cells_sequences;
  11753. int32_t used_cells = 0;
  11754. int32_t token_count = 0;
  11755. int32_t curr_contig_idx = -1;
  11756. uint32_t max_contig = 0;
  11757. int32_t max_contig_idx = -1;
  11758. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  11759. const size_t curr_size = kv_cells[i].seq_id.size();
  11760. token_count += curr_size;
  11761. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  11762. if (curr_size > 0) {
  11763. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  11764. max_contig = i - curr_contig_idx;
  11765. max_contig_idx = curr_contig_idx;
  11766. }
  11767. curr_contig_idx = -1;
  11768. } else if (curr_contig_idx < 0) {
  11769. curr_contig_idx = i;
  11770. }
  11771. int seq_idx = 0;
  11772. for (const llama_seq_id it : kv_cells[i].seq_id) {
  11773. if (seq_idx >= view->n_seq_max) {
  11774. break;
  11775. }
  11776. cs_curr[seq_idx] = it;
  11777. seq_idx++;
  11778. }
  11779. if (seq_idx != 0) {
  11780. used_cells++;
  11781. }
  11782. for (; seq_idx < view->n_seq_max; seq_idx++) {
  11783. cs_curr[seq_idx] = -1;
  11784. }
  11785. }
  11786. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  11787. max_contig_idx = curr_contig_idx;
  11788. max_contig = kv_cells.size() - curr_contig_idx;
  11789. }
  11790. view->max_contiguous = max_contig;
  11791. view->max_contiguous_idx = max_contig_idx;
  11792. view->token_count = token_count;
  11793. view->used_cells = used_cells;
  11794. if (uint32_t(used_cells) != ctx->kv_self.used) {
  11795. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  11796. __func__, ctx->kv_self.used, used_cells);
  11797. }
  11798. }
  11799. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  11800. int result = 0;
  11801. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  11802. result += ctx->kv_self.cells[i].seq_id.size();
  11803. }
  11804. return result;
  11805. }
  11806. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  11807. return ctx->kv_self.used;
  11808. }
  11809. void llama_kv_cache_clear(struct llama_context * ctx) {
  11810. llama_kv_cache_clear(ctx->kv_self);
  11811. }
  11812. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  11813. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  11814. }
  11815. void llama_kv_cache_seq_cp(struct llama_context * ctx, llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
  11816. if (seq_id_src == seq_id_dst) {
  11817. return;
  11818. }
  11819. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  11820. }
  11821. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  11822. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  11823. }
  11824. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  11825. if (delta == 0) {
  11826. return;
  11827. }
  11828. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  11829. }
  11830. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  11831. if (d == 1) {
  11832. return;
  11833. }
  11834. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  11835. }
  11836. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  11837. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  11838. }
  11839. void llama_kv_cache_defrag(struct llama_context * ctx) {
  11840. llama_kv_cache_defrag(ctx->kv_self);
  11841. }
  11842. void llama_kv_cache_update(struct llama_context * ctx) {
  11843. llama_kv_cache_update_internal(*ctx);
  11844. }
  11845. // Returns the *maximum* size of the state
  11846. size_t llama_get_state_size(const struct llama_context * ctx) {
  11847. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  11848. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  11849. const size_t s_rng_size = sizeof(size_t);
  11850. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  11851. const size_t s_logits_size = sizeof(size_t);
  11852. // assume worst case for logits although only currently set ones are serialized
  11853. const size_t s_logits = ctx->logits_size * sizeof(float);
  11854. const size_t s_embedding_size = sizeof(size_t);
  11855. const size_t s_embedding = ctx->embd_size * sizeof(float);
  11856. const size_t s_kv_buf_size = sizeof(size_t);
  11857. const size_t s_kv_head = sizeof(uint32_t);
  11858. const size_t s_kv_size = sizeof(uint32_t);
  11859. const size_t s_kv_used = sizeof(uint32_t);
  11860. const size_t s_kv = ctx->kv_self.total_size();
  11861. // TODO: assume the max is more than 1 seq_id per KV cell
  11862. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  11863. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  11864. const size_t s_total = (
  11865. + s_rng_size
  11866. + s_rng
  11867. + s_logits_size
  11868. + s_logits
  11869. + s_embedding_size
  11870. + s_embedding
  11871. + s_kv_buf_size
  11872. + s_kv_head
  11873. + s_kv_size
  11874. + s_kv_used
  11875. + s_kv
  11876. + s_kv_cells
  11877. );
  11878. return s_total;
  11879. }
  11880. // llama_context_data
  11881. struct llama_data_context {
  11882. virtual void write(const void * src, size_t size) = 0;
  11883. virtual size_t get_size_written() = 0;
  11884. virtual ~llama_data_context() = default;
  11885. };
  11886. struct llama_data_buffer_context : llama_data_context {
  11887. uint8_t * ptr;
  11888. size_t size_written = 0;
  11889. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  11890. void write(const void * src, size_t size) override {
  11891. memcpy(ptr, src, size);
  11892. ptr += size;
  11893. size_written += size;
  11894. }
  11895. size_t get_size_written() override {
  11896. return size_written;
  11897. }
  11898. };
  11899. struct llama_data_file_context : llama_data_context {
  11900. llama_file * file;
  11901. size_t size_written = 0;
  11902. llama_data_file_context(llama_file * f) : file(f) {}
  11903. void write(const void * src, size_t size) override {
  11904. file->write_raw(src, size);
  11905. size_written += size;
  11906. }
  11907. size_t get_size_written() override {
  11908. return size_written;
  11909. }
  11910. };
  11911. /** copy state data into either a buffer or file depending on the passed in context
  11912. *
  11913. * file context:
  11914. * llama_file file("/path", "wb");
  11915. * llama_data_file_context data_ctx(&file);
  11916. * llama_copy_state_data(ctx, &data_ctx);
  11917. *
  11918. * buffer context:
  11919. * std::vector<uint8_t> buf(max_size, 0);
  11920. * llama_data_buffer_context data_ctx(&buf.data());
  11921. * llama_copy_state_data(ctx, &data_ctx);
  11922. *
  11923. */
  11924. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  11925. // copy rng
  11926. {
  11927. std::ostringstream rng_ss;
  11928. rng_ss << ctx->rng;
  11929. const std::string & rng_str = rng_ss.str();
  11930. const size_t rng_size = rng_str.size();
  11931. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11932. data_ctx->write(&rng_size, sizeof(rng_size));
  11933. data_ctx->write(rng_str.data(), rng_size);
  11934. }
  11935. // copy logits
  11936. {
  11937. const size_t logits_size = ctx->logits_size;
  11938. data_ctx->write(&logits_size, sizeof(logits_size));
  11939. if (logits_size) {
  11940. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  11941. }
  11942. }
  11943. // copy embeddings
  11944. {
  11945. const size_t embeddings_size = ctx->embd_size;
  11946. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  11947. if (embeddings_size) {
  11948. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  11949. }
  11950. }
  11951. // copy kv cache
  11952. {
  11953. const auto & kv_self = ctx->kv_self;
  11954. const auto & hparams = ctx->model.hparams;
  11955. const uint32_t n_layer = hparams.n_layer;
  11956. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11957. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11958. const size_t kv_buf_size = kv_self.total_size();
  11959. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  11960. const uint32_t kv_size = kv_self.size;
  11961. const uint32_t kv_used = kv_self.used;
  11962. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  11963. data_ctx->write(&kv_head, sizeof(kv_head));
  11964. data_ctx->write(&kv_size, sizeof(kv_size));
  11965. data_ctx->write(&kv_used, sizeof(kv_used));
  11966. if (kv_buf_size) {
  11967. std::vector<uint8_t> tmp_buf;
  11968. for (int il = 0; il < (int) n_layer; ++il) {
  11969. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11970. tmp_buf.resize(k_size);
  11971. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11972. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11973. if (kv_self.recurrent) {
  11974. // v is contiguous for recurrent models
  11975. // TODO: use other tensors for state models than k and v
  11976. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11977. tmp_buf.resize(v_size);
  11978. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11979. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11980. continue;
  11981. }
  11982. // v is not contiguous, copy row by row
  11983. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11984. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11985. tmp_buf.resize(v_row_size);
  11986. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11987. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  11988. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11989. }
  11990. }
  11991. }
  11992. for (uint32_t i = 0; i < kv_head; ++i) {
  11993. const auto & cell = kv_self.cells[i];
  11994. const llama_pos pos = cell.pos;
  11995. const size_t seq_id_size = cell.seq_id.size();
  11996. data_ctx->write(&pos, sizeof(pos));
  11997. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  11998. for (auto seq_id : cell.seq_id) {
  11999. data_ctx->write(&seq_id, sizeof(seq_id));
  12000. }
  12001. }
  12002. }
  12003. }
  12004. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12005. llama_data_buffer_context data_ctx(dst);
  12006. llama_copy_state_data_internal(ctx, &data_ctx);
  12007. return data_ctx.get_size_written();
  12008. }
  12009. // Sets the state reading from the specified source address
  12010. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12011. const uint8_t * inp = src;
  12012. // set rng
  12013. {
  12014. size_t rng_size;
  12015. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12016. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12017. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12018. std::istringstream rng_ss(rng_str);
  12019. rng_ss >> ctx->rng;
  12020. GGML_ASSERT(!rng_ss.fail());
  12021. }
  12022. // set logits
  12023. {
  12024. size_t logits_size;
  12025. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12026. GGML_ASSERT(ctx->logits_size >= logits_size);
  12027. if (logits_size) {
  12028. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12029. inp += logits_size * sizeof(float);
  12030. }
  12031. }
  12032. // set embeddings
  12033. {
  12034. size_t embeddings_size;
  12035. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12036. GGML_ASSERT(ctx->embd_size == embeddings_size);
  12037. if (embeddings_size) {
  12038. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12039. inp += embeddings_size * sizeof(float);
  12040. }
  12041. }
  12042. // set kv cache
  12043. {
  12044. const auto & kv_self = ctx->kv_self;
  12045. const auto & hparams = ctx->model.hparams;
  12046. const uint32_t n_layer = hparams.n_layer;
  12047. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12048. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12049. size_t kv_buf_size;
  12050. uint32_t kv_head;
  12051. uint32_t kv_size;
  12052. uint32_t kv_used;
  12053. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12054. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12055. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12056. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12057. if (kv_buf_size) {
  12058. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  12059. for (int il = 0; il < (int) n_layer; ++il) {
  12060. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12061. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12062. inp += k_size;
  12063. if (kv_self.recurrent) {
  12064. // v is contiguous for recurrent models
  12065. // TODO: use other tensors for state models than k and v
  12066. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12067. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12068. inp += v_size;
  12069. continue;
  12070. }
  12071. // v is not contiguous, copy row by row
  12072. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12073. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12074. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12075. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12076. inp += v_row_size;
  12077. }
  12078. }
  12079. }
  12080. GGML_ASSERT(kv_self.size == kv_size);
  12081. ctx->kv_self.head = kv_head;
  12082. ctx->kv_self.size = kv_size;
  12083. ctx->kv_self.used = kv_used;
  12084. ctx->kv_self.cells.resize(kv_size);
  12085. for (uint32_t i = 0; i < kv_head; ++i) {
  12086. llama_pos pos;
  12087. size_t seq_id_size;
  12088. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12089. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12090. ctx->kv_self.cells[i].pos = pos;
  12091. llama_seq_id seq_id;
  12092. for (size_t j = 0; j < seq_id_size; ++j) {
  12093. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12094. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12095. }
  12096. }
  12097. for (uint32_t i = kv_head; i < kv_size; ++i) {
  12098. ctx->kv_self.cells[i].pos = -1;
  12099. ctx->kv_self.cells[i].seq_id.clear();
  12100. }
  12101. }
  12102. const size_t nread = inp - src;
  12103. const size_t max_size = llama_get_state_size(ctx);
  12104. GGML_ASSERT(nread <= max_size);
  12105. return nread;
  12106. }
  12107. static bool llama_load_session_file_internal(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  12108. llama_file file(path_session, "rb");
  12109. // sanity checks
  12110. {
  12111. const uint32_t magic = file.read_u32();
  12112. const uint32_t version = file.read_u32();
  12113. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12114. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12115. return false;
  12116. }
  12117. llama_hparams session_hparams;
  12118. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12119. if (session_hparams != ctx->model.hparams) {
  12120. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12121. return false;
  12122. }
  12123. }
  12124. // load the prompt
  12125. {
  12126. const uint32_t n_token_count = file.read_u32();
  12127. if (n_token_count > n_token_capacity) {
  12128. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12129. return false;
  12130. }
  12131. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12132. *n_token_count_out = n_token_count;
  12133. }
  12134. // restore the context state
  12135. {
  12136. const size_t n_state_size_cur = file.size - file.tell();
  12137. const size_t n_state_size_max = llama_get_state_size(ctx);
  12138. if (n_state_size_cur > n_state_size_max) {
  12139. LLAMA_LOG_ERROR("%s : the state size in session file is too big! max %zu, got %zu\n", __func__, n_state_size_max, n_state_size_cur);
  12140. return false;
  12141. }
  12142. std::vector<uint8_t> state_data(n_state_size_max);
  12143. file.read_raw(state_data.data(), n_state_size_cur);
  12144. llama_set_state_data(ctx, state_data.data());
  12145. }
  12146. return true;
  12147. }
  12148. bool llama_load_session_file(struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
  12149. try {
  12150. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12151. } catch (const std::exception & err) {
  12152. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12153. return false;
  12154. }
  12155. }
  12156. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12157. llama_file file(path_session, "wb");
  12158. file.write_u32(LLAMA_SESSION_MAGIC);
  12159. file.write_u32(LLAMA_SESSION_VERSION);
  12160. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12161. // save the prompt
  12162. file.write_u32((uint32_t) n_token_count);
  12163. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12164. // save the context state using stream saving
  12165. llama_data_file_context data_ctx(&file);
  12166. llama_copy_state_data_internal(ctx, &data_ctx);
  12167. return true;
  12168. }
  12169. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  12170. ctx->cparams.n_threads = n_threads;
  12171. ctx->cparams.n_threads_batch = n_threads_batch;
  12172. }
  12173. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  12174. ctx->abort_callback = abort_callback;
  12175. ctx->abort_callback_data = abort_callback_data;
  12176. }
  12177. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  12178. ctx->cparams.causal_attn = causal_attn;
  12179. }
  12180. struct llama_batch llama_batch_get_one(
  12181. llama_token * tokens,
  12182. int32_t n_tokens,
  12183. llama_pos pos_0,
  12184. llama_seq_id seq_id) {
  12185. return {
  12186. /*n_tokens =*/ n_tokens,
  12187. /*tokens =*/ tokens,
  12188. /*embd =*/ nullptr,
  12189. /*pos =*/ nullptr,
  12190. /*n_seq_id =*/ nullptr,
  12191. /*seq_id =*/ nullptr,
  12192. /*logits =*/ nullptr,
  12193. /*all_pos_0 =*/ pos_0,
  12194. /*all_pos_1 =*/ 1,
  12195. /*all_seq_id =*/ seq_id,
  12196. };
  12197. }
  12198. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  12199. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  12200. if (embd) {
  12201. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  12202. } else {
  12203. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  12204. }
  12205. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  12206. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  12207. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  12208. for (int i = 0; i < n_tokens_alloc; ++i) {
  12209. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  12210. }
  12211. batch.seq_id[n_tokens_alloc] = nullptr;
  12212. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  12213. return batch;
  12214. }
  12215. void llama_batch_free(struct llama_batch batch) {
  12216. if (batch.token) free(batch.token);
  12217. if (batch.embd) free(batch.embd);
  12218. if (batch.pos) free(batch.pos);
  12219. if (batch.n_seq_id) free(batch.n_seq_id);
  12220. if (batch.seq_id) {
  12221. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  12222. free(batch.seq_id[i]);
  12223. }
  12224. free(batch.seq_id);
  12225. }
  12226. if (batch.logits) free(batch.logits);
  12227. }
  12228. int32_t llama_decode(
  12229. struct llama_context * ctx,
  12230. struct llama_batch batch) {
  12231. const int ret = llama_decode_internal(*ctx, batch);
  12232. if (ret < 0) {
  12233. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  12234. }
  12235. return ret;
  12236. }
  12237. void llama_synchronize(struct llama_context * ctx) {
  12238. ggml_backend_sched_synchronize(ctx->sched);
  12239. // FIXME: if multiple single tokens are evaluated without a synchronization,
  12240. // the stats will be added to the prompt evaluation stats
  12241. // this should only happen when using batch size 1 to evaluate a batch
  12242. // add the evaluation to the stats
  12243. if (ctx->n_queued_tokens == 1) {
  12244. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12245. ctx->n_eval++;
  12246. } else if (ctx->n_queued_tokens > 1) {
  12247. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12248. ctx->n_p_eval += ctx->n_queued_tokens;
  12249. }
  12250. // get a more accurate load time, upon first eval
  12251. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  12252. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  12253. ctx->has_evaluated_once = true;
  12254. }
  12255. ctx->n_queued_tokens = 0;
  12256. ctx->t_compute_start_us = 0;
  12257. }
  12258. float * llama_get_logits(struct llama_context * ctx) {
  12259. llama_synchronize(ctx);
  12260. return ctx->logits;
  12261. }
  12262. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  12263. assert(ctx->logits_valid.at(i));
  12264. llama_synchronize(ctx);
  12265. return ctx->logits + i*ctx->model.hparams.n_vocab;
  12266. }
  12267. float * llama_get_embeddings(struct llama_context * ctx) {
  12268. llama_synchronize(ctx);
  12269. return ctx->embd;
  12270. }
  12271. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  12272. llama_synchronize(ctx);
  12273. return ctx->embd + i*ctx->model.hparams.n_embd;
  12274. }
  12275. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  12276. llama_synchronize(ctx);
  12277. auto it = ctx->embd_seq.find(seq_id);
  12278. if (it == ctx->embd_seq.end()) {
  12279. return nullptr;
  12280. }
  12281. return it->second.data();
  12282. }
  12283. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  12284. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12285. return model->vocab.id_to_token[token].text.c_str();
  12286. }
  12287. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  12288. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12289. return model->vocab.id_to_token[token].score;
  12290. }
  12291. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  12292. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12293. return model->vocab.id_to_token[token].type;
  12294. }
  12295. llama_token llama_token_bos(const struct llama_model * model) {
  12296. return model->vocab.special_bos_id;
  12297. }
  12298. llama_token llama_token_eos(const struct llama_model * model) {
  12299. return model->vocab.special_eos_id;
  12300. }
  12301. llama_token llama_token_nl(const struct llama_model * model) {
  12302. return model->vocab.linefeed_id;
  12303. }
  12304. int32_t llama_add_bos_token(const struct llama_model * model) {
  12305. return model->vocab.special_add_bos;
  12306. }
  12307. int32_t llama_add_eos_token(const struct llama_model * model) {
  12308. return model->vocab.special_add_eos;
  12309. }
  12310. llama_token llama_token_prefix(const struct llama_model * model) {
  12311. return model->vocab.special_prefix_id;
  12312. }
  12313. llama_token llama_token_middle(const struct llama_model * model) {
  12314. return model->vocab.special_middle_id;
  12315. }
  12316. llama_token llama_token_suffix(const struct llama_model * model) {
  12317. return model->vocab.special_suffix_id;
  12318. }
  12319. llama_token llama_token_eot(const struct llama_model * model) {
  12320. return model->vocab.special_eot_id;
  12321. }
  12322. int32_t llama_tokenize(
  12323. const struct llama_model * model,
  12324. const char * text,
  12325. int32_t text_len,
  12326. llama_token * tokens,
  12327. int32_t n_tokens_max,
  12328. bool add_bos,
  12329. bool special) {
  12330. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  12331. if (n_tokens_max < (int) res.size()) {
  12332. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  12333. return -((int) res.size());
  12334. }
  12335. for (size_t i = 0; i < res.size(); i++) {
  12336. tokens[i] = res[i];
  12337. }
  12338. return res.size();
  12339. }
  12340. static std::string llama_decode_text(const std::string & text) {
  12341. std::string decoded_text;
  12342. auto unicode_sequences = unicode_cpts_from_utf8(text);
  12343. for (auto & unicode_sequence : unicode_sequences) {
  12344. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  12345. }
  12346. return decoded_text;
  12347. }
  12348. // does not write null-terminator to buf
  12349. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  12350. if (0 <= token && token < llama_n_vocab(model)) {
  12351. switch (llama_vocab_get_type(model->vocab)) {
  12352. case LLAMA_VOCAB_TYPE_WPM:
  12353. case LLAMA_VOCAB_TYPE_SPM: {
  12354. // NOTE: we accept all unsupported token types,
  12355. // suppressing them like CONTROL tokens.
  12356. if (llama_is_normal_token(model->vocab, token)) {
  12357. std::string result = model->vocab.id_to_token[token].text;
  12358. llama_unescape_whitespace(result);
  12359. if (length < (int) result.length()) {
  12360. return -(int) result.length();
  12361. }
  12362. memcpy(buf, result.c_str(), result.length());
  12363. return result.length();
  12364. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12365. std::string result = model->vocab.id_to_token[token].text;
  12366. if (length < (int) result.length()) {
  12367. return -(int) result.length();
  12368. }
  12369. memcpy(buf, result.c_str(), result.length());
  12370. return result.length();
  12371. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  12372. if (length < 3) {
  12373. return -3;
  12374. }
  12375. memcpy(buf, "\xe2\x96\x85", 3);
  12376. return 3;
  12377. } else if (llama_is_control_token(model->vocab, token)) {
  12378. ;
  12379. } else if (llama_is_byte_token(model->vocab, token)) {
  12380. if (length < 1) {
  12381. return -1;
  12382. }
  12383. buf[0] = llama_token_to_byte(model->vocab, token);
  12384. return 1;
  12385. }
  12386. break;
  12387. }
  12388. case LLAMA_VOCAB_TYPE_BPE: {
  12389. // NOTE: we accept all unsupported token types,
  12390. // suppressing them like CONTROL tokens.
  12391. if (llama_is_normal_token(model->vocab, token)) {
  12392. std::string result = model->vocab.id_to_token[token].text;
  12393. result = llama_decode_text(result);
  12394. if (length < (int) result.length()) {
  12395. return -(int) result.length();
  12396. }
  12397. memcpy(buf, result.c_str(), result.length());
  12398. return result.length();
  12399. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12400. std::string result = model->vocab.id_to_token[token].text;
  12401. if (length < (int) result.length()) {
  12402. return -(int) result.length();
  12403. }
  12404. memcpy(buf, result.c_str(), result.length());
  12405. return result.length();
  12406. } else if (llama_is_control_token(model->vocab, token)) {
  12407. ;
  12408. }
  12409. break;
  12410. }
  12411. default:
  12412. GGML_ASSERT(false);
  12413. }
  12414. }
  12415. return 0;
  12416. }
  12417. // trim whitespace from the beginning and end of a string
  12418. static std::string trim(const std::string & str) {
  12419. size_t start = 0;
  12420. size_t end = str.size();
  12421. while (start < end && isspace(str[start])) {
  12422. start += 1;
  12423. }
  12424. while (end > start && isspace(str[end - 1])) {
  12425. end -= 1;
  12426. }
  12427. return str.substr(start, end - start);
  12428. }
  12429. // Simple version of "llama_apply_chat_template" that only works with strings
  12430. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12431. static int32_t llama_chat_apply_template_internal(
  12432. const std::string & tmpl,
  12433. const std::vector<const llama_chat_message *> & chat,
  12434. std::string & dest, bool add_ass) {
  12435. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12436. std::stringstream ss;
  12437. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12438. // chatml template
  12439. for (auto message : chat) {
  12440. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12441. }
  12442. if (add_ass) {
  12443. ss << "<|im_start|>assistant\n";
  12444. }
  12445. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12446. // llama2 template and its variants
  12447. // [variant] support system message
  12448. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12449. // [variant] space before + after response
  12450. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12451. // [variant] add BOS inside history
  12452. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12453. // [variant] trim spaces from the input message
  12454. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12455. // construct the prompt
  12456. bool is_inside_turn = true; // skip BOS at the beginning
  12457. ss << "[INST] ";
  12458. for (auto message : chat) {
  12459. std::string content = strip_message ? trim(message->content) : message->content;
  12460. std::string role(message->role);
  12461. if (!is_inside_turn) {
  12462. is_inside_turn = true;
  12463. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12464. }
  12465. if (role == "system") {
  12466. if (support_system_message) {
  12467. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12468. } else {
  12469. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12470. ss << content << "\n";
  12471. }
  12472. } else if (role == "user") {
  12473. ss << content << " [/INST]";
  12474. } else {
  12475. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12476. is_inside_turn = false;
  12477. }
  12478. }
  12479. // llama2 templates seem to not care about "add_generation_prompt"
  12480. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12481. // zephyr template
  12482. for (auto message : chat) {
  12483. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  12484. }
  12485. if (add_ass) {
  12486. ss << "<|assistant|>\n";
  12487. }
  12488. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  12489. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  12490. for (auto message : chat) {
  12491. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  12492. ss << bos << message->role << "\n" << message->content << "</s>\n";
  12493. }
  12494. if (add_ass) {
  12495. ss << "<s>assistant\n";
  12496. }
  12497. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  12498. // google/gemma-7b-it
  12499. std::string system_prompt = "";
  12500. for (auto message : chat) {
  12501. std::string role(message->role);
  12502. if (role == "system") {
  12503. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  12504. system_prompt = trim(message->content);
  12505. continue;
  12506. }
  12507. // in gemma, "assistant" is "model"
  12508. role = role == "assistant" ? "model" : message->role;
  12509. ss << "<start_of_turn>" << role << "\n";
  12510. if (!system_prompt.empty() && role != "model") {
  12511. ss << system_prompt << "\n\n";
  12512. system_prompt = "";
  12513. }
  12514. ss << trim(message->content) << "<end_of_turn>\n";
  12515. }
  12516. if (add_ass) {
  12517. ss << "<start_of_turn>model\n";
  12518. }
  12519. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  12520. // OrionStarAI/Orion-14B-Chat
  12521. std::string system_prompt = "";
  12522. for (auto message : chat) {
  12523. std::string role(message->role);
  12524. if (role == "system") {
  12525. // there is no system message support, we will merge it with user prompt
  12526. system_prompt = message->content;
  12527. continue;
  12528. } else if (role == "user") {
  12529. ss << "Human: ";
  12530. if (!system_prompt.empty()) {
  12531. ss << system_prompt << "\n\n";
  12532. system_prompt = "";
  12533. }
  12534. ss << message->content << "\n\nAssistant: </s>";
  12535. } else {
  12536. ss << message->content << "</s>";
  12537. }
  12538. }
  12539. } else {
  12540. // template not supported
  12541. return -1;
  12542. }
  12543. dest = ss.str();
  12544. return dest.size();
  12545. }
  12546. LLAMA_API int32_t llama_chat_apply_template(
  12547. const struct llama_model * model,
  12548. const char * tmpl,
  12549. const struct llama_chat_message * chat,
  12550. size_t n_msg,
  12551. bool add_ass,
  12552. char * buf,
  12553. int32_t length) {
  12554. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  12555. if (tmpl == nullptr) {
  12556. GGML_ASSERT(model != nullptr);
  12557. // load template from model
  12558. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  12559. std::string template_key = "tokenizer.chat_template";
  12560. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  12561. if (res < 0) {
  12562. // worst case: there is no information about template, we will use chatml by default
  12563. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  12564. } else {
  12565. curr_tmpl = std::string(model_template.data(), model_template.size());
  12566. }
  12567. }
  12568. // format the chat to string
  12569. std::vector<const llama_chat_message *> chat_vec;
  12570. chat_vec.resize(n_msg);
  12571. for (size_t i = 0; i < n_msg; i++) {
  12572. chat_vec[i] = &chat[i];
  12573. }
  12574. std::string formatted_chat;
  12575. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  12576. if (res < 0) {
  12577. return res;
  12578. }
  12579. if (buf && length > 0) {
  12580. strncpy(buf, formatted_chat.c_str(), length);
  12581. }
  12582. return res;
  12583. }
  12584. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  12585. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  12586. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  12587. return strlen(split_path);
  12588. }
  12589. return 0;
  12590. }
  12591. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  12592. std::string str_split_path(split_path);
  12593. char postfix[32];
  12594. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  12595. std::string str_postfix(postfix);
  12596. // check if dest ends with postfix
  12597. int size_prefix = str_split_path.size() - str_postfix.size();
  12598. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  12599. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  12600. return size_prefix;
  12601. }
  12602. return 0;
  12603. }
  12604. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  12605. struct llama_timings result = {
  12606. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  12607. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  12608. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  12609. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  12610. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  12611. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  12612. /*.n_sample =*/ std::max(1, ctx->n_sample),
  12613. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  12614. /*.n_eval =*/ std::max(1, ctx->n_eval),
  12615. };
  12616. return result;
  12617. }
  12618. void llama_print_timings(struct llama_context * ctx) {
  12619. const llama_timings timings = llama_get_timings(ctx);
  12620. LLAMA_LOG_INFO("\n");
  12621. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  12622. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12623. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  12624. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  12625. __func__, timings.t_p_eval_ms, timings.n_p_eval, timings.t_p_eval_ms / timings.n_p_eval, 1e3 / timings.t_p_eval_ms * timings.n_p_eval);
  12626. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12627. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  12628. LLAMA_LOG_INFO("%s: total time = %10.2f ms / %5d tokens\n", __func__, (timings.t_end_ms - timings.t_start_ms), (timings.n_p_eval + timings.n_eval));
  12629. }
  12630. void llama_reset_timings(struct llama_context * ctx) {
  12631. ctx->t_start_us = ggml_time_us();
  12632. ctx->t_sample_us = ctx->n_sample = 0;
  12633. ctx->t_eval_us = ctx->n_eval = 0;
  12634. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  12635. }
  12636. const char * llama_print_system_info(void) {
  12637. static std::string s;
  12638. s = "";
  12639. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  12640. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  12641. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  12642. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  12643. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  12644. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  12645. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  12646. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  12647. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  12648. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  12649. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  12650. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  12651. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  12652. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  12653. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  12654. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  12655. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  12656. return s.c_str();
  12657. }
  12658. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  12659. fprintf(stream, "\n");
  12660. fprintf(stream, "###########\n");
  12661. fprintf(stream, "# Timings #\n");
  12662. fprintf(stream, "###########\n");
  12663. fprintf(stream, "\n");
  12664. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  12665. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  12666. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  12667. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  12668. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  12669. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  12670. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  12671. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  12672. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  12673. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  12674. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  12675. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  12676. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  12677. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  12678. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  12679. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  12680. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  12681. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  12682. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  12683. }
  12684. // For internal test use
  12685. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  12686. struct llama_context * ctx
  12687. ) {
  12688. return ctx->model.tensors_by_name;
  12689. }
  12690. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  12691. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  12692. g_state.log_callback_user_data = user_data;
  12693. #ifdef GGML_USE_METAL
  12694. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  12695. #endif
  12696. }
  12697. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  12698. va_list args_copy;
  12699. va_copy(args_copy, args);
  12700. char buffer[128];
  12701. int len = vsnprintf(buffer, 128, format, args);
  12702. if (len < 128) {
  12703. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  12704. } else {
  12705. char* buffer2 = new char[len+1];
  12706. vsnprintf(buffer2, len+1, format, args_copy);
  12707. buffer2[len] = 0;
  12708. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  12709. delete[] buffer2;
  12710. }
  12711. va_end(args_copy);
  12712. }
  12713. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  12714. va_list args;
  12715. va_start(args, format);
  12716. llama_log_internal_v(level, format, args);
  12717. va_end(args);
  12718. }
  12719. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  12720. (void) level;
  12721. (void) user_data;
  12722. fputs(text, stderr);
  12723. fflush(stderr);
  12724. }