llama.cpp 361 KB

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