llama.cpp 397 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513
  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_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #endif
  12. #ifdef GGML_USE_METAL
  13. # include "ggml-metal.h"
  14. #endif
  15. #ifdef GGML_USE_MPI
  16. # include "ggml-mpi.h"
  17. #endif
  18. #ifndef QK_K
  19. # ifdef GGML_QKK_64
  20. # define QK_K 64
  21. # else
  22. # define QK_K 256
  23. # endif
  24. #endif
  25. #ifdef __has_include
  26. #if __has_include(<unistd.h>)
  27. #include <unistd.h>
  28. #if defined(_POSIX_MAPPED_FILES)
  29. #include <sys/mman.h>
  30. #include <fcntl.h>
  31. #endif
  32. #if defined(_POSIX_MEMLOCK_RANGE)
  33. #include <sys/resource.h>
  34. #endif
  35. #endif
  36. #endif
  37. #if defined(_WIN32)
  38. #define WIN32_LEAN_AND_MEAN
  39. #ifndef NOMINMAX
  40. #define NOMINMAX
  41. #endif
  42. #include <windows.h>
  43. #include <io.h>
  44. #endif
  45. #include <algorithm>
  46. #include <array>
  47. #include <cassert>
  48. #include <cinttypes>
  49. #include <climits>
  50. #include <cmath>
  51. #include <cstdarg>
  52. #include <cstddef>
  53. #include <cstdint>
  54. #include <cstdio>
  55. #include <cstring>
  56. #include <ctime>
  57. #include <forward_list>
  58. #include <fstream>
  59. #include <functional>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <set>
  69. #include <sstream>
  70. #include <thread>
  71. #include <type_traits>
  72. #include <unordered_map>
  73. #if defined(_MSC_VER)
  74. #pragma warning(disable: 4244 4267) // possible loss of data
  75. #endif
  76. #ifdef __GNUC__
  77. #ifdef __MINGW32__
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  79. #else
  80. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  81. #endif
  82. #else
  83. #define LLAMA_ATTRIBUTE_FORMAT(...)
  84. #endif
  85. #define LLAMA_MAX_NODES 8192
  86. #define LLAMA_MAX_EXPERTS 8
  87. //
  88. // logging
  89. //
  90. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  91. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  92. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  93. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  94. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  95. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  96. //
  97. // helpers
  98. //
  99. static size_t utf8_len(char src) {
  100. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  101. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  102. return lookup[highbits];
  103. }
  104. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  105. std::string result;
  106. for (size_t pos = 0; ; pos += search.length()) {
  107. auto new_pos = s.find(search, pos);
  108. if (new_pos == std::string::npos) {
  109. result += s.substr(pos, s.size() - pos);
  110. break;
  111. }
  112. result += s.substr(pos, new_pos - pos) + replace;
  113. pos = new_pos;
  114. }
  115. s = std::move(result);
  116. }
  117. static bool is_float_close(float a, float b, float abs_tol) {
  118. // Check for non-negative tolerance
  119. if (abs_tol < 0.0) {
  120. throw std::invalid_argument("Tolerance must be non-negative");
  121. }
  122. // Exact equality check
  123. if (a == b) {
  124. return true;
  125. }
  126. // Check for infinities
  127. if (std::isinf(a) || std::isinf(b)) {
  128. return false;
  129. }
  130. // Regular comparison using the provided absolute tolerance
  131. return std::fabs(b - a) <= abs_tol;
  132. }
  133. static void zeros(std::ofstream & file, size_t n) {
  134. char zero = 0;
  135. for (size_t i = 0; i < n; ++i) {
  136. file.write(&zero, 1);
  137. }
  138. }
  139. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  140. static std::string format(const char * fmt, ...) {
  141. va_list ap;
  142. va_list ap2;
  143. va_start(ap, fmt);
  144. va_copy(ap2, ap);
  145. int size = vsnprintf(NULL, 0, fmt, ap);
  146. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  147. std::vector<char> buf(size + 1);
  148. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  149. GGML_ASSERT(size2 == size);
  150. va_end(ap2);
  151. va_end(ap);
  152. return std::string(buf.data(), size);
  153. }
  154. //
  155. // gguf constants (sync with gguf.py)
  156. //
  157. enum llm_arch {
  158. LLM_ARCH_LLAMA,
  159. LLM_ARCH_FALCON,
  160. LLM_ARCH_BAICHUAN,
  161. LLM_ARCH_GPT2,
  162. LLM_ARCH_GPTJ,
  163. LLM_ARCH_GPTNEOX,
  164. LLM_ARCH_MPT,
  165. LLM_ARCH_STARCODER,
  166. LLM_ARCH_PERSIMMON,
  167. LLM_ARCH_REFACT,
  168. LLM_ARCH_BLOOM,
  169. LLM_ARCH_STABLELM,
  170. LLM_ARCH_QWEN,
  171. LLM_ARCH_PHI2,
  172. LLM_ARCH_PLAMO,
  173. LLM_ARCH_UNKNOWN,
  174. };
  175. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  176. { LLM_ARCH_LLAMA, "llama" },
  177. { LLM_ARCH_FALCON, "falcon" },
  178. { LLM_ARCH_GPT2, "gpt2" },
  179. { LLM_ARCH_GPTJ, "gptj" },
  180. { LLM_ARCH_GPTNEOX, "gptneox" },
  181. { LLM_ARCH_MPT, "mpt" },
  182. { LLM_ARCH_BAICHUAN, "baichuan" },
  183. { LLM_ARCH_STARCODER, "starcoder" },
  184. { LLM_ARCH_PERSIMMON, "persimmon" },
  185. { LLM_ARCH_REFACT, "refact" },
  186. { LLM_ARCH_BLOOM, "bloom" },
  187. { LLM_ARCH_STABLELM, "stablelm" },
  188. { LLM_ARCH_QWEN, "qwen" },
  189. { LLM_ARCH_PHI2, "phi2" },
  190. { LLM_ARCH_PLAMO, "plamo" },
  191. };
  192. enum llm_kv {
  193. LLM_KV_GENERAL_ARCHITECTURE,
  194. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  195. LLM_KV_GENERAL_ALIGNMENT,
  196. LLM_KV_GENERAL_NAME,
  197. LLM_KV_GENERAL_AUTHOR,
  198. LLM_KV_GENERAL_URL,
  199. LLM_KV_GENERAL_DESCRIPTION,
  200. LLM_KV_GENERAL_LICENSE,
  201. LLM_KV_GENERAL_SOURCE_URL,
  202. LLM_KV_GENERAL_SOURCE_HF_REPO,
  203. LLM_KV_CONTEXT_LENGTH,
  204. LLM_KV_EMBEDDING_LENGTH,
  205. LLM_KV_BLOCK_COUNT,
  206. LLM_KV_FEED_FORWARD_LENGTH,
  207. LLM_KV_USE_PARALLEL_RESIDUAL,
  208. LLM_KV_TENSOR_DATA_LAYOUT,
  209. LLM_KV_EXPERT_COUNT,
  210. LLM_KV_EXPERT_USED_COUNT,
  211. LLM_KV_ATTENTION_HEAD_COUNT,
  212. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  213. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  214. LLM_KV_ATTENTION_CLAMP_KQV,
  215. LLM_KV_ATTENTION_KEY_LENGTH,
  216. LLM_KV_ATTENTION_VALUE_LENGTH,
  217. LLM_KV_ATTENTION_LAYERNORM_EPS,
  218. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  219. LLM_KV_ROPE_DIMENSION_COUNT,
  220. LLM_KV_ROPE_FREQ_BASE,
  221. LLM_KV_ROPE_SCALE_LINEAR,
  222. LLM_KV_ROPE_SCALING_TYPE,
  223. LLM_KV_ROPE_SCALING_FACTOR,
  224. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  225. LLM_KV_ROPE_SCALING_FINETUNED,
  226. LLM_KV_TOKENIZER_MODEL,
  227. LLM_KV_TOKENIZER_LIST,
  228. LLM_KV_TOKENIZER_TOKEN_TYPE,
  229. LLM_KV_TOKENIZER_SCORES,
  230. LLM_KV_TOKENIZER_MERGES,
  231. LLM_KV_TOKENIZER_BOS_ID,
  232. LLM_KV_TOKENIZER_EOS_ID,
  233. LLM_KV_TOKENIZER_UNK_ID,
  234. LLM_KV_TOKENIZER_SEP_ID,
  235. LLM_KV_TOKENIZER_PAD_ID,
  236. LLM_KV_TOKENIZER_ADD_BOS,
  237. LLM_KV_TOKENIZER_ADD_EOS,
  238. LLM_KV_TOKENIZER_HF_JSON,
  239. LLM_KV_TOKENIZER_RWKV,
  240. };
  241. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  242. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  243. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  244. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  245. { LLM_KV_GENERAL_NAME, "general.name" },
  246. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  247. { LLM_KV_GENERAL_URL, "general.url" },
  248. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  249. { LLM_KV_GENERAL_LICENSE, "general.license" },
  250. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  251. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  252. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  253. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  254. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  255. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  256. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  257. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  258. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  259. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  260. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  261. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  262. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  263. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  264. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  265. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  266. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  267. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  268. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  269. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  270. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  271. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  272. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  273. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  274. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  275. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  276. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  277. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  278. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  279. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  280. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  281. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  282. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  283. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  284. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  285. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  286. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  287. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  288. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  289. };
  290. struct LLM_KV {
  291. LLM_KV(llm_arch arch) : arch(arch) {}
  292. llm_arch arch;
  293. std::string operator()(llm_kv kv) const {
  294. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  295. }
  296. };
  297. enum llm_tensor {
  298. LLM_TENSOR_TOKEN_EMBD,
  299. LLM_TENSOR_TOKEN_EMBD_NORM,
  300. LLM_TENSOR_POS_EMBD,
  301. LLM_TENSOR_OUTPUT,
  302. LLM_TENSOR_OUTPUT_NORM,
  303. LLM_TENSOR_ROPE_FREQS,
  304. LLM_TENSOR_ATTN_Q,
  305. LLM_TENSOR_ATTN_K,
  306. LLM_TENSOR_ATTN_V,
  307. LLM_TENSOR_ATTN_QKV,
  308. LLM_TENSOR_ATTN_OUT,
  309. LLM_TENSOR_ATTN_NORM,
  310. LLM_TENSOR_ATTN_NORM_2,
  311. LLM_TENSOR_ATTN_ROT_EMBD,
  312. LLM_TENSOR_FFN_GATE_INP,
  313. LLM_TENSOR_FFN_NORM,
  314. LLM_TENSOR_FFN_GATE,
  315. LLM_TENSOR_FFN_DOWN,
  316. LLM_TENSOR_FFN_UP,
  317. LLM_TENSOR_FFN_ACT,
  318. LLM_TENSOR_FFN_DOWN_EXP,
  319. LLM_TENSOR_FFN_GATE_EXP,
  320. LLM_TENSOR_FFN_UP_EXP,
  321. LLM_TENSOR_ATTN_Q_NORM,
  322. LLM_TENSOR_ATTN_K_NORM,
  323. };
  324. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  325. {
  326. LLM_ARCH_LLAMA,
  327. {
  328. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  329. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  330. { LLM_TENSOR_OUTPUT, "output" },
  331. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  332. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  333. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  334. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  335. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  336. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  337. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  338. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  339. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  340. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  341. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  342. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  343. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  344. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  345. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  346. },
  347. },
  348. {
  349. LLM_ARCH_BAICHUAN,
  350. {
  351. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  352. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  353. { LLM_TENSOR_OUTPUT, "output" },
  354. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  355. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  356. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  357. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  358. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  359. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  360. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  361. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  362. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  363. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  364. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  365. },
  366. },
  367. {
  368. LLM_ARCH_FALCON,
  369. {
  370. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  371. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  372. { LLM_TENSOR_OUTPUT, "output" },
  373. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  374. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  375. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  376. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  377. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  378. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  379. },
  380. },
  381. {
  382. LLM_ARCH_GPT2,
  383. {
  384. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  385. { LLM_TENSOR_POS_EMBD, "position_embd" },
  386. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  387. { LLM_TENSOR_OUTPUT, "output" },
  388. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  389. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  390. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  391. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  392. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  393. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  394. },
  395. },
  396. {
  397. LLM_ARCH_GPTJ,
  398. {
  399. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  400. },
  401. },
  402. {
  403. LLM_ARCH_GPTNEOX,
  404. {
  405. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  406. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  407. { LLM_TENSOR_OUTPUT, "output" },
  408. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  409. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  410. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  411. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  412. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  413. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  414. },
  415. },
  416. {
  417. LLM_ARCH_PERSIMMON,
  418. {
  419. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  420. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  421. { LLM_TENSOR_OUTPUT, "output"},
  422. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  423. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  424. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  425. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  426. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  427. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  428. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  429. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  430. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  431. },
  432. },
  433. {
  434. LLM_ARCH_MPT,
  435. {
  436. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  437. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  438. { LLM_TENSOR_OUTPUT, "output" },
  439. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  440. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  441. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  442. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  443. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  444. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  445. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  446. },
  447. },
  448. {
  449. LLM_ARCH_STARCODER,
  450. {
  451. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  452. { LLM_TENSOR_POS_EMBD, "position_embd" },
  453. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  454. { LLM_TENSOR_OUTPUT, "output" },
  455. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  456. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  457. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  458. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  459. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  460. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  461. },
  462. },
  463. {
  464. LLM_ARCH_REFACT,
  465. {
  466. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  467. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  468. { LLM_TENSOR_OUTPUT, "output" },
  469. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  470. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  471. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  472. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  473. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  474. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  475. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  476. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  477. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  478. },
  479. },
  480. {
  481. LLM_ARCH_BLOOM,
  482. {
  483. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  484. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  485. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  486. { LLM_TENSOR_OUTPUT, "output" },
  487. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  488. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  489. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  490. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  491. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  492. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  493. },
  494. },
  495. {
  496. LLM_ARCH_STABLELM,
  497. {
  498. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  499. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  500. { LLM_TENSOR_OUTPUT, "output" },
  501. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  502. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  503. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  504. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  505. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  506. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  507. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  508. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  509. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  510. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  511. },
  512. },
  513. {
  514. LLM_ARCH_QWEN,
  515. {
  516. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  517. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  518. { LLM_TENSOR_OUTPUT, "output" },
  519. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  520. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  521. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  522. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  523. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  524. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  525. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  526. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  527. },
  528. },
  529. {
  530. LLM_ARCH_PHI2,
  531. {
  532. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  533. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  534. { LLM_TENSOR_OUTPUT, "output" },
  535. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  536. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  537. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  538. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  539. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  540. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  541. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  542. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  543. },
  544. },
  545. {
  546. LLM_ARCH_PLAMO,
  547. {
  548. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  549. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  550. { LLM_TENSOR_OUTPUT, "output" },
  551. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  552. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  553. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  554. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  555. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  556. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  557. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  558. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  561. },
  562. },
  563. {
  564. LLM_ARCH_UNKNOWN,
  565. {
  566. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  567. },
  568. },
  569. };
  570. static llm_arch llm_arch_from_string(const std::string & name) {
  571. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  572. if (kv.second == name) {
  573. return kv.first;
  574. }
  575. }
  576. return LLM_ARCH_UNKNOWN;
  577. }
  578. // helper to handle gguf constants
  579. // usage:
  580. //
  581. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  582. //
  583. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  584. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  585. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  586. //
  587. struct LLM_TN {
  588. LLM_TN(llm_arch arch) : arch(arch) {}
  589. llm_arch arch;
  590. std::string operator()(llm_tensor tensor) const {
  591. return LLM_TENSOR_NAMES[arch].at(tensor);
  592. }
  593. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  594. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  595. }
  596. std::string operator()(llm_tensor tensor, int bid) const {
  597. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  598. }
  599. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  600. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  601. }
  602. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  603. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  604. }
  605. };
  606. //
  607. // gguf helpers
  608. //
  609. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  610. { LLAMA_ROPE_SCALING_NONE, "none" },
  611. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  612. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  613. };
  614. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  615. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  616. if (kv.second == name) {
  617. return kv.first;
  618. }
  619. }
  620. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  621. }
  622. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  623. switch (type) {
  624. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  625. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  626. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  627. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  628. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  629. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  630. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  631. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  632. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  633. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  634. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  635. default: return format("unknown type %d", type);
  636. }
  637. }
  638. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  639. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  640. switch (type) {
  641. case GGUF_TYPE_STRING:
  642. return gguf_get_val_str(ctx_gguf, i);
  643. case GGUF_TYPE_ARRAY:
  644. {
  645. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  646. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  647. const void * data = gguf_get_arr_data(ctx_gguf, i);
  648. std::stringstream ss;
  649. ss << "[";
  650. for (int j = 0; j < arr_n; j++) {
  651. if (arr_type == GGUF_TYPE_STRING) {
  652. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  653. // escape quotes
  654. replace_all(val, "\\", "\\\\");
  655. replace_all(val, "\"", "\\\"");
  656. ss << '"' << val << '"';
  657. } else if (arr_type == GGUF_TYPE_ARRAY) {
  658. ss << "???";
  659. } else {
  660. ss << gguf_data_to_str(arr_type, data, j);
  661. }
  662. if (j < arr_n - 1) {
  663. ss << ", ";
  664. }
  665. }
  666. ss << "]";
  667. return ss.str();
  668. }
  669. default:
  670. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  671. }
  672. }
  673. //
  674. // ggml helpers
  675. //
  676. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  677. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  678. if (plan.work_size > 0) {
  679. buf.resize(plan.work_size);
  680. plan.work_data = buf.data();
  681. }
  682. ggml_graph_compute(graph, &plan);
  683. }
  684. //
  685. // llama helpers
  686. //
  687. #if defined(_WIN32)
  688. static std::string llama_format_win_err(DWORD err) {
  689. LPSTR buf;
  690. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  691. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  692. if (!size) {
  693. return "FormatMessageA failed";
  694. }
  695. std::string ret(buf, size);
  696. LocalFree(buf);
  697. return ret;
  698. }
  699. #endif
  700. template <typename T>
  701. struct no_init {
  702. T value;
  703. no_init() { /* do nothing */ }
  704. };
  705. struct llama_file {
  706. // use FILE * so we don't have to re-open the file to mmap
  707. FILE * fp;
  708. size_t size;
  709. llama_file(const char * fname, const char * mode) {
  710. fp = std::fopen(fname, mode);
  711. if (fp == NULL) {
  712. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  713. }
  714. seek(0, SEEK_END);
  715. size = tell();
  716. seek(0, SEEK_SET);
  717. }
  718. size_t tell() const {
  719. #ifdef _WIN32
  720. __int64 ret = _ftelli64(fp);
  721. #else
  722. long ret = std::ftell(fp);
  723. #endif
  724. GGML_ASSERT(ret != -1); // this really shouldn't fail
  725. return (size_t) ret;
  726. }
  727. void seek(size_t offset, int whence) const {
  728. #ifdef _WIN32
  729. int ret = _fseeki64(fp, (__int64) offset, whence);
  730. #else
  731. int ret = std::fseek(fp, (long) offset, whence);
  732. #endif
  733. GGML_ASSERT(ret == 0); // same
  734. }
  735. void read_raw(void * ptr, size_t len) const {
  736. if (len == 0) {
  737. return;
  738. }
  739. errno = 0;
  740. std::size_t ret = std::fread(ptr, len, 1, fp);
  741. if (ferror(fp)) {
  742. throw std::runtime_error(format("read error: %s", strerror(errno)));
  743. }
  744. if (ret != 1) {
  745. throw std::runtime_error("unexpectedly reached end of file");
  746. }
  747. }
  748. uint32_t read_u32() const {
  749. uint32_t ret;
  750. read_raw(&ret, sizeof(ret));
  751. return ret;
  752. }
  753. void write_raw(const void * ptr, size_t len) const {
  754. if (len == 0) {
  755. return;
  756. }
  757. errno = 0;
  758. size_t ret = std::fwrite(ptr, len, 1, fp);
  759. if (ret != 1) {
  760. throw std::runtime_error(format("write error: %s", strerror(errno)));
  761. }
  762. }
  763. void write_u32(std::uint32_t val) const {
  764. write_raw(&val, sizeof(val));
  765. }
  766. ~llama_file() {
  767. if (fp) {
  768. std::fclose(fp);
  769. }
  770. }
  771. };
  772. struct llama_mmap {
  773. void * addr;
  774. size_t size;
  775. llama_mmap(const llama_mmap &) = delete;
  776. #ifdef _POSIX_MAPPED_FILES
  777. static constexpr bool SUPPORTED = true;
  778. // list of mapped fragments (first_offset, last_offset)
  779. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  780. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  781. size = file->size;
  782. int fd = fileno(file->fp);
  783. int flags = MAP_SHARED;
  784. // prefetch/readahead impairs performance on NUMA systems
  785. if (numa) { prefetch = 0; }
  786. #ifdef __linux__
  787. // advise the kernel to read the file sequentially (increases readahead)
  788. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  789. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  790. strerror(errno));
  791. }
  792. if (prefetch) { flags |= MAP_POPULATE; }
  793. #endif
  794. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  795. if (addr == MAP_FAILED) { // NOLINT
  796. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  797. }
  798. if (prefetch > 0) {
  799. // advise the kernel to preload the mapped memory
  800. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  801. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  802. strerror(errno));
  803. }
  804. }
  805. if (numa) {
  806. // advise the kernel not to use readahead
  807. // (because the next page might not belong on the same node)
  808. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  809. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  810. strerror(errno));
  811. }
  812. }
  813. // initialize list of mapped_fragments
  814. mapped_fragments.emplace_back(0, file->size);
  815. }
  816. static void align_range(size_t * first, size_t * last, size_t page_size) {
  817. // align first to the next page
  818. size_t offset_in_page = *first & (page_size - 1);
  819. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  820. *first += offset_to_page;
  821. // align last to the previous page
  822. *last = *last & ~(page_size - 1);
  823. if (*last <= *first) {
  824. *last = *first;
  825. }
  826. }
  827. // partially unmap the file in the range [first, last)
  828. void unmap_fragment(size_t first, size_t last) {
  829. // note: this function must not be called multiple times with overlapping ranges
  830. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  831. int page_size = sysconf(_SC_PAGESIZE);
  832. align_range(&first, &last, page_size);
  833. size_t len = last - first;
  834. if (len == 0) {
  835. return;
  836. }
  837. GGML_ASSERT(first % page_size == 0);
  838. GGML_ASSERT(last % page_size == 0);
  839. GGML_ASSERT(last > first);
  840. void * next_page_start = (uint8_t *) addr + first;
  841. // unmap the range
  842. if (munmap(next_page_start, len)) {
  843. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  844. }
  845. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  846. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  847. for (const auto & frag : mapped_fragments) {
  848. if (frag.first < first && frag.second > last) {
  849. // the range is in the middle of the fragment, split it
  850. new_mapped_fragments.emplace_back(frag.first, first);
  851. new_mapped_fragments.emplace_back(last, frag.second);
  852. } else if (frag.first < first && frag.second > first) {
  853. // the range starts in the middle of the fragment
  854. new_mapped_fragments.emplace_back(frag.first, first);
  855. } else if (frag.first < last && frag.second > last) {
  856. // the range ends in the middle of the fragment
  857. new_mapped_fragments.emplace_back(last, frag.second);
  858. } else if (frag.first >= first && frag.second <= last) {
  859. // the range covers the entire fragment
  860. } else {
  861. // the range is outside the fragment
  862. new_mapped_fragments.push_back(frag);
  863. }
  864. }
  865. mapped_fragments = std::move(new_mapped_fragments);
  866. }
  867. ~llama_mmap() {
  868. for (const auto & frag : mapped_fragments) {
  869. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  870. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  871. }
  872. }
  873. }
  874. #elif defined(_WIN32)
  875. static constexpr bool SUPPORTED = true;
  876. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  877. GGML_UNUSED(numa);
  878. size = file->size;
  879. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  880. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  881. if (hMapping == NULL) {
  882. DWORD error = GetLastError();
  883. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  884. }
  885. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  886. DWORD error = GetLastError();
  887. CloseHandle(hMapping);
  888. if (addr == NULL) {
  889. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  890. }
  891. if (prefetch > 0) {
  892. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  893. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  894. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  895. // may fail on pre-Windows 8 systems
  896. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  897. if (pPrefetchVirtualMemory) {
  898. // advise the kernel to preload the mapped memory
  899. WIN32_MEMORY_RANGE_ENTRY range;
  900. range.VirtualAddress = addr;
  901. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  902. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  903. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  904. llama_format_win_err(GetLastError()).c_str());
  905. }
  906. }
  907. }
  908. }
  909. void unmap_fragment(size_t first, size_t last) {
  910. // not supported
  911. GGML_UNUSED(first);
  912. GGML_UNUSED(last);
  913. }
  914. ~llama_mmap() {
  915. if (!UnmapViewOfFile(addr)) {
  916. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  917. llama_format_win_err(GetLastError()).c_str());
  918. }
  919. }
  920. #else
  921. static constexpr bool SUPPORTED = false;
  922. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  923. GGML_UNUSED(file);
  924. GGML_UNUSED(prefetch);
  925. GGML_UNUSED(numa);
  926. throw std::runtime_error("mmap not supported");
  927. }
  928. void unmap_fragment(size_t first, size_t last) {
  929. GGML_UNUSED(first);
  930. GGML_UNUSED(last);
  931. throw std::runtime_error("mmap not supported");
  932. }
  933. #endif
  934. };
  935. // Represents some region of memory being locked using mlock or VirtualLock;
  936. // will automatically unlock on destruction.
  937. struct llama_mlock {
  938. void * addr = NULL;
  939. size_t size = 0;
  940. bool failed_already = false;
  941. llama_mlock() {}
  942. llama_mlock(const llama_mlock &) = delete;
  943. ~llama_mlock() {
  944. if (size) {
  945. raw_unlock(addr, size);
  946. }
  947. }
  948. void init(void * ptr) {
  949. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  950. addr = ptr;
  951. }
  952. void grow_to(size_t target_size) {
  953. GGML_ASSERT(addr);
  954. if (failed_already) {
  955. return;
  956. }
  957. size_t granularity = lock_granularity();
  958. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  959. if (target_size > size) {
  960. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  961. size = target_size;
  962. } else {
  963. failed_already = true;
  964. }
  965. }
  966. }
  967. #ifdef _POSIX_MEMLOCK_RANGE
  968. static constexpr bool SUPPORTED = true;
  969. static size_t lock_granularity() {
  970. return (size_t) sysconf(_SC_PAGESIZE);
  971. }
  972. #ifdef __APPLE__
  973. #define MLOCK_SUGGESTION \
  974. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  975. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  976. #else
  977. #define MLOCK_SUGGESTION \
  978. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  979. #endif
  980. bool raw_lock(const void * addr, size_t size) const {
  981. if (!mlock(addr, size)) {
  982. return true;
  983. }
  984. char* errmsg = std::strerror(errno);
  985. bool suggest = (errno == ENOMEM);
  986. // Check if the resource limit is fine after all
  987. struct rlimit lock_limit;
  988. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  989. suggest = false;
  990. }
  991. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  992. suggest = false;
  993. }
  994. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  995. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  996. return false;
  997. }
  998. #undef MLOCK_SUGGESTION
  999. static void raw_unlock(void * addr, size_t size) {
  1000. if (munlock(addr, size)) {
  1001. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1002. }
  1003. }
  1004. #elif defined(_WIN32)
  1005. static constexpr bool SUPPORTED = true;
  1006. static size_t lock_granularity() {
  1007. SYSTEM_INFO si;
  1008. GetSystemInfo(&si);
  1009. return (size_t) si.dwPageSize;
  1010. }
  1011. bool raw_lock(void * ptr, size_t len) const {
  1012. for (int tries = 1; ; tries++) {
  1013. if (VirtualLock(ptr, len)) {
  1014. return true;
  1015. }
  1016. if (tries == 2) {
  1017. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1018. len, size, llama_format_win_err(GetLastError()).c_str());
  1019. return false;
  1020. }
  1021. // It failed but this was only the first try; increase the working
  1022. // set size and try again.
  1023. SIZE_T min_ws_size, max_ws_size;
  1024. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1025. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  1026. llama_format_win_err(GetLastError()).c_str());
  1027. return false;
  1028. }
  1029. // Per MSDN: "The maximum number of pages that a process can lock
  1030. // is equal to the number of pages in its minimum working set minus
  1031. // a small overhead."
  1032. // Hopefully a megabyte is enough overhead:
  1033. size_t increment = len + 1048576;
  1034. // The minimum must be <= the maximum, so we need to increase both:
  1035. min_ws_size += increment;
  1036. max_ws_size += increment;
  1037. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1038. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  1039. llama_format_win_err(GetLastError()).c_str());
  1040. return false;
  1041. }
  1042. }
  1043. }
  1044. static void raw_unlock(void * ptr, size_t len) {
  1045. if (!VirtualUnlock(ptr, len)) {
  1046. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  1047. llama_format_win_err(GetLastError()).c_str());
  1048. }
  1049. }
  1050. #else
  1051. static constexpr bool SUPPORTED = false;
  1052. static size_t lock_granularity() {
  1053. return (size_t) 65536;
  1054. }
  1055. bool raw_lock(const void * addr, size_t len) const {
  1056. fprintf(stderr, "warning: mlock not supported on this system\n");
  1057. return false;
  1058. }
  1059. static void raw_unlock(const void * addr, size_t len) {}
  1060. #endif
  1061. };
  1062. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1063. std::vector<char> result(8, 0);
  1064. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1065. if (n_tokens < 0) {
  1066. result.resize(-n_tokens);
  1067. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1068. GGML_ASSERT(check == -n_tokens);
  1069. }
  1070. else {
  1071. result.resize(n_tokens);
  1072. }
  1073. return std::string(result.data(), result.size());
  1074. }
  1075. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1076. ggml_backend_buffer_type_t buft = nullptr;
  1077. #if defined(GGML_USE_CUBLAS)
  1078. // host buffers should only be used when data is expected to be copied to/from the GPU
  1079. if (host_buffer) {
  1080. buft = ggml_backend_cuda_host_buffer_type();
  1081. }
  1082. #elif defined(GGML_USE_CPU_HBM)
  1083. buft = ggml_backend_cpu_hbm_buffer_type();
  1084. #endif
  1085. if (buft == nullptr) {
  1086. buft = ggml_backend_cpu_buffer_type();
  1087. }
  1088. return buft;
  1089. GGML_UNUSED(host_buffer);
  1090. }
  1091. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1092. ggml_backend_buffer_type_t buft = nullptr;
  1093. #ifdef GGML_USE_METAL
  1094. buft = ggml_backend_metal_buffer_type();
  1095. #elif defined(GGML_USE_CUBLAS)
  1096. buft = ggml_backend_cuda_buffer_type(gpu);
  1097. #elif defined(GGML_USE_CLBLAST)
  1098. buft = ggml_backend_opencl_buffer_type();
  1099. #endif
  1100. if (buft == nullptr) {
  1101. buft = llama_default_buffer_type_cpu(true);
  1102. }
  1103. return buft;
  1104. GGML_UNUSED(gpu);
  1105. }
  1106. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1107. ggml_backend_buffer_type_t buft = nullptr;
  1108. #ifdef GGML_USE_CUBLAS
  1109. if (ggml_backend_cuda_get_device_count() > 1) {
  1110. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1111. }
  1112. #endif
  1113. if (buft == nullptr) {
  1114. buft = llama_default_buffer_type_offload(fallback_gpu);
  1115. }
  1116. return buft;
  1117. GGML_UNUSED(tensor_split);
  1118. }
  1119. //
  1120. // globals
  1121. //
  1122. struct llama_state {
  1123. llama_state() {
  1124. #ifdef GGML_USE_METAL
  1125. ggml_metal_log_set_callback(log_callback, log_callback_user_data);
  1126. #endif
  1127. }
  1128. // We save the log callback globally
  1129. ggml_log_callback log_callback = llama_log_callback_default;
  1130. void * log_callback_user_data = nullptr;
  1131. };
  1132. static llama_state g_state;
  1133. // available llama models
  1134. enum e_model {
  1135. MODEL_UNKNOWN,
  1136. MODEL_1B,
  1137. MODEL_3B,
  1138. MODEL_7B,
  1139. MODEL_8B,
  1140. MODEL_13B,
  1141. MODEL_15B,
  1142. MODEL_30B,
  1143. MODEL_34B,
  1144. MODEL_40B,
  1145. MODEL_65B,
  1146. MODEL_70B,
  1147. MODEL_SMALL,
  1148. MODEL_MEDIUM,
  1149. MODEL_LARGE,
  1150. MODEL_XL,
  1151. };
  1152. static const size_t kiB = 1024;
  1153. static const size_t MiB = 1024*kiB;
  1154. static const size_t GiB = 1024*MiB;
  1155. struct llama_hparams {
  1156. bool vocab_only;
  1157. uint32_t n_vocab;
  1158. uint32_t n_ctx_train; // context size the model was trained on
  1159. uint32_t n_embd;
  1160. uint32_t n_head;
  1161. uint32_t n_head_kv;
  1162. uint32_t n_layer;
  1163. uint32_t n_rot;
  1164. 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
  1165. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1166. uint32_t n_ff;
  1167. uint32_t n_expert = 0;
  1168. uint32_t n_expert_used = 0;
  1169. float f_norm_eps;
  1170. float f_norm_rms_eps;
  1171. float rope_freq_base_train;
  1172. float rope_freq_scale_train;
  1173. uint32_t n_yarn_orig_ctx;
  1174. int8_t rope_scaling_type_train : 3;
  1175. bool rope_finetuned : 1;
  1176. float f_clamp_kqv;
  1177. float f_max_alibi_bias;
  1178. bool operator!=(const llama_hparams & other) const {
  1179. if (this->vocab_only != other.vocab_only) return true;
  1180. if (this->n_vocab != other.n_vocab) return true;
  1181. if (this->n_ctx_train != other.n_ctx_train) return true;
  1182. if (this->n_embd != other.n_embd) return true;
  1183. if (this->n_head != other.n_head) return true;
  1184. if (this->n_head_kv != other.n_head_kv) return true;
  1185. if (this->n_layer != other.n_layer) return true;
  1186. if (this->n_rot != other.n_rot) return true;
  1187. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1188. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1189. if (this->n_ff != other.n_ff) return true;
  1190. if (this->n_expert != other.n_expert) return true;
  1191. if (this->n_expert_used != other.n_expert_used) return true;
  1192. if (this->rope_finetuned != other.rope_finetuned) return true;
  1193. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1194. const float EPSILON = 1e-9f;
  1195. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1196. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1197. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1198. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1199. return false;
  1200. }
  1201. uint32_t n_gqa() const {
  1202. return n_head/n_head_kv;
  1203. }
  1204. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1205. return n_embd_head_k * n_head_kv;
  1206. }
  1207. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1208. return n_embd_head_v * n_head_kv;
  1209. }
  1210. };
  1211. struct llama_cparams {
  1212. uint32_t n_ctx; // context size used during inference
  1213. uint32_t n_batch;
  1214. uint32_t n_threads; // number of threads to use for generation
  1215. uint32_t n_threads_batch; // number of threads to use for batch processing
  1216. float rope_freq_base;
  1217. float rope_freq_scale;
  1218. uint32_t n_yarn_orig_ctx;
  1219. // These hyperparameters are not exposed in GGUF, because all
  1220. // existing YaRN models use the same values for them.
  1221. float yarn_ext_factor;
  1222. float yarn_attn_factor;
  1223. float yarn_beta_fast;
  1224. float yarn_beta_slow;
  1225. bool mul_mat_q;
  1226. bool offload_kqv;
  1227. };
  1228. struct llama_layer {
  1229. // normalization
  1230. struct ggml_tensor * attn_norm;
  1231. struct ggml_tensor * attn_norm_b;
  1232. struct ggml_tensor * attn_norm_2;
  1233. struct ggml_tensor * attn_norm_2_b;
  1234. struct ggml_tensor * attn_q_norm;
  1235. struct ggml_tensor * attn_q_norm_b;
  1236. struct ggml_tensor * attn_k_norm;
  1237. struct ggml_tensor * attn_k_norm_b;
  1238. // attention
  1239. struct ggml_tensor * wq;
  1240. struct ggml_tensor * wk;
  1241. struct ggml_tensor * wv;
  1242. struct ggml_tensor * wo;
  1243. struct ggml_tensor * wqkv;
  1244. // attention bias
  1245. struct ggml_tensor * bq;
  1246. struct ggml_tensor * bk;
  1247. struct ggml_tensor * bv;
  1248. struct ggml_tensor * bo;
  1249. struct ggml_tensor * bqkv;
  1250. // normalization
  1251. struct ggml_tensor * ffn_norm;
  1252. struct ggml_tensor * ffn_norm_b;
  1253. // ff
  1254. struct ggml_tensor * ffn_gate; // w1
  1255. struct ggml_tensor * ffn_down; // w2
  1256. struct ggml_tensor * ffn_up; // w3
  1257. // ff MoE
  1258. struct ggml_tensor * ffn_gate_inp;
  1259. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1260. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1261. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1262. // ff bias
  1263. struct ggml_tensor * ffn_down_b; // b2
  1264. struct ggml_tensor * ffn_up_b; // b3
  1265. struct ggml_tensor * ffn_act;
  1266. };
  1267. struct llama_kv_cell {
  1268. llama_pos pos = -1;
  1269. llama_pos delta = 0;
  1270. std::set<llama_seq_id> seq_id;
  1271. bool has_seq_id(const llama_seq_id & id) const {
  1272. return seq_id.find(id) != seq_id.end();
  1273. }
  1274. };
  1275. // ring-buffer of cached KV data
  1276. struct llama_kv_cache {
  1277. bool has_shift = false;
  1278. // Note: The value of head isn't only used to optimize searching
  1279. // for a free KV slot. llama_decode_internal also uses it, so it
  1280. // cannot be freely changed after a slot has been allocated.
  1281. uint32_t head = 0;
  1282. uint32_t size = 0;
  1283. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1284. // computed before each graph build
  1285. uint32_t n = 0;
  1286. std::vector<llama_kv_cell> cells;
  1287. std::vector<struct ggml_tensor *> k_l; // per layer
  1288. std::vector<struct ggml_tensor *> v_l;
  1289. std::vector<struct ggml_context *> ctxs;
  1290. std::vector<ggml_backend_buffer_t> bufs;
  1291. size_t total_size() const {
  1292. size_t size = 0;
  1293. for (ggml_backend_buffer_t buf : bufs) {
  1294. size += ggml_backend_buffer_get_size(buf);
  1295. }
  1296. return size;
  1297. }
  1298. ~llama_kv_cache() {
  1299. for (struct ggml_context * ctx : ctxs) {
  1300. ggml_free(ctx);
  1301. }
  1302. for (ggml_backend_buffer_t buf : bufs) {
  1303. ggml_backend_buffer_free(buf);
  1304. }
  1305. }
  1306. };
  1307. struct llama_vocab {
  1308. using id = int32_t;
  1309. using token = std::string;
  1310. using ttype = llama_token_type;
  1311. struct token_data {
  1312. token text;
  1313. float score;
  1314. ttype type;
  1315. };
  1316. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1317. std::unordered_map<token, id> token_to_id;
  1318. std::vector<token_data> id_to_token;
  1319. std::unordered_map<token, id> special_tokens_cache;
  1320. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1321. // default LLaMA special tokens
  1322. id special_bos_id = 1;
  1323. id special_eos_id = 2;
  1324. id special_unk_id = 0;
  1325. id special_sep_id = -1;
  1326. id special_pad_id = -1;
  1327. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1328. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1329. id linefeed_id = 13;
  1330. id special_prefix_id = 32007;
  1331. id special_middle_id = 32009;
  1332. id special_suffix_id = 32008;
  1333. id special_eot_id = 32010;
  1334. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1335. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1336. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1337. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1338. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1339. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1340. if (it == bpe_ranks.end()) {
  1341. return -1;
  1342. }
  1343. return it->second;
  1344. }
  1345. };
  1346. struct llama_model {
  1347. e_model type = MODEL_UNKNOWN;
  1348. llm_arch arch = LLM_ARCH_UNKNOWN;
  1349. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1350. std::string name = "n/a";
  1351. llama_hparams hparams = {};
  1352. llama_vocab vocab;
  1353. struct ggml_tensor * tok_embd;
  1354. struct ggml_tensor * pos_embd;
  1355. struct ggml_tensor * tok_norm;
  1356. struct ggml_tensor * tok_norm_b;
  1357. struct ggml_tensor * output_norm;
  1358. struct ggml_tensor * output_norm_b;
  1359. struct ggml_tensor * output;
  1360. struct ggml_tensor * output_b;
  1361. std::vector<llama_layer> layers;
  1362. llama_split_mode split_mode;
  1363. int main_gpu;
  1364. int n_gpu_layers;
  1365. // gguf metadata
  1366. std::unordered_map<std::string, std::string> gguf_kv;
  1367. // layer -> buffer type mapping
  1368. struct layer_buft {
  1369. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1370. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1371. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1372. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1373. ggml_backend_buffer_type_t buft; // everything else
  1374. };
  1375. layer_buft buft_input;
  1376. layer_buft buft_output;
  1377. std::vector<layer_buft> buft_layer;
  1378. // contexts where the model tensors metadata is stored
  1379. std::vector<struct ggml_context *> ctxs;
  1380. // the model memory buffers for the tensor data
  1381. std::vector<ggml_backend_buffer_t> bufs;
  1382. // model memory mapped file
  1383. std::unique_ptr<llama_mmap> mapping;
  1384. // objects representing data potentially being locked in memory
  1385. llama_mlock mlock_buf;
  1386. llama_mlock mlock_mmap;
  1387. // for quantize-stats only
  1388. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1389. int64_t t_load_us = 0;
  1390. int64_t t_start_us = 0;
  1391. ~llama_model() {
  1392. for (struct ggml_context * ctx : ctxs) {
  1393. ggml_free(ctx);
  1394. }
  1395. for (ggml_backend_buffer_t buf : bufs) {
  1396. ggml_backend_buffer_free(buf);
  1397. }
  1398. }
  1399. };
  1400. struct llama_context {
  1401. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1402. ~llama_context() {
  1403. ggml_backend_sched_free(sched);
  1404. for (ggml_backend_t backend : backends) {
  1405. ggml_backend_free(backend);
  1406. }
  1407. }
  1408. llama_cparams cparams;
  1409. std::vector<ggml_backend_t> backends;
  1410. #ifdef GGML_USE_METAL
  1411. ggml_backend_t backend_metal = nullptr;
  1412. #endif
  1413. ggml_backend_t backend_cpu = nullptr;
  1414. const llama_model & model;
  1415. // key + value cache for the self attention
  1416. struct llama_kv_cache kv_self;
  1417. std::mt19937 rng;
  1418. bool has_evaluated_once = false;
  1419. int64_t t_start_us;
  1420. int64_t t_load_us;
  1421. int64_t t_sample_us = 0;
  1422. int64_t t_p_eval_us = 0;
  1423. int64_t t_eval_us = 0;
  1424. int32_t n_sample = 0; // number of tokens sampled
  1425. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1426. int32_t n_eval = 0; // number of eval calls
  1427. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1428. std::vector<float> logits;
  1429. #ifndef NDEBUG
  1430. // guard against access to unset logits
  1431. std::vector<bool> logits_valid;
  1432. #endif
  1433. bool logits_all = false;
  1434. // input embedding (1-dimensional array: [n_embd])
  1435. std::vector<float> embedding;
  1436. // memory buffers used to evaluate the model
  1437. std::vector<uint8_t> buf_compute_meta;
  1438. ggml_backend_sched_t sched = nullptr;
  1439. // allocator for the input tensors
  1440. ggml_tallocr * alloc = nullptr;
  1441. // temporary buffer for copying data to/from the backend
  1442. std::vector<no_init<uint8_t>> buf_copy;
  1443. #ifdef GGML_USE_MPI
  1444. ggml_mpi_context * ctx_mpi = NULL;
  1445. #endif
  1446. };
  1447. //
  1448. // kv cache helpers
  1449. //
  1450. static bool llama_kv_cache_init(
  1451. struct llama_kv_cache & cache,
  1452. const llama_model & model,
  1453. ggml_type ktype,
  1454. ggml_type vtype,
  1455. uint32_t n_ctx,
  1456. bool offload) {
  1457. const struct llama_hparams & hparams = model.hparams;
  1458. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1459. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1460. const int64_t n_layer = hparams.n_layer;
  1461. cache.has_shift = false;
  1462. cache.head = 0;
  1463. cache.size = n_ctx;
  1464. cache.used = 0;
  1465. cache.cells.clear();
  1466. cache.cells.resize(n_ctx);
  1467. #ifdef GGML_USE_CLBLAST
  1468. offload = false;
  1469. #endif
  1470. // count used buffer types
  1471. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1472. if (offload) {
  1473. for (int64_t i = 0; i < n_layer; ++i) {
  1474. buft_layer_count[model.buft_layer[i].buft]++;
  1475. }
  1476. } else {
  1477. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1478. }
  1479. // create a context for each buffer type
  1480. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1481. for (auto & it : buft_layer_count) {
  1482. int n_layers = it.second;
  1483. struct ggml_init_params params = {
  1484. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1485. /*.mem_buffer =*/ NULL,
  1486. /*.no_alloc =*/ true,
  1487. };
  1488. ggml_context * ctx = ggml_init(params);
  1489. if (!ctx) {
  1490. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1491. return false;
  1492. }
  1493. ctx_map[it.first] = ctx;
  1494. cache.ctxs.push_back(ctx);
  1495. }
  1496. cache.k_l.reserve(n_layer);
  1497. cache.v_l.reserve(n_layer);
  1498. for (int i = 0; i < (int) n_layer; i++) {
  1499. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1500. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1501. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1502. ggml_format_name(k, "cache_k_l%d", i);
  1503. ggml_format_name(v, "cache_v_l%d", i);
  1504. cache.k_l.push_back(k);
  1505. cache.v_l.push_back(v);
  1506. }
  1507. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1508. for (auto it : ctx_map) {
  1509. ggml_backend_buffer_type_t buft = it.first;
  1510. ggml_context * ctx = it.second;
  1511. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1512. if (!buf) {
  1513. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1514. return false;
  1515. }
  1516. ggml_backend_buffer_clear(buf, 0);
  1517. 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);
  1518. cache.bufs.push_back(buf);
  1519. }
  1520. return true;
  1521. }
  1522. // find an empty slot of size "n_tokens" in the cache
  1523. // updates the cache head
  1524. // Note: On success, it's important that cache.head points
  1525. // to the first cell of the slot.
  1526. static bool llama_kv_cache_find_slot(
  1527. struct llama_kv_cache & cache,
  1528. const struct llama_batch & batch) {
  1529. const uint32_t n_ctx = cache.size;
  1530. const uint32_t n_tokens = batch.n_tokens;
  1531. if (n_tokens > n_ctx) {
  1532. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1533. return false;
  1534. }
  1535. uint32_t n_tested = 0;
  1536. while (true) {
  1537. if (cache.head + n_tokens > n_ctx) {
  1538. n_tested += n_ctx - cache.head;
  1539. cache.head = 0;
  1540. continue;
  1541. }
  1542. bool found = true;
  1543. for (uint32_t i = 0; i < n_tokens; i++) {
  1544. if (cache.cells[cache.head + i].pos >= 0) {
  1545. found = false;
  1546. cache.head += i + 1;
  1547. n_tested += i + 1;
  1548. break;
  1549. }
  1550. }
  1551. if (found) {
  1552. break;
  1553. }
  1554. if (n_tested >= n_ctx) {
  1555. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1556. return false;
  1557. }
  1558. }
  1559. for (uint32_t i = 0; i < n_tokens; i++) {
  1560. cache.cells[cache.head + i].pos = batch.pos[i];
  1561. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1562. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1563. }
  1564. }
  1565. cache.used += n_tokens;
  1566. return true;
  1567. }
  1568. // find how many cells are currently in use
  1569. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1570. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1571. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1572. return i + 1;
  1573. }
  1574. }
  1575. return 0;
  1576. }
  1577. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1578. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1579. cache.cells[i].pos = -1;
  1580. cache.cells[i].seq_id.clear();
  1581. }
  1582. cache.head = 0;
  1583. cache.used = 0;
  1584. }
  1585. static void llama_kv_cache_seq_rm(
  1586. struct llama_kv_cache & cache,
  1587. llama_seq_id seq_id,
  1588. llama_pos p0,
  1589. llama_pos p1) {
  1590. uint32_t new_head = cache.size;
  1591. if (p0 < 0) p0 = 0;
  1592. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1593. for (uint32_t i = 0; i < cache.size; ++i) {
  1594. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1595. if (seq_id < 0) {
  1596. cache.cells[i].seq_id.clear();
  1597. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1598. cache.cells[i].seq_id.erase(seq_id);
  1599. } else {
  1600. continue;
  1601. }
  1602. if (cache.cells[i].seq_id.empty()) {
  1603. // keep count of the number of used cells
  1604. if (cache.cells[i].pos >= 0) cache.used--;
  1605. cache.cells[i].pos = -1;
  1606. if (new_head == cache.size) new_head = i;
  1607. }
  1608. }
  1609. }
  1610. // If we freed up a slot, set head to it so searching can start there.
  1611. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1612. }
  1613. static void llama_kv_cache_seq_cp(
  1614. struct llama_kv_cache & cache,
  1615. llama_seq_id seq_id_src,
  1616. llama_seq_id seq_id_dst,
  1617. llama_pos p0,
  1618. llama_pos p1) {
  1619. if (p0 < 0) p0 = 0;
  1620. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1621. cache.head = 0;
  1622. for (uint32_t i = 0; i < cache.size; ++i) {
  1623. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1624. cache.cells[i].seq_id.insert(seq_id_dst);
  1625. }
  1626. }
  1627. }
  1628. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1629. uint32_t new_head = cache.size;
  1630. for (uint32_t i = 0; i < cache.size; ++i) {
  1631. if (!cache.cells[i].has_seq_id(seq_id)) {
  1632. if (cache.cells[i].pos >= 0) cache.used--;
  1633. cache.cells[i].pos = -1;
  1634. cache.cells[i].seq_id.clear();
  1635. if (new_head == cache.size) new_head = i;
  1636. } else {
  1637. cache.cells[i].seq_id.clear();
  1638. cache.cells[i].seq_id.insert(seq_id);
  1639. }
  1640. }
  1641. // If we freed up a slot, set head to it so searching can start there.
  1642. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1643. }
  1644. static void llama_kv_cache_seq_shift(
  1645. struct llama_kv_cache & cache,
  1646. llama_seq_id seq_id,
  1647. llama_pos p0,
  1648. llama_pos p1,
  1649. llama_pos delta) {
  1650. uint32_t new_head = cache.size;
  1651. if (p0 < 0) p0 = 0;
  1652. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1653. for (uint32_t i = 0; i < cache.size; ++i) {
  1654. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1655. cache.has_shift = true;
  1656. cache.cells[i].pos += delta;
  1657. cache.cells[i].delta += delta;
  1658. if (cache.cells[i].pos < 0) {
  1659. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1660. cache.cells[i].pos = -1;
  1661. cache.cells[i].seq_id.clear();
  1662. if (new_head == cache.size) new_head = i;
  1663. }
  1664. }
  1665. }
  1666. // If we freed up a slot, set head to it so searching can start there.
  1667. // Otherwise we just start the next search from the beginning.
  1668. cache.head = new_head != cache.size ? new_head : 0;
  1669. }
  1670. static void llama_kv_cache_seq_div(
  1671. struct llama_kv_cache & cache,
  1672. llama_seq_id seq_id,
  1673. llama_pos p0,
  1674. llama_pos p1,
  1675. int d) {
  1676. if (p0 < 0) p0 = 0;
  1677. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1678. for (uint32_t i = 0; i < cache.size; ++i) {
  1679. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1680. cache.has_shift = true;
  1681. {
  1682. llama_pos p_old = cache.cells[i].pos;
  1683. cache.cells[i].pos /= d;
  1684. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1685. }
  1686. }
  1687. }
  1688. }
  1689. //
  1690. // model loading and saving
  1691. //
  1692. enum llama_fver {
  1693. GGUF_FILE_VERSION_V1 = 1,
  1694. GGUF_FILE_VERSION_V2 = 2,
  1695. GGUF_FILE_VERSION_V3 = 3,
  1696. };
  1697. static const char * llama_file_version_name(llama_fver version) {
  1698. switch (version) {
  1699. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1700. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1701. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1702. }
  1703. return "unknown";
  1704. }
  1705. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1706. char buf[256];
  1707. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1708. for (size_t i = 1; i < ne.size(); i++) {
  1709. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1710. }
  1711. return buf;
  1712. }
  1713. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1714. char buf[256];
  1715. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1716. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1717. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1718. }
  1719. return buf;
  1720. }
  1721. namespace GGUFMeta {
  1722. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1723. struct GKV_Base_Type {
  1724. static constexpr gguf_type gt = gt_;
  1725. static T getter(const gguf_context * ctx, const int kid) {
  1726. return gfun(ctx, kid);
  1727. }
  1728. };
  1729. template<typename T> struct GKV_Base;
  1730. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1731. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1732. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1733. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1734. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1735. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1736. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1737. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1738. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1739. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1740. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1741. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1742. template<> struct GKV_Base<std::string> {
  1743. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1744. static std::string getter(const gguf_context * ctx, const int kid) {
  1745. return gguf_get_val_str(ctx, kid);
  1746. }
  1747. };
  1748. struct ArrayInfo{
  1749. const gguf_type gt;
  1750. const size_t length;
  1751. const void * data;
  1752. };
  1753. template<> struct GKV_Base<ArrayInfo> {
  1754. public:
  1755. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1756. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1757. return ArrayInfo {
  1758. gguf_get_arr_type(ctx, k),
  1759. size_t(gguf_get_arr_n(ctx, k)),
  1760. gguf_get_arr_data(ctx, k),
  1761. };
  1762. }
  1763. };
  1764. template<typename T>
  1765. class GKV: public GKV_Base<T> {
  1766. GKV() = delete;
  1767. public:
  1768. static T get_kv(const gguf_context * ctx, const int k) {
  1769. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1770. if (kt != GKV::gt) {
  1771. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1772. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1773. }
  1774. return GKV::getter(ctx, k);
  1775. }
  1776. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1777. switch (ty) {
  1778. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1779. case LLAMA_KV_OVERRIDE_INT: return "int";
  1780. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1781. }
  1782. return "unknown";
  1783. }
  1784. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1785. if (!override) { return false; }
  1786. if (override->tag == expected_type) {
  1787. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1788. __func__, override_type_to_str(override->tag), override->key);
  1789. switch (override->tag) {
  1790. case LLAMA_KV_OVERRIDE_BOOL: {
  1791. printf("%s\n", override->bool_value ? "true" : "false");
  1792. } break;
  1793. case LLAMA_KV_OVERRIDE_INT: {
  1794. printf("%" PRId64 "\n", override->int_value);
  1795. } break;
  1796. case LLAMA_KV_OVERRIDE_FLOAT: {
  1797. printf("%.6f\n", override->float_value);
  1798. } break;
  1799. default:
  1800. // Shouldn't be possible to end up here, but just in case...
  1801. throw std::runtime_error(
  1802. format("Unsupported attempt to override %s type for metadata key %s\n",
  1803. override_type_to_str(override->tag), override->key));
  1804. }
  1805. return true;
  1806. }
  1807. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1808. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1809. return false;
  1810. }
  1811. template<typename OT>
  1812. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1813. try_override(OT & target, const struct llama_model_kv_override *override) {
  1814. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1815. target = override->bool_value;
  1816. return true;
  1817. }
  1818. return false;
  1819. }
  1820. template<typename OT>
  1821. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1822. try_override(OT & target, const struct llama_model_kv_override *override) {
  1823. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1824. target = override->int_value;
  1825. return true;
  1826. }
  1827. return false;
  1828. }
  1829. template<typename OT>
  1830. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1831. try_override(T & target, const struct llama_model_kv_override *override) {
  1832. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1833. target = override->float_value;
  1834. return true;
  1835. }
  1836. return false;
  1837. }
  1838. template<typename OT>
  1839. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1840. try_override(T & target, const struct llama_model_kv_override *override) {
  1841. (void)target;
  1842. (void)override;
  1843. if (!override) { return false; }
  1844. // Currently, we should never end up here so it would be a bug if we do.
  1845. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1846. override ? override->key : "NULL"));
  1847. }
  1848. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1849. if (try_override<T>(target, override)) {
  1850. return true;
  1851. }
  1852. if (k < 0) { return false; }
  1853. target = get_kv(ctx, k);
  1854. return true;
  1855. }
  1856. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1857. return set(ctx, gguf_find_key(ctx, key), target, override);
  1858. }
  1859. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1860. return set(ctx, key.c_str(), target, override);
  1861. }
  1862. };
  1863. }
  1864. struct llama_model_loader {
  1865. int n_kv = 0;
  1866. int n_tensors = 0;
  1867. int n_created = 0;
  1868. int64_t n_elements = 0;
  1869. size_t n_bytes = 0;
  1870. bool use_mmap = false;
  1871. llama_file file;
  1872. llama_ftype ftype;
  1873. llama_fver fver;
  1874. std::unique_ptr<llama_mmap> mapping;
  1875. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1876. struct gguf_context * ctx_gguf = NULL;
  1877. struct ggml_context * ctx_meta = NULL;
  1878. std::string arch_name;
  1879. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1880. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1881. struct gguf_init_params params = {
  1882. /*.no_alloc = */ true,
  1883. /*.ctx = */ &ctx_meta,
  1884. };
  1885. if (param_overrides_p != nullptr) {
  1886. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1887. kv_overrides.insert({std::string(p->key), *p});
  1888. }
  1889. }
  1890. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1891. if (!ctx_gguf) {
  1892. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1893. }
  1894. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1895. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1896. n_kv = gguf_get_n_kv(ctx_gguf);
  1897. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1898. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1899. for (int i = 0; i < n_tensors; i++) {
  1900. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1901. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1902. n_elements += ggml_nelements(t);
  1903. n_bytes += ggml_nbytes(t);
  1904. }
  1905. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1906. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1907. // determine file type based on the number of tensors for each quantization and print meta data
  1908. // TODO: make optional
  1909. {
  1910. std::map<enum ggml_type, uint32_t> n_type;
  1911. uint32_t n_type_max = 0;
  1912. enum ggml_type type_max = GGML_TYPE_F32;
  1913. for (int i = 0; i < n_tensors; i++) {
  1914. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  1915. n_type[type]++;
  1916. if (n_type_max < n_type[type]) {
  1917. n_type_max = n_type[type];
  1918. type_max = type;
  1919. }
  1920. // TODO: make runtime configurable
  1921. #if 0
  1922. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  1923. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  1924. #endif
  1925. }
  1926. switch (type_max) {
  1927. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1928. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1929. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1930. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1931. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1932. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1933. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1934. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1935. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1936. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1937. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1938. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1939. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  1940. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  1941. default:
  1942. {
  1943. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1944. ftype = LLAMA_FTYPE_ALL_F32;
  1945. } break;
  1946. }
  1947. // this is a way to mark that we have "guessed" the file type
  1948. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1949. {
  1950. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1951. if (kid >= 0) {
  1952. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1953. }
  1954. }
  1955. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  1956. for (int i = 0; i < n_kv; i++) {
  1957. const char * name = gguf_get_key(ctx_gguf, i);
  1958. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1959. const std::string type_name =
  1960. type == GGUF_TYPE_ARRAY
  1961. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx_gguf, i)), gguf_get_arr_n(ctx_gguf, i))
  1962. : gguf_type_name(type);
  1963. std::string value = gguf_kv_to_str(ctx_gguf, i);
  1964. const size_t MAX_VALUE_LEN = 40;
  1965. if (value.size() > MAX_VALUE_LEN) {
  1966. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  1967. }
  1968. replace_all(value, "\n", "\\n");
  1969. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  1970. }
  1971. // print type counts
  1972. for (auto & kv : n_type) {
  1973. if (kv.second == 0) {
  1974. continue;
  1975. }
  1976. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1977. }
  1978. }
  1979. if (!llama_mmap::SUPPORTED) {
  1980. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1981. use_mmap = false;
  1982. }
  1983. this->use_mmap = use_mmap;
  1984. }
  1985. ~llama_model_loader() {
  1986. if (ctx_gguf) {
  1987. gguf_free(ctx_gguf);
  1988. }
  1989. if (ctx_meta) {
  1990. ggml_free(ctx_meta);
  1991. }
  1992. }
  1993. template<typename T>
  1994. typename std::enable_if<std::is_integral<T>::value, bool>::type
  1995. get_arr_n(const std::string & key, T & result, const bool required = true) {
  1996. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  1997. if (kid < 0) {
  1998. if (required) {
  1999. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2000. }
  2001. return false;
  2002. }
  2003. struct GGUFMeta::ArrayInfo arr_info =
  2004. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2005. result = arr_info.length;
  2006. return true;
  2007. }
  2008. template<typename T>
  2009. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2010. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2011. return get_arr_n(llm_kv(kid), result, required);
  2012. }
  2013. template<typename T>
  2014. bool get_key(const std::string & key, T & result, const bool required = true) {
  2015. auto it = kv_overrides.find(key);
  2016. const struct llama_model_kv_override * override =
  2017. it != kv_overrides.end() ? &it->second : nullptr;
  2018. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2019. if (required && !found) {
  2020. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2021. }
  2022. return found;
  2023. }
  2024. template<typename T>
  2025. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2026. return get_key(llm_kv(kid), result, required);
  2027. }
  2028. std::string get_arch_name() const {
  2029. return arch_name;
  2030. }
  2031. enum llm_arch get_arch() const {
  2032. return llm_kv.arch;
  2033. }
  2034. const char * get_tensor_name(int i) const {
  2035. return gguf_get_tensor_name(ctx_gguf, i);
  2036. }
  2037. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2038. return ggml_get_tensor(ctx_meta, name);
  2039. }
  2040. struct ggml_tensor * get_tensor_meta(int i) const {
  2041. return get_tensor_meta(get_tensor_name(i));
  2042. }
  2043. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2044. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2045. ggml_set_name(tensor, ggml_get_name(meta));
  2046. n_created++;
  2047. return tensor;
  2048. }
  2049. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2050. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2051. if (cur == NULL) {
  2052. if (!required) {
  2053. return NULL;
  2054. }
  2055. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2056. }
  2057. {
  2058. bool is_ok = true;
  2059. for (size_t i = 0; i < ne.size(); ++i) {
  2060. if (ne[i] != cur->ne[i]) {
  2061. is_ok = false;
  2062. break;
  2063. }
  2064. }
  2065. if (!is_ok) {
  2066. throw std::runtime_error(
  2067. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2068. __func__, name.c_str(),
  2069. llama_format_tensor_shape(ne).c_str(),
  2070. llama_format_tensor_shape(cur).c_str()));
  2071. }
  2072. }
  2073. return create_tensor_for(ctx, cur);
  2074. }
  2075. void done_getting_tensors() const {
  2076. if (n_created != n_tensors) {
  2077. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2078. }
  2079. }
  2080. size_t file_offset(const char * name) const {
  2081. const int idx = gguf_find_tensor(ctx_gguf, name);
  2082. if (idx < 0) {
  2083. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2084. }
  2085. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2086. }
  2087. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2088. // prefetch the whole file - all the data is needed anyway
  2089. if (use_mmap) {
  2090. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2091. }
  2092. // compute the total size of all tensors for progress reporting
  2093. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2094. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2095. size_data += ggml_nbytes(cur);
  2096. }
  2097. if (use_mmap && mapping) {
  2098. if (lmlock) {
  2099. lmlock->init(mapping->addr);
  2100. }
  2101. mmap_used_first = mapping->size;
  2102. }
  2103. }
  2104. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2105. GGML_ASSERT(mapping);
  2106. *first = mapping->size;
  2107. *last = 0;
  2108. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2109. const size_t offs = file_offset(ggml_get_name(tensor));
  2110. *first = std::min(*first, offs);
  2111. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2112. }
  2113. }
  2114. // for backwards compatibility, does not support ggml-backend
  2115. void load_data_for(struct ggml_tensor * cur) const {
  2116. const size_t offs = file_offset(ggml_get_name(cur));
  2117. if (use_mmap && mapping) {
  2118. if (cur->data == nullptr) {
  2119. cur->data = (uint8_t *)mapping->addr + offs;
  2120. } else {
  2121. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2122. }
  2123. } else {
  2124. GGML_ASSERT(cur->data != nullptr);
  2125. file.seek(offs, SEEK_SET);
  2126. file.read_raw(cur->data, ggml_nbytes(cur));
  2127. }
  2128. }
  2129. size_t size_done = 0;
  2130. size_t size_data = 0;
  2131. size_t mmap_used_first = -1;
  2132. size_t mmap_used_last = 0;
  2133. // Returns false if cancelled by progress_callback
  2134. bool load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, ggml_backend_buffer_t buf_mmap, llama_mlock * lmlock) {
  2135. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2136. std::vector<no_init<uint8_t>> read_buf;
  2137. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2138. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2139. if (!cur) {
  2140. // some tensors may be allocated in a different context
  2141. continue;
  2142. }
  2143. if (progress_callback) {
  2144. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2145. return false;
  2146. }
  2147. }
  2148. const size_t offs = file_offset(ggml_get_name(cur));
  2149. if (use_mmap && mapping) {
  2150. if (buf_mmap && cur->data == nullptr) {
  2151. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2152. if (lmlock) {
  2153. lmlock->grow_to(offs + ggml_nbytes(cur));
  2154. }
  2155. mmap_used_first = std::min(mmap_used_first, offs);
  2156. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2157. } else {
  2158. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2159. }
  2160. } else {
  2161. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2162. file.seek(offs, SEEK_SET);
  2163. file.read_raw(cur->data, ggml_nbytes(cur));
  2164. } else {
  2165. read_buf.resize(ggml_nbytes(cur));
  2166. file.seek(offs, SEEK_SET);
  2167. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2168. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2169. }
  2170. }
  2171. size_done += ggml_nbytes(cur);
  2172. }
  2173. // check if this is the last call and do final cleanup
  2174. if (size_done >= size_data) {
  2175. // unmap offloaded tensors and metadata
  2176. if (use_mmap && mapping) {
  2177. mapping->unmap_fragment(0, mmap_used_first);
  2178. if (mmap_used_last != 0) {
  2179. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2180. }
  2181. }
  2182. if (progress_callback) {
  2183. // Even though the model is done loading, we still honor
  2184. // cancellation since we need to free allocations.
  2185. return progress_callback(1.0f, progress_callback_user_data);
  2186. }
  2187. }
  2188. return true;
  2189. }
  2190. };
  2191. //
  2192. // load LLaMA models
  2193. //
  2194. static std::string llama_model_arch_name(llm_arch arch) {
  2195. auto it = LLM_ARCH_NAMES.find(arch);
  2196. if (it == LLM_ARCH_NAMES.end()) {
  2197. return "unknown";
  2198. }
  2199. return it->second;
  2200. }
  2201. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2202. if (ftype & LLAMA_FTYPE_GUESSED) {
  2203. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2204. }
  2205. switch (ftype) {
  2206. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2207. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2208. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2209. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2210. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2211. return "Q4_1, some F16";
  2212. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2213. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2214. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2215. // K-quants
  2216. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2217. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2218. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2219. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2220. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2221. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2222. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2223. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2224. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2225. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2226. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2227. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2228. default: return "unknown, may not work";
  2229. }
  2230. }
  2231. static const char * llama_model_type_name(e_model type) {
  2232. switch (type) {
  2233. case MODEL_1B: return "1B";
  2234. case MODEL_3B: return "3B";
  2235. case MODEL_7B: return "7B";
  2236. case MODEL_8B: return "8B";
  2237. case MODEL_13B: return "13B";
  2238. case MODEL_15B: return "15B";
  2239. case MODEL_30B: return "30B";
  2240. case MODEL_34B: return "34B";
  2241. case MODEL_40B: return "40B";
  2242. case MODEL_65B: return "65B";
  2243. case MODEL_70B: return "70B";
  2244. case MODEL_SMALL: return "0.1B";
  2245. case MODEL_MEDIUM: return "0.4B";
  2246. case MODEL_LARGE: return "0.8B";
  2247. case MODEL_XL: return "1.5B";
  2248. default: return "?B";
  2249. }
  2250. }
  2251. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2252. model.arch = ml.get_arch();
  2253. if (model.arch == LLM_ARCH_UNKNOWN) {
  2254. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2255. }
  2256. }
  2257. static void llm_load_hparams(
  2258. llama_model_loader & ml,
  2259. llama_model & model) {
  2260. auto & hparams = model.hparams;
  2261. const gguf_context * ctx = ml.ctx_gguf;
  2262. // get metadata as string
  2263. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2264. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2265. if (type == GGUF_TYPE_ARRAY) {
  2266. continue;
  2267. }
  2268. const char * name = gguf_get_key(ctx, i);
  2269. const std::string value = gguf_kv_to_str(ctx, i);
  2270. model.gguf_kv.emplace(name, value);
  2271. }
  2272. // get general kv
  2273. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2274. // get hparams kv
  2275. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2276. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2277. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2278. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2279. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2280. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2281. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2282. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2283. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2284. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2285. if (hparams.n_expert > 0) {
  2286. GGML_ASSERT(hparams.n_expert_used > 0);
  2287. } else {
  2288. GGML_ASSERT(hparams.n_expert_used == 0);
  2289. }
  2290. // n_head_kv is optional, default to n_head
  2291. hparams.n_head_kv = hparams.n_head;
  2292. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2293. bool rope_finetuned = false;
  2294. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2295. hparams.rope_finetuned = rope_finetuned;
  2296. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2297. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2298. // rope_freq_base (optional)
  2299. hparams.rope_freq_base_train = 10000.0f;
  2300. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2301. std::string rope_scaling("linear");
  2302. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2303. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2304. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2305. // rope_freq_scale (inverse of the kv) is optional
  2306. float ropescale = 0.0f;
  2307. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2308. // try the old key name
  2309. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2310. }
  2311. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2312. // sanity check for n_rot (optional)
  2313. {
  2314. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2315. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2316. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2317. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2318. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2319. }
  2320. }
  2321. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2322. // gpt-j n_rot = rotary_dim
  2323. }
  2324. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2325. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2326. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2327. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2328. // arch-specific KVs
  2329. switch (model.arch) {
  2330. case LLM_ARCH_LLAMA:
  2331. {
  2332. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2333. switch (hparams.n_layer) {
  2334. case 22: model.type = e_model::MODEL_1B; break;
  2335. case 26: model.type = e_model::MODEL_3B; break;
  2336. case 32: model.type = e_model::MODEL_7B; break;
  2337. case 40: model.type = e_model::MODEL_13B; break;
  2338. case 48: model.type = e_model::MODEL_34B; break;
  2339. case 60: model.type = e_model::MODEL_30B; break;
  2340. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2341. default: model.type = e_model::MODEL_UNKNOWN;
  2342. }
  2343. } break;
  2344. case LLM_ARCH_FALCON:
  2345. {
  2346. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2347. switch (hparams.n_layer) {
  2348. case 32: model.type = e_model::MODEL_7B; break;
  2349. case 60: model.type = e_model::MODEL_40B; break;
  2350. default: model.type = e_model::MODEL_UNKNOWN;
  2351. }
  2352. } break;
  2353. case LLM_ARCH_BAICHUAN:
  2354. {
  2355. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2356. switch (hparams.n_layer) {
  2357. case 32: model.type = e_model::MODEL_7B; break;
  2358. case 40: model.type = e_model::MODEL_13B; break;
  2359. default: model.type = e_model::MODEL_UNKNOWN;
  2360. }
  2361. } break;
  2362. case LLM_ARCH_STARCODER:
  2363. {
  2364. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2365. switch (hparams.n_layer) {
  2366. case 24: model.type = e_model::MODEL_1B; break;
  2367. case 36: model.type = e_model::MODEL_3B; break;
  2368. case 42: model.type = e_model::MODEL_7B; break;
  2369. case 40: model.type = e_model::MODEL_15B; break;
  2370. default: model.type = e_model::MODEL_UNKNOWN;
  2371. }
  2372. } break;
  2373. case LLM_ARCH_PERSIMMON:
  2374. {
  2375. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2376. switch (hparams.n_layer) {
  2377. case 36: model.type = e_model::MODEL_8B; break;
  2378. default: model.type = e_model::MODEL_UNKNOWN;
  2379. }
  2380. } break;
  2381. case LLM_ARCH_REFACT:
  2382. {
  2383. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2384. switch (hparams.n_layer) {
  2385. case 32: model.type = e_model::MODEL_1B; break;
  2386. default: model.type = e_model::MODEL_UNKNOWN;
  2387. }
  2388. } break;
  2389. case LLM_ARCH_BLOOM:
  2390. {
  2391. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2392. switch (hparams.n_layer) {
  2393. case 24: model.type = e_model::MODEL_1B; break;
  2394. case 30:
  2395. switch (hparams.n_embd) {
  2396. case 2560: model.type = e_model::MODEL_3B; break;
  2397. case 4096: model.type = e_model::MODEL_7B; break;
  2398. } break;
  2399. }
  2400. } break;
  2401. case LLM_ARCH_MPT:
  2402. {
  2403. hparams.f_clamp_kqv = 0.0f;
  2404. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2405. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2406. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2407. switch (hparams.n_layer) {
  2408. case 32: model.type = e_model::MODEL_7B; break;
  2409. case 48: model.type = e_model::MODEL_30B; break;
  2410. default: model.type = e_model::MODEL_UNKNOWN;
  2411. }
  2412. } break;
  2413. case LLM_ARCH_STABLELM:
  2414. {
  2415. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2416. switch (hparams.n_layer) {
  2417. case 32: model.type = e_model::MODEL_3B; break;
  2418. default: model.type = e_model::MODEL_UNKNOWN;
  2419. }
  2420. } break;
  2421. case LLM_ARCH_QWEN:
  2422. {
  2423. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2424. switch (hparams.n_layer) {
  2425. case 32: model.type = e_model::MODEL_7B; break;
  2426. case 40: model.type = e_model::MODEL_13B; break;
  2427. default: model.type = e_model::MODEL_UNKNOWN;
  2428. }
  2429. } break;
  2430. case LLM_ARCH_PHI2:
  2431. {
  2432. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2433. switch (hparams.n_layer) {
  2434. case 24: model.type = e_model::MODEL_1B; break;
  2435. case 32: model.type = e_model::MODEL_3B; break;
  2436. default: model.type = e_model::MODEL_UNKNOWN;
  2437. }
  2438. } break;
  2439. case LLM_ARCH_PLAMO:
  2440. {
  2441. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2442. switch (hparams.n_layer) {
  2443. case 40: model.type = e_model::MODEL_13B; break;
  2444. default: model.type = e_model::MODEL_UNKNOWN;
  2445. }
  2446. } break;
  2447. case LLM_ARCH_GPT2:
  2448. {
  2449. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2450. switch (hparams.n_layer) {
  2451. case 12: model.type = e_model::MODEL_SMALL; break;
  2452. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2453. case 36: model.type = e_model::MODEL_LARGE; break;
  2454. case 48: model.type = e_model::MODEL_XL; break;
  2455. default: model.type = e_model::MODEL_UNKNOWN;
  2456. }
  2457. } break;
  2458. default: (void)0;
  2459. }
  2460. model.ftype = ml.ftype;
  2461. }
  2462. // TODO: This should probably be in llama.h
  2463. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2464. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2465. static void llm_load_vocab(
  2466. llama_model_loader & ml,
  2467. llama_model & model) {
  2468. auto & vocab = model.vocab;
  2469. struct gguf_context * ctx = ml.ctx_gguf;
  2470. const auto kv = LLM_KV(model.arch);
  2471. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2472. if (token_idx == -1) {
  2473. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2474. }
  2475. const float * scores = nullptr;
  2476. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2477. if (score_idx != -1) {
  2478. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2479. }
  2480. const int * toktypes = nullptr;
  2481. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2482. if (toktype_idx != -1) {
  2483. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2484. }
  2485. // determine vocab type
  2486. {
  2487. std::string tokenizer_name;
  2488. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2489. if (tokenizer_name == "llama") {
  2490. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2491. // default special tokens
  2492. vocab.special_bos_id = 1;
  2493. vocab.special_eos_id = 2;
  2494. vocab.special_unk_id = 0;
  2495. vocab.special_sep_id = -1;
  2496. vocab.special_pad_id = -1;
  2497. } else if (tokenizer_name == "gpt2") {
  2498. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2499. // read bpe merges and populate bpe ranks
  2500. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2501. if (merges_keyidx == -1) {
  2502. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2503. }
  2504. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2505. for (int i = 0; i < n_merges; i++) {
  2506. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2507. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2508. std::string first;
  2509. std::string second;
  2510. const size_t pos = word.find(' ', 1);
  2511. if (pos != std::string::npos) {
  2512. first = word.substr(0, pos);
  2513. second = word.substr(pos + 1);
  2514. }
  2515. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2516. }
  2517. // default special tokens
  2518. vocab.special_bos_id = 11;
  2519. vocab.special_eos_id = 11;
  2520. vocab.special_unk_id = -1;
  2521. vocab.special_sep_id = -1;
  2522. vocab.special_pad_id = -1;
  2523. } else {
  2524. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2525. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2526. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2527. }
  2528. }
  2529. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2530. vocab.id_to_token.resize(n_vocab);
  2531. for (uint32_t i = 0; i < n_vocab; i++) {
  2532. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2533. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2534. vocab.token_to_id[word] = i;
  2535. auto & token_data = vocab.id_to_token[i];
  2536. token_data.text = std::move(word);
  2537. token_data.score = scores ? scores[i] : 0.0f;
  2538. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2539. }
  2540. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2541. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2542. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2543. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2544. } else {
  2545. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2546. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2547. vocab.linefeed_id = ids[0];
  2548. }
  2549. // special tokens
  2550. {
  2551. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2552. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2553. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2554. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2555. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2556. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2557. };
  2558. for (const auto & it : special_token_types) {
  2559. const std::string & key = kv(std::get<0>(it));
  2560. int32_t & id = std::get<1>(it);
  2561. uint32_t new_id;
  2562. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2563. continue;
  2564. }
  2565. if (new_id >= vocab.id_to_token.size()) {
  2566. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2567. __func__, key.c_str(), new_id, id);
  2568. } else {
  2569. id = new_id;
  2570. }
  2571. }
  2572. // Handle add_bos_token and add_eos_token
  2573. {
  2574. bool temp = true;
  2575. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2576. vocab.special_add_bos = int(temp);
  2577. }
  2578. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2579. vocab.special_add_eos = int(temp);
  2580. }
  2581. }
  2582. }
  2583. // build special tokens cache
  2584. {
  2585. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2586. // and will always be correctly labeled in 'added_tokens.json' etc.
  2587. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2588. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2589. // are special tokens.
  2590. // From testing, this appears to correlate 1:1 with special tokens.
  2591. //
  2592. // Counting special tokens and verifying in only one direction
  2593. // is sufficient to detect difference in those two sets.
  2594. //
  2595. uint32_t special_tokens_count_by_type = 0;
  2596. uint32_t special_tokens_count_from_verification = 0;
  2597. bool special_tokens_definition_mismatch = false;
  2598. for (const auto & t : vocab.token_to_id) {
  2599. const auto & token = t.first;
  2600. const auto & id = t.second;
  2601. // Count all non-normal tokens in the vocab while iterating
  2602. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2603. special_tokens_count_by_type++;
  2604. }
  2605. // Skip single character tokens
  2606. if (token.length() > 1) {
  2607. bool is_tokenizable = false;
  2608. // Split token string representation in two, in all possible ways
  2609. // and check if both halves can be matched to a valid token
  2610. for (unsigned i = 1; i < token.length();) {
  2611. const auto left = token.substr(0, i);
  2612. const auto right = token.substr(i);
  2613. // check if we didnt partition in the middle of a utf sequence
  2614. auto utf = utf8_len(left.at(left.length() - 1));
  2615. if (utf == 1) {
  2616. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2617. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2618. is_tokenizable = true;
  2619. break;
  2620. }
  2621. i++;
  2622. } else {
  2623. // skip over the rest of multibyte utf sequence
  2624. i += utf - 1;
  2625. }
  2626. }
  2627. if (!is_tokenizable) {
  2628. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2629. // it's faster to re-filter them here, since there are way less candidates now
  2630. // Calculate a total "utf" length of a token string representation
  2631. size_t utf8_str_len = 0;
  2632. for (unsigned i = 0; i < token.length();) {
  2633. utf8_str_len++;
  2634. i += utf8_len(token.at(i));
  2635. }
  2636. // And skip the ones which are one character
  2637. if (utf8_str_len > 1) {
  2638. // At this point what we have left are special tokens only
  2639. vocab.special_tokens_cache[token] = id;
  2640. // Count manually found special tokens
  2641. special_tokens_count_from_verification++;
  2642. // If this manually found special token is not marked as such, flag a mismatch
  2643. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2644. special_tokens_definition_mismatch = true;
  2645. }
  2646. }
  2647. }
  2648. }
  2649. }
  2650. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2651. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2652. __func__,
  2653. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2654. special_tokens_count_by_type, vocab.id_to_token.size()
  2655. );
  2656. } else {
  2657. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2658. __func__,
  2659. special_tokens_count_from_verification, vocab.id_to_token.size()
  2660. );
  2661. }
  2662. }
  2663. }
  2664. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2665. const auto & hparams = model.hparams;
  2666. const auto & vocab = model.vocab;
  2667. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2668. // hparams
  2669. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2670. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2671. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2672. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2673. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2674. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2675. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2676. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2677. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2678. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2679. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2680. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2681. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2682. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2683. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2684. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2685. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2686. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2687. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2688. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2689. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2690. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2691. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2692. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2693. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2694. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2695. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2696. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2697. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2698. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2699. if (ml.n_elements >= 1e12) {
  2700. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2701. } else if (ml.n_elements >= 1e9) {
  2702. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2703. } else if (ml.n_elements >= 1e6) {
  2704. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2705. } else {
  2706. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2707. }
  2708. if (ml.n_bytes < GiB) {
  2709. 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);
  2710. } else {
  2711. 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);
  2712. }
  2713. // general kv
  2714. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2715. // special tokens
  2716. 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() ); }
  2717. 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() ); }
  2718. 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() ); }
  2719. 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() ); }
  2720. 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() ); }
  2721. 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() ); }
  2722. }
  2723. // Returns false if cancelled by progress_callback
  2724. static bool llm_load_tensors(
  2725. llama_model_loader & ml,
  2726. llama_model & model,
  2727. int n_gpu_layers,
  2728. enum llama_split_mode split_mode,
  2729. int main_gpu,
  2730. const float * tensor_split,
  2731. bool use_mlock,
  2732. llama_progress_callback progress_callback,
  2733. void * progress_callback_user_data) {
  2734. model.t_start_us = ggml_time_us();
  2735. auto & hparams = model.hparams;
  2736. model.split_mode = split_mode;
  2737. model.main_gpu = main_gpu;
  2738. model.n_gpu_layers = n_gpu_layers;
  2739. const int64_t n_layer = hparams.n_layer;
  2740. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2741. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2742. model.buft_input = llama_default_buffer_type_cpu(true);
  2743. model.buft_layer.resize(n_layer);
  2744. // assign cpu layers
  2745. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2746. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2747. }
  2748. #ifdef GGML_USE_CUBLAS
  2749. if (split_mode == LLAMA_SPLIT_LAYER) {
  2750. // calculate the split points
  2751. int device_count = ggml_backend_cuda_get_device_count();
  2752. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2753. float splits[GGML_CUDA_MAX_DEVICES];
  2754. if (all_zero) {
  2755. // default split, by free memory
  2756. for (int i = 0; i < device_count; ++i) {
  2757. size_t total;
  2758. size_t free;
  2759. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2760. splits[i] = free;
  2761. }
  2762. } else {
  2763. std::copy(tensor_split, tensor_split + device_count, splits);
  2764. }
  2765. // sum and normalize the splits to get the split points
  2766. float split_sum = 0.0f;
  2767. for (int i = 0; i < device_count; ++i) {
  2768. split_sum += splits[i];
  2769. splits[i] = split_sum;
  2770. }
  2771. for (int i = 0; i < device_count; ++i) {
  2772. splits[i] /= split_sum;
  2773. }
  2774. // assign the repeating layers to the devices according to the splits
  2775. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2776. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2777. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2778. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2779. }
  2780. // assign the output layer
  2781. if (n_gpu_layers > n_layer) {
  2782. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2783. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2784. } else {
  2785. model.buft_output = llama_default_buffer_type_cpu(true);
  2786. }
  2787. } else
  2788. #endif
  2789. {
  2790. ggml_backend_buffer_type_t split_buft;
  2791. if (split_mode == LLAMA_SPLIT_ROW) {
  2792. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2793. } else {
  2794. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2795. split_buft = llama_default_buffer_type_offload(main_gpu);
  2796. }
  2797. // assign the repeating layers
  2798. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2799. model.buft_layer[i] = {
  2800. split_buft,
  2801. llama_default_buffer_type_offload(main_gpu)
  2802. };
  2803. }
  2804. // assign the output layer
  2805. if (n_gpu_layers > n_layer) {
  2806. model.buft_output = {
  2807. split_buft,
  2808. llama_default_buffer_type_offload(main_gpu)
  2809. };
  2810. } else {
  2811. model.buft_output = llama_default_buffer_type_cpu(true);
  2812. }
  2813. }
  2814. // count used buffer types
  2815. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2816. buft_layer_count[model.buft_input.buft]++;
  2817. buft_layer_count[model.buft_input.buft_matrix]++;
  2818. buft_layer_count[model.buft_output.buft]++;
  2819. buft_layer_count[model.buft_output.buft_matrix]++;
  2820. for (int64_t i = 0; i < n_layer; ++i) {
  2821. buft_layer_count[model.buft_layer[i].buft]++;
  2822. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2823. }
  2824. // create one context per buffer type
  2825. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2826. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2827. for (auto & it : buft_layer_count) {
  2828. struct ggml_init_params params = {
  2829. /*.mem_size =*/ ctx_size,
  2830. /*.mem_buffer =*/ NULL,
  2831. /*.no_alloc =*/ true,
  2832. };
  2833. ggml_context * ctx = ggml_init(params);
  2834. if (!ctx) {
  2835. throw std::runtime_error(format("failed to create context"));
  2836. }
  2837. ctx_map[it.first] = ctx;
  2838. model.ctxs.push_back(ctx);
  2839. }
  2840. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2841. // create tensors for the weights
  2842. {
  2843. const int64_t n_embd = hparams.n_embd;
  2844. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2845. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2846. const int64_t n_embd_gqa = n_embd_v_gqa;
  2847. const int64_t n_vocab = hparams.n_vocab;
  2848. const int64_t n_ff = hparams.n_ff;
  2849. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2850. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2851. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2852. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2853. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2854. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2855. model.layers.resize(n_layer);
  2856. const auto tn = LLM_TN(model.arch);
  2857. switch (model.arch) {
  2858. case LLM_ARCH_LLAMA:
  2859. case LLM_ARCH_REFACT:
  2860. {
  2861. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2862. // output
  2863. {
  2864. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2865. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2866. }
  2867. for (int i = 0; i < n_layer; ++i) {
  2868. ggml_context * ctx_layer = ctx_for_layer(i);
  2869. ggml_context * ctx_split = ctx_for_layer_split(i);
  2870. auto & layer = model.layers[i];
  2871. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2872. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2873. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2874. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2875. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2876. // optional bias tensors
  2877. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  2878. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  2879. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  2880. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  2881. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2882. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  2883. if (layer.ffn_gate_inp == nullptr) {
  2884. GGML_ASSERT(hparams.n_expert == 0);
  2885. GGML_ASSERT(hparams.n_expert_used == 0);
  2886. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2887. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2888. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2889. } else {
  2890. GGML_ASSERT(hparams.n_expert > 0);
  2891. GGML_ASSERT(hparams.n_expert_used > 0);
  2892. // MoE branch
  2893. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2894. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  2895. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  2896. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  2897. }
  2898. }
  2899. }
  2900. } break;
  2901. case LLM_ARCH_BAICHUAN:
  2902. {
  2903. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2904. {
  2905. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2906. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2907. }
  2908. for (int i = 0; i < n_layer; ++i) {
  2909. ggml_context * ctx_layer = ctx_for_layer(i);
  2910. ggml_context * ctx_split = ctx_for_layer_split(i);
  2911. auto & layer = model.layers[i];
  2912. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2913. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2914. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2915. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2916. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2917. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2918. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2919. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2920. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2921. }
  2922. } break;
  2923. case LLM_ARCH_FALCON:
  2924. {
  2925. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2926. // output
  2927. {
  2928. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2929. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  2930. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2931. }
  2932. for (int i = 0; i < n_layer; ++i) {
  2933. ggml_context * ctx_layer = ctx_for_layer(i);
  2934. ggml_context * ctx_split = ctx_for_layer_split(i);
  2935. auto & layer = model.layers[i];
  2936. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2937. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  2938. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  2939. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  2940. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  2941. }
  2942. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  2943. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2944. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2945. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2946. }
  2947. } break;
  2948. case LLM_ARCH_STARCODER:
  2949. {
  2950. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2951. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  2952. // output
  2953. {
  2954. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2955. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  2956. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2957. }
  2958. for (int i = 0; i < n_layer; ++i) {
  2959. ggml_context * ctx_layer = ctx_for_layer(i);
  2960. ggml_context * ctx_split = ctx_for_layer_split(i);
  2961. auto & layer = model.layers[i];
  2962. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2963. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  2964. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  2965. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  2966. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2967. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  2968. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2969. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  2970. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  2971. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  2972. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2973. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  2974. }
  2975. } break;
  2976. case LLM_ARCH_PERSIMMON:
  2977. {
  2978. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2979. {
  2980. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2981. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  2982. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2983. }
  2984. for (int i = 0; i < n_layer; ++i) {
  2985. ggml_context * ctx_layer = ctx_for_layer(i);
  2986. ggml_context * ctx_split = ctx_for_layer_split(i);
  2987. auto & layer = model.layers[i];
  2988. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2989. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  2990. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  2991. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  2992. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2993. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  2994. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  2995. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  2996. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2997. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  2998. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2999. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3000. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3001. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3002. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3003. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3004. }
  3005. } break;
  3006. case LLM_ARCH_BLOOM:
  3007. {
  3008. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3009. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3010. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3011. // output
  3012. {
  3013. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3014. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3015. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3016. }
  3017. for (int i = 0; i < n_layer; ++i) {
  3018. ggml_context * ctx_layer = ctx_for_layer(i);
  3019. ggml_context * ctx_split = ctx_for_layer_split(i);
  3020. auto & layer = model.layers[i];
  3021. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3022. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3023. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3024. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3025. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3026. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3027. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3028. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3029. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3030. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3031. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3032. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3033. }
  3034. } break;
  3035. case LLM_ARCH_MPT:
  3036. {
  3037. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3038. // output
  3039. {
  3040. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3041. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3042. }
  3043. for (int i = 0; i < n_layer; ++i) {
  3044. ggml_context * ctx_layer = ctx_for_layer(i);
  3045. ggml_context * ctx_split = ctx_for_layer_split(i);
  3046. auto & layer = model.layers[i];
  3047. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3048. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3049. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3050. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3051. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3052. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3053. // AWQ ScaleActivation layer
  3054. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3055. }
  3056. } break;
  3057. case LLM_ARCH_STABLELM:
  3058. {
  3059. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3060. // output
  3061. {
  3062. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3063. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3064. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3065. }
  3066. for (int i = 0; i < n_layer; ++i) {
  3067. ggml_context * ctx_layer = ctx_for_layer(i);
  3068. ggml_context * ctx_split = ctx_for_layer_split(i);
  3069. auto & layer = model.layers[i];
  3070. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3071. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3072. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3073. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3074. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3075. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3076. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3077. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3078. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3079. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3080. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3081. }
  3082. } break;
  3083. case LLM_ARCH_QWEN:
  3084. {
  3085. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3086. // output
  3087. {
  3088. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3089. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3090. }
  3091. for (int i = 0; i < n_layer; ++i) {
  3092. ggml_context * ctx_layer = ctx_for_layer(i);
  3093. ggml_context * ctx_split = ctx_for_layer_split(i);
  3094. auto & layer = model.layers[i];
  3095. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3096. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3097. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3098. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3099. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3100. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3101. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3102. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3103. }
  3104. } break;
  3105. case LLM_ARCH_PHI2:
  3106. {
  3107. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3108. // output
  3109. {
  3110. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3111. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3112. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3113. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3114. }
  3115. for (int i = 0; i < n_layer; ++i) {
  3116. ggml_context * ctx_layer = ctx_for_layer(i);
  3117. ggml_context * ctx_split = ctx_for_layer_split(i);
  3118. auto & layer = model.layers[i];
  3119. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3120. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3121. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3122. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3123. if (layer.wqkv == nullptr) {
  3124. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3125. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3126. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3127. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3128. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3129. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3130. }
  3131. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3132. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3133. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3134. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3135. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3136. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3137. }
  3138. } break;
  3139. case LLM_ARCH_PLAMO:
  3140. {
  3141. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3142. // output
  3143. {
  3144. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3145. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3146. }
  3147. for (int i = 0; i < n_layer; ++i) {
  3148. ggml_context * ctx_layer = ctx_for_layer(i);
  3149. ggml_context * ctx_split = ctx_for_layer_split(i);
  3150. auto & layer = model.layers[i];
  3151. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3152. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3153. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3154. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3155. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3156. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3157. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3158. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3159. }
  3160. } break;
  3161. case LLM_ARCH_GPT2:
  3162. {
  3163. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3164. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3165. // output
  3166. {
  3167. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3168. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3169. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3170. }
  3171. for (int i = 0; i < n_layer; ++i) {
  3172. ggml_context * ctx_layer = ctx_for_layer(i);
  3173. ggml_context * ctx_split = ctx_for_layer_split(i);
  3174. auto & layer = model.layers[i];
  3175. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3176. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3177. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3178. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3179. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3180. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3181. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3182. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3183. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3184. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3185. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3186. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3187. }
  3188. } break;
  3189. default:
  3190. throw std::runtime_error("unknown architecture");
  3191. }
  3192. }
  3193. ml.done_getting_tensors();
  3194. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3195. // create the backend buffers
  3196. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3197. for (auto & it : ctx_map) {
  3198. ggml_backend_buffer_type_t buft = it.first;
  3199. ggml_context * ctx = it.second;
  3200. ggml_backend_buffer_t buf = nullptr;
  3201. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3202. // 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
  3203. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3204. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3205. size_t first, last;
  3206. ml.get_mapping_range(&first, &last, ctx);
  3207. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3208. }
  3209. #ifdef GGML_USE_METAL
  3210. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3211. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3212. size_t first, last;
  3213. ml.get_mapping_range(&first, &last, ctx);
  3214. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3215. }
  3216. #endif
  3217. else {
  3218. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3219. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3220. model.mlock_buf.init (ggml_backend_buffer_get_base(buf));
  3221. model.mlock_buf.grow_to(ggml_backend_buffer_get_size(buf));
  3222. }
  3223. }
  3224. if (buf == nullptr) {
  3225. throw std::runtime_error("failed to allocate buffer");
  3226. }
  3227. // indicate that this buffer contains weights
  3228. // 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
  3229. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3230. model.bufs.push_back(buf);
  3231. ctx_bufs.emplace_back(ctx, buf);
  3232. }
  3233. // print memory requirements
  3234. {
  3235. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3236. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3237. if (n_gpu_layers > (int) hparams.n_layer) {
  3238. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3239. }
  3240. const int max_backend_supported_layers = hparams.n_layer + 1;
  3241. const int max_offloadable_layers = hparams.n_layer + 1;
  3242. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3243. for (ggml_backend_buffer_t buf : model.bufs) {
  3244. 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);
  3245. }
  3246. }
  3247. // populate tensors_by_name
  3248. for (ggml_context * ctx : model.ctxs) {
  3249. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3250. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3251. }
  3252. }
  3253. // load tensor data
  3254. for (auto & it : ctx_bufs) {
  3255. ggml_context * ctx = it.first;
  3256. ggml_backend_buffer_t buf = it.second;
  3257. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3258. return false;
  3259. }
  3260. }
  3261. model.mapping = std::move(ml.mapping);
  3262. // loading time will be recalculate after the first eval, so
  3263. // we take page faults deferred by mmap() into consideration
  3264. model.t_load_us = ggml_time_us() - model.t_start_us;
  3265. return true;
  3266. }
  3267. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3268. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3269. try {
  3270. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3271. model.hparams.vocab_only = params.vocab_only;
  3272. llm_load_arch (ml, model);
  3273. llm_load_hparams(ml, model);
  3274. llm_load_vocab (ml, model);
  3275. llm_load_print_meta(ml, model);
  3276. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3277. throw std::runtime_error("vocab size mismatch");
  3278. }
  3279. if (params.vocab_only) {
  3280. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3281. return 0;
  3282. }
  3283. if (!llm_load_tensors(
  3284. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3285. params.progress_callback, params.progress_callback_user_data
  3286. )) {
  3287. return -2;
  3288. }
  3289. } catch (const std::exception & err) {
  3290. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3291. return -1;
  3292. }
  3293. return 0;
  3294. }
  3295. //
  3296. // llm_build
  3297. //
  3298. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3299. enum llm_rope_type {
  3300. LLM_ROPE,
  3301. LLM_ROPE_NEOX,
  3302. LLM_ROPE_GLM,
  3303. };
  3304. enum llm_ffn_op_type {
  3305. LLM_FFN_SILU,
  3306. LLM_FFN_GELU,
  3307. LLM_FFN_RELU,
  3308. LLM_FFN_RELU_SQR,
  3309. };
  3310. enum llm_ffn_gate_type {
  3311. LLM_FFN_SEQ,
  3312. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3313. };
  3314. enum llm_norm_type {
  3315. LLM_NORM,
  3316. LLM_NORM_RMS,
  3317. };
  3318. static struct ggml_tensor * llm_build_inp_embd(
  3319. struct ggml_context * ctx,
  3320. const llama_hparams & hparams,
  3321. const llama_batch & batch,
  3322. struct ggml_tensor * tok_embd,
  3323. const llm_build_cb & cb) {
  3324. const int64_t n_embd = hparams.n_embd;
  3325. struct ggml_tensor * inpL;
  3326. if (batch.token) {
  3327. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  3328. cb(inp_tokens, "inp_tokens", -1);
  3329. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  3330. } else {
  3331. #ifdef GGML_USE_MPI
  3332. GGML_ASSERT(false && "not implemented");
  3333. #endif
  3334. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  3335. }
  3336. return inpL;
  3337. }
  3338. // Persimmon: n_rot = n_embd_head_k/2
  3339. // Other: n_rot = n_embd_head_k
  3340. static void llm_build_k_shift(
  3341. struct ggml_context * ctx,
  3342. const llama_hparams & hparams,
  3343. const llama_cparams & cparams,
  3344. const llama_kv_cache & kv,
  3345. struct ggml_cgraph * graph,
  3346. llm_rope_type type,
  3347. int64_t n_ctx,
  3348. float freq_base,
  3349. float freq_scale,
  3350. const llm_build_cb & cb) {
  3351. const int64_t n_layer = hparams.n_layer;
  3352. const int64_t n_head_kv = hparams.n_head_kv;
  3353. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3354. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3355. const int32_t n_rot = hparams.n_rot;
  3356. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3357. const float ext_factor = cparams.yarn_ext_factor;
  3358. const float attn_factor = cparams.yarn_attn_factor;
  3359. const float beta_fast = cparams.yarn_beta_fast;
  3360. const float beta_slow = cparams.yarn_beta_slow;
  3361. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  3362. cb(K_shift, "K_shift", -1);
  3363. int rope_type = 0;
  3364. switch (type) {
  3365. case LLM_ROPE: rope_type = 0; break;
  3366. case LLM_ROPE_NEOX: rope_type = 2; break;
  3367. case LLM_ROPE_GLM: rope_type = 4; break;
  3368. }
  3369. for (int il = 0; il < n_layer; ++il) {
  3370. struct ggml_tensor * tmp =
  3371. // we rotate only the first n_rot dimensions
  3372. ggml_rope_custom_inplace(ctx,
  3373. ggml_view_3d(ctx, kv.k_l[il],
  3374. n_embd_head_k, n_head_kv, n_ctx,
  3375. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3376. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3377. 0),
  3378. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3379. ext_factor, attn_factor, beta_fast, beta_slow);
  3380. cb(tmp, "K_shifted", il);
  3381. ggml_build_forward_expand(graph, tmp);
  3382. }
  3383. }
  3384. static void llm_build_kv_store(
  3385. struct ggml_context * ctx,
  3386. const llama_hparams & hparams,
  3387. const llama_kv_cache & kv,
  3388. struct ggml_cgraph * graph,
  3389. struct ggml_tensor * k_cur,
  3390. struct ggml_tensor * v_cur,
  3391. int64_t n_ctx,
  3392. int32_t n_tokens,
  3393. int32_t kv_head,
  3394. const llm_build_cb & cb,
  3395. int64_t il) {
  3396. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3397. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3398. // compute the transposed [n_tokens, n_embd] V matrix
  3399. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3400. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3401. cb(v_cur_t, "v_cur_t", il);
  3402. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3403. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3404. cb(k_cache_view, "k_cache_view", il);
  3405. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3406. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3407. (kv_head)*ggml_element_size(kv.v_l[il]));
  3408. cb(v_cache_view, "v_cache_view", il);
  3409. // important: storing RoPE-ed version of K in the KV cache!
  3410. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3411. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3412. }
  3413. static struct ggml_tensor * llm_build_norm(
  3414. struct ggml_context * ctx,
  3415. struct ggml_tensor * cur,
  3416. const llama_hparams & hparams,
  3417. struct ggml_tensor * mw,
  3418. struct ggml_tensor * mb,
  3419. llm_norm_type type,
  3420. const llm_build_cb & cb,
  3421. int il) {
  3422. switch (type) {
  3423. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3424. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3425. }
  3426. if (mw || mb) {
  3427. cb(cur, "norm", il);
  3428. }
  3429. if (mw) {
  3430. cur = ggml_mul(ctx, cur, mw);
  3431. if (mb) {
  3432. cb(cur, "norm_w", il);
  3433. }
  3434. }
  3435. if (mb) {
  3436. cur = ggml_add(ctx, cur, mb);
  3437. }
  3438. return cur;
  3439. }
  3440. static struct ggml_tensor * llm_build_ffn(
  3441. struct ggml_context * ctx,
  3442. struct ggml_tensor * cur,
  3443. struct ggml_tensor * up,
  3444. struct ggml_tensor * up_b,
  3445. struct ggml_tensor * gate,
  3446. struct ggml_tensor * gate_b,
  3447. struct ggml_tensor * down,
  3448. struct ggml_tensor * down_b,
  3449. struct ggml_tensor * act_scales,
  3450. llm_ffn_op_type type_op,
  3451. llm_ffn_gate_type type_gate,
  3452. const llm_build_cb & cb,
  3453. int il) {
  3454. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3455. cb(tmp, "ffn_up", il);
  3456. if (up_b) {
  3457. tmp = ggml_add(ctx, tmp, up_b);
  3458. cb(tmp, "ffn_up_b", il);
  3459. }
  3460. if (gate) {
  3461. switch (type_gate) {
  3462. case LLM_FFN_SEQ:
  3463. {
  3464. cur = ggml_mul_mat(ctx, gate, tmp);
  3465. cb(cur, "ffn_gate", il);
  3466. } break;
  3467. case LLM_FFN_PAR:
  3468. {
  3469. cur = ggml_mul_mat(ctx, gate, cur);
  3470. cb(cur, "ffn_gate", il);
  3471. } break;
  3472. }
  3473. if (gate_b) {
  3474. cur = ggml_add(ctx, cur, gate_b);
  3475. cb(cur, "ffn_gate_b", il);
  3476. }
  3477. } else {
  3478. cur = tmp;
  3479. }
  3480. switch (type_op) {
  3481. case LLM_FFN_SILU:
  3482. {
  3483. cur = ggml_silu(ctx, cur);
  3484. cb(cur, "ffn_silu", il);
  3485. } break;
  3486. case LLM_FFN_GELU:
  3487. {
  3488. cur = ggml_gelu(ctx, cur);
  3489. cb(cur, "ffn_gelu", il);
  3490. if (act_scales != NULL) {
  3491. cur = ggml_div(ctx, cur, act_scales);
  3492. cb(cur, "ffn_act", il);
  3493. }
  3494. } break;
  3495. case LLM_FFN_RELU:
  3496. {
  3497. cur = ggml_relu(ctx, cur);
  3498. cb(cur, "ffn_relu", il);
  3499. } break;
  3500. case LLM_FFN_RELU_SQR:
  3501. {
  3502. cur = ggml_relu(ctx, cur);
  3503. cb(cur, "ffn_relu", il);
  3504. cur = ggml_sqr(ctx, cur);
  3505. cb(cur, "ffn_sqr(relu)", il);
  3506. } break;
  3507. }
  3508. if (type_gate == LLM_FFN_PAR) {
  3509. cur = ggml_mul(ctx, cur, tmp);
  3510. cb(cur, "ffn_gate_par", il);
  3511. }
  3512. cur = ggml_mul_mat(ctx, down, cur);
  3513. if (down_b) {
  3514. cb(cur, "ffn_down", il);
  3515. }
  3516. if (down_b) {
  3517. cur = ggml_add(ctx, cur, down_b);
  3518. }
  3519. return cur;
  3520. }
  3521. // if max_alibi_bias > 0 then apply ALiBi
  3522. static struct ggml_tensor * llm_build_kqv(
  3523. struct ggml_context * ctx,
  3524. const llama_model & model,
  3525. const llama_hparams & hparams,
  3526. const llama_kv_cache & kv,
  3527. struct ggml_tensor * wo,
  3528. struct ggml_tensor * wo_b,
  3529. struct ggml_tensor * q_cur,
  3530. struct ggml_tensor * kq_mask,
  3531. int64_t n_ctx,
  3532. int32_t n_tokens,
  3533. int32_t n_kv,
  3534. float max_alibi_bias,
  3535. float kq_scale,
  3536. const llm_build_cb & cb,
  3537. int il) {
  3538. const int64_t n_head = hparams.n_head;
  3539. const int64_t n_head_kv = hparams.n_head_kv;
  3540. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3541. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3542. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3543. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3544. cb(q, "q", il);
  3545. struct ggml_tensor * k =
  3546. ggml_view_3d(ctx, kv.k_l[il],
  3547. n_embd_head_k, n_kv, n_head_kv,
  3548. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3549. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3550. 0);
  3551. cb(k, "k", il);
  3552. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3553. cb(kq, "kq", il);
  3554. if (model.arch == LLM_ARCH_PHI2) {
  3555. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3556. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3557. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3558. }
  3559. if (max_alibi_bias > 0.0f) {
  3560. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3561. kq = ggml_scale(ctx, kq, kq_scale);
  3562. cb(kq, "kq_scaled", il);
  3563. if (max_alibi_bias > 0.0f) {
  3564. // TODO: n_head or n_head_kv
  3565. // TODO: K-shift is likely not working
  3566. // TODO: change to ggml_add
  3567. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3568. cb(kq, "kq_scaled_alibi", il);
  3569. }
  3570. kq = ggml_add(ctx, kq, kq_mask);
  3571. cb(kq, "kq_masked", il);
  3572. kq = ggml_soft_max(ctx, kq);
  3573. cb(kq, "kq_soft_max", il);
  3574. } else {
  3575. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3576. cb(kq, "kq_soft_max_ext", il);
  3577. }
  3578. // split cached v into n_head heads
  3579. struct ggml_tensor * v =
  3580. ggml_view_3d(ctx, kv.v_l[il],
  3581. n_kv, n_embd_head_v, n_head_kv,
  3582. ggml_element_size(kv.v_l[il])*n_ctx,
  3583. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3584. 0);
  3585. cb(v, "v", il);
  3586. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3587. cb(kqv, "kqv", il);
  3588. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3589. cb(kqv_merged, "kqv_merged", il);
  3590. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3591. cb(cur, "kqv_merged_cont", il);
  3592. cur = ggml_mul_mat(ctx, wo, cur);
  3593. if (wo_b) {
  3594. cb(cur, "kqv_wo", il);
  3595. }
  3596. if (wo_b) {
  3597. cur = ggml_add(ctx, cur, wo_b);
  3598. }
  3599. return cur;
  3600. }
  3601. struct llm_build_context {
  3602. const llama_model & model;
  3603. const llama_hparams & hparams;
  3604. const llama_cparams & cparams;
  3605. const llama_batch & batch;
  3606. const llama_kv_cache & kv_self;
  3607. const int64_t n_embd;
  3608. const int64_t n_layer;
  3609. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3610. const int64_t n_head;
  3611. const int64_t n_head_kv;
  3612. const int64_t n_embd_head_k;
  3613. const int64_t n_embd_k_gqa;
  3614. const int64_t n_embd_head_v;
  3615. const int64_t n_embd_v_gqa;
  3616. const int64_t n_expert;
  3617. const int64_t n_expert_used;
  3618. const float freq_base;
  3619. const float freq_scale;
  3620. const float ext_factor;
  3621. const float attn_factor;
  3622. const float beta_fast;
  3623. const float beta_slow;
  3624. const float norm_eps;
  3625. const float norm_rms_eps;
  3626. const int32_t n_tokens;
  3627. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3628. const int32_t kv_head; // index of where we store new KV data in the cache
  3629. const int32_t n_orig_ctx;
  3630. const bool do_rope_shift;
  3631. const llm_build_cb & cb;
  3632. std::vector<uint8_t> & buf_compute_meta;
  3633. struct ggml_context * ctx0 = nullptr;
  3634. // TODO: consider making the entire interface noexcept
  3635. llm_build_context(
  3636. llama_context & lctx,
  3637. const llama_batch & batch,
  3638. const llm_build_cb & cb,
  3639. bool worst_case) :
  3640. model (lctx.model),
  3641. hparams (model.hparams),
  3642. cparams (lctx.cparams),
  3643. batch (batch),
  3644. kv_self (lctx.kv_self),
  3645. n_embd (hparams.n_embd),
  3646. n_layer (hparams.n_layer),
  3647. n_ctx (cparams.n_ctx),
  3648. n_head (hparams.n_head),
  3649. n_head_kv (hparams.n_head_kv),
  3650. n_embd_head_k (hparams.n_embd_head_k),
  3651. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3652. n_embd_head_v (hparams.n_embd_head_v),
  3653. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3654. n_expert (hparams.n_expert),
  3655. n_expert_used (hparams.n_expert_used),
  3656. freq_base (cparams.rope_freq_base),
  3657. freq_scale (cparams.rope_freq_scale),
  3658. ext_factor (cparams.yarn_ext_factor),
  3659. attn_factor (cparams.yarn_attn_factor),
  3660. beta_fast (cparams.yarn_beta_fast),
  3661. beta_slow (cparams.yarn_beta_slow),
  3662. norm_eps (hparams.f_norm_eps),
  3663. norm_rms_eps (hparams.f_norm_rms_eps),
  3664. n_tokens (batch.n_tokens),
  3665. n_kv (worst_case ? n_ctx : kv_self.n),
  3666. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3667. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3668. do_rope_shift (worst_case || kv_self.has_shift),
  3669. cb (cb),
  3670. buf_compute_meta (lctx.buf_compute_meta) {
  3671. // all initializations should be done in init()
  3672. }
  3673. void init() {
  3674. struct ggml_init_params params = {
  3675. /*.mem_size =*/ buf_compute_meta.size(),
  3676. /*.mem_buffer =*/ buf_compute_meta.data(),
  3677. /*.no_alloc =*/ true,
  3678. };
  3679. ctx0 = ggml_init(params);
  3680. }
  3681. void free() {
  3682. if (ctx0) {
  3683. ggml_free(ctx0);
  3684. ctx0 = nullptr;
  3685. }
  3686. }
  3687. struct ggml_cgraph * build_llama() {
  3688. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3689. const int64_t n_embd_head = hparams.n_embd_head_v;
  3690. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3691. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3692. struct ggml_tensor * cur;
  3693. struct ggml_tensor * inpL;
  3694. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3695. cb(inpL, "inp_embd", -1);
  3696. // inp_pos - contains the positions
  3697. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3698. cb(inp_pos, "inp_pos", -1);
  3699. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3700. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3701. cb(KQ_mask, "KQ_mask", -1);
  3702. // shift the entire K-cache if needed
  3703. if (do_rope_shift) {
  3704. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3705. }
  3706. for (int il = 0; il < n_layer; ++il) {
  3707. struct ggml_tensor * inpSA = inpL;
  3708. // norm
  3709. cur = llm_build_norm(ctx0, inpL, hparams,
  3710. model.layers[il].attn_norm, NULL,
  3711. LLM_NORM_RMS, cb, il);
  3712. cb(cur, "attn_norm", il);
  3713. // self-attention
  3714. {
  3715. // compute Q and K and RoPE them
  3716. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3717. cb(Qcur, "Qcur", il);
  3718. if (model.layers[il].bq) {
  3719. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3720. cb(Qcur, "Qcur", il);
  3721. }
  3722. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3723. cb(Kcur, "Kcur", il);
  3724. if (model.layers[il].bk) {
  3725. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3726. cb(Kcur, "Kcur", il);
  3727. }
  3728. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3729. cb(Vcur, "Vcur", il);
  3730. if (model.layers[il].bv) {
  3731. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3732. cb(Vcur, "Vcur", il);
  3733. }
  3734. // these nodes are added to the graph together so that they are not reordered
  3735. // by doing so, the number of splits in the graph is reduced
  3736. ggml_build_forward_expand(gf, Qcur);
  3737. ggml_build_forward_expand(gf, Kcur);
  3738. ggml_build_forward_expand(gf, Vcur);
  3739. Qcur = ggml_rope_custom(
  3740. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3741. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3742. ext_factor, attn_factor, beta_fast, beta_slow
  3743. );
  3744. cb(Qcur, "Qcur", il);
  3745. Kcur = ggml_rope_custom(
  3746. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3747. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3748. ext_factor, attn_factor, beta_fast, beta_slow
  3749. );
  3750. cb(Kcur, "Kcur", il);
  3751. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3752. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  3753. model.layers[il].wo, model.layers[il].bo,
  3754. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3755. cb(cur, "kqv_out", il);
  3756. }
  3757. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3758. cb(ffn_inp, "ffn_inp", il);
  3759. // feed-forward network
  3760. if (model.layers[il].ffn_gate_inp == nullptr) {
  3761. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3762. model.layers[il].ffn_norm, NULL,
  3763. LLM_NORM_RMS, cb, il);
  3764. cb(cur, "ffn_norm", il);
  3765. cur = llm_build_ffn(ctx0, cur,
  3766. model.layers[il].ffn_up, NULL,
  3767. model.layers[il].ffn_gate, NULL,
  3768. model.layers[il].ffn_down, NULL,
  3769. NULL,
  3770. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3771. cb(cur, "ffn_out", il);
  3772. } else {
  3773. // MoE branch
  3774. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3775. model.layers[il].ffn_norm, NULL,
  3776. LLM_NORM_RMS, cb, il);
  3777. cb(cur, "ffn_norm", il);
  3778. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3779. cb(logits, "ffn_moe_logits", il);
  3780. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3781. cb(probs, "ffn_moe_probs", il);
  3782. // select experts
  3783. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3784. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3785. ggml_tensor * weights = ggml_get_rows(ctx0,
  3786. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3787. cb(weights, "ffn_moe_weights", il);
  3788. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3789. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3790. cb(weights_sum, "ffn_moe_weights_sum", il);
  3791. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3792. cb(weights, "ffn_moe_weights_norm", il);
  3793. // compute expert outputs
  3794. ggml_tensor * moe_out = nullptr;
  3795. for (int i = 0; i < n_expert_used; ++i) {
  3796. ggml_tensor * cur_expert;
  3797. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3798. cb(cur_up, "ffn_moe_up", il);
  3799. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3800. cb(cur_gate, "ffn_moe_gate", il);
  3801. cur_gate = ggml_silu(ctx0, cur_gate);
  3802. cb(cur_gate, "ffn_moe_silu", il);
  3803. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3804. cb(cur_expert, "ffn_moe_gate_par", il);
  3805. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3806. cb(cur_expert, "ffn_moe_down", il);
  3807. cur_expert = ggml_mul(ctx0, cur_expert,
  3808. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3809. cb(cur_expert, "ffn_moe_weighted", il);
  3810. if (i == 0) {
  3811. moe_out = cur_expert;
  3812. } else {
  3813. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3814. cb(moe_out, "ffn_moe_out", il);
  3815. }
  3816. }
  3817. cur = moe_out;
  3818. }
  3819. cur = ggml_add(ctx0, cur, ffn_inp);
  3820. cb(cur, "l_out", il);
  3821. // input for next layer
  3822. inpL = cur;
  3823. }
  3824. cur = inpL;
  3825. cur = llm_build_norm(ctx0, cur, hparams,
  3826. model.output_norm, NULL,
  3827. LLM_NORM_RMS, cb, -1);
  3828. cb(cur, "result_norm", -1);
  3829. // lm_head
  3830. cur = ggml_mul_mat(ctx0, model.output, cur);
  3831. cb(cur, "result_output", -1);
  3832. ggml_build_forward_expand(gf, cur);
  3833. return gf;
  3834. }
  3835. struct ggml_cgraph * build_baichuan() {
  3836. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3837. const int64_t n_embd_head = hparams.n_embd_head_v;
  3838. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3839. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3840. struct ggml_tensor * cur;
  3841. struct ggml_tensor * inpL;
  3842. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3843. cb(inpL, "inp_embd", -1);
  3844. // inp_pos - contains the positions
  3845. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3846. cb(inp_pos, "inp_pos", -1);
  3847. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3848. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3849. cb(KQ_mask, "KQ_mask", -1);
  3850. // shift the entire K-cache if needed
  3851. if (do_rope_shift) {
  3852. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3853. }
  3854. for (int il = 0; il < n_layer; ++il) {
  3855. struct ggml_tensor * inpSA = inpL;
  3856. cur = llm_build_norm(ctx0, inpL, hparams,
  3857. model.layers[il].attn_norm, NULL,
  3858. LLM_NORM_RMS, cb, il);
  3859. cb(cur, "attn_norm", il);
  3860. // self-attention
  3861. {
  3862. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3863. cb(Qcur, "Qcur", il);
  3864. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3865. cb(Kcur, "Kcur", il);
  3866. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3867. cb(Vcur, "Vcur", il);
  3868. switch (model.type) {
  3869. case MODEL_7B:
  3870. Qcur = ggml_rope_custom(
  3871. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3872. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3873. ext_factor, attn_factor, beta_fast, beta_slow
  3874. );
  3875. Kcur = ggml_rope_custom(
  3876. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3877. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3878. ext_factor, attn_factor, beta_fast, beta_slow
  3879. );
  3880. break;
  3881. case MODEL_13B:
  3882. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  3883. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  3884. break;
  3885. default:
  3886. GGML_ASSERT(false);
  3887. }
  3888. cb(Qcur, "Qcur", il);
  3889. cb(Kcur, "Kcur", il);
  3890. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3891. // apply ALiBi for 13B model
  3892. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  3893. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  3894. model.layers[il].wo, NULL,
  3895. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3896. cb(cur, "kqv_out", il);
  3897. }
  3898. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3899. cb(ffn_inp, "ffn_inp", il);
  3900. // feed-forward network
  3901. {
  3902. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3903. model.layers[il].ffn_norm, NULL,
  3904. LLM_NORM_RMS, cb, il);
  3905. cb(cur, "ffn_norm", il);
  3906. cur = llm_build_ffn(ctx0, cur,
  3907. model.layers[il].ffn_up, NULL,
  3908. model.layers[il].ffn_gate, NULL,
  3909. model.layers[il].ffn_down, NULL,
  3910. NULL,
  3911. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3912. cb(cur, "ffn_out", il);
  3913. }
  3914. cur = ggml_add(ctx0, cur, ffn_inp);
  3915. cb(cur, "l_out", il);
  3916. // input for next layer
  3917. inpL = cur;
  3918. }
  3919. cur = inpL;
  3920. cur = llm_build_norm(ctx0, cur, hparams,
  3921. model.output_norm, NULL,
  3922. LLM_NORM_RMS, cb, -1);
  3923. cb(cur, "result_norm", -1);
  3924. // lm_head
  3925. cur = ggml_mul_mat(ctx0, model.output, cur);
  3926. cb(cur, "result_output", -1);
  3927. ggml_build_forward_expand(gf, cur);
  3928. return gf;
  3929. }
  3930. struct ggml_cgraph * build_falcon() {
  3931. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3932. const int64_t n_embd_head = hparams.n_embd_head_v;
  3933. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  3934. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3935. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3936. struct ggml_tensor * cur;
  3937. struct ggml_tensor * inpL;
  3938. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3939. cb(inpL, "inp_embd", -1);
  3940. // inp_pos - contains the positions
  3941. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3942. cb(inp_pos, "inp_pos", -1);
  3943. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3944. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3945. cb(KQ_mask, "KQ_mask", -1);
  3946. // shift the entire K-cache if needed
  3947. if (do_rope_shift) {
  3948. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  3949. }
  3950. for (int il = 0; il < n_layer; ++il) {
  3951. struct ggml_tensor * attn_norm;
  3952. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  3953. model.layers[il].attn_norm,
  3954. model.layers[il].attn_norm_b,
  3955. LLM_NORM, cb, il);
  3956. cb(attn_norm, "attn_norm", il);
  3957. // self-attention
  3958. {
  3959. if (model.layers[il].attn_norm_2) {
  3960. // Falcon-40B
  3961. cur = llm_build_norm(ctx0, inpL, hparams,
  3962. model.layers[il].attn_norm_2,
  3963. model.layers[il].attn_norm_2_b,
  3964. LLM_NORM, cb, il);
  3965. cb(cur, "attn_norm_2", il);
  3966. } else {
  3967. cur = attn_norm;
  3968. }
  3969. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  3970. cb(cur, "wqkv", il);
  3971. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  3972. 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)));
  3973. 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)));
  3974. cb(Qcur, "Qcur", il);
  3975. cb(Kcur, "Kcur", il);
  3976. cb(Vcur, "Vcur", il);
  3977. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  3978. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  3979. // using mode = 2 for neox mode
  3980. Qcur = ggml_rope_custom(
  3981. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  3982. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3983. );
  3984. cb(Qcur, "Qcur", il);
  3985. Kcur = ggml_rope_custom(
  3986. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  3987. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  3988. );
  3989. cb(Kcur, "Kcur", il);
  3990. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3991. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  3992. model.layers[il].wo, NULL,
  3993. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3994. cb(cur, "kqv_out", il);
  3995. }
  3996. struct ggml_tensor * ffn_inp = cur;
  3997. // feed forward
  3998. {
  3999. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4000. model.layers[il].ffn_up, NULL,
  4001. NULL, NULL,
  4002. model.layers[il].ffn_down, NULL,
  4003. NULL,
  4004. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4005. cb(cur, "ffn_out", il);
  4006. }
  4007. cur = ggml_add(ctx0, cur, ffn_inp);
  4008. cb(cur, "l_out", il);
  4009. cur = ggml_add(ctx0, cur, inpL);
  4010. cb(cur, "l_out", il);
  4011. // input for next layer
  4012. inpL = cur;
  4013. }
  4014. cur = inpL;
  4015. // norm
  4016. cur = llm_build_norm(ctx0, cur, hparams,
  4017. model.output_norm,
  4018. model.output_norm_b,
  4019. LLM_NORM, cb, -1);
  4020. cb(cur, "result_norm", -1);
  4021. cur = ggml_mul_mat(ctx0, model.output, cur);
  4022. cb(cur, "result_output", -1);
  4023. ggml_build_forward_expand(gf, cur);
  4024. return gf;
  4025. }
  4026. struct ggml_cgraph * build_starcoder() {
  4027. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4028. const int64_t n_embd_head = hparams.n_embd_head_v;
  4029. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4030. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4031. struct ggml_tensor * cur;
  4032. struct ggml_tensor * pos;
  4033. struct ggml_tensor * inpL;
  4034. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4035. cb(inpL, "inp_embd", -1);
  4036. // inp_pos - contains the positions
  4037. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4038. cb(inp_pos, "inp_pos", -1);
  4039. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4040. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4041. cb(KQ_mask, "KQ_mask", -1);
  4042. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4043. cb(pos, "pos_embd", -1);
  4044. inpL = ggml_add(ctx0, inpL, pos);
  4045. cb(inpL, "inpL", -1);
  4046. for (int il = 0; il < n_layer; ++il) {
  4047. cur = llm_build_norm(ctx0, inpL, hparams,
  4048. model.layers[il].attn_norm,
  4049. model.layers[il].attn_norm_b,
  4050. LLM_NORM, cb, il);
  4051. cb(cur, "attn_norm", il);
  4052. // self-attention
  4053. {
  4054. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4055. cb(cur, "wqkv", il);
  4056. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4057. cb(cur, "bqkv", il);
  4058. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4059. 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)));
  4060. 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)));
  4061. cb(Qcur, "Qcur", il);
  4062. cb(Kcur, "Kcur", il);
  4063. cb(Vcur, "Vcur", il);
  4064. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4065. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4066. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4067. model.layers[il].wo, model.layers[il].bo,
  4068. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4069. cb(cur, "kqv_out", il);
  4070. }
  4071. // add the input
  4072. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4073. cb(ffn_inp, "ffn_inp", il);
  4074. // FF
  4075. {
  4076. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4077. model.layers[il].ffn_norm,
  4078. model.layers[il].ffn_norm_b,
  4079. LLM_NORM, cb, il);
  4080. cb(cur, "ffn_norm", il);
  4081. cur = llm_build_ffn(ctx0, cur,
  4082. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4083. NULL, NULL,
  4084. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4085. NULL,
  4086. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4087. cb(cur, "ffn_out", il);
  4088. }
  4089. inpL = ggml_add(ctx0, cur, ffn_inp);
  4090. cb(inpL, "l_out", il);
  4091. }
  4092. cur = llm_build_norm(ctx0, inpL, hparams,
  4093. model.output_norm,
  4094. model.output_norm_b,
  4095. LLM_NORM, cb, -1);
  4096. cb(cur, "result_norm", -1);
  4097. cur = ggml_mul_mat(ctx0, model.output, cur);
  4098. cb(cur, "result_output", -1);
  4099. ggml_build_forward_expand(gf, cur);
  4100. return gf;
  4101. }
  4102. struct ggml_cgraph * build_persimmon() {
  4103. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4104. const int64_t n_embd_head = hparams.n_embd_head_v;
  4105. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4106. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4107. struct ggml_tensor * cur;
  4108. struct ggml_tensor * inpL;
  4109. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4110. cb(inpL, "inp_embd", -1);
  4111. // inp_pos - contains the positions
  4112. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4113. cb(inp_pos, "inp_pos", -1);
  4114. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4115. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4116. cb(KQ_mask, "KQ_mask", -1);
  4117. if (do_rope_shift) {
  4118. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4119. }
  4120. for (int il = 0; il < n_layer; ++il) {
  4121. struct ggml_tensor * residual = inpL;
  4122. cur = llm_build_norm(ctx0, inpL, hparams,
  4123. model.layers[il].attn_norm,
  4124. model.layers[il].attn_norm_b,
  4125. LLM_NORM, cb, il);
  4126. cb(cur, "attn_norm", il);
  4127. // self attention
  4128. {
  4129. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4130. cb(cur, "wqkv", il);
  4131. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4132. cb(cur, "bqkv", il);
  4133. // split qkv
  4134. GGML_ASSERT(n_head_kv == n_head);
  4135. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4136. cb(tmpqkv, "tmpqkv", il);
  4137. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4138. cb(tmpqkv_perm, "tmpqkv", il);
  4139. struct ggml_tensor * tmpq = ggml_view_3d(
  4140. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4141. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4142. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4143. 0
  4144. );
  4145. cb(tmpq, "tmpq", il);
  4146. struct ggml_tensor * tmpk = ggml_view_3d(
  4147. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4148. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4149. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4150. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4151. );
  4152. cb(tmpk, "tmpk", il);
  4153. // Q/K Layernorm
  4154. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4155. model.layers[il].attn_q_norm,
  4156. model.layers[il].attn_q_norm_b,
  4157. LLM_NORM, cb, il);
  4158. cb(tmpq, "tmpq", il);
  4159. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4160. model.layers[il].attn_k_norm,
  4161. model.layers[il].attn_k_norm_b,
  4162. LLM_NORM, cb, il);
  4163. cb(tmpk, "tmpk", il);
  4164. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4165. struct ggml_tensor * qrot = ggml_view_3d(
  4166. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4167. ggml_element_size(tmpq) * n_embd_head,
  4168. ggml_element_size(tmpq) * n_embd_head * n_head,
  4169. 0
  4170. );
  4171. cb(qrot, "qrot", il);
  4172. struct ggml_tensor * krot = ggml_view_3d(
  4173. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4174. ggml_element_size(tmpk) * n_embd_head,
  4175. ggml_element_size(tmpk) * n_embd_head * n_head,
  4176. 0
  4177. );
  4178. cb(krot, "krot", il);
  4179. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4180. struct ggml_tensor * qpass = ggml_view_3d(
  4181. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4182. ggml_element_size(tmpq) * n_embd_head,
  4183. ggml_element_size(tmpq) * n_embd_head * n_head,
  4184. ggml_element_size(tmpq) * hparams.n_rot
  4185. );
  4186. cb(qpass, "qpass", il);
  4187. struct ggml_tensor * kpass = ggml_view_3d(
  4188. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4189. ggml_element_size(tmpk) * n_embd_head,
  4190. ggml_element_size(tmpk) * n_embd_head * n_head,
  4191. ggml_element_size(tmpk) * hparams.n_rot
  4192. );
  4193. cb(kpass, "kpass", il);
  4194. struct ggml_tensor * qrotated = ggml_rope_custom(
  4195. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4196. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4197. );
  4198. cb(qrotated, "qrotated", il);
  4199. struct ggml_tensor * krotated = ggml_rope_custom(
  4200. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4201. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4202. );
  4203. cb(krotated, "krotated", il);
  4204. // ggml currently only supports concatenation on dim=2
  4205. // so we need to permute qrot, qpass, concat, then permute back.
  4206. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4207. cb(qrotated, "qrotated", il);
  4208. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4209. cb(krotated, "krotated", il);
  4210. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4211. cb(qpass, "qpass", il);
  4212. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4213. cb(kpass, "kpass", il);
  4214. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4215. cb(Qcur, "Qcur", il);
  4216. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4217. cb(Kcur, "Kcur", il);
  4218. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4219. cb(Q, "Q", il);
  4220. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4221. cb(Kcur, "Kcur", il);
  4222. struct ggml_tensor * Vcur = ggml_view_3d(
  4223. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4224. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4225. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4226. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4227. );
  4228. cb(Vcur, "Vcur", il);
  4229. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4230. // TODO: not tested, could be broken
  4231. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4232. model.layers[il].wo, model.layers[il].bo,
  4233. Q, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4234. cb(cur, "kqv_out", il);
  4235. }
  4236. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4237. cb(ffn_inp, "ffn_inp", il);
  4238. // feed-forward network
  4239. {
  4240. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4241. model.layers[il].ffn_norm,
  4242. model.layers[il].ffn_norm_b,
  4243. LLM_NORM, cb, il);
  4244. cb(cur, "ffn_norm", il);
  4245. cur = llm_build_ffn(ctx0, cur,
  4246. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4247. NULL, NULL,
  4248. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4249. NULL,
  4250. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4251. cb(cur, "ffn_out", il);
  4252. }
  4253. cur = ggml_add(ctx0, cur, ffn_inp);
  4254. cb(cur, "l_out", il);
  4255. inpL = cur;
  4256. }
  4257. cur = inpL;
  4258. cur = llm_build_norm(ctx0, cur, hparams,
  4259. model.output_norm,
  4260. model.output_norm_b,
  4261. LLM_NORM, cb, -1);
  4262. cb(cur, "result_norm", -1);
  4263. cur = ggml_mul_mat(ctx0, model.output, cur);
  4264. cb(cur, "result_output", -1);
  4265. ggml_build_forward_expand(gf, cur);
  4266. return gf;
  4267. }
  4268. struct ggml_cgraph * build_refact() {
  4269. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4270. const int64_t n_embd_head = hparams.n_embd_head_v;
  4271. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4272. struct ggml_tensor * cur;
  4273. struct ggml_tensor * inpL;
  4274. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4275. cb(inpL, "inp_embd", -1);
  4276. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4277. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4278. cb(KQ_mask, "KQ_mask", -1);
  4279. for (int il = 0; il < n_layer; ++il) {
  4280. struct ggml_tensor * inpSA = inpL;
  4281. cur = llm_build_norm(ctx0, inpL, hparams,
  4282. model.layers[il].attn_norm, NULL,
  4283. LLM_NORM_RMS, cb, il);
  4284. cb(cur, "attn_norm", il);
  4285. // self-attention
  4286. {
  4287. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4288. cb(Qcur, "Qcur", il);
  4289. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4290. cb(Kcur, "Kcur", il);
  4291. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4292. cb(Vcur, "Vcur", il);
  4293. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4294. cb(Kcur, "Kcur", il);
  4295. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4296. cb(Qcur, "Qcur", il);
  4297. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4298. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4299. model.layers[il].wo, NULL,
  4300. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4301. cb(cur, "kqv_out", il);
  4302. }
  4303. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4304. cb(ffn_inp, "ffn_inp", il);
  4305. // feed-forward network
  4306. {
  4307. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4308. model.layers[il].ffn_norm, NULL,
  4309. LLM_NORM_RMS, cb, il);
  4310. cb(cur, "ffn_norm", il);
  4311. cur = llm_build_ffn(ctx0, cur,
  4312. model.layers[il].ffn_up, NULL,
  4313. model.layers[il].ffn_gate, NULL,
  4314. model.layers[il].ffn_down, NULL,
  4315. NULL,
  4316. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4317. cb(cur, "ffn_out", il);
  4318. }
  4319. cur = ggml_add(ctx0, cur, ffn_inp);
  4320. cb(cur, "l_out", il);
  4321. // input for next layer
  4322. inpL = cur;
  4323. }
  4324. cur = inpL;
  4325. cur = llm_build_norm(ctx0, cur, hparams,
  4326. model.output_norm, NULL,
  4327. LLM_NORM_RMS, cb, -1);
  4328. cb(cur, "result_norm", -1);
  4329. // lm_head
  4330. cur = ggml_mul_mat(ctx0, model.output, cur);
  4331. cb(cur, "result_output", -1);
  4332. ggml_build_forward_expand(gf, cur);
  4333. return gf;
  4334. }
  4335. struct ggml_cgraph * build_bloom() {
  4336. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4337. const int64_t n_embd_head = hparams.n_embd_head_v;
  4338. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4339. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4340. struct ggml_tensor * cur;
  4341. struct ggml_tensor * inpL;
  4342. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4343. cb(inpL, "inp_embd", -1);
  4344. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4345. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4346. cb(KQ_mask, "KQ_mask", -1);
  4347. inpL = llm_build_norm(ctx0, inpL, hparams,
  4348. model.tok_norm,
  4349. model.tok_norm_b,
  4350. LLM_NORM, cb, -1);
  4351. cb(inpL, "inp_norm", -1);
  4352. for (int il = 0; il < n_layer; ++il) {
  4353. cur = llm_build_norm(ctx0, inpL, hparams,
  4354. model.layers[il].attn_norm,
  4355. model.layers[il].attn_norm_b,
  4356. LLM_NORM, cb, il);
  4357. cb(cur, "attn_norm", il);
  4358. // self-attention
  4359. {
  4360. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4361. cb(cur, "wqkv", il);
  4362. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4363. cb(cur, "bqkv", il);
  4364. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4365. 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)));
  4366. 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)));
  4367. cb(Qcur, "Qcur", il);
  4368. cb(Kcur, "Kcur", il);
  4369. cb(Vcur, "Vcur", il);
  4370. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4371. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4372. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4373. model.layers[il].wo, model.layers[il].bo,
  4374. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4375. cb(cur, "kqv_out", il);
  4376. }
  4377. // Add the input
  4378. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4379. cb(ffn_inp, "ffn_inp", il);
  4380. // FF
  4381. {
  4382. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4383. model.layers[il].ffn_norm,
  4384. model.layers[il].ffn_norm_b,
  4385. LLM_NORM, cb, il);
  4386. cb(cur, "ffn_norm", il);
  4387. cur = llm_build_ffn(ctx0, cur,
  4388. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4389. NULL, NULL,
  4390. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4391. NULL,
  4392. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4393. cb(cur, "ffn_out", il);
  4394. }
  4395. inpL = ggml_add(ctx0, cur, ffn_inp);
  4396. cb(inpL, "l_out", il);
  4397. }
  4398. cur = llm_build_norm(ctx0, inpL, hparams,
  4399. model.output_norm,
  4400. model.output_norm_b,
  4401. LLM_NORM, cb, -1);
  4402. cb(cur, "result_norm", -1);
  4403. cur = ggml_mul_mat(ctx0, model.output, cur);
  4404. cb(cur, "result_output", -1);
  4405. ggml_build_forward_expand(gf, cur);
  4406. return gf;
  4407. }
  4408. struct ggml_cgraph * build_mpt() {
  4409. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4410. const int64_t n_embd_head = hparams.n_embd_head_v;
  4411. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4412. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4413. struct ggml_tensor * cur;
  4414. struct ggml_tensor * inpL;
  4415. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4416. cb(inpL, "inp_embd", -1);
  4417. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4418. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4419. cb(KQ_mask, "KQ_mask", -1);
  4420. for (int il = 0; il < n_layer; ++il) {
  4421. struct ggml_tensor * attn_norm;
  4422. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4423. model.layers[il].attn_norm,
  4424. NULL,
  4425. LLM_NORM, cb, il);
  4426. cb(attn_norm, "attn_norm", il);
  4427. // self-attention
  4428. {
  4429. cur = attn_norm;
  4430. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4431. cb(cur, "wqkv", il);
  4432. if (hparams.f_clamp_kqv > 0.0f) {
  4433. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4434. cb(cur, "wqkv_clamped", il);
  4435. }
  4436. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4437. 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)));
  4438. 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)));
  4439. cb(Qcur, "Qcur", il);
  4440. cb(Kcur, "Kcur", il);
  4441. cb(Vcur, "Vcur", il);
  4442. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4443. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4444. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4445. model.layers[il].wo, NULL,
  4446. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4447. cb(cur, "kqv_out", il);
  4448. }
  4449. // Add the input
  4450. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4451. cb(ffn_inp, "ffn_inp", il);
  4452. // feed forward
  4453. {
  4454. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4455. model.layers[il].ffn_norm,
  4456. NULL,
  4457. LLM_NORM, cb, il);
  4458. cb(cur, "ffn_norm", il);
  4459. cur = llm_build_ffn(ctx0, cur,
  4460. model.layers[il].ffn_up, NULL,
  4461. NULL, NULL,
  4462. model.layers[il].ffn_down, NULL,
  4463. model.layers[il].ffn_act,
  4464. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4465. cb(cur, "ffn_out", il);
  4466. }
  4467. cur = ggml_add(ctx0, cur, ffn_inp);
  4468. cb(cur, "l_out", il);
  4469. // input for next layer
  4470. inpL = cur;
  4471. }
  4472. cur = inpL;
  4473. cur = llm_build_norm(ctx0, cur, hparams,
  4474. model.output_norm,
  4475. NULL,
  4476. LLM_NORM, cb, -1);
  4477. cb(cur, "result_norm", -1);
  4478. cur = ggml_mul_mat(ctx0, model.output, cur);
  4479. cb(cur, "result_output", -1);
  4480. ggml_build_forward_expand(gf, cur);
  4481. return gf;
  4482. }
  4483. struct ggml_cgraph * build_stablelm() {
  4484. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4485. const int64_t n_embd_head = hparams.n_embd_head_v;
  4486. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4487. struct ggml_tensor * cur;
  4488. struct ggml_tensor * inpL;
  4489. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4490. cb(inpL, "inp_embd", -1);
  4491. // inp_pos - contains the positions
  4492. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4493. cb(inp_pos, "inp_pos", -1);
  4494. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4495. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4496. cb(KQ_mask, "KQ_mask", -1);
  4497. // shift the entire K-cache if needed
  4498. if (do_rope_shift) {
  4499. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4500. }
  4501. for (int il = 0; il < n_layer; ++il) {
  4502. struct ggml_tensor * inpSA = inpL;
  4503. // norm
  4504. cur = llm_build_norm(ctx0, inpL, hparams,
  4505. model.layers[il].attn_norm,
  4506. model.layers[il].attn_norm_b,
  4507. LLM_NORM, cb, il);
  4508. cb(cur, "attn_norm", il);
  4509. // self-attention
  4510. {
  4511. // compute Q and K and RoPE them
  4512. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4513. cb(Qcur, "Qcur", il);
  4514. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4515. cb(Kcur, "Kcur", il);
  4516. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4517. cb(Vcur, "Vcur", il);
  4518. Qcur = ggml_rope_custom(
  4519. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4520. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4521. ext_factor, attn_factor, beta_fast, beta_slow
  4522. );
  4523. cb(Qcur, "Qcur", il);
  4524. Kcur = ggml_rope_custom(
  4525. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4526. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4527. ext_factor, attn_factor, beta_fast, beta_slow
  4528. );
  4529. cb(Kcur, "Kcur", il);
  4530. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4531. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4532. model.layers[il].wo, NULL,
  4533. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4534. cb(cur, "kqv_out", il);
  4535. }
  4536. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4537. cb(ffn_inp, "ffn_inp", il);
  4538. // feed-forward network
  4539. {
  4540. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4541. model.layers[il].ffn_norm,
  4542. model.layers[il].ffn_norm_b,
  4543. LLM_NORM, cb, il);
  4544. cb(cur, "ffn_norm", il);
  4545. cur = llm_build_ffn(ctx0, cur,
  4546. model.layers[il].ffn_up, NULL,
  4547. model.layers[il].ffn_gate, NULL,
  4548. model.layers[il].ffn_down, NULL,
  4549. NULL,
  4550. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4551. cb(cur, "ffn_out", il);
  4552. }
  4553. cur = ggml_add(ctx0, cur, ffn_inp);
  4554. cb(cur, "l_out", il);
  4555. // input for next layer
  4556. inpL = cur;
  4557. }
  4558. cur = inpL;
  4559. cur = llm_build_norm(ctx0, cur, hparams,
  4560. model.output_norm,
  4561. model.output_norm_b,
  4562. LLM_NORM, cb, -1);
  4563. cb(cur, "result_norm", -1);
  4564. // lm_head
  4565. cur = ggml_mul_mat(ctx0, model.output, cur);
  4566. cb(cur, "result_output", -1);
  4567. ggml_build_forward_expand(gf, cur);
  4568. return gf;
  4569. }
  4570. struct ggml_cgraph * build_qwen() {
  4571. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4572. const int64_t n_embd_head = hparams.n_embd_head_v;
  4573. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4574. struct ggml_tensor * cur;
  4575. struct ggml_tensor * inpL;
  4576. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4577. cb(inpL, "inp_embd", -1);
  4578. // inp_pos - contains the positions
  4579. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4580. cb(inp_pos, "inp_pos", -1);
  4581. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4582. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4583. cb(KQ_mask, "KQ_mask", -1);
  4584. // shift the entire K-cache if needed
  4585. if (do_rope_shift) {
  4586. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4587. }
  4588. for (int il = 0; il < n_layer; ++il) {
  4589. struct ggml_tensor * inpSA = inpL;
  4590. cur = llm_build_norm(ctx0, inpL, hparams,
  4591. model.layers[il].attn_norm, NULL,
  4592. LLM_NORM_RMS, cb, il);
  4593. cb(cur, "attn_norm", il);
  4594. // self-attention
  4595. {
  4596. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4597. cb(cur, "wqkv", il);
  4598. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4599. cb(cur, "bqkv", il);
  4600. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4601. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4602. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4603. cb(Qcur, "Qcur", il);
  4604. cb(Kcur, "Kcur", il);
  4605. cb(Vcur, "Vcur", il);
  4606. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4607. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4608. // using mode = 2 for neox mode
  4609. Qcur = ggml_rope_custom(
  4610. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4611. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4612. );
  4613. cb(Qcur, "Qcur", il);
  4614. Kcur = ggml_rope_custom(
  4615. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4616. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4617. );
  4618. cb(Kcur, "Kcur", il);
  4619. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4620. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4621. model.layers[il].wo, NULL,
  4622. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4623. cb(cur, "kqv_out", il);
  4624. }
  4625. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4626. cb(ffn_inp, "ffn_inp", il);
  4627. // feed-forward forward
  4628. {
  4629. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4630. model.layers[il].ffn_norm, NULL,
  4631. LLM_NORM_RMS, cb, il);
  4632. cb(cur, "ffn_norm", il);
  4633. cur = llm_build_ffn(ctx0, cur,
  4634. model.layers[il].ffn_up, NULL,
  4635. model.layers[il].ffn_gate, NULL,
  4636. model.layers[il].ffn_down, NULL,
  4637. NULL,
  4638. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4639. cb(cur, "ffn_out", il);
  4640. }
  4641. cur = ggml_add(ctx0, cur, ffn_inp);
  4642. cb(cur, "l_out", il);
  4643. // input for next layer
  4644. inpL = cur;
  4645. }
  4646. cur = inpL;
  4647. cur = llm_build_norm(ctx0, cur, hparams,
  4648. model.output_norm, NULL,
  4649. LLM_NORM_RMS, cb, -1);
  4650. cb(cur, "result_norm", -1);
  4651. // lm_head
  4652. cur = ggml_mul_mat(ctx0, model.output, cur);
  4653. cb(cur, "result_output", -1);
  4654. ggml_build_forward_expand(gf, cur);
  4655. return gf;
  4656. }
  4657. struct ggml_cgraph * build_phi2() {
  4658. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4659. const int64_t n_embd_head = hparams.n_embd_head_v;
  4660. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4661. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4662. struct ggml_tensor * cur;
  4663. struct ggml_tensor * attn_norm_output;
  4664. struct ggml_tensor * ffn_output;
  4665. struct ggml_tensor * inpL;
  4666. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4667. cb(inpL, "inp_embd", -1);
  4668. // inp_pos - contains the positions
  4669. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4670. cb(inp_pos, "inp_pos", -1);
  4671. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4672. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4673. cb(KQ_mask, "KQ_mask", -1);
  4674. // shift the entire K-cache if needed
  4675. if (do_rope_shift) {
  4676. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4677. }
  4678. for (int il = 0; il < n_layer; ++il) {
  4679. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  4680. model.layers[il].attn_norm,
  4681. model.layers[il].attn_norm_b,
  4682. LLM_NORM, cb, il);
  4683. cb(attn_norm_output, "attn_norm", il);
  4684. // self-attention
  4685. {
  4686. struct ggml_tensor * Qcur = nullptr;
  4687. struct ggml_tensor * Kcur = nullptr;
  4688. struct ggml_tensor * Vcur = nullptr;
  4689. if (model.layers[il].wqkv) {
  4690. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  4691. cb(cur, "wqkv", il);
  4692. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4693. cb(cur, "bqkv", il);
  4694. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4695. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4696. 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)));
  4697. } else {
  4698. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  4699. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  4700. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  4701. }
  4702. cb(Qcur, "Qcur", il);
  4703. cb(Kcur, "Kcur", il);
  4704. cb(Vcur, "Vcur", il);
  4705. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4706. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4707. Qcur = ggml_rope_custom(
  4708. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4709. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4710. );
  4711. cb(Qcur, "Qcur", il);
  4712. // with phi2, we scale the Q to avoid precision issues
  4713. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  4714. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  4715. cb(Qcur, "Qcur", il);
  4716. Kcur = ggml_rope_custom(
  4717. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4718. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4719. );
  4720. cb(Kcur, "Kcur", il);
  4721. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4722. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4723. model.layers[il].wo, model.layers[il].bo,
  4724. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f, cb, il);
  4725. cb(cur, "kqv_out", il);
  4726. }
  4727. // FF
  4728. {
  4729. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  4730. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4731. NULL, NULL,
  4732. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4733. NULL,
  4734. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4735. cb(ffn_output, "ffn_out", il);
  4736. }
  4737. cur = ggml_add(ctx0, cur, ffn_output);
  4738. cb(cur, "l_out", il);
  4739. cur = ggml_add(ctx0, cur, inpL);
  4740. cb(cur, "l_out", il);
  4741. inpL = cur;
  4742. }
  4743. cur = llm_build_norm(ctx0, inpL, hparams,
  4744. model.output_norm,
  4745. model.output_norm_b,
  4746. LLM_NORM, cb, -1);
  4747. cb(cur, "result_norm", -1);
  4748. cur = ggml_mul_mat(ctx0, model.output, cur);
  4749. cb(cur, "result_output_no_bias", -1);
  4750. cur = ggml_add(ctx0, cur, model.output_b);
  4751. cb(cur, "result_output", -1);
  4752. ggml_build_forward_expand(gf, cur);
  4753. return gf;
  4754. }
  4755. struct ggml_cgraph * build_plamo() {
  4756. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4757. const int64_t n_embd_head = hparams.n_embd_head_v;
  4758. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4759. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4760. struct ggml_tensor * cur;
  4761. struct ggml_tensor * inpL;
  4762. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4763. cb(inpL, "inp_embd", -1);
  4764. // inp_pos - contains the positions
  4765. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4766. cb(inp_pos, "inp_pos", -1);
  4767. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4768. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4769. cb(KQ_mask, "KQ_mask", -1);
  4770. // shift the entire K-cache if needed
  4771. if (do_rope_shift) {
  4772. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4773. }
  4774. for (int il = 0; il < n_layer; ++il) {
  4775. // norm
  4776. cur = llm_build_norm(ctx0, inpL, hparams,
  4777. model.layers[il].attn_norm, NULL,
  4778. LLM_NORM_RMS, cb, il);
  4779. cb(cur, "attn_norm", il);
  4780. struct ggml_tensor * attention_norm = cur;
  4781. // self-attention
  4782. {
  4783. // compute Q and K and RoPE them
  4784. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4785. cb(Qcur, "Qcur", il);
  4786. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4787. cb(Kcur, "Kcur", il);
  4788. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4789. cb(Vcur, "Vcur", il);
  4790. Qcur = ggml_rope_custom(
  4791. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  4792. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4793. ext_factor, attn_factor, beta_fast, beta_slow);
  4794. cb(Qcur, "Qcur", il);
  4795. Kcur = ggml_rope_custom(
  4796. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  4797. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4798. ext_factor, attn_factor, beta_fast, beta_slow);
  4799. cb(Kcur, "Kcur", il);
  4800. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4801. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4802. model.layers[il].wo, NULL,
  4803. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4804. cb(cur, "kqv_out", il);
  4805. }
  4806. struct ggml_tensor * sa_out = cur;
  4807. cur = attention_norm;
  4808. // feed-forward network
  4809. {
  4810. cur = llm_build_ffn(ctx0, cur,
  4811. model.layers[il].ffn_up, NULL,
  4812. model.layers[il].ffn_gate, NULL,
  4813. model.layers[il].ffn_down, NULL,
  4814. NULL,
  4815. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4816. cb(cur, "ffn_out", il);
  4817. }
  4818. cur = ggml_add(ctx0, cur, sa_out);
  4819. cb(cur, "l_out", il);
  4820. cur = ggml_add(ctx0, cur, inpL);
  4821. cb(cur, "l_out", il);
  4822. // input for next layer
  4823. inpL = cur;
  4824. }
  4825. cur = inpL;
  4826. cur = llm_build_norm(ctx0, cur, hparams,
  4827. model.output_norm, NULL,
  4828. LLM_NORM_RMS, cb, -1);
  4829. cb(cur, "result_norm", -1);
  4830. // lm_head
  4831. cur = ggml_mul_mat(ctx0, model.output, cur);
  4832. cb(cur, "result_output", -1);
  4833. ggml_build_forward_expand(gf, cur);
  4834. return gf;
  4835. }
  4836. struct ggml_cgraph * build_gpt2() {
  4837. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4838. const int64_t n_embd_head = hparams.n_embd_head_v;
  4839. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4840. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4841. struct ggml_tensor * cur;
  4842. struct ggml_tensor * pos;
  4843. struct ggml_tensor * inpL;
  4844. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4845. cb(inpL, "inp_embd", -1);
  4846. // inp_pos - contains the positions
  4847. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4848. cb(inp_pos, "inp_pos", -1);
  4849. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4850. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4851. cb(KQ_mask, "KQ_mask", -1);
  4852. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4853. cb(pos, "pos_embd", -1);
  4854. inpL = ggml_add(ctx0, inpL, pos);
  4855. cb(inpL, "inpL", -1);
  4856. for (int il = 0; il < n_layer; ++il) {
  4857. cur = llm_build_norm(ctx0, inpL, hparams,
  4858. model.layers[il].attn_norm,
  4859. model.layers[il].attn_norm_b,
  4860. LLM_NORM, cb, il);
  4861. cb(cur, "attn_norm", il);
  4862. // self-attention
  4863. {
  4864. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4865. cb(cur, "wqkv", il);
  4866. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4867. cb(cur, "bqkv", il);
  4868. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4869. 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)));
  4870. 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)));
  4871. cb(Qcur, "Qcur", il);
  4872. cb(Kcur, "Kcur", il);
  4873. cb(Vcur, "Vcur", il);
  4874. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4875. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4876. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4877. model.layers[il].wo, model.layers[il].bo,
  4878. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4879. cb(cur, "kqv_out", il);
  4880. }
  4881. // add the input
  4882. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4883. cb(ffn_inp, "ffn_inp", il);
  4884. // FF
  4885. {
  4886. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4887. model.layers[il].ffn_norm,
  4888. model.layers[il].ffn_norm_b,
  4889. LLM_NORM, cb, il);
  4890. cb(cur, "ffn_norm", il);
  4891. cur = llm_build_ffn(ctx0, cur,
  4892. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4893. NULL, NULL,
  4894. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4895. NULL,
  4896. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4897. cb(cur, "ffn_out", il);
  4898. }
  4899. inpL = ggml_add(ctx0, cur, ffn_inp);
  4900. cb(inpL, "l_out", il);
  4901. }
  4902. cur = llm_build_norm(ctx0, inpL, hparams,
  4903. model.output_norm,
  4904. model.output_norm_b,
  4905. LLM_NORM, cb, -1);
  4906. cb(cur, "result_norm", -1);
  4907. cur = ggml_mul_mat(ctx0, model.output, cur);
  4908. cb(cur, "result_output", -1);
  4909. ggml_build_forward_expand(gf, cur);
  4910. return gf;
  4911. }
  4912. };
  4913. static struct ggml_cgraph * llama_build_graph(
  4914. llama_context & lctx,
  4915. const llama_batch & batch) {
  4916. const auto & model = lctx.model;
  4917. // check if we should build the worst-case graph (for memory measurement)
  4918. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  4919. // keep track of the input that has already been allocated
  4920. bool alloc_inp_tokens = false;
  4921. bool alloc_inp_embd = false;
  4922. bool alloc_inp_pos = false;
  4923. bool alloc_inp_KQ_mask = false;
  4924. bool alloc_inp_K_shift = false;
  4925. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  4926. // TODO: improve handling of input and output tensors, then replace this with ggml_set_name
  4927. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  4928. if (il >= 0) {
  4929. ggml_format_name(cur, "%s-%d", name, il);
  4930. } else {
  4931. ggml_set_name(cur, name);
  4932. }
  4933. //
  4934. // allocate input tensors and set input data
  4935. //
  4936. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  4937. ggml_tallocr_alloc(lctx.alloc, cur);
  4938. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.token) {
  4939. const int64_t n_tokens = cur->ne[0];
  4940. ggml_backend_tensor_set(cur, batch.token, 0, n_tokens*ggml_element_size(cur));
  4941. }
  4942. alloc_inp_tokens = true;
  4943. }
  4944. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0 && batch.embd) {
  4945. ggml_tallocr_alloc(lctx.alloc, cur);
  4946. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.embd) {
  4947. const int64_t n_embd = cur->ne[0];
  4948. const int64_t n_tokens = cur->ne[1];
  4949. ggml_backend_tensor_set(cur, batch.embd, 0, n_tokens*n_embd*ggml_element_size(cur));
  4950. }
  4951. alloc_inp_embd = true;
  4952. }
  4953. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  4954. ggml_tallocr_alloc(lctx.alloc, cur);
  4955. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.pos) {
  4956. const int64_t n_tokens = cur->ne[0];
  4957. static_assert(std::is_same<llama_pos, int32_t>::value, "llama_pos must be int32_t");
  4958. ggml_backend_tensor_set(cur, batch.pos, 0, n_tokens*ggml_element_size(cur));
  4959. }
  4960. alloc_inp_pos = true;
  4961. }
  4962. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  4963. ggml_tallocr_alloc(lctx.alloc, cur);
  4964. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  4965. const int64_t n_kv = cur->ne[0];
  4966. const int64_t n_tokens = cur->ne[1];
  4967. float * data;
  4968. if (ggml_backend_buffer_is_host(cur->buffer)) {
  4969. data = (float *) cur->data;
  4970. } else {
  4971. lctx.buf_copy.resize(ggml_nbytes(cur));
  4972. data = (float *) lctx.buf_copy.data();
  4973. }
  4974. for (int h = 0; h < 1; ++h) {
  4975. for (int j = 0; j < n_tokens; ++j) {
  4976. const llama_pos pos = batch.pos[j];
  4977. const llama_seq_id seq_id = batch.seq_id[j][0];
  4978. for (int i = 0; i < n_kv; ++i) {
  4979. float f;
  4980. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  4981. f = -INFINITY;
  4982. } else {
  4983. f = 0;
  4984. }
  4985. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  4986. }
  4987. }
  4988. }
  4989. if (data != cur->data) {
  4990. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  4991. }
  4992. }
  4993. alloc_inp_KQ_mask = true;
  4994. }
  4995. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  4996. ggml_tallocr_alloc(lctx.alloc, cur);
  4997. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  4998. const int64_t n_ctx = cur->ne[0];
  4999. int32_t * data;
  5000. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5001. data = (int32_t *) cur->data;
  5002. } else {
  5003. lctx.buf_copy.resize(ggml_nbytes(cur));
  5004. data = (int32_t *) lctx.buf_copy.data();
  5005. }
  5006. for (int i = 0; i < n_ctx; ++i) {
  5007. data[i] = lctx.kv_self.cells[i].delta;
  5008. }
  5009. if (data != cur->data) {
  5010. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5011. }
  5012. }
  5013. alloc_inp_K_shift = true;
  5014. }
  5015. };
  5016. struct ggml_cgraph * result = NULL;
  5017. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5018. llm.init();
  5019. switch (model.arch) {
  5020. case LLM_ARCH_LLAMA:
  5021. {
  5022. result = llm.build_llama();
  5023. } break;
  5024. case LLM_ARCH_BAICHUAN:
  5025. {
  5026. result = llm.build_baichuan();
  5027. } break;
  5028. case LLM_ARCH_FALCON:
  5029. {
  5030. result = llm.build_falcon();
  5031. } break;
  5032. case LLM_ARCH_STARCODER:
  5033. {
  5034. result = llm.build_starcoder();
  5035. } break;
  5036. case LLM_ARCH_PERSIMMON:
  5037. {
  5038. result = llm.build_persimmon();
  5039. } break;
  5040. case LLM_ARCH_REFACT:
  5041. {
  5042. result = llm.build_refact();
  5043. } break;
  5044. case LLM_ARCH_BLOOM:
  5045. {
  5046. result = llm.build_bloom();
  5047. } break;
  5048. case LLM_ARCH_MPT:
  5049. {
  5050. result = llm.build_mpt();
  5051. } break;
  5052. case LLM_ARCH_STABLELM:
  5053. {
  5054. result = llm.build_stablelm();
  5055. } break;
  5056. case LLM_ARCH_QWEN:
  5057. {
  5058. result = llm.build_qwen();
  5059. } break;
  5060. case LLM_ARCH_PHI2:
  5061. {
  5062. result = llm.build_phi2();
  5063. } break;
  5064. case LLM_ARCH_PLAMO:
  5065. {
  5066. result = llm.build_plamo();
  5067. } break;
  5068. case LLM_ARCH_GPT2:
  5069. {
  5070. result = llm.build_gpt2();
  5071. } break;
  5072. default:
  5073. GGML_ASSERT(false);
  5074. }
  5075. llm.free();
  5076. return result;
  5077. }
  5078. // decode a batch of tokens by evaluating the transformer
  5079. //
  5080. // - lctx: llama context
  5081. // - batch: batch to evaluate
  5082. //
  5083. // return 0 on success
  5084. // return positive int on warning
  5085. // return negative int on error
  5086. //
  5087. static int llama_decode_internal(
  5088. llama_context & lctx,
  5089. llama_batch batch) {
  5090. const uint32_t n_tokens = batch.n_tokens;
  5091. if (n_tokens == 0) {
  5092. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5093. return -1;
  5094. }
  5095. const auto & model = lctx.model;
  5096. const auto & hparams = model.hparams;
  5097. const auto & cparams = lctx.cparams;
  5098. const auto n_batch = cparams.n_batch;
  5099. GGML_ASSERT(n_tokens <= n_batch);
  5100. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5101. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5102. const int64_t t_start_us = ggml_time_us();
  5103. #ifdef GGML_USE_MPI
  5104. // TODO: needs fix after #3228
  5105. GGML_ASSERT(false && "not implemented");
  5106. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5107. #endif
  5108. GGML_ASSERT(n_threads > 0);
  5109. auto & kv_self = lctx.kv_self;
  5110. const int64_t n_embd = hparams.n_embd;
  5111. const int64_t n_vocab = hparams.n_vocab;
  5112. // helpers for smoother batch API transition
  5113. // after deprecating the llama_eval calls, these will be removed
  5114. std::vector<llama_pos> pos;
  5115. std::vector<int32_t> n_seq_id;
  5116. std::vector<llama_seq_id *> seq_id_arr;
  5117. std::vector<std::vector<llama_seq_id>> seq_id;
  5118. if (batch.pos == nullptr) {
  5119. pos.resize(n_tokens);
  5120. for (uint32_t i = 0; i < n_tokens; i++) {
  5121. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5122. }
  5123. batch.pos = pos.data();
  5124. }
  5125. if (batch.seq_id == nullptr) {
  5126. n_seq_id.resize(n_tokens);
  5127. seq_id.resize(n_tokens);
  5128. seq_id_arr.resize(n_tokens);
  5129. for (uint32_t i = 0; i < n_tokens; i++) {
  5130. n_seq_id[i] = 1;
  5131. seq_id[i].resize(1);
  5132. seq_id[i][0] = batch.all_seq_id;
  5133. seq_id_arr[i] = seq_id[i].data();
  5134. }
  5135. batch.n_seq_id = n_seq_id.data();
  5136. batch.seq_id = seq_id_arr.data();
  5137. }
  5138. // if we have enough unused cells before the current head ->
  5139. // better to start searching from the beginning of the cache, hoping to fill it
  5140. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5141. kv_self.head = 0;
  5142. }
  5143. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5144. return 1;
  5145. }
  5146. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5147. // after enough generations, the benefit from this heuristic disappears
  5148. // if we start defragmenting the cache, the benefit from this will be more important
  5149. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5150. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5151. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5152. ggml_backend_sched_reset(lctx.sched);
  5153. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5154. // the output is always the last tensor in the graph
  5155. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5156. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5157. // the embeddings could be the second to last tensor, or the third to last tensor
  5158. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5159. if (strcmp(embeddings->name, "result_norm") != 0) {
  5160. embeddings = gf->nodes[gf->n_nodes - 3];
  5161. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5162. }
  5163. // 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);
  5164. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5165. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5166. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5167. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5168. // with the BLAS calls. need a better solution
  5169. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5170. n_threads = std::min(4, n_threads);
  5171. }
  5172. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5173. if (ggml_cpu_has_cublas() && fully_offloaded) {
  5174. n_threads = 1;
  5175. }
  5176. #ifdef GGML_USE_MPI
  5177. const int64_t n_layer = hparams.n_layer;
  5178. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5179. #endif
  5180. #ifdef GGML_USE_METAL
  5181. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5182. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5183. }
  5184. #endif
  5185. if (lctx.backend_cpu != nullptr) {
  5186. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5187. }
  5188. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5189. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5190. #ifdef GGML_USE_MPI
  5191. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5192. #endif
  5193. // update the kv ring buffer
  5194. {
  5195. if (kv_self.has_shift) {
  5196. kv_self.has_shift = false;
  5197. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5198. kv_self.cells[i].delta = 0;
  5199. }
  5200. }
  5201. kv_self.head += n_tokens;
  5202. // Ensure kv cache head points to a valid index.
  5203. if (kv_self.head >= kv_self.size) {
  5204. kv_self.head = 0;
  5205. }
  5206. }
  5207. #ifdef GGML_PERF
  5208. // print timing information per ggml operation (for debugging purposes)
  5209. // requires GGML_PERF to be defined
  5210. ggml_graph_print(gf);
  5211. #endif
  5212. // plot the computation graph in dot format (for debugging purposes)
  5213. //if (n_past%100 == 0) {
  5214. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5215. //}
  5216. // extract logits
  5217. // TODO: do not compute and extract logits if only embeddings are needed
  5218. // need to update the graphs to skip "result_output"
  5219. {
  5220. auto & logits_out = lctx.logits;
  5221. #ifndef NDEBUG
  5222. auto & logits_valid = lctx.logits_valid;
  5223. logits_valid.clear();
  5224. logits_valid.resize(n_tokens);
  5225. logits_out.clear();
  5226. #endif
  5227. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5228. GGML_ASSERT(res_backend != nullptr);
  5229. if (batch.logits) {
  5230. logits_out.resize(n_vocab * n_tokens);
  5231. for (uint32_t i = 0; i < n_tokens; i++) {
  5232. if (batch.logits[i] == 0) {
  5233. continue;
  5234. }
  5235. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5236. #ifndef NDEBUG
  5237. logits_valid[i] = true;
  5238. #endif
  5239. }
  5240. } else if (lctx.logits_all) {
  5241. logits_out.resize(n_vocab * n_tokens);
  5242. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5243. #ifndef NDEBUG
  5244. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5245. #endif
  5246. } else {
  5247. logits_out.resize(n_vocab);
  5248. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5249. #ifndef NDEBUG
  5250. logits_valid[0] = true;
  5251. #endif
  5252. }
  5253. ggml_backend_synchronize(res_backend);
  5254. }
  5255. // extract embeddings
  5256. if (!lctx.embedding.empty()) {
  5257. auto & embedding_out = lctx.embedding;
  5258. embedding_out.resize(n_embd);
  5259. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5260. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5261. ggml_backend_synchronize(embeddings_backend);
  5262. }
  5263. // measure the performance only for the single-token evals
  5264. if (n_tokens == 1) {
  5265. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5266. lctx.n_eval++;
  5267. }
  5268. else if (n_tokens > 1) {
  5269. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5270. lctx.n_p_eval += n_tokens;
  5271. }
  5272. // get a more accurate load time, upon first eval
  5273. // TODO: fix this
  5274. if (!lctx.has_evaluated_once) {
  5275. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5276. lctx.has_evaluated_once = true;
  5277. }
  5278. return 0;
  5279. }
  5280. //
  5281. // tokenizer
  5282. //
  5283. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5284. return vocab.type;
  5285. }
  5286. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5287. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5288. }
  5289. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5290. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5291. }
  5292. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5293. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5294. }
  5295. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5296. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5297. }
  5298. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5299. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5300. }
  5301. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5302. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5303. const auto& token_data = vocab.id_to_token.at(id);
  5304. switch (llama_vocab_get_type(vocab)) {
  5305. case LLAMA_VOCAB_TYPE_SPM: {
  5306. auto buf = token_data.text.substr(3, 2);
  5307. return strtol(buf.c_str(), NULL, 16);
  5308. }
  5309. case LLAMA_VOCAB_TYPE_BPE: {
  5310. GGML_ASSERT(false);
  5311. return unicode_to_bytes_bpe(token_data.text);
  5312. }
  5313. default:
  5314. GGML_ASSERT(false);
  5315. }
  5316. }
  5317. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5318. static const char * hex = "0123456789ABCDEF";
  5319. switch (llama_vocab_get_type(vocab)) {
  5320. case LLAMA_VOCAB_TYPE_SPM: {
  5321. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5322. return vocab.token_to_id.at(buf);
  5323. }
  5324. case LLAMA_VOCAB_TYPE_BPE: {
  5325. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5326. }
  5327. default:
  5328. GGML_ASSERT(false);
  5329. }
  5330. }
  5331. static void llama_escape_whitespace(std::string & text) {
  5332. replace_all(text, " ", "\xe2\x96\x81");
  5333. }
  5334. static void llama_unescape_whitespace(std::string & word) {
  5335. replace_all(word, "\xe2\x96\x81", " ");
  5336. }
  5337. struct llm_symbol {
  5338. using index = int;
  5339. index prev;
  5340. index next;
  5341. const char * text;
  5342. size_t n;
  5343. };
  5344. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5345. // SPM tokenizer
  5346. // original implementation:
  5347. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5348. struct llm_bigram_spm {
  5349. struct comparator {
  5350. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5351. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5352. }
  5353. };
  5354. using queue_storage = std::vector<llm_bigram_spm>;
  5355. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5356. llm_symbol::index left;
  5357. llm_symbol::index right;
  5358. float score;
  5359. size_t size;
  5360. };
  5361. struct llm_tokenizer_spm {
  5362. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5363. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5364. // split string into utf8 chars
  5365. int index = 0;
  5366. size_t offs = 0;
  5367. while (offs < text.size()) {
  5368. llm_symbol sym;
  5369. size_t len = utf8_len(text[offs]);
  5370. sym.text = text.c_str() + offs;
  5371. sym.n = std::min(len, text.size() - offs);
  5372. offs += sym.n;
  5373. sym.prev = index - 1;
  5374. sym.next = offs == text.size() ? -1 : index + 1;
  5375. index++;
  5376. symbols.emplace_back(sym);
  5377. }
  5378. // seed the work queue with all possible 2-character tokens.
  5379. for (size_t i = 1; i < symbols.size(); ++i) {
  5380. try_add_bigram(i - 1, i);
  5381. }
  5382. // keep substituting the highest frequency pairs for as long as we can.
  5383. while (!work_queue.empty()) {
  5384. auto bigram = work_queue.top();
  5385. work_queue.pop();
  5386. auto & left_sym = symbols[bigram.left];
  5387. auto & right_sym = symbols[bigram.right];
  5388. // if one of the symbols already got merged, skip it.
  5389. if (left_sym.n == 0 || right_sym.n == 0 ||
  5390. left_sym.n + right_sym.n != bigram.size) {
  5391. continue;
  5392. }
  5393. // merge the right sym into the left one
  5394. left_sym.n += right_sym.n;
  5395. right_sym.n = 0;
  5396. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5397. // remove the right sym from the chain
  5398. left_sym.next = right_sym.next;
  5399. if (right_sym.next >= 0) {
  5400. symbols[right_sym.next].prev = bigram.left;
  5401. }
  5402. // find more substitutions
  5403. try_add_bigram(left_sym.prev, bigram.left);
  5404. try_add_bigram(bigram.left, left_sym.next);
  5405. }
  5406. for (int i = 0; i != -1; i = symbols[i].next) {
  5407. auto & symbol = symbols[i];
  5408. resegment(symbol, output);
  5409. }
  5410. }
  5411. private:
  5412. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5413. auto text = std::string(symbol.text, symbol.n);
  5414. auto token = vocab.token_to_id.find(text);
  5415. // Do we need to support is_unused?
  5416. if (token != vocab.token_to_id.end()) {
  5417. output.push_back((*token).second);
  5418. return;
  5419. }
  5420. const auto p = rev_merge.find(text);
  5421. if (p == rev_merge.end()) {
  5422. // output any symbols that did not form tokens as bytes.
  5423. for (int j = 0; j < (int)symbol.n; ++j) {
  5424. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5425. output.push_back(token_id);
  5426. }
  5427. return;
  5428. }
  5429. resegment(symbols[p->second.first], output);
  5430. resegment(symbols[p->second.second], output);
  5431. }
  5432. void try_add_bigram(int left, int right) {
  5433. if (left == -1 || right == -1) {
  5434. return;
  5435. }
  5436. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5437. auto token = vocab.token_to_id.find(text);
  5438. if (token == vocab.token_to_id.end()) {
  5439. return;
  5440. }
  5441. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5442. return;
  5443. }
  5444. const auto & tok_data = vocab.id_to_token[(*token).second];
  5445. llm_bigram_spm bigram;
  5446. bigram.left = left;
  5447. bigram.right = right;
  5448. bigram.score = tok_data.score;
  5449. bigram.size = text.size();
  5450. work_queue.push(bigram);
  5451. // Do we need to support is_unused?
  5452. rev_merge[text] = std::make_pair(left, right);
  5453. }
  5454. const llama_vocab & vocab;
  5455. std::vector<llm_symbol> symbols;
  5456. llm_bigram_spm::queue work_queue;
  5457. std::map<std::string, std::pair<int, int>> rev_merge;
  5458. };
  5459. // BPE tokenizer
  5460. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5461. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5462. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5463. struct llm_bigram_bpe {
  5464. struct comparator {
  5465. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5466. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5467. }
  5468. };
  5469. using queue_storage = std::vector<llm_bigram_bpe>;
  5470. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5471. llm_symbol::index left;
  5472. llm_symbol::index right;
  5473. std::string text;
  5474. int rank;
  5475. size_t size;
  5476. };
  5477. struct llm_tokenizer_bpe {
  5478. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5479. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5480. int final_prev_index = -1;
  5481. auto word_collection = bpe_gpt2_preprocess(text);
  5482. symbols_final.clear();
  5483. for (auto & word : word_collection) {
  5484. work_queue = llm_bigram_bpe::queue();
  5485. symbols.clear();
  5486. int index = 0;
  5487. size_t offset = 0;
  5488. while (offset < word.size()) {
  5489. llm_symbol sym;
  5490. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5491. sym.text = word.c_str() + offset;
  5492. sym.n = char_len;
  5493. offset += sym.n;
  5494. sym.prev = index - 1;
  5495. sym.next = offset == word.size() ? -1 : index + 1;
  5496. index++;
  5497. symbols.emplace_back(sym);
  5498. }
  5499. for (size_t i = 1; i < symbols.size(); ++i) {
  5500. add_new_bigram(i - 1, i);
  5501. }
  5502. // build token(s)
  5503. while (!work_queue.empty()) {
  5504. auto bigram = work_queue.top();
  5505. work_queue.pop();
  5506. auto & left_symbol = symbols[bigram.left];
  5507. auto & right_symbol = symbols[bigram.right];
  5508. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5509. continue;
  5510. }
  5511. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5512. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5513. if (left_token + right_token != bigram.text) {
  5514. continue; // Skip this bigram if it's outdated
  5515. }
  5516. // merge the right sym into the left one
  5517. left_symbol.n += right_symbol.n;
  5518. right_symbol.n = 0;
  5519. // remove the right sym from the chain
  5520. left_symbol.next = right_symbol.next;
  5521. if (right_symbol.next >= 0) {
  5522. symbols[right_symbol.next].prev = bigram.left;
  5523. }
  5524. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5525. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5526. }
  5527. // add the fnished tokens to the final list keeping correct order for next and prev
  5528. for (auto & sym : symbols) {
  5529. if (sym.n > 0) {
  5530. sym.prev = final_prev_index;
  5531. sym.next = -1;
  5532. if (final_prev_index != -1) {
  5533. symbols_final[final_prev_index].next = symbols_final.size();
  5534. }
  5535. symbols_final.emplace_back(sym);
  5536. final_prev_index = symbols_final.size() - 1;
  5537. }
  5538. }
  5539. }
  5540. symbols = symbols_final;
  5541. if (!symbols.empty()) {
  5542. for (int i = 0; i != -1; i = symbols[i].next) {
  5543. auto & symbol = symbols[i];
  5544. if (symbol.n == 0) {
  5545. continue;
  5546. }
  5547. const std::string str = std::string(symbol.text, symbol.n);
  5548. const auto token = vocab.token_to_id.find(str);
  5549. if (token == vocab.token_to_id.end()) {
  5550. for (auto j = str.begin(); j != str.end(); ++j) {
  5551. std::string byte_str(1, *j);
  5552. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5553. if (token_multibyte == vocab.token_to_id.end()) {
  5554. throw std::runtime_error("ERROR: byte not found in vocab");
  5555. }
  5556. output.push_back((*token_multibyte).second);
  5557. }
  5558. } else {
  5559. output.push_back((*token).second);
  5560. }
  5561. }
  5562. }
  5563. }
  5564. private:
  5565. void add_new_bigram(int left, int right) {
  5566. if (left == -1 || right == -1) {
  5567. return;
  5568. }
  5569. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5570. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5571. int rank_found = -1;
  5572. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5573. if (rank_found < 0) {
  5574. return;
  5575. }
  5576. llm_bigram_bpe bigram;
  5577. bigram.left = left;
  5578. bigram.right = right;
  5579. bigram.text = left_token + right_token;
  5580. bigram.size = left_token.size() + right_token.size();
  5581. bigram.rank = rank_found;
  5582. work_queue.push(bigram);
  5583. }
  5584. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5585. std::vector<std::string> bpe_words;
  5586. std::vector<std::string> bpe_encoded_words;
  5587. std::string token = "";
  5588. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5589. bool collecting_numeric = false;
  5590. bool collecting_letter = false;
  5591. bool collecting_special = false;
  5592. bool collecting_whitespace_lookahead = false;
  5593. bool collecting = false;
  5594. std::vector<std::string> text_utf;
  5595. text_utf.reserve(text.size());
  5596. bpe_words.reserve(text.size());
  5597. bpe_encoded_words.reserve(text.size());
  5598. auto cps = codepoints_from_utf8(text);
  5599. for (size_t i = 0; i < cps.size(); ++i)
  5600. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5601. for (int i = 0; i < (int)text_utf.size(); i++) {
  5602. const std::string & utf_char = text_utf[i];
  5603. bool split_condition = false;
  5604. int bytes_remain = text_utf.size() - i;
  5605. // forward backward lookups
  5606. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5607. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5608. // handling contractions
  5609. if (!split_condition && bytes_remain >= 2) {
  5610. // 's|'t|'m|'d
  5611. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5612. split_condition = true;
  5613. }
  5614. if (split_condition) {
  5615. if (token.size()) {
  5616. bpe_words.emplace_back(token); // push previous content as token
  5617. }
  5618. token = utf_char + utf_char_next;
  5619. bpe_words.emplace_back(token);
  5620. token = "";
  5621. i++;
  5622. continue;
  5623. }
  5624. }
  5625. if (!split_condition && bytes_remain >= 3) {
  5626. // 're|'ve|'ll
  5627. if (utf_char == "\'" && (
  5628. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5629. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5630. (utf_char_next == "l" && utf_char_next_next == "l"))
  5631. ) {
  5632. split_condition = true;
  5633. }
  5634. if (split_condition) {
  5635. // current token + next token can be defined
  5636. if (token.size()) {
  5637. bpe_words.emplace_back(token); // push previous content as token
  5638. }
  5639. token = utf_char + utf_char_next + utf_char_next_next;
  5640. bpe_words.emplace_back(token); // the contraction
  5641. token = "";
  5642. i += 2;
  5643. continue;
  5644. }
  5645. }
  5646. if (!split_condition && !collecting) {
  5647. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5648. collecting_letter = true;
  5649. collecting = true;
  5650. }
  5651. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5652. collecting_numeric = true;
  5653. collecting = true;
  5654. }
  5655. else if (
  5656. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  5657. (!token.size() && utf_char == " " && codepoint_type(utf_char_next) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && codepoint_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  5658. ) {
  5659. collecting_special = true;
  5660. collecting = true;
  5661. }
  5662. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  5663. collecting_whitespace_lookahead = true;
  5664. collecting = true;
  5665. }
  5666. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  5667. split_condition = true;
  5668. }
  5669. }
  5670. else if (!split_condition && collecting) {
  5671. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  5672. split_condition = true;
  5673. }
  5674. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  5675. split_condition = true;
  5676. }
  5677. else if (collecting_special && (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  5678. split_condition = true;
  5679. }
  5680. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5681. split_condition = true;
  5682. }
  5683. }
  5684. if (utf_char_next == "") {
  5685. split_condition = true; // final
  5686. token += utf_char;
  5687. }
  5688. if (split_condition) {
  5689. if (token.size()) {
  5690. bpe_words.emplace_back(token);
  5691. }
  5692. token = utf_char;
  5693. collecting = false;
  5694. collecting_letter = false;
  5695. collecting_numeric = false;
  5696. collecting_special = false;
  5697. collecting_whitespace_lookahead = false;
  5698. }
  5699. else {
  5700. token += utf_char;
  5701. }
  5702. }
  5703. for (std::string & word : bpe_words) {
  5704. std::string encoded_token = "";
  5705. for (char & c : word) {
  5706. encoded_token += bytes_to_unicode_bpe(c);
  5707. }
  5708. bpe_encoded_words.emplace_back(encoded_token);
  5709. }
  5710. return bpe_encoded_words;
  5711. }
  5712. const llama_vocab & vocab;
  5713. std::vector<llm_symbol> symbols;
  5714. std::vector<llm_symbol> symbols_final;
  5715. llm_bigram_bpe::queue work_queue;
  5716. };
  5717. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  5718. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  5719. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  5720. } FRAGMENT_BUFFER_VARIANT_TYPE;
  5721. struct fragment_buffer_variant{
  5722. fragment_buffer_variant(llama_vocab::id _token)
  5723. :
  5724. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  5725. token(_token),
  5726. raw_text(_dummy),
  5727. offset(0),
  5728. length(0){}
  5729. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  5730. :
  5731. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  5732. token((llama_vocab::id)-1),
  5733. raw_text(_raw_text),
  5734. offset(_offset),
  5735. length(_length){
  5736. GGML_ASSERT( _offset >= 0 );
  5737. GGML_ASSERT( _length >= 1 );
  5738. GGML_ASSERT( offset + length <= raw_text.length() );
  5739. }
  5740. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  5741. const llama_vocab::id token;
  5742. const std::string _dummy;
  5743. const std::string & raw_text;
  5744. const uint64_t offset;
  5745. const uint64_t length;
  5746. };
  5747. // #define PRETOKENIZERDEBUG
  5748. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  5749. {
  5750. // for each special token
  5751. for (const auto & st: vocab.special_tokens_cache) {
  5752. const auto & special_token = st.first;
  5753. const auto & special_id = st.second;
  5754. // for each text fragment
  5755. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  5756. while (it != buffer.end()) {
  5757. auto & fragment = (*it);
  5758. // if a fragment is text ( not yet processed )
  5759. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  5760. auto * raw_text = &(fragment.raw_text);
  5761. auto raw_text_base_offset = fragment.offset;
  5762. auto raw_text_base_length = fragment.length;
  5763. // loop over the text
  5764. while (true) {
  5765. // find the first occurrence of a given special token in this fragment
  5766. // passing offset argument only limit the "search area" but match coordinates
  5767. // are still relative to the source full raw_text
  5768. auto match = raw_text->find(special_token, raw_text_base_offset);
  5769. // no occurrences found, stop processing this fragment for a given special token
  5770. if (match == std::string::npos) break;
  5771. // check if match is within bounds of offset <-> length
  5772. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  5773. #ifdef PRETOKENIZERDEBUG
  5774. fprintf(stderr, "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());
  5775. #endif
  5776. auto source = std::distance(buffer.begin(), it);
  5777. // if match is further than base offset
  5778. // then we have some text to the left of it
  5779. if (match > raw_text_base_offset) {
  5780. // left
  5781. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  5782. const int64_t left_reminder_length = match - raw_text_base_offset;
  5783. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  5784. #ifdef PRETOKENIZERDEBUG
  5785. fprintf(stderr, "FL: (%ld %ld) '%s'\n", left_reminder_offset, left_reminder_length, raw_text->substr(left_reminder_offset, left_reminder_length).c_str());
  5786. #endif
  5787. it++;
  5788. }
  5789. // special token
  5790. buffer.emplace_after(it, special_id);
  5791. it++;
  5792. // right
  5793. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  5794. const int64_t right_reminder_offset = match + special_token.length();
  5795. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  5796. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  5797. #ifdef PRETOKENIZERDEBUG
  5798. fprintf(stderr, "FR: (%ld %ld) '%s'\n", right_reminder_offset, right_reminder_length, raw_text->substr(right_reminder_offset, right_reminder_length).c_str());
  5799. #endif
  5800. it++;
  5801. if (source == 0) {
  5802. buffer.erase_after(buffer.before_begin());
  5803. } else {
  5804. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  5805. }
  5806. // repeat for the right side
  5807. raw_text_base_offset = right_reminder_offset;
  5808. raw_text_base_length = right_reminder_length;
  5809. #ifdef PRETOKENIZERDEBUG
  5810. fprintf(stderr, "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());
  5811. #endif
  5812. } else {
  5813. if (source == 0) {
  5814. buffer.erase_after(buffer.before_begin());
  5815. } else {
  5816. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  5817. }
  5818. break;
  5819. }
  5820. }
  5821. }
  5822. it++;
  5823. }
  5824. }
  5825. }
  5826. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  5827. std::vector<llama_vocab::id> output;
  5828. // OG tokenizer behavior:
  5829. //
  5830. // tokenizer.encode('', add_bos=True) returns [1]
  5831. // tokenizer.encode('', add_bos=False) returns []
  5832. if (bos && vocab.special_bos_id != -1) {
  5833. output.push_back(vocab.special_bos_id);
  5834. }
  5835. if (raw_text.empty()) {
  5836. return output;
  5837. }
  5838. std::forward_list<fragment_buffer_variant> fragment_buffer;
  5839. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  5840. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  5841. switch (vocab.type) {
  5842. case LLAMA_VOCAB_TYPE_SPM:
  5843. {
  5844. for (const auto & fragment: fragment_buffer)
  5845. {
  5846. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  5847. {
  5848. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  5849. // TODO: It's likely possible to get rid of this string copy entirely
  5850. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  5851. // and passing 'add space prefix' as bool argument
  5852. //
  5853. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  5854. if (&fragment == &fragment_buffer.front()) {
  5855. raw_text = " " + raw_text; // prefix with space if the first token is not special
  5856. }
  5857. #ifdef PRETOKENIZERDEBUG
  5858. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  5859. #endif
  5860. llm_tokenizer_spm tokenizer(vocab);
  5861. llama_escape_whitespace(raw_text);
  5862. tokenizer.tokenize(raw_text, output);
  5863. }
  5864. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  5865. {
  5866. output.push_back(fragment.token);
  5867. }
  5868. }
  5869. } break;
  5870. case LLAMA_VOCAB_TYPE_BPE:
  5871. {
  5872. for (const auto & fragment: fragment_buffer)
  5873. {
  5874. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  5875. {
  5876. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  5877. #ifdef PRETOKENIZERDEBUG
  5878. fprintf(stderr,"TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  5879. #endif
  5880. llm_tokenizer_bpe tokenizer(vocab);
  5881. tokenizer.tokenize(raw_text, output);
  5882. }
  5883. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  5884. {
  5885. output.push_back(fragment.token);
  5886. }
  5887. }
  5888. } break;
  5889. }
  5890. return output;
  5891. }
  5892. //
  5893. // grammar - internal
  5894. //
  5895. struct llama_partial_utf8 {
  5896. uint32_t value; // bit value so far (unshifted)
  5897. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  5898. };
  5899. struct llama_grammar {
  5900. const std::vector<std::vector<llama_grammar_element>> rules;
  5901. std::vector<std::vector<const llama_grammar_element *>> stacks;
  5902. // buffer for partially generated UTF-8 sequence from accepted tokens
  5903. llama_partial_utf8 partial_utf8;
  5904. };
  5905. struct llama_grammar_candidate {
  5906. size_t index;
  5907. const uint32_t * code_points;
  5908. llama_partial_utf8 partial_utf8;
  5909. };
  5910. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  5911. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  5912. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  5913. const std::string & src,
  5914. llama_partial_utf8 partial_start) {
  5915. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  5916. const char * pos = src.c_str();
  5917. std::vector<uint32_t> code_points;
  5918. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  5919. code_points.reserve(src.size() + 1);
  5920. uint32_t value = partial_start.value;
  5921. int n_remain = partial_start.n_remain;
  5922. // continue previous decode, if applicable
  5923. while (*pos != 0 && n_remain > 0) {
  5924. uint8_t next_byte = static_cast<uint8_t>(*pos);
  5925. if ((next_byte >> 6) != 2) {
  5926. // invalid sequence, abort
  5927. code_points.push_back(0);
  5928. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  5929. }
  5930. value = (value << 6) + (next_byte & 0x3F);
  5931. ++pos;
  5932. --n_remain;
  5933. }
  5934. if (partial_start.n_remain > 0 && n_remain == 0) {
  5935. code_points.push_back(value);
  5936. }
  5937. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  5938. while (*pos != 0) {
  5939. uint8_t first_byte = static_cast<uint8_t>(*pos);
  5940. uint8_t highbits = first_byte >> 4;
  5941. n_remain = lookup[highbits] - 1;
  5942. if (n_remain < 0) {
  5943. // invalid sequence, abort
  5944. code_points.clear();
  5945. code_points.push_back(0);
  5946. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  5947. }
  5948. uint8_t mask = (1 << (7 - n_remain)) - 1;
  5949. value = first_byte & mask;
  5950. ++pos;
  5951. while (*pos != 0 && n_remain > 0) {
  5952. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  5953. ++pos;
  5954. --n_remain;
  5955. }
  5956. if (n_remain == 0) {
  5957. code_points.push_back(value);
  5958. }
  5959. }
  5960. code_points.push_back(0);
  5961. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  5962. }
  5963. // returns true iff pos points to the end of one of the definitions of a rule
  5964. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  5965. switch (pos->type) {
  5966. case LLAMA_GRETYPE_END: return true; // NOLINT
  5967. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  5968. default: return false;
  5969. }
  5970. }
  5971. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  5972. // asserts that pos is pointing to a char range element
  5973. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  5974. const llama_grammar_element * pos,
  5975. const uint32_t chr) {
  5976. bool found = false;
  5977. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5978. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  5979. do {
  5980. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  5981. // inclusive range, e.g. [a-z]
  5982. found = found || (pos->value <= chr && chr <= pos[1].value);
  5983. pos += 2;
  5984. } else {
  5985. // exact char match, e.g. [a] or "a"
  5986. found = found || pos->value == chr;
  5987. pos += 1;
  5988. }
  5989. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  5990. return std::make_pair(found == is_positive_char, pos);
  5991. }
  5992. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  5993. // range at pos (regular or inverse range)
  5994. // asserts that pos is pointing to a char range element
  5995. static bool llama_grammar_match_partial_char(
  5996. const llama_grammar_element * pos,
  5997. const llama_partial_utf8 partial_utf8) {
  5998. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  5999. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6000. uint32_t partial_value = partial_utf8.value;
  6001. int n_remain = partial_utf8.n_remain;
  6002. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6003. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6004. return false;
  6005. }
  6006. // range of possible code points this partial UTF-8 sequence could complete to
  6007. uint32_t low = partial_value << (n_remain * 6);
  6008. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6009. if (low == 0) {
  6010. if (n_remain == 2) {
  6011. low = 1 << 11;
  6012. } else if (n_remain == 3) {
  6013. low = 1 << 16;
  6014. }
  6015. }
  6016. do {
  6017. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6018. // inclusive range, e.g. [a-z]
  6019. if (pos->value <= high && low <= pos[1].value) {
  6020. return is_positive_char;
  6021. }
  6022. pos += 2;
  6023. } else {
  6024. // exact char match, e.g. [a] or "a"
  6025. if (low <= pos->value && pos->value <= high) {
  6026. return is_positive_char;
  6027. }
  6028. pos += 1;
  6029. }
  6030. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6031. return !is_positive_char;
  6032. }
  6033. // transforms a grammar pushdown stack into N possible stacks, all ending
  6034. // at a character range (terminal element)
  6035. static void llama_grammar_advance_stack(
  6036. const std::vector<std::vector<llama_grammar_element>> & rules,
  6037. const std::vector<const llama_grammar_element *> & stack,
  6038. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6039. if (stack.empty()) {
  6040. new_stacks.emplace_back(stack);
  6041. return;
  6042. }
  6043. const llama_grammar_element * pos = stack.back();
  6044. switch (pos->type) {
  6045. case LLAMA_GRETYPE_RULE_REF: {
  6046. const size_t rule_id = static_cast<size_t>(pos->value);
  6047. const llama_grammar_element * subpos = rules[rule_id].data();
  6048. do {
  6049. // init new stack without the top (pos)
  6050. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6051. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6052. // if this rule ref is followed by another element, add that to stack
  6053. new_stack.push_back(pos + 1);
  6054. }
  6055. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6056. // if alternate is nonempty, add to stack
  6057. new_stack.push_back(subpos);
  6058. }
  6059. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6060. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6061. // scan to end of alternate def
  6062. subpos++;
  6063. }
  6064. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6065. // there's another alternate def of this rule to process
  6066. subpos++;
  6067. } else {
  6068. break;
  6069. }
  6070. } while (true);
  6071. break;
  6072. }
  6073. case LLAMA_GRETYPE_CHAR:
  6074. case LLAMA_GRETYPE_CHAR_NOT:
  6075. new_stacks.emplace_back(stack);
  6076. break;
  6077. default:
  6078. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6079. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6080. // those
  6081. GGML_ASSERT(false);
  6082. }
  6083. }
  6084. // takes a set of possible pushdown stacks on a grammar, which are required to
  6085. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6086. // produces the N possible stacks if the given char is accepted at those
  6087. // positions
  6088. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6089. const std::vector<std::vector<llama_grammar_element>> & rules,
  6090. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6091. const uint32_t chr) {
  6092. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6093. for (const auto & stack : stacks) {
  6094. if (stack.empty()) {
  6095. continue;
  6096. }
  6097. auto match = llama_grammar_match_char(stack.back(), chr);
  6098. if (match.first) {
  6099. const llama_grammar_element * pos = match.second;
  6100. // update top of stack to next element, if any
  6101. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6102. if (!llama_grammar_is_end_of_sequence(pos)) {
  6103. new_stack.push_back(pos);
  6104. }
  6105. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6106. }
  6107. }
  6108. return new_stacks;
  6109. }
  6110. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6111. const std::vector<std::vector<llama_grammar_element>> & rules,
  6112. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6113. const std::vector<llama_grammar_candidate> & candidates);
  6114. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6115. const std::vector<std::vector<llama_grammar_element>> & rules,
  6116. const std::vector<const llama_grammar_element *> & stack,
  6117. const std::vector<llama_grammar_candidate> & candidates) {
  6118. std::vector<llama_grammar_candidate> rejects;
  6119. if (stack.empty()) {
  6120. for (const auto & tok : candidates) {
  6121. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6122. rejects.push_back(tok);
  6123. }
  6124. }
  6125. return rejects;
  6126. }
  6127. const llama_grammar_element * stack_pos = stack.back();
  6128. std::vector<llama_grammar_candidate> next_candidates;
  6129. for (const auto & tok : candidates) {
  6130. if (*tok.code_points == 0) {
  6131. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6132. // that cannot satisfy this position in grammar
  6133. if (tok.partial_utf8.n_remain != 0 &&
  6134. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6135. rejects.push_back(tok);
  6136. }
  6137. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6138. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6139. } else {
  6140. rejects.push_back(tok);
  6141. }
  6142. }
  6143. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6144. // update top of stack to next element, if any
  6145. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6146. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6147. stack_after.push_back(stack_pos_after);
  6148. }
  6149. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6150. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6151. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6152. for (const auto & tok : next_rejects) {
  6153. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6154. }
  6155. return rejects;
  6156. }
  6157. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6158. const std::vector<std::vector<llama_grammar_element>> & rules,
  6159. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6160. const std::vector<llama_grammar_candidate> & candidates) {
  6161. GGML_ASSERT(!stacks.empty()); // REVIEW
  6162. if (candidates.empty()) {
  6163. return std::vector<llama_grammar_candidate>();
  6164. }
  6165. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6166. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6167. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6168. }
  6169. return rejects;
  6170. }
  6171. //
  6172. // grammar - external
  6173. //
  6174. struct llama_grammar * llama_grammar_init(
  6175. const llama_grammar_element ** rules,
  6176. size_t n_rules,
  6177. size_t start_rule_index) {
  6178. const llama_grammar_element * pos;
  6179. // copy rule definitions into vectors
  6180. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6181. for (size_t i = 0; i < n_rules; i++) {
  6182. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6183. vec_rules[i].push_back(*pos);
  6184. }
  6185. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6186. }
  6187. // loop over alternates of start rule to build initial stacks
  6188. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6189. pos = rules[start_rule_index];
  6190. do {
  6191. std::vector<const llama_grammar_element *> stack;
  6192. if (!llama_grammar_is_end_of_sequence(pos)) {
  6193. // if alternate is nonempty, add to stack
  6194. stack.push_back(pos);
  6195. }
  6196. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6197. while (!llama_grammar_is_end_of_sequence(pos)) {
  6198. // scan to end of alternate def
  6199. pos++;
  6200. }
  6201. if (pos->type == LLAMA_GRETYPE_ALT) {
  6202. // there's another alternate def of this rule to process
  6203. pos++;
  6204. } else {
  6205. break;
  6206. }
  6207. } while (true);
  6208. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6209. }
  6210. void llama_grammar_free(struct llama_grammar * grammar) {
  6211. delete grammar;
  6212. }
  6213. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6214. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6215. // redirect elements in stacks to point to new rules
  6216. for (size_t is = 0; is < result->stacks.size(); is++) {
  6217. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6218. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6219. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6220. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6221. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6222. }
  6223. }
  6224. }
  6225. }
  6226. }
  6227. return result;
  6228. }
  6229. //
  6230. // sampling
  6231. //
  6232. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6233. if (seed == LLAMA_DEFAULT_SEED) {
  6234. seed = time(NULL);
  6235. }
  6236. ctx->rng.seed(seed);
  6237. }
  6238. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6239. GGML_ASSERT(candidates->size > 0);
  6240. const int64_t t_start_sample_us = ggml_time_us();
  6241. // Sort the logits in descending order
  6242. if (!candidates->sorted) {
  6243. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6244. return a.logit > b.logit;
  6245. });
  6246. candidates->sorted = true;
  6247. }
  6248. float max_l = candidates->data[0].logit;
  6249. float cum_sum = 0.0f;
  6250. for (size_t i = 0; i < candidates->size; ++i) {
  6251. float p = expf(candidates->data[i].logit - max_l);
  6252. candidates->data[i].p = p;
  6253. cum_sum += p;
  6254. }
  6255. for (size_t i = 0; i < candidates->size; ++i) {
  6256. candidates->data[i].p /= cum_sum;
  6257. }
  6258. if (ctx) {
  6259. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6260. }
  6261. }
  6262. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6263. const int64_t t_start_sample_us = ggml_time_us();
  6264. k = std::max(k, (int) min_keep);
  6265. k = std::min(k, (int) candidates->size);
  6266. // Sort scores in descending order
  6267. if (!candidates->sorted) {
  6268. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6269. return a.logit > b.logit;
  6270. };
  6271. if (k == (int) candidates->size) {
  6272. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6273. } else {
  6274. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6275. }
  6276. candidates->sorted = true;
  6277. }
  6278. candidates->size = k;
  6279. if (ctx) {
  6280. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6281. }
  6282. }
  6283. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6284. if (p >= 1.0f) {
  6285. return;
  6286. }
  6287. llama_sample_softmax(ctx, candidates);
  6288. const int64_t t_start_sample_us = ggml_time_us();
  6289. // Compute the cumulative probabilities
  6290. float cum_sum = 0.0f;
  6291. size_t last_idx = candidates->size;
  6292. for (size_t i = 0; i < candidates->size; ++i) {
  6293. cum_sum += candidates->data[i].p;
  6294. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6295. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6296. if (cum_sum >= p && i + 1 >= min_keep) {
  6297. last_idx = i + 1;
  6298. break;
  6299. }
  6300. }
  6301. // Resize the output vector to keep only the top-p tokens
  6302. candidates->size = last_idx;
  6303. if (ctx) {
  6304. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6305. }
  6306. }
  6307. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6308. if (p <= 0.0f || !candidates->size) {
  6309. return;
  6310. }
  6311. llama_sample_softmax(ctx, candidates);
  6312. const int64_t t_start_sample_us = ggml_time_us();
  6313. float scale = candidates->data[0].p; // scale by max prob
  6314. size_t i = 1; // first token always matches
  6315. for (; i < candidates->size; ++i) {
  6316. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6317. break; // prob too small
  6318. }
  6319. }
  6320. // Resize the output vector to keep only the matching tokens
  6321. candidates->size = i;
  6322. if (ctx) {
  6323. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6324. }
  6325. }
  6326. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6327. if (z >= 1.0f || candidates->size <= 2) {
  6328. return;
  6329. }
  6330. llama_sample_softmax(nullptr, candidates);
  6331. const int64_t t_start_sample_us = ggml_time_us();
  6332. // Compute the first and second derivatives
  6333. std::vector<float> first_derivatives(candidates->size - 1);
  6334. std::vector<float> second_derivatives(candidates->size - 2);
  6335. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6336. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6337. }
  6338. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6339. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6340. }
  6341. // Calculate absolute value of second derivatives
  6342. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6343. second_derivatives[i] = std::abs(second_derivatives[i]);
  6344. }
  6345. // Normalize the second derivatives
  6346. {
  6347. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6348. if (second_derivatives_sum > 1e-6f) {
  6349. for (float & value : second_derivatives) {
  6350. value /= second_derivatives_sum;
  6351. }
  6352. } else {
  6353. for (float & value : second_derivatives) {
  6354. value = 1.0f / second_derivatives.size();
  6355. }
  6356. }
  6357. }
  6358. float cum_sum = 0.0f;
  6359. size_t last_idx = candidates->size;
  6360. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6361. cum_sum += second_derivatives[i];
  6362. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6363. if (cum_sum > z && i >= min_keep) {
  6364. last_idx = i;
  6365. break;
  6366. }
  6367. }
  6368. // Resize the output vector to keep only the tokens above the tail location
  6369. candidates->size = last_idx;
  6370. if (ctx) {
  6371. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6372. }
  6373. }
  6374. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6375. // Reference implementation:
  6376. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6377. if (p >= 1.0f) {
  6378. return;
  6379. }
  6380. // Compute the softmax of logits and calculate entropy
  6381. llama_sample_softmax(nullptr, candidates);
  6382. const int64_t t_start_sample_us = ggml_time_us();
  6383. float entropy = 0.0f;
  6384. for (size_t i = 0; i < candidates->size; ++i) {
  6385. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6386. }
  6387. // Compute the absolute difference between negative log probability and entropy for each candidate
  6388. std::vector<float> shifted_scores;
  6389. for (size_t i = 0; i < candidates->size; ++i) {
  6390. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6391. shifted_scores.push_back(shifted_score);
  6392. }
  6393. // Sort tokens based on the shifted_scores and their corresponding indices
  6394. std::vector<size_t> indices(candidates->size);
  6395. std::iota(indices.begin(), indices.end(), 0);
  6396. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6397. return shifted_scores[a] < shifted_scores[b];
  6398. });
  6399. // Compute the cumulative probabilities
  6400. float cum_sum = 0.0f;
  6401. size_t last_idx = indices.size();
  6402. for (size_t i = 0; i < indices.size(); ++i) {
  6403. size_t idx = indices[i];
  6404. cum_sum += candidates->data[idx].p;
  6405. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6406. if (cum_sum > p && i >= min_keep - 1) {
  6407. last_idx = i + 1;
  6408. break;
  6409. }
  6410. }
  6411. // Resize the output vector to keep only the locally typical tokens
  6412. std::vector<llama_token_data> new_candidates;
  6413. for (size_t i = 0; i < last_idx; ++i) {
  6414. size_t idx = indices[i];
  6415. new_candidates.push_back(candidates->data[idx]);
  6416. }
  6417. // Replace the data in candidates with the new_candidates data
  6418. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6419. candidates->size = new_candidates.size();
  6420. candidates->sorted = false;
  6421. if (ctx) {
  6422. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6423. }
  6424. }
  6425. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6426. const int64_t t_start_sample_us = ggml_time_us();
  6427. for (size_t i = 0; i < candidates_p->size; ++i) {
  6428. candidates_p->data[i].logit /= temp;
  6429. }
  6430. if (ctx) {
  6431. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6432. }
  6433. }
  6434. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6435. llama_sample_temp(ctx, candidates_p, temp);
  6436. }
  6437. void llama_sample_repetition_penalties(
  6438. struct llama_context * ctx,
  6439. llama_token_data_array * candidates,
  6440. const llama_token * last_tokens,
  6441. size_t penalty_last_n,
  6442. float penalty_repeat,
  6443. float penalty_freq,
  6444. float penalty_present) {
  6445. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6446. return;
  6447. }
  6448. const int64_t t_start_sample_us = ggml_time_us();
  6449. // Create a frequency map to count occurrences of each token in last_tokens
  6450. std::unordered_map<llama_token, int> token_count;
  6451. for (size_t i = 0; i < penalty_last_n; ++i) {
  6452. token_count[last_tokens[i]]++;
  6453. }
  6454. // Apply frequency and presence penalties to the candidates
  6455. for (size_t i = 0; i < candidates->size; ++i) {
  6456. const auto token_iter = token_count.find(candidates->data[i].id);
  6457. if (token_iter == token_count.end()) {
  6458. continue;
  6459. }
  6460. const int count = token_iter->second;
  6461. // 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.
  6462. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6463. if (candidates->data[i].logit <= 0) {
  6464. candidates->data[i].logit *= penalty_repeat;
  6465. } else {
  6466. candidates->data[i].logit /= penalty_repeat;
  6467. }
  6468. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6469. }
  6470. candidates->sorted = false;
  6471. if (ctx) {
  6472. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6473. }
  6474. }
  6475. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6476. GGML_ASSERT(ctx);
  6477. const int64_t t_start_sample_us = ggml_time_us();
  6478. bool allow_eos = false;
  6479. for (const auto & stack : grammar->stacks) {
  6480. if (stack.empty()) {
  6481. allow_eos = true;
  6482. break;
  6483. }
  6484. }
  6485. const llama_token eos = llama_token_eos(&ctx->model);
  6486. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6487. candidates_decoded.reserve(candidates->size);
  6488. std::vector<llama_grammar_candidate> candidates_grammar;
  6489. candidates_grammar.reserve(candidates->size);
  6490. for (size_t i = 0; i < candidates->size; ++i) {
  6491. const llama_token id = candidates->data[i].id;
  6492. const std::string piece = llama_token_to_piece(ctx, id);
  6493. if (id == eos) {
  6494. if (!allow_eos) {
  6495. candidates->data[i].logit = -INFINITY;
  6496. }
  6497. } else if (piece.empty() || piece[0] == 0) {
  6498. candidates->data[i].logit = -INFINITY;
  6499. } else {
  6500. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6501. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6502. }
  6503. }
  6504. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6505. for (const auto & reject : rejects) {
  6506. candidates->data[reject.index].logit = -INFINITY;
  6507. }
  6508. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6509. }
  6510. static void llama_log_softmax(float * array, size_t size) {
  6511. float max_l = *std::max_element(array, array + size);
  6512. float sum = 0.f;
  6513. for (size_t i = 0; i < size; ++i) {
  6514. float p = expf(array[i] - max_l);
  6515. sum += p;
  6516. array[i] = p;
  6517. }
  6518. for (size_t i = 0; i < size; ++i) {
  6519. array[i] = logf(array[i] / sum);
  6520. }
  6521. }
  6522. void llama_sample_classifier_free_guidance(
  6523. struct llama_context * ctx,
  6524. llama_token_data_array * candidates,
  6525. struct llama_context * guidance_ctx,
  6526. float scale) {
  6527. int64_t t_start_sample_us = ggml_time_us();
  6528. GGML_ASSERT(ctx);
  6529. auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6530. GGML_ASSERT(n_vocab == (int)candidates->size);
  6531. GGML_ASSERT(!candidates->sorted);
  6532. std::vector<float> logits_base;
  6533. logits_base.reserve(candidates->size);
  6534. for (size_t i = 0; i < candidates->size; ++i) {
  6535. logits_base.push_back(candidates->data[i].logit);
  6536. }
  6537. llama_log_softmax(logits_base.data(), candidates->size);
  6538. float* logits_guidance = llama_get_logits(guidance_ctx);
  6539. llama_log_softmax(logits_guidance, n_vocab);
  6540. for (int i = 0; i < n_vocab; ++i) {
  6541. float logit_guidance = logits_guidance[i];
  6542. float logit_base = logits_base[i];
  6543. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  6544. }
  6545. if (ctx) {
  6546. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6547. }
  6548. }
  6549. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  6550. GGML_ASSERT(ctx);
  6551. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6552. int64_t t_start_sample_us;
  6553. t_start_sample_us = ggml_time_us();
  6554. llama_sample_softmax(nullptr, candidates);
  6555. // Estimate s_hat using the most probable m tokens
  6556. float s_hat = 0.0;
  6557. float sum_ti_bi = 0.0;
  6558. float sum_ti_sq = 0.0;
  6559. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6560. float t_i = logf(float(i + 2) / float(i + 1));
  6561. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6562. sum_ti_bi += t_i * b_i;
  6563. sum_ti_sq += t_i * t_i;
  6564. }
  6565. s_hat = sum_ti_bi / sum_ti_sq;
  6566. // Compute k from the estimated s_hat and target surprise value
  6567. float epsilon_hat = s_hat - 1;
  6568. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6569. // Sample the next word X using top-k sampling
  6570. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6571. if (ctx) {
  6572. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6573. }
  6574. llama_token X = llama_sample_token(ctx, candidates);
  6575. t_start_sample_us = ggml_time_us();
  6576. // Compute error as the difference between observed surprise and target surprise value
  6577. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6578. return candidate.id == X;
  6579. }));
  6580. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6581. float e = observed_surprise - tau;
  6582. // Update mu using the learning rate and error
  6583. *mu = *mu - eta * e;
  6584. if (ctx) {
  6585. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6586. }
  6587. return X;
  6588. }
  6589. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6590. int64_t t_start_sample_us;
  6591. t_start_sample_us = ggml_time_us();
  6592. llama_sample_softmax(ctx, candidates);
  6593. // Truncate the words with surprise values greater than mu
  6594. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6595. return -log2f(candidate.p) > *mu;
  6596. }));
  6597. if (candidates->size == 0) {
  6598. candidates->size = 1;
  6599. }
  6600. if (ctx) {
  6601. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6602. }
  6603. // Normalize the probabilities of the remaining words
  6604. llama_sample_softmax(ctx, candidates);
  6605. // Sample the next word X from the remaining words
  6606. llama_token X = llama_sample_token(ctx, candidates);
  6607. t_start_sample_us = ggml_time_us();
  6608. // Compute error as the difference between observed surprise and target surprise value
  6609. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6610. return candidate.id == X;
  6611. }));
  6612. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6613. float e = observed_surprise - tau;
  6614. // Update mu using the learning rate and error
  6615. *mu = *mu - eta * e;
  6616. if (ctx) {
  6617. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6618. }
  6619. return X;
  6620. }
  6621. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  6622. const int64_t t_start_sample_us = ggml_time_us();
  6623. // Find max element
  6624. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6625. return a.logit < b.logit;
  6626. });
  6627. llama_token result = max_iter->id;
  6628. if (ctx) {
  6629. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6630. ctx->n_sample++;
  6631. }
  6632. return result;
  6633. }
  6634. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  6635. GGML_ASSERT(ctx);
  6636. const int64_t t_start_sample_us = ggml_time_us();
  6637. llama_sample_softmax(nullptr, candidates);
  6638. std::vector<float> probs;
  6639. probs.reserve(candidates->size);
  6640. for (size_t i = 0; i < candidates->size; ++i) {
  6641. probs.push_back(candidates->data[i].p);
  6642. }
  6643. std::discrete_distribution<> dist(probs.begin(), probs.end());
  6644. auto & rng = ctx->rng;
  6645. int idx = dist(rng);
  6646. llama_token result = candidates->data[idx].id;
  6647. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6648. ctx->n_sample++;
  6649. return result;
  6650. }
  6651. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  6652. const int64_t t_start_sample_us = ggml_time_us();
  6653. if (token == llama_token_eos(&ctx->model)) {
  6654. for (const auto & stack : grammar->stacks) {
  6655. if (stack.empty()) {
  6656. return;
  6657. }
  6658. }
  6659. GGML_ASSERT(false);
  6660. }
  6661. const std::string piece = llama_token_to_piece(ctx, token);
  6662. // Note terminating 0 in decoded string
  6663. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  6664. const auto & code_points = decoded.first;
  6665. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  6666. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  6667. }
  6668. grammar->partial_utf8 = decoded.second;
  6669. GGML_ASSERT(!grammar->stacks.empty());
  6670. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6671. }
  6672. //
  6673. // Beam search
  6674. //
  6675. struct llama_beam {
  6676. std::vector<llama_token> tokens;
  6677. float p; // Cumulative beam probability (renormalized relative to all beams)
  6678. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  6679. // Sort beams by probability. In case of ties, prefer beams at eob.
  6680. bool operator<(const llama_beam & rhs) const {
  6681. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  6682. }
  6683. // Shift off first n tokens and discard them.
  6684. void shift_tokens(const size_t n) {
  6685. if (n) {
  6686. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  6687. tokens.resize(tokens.size() - n);
  6688. }
  6689. }
  6690. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  6691. };
  6692. // A struct for calculating logit-related info.
  6693. struct llama_logit_info {
  6694. const float * const logits;
  6695. const int n_vocab;
  6696. const float max_l;
  6697. const float normalizer;
  6698. struct sum_exp {
  6699. float max_l;
  6700. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  6701. };
  6702. llama_logit_info(llama_context * ctx)
  6703. : logits(llama_get_logits(ctx))
  6704. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  6705. , max_l(*std::max_element(logits, logits + n_vocab))
  6706. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  6707. { }
  6708. llama_token_data get_token_data(const llama_token token_id) const {
  6709. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  6710. return {token_id, logits[token_id], p};
  6711. }
  6712. // Return top k token_data by logit.
  6713. std::vector<llama_token_data> top_k(size_t k) {
  6714. std::vector<llama_token_data> min_heap; // min-heap by logit
  6715. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  6716. min_heap.reserve(k_min);
  6717. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  6718. min_heap.push_back(get_token_data(token_id));
  6719. }
  6720. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  6721. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  6722. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  6723. if (min_heap.front().logit < logits[token_id]) {
  6724. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  6725. min_heap.back().id = token_id;
  6726. min_heap.back().logit = logits[token_id];
  6727. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  6728. }
  6729. }
  6730. return min_heap;
  6731. }
  6732. float probability_from_logit(float logit) const {
  6733. return normalizer * std::exp(logit - max_l);
  6734. }
  6735. };
  6736. struct llama_beam_search_data {
  6737. llama_context * ctx;
  6738. size_t n_beams;
  6739. int n_past;
  6740. int n_predict;
  6741. std::vector<llama_beam> beams;
  6742. std::vector<llama_beam> next_beams;
  6743. // Re-calculated on each loop iteration
  6744. size_t common_prefix_length;
  6745. // Used to communicate to/from callback on beams state.
  6746. std::vector<llama_beam_view> beam_views;
  6747. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  6748. : ctx(ctx)
  6749. , n_beams(n_beams)
  6750. , n_past(n_past)
  6751. , n_predict(n_predict)
  6752. , beam_views(n_beams) {
  6753. beams.reserve(n_beams);
  6754. next_beams.reserve(n_beams);
  6755. }
  6756. // Collapse beams to a single beam given by index.
  6757. void collapse_beams(const size_t beam_idx) {
  6758. if (0u < beam_idx) {
  6759. std::swap(beams[0], beams[beam_idx]);
  6760. }
  6761. beams.resize(1);
  6762. }
  6763. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  6764. // The repetitive patterns below reflect the 2 stages of heaps:
  6765. // * Gather elements until the vector is full, then call std::make_heap() on it.
  6766. // * If the heap is full and a new element is found that should be included, pop the
  6767. // least element to the back(), replace it with the new, then push it into the heap.
  6768. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  6769. // Min-heaps use a greater-than comparator.
  6770. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  6771. if (beam.eob) {
  6772. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  6773. if (next_beams.size() < n_beams) {
  6774. next_beams.push_back(std::move(beam));
  6775. if (next_beams.size() == n_beams) {
  6776. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  6777. }
  6778. } else if (next_beams.front().p < beam.p) {
  6779. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6780. next_beams.back() = std::move(beam);
  6781. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6782. }
  6783. } else {
  6784. // beam is not at end-of-sentence, so branch with next top_k tokens.
  6785. if (!beam.tokens.empty()) {
  6786. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  6787. }
  6788. llama_logit_info logit_info(ctx);
  6789. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  6790. size_t i=0;
  6791. if (next_beams.size() < n_beams) {
  6792. for (; next_beams.size() < n_beams ; ++i) {
  6793. llama_beam next_beam = beam;
  6794. next_beam.tokens.push_back(next_tokens[i].id);
  6795. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  6796. next_beams.push_back(std::move(next_beam));
  6797. }
  6798. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  6799. } else {
  6800. for (; next_beams.front().p == 0.0f ; ++i) {
  6801. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6802. next_beams.back() = beam;
  6803. next_beams.back().tokens.push_back(next_tokens[i].id);
  6804. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  6805. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6806. }
  6807. }
  6808. for (; i < n_beams ; ++i) {
  6809. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  6810. if (next_beams.front().p < next_p) {
  6811. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  6812. next_beams.back() = beam;
  6813. next_beams.back().tokens.push_back(next_tokens[i].id);
  6814. next_beams.back().p = next_p;
  6815. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  6816. }
  6817. }
  6818. }
  6819. }
  6820. // Find common_prefix_length based on beams.
  6821. // Requires beams is not empty.
  6822. size_t find_common_prefix_length() {
  6823. size_t common_prefix_length = beams[0].tokens.size();
  6824. for (size_t i = 1 ; i < beams.size() ; ++i) {
  6825. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  6826. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  6827. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  6828. common_prefix_length = j;
  6829. break;
  6830. }
  6831. }
  6832. }
  6833. return common_prefix_length;
  6834. }
  6835. // Construct beams_state to send back to caller via the callback function.
  6836. // Side effect: set common_prefix_length = find_common_prefix_length();
  6837. llama_beams_state get_beams_state(const bool last_call) {
  6838. for (size_t i = 0 ; i < beams.size() ; ++i) {
  6839. beam_views[i] = beams[i].view();
  6840. }
  6841. common_prefix_length = find_common_prefix_length();
  6842. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  6843. }
  6844. // Loop:
  6845. // * while i < n_predict, AND
  6846. // * any of the beams have not yet reached end-of-beam (eob), AND
  6847. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  6848. // (since all other beam probabilities can only decrease)
  6849. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  6850. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  6851. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  6852. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  6853. !beams[top_beam_index()].eob ; ++i) {
  6854. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  6855. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  6856. if (common_prefix_length) {
  6857. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  6858. n_past += common_prefix_length;
  6859. }
  6860. // Zero-out next_beam probabilities to place them last in following min-heap.
  6861. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  6862. for (llama_beam & beam : beams) {
  6863. beam.shift_tokens(common_prefix_length);
  6864. fill_next_beams_by_top_probabilities(beam);
  6865. }
  6866. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  6867. beams.swap(next_beams);
  6868. renormalize_beam_probabilities(beams);
  6869. }
  6870. collapse_beams(top_beam_index());
  6871. callback(callback_data, get_beams_state(true));
  6872. }
  6873. // As beams grow, the cumulative probabilities decrease.
  6874. // Renormalize them to avoid floating point underflow.
  6875. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  6876. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  6877. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  6878. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  6879. }
  6880. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  6881. size_t top_beam_index() {
  6882. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  6883. }
  6884. // Copy (p,eob) for each beam which may have been changed by the callback.
  6885. void update_beams_from_beam_views() {
  6886. for (size_t i = 0 ; i < beams.size() ; ++i) {
  6887. beams[i].p = beam_views[i].p;
  6888. beams[i].eob = beam_views[i].eob;
  6889. }
  6890. }
  6891. };
  6892. void llama_beam_search(llama_context * ctx,
  6893. llama_beam_search_callback_fn_t callback, void * callback_data,
  6894. size_t n_beams, int n_past, int n_predict) {
  6895. assert(ctx);
  6896. const int64_t t_start_sample_us = ggml_time_us();
  6897. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  6898. beam_search_data.loop(callback, callback_data);
  6899. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6900. ctx->n_sample++;
  6901. }
  6902. //
  6903. // quantization
  6904. //
  6905. struct quantize_state_internal {
  6906. const llama_model & model;
  6907. const llama_model_quantize_params * params;
  6908. int n_attention_wv = 0;
  6909. int n_feed_forward_w2 = 0;
  6910. int i_attention_wv = 0;
  6911. int i_feed_forward_w2 = 0;
  6912. int n_k_quantized = 0;
  6913. int n_fallback = 0;
  6914. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  6915. : model(model)
  6916. , params(params)
  6917. {}
  6918. };
  6919. static void llama_convert_tensor_internal(
  6920. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  6921. const size_t nelements, const int nthread
  6922. ) {
  6923. if (output.size() < nelements) {
  6924. output.resize(nelements);
  6925. }
  6926. float * f32_output = (float *) output.data();
  6927. ggml_type_traits_t qtype;
  6928. if (ggml_is_quantized(tensor->type)) {
  6929. qtype = ggml_internal_get_type_traits(tensor->type);
  6930. if (qtype.to_float == NULL) {
  6931. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  6932. }
  6933. } else if (tensor->type != GGML_TYPE_F16) {
  6934. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  6935. }
  6936. if (nthread < 2) {
  6937. if (tensor->type == GGML_TYPE_F16) {
  6938. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  6939. } else if (ggml_is_quantized(tensor->type)) {
  6940. qtype.to_float(tensor->data, f32_output, nelements);
  6941. } else {
  6942. GGML_ASSERT(false); // unreachable
  6943. }
  6944. return;
  6945. }
  6946. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  6947. size_t block_size_bytes = ggml_type_size(tensor->type);
  6948. GGML_ASSERT(nelements % block_size == 0);
  6949. size_t nblocks = nelements / block_size;
  6950. size_t blocks_per_thread = nblocks / nthread;
  6951. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  6952. size_t in_buff_offs = 0;
  6953. size_t out_buff_offs = 0;
  6954. for (int tnum = 0; tnum < nthread; tnum++) {
  6955. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  6956. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  6957. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  6958. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  6959. if (typ == GGML_TYPE_F16) {
  6960. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  6961. } else {
  6962. qtype.to_float(inbuf, outbuf, nels);
  6963. }
  6964. };
  6965. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  6966. in_buff_offs += thr_block_bytes;
  6967. out_buff_offs += thr_elems;
  6968. }
  6969. for (auto & w : workers) { w.join(); }
  6970. workers.clear();
  6971. }
  6972. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  6973. const std::string name = ggml_get_name(tensor);
  6974. // TODO: avoid hardcoded tensor names - use the TN_* constants
  6975. const llm_arch arch = qs.model.arch;
  6976. const auto tn = LLM_TN(arch);
  6977. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  6978. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  6979. };
  6980. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  6981. int nx = tensor->ne[0];
  6982. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  6983. new_type = GGML_TYPE_Q8_0;
  6984. }
  6985. else if (new_type != GGML_TYPE_Q8_0) {
  6986. new_type = GGML_TYPE_Q6_K;
  6987. }
  6988. } else if (name.find("attn_v.weight") != std::string::npos) {
  6989. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  6990. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  6991. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  6992. }
  6993. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  6994. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  6995. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  6996. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  6997. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  6998. (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;
  6999. if (qs.model.type == MODEL_70B) {
  7000. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7001. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7002. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7003. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7004. }
  7005. if (qs.model.hparams.n_expert == 8) {
  7006. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7007. // TODO: explore better strategies
  7008. new_type = GGML_TYPE_Q8_0;
  7009. }
  7010. ++qs.i_attention_wv;
  7011. } else if (name.find("attn_k.weight") != std::string::npos) {
  7012. if (qs.model.hparams.n_expert == 8) {
  7013. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7014. // TODO: explore better strategies
  7015. new_type = GGML_TYPE_Q8_0;
  7016. }
  7017. } else if (name.find("ffn_down") != std::string::npos) {
  7018. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7019. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  7020. if (qs.i_feed_forward_w2 < qs.n_feed_forward_w2/8) new_type = GGML_TYPE_Q4_K;
  7021. }
  7022. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7023. new_type = qs.i_feed_forward_w2 < qs.n_feed_forward_w2/16 ? GGML_TYPE_Q5_K
  7024. : arch != LLM_ARCH_FALCON || use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q4_K
  7025. : GGML_TYPE_Q3_K;
  7026. }
  7027. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7028. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7029. }
  7030. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7031. if (arch == LLM_ARCH_FALCON) {
  7032. new_type = qs.i_feed_forward_w2 < qs.n_feed_forward_w2/16 ? GGML_TYPE_Q6_K :
  7033. use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7034. } else {
  7035. if (use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  7036. }
  7037. }
  7038. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(qs.i_feed_forward_w2, qs.n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  7039. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && qs.i_feed_forward_w2 < qs.n_feed_forward_w2/8) {
  7040. new_type = GGML_TYPE_Q5_K;
  7041. }
  7042. ++qs.i_feed_forward_w2;
  7043. } else if (name.find("attn_output.weight") != std::string::npos) {
  7044. if (arch != LLM_ARCH_FALCON) {
  7045. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7046. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7047. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7048. } else {
  7049. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7050. }
  7051. }
  7052. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7053. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7054. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7055. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7056. }
  7057. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7058. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7059. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7060. //}
  7061. // This can be used to reduce the size of the Q5_K_S model.
  7062. // The associated PPL increase is fully in line with the size reduction
  7063. //else {
  7064. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7065. //}
  7066. bool convert_incompatible_tensor = false;
  7067. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7068. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  7069. int nx = tensor->ne[0];
  7070. int ny = tensor->ne[1];
  7071. if (nx % QK_K != 0) {
  7072. 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));
  7073. convert_incompatible_tensor = true;
  7074. } else {
  7075. ++qs.n_k_quantized;
  7076. }
  7077. }
  7078. if (convert_incompatible_tensor) {
  7079. switch (new_type) {
  7080. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7081. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7082. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7083. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7084. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7085. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7086. }
  7087. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7088. ++qs.n_fallback;
  7089. }
  7090. return new_type;
  7091. }
  7092. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7093. ggml_type quantized_type;
  7094. llama_ftype ftype = params->ftype;
  7095. switch (params->ftype) {
  7096. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7097. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7098. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7099. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7100. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7101. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7102. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7103. // K-quants
  7104. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7105. case LLAMA_FTYPE_MOSTLY_Q2_K_S: quantized_type = GGML_TYPE_Q2_K; break;
  7106. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7107. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7108. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7109. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7110. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7111. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7112. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7113. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7114. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7115. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7116. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7117. }
  7118. int nthread = params->nthread;
  7119. if (nthread <= 0) {
  7120. nthread = std::thread::hardware_concurrency();
  7121. }
  7122. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7123. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7124. #if defined(__linux__) || defined(_WIN32)
  7125. constexpr bool use_mmap = true;
  7126. #else
  7127. constexpr bool use_mmap = false;
  7128. #endif
  7129. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7130. ml.init_mapping(false); // no prefetching?
  7131. llama_model model;
  7132. llm_load_arch(ml, model);
  7133. llm_load_hparams(ml, model);
  7134. struct quantize_state_internal qs(model, params);
  7135. if (params->only_copy) {
  7136. ftype = model.ftype;
  7137. }
  7138. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7139. struct gguf_context * ctx_out = gguf_init_empty();
  7140. // copy the KV pairs from the input file
  7141. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7142. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7143. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7144. for (int i = 0; i < ml.n_tensors; ++i) {
  7145. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7146. const std::string name = ggml_get_name(meta);
  7147. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7148. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7149. ++qs.n_attention_wv;
  7150. }
  7151. else if (name.find("ffn_down") != std::string::npos) {
  7152. ++qs.n_feed_forward_w2;
  7153. }
  7154. }
  7155. if (qs.n_attention_wv != qs.n_feed_forward_w2 || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7156. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  7157. __func__, qs.n_attention_wv, qs.n_feed_forward_w2, model.hparams.n_layer);
  7158. }
  7159. size_t total_size_org = 0;
  7160. size_t total_size_new = 0;
  7161. std::vector<int64_t> hist_all(1 << 4, 0);
  7162. std::vector<std::thread> workers;
  7163. workers.reserve(nthread);
  7164. std::mutex mutex;
  7165. int idx = 0;
  7166. std::vector<no_init<uint8_t>> read_data;
  7167. std::vector<no_init<uint8_t>> work;
  7168. std::vector<no_init<float>> f32_conv_buf;
  7169. // populate the original tensors so we get an initial meta data
  7170. for (int i = 0; i < ml.n_tensors; ++i) {
  7171. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7172. gguf_add_tensor(ctx_out, meta);
  7173. }
  7174. std::ofstream fout(fname_out, std::ios::binary);
  7175. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7176. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7177. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7178. // placeholder for the meta data
  7179. ::zeros(fout, meta_size);
  7180. for (int i = 0; i < ml.n_tensors; ++i) {
  7181. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7182. const std::string name = ggml_get_name(tensor);
  7183. if (!ml.use_mmap) {
  7184. if (read_data.size() < ggml_nbytes(tensor)) {
  7185. read_data.resize(ggml_nbytes(tensor));
  7186. }
  7187. tensor->data = read_data.data();
  7188. }
  7189. ml.load_data_for(tensor);
  7190. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7191. ++idx, ml.n_tensors,
  7192. ggml_get_name(tensor),
  7193. llama_format_tensor_shape(tensor).c_str(),
  7194. ggml_type_name(tensor->type));
  7195. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7196. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7197. // quantize only 2D tensors
  7198. quantize &= (ggml_n_dims(tensor) == 2);
  7199. quantize &= params->quantize_output_tensor || name != "output.weight";
  7200. quantize &= !params->only_copy;
  7201. // do not quantize expert gating tensors
  7202. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7203. enum ggml_type new_type;
  7204. void * new_data;
  7205. size_t new_size;
  7206. if (quantize) {
  7207. new_type = quantized_type;
  7208. if (!params->pure) {
  7209. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7210. }
  7211. // If we've decided to quantize to the same type the tensor is already
  7212. // in then there's nothing to do.
  7213. quantize = tensor->type != new_type;
  7214. }
  7215. if (!quantize) {
  7216. new_type = tensor->type;
  7217. new_data = tensor->data;
  7218. new_size = ggml_nbytes(tensor);
  7219. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7220. } else {
  7221. const size_t nelements = ggml_nelements(tensor);
  7222. float * f32_data;
  7223. if (tensor->type == GGML_TYPE_F32) {
  7224. f32_data = (float *) tensor->data;
  7225. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7226. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7227. } else {
  7228. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7229. f32_data = (float *) f32_conv_buf.data();
  7230. }
  7231. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7232. fflush(stdout);
  7233. if (work.size() < nelements * 4) {
  7234. work.resize(nelements * 4); // upper bound on size
  7235. }
  7236. new_data = work.data();
  7237. std::array<int64_t, 1 << 4> hist_cur = {};
  7238. static const int chunk_size = 32 * 512;
  7239. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7240. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7241. if (nthread_use < 2) {
  7242. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  7243. } else {
  7244. size_t counter = 0;
  7245. new_size = 0;
  7246. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  7247. std::array<int64_t, 1 << 4> local_hist = {};
  7248. size_t local_size = 0;
  7249. while (true) {
  7250. std::unique_lock<std::mutex> lock(mutex);
  7251. size_t first = counter; counter += chunk_size;
  7252. if (first >= nelements) {
  7253. if (local_size > 0) {
  7254. for (int j=0; j<int(local_hist.size()); ++j) {
  7255. hist_cur[j] += local_hist[j];
  7256. }
  7257. new_size += local_size;
  7258. }
  7259. break;
  7260. }
  7261. lock.unlock();
  7262. size_t last = std::min(nelements, first + chunk_size);
  7263. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  7264. }
  7265. };
  7266. for (int it = 0; it < nthread_use - 1; ++it) {
  7267. workers.emplace_back(compute);
  7268. }
  7269. compute();
  7270. for (auto & w : workers) { w.join(); }
  7271. workers.clear();
  7272. }
  7273. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7274. int64_t tot_count = 0;
  7275. for (size_t i = 0; i < hist_cur.size(); i++) {
  7276. hist_all[i] += hist_cur[i];
  7277. tot_count += hist_cur[i];
  7278. }
  7279. if (tot_count > 0) {
  7280. for (size_t i = 0; i < hist_cur.size(); i++) {
  7281. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7282. }
  7283. }
  7284. LLAMA_LOG_INFO("\n");
  7285. }
  7286. total_size_org += ggml_nbytes(tensor);
  7287. total_size_new += new_size;
  7288. // update the gguf meta data as we go
  7289. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7290. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7291. // write tensor data + padding
  7292. fout.write((const char *) new_data, new_size);
  7293. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7294. }
  7295. // go back to beginning of file and write the updated meta data
  7296. {
  7297. fout.seekp(0);
  7298. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7299. gguf_get_meta_data(ctx_out, data.data());
  7300. fout.write((const char *) data.data(), data.size());
  7301. }
  7302. fout.close();
  7303. gguf_free(ctx_out);
  7304. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7305. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7306. // print histogram for all tensors
  7307. {
  7308. int64_t sum_all = 0;
  7309. for (size_t i = 0; i < hist_all.size(); i++) {
  7310. sum_all += hist_all[i];
  7311. }
  7312. if (sum_all > 0) {
  7313. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7314. for (size_t i = 0; i < hist_all.size(); i++) {
  7315. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7316. }
  7317. LLAMA_LOG_INFO("\n");
  7318. }
  7319. }
  7320. if (qs.n_fallback > 0) {
  7321. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7322. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7323. }
  7324. }
  7325. static int llama_apply_lora_from_file_internal(
  7326. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7327. ) {
  7328. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7329. const int64_t t_start_lora_us = ggml_time_us();
  7330. llama_file fin(path_lora, "rb");
  7331. // verify magic and version
  7332. {
  7333. uint32_t magic = fin.read_u32();
  7334. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7335. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7336. return 1;
  7337. }
  7338. uint32_t format_version = fin.read_u32();
  7339. if (format_version != 1) {
  7340. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7341. return 1;
  7342. }
  7343. }
  7344. int32_t lora_r = fin.read_u32();
  7345. int32_t lora_alpha = fin.read_u32();
  7346. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7347. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7348. // load base model
  7349. std::unique_ptr<llama_model_loader> ml;
  7350. if (path_base_model) {
  7351. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7352. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  7353. ml->init_mapping(/*prefetch*/ false); // no prefetching
  7354. }
  7355. struct tensor_meta {
  7356. std::string name;
  7357. ggml_type type;
  7358. int32_t ne[2];
  7359. size_t offset;
  7360. };
  7361. std::map<std::string, tensor_meta> tensor_meta_map;
  7362. // load all tensor meta
  7363. while (true) {
  7364. if (fin.tell() == fin.size) {
  7365. // eof
  7366. break;
  7367. }
  7368. int32_t n_dims;
  7369. int32_t name_len;
  7370. int32_t ftype;
  7371. fin.read_raw(&n_dims, sizeof(n_dims));
  7372. fin.read_raw(&name_len, sizeof(name_len));
  7373. fin.read_raw(&ftype, sizeof(ftype));
  7374. if (n_dims != 1 && n_dims != 2) {
  7375. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7376. return 1;
  7377. }
  7378. int32_t ne[2] = { 1, 1 };
  7379. for (int i = 0; i < n_dims; ++i) {
  7380. fin.read_raw(&ne[i], sizeof(ne[i]));
  7381. }
  7382. std::string name;
  7383. {
  7384. GGML_ASSERT(name_len < GGML_MAX_NAME);
  7385. char buf[GGML_MAX_NAME];
  7386. fin.read_raw(buf, name_len);
  7387. name = std::string(buf, name_len);
  7388. }
  7389. // check for lora suffix
  7390. std::string lora_suffix;
  7391. if (name.length() > 6) {
  7392. lora_suffix = name.substr(name.length() - 6);
  7393. }
  7394. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  7395. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7396. return 1;
  7397. }
  7398. // tensor type
  7399. ggml_type wtype;
  7400. switch (ftype) {
  7401. case 0: wtype = GGML_TYPE_F32; break;
  7402. case 1: wtype = GGML_TYPE_F16; break;
  7403. default:
  7404. {
  7405. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7406. __func__, ftype);
  7407. return false;
  7408. }
  7409. }
  7410. // data offset
  7411. size_t offset = fin.tell();
  7412. offset = (offset + 31) & -32;
  7413. // skip tensor data
  7414. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  7415. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  7416. }
  7417. bool warned = false;
  7418. int n_tensors = 0;
  7419. // apply
  7420. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  7421. if (backend_cpu == nullptr) {
  7422. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  7423. return 1;
  7424. }
  7425. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  7426. std::vector<no_init<uint8_t>> read_buf;
  7427. for (const auto & it : model.tensors_by_name) {
  7428. const std::string & base_name = it.first;
  7429. ggml_tensor * model_t = it.second;
  7430. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  7431. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  7432. continue;
  7433. }
  7434. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  7435. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  7436. ggml_init_params lora_init_params = {
  7437. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  7438. /* .mem_buffer */ nullptr,
  7439. /* .no_alloc */ true,
  7440. };
  7441. ggml_context * lora_ctx = ggml_init(lora_init_params);
  7442. if (lora_ctx == nullptr) {
  7443. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  7444. ggml_backend_free(backend_cpu);
  7445. return 1;
  7446. }
  7447. // create tensors
  7448. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  7449. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  7450. ggml_set_name(loraA, metaA.name.c_str());
  7451. ggml_set_name(loraB, metaB.name.c_str());
  7452. ggml_tensor * base_t;
  7453. if (ml) {
  7454. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  7455. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7456. return 1;
  7457. }
  7458. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  7459. } else {
  7460. base_t = ggml_dup_tensor(lora_ctx, model_t);
  7461. }
  7462. ggml_set_name(base_t, base_name.c_str());
  7463. // allocate in backend buffer
  7464. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7465. if (lora_buf == nullptr) {
  7466. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  7467. return 1;
  7468. }
  7469. // load tensor data
  7470. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  7471. read_buf.resize(ggml_nbytes(tensor));
  7472. fin.seek(tensor_meta.offset, SEEK_SET);
  7473. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  7474. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  7475. };
  7476. load_tensor(metaA, loraA);
  7477. load_tensor(metaB, loraB);
  7478. // load base model tensor data
  7479. if (ml) {
  7480. ml->load_data_for(base_t);
  7481. } else {
  7482. ggml_backend_tensor_copy(model_t, base_t);
  7483. }
  7484. if (ggml_is_quantized(base_t->type) && !warned) {
  7485. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  7486. "use a f16 or f32 base model with --lora-base\n", __func__);
  7487. warned = true;
  7488. }
  7489. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  7490. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  7491. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  7492. ggml_free(lora_ctx);
  7493. ggml_backend_buffer_free(lora_buf);
  7494. ggml_backend_free(backend_cpu);
  7495. return 1;
  7496. }
  7497. auto build_lora_graph = [&]() {
  7498. // w = w + BA*s
  7499. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  7500. ggml_set_name(BA, "BA");
  7501. if (scaling != 1.0f) {
  7502. BA = ggml_scale(lora_ctx, BA, scaling);
  7503. ggml_set_name(BA, "BA_scaled");
  7504. }
  7505. ggml_tensor * r;
  7506. r = ggml_add_inplace(lora_ctx, base_t, BA);
  7507. ggml_set_name(r, "r_add");
  7508. if (base_t->type != model_t->type) {
  7509. // convert the result to the model type
  7510. r = ggml_cast(lora_ctx, r, model_t->type);
  7511. ggml_set_name(r, "r_cast");
  7512. }
  7513. return r;
  7514. };
  7515. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  7516. ggml_tensor * r = build_lora_graph();
  7517. ggml_build_forward_expand(gf, r);
  7518. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7519. if (graph_buf == nullptr) {
  7520. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  7521. ggml_free(lora_ctx);
  7522. ggml_backend_buffer_free(lora_buf);
  7523. ggml_backend_free(backend_cpu);
  7524. return 1;
  7525. }
  7526. ggml_backend_graph_compute(backend_cpu, gf);
  7527. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  7528. #if 0
  7529. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  7530. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  7531. // sched compute
  7532. ggml_build_forward_expand(gf, build_graph());
  7533. ggml_backend_sched_init_measure(sched, gf);
  7534. // create the graph again, since the previous one was destroyed by the measure
  7535. ggml_graph_clear(gf);
  7536. ggml_build_forward_expand(gf, build_graph());
  7537. ggml_backend_sched_graph_compute(sched, gf);
  7538. ggml_backend_sched_free(sched);
  7539. #endif
  7540. ggml_backend_buffer_free(lora_buf);
  7541. ggml_backend_buffer_free(graph_buf);
  7542. ggml_free(lora_ctx);
  7543. n_tensors++;
  7544. if (n_tensors % 4 == 0) {
  7545. LLAMA_LOG_INFO(".");
  7546. }
  7547. }
  7548. ggml_backend_free(backend_cpu);
  7549. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  7550. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  7551. return 0;
  7552. }
  7553. //
  7554. // interface implementation
  7555. //
  7556. struct llama_model_params llama_model_default_params() {
  7557. struct llama_model_params result = {
  7558. /*.n_gpu_layers =*/ 0,
  7559. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  7560. /*.main_gpu =*/ 0,
  7561. /*.tensor_split =*/ nullptr,
  7562. /*.progress_callback =*/ nullptr,
  7563. /*.progress_callback_user_data =*/ nullptr,
  7564. /*.kv_overrides =*/ nullptr,
  7565. /*.vocab_only =*/ false,
  7566. /*.use_mmap =*/ true,
  7567. /*.use_mlock =*/ false,
  7568. };
  7569. #ifdef GGML_USE_METAL
  7570. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  7571. result.n_gpu_layers = 999;
  7572. #endif
  7573. return result;
  7574. }
  7575. struct llama_context_params llama_context_default_params() {
  7576. struct llama_context_params result = {
  7577. /*.seed =*/ LLAMA_DEFAULT_SEED,
  7578. /*.n_ctx =*/ 512,
  7579. /*.n_batch =*/ 512,
  7580. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  7581. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  7582. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  7583. /*.rope_freq_base =*/ 0.0f,
  7584. /*.rope_freq_scale =*/ 0.0f,
  7585. /*.yarn_ext_factor =*/ -1.0f,
  7586. /*.yarn_attn_factor =*/ 1.0f,
  7587. /*.yarn_beta_fast =*/ 32.0f,
  7588. /*.yarn_beta_slow =*/ 1.0f,
  7589. /*.yarn_orig_ctx =*/ 0,
  7590. /*.type_k =*/ GGML_TYPE_F16,
  7591. /*.type_v =*/ GGML_TYPE_F16,
  7592. /*.mul_mat_q =*/ true,
  7593. /*.logits_all =*/ false,
  7594. /*.embedding =*/ false,
  7595. /*.offload_kqv =*/ true,
  7596. };
  7597. return result;
  7598. }
  7599. struct llama_model_quantize_params llama_model_quantize_default_params() {
  7600. struct llama_model_quantize_params result = {
  7601. /*.nthread =*/ 0,
  7602. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  7603. /*.allow_requantize =*/ false,
  7604. /*.quantize_output_tensor =*/ true,
  7605. /*.only_copy =*/ false,
  7606. /*.pure =*/ false,
  7607. };
  7608. return result;
  7609. }
  7610. int32_t llama_max_devices(void) {
  7611. return LLAMA_MAX_DEVICES;
  7612. }
  7613. bool llama_mmap_supported(void) {
  7614. return llama_mmap::SUPPORTED;
  7615. }
  7616. bool llama_mlock_supported(void) {
  7617. return llama_mlock::SUPPORTED;
  7618. }
  7619. void llama_backend_init(bool numa) {
  7620. ggml_time_init();
  7621. // needed to initialize f16 tables
  7622. {
  7623. struct ggml_init_params params = { 0, NULL, false };
  7624. struct ggml_context * ctx = ggml_init(params);
  7625. ggml_free(ctx);
  7626. }
  7627. if (numa) {
  7628. ggml_numa_init();
  7629. }
  7630. #ifdef GGML_USE_MPI
  7631. ggml_mpi_backend_init();
  7632. #endif
  7633. }
  7634. void llama_backend_free(void) {
  7635. #ifdef GGML_USE_MPI
  7636. ggml_mpi_backend_free();
  7637. #endif
  7638. }
  7639. int64_t llama_time_us(void) {
  7640. return ggml_time_us();
  7641. }
  7642. struct llama_model * llama_load_model_from_file(
  7643. const char * path_model,
  7644. struct llama_model_params params) {
  7645. ggml_time_init();
  7646. llama_model * model = new llama_model;
  7647. unsigned cur_percentage = 0;
  7648. if (params.progress_callback == NULL) {
  7649. params.progress_callback_user_data = &cur_percentage;
  7650. params.progress_callback = [](float progress, void * ctx) {
  7651. unsigned * cur_percentage_p = (unsigned *) ctx;
  7652. unsigned percentage = (unsigned) (100 * progress);
  7653. while (percentage > *cur_percentage_p) {
  7654. *cur_percentage_p = percentage;
  7655. LLAMA_LOG_INFO(".");
  7656. if (percentage >= 100) {
  7657. LLAMA_LOG_INFO("\n");
  7658. }
  7659. }
  7660. return true;
  7661. };
  7662. }
  7663. int status = llama_model_load(path_model, *model, params);
  7664. GGML_ASSERT(status <= 0);
  7665. if (status < 0) {
  7666. if (status == -1) {
  7667. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  7668. } else if (status == -2) {
  7669. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  7670. }
  7671. delete model;
  7672. return nullptr;
  7673. }
  7674. return model;
  7675. }
  7676. void llama_free_model(struct llama_model * model) {
  7677. delete model;
  7678. }
  7679. struct llama_context * llama_new_context_with_model(
  7680. struct llama_model * model,
  7681. struct llama_context_params params) {
  7682. if (!model) {
  7683. return nullptr;
  7684. }
  7685. llama_context * ctx = new llama_context(*model);
  7686. const auto & hparams = model->hparams;
  7687. auto & cparams = ctx->cparams;
  7688. cparams.n_batch = params.n_batch;
  7689. cparams.n_threads = params.n_threads;
  7690. cparams.n_threads_batch = params.n_threads_batch;
  7691. cparams.yarn_ext_factor = params.yarn_ext_factor;
  7692. cparams.yarn_attn_factor = params.yarn_attn_factor;
  7693. cparams.yarn_beta_fast = params.yarn_beta_fast;
  7694. cparams.yarn_beta_slow = params.yarn_beta_slow;
  7695. cparams.mul_mat_q = params.mul_mat_q;
  7696. cparams.offload_kqv = params.offload_kqv;
  7697. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  7698. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  7699. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  7700. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  7701. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  7702. hparams.n_ctx_train;
  7703. auto rope_scaling_type = params.rope_scaling_type;
  7704. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  7705. rope_scaling_type = hparams.rope_scaling_type_train;
  7706. }
  7707. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  7708. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  7709. }
  7710. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  7711. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  7712. }
  7713. if (params.seed == LLAMA_DEFAULT_SEED) {
  7714. params.seed = time(NULL);
  7715. }
  7716. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  7717. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  7718. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  7719. ctx->rng = std::mt19937(params.seed);
  7720. ctx->logits_all = params.logits_all;
  7721. const ggml_type type_k = params.type_k;
  7722. const ggml_type type_v = params.type_v;
  7723. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  7724. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  7725. if (!hparams.vocab_only) {
  7726. // initialize backends
  7727. #ifdef GGML_USE_METAL
  7728. if (model->n_gpu_layers > 0) {
  7729. ctx->backend_metal = ggml_backend_metal_init();
  7730. if (ctx->backend_metal == nullptr) {
  7731. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  7732. llama_free(ctx);
  7733. return nullptr;
  7734. }
  7735. ctx->backends.push_back(ctx->backend_metal);
  7736. }
  7737. #elif defined(GGML_USE_CUBLAS)
  7738. if (model->n_gpu_layers > 0) {
  7739. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  7740. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  7741. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  7742. if (backend == nullptr) {
  7743. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  7744. llama_free(ctx);
  7745. return nullptr;
  7746. }
  7747. ctx->backends.push_back(backend);
  7748. } else {
  7749. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  7750. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  7751. ggml_backend_t backend = ggml_backend_cuda_init(device);
  7752. if (backend == nullptr) {
  7753. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  7754. llama_free(ctx);
  7755. return nullptr;
  7756. }
  7757. ctx->backends.push_back(backend);
  7758. }
  7759. }
  7760. }
  7761. #endif
  7762. ctx->backend_cpu = ggml_backend_cpu_init();
  7763. if (ctx->backend_cpu == nullptr) {
  7764. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  7765. llama_free(ctx);
  7766. return nullptr;
  7767. }
  7768. ctx->backends.push_back(ctx->backend_cpu);
  7769. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  7770. cparams.n_ctx, cparams.offload_kqv)) {
  7771. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  7772. llama_free(ctx);
  7773. return nullptr;
  7774. }
  7775. {
  7776. size_t memory_size_k = 0;
  7777. size_t memory_size_v = 0;
  7778. for (auto & k : ctx->kv_self.k_l) {
  7779. memory_size_k += ggml_nbytes(k);
  7780. }
  7781. for (auto & v : ctx->kv_self.v_l) {
  7782. memory_size_v += ggml_nbytes(v);
  7783. }
  7784. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  7785. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  7786. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  7787. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  7788. }
  7789. // resized during inference
  7790. if (params.logits_all) {
  7791. ctx->logits.reserve(cparams.n_ctx*hparams.n_vocab);
  7792. } else {
  7793. ctx->logits.reserve(hparams.n_vocab);
  7794. }
  7795. if (params.embedding){
  7796. ctx->embedding.resize(hparams.n_embd);
  7797. }
  7798. {
  7799. // buffer types used for the compute buffer of each backend
  7800. std::vector<ggml_backend_buffer_type_t> backend_buft;
  7801. for (auto * backend : ctx->backends) {
  7802. if (ggml_backend_is_cpu(backend)) {
  7803. // use host buffers for the CPU backend compute buffer
  7804. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  7805. } else {
  7806. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  7807. }
  7808. }
  7809. // buffer used to store the computation graph and the tensor meta data
  7810. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  7811. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  7812. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  7813. // build worst-case graph
  7814. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  7815. int n_past = cparams.n_ctx - n_tokens;
  7816. 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
  7817. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  7818. // initialize scheduler with the worst-case graph
  7819. ggml_backend_sched_init_measure(ctx->sched, gf);
  7820. // note: the number of splits during measure is higher than during inference due to the kv shift
  7821. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  7822. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  7823. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  7824. for (ggml_backend_t backend : ctx->backends) {
  7825. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  7826. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  7827. ggml_backend_buffer_name(buf),
  7828. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  7829. }
  7830. }
  7831. }
  7832. #ifdef GGML_USE_MPI
  7833. ctx->ctx_mpi = ggml_mpi_init();
  7834. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  7835. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  7836. // TODO: needs fix after #3228
  7837. GGML_ASSERT(false && "not implemented");
  7838. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  7839. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  7840. llama_backend_free();
  7841. exit(1);
  7842. }
  7843. #endif
  7844. return ctx;
  7845. }
  7846. void llama_free(struct llama_context * ctx) {
  7847. delete ctx;
  7848. }
  7849. const llama_model * llama_get_model(const struct llama_context * ctx) {
  7850. return &ctx->model;
  7851. }
  7852. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  7853. return ctx->cparams.n_ctx;
  7854. }
  7855. uint32_t llama_n_batch(const struct llama_context * ctx) {
  7856. return ctx->cparams.n_batch;
  7857. }
  7858. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  7859. return model->vocab.type;
  7860. }
  7861. int32_t llama_n_vocab(const struct llama_model * model) {
  7862. return model->vocab.id_to_token.size();
  7863. }
  7864. int32_t llama_n_ctx_train(const struct llama_model * model) {
  7865. return model->hparams.n_ctx_train;
  7866. }
  7867. int32_t llama_n_embd(const struct llama_model * model) {
  7868. return model->hparams.n_embd;
  7869. }
  7870. float llama_rope_freq_scale_train(const struct llama_model * model) {
  7871. return model->hparams.rope_freq_scale_train;
  7872. }
  7873. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  7874. const auto & it = model->gguf_kv.find(key);
  7875. if (it == model->gguf_kv.end()) {
  7876. if (buf_size > 0) {
  7877. buf[0] = '\0';
  7878. }
  7879. return -1;
  7880. }
  7881. return snprintf(buf, buf_size, "%s", it->second.c_str());
  7882. }
  7883. int32_t llama_model_meta_count(const struct llama_model * model) {
  7884. return (int)model->gguf_kv.size();
  7885. }
  7886. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  7887. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  7888. if (buf_size > 0) {
  7889. buf[0] = '\0';
  7890. }
  7891. return -1;
  7892. }
  7893. auto it = model->gguf_kv.begin();
  7894. std::advance(it, i);
  7895. return snprintf(buf, buf_size, "%s", it->first.c_str());
  7896. }
  7897. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  7898. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  7899. if (buf_size > 0) {
  7900. buf[0] = '\0';
  7901. }
  7902. return -1;
  7903. }
  7904. auto it = model->gguf_kv.begin();
  7905. std::advance(it, i);
  7906. return snprintf(buf, buf_size, "%s", it->second.c_str());
  7907. }
  7908. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  7909. return snprintf(buf, buf_size, "%s %s %s",
  7910. llama_model_arch_name(model->arch).c_str(),
  7911. llama_model_type_name(model->type),
  7912. llama_model_ftype_name(model->ftype).c_str());
  7913. }
  7914. uint64_t llama_model_size(const struct llama_model * model) {
  7915. uint64_t size = 0;
  7916. for (const auto & it : model->tensors_by_name) {
  7917. size += ggml_nbytes(it.second);
  7918. }
  7919. return size;
  7920. }
  7921. uint64_t llama_model_n_params(const struct llama_model * model) {
  7922. uint64_t nparams = 0;
  7923. for (const auto & it : model->tensors_by_name) {
  7924. nparams += ggml_nelements(it.second);
  7925. }
  7926. return nparams;
  7927. }
  7928. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  7929. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  7930. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  7931. return it.first == name;
  7932. });
  7933. if (it == model->tensors_by_name.end()) {
  7934. return nullptr;
  7935. }
  7936. return it->second;
  7937. }
  7938. uint32_t llama_model_quantize(
  7939. const char * fname_inp,
  7940. const char * fname_out,
  7941. const llama_model_quantize_params * params) {
  7942. try {
  7943. llama_model_quantize_internal(fname_inp, fname_out, params);
  7944. return 0;
  7945. } catch (const std::exception & err) {
  7946. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  7947. return 1;
  7948. }
  7949. }
  7950. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  7951. try {
  7952. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  7953. } catch (const std::exception & err) {
  7954. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  7955. return 1;
  7956. }
  7957. }
  7958. 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) {
  7959. try {
  7960. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  7961. } catch (const std::exception & err) {
  7962. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  7963. return 1;
  7964. }
  7965. }
  7966. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  7967. struct llama_kv_cache_view result = {
  7968. /*.n_cells = */ 0,
  7969. /*.n_max_seq = */ n_max_seq,
  7970. /*.token_count = */ 0,
  7971. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  7972. /*.max_contiguous = */ 0,
  7973. /*.max_contiguous_idx = */ -1,
  7974. /*.cells = */ nullptr,
  7975. /*.cells_sequences = */ nullptr,
  7976. };
  7977. return result;
  7978. }
  7979. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  7980. if (view->cells != nullptr) {
  7981. free(view->cells);
  7982. view->cells = nullptr;
  7983. }
  7984. if (view->cells_sequences != nullptr) {
  7985. free(view->cells_sequences);
  7986. view->cells_sequences = nullptr;
  7987. }
  7988. }
  7989. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  7990. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  7991. view->n_cells = int32_t(ctx->kv_self.size);
  7992. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  7993. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  7994. view->cells = (struct llama_kv_cache_view_cell *)p;
  7995. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  7996. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  7997. view->cells_sequences = (llama_seq_id *)p;
  7998. }
  7999. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8000. llama_kv_cache_view_cell * c_curr = view->cells;
  8001. llama_seq_id * cs_curr = view->cells_sequences;
  8002. int32_t used_cells = 0;
  8003. int32_t token_count = 0;
  8004. int32_t curr_contig_idx = -1;
  8005. uint32_t max_contig = 0;
  8006. int32_t max_contig_idx = -1;
  8007. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8008. const size_t curr_size = kv_cells[i].seq_id.size();
  8009. token_count += curr_size;
  8010. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8011. if (curr_size > 0) {
  8012. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8013. max_contig = i - curr_contig_idx;
  8014. max_contig_idx = curr_contig_idx;
  8015. }
  8016. curr_contig_idx = -1;
  8017. } else if (curr_contig_idx < 0) {
  8018. curr_contig_idx = i;
  8019. }
  8020. int seq_idx = 0;
  8021. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8022. if (seq_idx >= view->n_max_seq) {
  8023. break;
  8024. }
  8025. cs_curr[seq_idx] = it;
  8026. seq_idx++;
  8027. }
  8028. if (seq_idx != 0) {
  8029. used_cells++;
  8030. }
  8031. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8032. cs_curr[seq_idx] = -1;
  8033. }
  8034. }
  8035. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8036. max_contig_idx = curr_contig_idx;
  8037. max_contig = kv_cells.size() - curr_contig_idx;
  8038. }
  8039. view->max_contiguous = max_contig;
  8040. view->max_contiguous_idx = max_contig_idx;
  8041. view->token_count = token_count;
  8042. view->used_cells = used_cells;
  8043. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8044. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8045. __func__, ctx->kv_self.used, used_cells);
  8046. }
  8047. }
  8048. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8049. int result = 0;
  8050. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8051. result += ctx->kv_self.cells[i].seq_id.size();
  8052. }
  8053. return result;
  8054. }
  8055. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8056. return ctx->kv_self.used;
  8057. }
  8058. void llama_kv_cache_clear(struct llama_context * ctx) {
  8059. llama_kv_cache_clear(ctx->kv_self);
  8060. }
  8061. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8062. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8063. }
  8064. 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) {
  8065. if (seq_id_src == seq_id_dst) {
  8066. return;
  8067. }
  8068. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8069. }
  8070. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8071. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8072. }
  8073. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8074. if (delta == 0) {
  8075. return;
  8076. }
  8077. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8078. }
  8079. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8080. if (d == 1) {
  8081. return;
  8082. }
  8083. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8084. }
  8085. // Returns the *maximum* size of the state
  8086. size_t llama_get_state_size(const struct llama_context * ctx) {
  8087. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8088. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8089. const size_t s_rng_size = sizeof(size_t);
  8090. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8091. const size_t s_logits_capacity = sizeof(size_t);
  8092. const size_t s_logits_size = sizeof(size_t);
  8093. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8094. const size_t s_embedding_size = sizeof(size_t);
  8095. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8096. const size_t s_kv_size = sizeof(size_t);
  8097. const size_t s_kv_ntok = sizeof(int);
  8098. const size_t s_kv = ctx->kv_self.total_size();
  8099. const size_t s_total = (
  8100. + s_rng_size
  8101. + s_rng
  8102. + s_logits_capacity
  8103. + s_logits_size
  8104. + s_logits
  8105. + s_embedding_size
  8106. + s_embedding
  8107. + s_kv_size
  8108. + s_kv_ntok
  8109. + s_kv
  8110. );
  8111. return s_total;
  8112. }
  8113. // llama_context_data
  8114. struct llama_data_context {
  8115. virtual void write(const void * src, size_t size) = 0;
  8116. virtual size_t get_size_written() = 0;
  8117. virtual ~llama_data_context() = default;
  8118. };
  8119. struct llama_data_buffer_context : llama_data_context {
  8120. uint8_t * ptr;
  8121. size_t size_written = 0;
  8122. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8123. void write(const void * src, size_t size) override {
  8124. memcpy(ptr, src, size);
  8125. ptr += size;
  8126. size_written += size;
  8127. }
  8128. size_t get_size_written() override {
  8129. return size_written;
  8130. }
  8131. };
  8132. struct llama_data_file_context : llama_data_context {
  8133. llama_file * file;
  8134. size_t size_written = 0;
  8135. llama_data_file_context(llama_file * f) : file(f) {}
  8136. void write(const void * src, size_t size) override {
  8137. file->write_raw(src, size);
  8138. size_written += size;
  8139. }
  8140. size_t get_size_written() override {
  8141. return size_written;
  8142. }
  8143. };
  8144. /** copy state data into either a buffer or file depending on the passed in context
  8145. *
  8146. * file context:
  8147. * llama_file file("/path", "wb");
  8148. * llama_data_file_context data_ctx(&file);
  8149. * llama_copy_state_data(ctx, &data_ctx);
  8150. *
  8151. * buffer context:
  8152. * std::vector<uint8_t> buf(max_size, 0);
  8153. * llama_data_buffer_context data_ctx(&buf.data());
  8154. * llama_copy_state_data(ctx, &data_ctx);
  8155. *
  8156. */
  8157. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8158. // copy rng
  8159. {
  8160. std::stringstream rng_ss;
  8161. rng_ss << ctx->rng;
  8162. const size_t rng_size = rng_ss.str().size();
  8163. char rng_buf[LLAMA_MAX_RNG_STATE];
  8164. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  8165. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  8166. data_ctx->write(&rng_size, sizeof(rng_size));
  8167. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  8168. }
  8169. // copy logits
  8170. {
  8171. const size_t logits_cap = ctx->logits.capacity();
  8172. const size_t logits_size = ctx->logits.size();
  8173. data_ctx->write(&logits_cap, sizeof(logits_cap));
  8174. data_ctx->write(&logits_size, sizeof(logits_size));
  8175. if (logits_size) {
  8176. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8177. }
  8178. // If there is a gap between the size and the capacity, write padding
  8179. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  8180. if (padding_size > 0) {
  8181. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  8182. data_ctx->write(padding.data(), padding_size);
  8183. }
  8184. }
  8185. // copy embeddings
  8186. {
  8187. const size_t embedding_size = ctx->embedding.size();
  8188. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8189. if (embedding_size) {
  8190. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8191. }
  8192. }
  8193. // copy kv cache
  8194. {
  8195. const auto & kv_self = ctx->kv_self;
  8196. const auto & hparams = ctx->model.hparams;
  8197. const auto & cparams = ctx->cparams;
  8198. const auto n_layer = hparams.n_layer;
  8199. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  8200. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  8201. const auto n_ctx = cparams.n_ctx;
  8202. const size_t kv_buf_size = kv_self.total_size();
  8203. const uint32_t kv_head = kv_self.head;
  8204. const uint32_t kv_size = kv_self.size;
  8205. const uint32_t kv_used = kv_self.used;
  8206. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8207. data_ctx->write(&kv_head, sizeof(kv_head));
  8208. data_ctx->write(&kv_size, sizeof(kv_size));
  8209. data_ctx->write(&kv_used, sizeof(kv_used));
  8210. if (kv_buf_size) {
  8211. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8212. std::vector<uint8_t> tmp_buf;
  8213. for (int il = 0; il < (int) n_layer; ++il) {
  8214. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  8215. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  8216. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8217. // v is not contiguous, copy row by row
  8218. tmp_buf.resize(elt_size*kv_head);
  8219. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8220. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  8221. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8222. }
  8223. }
  8224. }
  8225. for (uint32_t i = 0; i < kv_size; ++i) {
  8226. const auto & cell = kv_self.cells[i];
  8227. const llama_pos pos = cell.pos;
  8228. const size_t seq_id_size = cell.seq_id.size();
  8229. data_ctx->write(&pos, sizeof(pos));
  8230. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8231. for (auto seq_id : cell.seq_id) {
  8232. data_ctx->write(&seq_id, sizeof(seq_id));
  8233. }
  8234. }
  8235. }
  8236. }
  8237. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8238. llama_data_buffer_context data_ctx(dst);
  8239. llama_copy_state_data_internal(ctx, &data_ctx);
  8240. return data_ctx.get_size_written();
  8241. }
  8242. // Sets the state reading from the specified source address
  8243. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8244. uint8_t * inp = src;
  8245. // set rng
  8246. {
  8247. size_t rng_size;
  8248. char rng_buf[LLAMA_MAX_RNG_STATE];
  8249. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8250. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  8251. std::stringstream rng_ss;
  8252. rng_ss.str(std::string(&rng_buf[0], rng_size));
  8253. rng_ss >> ctx->rng;
  8254. GGML_ASSERT(!rng_ss.fail());
  8255. }
  8256. // set logits
  8257. {
  8258. size_t logits_cap;
  8259. size_t logits_size;
  8260. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  8261. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8262. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  8263. if (logits_size) {
  8264. ctx->logits.resize(logits_size);
  8265. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8266. }
  8267. inp += logits_cap * sizeof(float);
  8268. }
  8269. // set embeddings
  8270. {
  8271. size_t embedding_size;
  8272. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8273. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8274. if (embedding_size) {
  8275. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8276. inp += embedding_size * sizeof(float);
  8277. }
  8278. }
  8279. // set kv cache
  8280. {
  8281. const auto & kv_self = ctx->kv_self;
  8282. const auto & hparams = ctx->model.hparams;
  8283. const auto & cparams = ctx->cparams;
  8284. const int n_layer = hparams.n_layer;
  8285. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  8286. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  8287. const int n_ctx = cparams.n_ctx;
  8288. size_t kv_buf_size;
  8289. uint32_t kv_head;
  8290. uint32_t kv_size;
  8291. uint32_t kv_used;
  8292. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8293. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8294. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8295. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8296. if (kv_buf_size) {
  8297. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  8298. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8299. for (int il = 0; il < (int) n_layer; ++il) {
  8300. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  8301. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  8302. inp += k_size;
  8303. // v is not contiguous, copy row by row
  8304. size_t v_row_size = elt_size*kv_head;
  8305. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8306. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  8307. inp += v_row_size;
  8308. }
  8309. }
  8310. }
  8311. ctx->kv_self.head = kv_head;
  8312. ctx->kv_self.size = kv_size;
  8313. ctx->kv_self.used = kv_used;
  8314. ctx->kv_self.cells.resize(kv_size);
  8315. for (uint32_t i = 0; i < kv_size; ++i) {
  8316. llama_pos pos;
  8317. size_t seq_id_size;
  8318. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8319. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8320. ctx->kv_self.cells[i].pos = pos;
  8321. llama_seq_id seq_id;
  8322. for (size_t j = 0; j < seq_id_size; ++j) {
  8323. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8324. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8325. }
  8326. }
  8327. }
  8328. const size_t nread = inp - src;
  8329. const size_t max_size = llama_get_state_size(ctx);
  8330. GGML_ASSERT(nread <= max_size);
  8331. return nread;
  8332. }
  8333. 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) {
  8334. llama_file file(path_session, "rb");
  8335. // sanity checks
  8336. {
  8337. const uint32_t magic = file.read_u32();
  8338. const uint32_t version = file.read_u32();
  8339. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8340. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8341. return false;
  8342. }
  8343. llama_hparams session_hparams;
  8344. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8345. if (session_hparams != ctx->model.hparams) {
  8346. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8347. return false;
  8348. }
  8349. }
  8350. // load the prompt
  8351. {
  8352. const uint32_t n_token_count = file.read_u32();
  8353. if (n_token_count > n_token_capacity) {
  8354. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8355. return false;
  8356. }
  8357. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8358. *n_token_count_out = n_token_count;
  8359. }
  8360. // restore the context state
  8361. {
  8362. const size_t n_state_size_cur = file.size - file.tell();
  8363. const size_t n_state_size_max = llama_get_state_size(ctx);
  8364. if (n_state_size_cur > n_state_size_max) {
  8365. 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);
  8366. return false;
  8367. }
  8368. std::vector<uint8_t> state_data(n_state_size_max);
  8369. file.read_raw(state_data.data(), n_state_size_cur);
  8370. llama_set_state_data(ctx, state_data.data());
  8371. }
  8372. return true;
  8373. }
  8374. 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) {
  8375. try {
  8376. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8377. } catch (const std::exception & err) {
  8378. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8379. return false;
  8380. }
  8381. }
  8382. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8383. llama_file file(path_session, "wb");
  8384. file.write_u32(LLAMA_SESSION_MAGIC);
  8385. file.write_u32(LLAMA_SESSION_VERSION);
  8386. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8387. // save the prompt
  8388. file.write_u32((uint32_t) n_token_count);
  8389. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8390. // save the context state using stream saving
  8391. llama_data_file_context data_ctx(&file);
  8392. llama_copy_state_data_internal(ctx, &data_ctx);
  8393. return true;
  8394. }
  8395. int llama_eval(
  8396. struct llama_context * ctx,
  8397. llama_token * tokens,
  8398. int32_t n_tokens,
  8399. int32_t n_past) {
  8400. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8401. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8402. if (ret < 0) {
  8403. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8404. }
  8405. return ret;
  8406. }
  8407. int llama_eval_embd(
  8408. struct llama_context * ctx,
  8409. float * embd,
  8410. int32_t n_tokens,
  8411. int32_t n_past) {
  8412. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8413. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8414. const int ret = llama_decode_internal(*ctx, batch);
  8415. if (ret < 0) {
  8416. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8417. }
  8418. return ret;
  8419. }
  8420. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8421. ctx->cparams.n_threads = n_threads;
  8422. ctx->cparams.n_threads_batch = n_threads_batch;
  8423. }
  8424. struct llama_batch llama_batch_get_one(
  8425. llama_token * tokens,
  8426. int32_t n_tokens,
  8427. llama_pos pos_0,
  8428. llama_seq_id seq_id) {
  8429. return {
  8430. /*n_tokens =*/ n_tokens,
  8431. /*tokens =*/ tokens,
  8432. /*embd =*/ nullptr,
  8433. /*pos =*/ nullptr,
  8434. /*n_seq_id =*/ nullptr,
  8435. /*seq_id =*/ nullptr,
  8436. /*logits =*/ nullptr,
  8437. /*all_pos_0 =*/ pos_0,
  8438. /*all_pos_1 =*/ 1,
  8439. /*all_seq_id =*/ seq_id,
  8440. };
  8441. }
  8442. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8443. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8444. if (embd) {
  8445. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8446. } else {
  8447. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8448. }
  8449. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8450. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8451. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8452. for (int i = 0; i < n_tokens; ++i) {
  8453. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8454. }
  8455. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8456. return batch;
  8457. }
  8458. void llama_batch_free(struct llama_batch batch) {
  8459. if (batch.token) free(batch.token);
  8460. if (batch.embd) free(batch.embd);
  8461. if (batch.pos) free(batch.pos);
  8462. if (batch.n_seq_id) free(batch.n_seq_id);
  8463. if (batch.seq_id) {
  8464. for (int i = 0; i < batch.n_tokens; ++i) {
  8465. free(batch.seq_id[i]);
  8466. }
  8467. free(batch.seq_id);
  8468. }
  8469. if (batch.logits) free(batch.logits);
  8470. }
  8471. int32_t llama_decode(
  8472. struct llama_context * ctx,
  8473. struct llama_batch batch) {
  8474. const int ret = llama_decode_internal(*ctx, batch);
  8475. if (ret < 0) {
  8476. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8477. }
  8478. return ret;
  8479. }
  8480. float * llama_get_logits(struct llama_context * ctx) {
  8481. return ctx->logits.data();
  8482. }
  8483. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  8484. assert(ctx->logits_valid.at(i));
  8485. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  8486. }
  8487. float * llama_get_embeddings(struct llama_context * ctx) {
  8488. return ctx->embedding.data();
  8489. }
  8490. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  8491. return model->vocab.id_to_token[token].text.c_str();
  8492. }
  8493. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  8494. return model->vocab.id_to_token[token].score;
  8495. }
  8496. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  8497. return model->vocab.id_to_token[token].type;
  8498. }
  8499. llama_token llama_token_bos(const struct llama_model * model) {
  8500. return model->vocab.special_bos_id;
  8501. }
  8502. llama_token llama_token_eos(const struct llama_model * model) {
  8503. return model->vocab.special_eos_id;
  8504. }
  8505. llama_token llama_token_nl(const struct llama_model * model) {
  8506. return model->vocab.linefeed_id;
  8507. }
  8508. int32_t llama_add_bos_token(const struct llama_model * model) {
  8509. return model->vocab.special_add_bos;
  8510. }
  8511. int32_t llama_add_eos_token(const struct llama_model * model) {
  8512. return model->vocab.special_add_eos;
  8513. }
  8514. llama_token llama_token_prefix(const struct llama_model * model) {
  8515. return model->vocab.special_prefix_id;
  8516. }
  8517. llama_token llama_token_middle(const struct llama_model * model) {
  8518. return model->vocab.special_middle_id;
  8519. }
  8520. llama_token llama_token_suffix(const struct llama_model * model) {
  8521. return model->vocab.special_suffix_id;
  8522. }
  8523. llama_token llama_token_eot(const struct llama_model * model) {
  8524. return model->vocab.special_eot_id;
  8525. }
  8526. int32_t llama_tokenize(
  8527. const struct llama_model * model,
  8528. const char * text,
  8529. int32_t text_len,
  8530. llama_token * tokens,
  8531. int32_t n_max_tokens,
  8532. bool add_bos,
  8533. bool special) {
  8534. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  8535. if (n_max_tokens < (int) res.size()) {
  8536. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  8537. return -((int) res.size());
  8538. }
  8539. for (size_t i = 0; i < res.size(); i++) {
  8540. tokens[i] = res[i];
  8541. }
  8542. return res.size();
  8543. }
  8544. static std::string llama_decode_text(const std::string & text) {
  8545. std::string decoded_text;
  8546. auto unicode_sequences = codepoints_from_utf8(text);
  8547. for (auto& unicode_sequence : unicode_sequences) {
  8548. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  8549. }
  8550. return decoded_text;
  8551. }
  8552. // does not write null-terminator to buf
  8553. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  8554. if (0 <= token && token < llama_n_vocab(model)) {
  8555. switch (llama_vocab_get_type(model->vocab)) {
  8556. case LLAMA_VOCAB_TYPE_SPM: {
  8557. if (llama_is_normal_token(model->vocab, token)) {
  8558. std::string result = model->vocab.id_to_token[token].text;
  8559. llama_unescape_whitespace(result);
  8560. if (length < (int) result.length()) {
  8561. return -(int) result.length();
  8562. }
  8563. memcpy(buf, result.c_str(), result.length());
  8564. return result.length();
  8565. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  8566. if (length < 3) {
  8567. return -3;
  8568. }
  8569. memcpy(buf, "\xe2\x96\x85", 3);
  8570. return 3;
  8571. } else if (llama_is_control_token(model->vocab, token)) {
  8572. ;
  8573. } else if (llama_is_byte_token(model->vocab, token)) {
  8574. if (length < 1) {
  8575. return -1;
  8576. }
  8577. buf[0] = llama_token_to_byte(model->vocab, token);
  8578. return 1;
  8579. } else {
  8580. // TODO: for now we accept all unsupported token types,
  8581. // suppressing them like CONTROL tokens.
  8582. // GGML_ASSERT(false);
  8583. }
  8584. break;
  8585. }
  8586. case LLAMA_VOCAB_TYPE_BPE: {
  8587. if (llama_is_normal_token(model->vocab, token)) {
  8588. std::string result = model->vocab.id_to_token[token].text;
  8589. result = llama_decode_text(result);
  8590. if (length < (int) result.length()) {
  8591. return -(int) result.length();
  8592. }
  8593. memcpy(buf, result.c_str(), result.length());
  8594. return result.length();
  8595. } else if (llama_is_control_token(model->vocab, token)) {
  8596. ;
  8597. } else {
  8598. // TODO: for now we accept all unsupported token types,
  8599. // suppressing them like CONTROL tokens.
  8600. // GGML_ASSERT(false);
  8601. }
  8602. break;
  8603. }
  8604. default:
  8605. GGML_ASSERT(false);
  8606. }
  8607. }
  8608. return 0;
  8609. }
  8610. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  8611. struct llama_timings result = {
  8612. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  8613. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  8614. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  8615. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  8616. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  8617. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  8618. /*.n_sample =*/ std::max(1, ctx->n_sample),
  8619. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  8620. /*.n_eval =*/ std::max(1, ctx->n_eval),
  8621. };
  8622. return result;
  8623. }
  8624. void llama_print_timings(struct llama_context * ctx) {
  8625. const llama_timings timings = llama_get_timings(ctx);
  8626. LLAMA_LOG_INFO("\n");
  8627. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  8628. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  8629. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  8630. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  8631. __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);
  8632. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  8633. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  8634. 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));
  8635. }
  8636. void llama_reset_timings(struct llama_context * ctx) {
  8637. ctx->t_start_us = ggml_time_us();
  8638. ctx->t_sample_us = ctx->n_sample = 0;
  8639. ctx->t_eval_us = ctx->n_eval = 0;
  8640. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  8641. }
  8642. const char * llama_print_system_info(void) {
  8643. static std::string s;
  8644. s = "";
  8645. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  8646. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  8647. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  8648. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  8649. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  8650. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  8651. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  8652. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  8653. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  8654. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  8655. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  8656. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  8657. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  8658. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  8659. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  8660. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  8661. return s.c_str();
  8662. }
  8663. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  8664. fprintf(stream, "\n");
  8665. fprintf(stream, "###########\n");
  8666. fprintf(stream, "# Timings #\n");
  8667. fprintf(stream, "###########\n");
  8668. fprintf(stream, "\n");
  8669. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  8670. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  8671. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  8672. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  8673. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  8674. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  8675. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  8676. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  8677. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  8678. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  8679. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  8680. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  8681. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  8682. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  8683. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  8684. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  8685. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  8686. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  8687. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  8688. }
  8689. // For internal test use
  8690. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  8691. struct llama_context * ctx
  8692. ) {
  8693. return ctx->model.tensors_by_name;
  8694. }
  8695. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  8696. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  8697. g_state.log_callback_user_data = user_data;
  8698. #ifdef GGML_USE_METAL
  8699. ggml_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  8700. #endif
  8701. }
  8702. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  8703. va_list args_copy;
  8704. va_copy(args_copy, args);
  8705. char buffer[128];
  8706. int len = vsnprintf(buffer, 128, format, args);
  8707. if (len < 128) {
  8708. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  8709. } else {
  8710. char* buffer2 = new char[len+1];
  8711. vsnprintf(buffer2, len+1, format, args_copy);
  8712. buffer2[len] = 0;
  8713. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  8714. delete[] buffer2;
  8715. }
  8716. va_end(args_copy);
  8717. }
  8718. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  8719. va_list args;
  8720. va_start(args, format);
  8721. llama_log_internal_v(level, format, args);
  8722. va_end(args);
  8723. }
  8724. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  8725. (void) level;
  8726. (void) user_data;
  8727. fputs(text, stderr);
  8728. fflush(stderr);
  8729. }