llama.cpp 359 KB

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